Stage 11 · The server: from keyboard to token
This is where the circle closes. The complete answer to "how is it that I type something and it answers me?".
Scripts
| File | What it does |
|---|---|
servidor.py | HTTP + SSE + chat template + context management + web interface |
chat.py | Terminal client (and a --local mode with no server) |
python etapas/11_servidor_chat/servidor.py # http://localhost:8017
python etapas/11_servidor_chat/chat.py # in another terminal
python etapas/11_servidor_chat/chat.py --local # everything in one process
The two things almost nobody knows
1. The model has NO memory. None. Every request is processed from scratch and the server resends it the entire conversation. What you perceive as "it remembers" is a for loop over a list of messages.
2. You cannot send just any token as-is. A token can be half a UTF-8 character. Send it on its own and the browser draws �. You have to accumulate bytes until you have complete characters: DecodificadorEnStreaming.
What you will see in the API response
{"tipo":"fin","tokens_prompt":19,"tokens_generados":18,
"ms_precarga":7.4,"tokens_por_segundo":517.7,"turnos_recortados":0}
turnos_recortados literally means "the model has forgotten the beginning of the conversation". There is no degradation and no forgetting: there is a truncation.
Requirement
It needs a model with SFT. If you only have the base one, it will continue text instead of answering (the server warns you at startup).
What to expect from your model (and what not to)
Be realistic about what is in front of you: a model with 810,000 parameters (or 4.2 million if you did stage 06.4) fine-tuned on 20 question-and-answer pairs.
you > What is a token? -> A piece of text. (perfect)
you > What is attention? -> rede manera incres de aprender. (rubbish)
The second one fails because in the data the question is "What is attention for?", not "What is attention?". That is not a bug: it is stage 09 in action. SFT taught format, not knowledge, and with 20 examples there is no room to generalize to new phrasings.
A real model is fine-tuned on between 10,000 and 1,000,000 examples. That is where the ability to answer any way of asking comes from.
If you want it to answer more things, the path is obvious and it is in datos/generar_corpus.py: add pairs to PARES_CORTOS and run stage 09 again. It is exactly what a lab does, only with five orders of magnitude more data.
Full source code
chat.py
168 lines"""
ETAPA 11 · Cliente de chat por terminal
========================================
El otro extremo del cable. Este fichero es deliberadamente pequeño para que
veas que un "cliente de IA" no tiene nada dentro: manda JSON, lee un flujo,
pinta caracteres.
Uso:
# terminal 1
python etapas/11_servidor_chat/servidor.py
# terminal 2
python etapas/11_servidor_chat/chat.py
Sin servidor (todo en el mismo proceso):
python etapas/11_servidor_chat/chat.py --local
"""
import argparse
import json
import pathlib
import sys
import urllib.error
import urllib.request
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from ruta import preparar # noqa: E402
RAIZ = preparar("11_servidor_chat")
PUERTO = 8017
def chat_remoto(args):
base = f"http://localhost:{args.puerto}"
try:
with urllib.request.urlopen(base + "/api/info", timeout=3) as r:
info = json.loads(r.read())
except urllib.error.URLError:
print(f"No hay nadie escuchando en {base}.")
print("Arranca el servidor: python etapas/11_servidor_chat/servidor.py")
print("O ejecuta esto con --local para no usar servidor.")
return 1
print("=" * 70)
print(f" Conectado a {base}")
print(f" modelo {info['modelo']} · {info['capas']} capas · "
f"contexto {info['contexto']} · vocabulario {info['vocabulario']}")
if not info["chat"]:
print(" AVISO: modelo base sin SFT: continuará texto, no responderá.")
print("=" * 70)
print(" Escribe 'salir' para terminar, 'limpiar' para olvidar la conversación.\n")
historial = []
while True:
try:
entrada = input("tú > ").strip()
except (EOFError, KeyboardInterrupt):
print()
break
if not entrada:
continue
if entrada.lower() in ("salir", "exit", "quit"):
break
if entrada.lower() == "limpiar":
historial.clear()
print(" (historial borrado)\n")
continue
historial.append({"rol": "usuario", "contenido": entrada})
cuerpo = json.dumps({"mensajes": historial,
"temperatura": args.temperatura,
"max_tokens": args.max_tokens}).encode()
pet = urllib.request.Request(
base + "/api/chat", data=cuerpo,
headers={"Content-Type": "application/json"})
print("ia > ", end="", flush=True)
acumulado = ""
try:
with urllib.request.urlopen(pet) as r:
buffer = ""
while True:
trozo = r.read(1)
if not trozo:
break
buffer += trozo.decode("utf-8", errors="replace")
while "\n\n" in buffer:
linea, buffer = buffer.split("\n\n", 1)
if not linea.startswith("data: "):
continue
ev = json.loads(linea[6:])
if ev["tipo"] == "texto":
acumulado += ev["texto"]
print(ev["texto"], end="", flush=True)
elif ev["tipo"] == "aviso":
print(f"\n {ev['texto']}", end="", flush=True)
elif ev["tipo"] == "fin":
print(f"\n [{ev['tokens_prompt']} tok prompt · "
f"{ev['tokens_generados']} generados · "
f"{ev['tokens_por_segundo']} tok/s"
+ (f" · {ev['turnos_recortados']} turnos recortados"
if ev["turnos_recortados"] else "") + "]")
except urllib.error.URLError as e:
print(f"\n error de conexión: {e}")
break
historial.append({"rol": "asistente", "contenido": acumulado})
print()
print("Hasta luego.")
return 0
def chat_local(args):
"""Sin HTTP: importa el servicio directamente. Útil para depurar."""
import importlib
srv = importlib.import_module("servidor")
servicio = srv.ServicioChat()
print("=" * 70)
print(f" Modo local (sin servidor) · modelo {servicio.nombre} · "
f"contexto {servicio.block}")
if not servicio.tiene_chat:
print(" AVISO: modelo base sin SFT: continuará texto, no responderá.")
print("=" * 70 + "\n")
historial = []
while True:
try:
entrada = input("tú > ").strip()
except (EOFError, KeyboardInterrupt):
print()
break
if not entrada or entrada.lower() in ("salir", "exit"):
break
if entrada.lower() == "limpiar":
historial.clear()
print(" (historial borrado)\n")
continue
historial.append({"rol": "usuario", "contenido": entrada})
print("ia > ", end="", flush=True)
acumulado = ""
for ev in servicio.generar_flujo(historial, temperatura=args.temperatura,
max_tokens=args.max_tokens):
if ev["tipo"] == "texto":
acumulado += ev["texto"]
print(ev["texto"], end="", flush=True)
elif ev["tipo"] == "fin":
print(f"\n [{ev['tokens_prompt']} tok prompt · "
f"{ev['tokens_generados']} generados · "
f"{ev['tokens_por_segundo']} tok/s]")
historial.append({"rol": "asistente", "contenido": acumulado})
print()
return 0
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--local", action="store_true",
help="sin servidor HTTP, todo en este proceso")
ap.add_argument("--puerto", type=int, default=PUERTO)
ap.add_argument("--temperatura", type=float, default=0.4)
ap.add_argument("--max-tokens", type=int, default=80)
args = ap.parse_args()
return chat_local(args) if args.local else chat_remoto(args)
if __name__ == "__main__":
sys.exit(main())
servidor.py
370 lines"""
ETAPA 11 — El servidor: del teclado al token
=============================================
Aquí se cierra el círculo. Esta es la respuesta completa a tu pregunta
original: "¿cómo es que escribo algo en una interfaz y me responde?"
EL VIAJE COMPLETO DE TU MENSAJE
-------------------------------
1. Escribes "¿Qué es un token?" y pulsas Enter.
2. El navegador manda un POST con JSON al servidor.
3. El servidor coge el historial de la conversación y lo MONTA en una única
cadena con la plantilla de chat:
<|usuario|>¿Qué es un token?<|asistente|>
4. El tokenizador convierte esa cadena en una lista de enteros.
5. Se comprueba que quepa en la ventana de contexto. Si no cabe, se recortan
los turnos más viejos (y esa es LA razón de que el modelo "se olvide").
6. PRECARGA: se pasa todo por el modelo llenando el KV-cache.
7. BUCLE: logits -> muestreo -> token -> al cache -> otra vez.
8. Cada token se decodifica y se manda al navegador por un flujo SSE.
9. El navegador lo va pintando. Por eso ves el texto aparecer poco a poco.
10. Al salir <|fin|>, el servidor cierra el flujo.
NO HAY NADA MÁS. Ni bases de datos de respuestas, ni búsqueda, ni un humano
detrás. Multiplicaciones de matrices y un bucle.
DOS DETALLES QUE SE LLEVAN MUCHÍSIMO TIEMPO DE INGENIERÍA REAL
--------------------------------------------------------------
A) EL MODELO NO TIENE MEMORIA. Cero. Cada petición se procesa desde cero y
el servidor le vuelve a enviar TODA la conversación. Lo que tú percibes
como "se acuerda de lo que hablamos" es el servidor reenviándolo todo.
B) NO SE PUEDE ENVIAR CUALQUIER TOKEN TAL CUAL. Un token puede ser medio
carácter UTF-8 (etapa 01, rareza 4). Si lo mandas suelto, el navegador
pinta '�'. Hay que acumular bytes hasta tener caracteres completos. Aquí
está implementado de verdad.
Ejecuta: python etapas/11_servidor_chat/servidor.py
(y en otra terminal: python etapas/11_servidor_chat/chat.py)
También puedes abrir http://localhost:8017 en el navegador.
"""
import json
import pathlib
import sys
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import numpy as np
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from ruta import preparar # noqa: E402
RAIZ = preparar("01_tokenizador", "06_transformer", "08_inferencia")
from bpe import TokenizadorCaracteres # noqa: E402
import importlib # noqa: E402
kvmod = importlib.import_module("02_kv_cache")
MotorGPT = kvmod.MotorGPT
from gpt import muestrear # noqa: E402
PUERTO = 8017
USUARIO, ASISTENTE, FIN, PAD = "<|usuario|>", "<|asistente|>", "<|fin|>", "<|pad|>"
# ---------------------------------------------------------------------------
# Decodificador incremental: el detalle que evita los '�'
# ---------------------------------------------------------------------------
class DecodificadorEnStreaming:
"""Convierte tokens en texto seguro para enviar, uno a uno.
Con un tokenizador de CARACTERES esto es trivial. Con uno BPE de bytes
(el caso real) es imprescindible: el token 195 es medio carácter 'ñ', y
enviarlo solo produce basura en pantalla.
La estrategia: acumular bytes y sólo emitir el prefijo que decodifica
limpiamente como UTF-8. Lo demás se queda esperando al siguiente token."""
def __init__(self, tokenizador):
self.tok = tokenizador
self.pendientes = bytearray()
def empujar(self, token_id: int) -> str:
trozo = self.tok.decode([token_id])
self.pendientes.extend(trozo.encode("utf-8"))
# Intentamos decodificar; si falla por bytes incompletos al final,
# emitimos sólo lo que sí es válido y guardamos el resto.
for recorte in range(0, min(4, len(self.pendientes)) + 1):
fin = len(self.pendientes) - recorte
try:
texto = self.pendientes[:fin].decode("utf-8")
except UnicodeDecodeError:
continue
del self.pendientes[:fin]
return texto
return ""
def vaciar(self) -> str:
texto = self.pendientes.decode("utf-8", errors="replace")
self.pendientes.clear()
return texto
# ---------------------------------------------------------------------------
# El motor de chat
# ---------------------------------------------------------------------------
class ServicioChat:
def __init__(self):
# Preferimos el modelo más avanzado que exista, en este orden.
for nombre in ("gpt_grande_chat", "gpt_dpo", "gpt_chat",
"gpt_grande", "gpt"):
p = RAIZ / "pesos" / f"{nombre}.npz"
if p.exists():
self.nombre = nombre
break
else:
raise SystemExit("No hay ningún modelo. Entrena la etapa 06 primero.")
cfg_p = RAIZ / "pesos" / f"{self.nombre}_config.json"
tok_p = RAIZ / "pesos" / f"{self.nombre}_tokenizador.json"
if not cfg_p.exists():
cfg_p = RAIZ / "pesos" / "gpt_config.json"
if not tok_p.exists():
tok_p = RAIZ / "pesos" / "gpt_tokenizador.json"
self.cfg = json.loads(cfg_p.read_text())
self.tok = TokenizadorCaracteres.cargar(str(tok_p))
with np.load(RAIZ / "pesos" / f"{self.nombre}.npz") as z:
estado = {k: z[k] for k in z.files}
self.cfg["vocab_size"] = estado["wte.weight"].shape[0]
self.motor = MotorGPT(estado, self.cfg)
self.block = self.cfg["block_size"]
self.tiene_chat = USUARIO in self.tok.stoi
self.candado = threading.Lock() # un modelo, muchas peticiones
# -- montaje del prompt -------------------------------------------------
def construir_prompt(self, mensajes):
"""Aplica la PLANTILLA DE CHAT y recorta si no cabe.
Cada familia de modelos tiene su plantilla, y usar la equivocada
degrada muchísimo la calidad sin dar ningún error. Ejemplos reales:
ChatML (OpenAI): <|im_start|>user\\n...<|im_end|>\\n<|im_start|>assistant\\n
LLaMA 3: <|start_header_id|>user<|end_header_id|>\\n\\n...<|eot_id|>
Mistral: [INST] ... [/INST]
La nuestra: <|usuario|>...<|asistente|>...<|fin|>
"""
if not self.tiene_chat:
# Modelo base, sin SFT: sólo sabe continuar texto.
return self.tok.encode(mensajes[-1]["contenido"]), 0
partes = []
for m in mensajes:
if m["rol"] == "usuario":
partes.append(f"{USUARIO}{m['contenido']}{ASISTENTE}")
else:
partes.append(f"{m['contenido']}{FIN}")
texto = "".join(partes)
ids = self.tok.encode(texto)
recortados = 0
# EL RECORTE: si no cabe, tiramos turnos viejos. Esto es, literalmente,
# "el modelo se ha olvidado del principio de la conversación".
# Dejamos sitio para generar al menos 24 tokens.
limite = self.block - 24
while len(ids) > limite and len(mensajes) > 1:
mensajes = mensajes[1:]
recortados += 1
partes = []
for m in mensajes:
if m["rol"] == "usuario":
partes.append(f"{USUARIO}{m['contenido']}{ASISTENTE}")
else:
partes.append(f"{m['contenido']}{FIN}")
ids = self.tok.encode("".join(partes))
if len(ids) > limite:
ids = ids[-limite:]
return ids, recortados
# -- generación en flujo ------------------------------------------------
def generar_flujo(self, mensajes, temperatura=0.4, top_p=0.9,
max_tokens=80):
with self.candado:
ids, recortados = self.construir_prompt(mensajes)
t0 = time.time()
cache = self.motor.nuevo_cache()
logits = None
for t in ids:
logits = self.motor.paso(int(t), cache)
t_precarga = time.time() - t0
dec = DecodificadorEnStreaming(self.tok)
id_fin = self.tok.stoi.get(FIN, -1)
rng = np.random.default_rng()
n = 0
for _ in range(max_tokens):
sig = muestrear(logits, temperatura, None, top_p, rng)
if sig == id_fin:
break
n += 1
trozo = dec.empujar(sig)
if trozo:
yield {"tipo": "texto", "texto": trozo}
if cache["n"] >= self.block:
yield {"tipo": "aviso",
"texto": " [ventana de contexto agotada]"}
break
logits = self.motor.paso(sig, cache)
resto = dec.vaciar()
if resto:
yield {"tipo": "texto", "texto": resto}
dt = time.time() - t0
yield {"tipo": "fin", "tokens_prompt": len(ids),
"tokens_generados": n,
"turnos_recortados": recortados,
"ms_precarga": round(t_precarga * 1000, 1),
"ms_total": round(dt * 1000, 1),
"tokens_por_segundo": round(n / max(dt, 1e-9), 1)}
# ---------------------------------------------------------------------------
# HTTP
# ---------------------------------------------------------------------------
PAGINA = """<!doctype html><html lang="es"><head><meta charset="utf-8">
<title>IA desde cero</title><style>
body{font:15px/1.5 -apple-system,system-ui,sans-serif;max-width:760px;margin:2rem auto;padding:0 1rem;background:#0f1115;color:#e6e6e6}
h1{font-size:1.2rem;color:#9ad}
#chat{border:1px solid #2a2f3a;border-radius:8px;padding:1rem;min-height:320px;background:#151922}
.msg{margin:.6rem 0;padding:.5rem .7rem;border-radius:6px;white-space:pre-wrap}
.u{background:#1d2633} .a{background:#1a2420}
.meta{color:#667;font-size:12px;margin-top:.3rem}
form{display:flex;gap:.5rem;margin-top:1rem}
input{flex:1;padding:.6rem;border-radius:6px;border:1px solid #2a2f3a;background:#0f1115;color:#e6e6e6}
button{padding:.6rem 1rem;border-radius:6px;border:0;background:#3a6ea5;color:#fff;cursor:pointer}
</style></head><body>
<h1>IA desde cero · modelo local</h1>
<div id="chat"></div>
<form id="f"><input id="i" placeholder="Escribe algo..." autocomplete="off" autofocus><button>Enviar</button></form>
<script>
const hist=[];
const chat=document.getElementById('chat');
function add(cls,txt){const d=document.createElement('div');d.className='msg '+cls;d.textContent=txt;chat.appendChild(d);chat.scrollTop=chat.scrollHeight;return d;}
document.getElementById('f').onsubmit=async e=>{
e.preventDefault();const i=document.getElementById('i');const t=i.value.trim();if(!t)return;i.value='';
add('u',t);hist.push({rol:'usuario',contenido:t});
const d=add('a','');let acc='';
const r=await fetch('/api/chat',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({mensajes:hist})});
const rd=r.body.getReader();const dec=new TextDecoder();let buf='';
while(true){const {value,done}=await rd.read();if(done)break;
buf+=dec.decode(value,{stream:true});
const lineas=buf.split('\\n\\n');buf=lineas.pop();
for(const l of lineas){if(!l.startsWith('data: '))continue;
const ev=JSON.parse(l.slice(6));
if(ev.tipo==='texto'){acc+=ev.texto;d.textContent=acc;}
else if(ev.tipo==='fin'){const m=document.createElement('div');m.className='meta';
m.textContent=`${ev.tokens_prompt} tokens de prompt · ${ev.tokens_generados} generados · ${ev.tokens_por_segundo} tok/s · precarga ${ev.ms_precarga} ms`+(ev.turnos_recortados?` · ${ev.turnos_recortados} turnos recortados`:'');
d.appendChild(m);}
chat.scrollTop=chat.scrollHeight;}}
hist.push({rol:'asistente',contenido:acc});
};
</script></body></html>"""
def crear_manejador(servicio):
class Manejador(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *a):
pass
def do_GET(self):
if self.path in ("/", "/index.html"):
cuerpo = PAGINA.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(cuerpo)))
self.end_headers()
self.wfile.write(cuerpo)
elif self.path == "/api/info":
cuerpo = json.dumps({
"modelo": servicio.nombre,
"vocabulario": servicio.cfg["vocab_size"],
"contexto": servicio.block,
"capas": servicio.cfg["n_layer"],
"chat": servicio.tiene_chat,
}).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(cuerpo)))
self.end_headers()
self.wfile.write(cuerpo)
else:
self.send_error(404)
def do_POST(self):
if self.path != "/api/chat":
return self.send_error(404)
n = int(self.headers.get("Content-Length", 0))
datos = json.loads(self.rfile.read(n) or b"{}")
# SERVER-SENT EVENTS: un flujo HTTP que se mantiene abierto y por
# el que el servidor va empujando líneas "data: {...}". Es lo que
# usan de verdad las APIs de chat (incluida la de OpenAI).
# La alternativa serían websockets; SSE es más simple y basta,
# porque el flujo sólo va en una dirección.
self.send_response(200)
self.send_header("Content-Type", "text/event-stream; charset=utf-8")
self.send_header("Cache-Control", "no-cache")
self.send_header("Connection", "keep-alive")
self.end_headers()
try:
for ev in servicio.generar_flujo(
datos.get("mensajes", []),
temperatura=float(datos.get("temperatura", 0.4)),
top_p=float(datos.get("top_p", 0.9)),
max_tokens=int(datos.get("max_tokens", 80))):
linea = f"data: {json.dumps(ev, ensure_ascii=False)}\n\n"
self.wfile.write(linea.encode("utf-8"))
self.wfile.flush()
except (BrokenPipeError, ConnectionResetError):
pass # el cliente cerró: normal, no es un error
return Manejador
def main():
print(__doc__.split("Ejecuta:")[0])
servicio = ServicioChat()
print("=" * 78)
print(f" modelo : pesos/{servicio.nombre}.npz")
print(f" vocabulario : {servicio.cfg['vocab_size']}")
print(f" contexto : {servicio.block} tokens")
print(f" plantilla : {'chat (<|usuario|>/<|asistente|>)' if servicio.tiene_chat else 'NINGUNA (modelo base: sólo continúa texto)'}")
if not servicio.tiene_chat:
print("\n AVISO: este modelo no ha pasado por SFT. No responderá preguntas,")
print(" continuará el texto. Ejecuta etapas/09_finetuning_lora/01_sft_chat.py")
print("=" * 78)
print(f"\n Navegador : http://localhost:{PUERTO}")
print(f" Terminal : python etapas/11_servidor_chat/chat.py")
print(f" API : curl -N -X POST http://localhost:{PUERTO}/api/chat \\")
print(f" -H 'Content-Type: application/json' \\")
print(f" -d '{{\"mensajes\":[{{\"rol\":\"usuario\",\"contenido\":\"¿Qué es un token?\"}}]}}'")
print("\n Ctrl+C para parar.\n")
servidor = ThreadingHTTPServer(("127.0.0.1", PUERTO), crear_manejador(servicio))
try:
servidor.serve_forever()
except KeyboardInterrupt:
print("\n Parado.")
servidor.server_close()
return 0
if __name__ == "__main__":
sys.exit(main())