App de referencia MÍNIMA pero real: login con refresh, chat con streaming SSE, conversaciones persistentes en Leka (con integridad firmada), memoria de sesión y manejo de errores. Cópiala como base de tu integración.
Requisitos: Node 20+, Next.js 14+ (App Router). El token nunca llega al browser: todas las llamadas a Leka van por rutas de servidor.
lib/leka.ts ← cliente de Leka (server-only): auth, chat, stream, conversaciones
app/api/login/route.ts ← login + emisión de cookie de sesión httpOnly
app/api/chat/route.ts ← chat streaming (SSE) con persistencia automática
app/page.tsx ← UI mínima de chat
# .env.local
LEKA_GATEWAY=https://tu-gateway-ai-edge
LEKA_BASE=$LEKA_GATEWAY/leka-chat # modalidad chat gobernado
LEKA_USERNAME=usuario@cliente.com
LEKA_PASSWORD=********
npm install && npm run dev
# arranca la app y ábrela en tu navegador
Login una vez + refresh del token (nunca re-login por petición)
Streaming SSE con reasoning separado (reasoning_content)
Persistencia del historial en Leka con un header (X-Conversation-Id)
Memoria de sesión (session_id en el body)
Lectura de usage.x_leka (gobierno visible)
429/5xx con backoff, 403 terminal
NO incluye: tools/function calling, adjuntos, multimedia, RAG — ver las
guías de guía del modo chat para añadirlos.
/**
* lib/leka.ts — Cliente de Leka AI Service vía ai-edge (SERVER-ONLY).
*
* Patrón: un token por servicio, renovado con /refresh (nunca re-login por
* petición). Todas las llamadas llevan Authorization: Bearer.
* Adaptado de los patrones verificados en producción, simplificado para
* integradores.
*/
const GATEWAY = process.env.LEKA_GATEWAY!;
const BASE = process.env.LEKA_BASE ?? `${GATEWAY}/leka-chat`;
// ── Sesión del servicio (token en memoria — UNA por proceso) ────────────────
let cached: { token: string; exp: number } | null = null;
function decodeExp(jwt: string): number {
// exp del payload (segundos) — sin verificar firma (eso lo hace el gateway)
const payload = JSON.parse(Buffer.from(jwt.split(".")[1], "base64url").toString());
return (payload.exp ?? 0) * 1000;
}
export async function getToken(): Promise<string> {
// Renueva 60s antes de caducar
if (cached && cached.exp > Date.now() + 60_000) return cached.token;
if (cached) {
// refresh primero — nunca login si tenemos token válido-caducado
const r = await fetch(`${GATEWAY}/api/v1/authenticate/refresh`, {
method: "POST",
headers: { Authorization: `Bearer ${cached.token}` },
});
if (r.ok) {
const { token } = (await r.json()) as { token: string };
cached = { token, exp: decodeExp(token) };
return token;
}
// refresh fallado (revocado) → login completo abajo
}
const r = await fetch(`${GATEWAY}/api/v1/authenticate/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
username: process.env.LEKA_USERNAME,
password: process.env.LEKA_PASSWORD,
}),
});
if (!r.ok) throw new Error(`login fallido: HTTP ${r.status}`);
const { token } = (await r.json()) as { token: string };
cached = { token, exp: decodeExp(token) };
return token;
}
// ── Helpers ─────────────────────────────────────────────────────────────────
async function authHeaders(): Promise<Record<string, string>> {
return {
Authorization: `Bearer ${await getToken()}`,
"Content-Type": "application/json",
};
}
/** Backoff exponencial SOLO para 429/5xx (los 4xx de negocio no se reintentan). */
async function withRetry<T>(fn: () => Promise<T>, max = 3): Promise<T> {
for (let attempt = 0; ; attempt++) {
try {
return await fn();
} catch (err: any) {
const retriable = err?.status === 429 || (err?.status ?? 0) >= 500;
if (!retriable || attempt >= max) throw err;
// 429: respeta Retry-After si viene; si no, exponencial 1s/2s/4s
const wait = err.retryAfterMs ?? 1000 * 2 ** attempt;
await new Promise((r) => setTimeout(r, wait));
}
}
}
async function post(path: string, body: unknown) {
const r = await fetch(`${BASE}${path}`, {
method: "POST",
headers: await authHeaders(),
body: JSON.stringify(body),
});
if (!r.ok) {
const err: any = new Error(`Leka ${path}: HTTP ${r.status}`);
err.status = r.status;
const ra = r.headers.get("retry-after");
if (ra) err.retryAfterMs = Number(ra) * 1000;
throw err;
}
return r;
}
// ── Conversaciones (el historial vive en Leka, con integridad firmada) ──────
export async function crearConversacion(titulo: string) {
const r = await post("/v1/conversations", { title: titulo });
return (await r.json()) as { id: string };
}
export async function listarConversaciones(limit = 50, offset = 0) {
const r = await fetch(
`${BASE}/v1/conversations?limit=${limit}&offset=${offset}`,
{ headers: await authHeaders() },
);
return (await r.json()) as Array<{ id: string; title: string; updated_at: string }>;
}
export async function mensajesDe(convId: string) {
const r = await fetch(`${BASE}/v1/conversations/${convId}/messages?order=asc`, {
headers: await authHeaders(),
});
return (await r.json()) as Array<{
role: "user" | "assistant" | "tool";
content: string;
created_at: string;
}>;
}
export async function verificarIntegridad(convId: string) {
const r = await fetch(`${BASE}/v1/conversations/${convId}/verify`, {
headers: await authHeaders(),
});
return (await r.json()) as { chainOk: boolean; signaturesOk: boolean };
}
// ── Chat (streaming) ────────────────────────────────────────────────────────
export interface ChatChunk {
type: "text" | "think";
content: string;
}
export interface ChatResult {
chunks: ChatChunk[];
fullText: string;
/** gobierno: política aplicada, degradaciones declaradas — REGÍSTRALO */
xLeka?: Record<string, unknown>;
}
/**
* Chat con streaming. Persistencia automática: con X-Conversation-Id,
* Leka guarda el turno user+assistant con su cadena de integridad.
* El contexto lo construye el llamador (ventana deslizante — ver guía §5).
*/
export async function chatStream(
messages: Array<{ role: string; content: string }>,
opts: { conversationId: string; model: string; onChunk: (c: ChatChunk) => void },
): Promise<ChatResult> {
return withRetry(async () => {
const r2 = await fetch(`${BASE}/v1/chat/completions`, {
method: "POST",
headers: {
...(await authHeaders()),
"X-Conversation-Id": opts.conversationId,
},
body: JSON.stringify({
model: opts.model,
messages,
stream: true,
session_id: opts.conversationId,
}),
// conexión 10s; lectura sin límite (watchdog lo pone el consumidor)
signal: AbortSignal.timeout(10_000),
});
if (!r2.ok && (r2.status === 429 || r2.status >= 500)) {
const err: any = new Error(`chat: HTTP ${r2.status}`);
err.status = r2.status;
throw err;
}
if (!r2.ok) {
const detail = await r2.text().catch(() => "");
// 403 política / 422 DLP son TERMINALES — no se reintentan
throw Object.assign(new Error(`chat: HTTP ${r2.status} ${detail.slice(0, 300)}`), {
status: r2.status,
});
}
const chunks: ChatChunk[] = [];
let fullText = "";
const reader = r2.body!.getReader();
const decoder = new TextDecoder();
let buffer = "";
let usage: any = null;
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
for (const line of buffer.split("\n")) {
if (!line.startsWith("data: ")) continue;
const data = line.slice(6).trim();
if (data === "[DONE]") continue;
let evt: any;
try { evt = JSON.parse(data); } catch { continue; }
if (evt.usage) usage = evt.usage;
const delta = evt.choices?.[0]?.delta ?? {};
if (delta.reasoning_content) {
const c = { type: "think", content: delta.reasoning_content };
chunks.push(c); opts.onChunk(c);
}
if (delta.content) {
fullText += delta.content;
const c = { type: "text", content: delta.content };
chunks.push(c); opts.onChunk(c);
}
}
buffer = buffer.slice(buffer.lastIndexOf("\n") + 1);
}
return { chunks, fullText, xLeka: usage?.x_leka };
});
}
/**
* app/api/chat/route.ts — Chat streaming del navegador hacia Leka.
*
* El navegador llama a ESTA ruta (mismo origen, sin CORS ni token expuesto);
* el server proxya a Leka con streaming. Recibe el turno del usuario,
* construye la ventana de contexto (últimos N turnos del historial de Leka —
* ventana deslizante, guía MODO_CHAT §5.1) y devuelve texto plano en stream.
*/
import { NextRequest } from "next/server";
import {
chatStream,
crearConversacion,
mensajesDe,
} from "@/lib/leka";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
const MODELO = process.env.LEKA_MODEL ?? "kimi-k2.5";
const SYSTEM = "Eres el asistente de la aplicación. Responde claro y breve.";
const MAX_TURNOS = 12; // ventana deslizante: últimos 12 turnos
export async function POST(req: NextRequest) {
const { message, conversationId } = (await req.json()) as {
message: string;
conversationId?: string;
};
// 1. Conversación: reusa o crea (el historial vive en Leka, firmado)
const convId = conversationId ?? (await crearConversacion("Chat web")).id;
// 2. Contexto: system + últimos turnos del historial + turno nuevo
const history = await mensajesDe(convId);
const recent = history.filter((m) => m.role !== "tool").slice(-MAX_TURNOS);
const messages = [
{ role: "system", content: SYSTEM },
...recent.map((m) => ({ role: m.role, content: m.content })),
{ role: "user", content: message },
];
// 3. Stream al navegador: texto plano + cabecera con la conversación
const encoder = new TextEncoder();
const stream = new ReadableStream({
async start(controller) {
try {
await chatStream(messages, {
conversationId: convId,
model: MODELO,
onChunk: (c) =>
controller.enqueue(
encoder.encode(c.type === "text" ? c.content : ""),
),
});
} catch (err: any) {
// 403 política / 422 DLP: mensaje accionable, no stack traces
const msg =
err.status === 403
? "\n[La política de gobierno de tu organización ha denegado esta petición]"
: err.status === 422
? "\n[Contenido bloqueado por seguridad (DLP) — revisa el mensaje]"
: "\n[Error temporal del servicio de IA — reintenta en unos segundos]";
controller.enqueue(encoder.encode(msg));
console.error("[leka] chat error:", err.status, String(err.message).slice(0, 200));
} finally {
controller.close();
}
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/plain; charset=utf-8",
"Cache-Control": "no-cache",
"X-Conversation-Id": convId, // el browser la guarda para el siguiente turno
},
});
}
/**
* app/api/verify/route.ts — Verificación de integridad de una conversación
* (auditoría): recomputa la cadena hash+firma en Leka y devuelve el veredicto.
*/
import { NextRequest } from "next/server";
import { verificarIntegridad } from "@/lib/leka";
export const runtime = "nodejs";
export async function GET(req: NextRequest) {
const conv = req.nextUrl.searchParams.get("conv");
if (!conv) return Response.json({ error: "falta conv" }, { status: 400 });
return Response.json(await verificarIntegridad(conv));
}
"use client";
/**
* app/page.tsx — UI mínima de chat.
* Demo de consumo de la ruta /api/chat (stream de texto plano) + verificación
* de integridad de la conversación (auditoría) mediante /api/verify.
*/
import { useRef, useState } from "react";
export default function Chat() {
const [convId, setConvId] = useState<string | null>(null);
const [messages, setMessages] = useState<{ from: "user" | "bot"; text: string }[]>([]);
const [input, setInput] = useState("");
const [busy, setBusy] = useState(false);
const bottomRef = useRef<HTMLDivElement>(null);
async function send(e: React.FormEvent) {
e.preventDefault();
if (!input.trim() || busy) return;
const text = input.trim();
setInput("");
setMessages((m) => [...m, { from: "user", text }, { from: "bot", text: "" }]);
setBusy(true);
const res = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: text, conversationId: convId }),
});
const newConv = res.headers.get("X-Conversation-Id");
if (newConv) setConvId(newConv);
const reader = res.body!.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
setMessages((m) => {
const copy = [...m];
copy[copy.length - 1] = {
from: "bot",
text: copy[copy.length - 1].text + chunk,
};
return copy;
});
bottomRef.current?.scrollIntoView({ behavior: "smooth" });
}
setBusy(false);
}
async function verificar() {
if (!convId) return;
const r = await fetch(`/api/verify?conv=${convId}`);
const proof = await r.json();
alert(
proof.chainOk && proof.signaturesOk
? "Cadena de integridad verificada — la conversación no se alteró."
: `Verificación fallida: ${JSON.stringify(proof.brokenAt)}`,
);
}
return (
<main style={{ maxWidth: 640, margin: "2rem auto", fontFamily: "system-ui" }}>
<h1>Chat · Leka AI Service</h1>
<div style={{ height: "60vh", overflowY: "auto", border: "1px solid #ccc", borderRadius: 8, padding: 12 }}>
{messages.map((m, i) => (
<div key={i} style={{ textAlign: m.from === "user" ? "right" : "left", margin: "6px 0" }}>
<span
style={{
display: "inline-block",
padding: "6px 10px",
borderRadius: 12,
background: m.from === "user" ? "#d0e7ff" : "#f0f0f0",
whiteSpace: "pre-wrap",
}}
>
{m.text}
</span>
</div>
))}
<div ref={bottomRef} />
</div>
<form onSubmit={send} style={{ display: "flex", gap: 8, marginTop: 12 }}>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Escribe tu mensaje…"
style={{ flex: 1, padding: 10, borderRadius: 8, border: "1px solid #ccc" }}
disabled={busy}
/>
<button type="submit" disabled={busy} style={{ padding: "10px 16px", borderRadius: 8 }}>
{busy ? "…" : "Enviar"}
</button>
</form>
{convId && (
<p style={{ fontSize: 12, color: "#666" }}>
Conversación: {convId.slice(0, 18)}… ·{" "}
<button onClick={verificar} style={{ border: 0, color: "#06c", background: 0, cursor: "pointer" }}>
verificar integridad
</button>
</p>
)}
</main>
);
}