En este tutorial aprenderás:
- Cómo conectarte a Google Gemini 2.5 Flash usando PHP y cURL
- Crear un sistema de base de conocimiento flexible
- Procesar archivos de texto y PDFs
- Implementar una interfaz web interactiva
- Formatear respuestas Markdown de forma elegante
¿Por qué Gemini 2.5 Flash?
Gratis
1,500 requests/día sin costo
Rápido
Respuestas en menos de 2 segundos
Inteligente
Comprensión avanzada del contexto
Multilenguaje
Excelente soporte para español
Código Completo
A continuación el código completo funcional del chatbot:
config.php
<?php
define('GEMINI_API_KEY', 'TU_API_KEY_AQUI');
define('GEMINI_MODEL', 'gemini-2.5-flash');
define('GEMINI_API_URL', 'https://generativelanguage.googleapis.com/v1beta/models/');
?>
process.php
Tip:
El archivo contexto.txt (o contexto.pdf) tiene todo el texto que el agente de AI va a usar para personalizar las respuestas contextuales. Cuanto más detallada sea la info del archivo respecto de tus intereses, más exactas van a ser las respuestas del agente.
<?php
require_once 'config.php';
// Cargar contexto desde un archivo de texto
$contextFile = file_get_contents('contexto.txt');
$contexto = substr($contextFile, 0, 3000); // limitar la caracteres para controlar límite de tokens
// Cargar contexto desde PDF
// https://github.com/smalot/pdfparser
// composer require smalot/pdfparser
require 'vendor/autoload.php';
use Smalot\PdfParser\Parser;
$parser = new Parser();
$pdf = $parser->parseFile('contexto.pdf');
$contexto = $pdf->getText();
// CONFIGURAR ENCODING CORRECTO
mb_internal_encoding('UTF-8');
ini_set('default_charset', 'UTF-8');
function formatearRespuestaParaWeb($markdown) {
// 1. Convertir enlaces Markdown [texto](url) a HTML
$html = preg_replace(
'/\[([^\]]+)\]\(([^)]+)\)/',
'$1',
$markdown
);
// 3. Convertir negritas **texto** a
$html = preg_replace('/\*\*(.+?)\*\*/', '$1', $html);
// 4. Convertir cursivas *texto* a
$html = preg_replace('/(?$1', $html);
// 5. Convertir listas (* item o - item)
$html = preg_replace_callback('/(\*\s+.+\n?)+/', function($matches) {
$items = preg_replace('/^\*\s+(.+)$/m', '$1 ', $matches[0]);
return '' . $items . '
';
}, $html);
// También soportar listas con guiones
$html = preg_replace_callback('/(\-\s+.+\n?)+/', function($matches) {
$items = preg_replace('/^\-\s+(.+)$/m', '$1 ', $matches[0]);
return '' . $items . '
';
}, $html);
// 6. Convertir listas numeradas (1. item, 2. item)
$html = preg_replace_callback('/(\d+\.\s+.+\n?)+/', function($matches) {
$items = preg_replace('/^\d+\.\s+(.+)$/m', '$1 ', $matches[0]);
return '' . $items . '
';
}, $html);
// 7. Convertir títulos
$html = preg_replace('/^###\s+(.+?)$/m', '$1
', $html);
$html = preg_replace('/^##\s+(.+?)$/m', '$1
', $html);
$html = preg_replace('/^#\s+(.+?)$/m', '$1
', $html);
// 8. Convertir bloques de código ```código```
$html = preg_replace('/```([a-z]*)\n([\s\S]*?)```/', '$2
', $html);
// 9. Convertir código inline `código`
$html = preg_replace('/`([^`]+)`/', '$1
', $html);
// 10. Saltos de línea
$html = nl2br($html);
return $html;
}
// LIMPIAR Y VALIDAR UTF-8
function limpiarUTF8($texto) {
// Eliminar BOM si existe
$texto = str_replace("\xEF\xBB\xBF", '', $texto);
// Convertir a UTF-8 válido
if (!mb_check_encoding($texto, 'UTF-8')) {
$texto = mb_convert_encoding($texto, 'UTF-8', 'UTF-8');
}
// Eliminar caracteres no válidos
$texto = mb_convert_encoding($texto, 'UTF-8', 'UTF-8');
return $texto;
}
function consultarGemini($contexto, $pregunta) {
$url = GEMINI_API_URL . GEMINI_MODEL . ':generateContent?key=' . GEMINI_API_KEY;
// En la siguiente línea, donde se construye el mensaje, puedes indicarle a la IA como quieres que conteste, por ejemplo:
// Escribe de forma natural como si hablaras con una persona. (el que figura actualmente)
// Se breve, la respuesta debe estar enfocada precisamente en la pregunta.
// Contesta agresivamente, como si odiases a la persona que pregunta.
// Contesta brevemente y con humor, intenta ser lo más gracioso posible.
$mensaje = "CONTEXTO DE LA CONSULTA:\n" . $contexto . "\n\n---\n\n"
. "INSTRUCCION IMPORTANTE: Escribe de forma natural como si hablaras con una persona.\n\n"
. "PREGUNTA: " . $pregunta;
$mensaje = limpiarUTF8($mensaje);
$data = [
"contents" => [
["parts" => [["text" => $mensaje]]]
]
];
// CONVERTIR A JSON CON FLAGS ESPECIALES
$jsonData = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $jsonData,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Content-Length: ' . strlen($jsonData)
],
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_VERBOSE => false
]);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
return formatearRespuestaParaWeb($result['candidates'][0]['content']['parts'][0]['text']);
}
try {
$pregunta = $_POST['pregunta'];
$respuesta = consultarGemini($contexto, $pregunta);
echo json_encode(['success' => true, 'respuesta' => $respuesta]);
} catch (Exception $e) {
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>
index.html (Frontend)
<!DOCTYPE html>
<html>
<head>
<title>Chatbot Gemini</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
</head>
<body>
<h1><i class="fas fa-robot"></i> Chatbot Gemini</h1>
<form id="chatForm">
<input name="pregunta" placeholder="Tu pregunta..." style="min-width: 300px;" required>
<button type="submit"><i class="fas fa-paper-plane"></i> Enviar</button>
</form>
<div id="respuesta" style="border: 1px solid black; width: 500px; height: 600px; margin-top: 20px; overflow: auto;"></div>
<script>
document.getElementById('chatForm').addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const response = await fetch('process.php', {
method: 'POST',
body: formData
});
const data = await response.json();
if (data.success) {
const myDiv = document.getElementById('respuesta');
myDiv.innerHTML = data.respuesta;
myDiv.scrollTop = myDiv.scrollHeight;
} else {
alert("Error: "+data.error);
}
});
</script>
</body>
</html>
¡Listo!
Ya tienes un chatbot básico funcional. Solo necesitas:
- Obtener tu API Key de Google AI Studio
- Reemplazarla en config.php
- Crear un archivo de contexto con toda la información relevante
- Ejecutar en tu entorno de desarrollo (Por ejemplo: xampp)
Próximos Pasos
Ahora puedes mejorar tu chatbot agregando:
- CSS para embellecer el chatbot
- Sistema de caché de respuestas
- Historial de conversaciones
- Rate limiting por IP
Tip:
Para producción, usa variables de entorno para la API key y habilita HTTPS.