FondationsChapitre 2 · 15 min de lecture
Un premier agent qui répond
Une classe ToolLoopAgent, un serveur HTTP en streaming, et un chat en terminal.
L'idée
Un agent, c'est un modèle + des instructions + des outils, exécutés en boucle : le modèle réfléchit, appelle un outil, lit le résultat, recommence, jusqu'à avoir une réponse. ToolLoopAgent fait cette boucle pour toi.
La version minimale
// src/agent/build.ts (version du chapitre 2)
import { ToolLoopAgent, isStepCount } from "ai";
export function buildAgent() {
return new ToolLoopAgent({
model: "anthropic/claude-sonnet-5.5",
instructions: "You are a helpful engineering lead. Answer in the language of the user.",
stopWhen: isStepCount(20), // garde-fou : jamais de boucle infinie
});
}
modelest une simple chaîne passée à l'AI Gateway : pas de paquet fournisseur à installer.stopWhenborne le nombre d'étapes. Pose-le toujours explicitement.
Parler à l'agent dans le terminal
Le moyen le plus rapide de tester, sans serveur :
agent-example/src/cli.ts
/** Talk to the agent from a terminal, no server needed: npm run chat */
import { createInterface } from "node:readline/promises";
import { stdin, stdout } from "node:process";
import { buildAgent } from "./agent/build";
import type { ModelMessage } from "ai";
const agent = buildAgent();
const rl = createInterface({ input: stdin, output: stdout });
const messages: ModelMessage[] = [];
console.log("Ctrl+C pour quitter.");
for (;;) {
const text = (await rl.question("\n> ")).trim();
if (!text) continue;
messages.push({ role: "user", content: text });
const result = await agent.generate({ messages });
console.log(`\n${result.text}`);
messages.push({ role: "assistant", content: result.text });
}
npm run chat
Le serveur HTTP
Le serveur est le point d'entrée de l'agent, quel que soit l'hébergeur. Il est coupé en deux fichiers pour pouvoir être testé sans démarrer de processus : app.ts déclare les routes, server.ts démarre le processus et lance les canaux.
agent-example/src/app.ts
import { createAgentUIStreamResponse } from "ai";
import { readFileSync } from "node:fs";
import { Hono } from "hono";
import { buildAgent } from "./agent/build";
import { getAgentConfig } from "./config";
import { handleIncoming } from "./channels/core";
import { handleTelegramWebhook } from "./channels/telegram";
import { checkAccess } from "./lib/auth";
import { isDatabaseConfigured } from "./lib/db";
import { addMemories, chunkText, deleteBySource } from "./lib/memory";
export const app = new Hono();
/**
* Anti-CSRF: every POST must declare application/json. A web page on another site cannot send that
* type without a CORS preflight, which this server never approves. Without this check, a hostile page
* could POST text/plain to a local agent that runs without a token (development) and drive it.
*/
app.use("*", async (c, next) => {
if (c.req.method === "POST" && !c.req.header("content-type")?.toLowerCase().startsWith("application/json")) {
return c.json({ error: "Content-Type must be application/json" }, 415);
}
await next();
});
/** Liveness probe for Docker, Fly, Railway, Render, Kubernetes... Reveals nothing sensitive. */
app.get("/health", (c) => c.json({ ok: true }));
/** Streaming chat endpoint, compatible with the AI SDK's useChat. */
app.post("/chat", async (c) => {
const denied = checkAccess(c.req.raw);
if (denied) return denied;
const { messages } = await c.req.json();
return createAgentUIStreamResponse({
agent: buildAgent(),
uiMessages: messages,
abortSignal: c.req.raw.signal,
});
});
/** Adds a document to the knowledge base of the active preset. */
app.post("/knowledge", async (c) => {
const denied = checkAccess(c.req.raw);
if (denied) return denied;
if (!isDatabaseConfigured()) return c.json({ error: "DATABASE_URL is not set" }, 503);
const body = (await c.req.json().catch(() => null)) as { title?: string; text?: string } | null;
if (!body?.title || !body.text || body.text.length < 20 || body.text.length > 200_000) {
return c.json({ error: "Expected { title, text } (20 to 200000 characters)" }, 400);
}
const { id } = getAgentConfig();
await deleteBySource(id, body.title);
const passages = await addMemories(id, "document", chunkText(body.text), body.title);
return c.json({ namespace: id, passages });
});
/** Telegram webhook mode only. */
app.post("/channels/telegram", async (c) => {
const ok = handleTelegramWebhook(c.req.header("x-telegram-bot-api-secret-token"), await c.req.json());
return ok ? c.json({ ok: true }) : c.text("Unauthorized", 401);
});
/** A minimal web page: the same agent, the same commands, from a browser. Chapter 21. */
const page = () => readFileSync("public/index.html", "utf8");
app.get("/", (c) => {
c.header(
"content-security-policy",
"default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; media-src blob: data:; img-src 'self' data:",
);
return c.html(page());
});
app.post("/web/message", async (c) => {
const denied = checkAccess(c.req.raw);
if (denied) return denied;
const body = (await c.req.json().catch(() => null)) as { text?: string; audioBase64?: string } | null;
if (!body || (!body.text?.trim() && !body.audioBase64)) return c.json({ error: "Expected { text } or { audioBase64 }" }, 400);
if (body.text && body.text.length > 8000) return c.json({ error: "Message too long" }, 413);
const reply = await handleIncoming({
channel: "web",
chatId: "owner", // one conversation: the token holder is the owner
text: body.text,
audio: body.audioBase64 ? new Uint8Array(Buffer.from(body.audioBase64, "base64")) : undefined,
});
const pack = (a?: { data: Uint8Array; mediaType: string; filename: string }) =>
a && { base64: Buffer.from(a.data).toString("base64"), mediaType: a.mediaType, filename: a.filename };
return c.json({ heard: reply.heard, text: reply.text, voice: pack(reply.voice), file: pack(reply.file) });
});
agent-example/src/server.ts
import { serve } from "@hono/node-server";
import { app } from "./app";
import { signalEnabled, startSignal } from "./channels/signal";
import { startTelegram, telegramEnabled } from "./channels/telegram";
import { getAgentConfig } from "./config";
import { isDatabaseConfigured } from "./lib/db";
import { schedulerEnabled, startScheduler } from "./scheduler";
const port = Number(process.env.PORT ?? 3000);
serve({ fetch: app.fetch, port }, () => {
const preset = getAgentConfig();
console.log(`agent "${preset.id}" (${preset.model}) listening on :${port}`);
console.log(`memory: ${isDatabaseConfigured() ? "on" : "off (no DATABASE_URL)"}`);
});
if (telegramEnabled()) startTelegram().catch((error) => console.error("telegram failed to start", error));
if (signalEnabled()) startSignal();
if (schedulerEnabled()) startScheduler();
// Hosts stop containers with SIGTERM: leave quickly instead of being killed mid-request.
for (const signal of ["SIGTERM", "SIGINT"] as const) process.on(signal, () => process.exit(0));
Les routes : /health (sonde de vie), /chat (streaming), /knowledge (chapitre 8), /channels/telegram (chapitre 9), / et /web/message (chapitre optionnel 21).
À retenir :
- Hono manipule des
RequestetResponsestandard : le même code tourne sur Node, Bun, Deno ou en serverless. /chatreçoit les messages d'une interface et renvoie un flux :createAgentUIStreamResponsefait tout le travail, etabortSignalarrête l'agent si le client se déconnecte.- Protection contre les requêtes inter-sites (CSRF) : tout
POSTdoit déclarerContent-Type: application/json. Une page tierce ne peut pas envoyer ce type sans une pré-vérification CORS que le serveur n'approuve jamais ; sans ce garde-fou, une page hostile pourrait piloter un agent local lancé sans jeton, en développement. C'est testé (test/app.test.ts). - Arrêt propre : les hébergeurs stoppent les conteneurs avec
SIGTERM; le serveur quitte au lieu d'être tué en plein travail. - Le démarrage affiche l'état de la mémoire : tu vois tout de suite si
DATABASE_URLest pris en compte.
Une interface web ?
/chat parle le protocole de messages de l'AI SDK : n'importe quelle application React peut s'y brancher avec useChat et un DefaultChatTransport({ api: "https://ton-agent/chat" }), et envoyer l'en-tête x-access-token. Ce tutoriel ne fournit pas d'interface : ton téléphone (chapitres 9 à 13) est l'interface principale.
Point de contrôle
npm run dev
curl http://localhost:3000/health
curl -N -X POST http://localhost:3000/chat -H "content-type: application/json" \
-d '{"messages":[{"id":"1","role":"user","parts":[{"type":"text","text":"Salut !"}]}]}'
Tu dois voir arriver un flux d'événements contenant la réponse. Pas de réponse ? Vérifie d'abord AI_GATEWAY_API_KEY, puis la console du serveur.