un chatbot en php utilizando ia,

 ¡Claro que sí! Vamos a construir juntos un chatbot en PHP súper sencillo que use IA. El objetivo es que entiendas los conceptos básicos para integrar inteligencia artificial en tus aplicaciones PHP.

Lo que necesitarás:

  • PHP 7.4 o superior

  • Una cuenta gratis en OpenAI (para obtener una API Key)

  • Curiosidad y ganas de aprender

Paso 1: Obtén tu API Key de OpenAI

  1. Ve a platform.openai.com

  2. Regístrate (te dan crédito gratis inicial)

  3. Ve a "API Keys" y crea una nueva

  4. Copia la clave (se parece a sk-proj-...)

Paso 2: Estructura del proyecto

Crea una carpeta con estos 3 archivos:

text
mi-chatbot/
├── index.html      (frontend simple)
├── chatbot.php     (backend PHP)
└── config.php      (configuración)

Paso 3: Código paso a paso

config.php - Configuración básica

php
<?php
// Configuración
define('OPENAI_API_KEY', 'tu-api-key-aqui');
define('OPENAI_API_URL', 'https://api.openai.com/v1/chat/completions');

// Función para limpiar mensajes
function limpiarTexto($texto) {
    return htmlspecialchars(strip_tags(trim($texto)));
}
?>

chatbot.php - Lógica del chatbot

php
<?php
require_once 'config.php';

// Solo aceptamos peticiones POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Método no permitido']);
    exit;
}

// Obtenemos el mensaje del usuario
$input = json_decode(file_get_contents('php://input'), true);
$mensaje = limpiarTexto($input['mensaje'] ?? '');

if (empty($mensaje)) {
    echo json_encode(['error' => 'Mensaje vacío']);
    exit;
}

// Preparamos los datos para OpenAI
$data = [
    'model' => 'gpt-3.5-turbo', // El más económico
    'messages' => [
        [
            'role' => 'system',
            'content' => 'Eres un asistente amigable que responde en español de forma clara y concisa.'
        ],
        [
            'role' => 'user',
            'content' => $mensaje
        ]
    ],
    'max_tokens' => 150, // Respuestas cortas
    'temperature' => 0.7 // Creatividad media
];

// Configuramos la petición cURL
$ch = curl_init(OPENAI_API_URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . OPENAI_API_KEY
]);

// Ejecutamos y obtenemos respuesta
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// Procesamos la respuesta
if ($httpCode === 200) {
    $resultado = json_decode($response, true);
    $respuesta = $resultado['choices'][0]['message']['content'] ?? 'No pude procesar tu mensaje.';
    
    echo json_encode([
        'success' => true,
        'respuesta' => $respuesta
    ]);
} else {
    echo json_encode([
        'success' => false,
        'error' => 'Error al comunicarme con la IA',
        'detalle' => $response
    ]);
}
?>

index.html - Interfaz simple

html
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mi Chatbot IA</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 50px auto;
            padding: 20px;
            background: #f0f0f0;
        }
        .chat-container {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .messages {
            min-height: 400px;
            max-height: 400px;
            overflow-y: auto;
            margin-bottom: 20px;
            padding: 10px;
        }
        .message {
            margin: 10px 0;
            padding: 10px;
            border-radius: 5px;
        }
        .user {
            background: #007bff;
            color: white;
            text-align: right;
        }
        .bot {
            background: #e9ecef;
            color: black;
        }
        .input-area {
            display: flex;
            gap: 10px;
        }
        input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        button {
            padding: 10px 20px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        button:hover {
            background: #0056b3;
        }
        .loading {
            text-align: center;
            color: #666;
            font-style: italic;
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <h1>🤖 Mi Chatbot IA</h1>
        <div class="messages" id="messages">
            <div class="message bot">¡Hola! Soy tu chatbot. ¿En qué puedo ayudarte?</div>
        </div>
        <div class="input-area">
            <input type="text" id="userInput" placeholder="Escribe tu mensaje..." onkeypress="if(event.key==='Enter') enviarMensaje()">
            <button onclick="enviarMensaje()">Enviar</button>
        </div>
    </div>

    <script>
        async function enviarMensaje() {
            const input = document.getElementById('userInput');
            const mensaje = input.value.trim();
            
            if (!mensaje) return;
            
            // Mostrar mensaje del usuario
            agregarMensaje(mensaje, 'user');
            input.value = '';
            
            // Mostrar loading
            const loadingId = agregarMensaje('🤔 Pensando...', 'bot', true);
            
            try {
                const response = await fetch('chatbot.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ mensaje: mensaje })
                });
                
                const data = await response.json();
                
                // Remover mensaje de loading
                document.getElementById(loadingId)?.remove();
                
                if (data.success) {
                    agregarMensaje(data.respuesta, 'bot');
                } else {
                    agregarMensaje('❌ Error: ' + (data.error || 'Algo salió mal'), 'bot');
                }
            } catch (error) {
                document.getElementById(loadingId)?.remove();
                agregarMensaje('❌ Error de conexión: ' + error.message, 'bot');
            }
        }
        
        function agregarMensaje(texto, tipo, esLoading = false) {
            const messagesDiv = document.getElementById('messages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${tipo}`;
            messageDiv.textContent = texto;
            
            if (esLoading) {
                const id = 'loading-' + Date.now();
                messageDiv.id = id;
                messagesDiv.appendChild(messageDiv);
                messagesDiv.scrollTop = messagesDiv.scrollHeight;
                return id;
            } else {
                messagesDiv.appendChild(messageDiv);
                messagesDiv.scrollTop = messagesDiv.scrollHeight;
                return null;
            }
        }
    </script>
</body>
</html>

Paso 4: ¡Pruébalo!

  1. Guarda todos los archivos

  2. Coloca tu API Key real en config.php

  3. Desde tu servidor local (XAMPP, WAMP, o con php -S localhost:8000)

  4. Abre index.html en tu navegador

  5. ¡Empieza a conversar!

Conceptos clave que has aprendido:

  1. Peticiones HTTP: PHP se comunica con la API de OpenAI usando cURL

  2. JSON: Tanto para enviar datos a la API como para recibir respuestas

  3. API Keys: Cómo autenticarte con servicios externos

  4. Seguridad básica: Limpiar inputs y manejar errores

  5. Frontend simple: HTML/CSS/JS para interactuar con el usuario

Próximos pasos para seguir aprendiendo:

  • Mantén conversaciones: Guarda el historial en sesión o base de datos

  • Personaliza el prompt: Cambia el role: system para darle una personalidad específica

  • Añade comandos especiales: Que el bot pueda consultar una API o base de datos

  • Usa modelos más avanzados: GPT-4 cuando tengas más presupuesto

¡Importante con tu API Key!

php
// NUNCA subas tu API Key a GitHub
// Mejor usa variables de entorno:
$api_key = getenv('OPENAI_API_KEY');

¿Quieres que profundice en algún concepto específico o que añadamos alguna funcionalidad como guardar conversaciones?

Comentarios

Entradas más populares de este blog

1. Introducción al curso de Chatbots personalizados con Laravel & OpenAI

2. Prerequisitos para el Curso de Chatbots con Laravel y OpenAI

4. Herramientas de Calidad