domingo, 10 de agosto de 2025

Cómo crear una interfaz en PHP tipo OpenWebUI que enrute preguntas a OpenAI, Copilot y Gemini

En este artículo te mostraré cómo construir una interfaz web en PHP que permita a los usuarios interactuar con un asistente conversacional, y que enrute automáticamente las preguntas a diferentes APIs según su temática:

  • Preguntas legales → se envían a Copilot.
  • Preguntas de programación → se envían a Gemini.
  • El resto de preguntas → se manejan con OpenAI

Paso 1: Requisitos previos

Antes de comenzar, asegúrate de tener:

  • Un servidor con PHP 8.x y cURL habilitado.
  • Claves API para:
    • OpenAI (https://platform.openai.com/)
    • Gemini (https://ai.google.dev/)
    • Microsoft Copilot (según el proveedor, puede requerir acceso empresarial).
  • Composer (opcional, si deseas usar librerías externas para HTTP).

Paso 2: Crear la interfaz HTML

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Asistente Multimotor</title>
</head>
<body>
    <h1>Asistente Inteligente</h1>
    <form method="POST">
        <textarea name="pregunta" rows="6" cols="60" placeholder="Escribe tu pregunta aquí..."><?php echo isset($_POST['pregunta']) ? htmlspecialchars($_POST['pregunta']) : ''; ?></textarea><br>
        <button type="submit">Enviar</button>
    </form>

    <?php if ($respuesta): ?>
        <h2>Respuesta:</h2>
        <pre><?php print_r($respuesta); ?></pre>
    <?php endif; ?>
</body>
</html>

Paso 3: Clasificar la pregunta

En procesar.php, primero clasificamos la pregunta para decidir a qué API enviarla. Puedes usar expresiones clave simples o un modelo de clasificación más avanzado.

function clasificarPregunta($texto) {
    $texto = strtolower($texto);
    if (str_contains($texto, 'ley') || str_contains($texto, 'contrato') || str_contains($texto, 'legal')) {
        return 'copilot';
    } elseif (str_contains($texto, 'código') || str_contains($texto, 'programar') || str_contains($texto, 'php') || str_contains($texto, 'javascript')) {
        return 'gemini';
    } else {
        return 'openai';
    }
}

Paso 4: Conectar con las APIs

Aquí un ejemplo básico de cómo enviar la pregunta a cada API:


function consultarOpenAI($pregunta, $apiKey) {
    $data = [
        'model' => 'gpt-4',
        'messages' => [['role' => 'user', 'content' => $pregunta]]
    ];
    return enviarPeticion('https://api.openai.com/v1/chat/completions', $data, $apiKey, 'Authorization: Bearer ');
}

function consultarGemini($pregunta, $apiKey) {
    $data = ['contents' => [['parts' => [['text' => $pregunta]]]]];
    return enviarPeticion("https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=$apiKey", $data);
}

function consultarCopilot($pregunta, $apiKey) {
    // Este endpoint puede variar según el proveedor
    $data = ['prompt' => $pregunta];
    return enviarPeticion('https://copilot.microsoft.com/api/ask', $data, $apiKey, 'Authorization: Bearer ');
}

function enviarPeticion($url, $data, $apiKey = '', $authHeaderPrefix = '') {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge([
        'Content-Type: application/json'
    ], $apiKey ? [$authHeaderPrefix . $apiKey] : []));
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}

Paso 5: Procesar la pregunta

$pregunta = $_POST['pregunta'];
$destino = clasificarPregunta($pregunta);

switch ($destino) {
    case 'copilot':
        $respuesta = consultarCopilot($pregunta, 'TU_API_KEY_COPILOT');
        break;
    case 'gemini':
        $respuesta = consultarGemini($pregunta, 'TU_API_KEY_GEMINI');
        break;
    default:
        $respuesta = consultarOpenAI($pregunta, 'TU_API_KEY_OPENAI');
        break;
}

echo "<h2>Respuesta:</h2><pre>" . print_r($respuesta, true) . "</pre>";


Paso 6: Consideraciones de seguridad

Valida y sanitiza la entrada del usuario.
Usa HTTPS para proteger las claves API.
Implementa límites de uso o autenticación si vas a publicar la herramienta.

Paso 7: Aqui el script completo:


<?php
// Clasifica la pregunta según su contenido
function clasificarPregunta($texto) {
    $texto = strtolower($texto);
    if (str_contains($texto, 'ley') || str_contains($texto, 'contrato') || str_contains($texto, 'legal')) {
        return 'copilot';
    } elseif (str_contains($texto, 'código') || str_contains($texto, 'programar') || str_contains($texto, 'php') || str_contains($texto, 'javascript')) {
        return 'gemini';
    } else {
        return 'openai';
    }
}

// Función genérica para enviar peticiones a una API
function enviarPeticion($url, $data, $apiKey = '', $authHeaderPrefix = '') {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge([
        'Content-Type: application/json'
    ], $apiKey ? [$authHeaderPrefix . $apiKey] : []));
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}

// Funciones para consultar cada API
function consultarOpenAI($pregunta, $apiKey) {
    $data = [
        'model' => 'gpt-4',
        'messages' => [['role' => 'user', 'content' => $pregunta]]
    ];
    return enviarPeticion('https://api.openai.com/v1/chat/completions', $data, $apiKey, 'Authorization: Bearer ');
}

function consultarGemini($pregunta, $apiKey) {
    $data = ['contents' => [['parts' => [['text' => $pregunta]]]]];
    return enviarPeticion("https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=$apiKey", $data);
}

function consultarCopilot($pregunta, $apiKey) {
    $data = ['prompt' => $pregunta];
    return enviarPeticion('https://copilot.microsoft.com/api/ask', $data, $apiKey, 'Authorization: Bearer ');
}

// Procesamiento del formulario
$respuesta = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['pregunta'])) {
    $pregunta = trim($_POST['pregunta']);
    $destino = clasificarPregunta($pregunta);

    // Reemplaza estas claves con tus claves reales
    $openai_key = 'TU_API_KEY_OPENAI';
    $gemini_key = 'TU_API_KEY_GEMINI';
    $copilot_key = 'TU_API_KEY_COPILOT';

    switch ($destino) {
        case 'copilot':
            $respuesta = consultarCopilot($pregunta, $copilot_key);
            break;
        case 'gemini':
            $respuesta = consultarGemini($pregunta, $gemini_key);
            break;
        default:
            $respuesta = consultarOpenAI($pregunta, $openai_key);
            break;
    }
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Asistente Multimotor de LaRebelion</title>
</head>
<body>
    <h1>Asistente Inteligente</h1>
    <form method="POST">
        <textarea name="pregunta" rows="6" cols="60" placeholder="Escribe tu pregunta aquí..."><?php echo isset($_POST['pregunta']) ? htmlspecialchars($_POST['pregunta']) : ''; ?></textarea><br>
        <button type="submit">Enviar</button>
    </form>

    <?php if ($respuesta): ?>
        <h2>Respuesta:</h2>
        <pre><?php print_r($respuesta); ?></pre>
    <?php endif; ?>
</body>
</html>

No hay comentarios:

Publicar un comentario