Gemma 3 en 1 hora para clase-consumil gemma 3 con php

 

PARTE 1: Instalar Gemma 3 (5 minutos)

Paso 1: Abrir terminal y escribir:

bash
# Solo este comando:
ollama pull gemma3:4b

Paso 2: Verificar que se instaló:

bash
# Escribir:
ollama list

Deberías ver: gemma3:4b en la lista.


PARTE 2: Código PHP más simple (archivo 1)

hola_gemma.php - ¡Solo 15 líneas!

php
<?php
// hola_gemma.php - EL MÁS SIMPLE

echo "🤖 Probando Gemma 3...\n";

// 1. Preparar la pregunta
$pregunta = "Hola Gemma, ¿cómo estás?";

// 2. Crear los datos para Ollama
$datos = [
    "model" => "gemma3:4b",
    "prompt" => $pregunta,
    "stream" => false
];

// 3. Convertir a JSON
$json_datos = json_encode($datos);

// 4. Enviar a Ollama
$respuesta = file_get_contents(
    'http://localhost:11434/api/generate',
    false,
    stream_context_create([
        'http' => [
            'method' => 'POST',
            'header' => 'Content-Type: application/json',
            'content' => $json_datos
        ]
    ])
);

// 5. Mostrar respuesta
$resultado = json_decode($respuesta, true);
echo "✅ Respuesta: " . $resultado['response'];
?>

Para ejecutar:

bash
php hola_gemma.php

PARTE 3: Chatbot simple (archivo 2)

chatbot_simple.php - Chat interactivo

php
<?php
// chatbot_simple.php - CHAT INTERACTIVO

echo "💬 CHAT CON GEMMA 3\n";
echo "==================\n";

// Historial de conversación
$historial = [];

while (true) {
    // 1. Pedir mensaje al usuario
    echo "\n👤 Tú: ";
    $mensaje = trim(fgets(STDIN));
    
    // Salir si escribe "salir"
    if ($mensaje == 'salir') {
        echo "¡Adiós! 👋\n";
        break;
    }
    
    // 2. Agregar al historial
    $historial[] = ["role" => "user", "content" => $mensaje];
    
    // 3. Preparar datos para Ollama
    $datos = [
        "model" => "gemma3:4b",
        "messages" => $historial,
        "stream" => false
    ];
    
    // 4. Enviar y obtener respuesta
    $respuesta = file_get_contents(
        'http://localhost:11434/api/chat',
        false,
        stream_context_create([
            'http' => [
                'method' => 'POST',
                'header' => 'Content-Type: application/json',
                'content' => json_encode($datos)
            ]
        ])
    );
    
    // 5. Mostrar respuesta
    $resultado = json_decode($respuesta, true);
    $respuesta_gemma = $resultado['message']['content'] ?? "No entendí";
    
    echo "🤖 Gemma: " . $respuesta_gemma . "\n";
    
    // 6. Agregar respuesta al historial
    $historial[] = ["role" => "assistant", "content" => $respuesta_gemma];
}
?>

Para ejecutar:

bash
php chatbot_simple.php

Ejemplo de uso:

text
💬 CHAT CON GEMMA 3
==================

👤 Tú: Hola
🤖 Gemma: ¡Hola! ¿Cómo estás? 😊

👤 Tú: ¿Qué es PHP?
🤖 Gemma: PHP es un lenguaje de programación...

👤 Tú: salir
¡Adiós! 👋

PARTE 4: Página web simple (3 archivos)

Archivo 1: index.html - Interfaz web

html
<!-- index.html - INTERFAZ WEB SIMPLE -->
<!DOCTYPE html>
<html>
<head>
    <title>Chat Gemma 3</title>
    <style>
        body {
            font-family: Arial;
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
        }
        #chat {
            border: 1px solid #ccc;
            height: 400px;
            overflow-y: auto;
            padding: 10px;
            margin-bottom: 10px;
        }
        .mensaje {
            margin: 5px 0;
            padding: 8px;
            border-radius: 5px;
        }
        .usuario {
            background: #e3f2fd;
            text-align: right;
        }
        .gemma {
            background: #f1f8e9;
        }
        input {
            width: 80%;
            padding: 10px;
        }
        button {
            padding: 10px;
            background: #4CAF50;
            color: white;
            border: none;
        }
    </style>
</head>
<body>
    <h1>💬 Chat con Gemma 3</h1>
    
    <div id="chat"></div>
    
    <div>
        <input type="text" id="mensaje" placeholder="Escribe tu mensaje...">
        <button onclick="enviarMensaje()">Enviar</button>
    </div>
    
    <script>
        // Enviar mensaje
        function enviarMensaje() {
            const input = document.getElementById('mensaje');
            const mensaje = input.value.trim();
            
            if (!mensaje) return;
            
            // Agregar mensaje del usuario
            agregarMensaje('usuario', mensaje);
            input.value = '';
            
            // Enviar a PHP
            fetch('procesar.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'mensaje=' + encodeURIComponent(mensaje)
            })
            .then(response => response.json())
            .then(data => {
                agregarMensaje('gemma', data.respuesta);
            });
        }
        
        // Agregar mensaje al chat
        function agregarMensaje(tipo, texto) {
            const chat = document.getElementById('chat');
            const div = document.createElement('div');
            div.className = 'mensaje ' + tipo;
            div.textContent = texto;
            chat.appendChild(div);
            chat.scrollTop = chat.scrollHeight;
        }
        
        // Enter para enviar
        document.getElementById('mensaje').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') enviarMensaje();
        });
    </script>
</body>
</html>

Archivo 2: procesar.php - Backend simple

php
<?php
// procesar.php - BACKEND SIMPLE

// 1. Recibir mensaje
$mensaje = $_POST['mensaje'] ?? '';

// 2. Preparar para Gemma
$datos = [
    "model" => "gemma3:4b",
    "prompt" => $mensaje,
    "stream" => false
];

// 3. Enviar a Ollama
$respuesta = @file_get_contents(
    'http://localhost:11434/api/generate',
    false,
    stream_context_create([
        'http' => [
            'method' => 'POST',
            'header' => 'Content-Type: application/json',
            'content' => json_encode($datos)
        ]
    ])
);

// 4. Devolver respuesta
if ($respuesta === FALSE) {
    echo json_encode(["respuesta" => "❌ Error: Ollama no está corriendo"]);
} else {
    $resultado = json_decode($respuesta, true);
    echo json_encode(["respuesta" => $resultado['response'] ?? "No hay respuesta"]);
}
?>

Archivo 3: ver_modelos.php - Ver modelos instalados

php
<?php
// ver_modelos.php - VER MODELOS

echo "📦 Modelos instalados en Ollama:\n\n";

// Obtener lista de modelos
$respuesta = @file_get_contents('http://localhost:11434/api/tags');

if ($respuesta === FALSE) {
    echo "❌ Error: Ollama no está corriendo\n";
    echo "Ejecuta: ollama serve\n";
} else {
    $datos = json_decode($respuesta, true);
    
    foreach ($datos['models'] as $modelo) {
        echo "• " . $modelo['name'] . "\n";
    }
    
    echo "\n✅ Total: " . count($datos['models']) . " modelos\n";
}
?>

PARTE 5: Ejercicios para estudiantes

Ejercicio 1: Modificar el saludo

php
// Cambiar esta línea en hola_gemma.php:
$pregunta = "Hola Gemma, ¿cómo estás?";
// Por:
$pregunta = "Hola Gemma, cuéntame un chiste";

Ejercicio 2: Cambiar el modelo

php
// En cualquier archivo, cambiar:
"model" => "gemma3:4b"
// Por otro modelo si lo tienen instalado:
"model" => "llama3.2"

Ejercicio 3: Añadir emojis a las respuestas

php
// En procesar.php, después de obtener respuesta:
$respuesta_texto = $resultado['response'] ?? "No hay respuesta";
$respuesta_con_emoji = "🤖 " . $respuesta_texto;
echo json_encode(["respuesta" => $respuesta_con_emoji]);

Ejercicio 4: Contador de mensajes

php
// Agregar al inicio de chatbot_simple.php:
$contador = 0;

// Dentro del while, después de cada respuesta:
$contador++;
echo "Mensaje #$contador\n";

PARTE 6: Solución rápida de problemas

Problema 1: "Ollama no está corriendo"

bash
# En una terminal nueva:
ollama serve
# Dejar abierta esta terminal

Problema 2: "No tengo Gemma 3"

bash
# Instalar rápido:
ollama pull gemma3:4b
# Si tarda mucho, usar modelo más pequeño:
ollama pull gemma3:1b  # Más rápido

Problema 3: PHP no encuentra file_get_contents

php
// Usar cURL en vez de file_get_contents:
function preguntarAGemma($pregunta) {
    $ch = curl_init('http://localhost:11434/api/generate');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
        "model" => "gemma3:4b",
        "prompt" => $pregunta
    ]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    
    $respuesta = curl_exec($ch);
    curl_close($ch);
    
    return json_decode($respuesta, true);
}

PARTE 7: Resumen de comandos básicos

Comandos de terminal:

bash
# Instalar Gemma 3
ollama pull gemma3:4b

# Ver modelos
ollama list

# Probar en terminal
ollama run gemma3:4b "Hola"

# Iniciar servidor
ollama serve

Códigos PHP esenciales:

php
// 1. Configuración básica
$datos = [
    "model" => "gemma3:4b",
    "prompt" => "Tu pregunta aquí",
    "stream" => false
];

// 2. Enviar a Ollama
$respuesta = file_get_contents(
    'http://localhost:11434/api/generate',
    false,
    stream_context_create([
        'http' => [
            'method' => 'POST',
            'header' => 'Content-Type: application/json',
            'content' => json_encode($datos)
        ]
    ])
);

// 3. Leer respuesta
$resultado = json_decode($respuesta, true);
echo $resultado['response'];

📋 PLAN DE CLASE DE 1 HORA

Minutos 0-10:

  • Instalar Gemma 3 (ollama pull gemma3:4b)

  • Probar en terminal (ollama run gemma3:4b "Hola")

Minutos 10-25:

  • Copiar y probar hola_gemma.php

  • Explicar cómo funciona línea por línea

Minutos 25-40:

  • Copiar y probar chatbot_simple.php

  • Hacer el ejercicio de modificar saludo

Minutos 40-55:

  • Crear la página web (3 archivos)

  • Probar en navegador

Minutos 55-60:

  • Preguntas y resumen

  • Mostrar ver_modelos.php


✨ EXTRA: Código todo-en-uno para emergencias

todo_en_uno.php - Si algo falla, usar este:

php
<?php
// TODO EN UNO - Copiar, pegar y listo

echo "<h1>💬 Chat Gemma 3</h1>";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $mensaje = $_POST['mensaje'] ?? '';
    
    if (!empty($mensaje)) {
        // Enviar a Gemma
        $datos = ["model" => "gemma3:4b", "prompt" => $mensaje];
        $respuesta = file_get_contents(
            'http://localhost:11434/api/generate',
            false,
            stream_context_create([
                'http' => [
                    'method' => 'POST',
                    'header' => 'Content-Type: application/json',
                    'content' => json_encode($datos)
                ]
            ])
        );
        
        $resultado = json_decode($respuesta, true);
        echo "<p><strong>👤 Tú:</strong> $mensaje</p>";
        echo "<p><strong>🤖 Gemma:</strong> " . ($resultado['response'] ?? 'Error') . "</p>";
    }
}
?>

<form method="POST">
    <input type="text" name="mensaje" placeholder="Escribe algo..." required>
    <button type="submit">Enviar</button>
</form>

<hr>
<p><a href="?action=modelos">📦 Ver modelos instalados</a></p>

<?php
if (isset($_GET['action']) && $_GET['action'] == 'modelos') {
    $modelos = file_get_contents('http://localhost:11434/api/tags');
    $datos = json_decode($modelos, true);
    
    echo "<h3>Modelos disponibles:</h3>";
    foreach ($datos['models'] ?? [] as $modelo) {
        echo "<li>" . $modelo['name'] . "</li>";
    }
}
?>

✅ RESUMEN FINAL PARA ESTUDIANTES

  1. Instalar: ollama pull gemma3:4b

  2. Probar: ollama run gemma3:4b "Hola"

  3. Código básico: 5 líneas para conectar PHP con Ollama

  4. URL de la API: http://localhost:11434/api/generate

  5. Formato: Enviar JSON con model y prompt

La línea más importante que deben recordar:

php
// Esto es TODO lo que necesitan para usar Gemma 3 desde PHP:
file_get_contents('http://localhost:11434/api/generate', false, stream_context_create([
    'http' => ['method' => 'POST', 'header' => 'Content-Type: application/json', 'content' => json_encode([
        "model" => "gemma3:4b",
        "prompt" => "Su pregunta aquí"
    ])]
]));

¡Listo! En 1 hora tienen su propio chatbot con IA local funcionando. 

Comentarios

Entradas más populares de este blog

1-Instalación y Primeros Pasos con Ollama

3- Creando tu Primer Entorno Virtual Python con Flask

2- Cómo Usar Ollama con Postman (APIs y Comunicación)