Tous les chapitres

Rapports et voixChapitre 12 · 15 min de lecture

Des rapports écrits

Demander un rapport par commande, le faire enregistrer par l'agent, le retrouver plus tard.

Ce qu'on veut

Depuis ton téléphone : /rapport avancement du module de facturation et recevoir un document structuré, conservé pour pouvoir le relire ou se le faire lire (chapitre suivant).

L'outil saveReport

Le rapport est écrit par l'agent lui-même, avec sa mémoire (recall) et, s'il le juge utile, ses sous-agents. Il enregistre ensuite le résultat via un outil :

agent-example/src/agent/report-tools.ts

import { tool } from "ai";
import { z } from "zod";
import { saveReportRow } from "../lib/store";

export function reportTools(namespace: string) {
  return {
    saveReport: tool({
      description:
        "Save a finished written report so the user can read it later or have it read aloud. Call it once, with the complete Markdown report.",
      inputSchema: z.object({
        title: z.string().min(3).max(120),
        markdown: z.string().min(50).describe("The full report in Markdown"),
      }),
      execute: async ({ title, markdown }) => {
        const id = await saveReportRow(namespace, title, markdown);
        return { saved: true as const, id };
      },
    }),
  };
}

Seul l'agent principal reçoit cet outil : les sous-agents ne peuvent que lire la mémoire. C'est un choix de sécurité simple : un seul endroit écrit des documents.

Le stockage

Les rapports vont dans la table reports du même Postgres, rangés par namespace (l'id du preset, comme la mémoire) :

agent-example/src/lib/store.ts

import { isDatabaseConfigured, query } from "./db";

let ready: Promise<void> | null = null;

function ensure(): Promise<void> {
  return (ready ??= (async () => {
    await query(`
      CREATE TABLE IF NOT EXISTS chat_history (
        id         BIGSERIAL PRIMARY KEY,
        chat_key   TEXT NOT NULL,
        role       TEXT NOT NULL,
        content    TEXT NOT NULL,
        created_at TIMESTAMPTZ NOT NULL DEFAULT now()
      )`);
    await query("CREATE INDEX IF NOT EXISTS chat_history_key_idx ON chat_history (chat_key, id)");
    await query(`
      CREATE TABLE IF NOT EXISTS reports (
        id         BIGSERIAL PRIMARY KEY,
        namespace  TEXT NOT NULL,
        title      TEXT NOT NULL,
        body       TEXT NOT NULL,
        created_at TIMESTAMPTZ NOT NULL DEFAULT now()
      )`);
  })().catch((error) => {
    ready = null;
    throw error;
  }));
}

export type HistoryMessage = { role: "user" | "assistant"; content: string };

const SUMMARY_PREFIX = "[Résumé de la conversation précédente]\n";

/**
 * The summary row (if any) plus the last `limit` messages, oldest first.
 * Without a database the agent simply has no conversation history on chat channels.
 */
export async function loadHistory(chatKey: string, limit = 20): Promise<HistoryMessage[]> {
  if (!isDatabaseConfigured()) return [];
  await ensure();
  const rows = await query<{ role: string; content: string }>(
    `SELECT role, content FROM chat_history
      WHERE chat_key = $1
        AND (role = 'summary' OR id IN (SELECT id FROM chat_history WHERE chat_key = $1 ORDER BY id DESC LIMIT $2))
      ORDER BY id`,
    [chatKey, limit],
  );
  return rows.map((r) =>
    r.role === "summary"
      ? { role: "user" as const, content: SUMMARY_PREFIX + r.content }
      : { role: r.role as "user" | "assistant", content: r.content },
  );
}

/**
 * Keeps long conversations cheap: once a chat holds more than `threshold` rows, everything except the
 * last `keep` rows is replaced by ONE summary row (itself summarised again next time).
 * One SQL statement, so a crash cannot leave the history half deleted.
 */
export async function compactHistory(
  chatKey: string,
  summarize: (transcript: string) => Promise<string>,
  { threshold = 40, keep = 12 }: { threshold?: number; keep?: number } = {},
): Promise<boolean> {
  if (!isDatabaseConfigured()) return false;
  await ensure();
  const rows = await query<{ id: string | number; role: string; content: string }>(
    "SELECT id, role, content FROM chat_history WHERE chat_key = $1 ORDER BY id",
    [chatKey],
  );
  if (rows.length <= threshold) return false;

  const old = rows.slice(0, rows.length - keep);
  const transcript = old
    .map((r) => `${r.role === "summary" ? "Résumé précédent" : r.role === "user" ? "Utilisateur" : "Agent"} : ${r.content}`)
    .join("\n");
  const summary = (await summarize(transcript)).trim();
  if (!summary) return false;

  const firstId = Number(old[0].id);
  await query(
    `WITH removed AS (
       DELETE FROM chat_history WHERE chat_key = $1 AND id = ANY($2::bigint[]) AND id <> $3
     )
     UPDATE chat_history SET role = 'summary', content = $4 WHERE id = $3`,
    [chatKey, old.map((r) => Number(r.id)), firstId, summary],
  );
  return true;
}

export async function appendHistory(chatKey: string, ...messages: HistoryMessage[]) {
  if (!isDatabaseConfigured()) return;
  await ensure();
  for (const m of messages) {
    await query("INSERT INTO chat_history (chat_key, role, content) VALUES ($1, $2, $3)", [
      chatKey,
      m.role,
      m.content,
    ]);
  }
}

export async function clearHistory(chatKey: string) {
  if (!isDatabaseConfigured()) return;
  await ensure();
  await query("DELETE FROM chat_history WHERE chat_key = $1", [chatKey]);
}

export async function saveReportRow(namespace: string, title: string, body: string): Promise<number> {
  await ensure();
  const rows = (await query(
    "INSERT INTO reports (namespace, title, body) VALUES ($1, $2, $3) RETURNING id",
    [namespace, title, body],
  )) as Array<{ id: string | number }>;
  return Number(rows[0].id);
}

export async function latestReport(namespace: string) {
  await ensure();
  const rows = (await query(
    "SELECT id, title, body FROM reports WHERE namespace = $1 ORDER BY id DESC LIMIT 1",
    [namespace],
  )) as Array<{ id: string | number; title: string; body: string }>;
  return rows[0] ? { id: Number(rows[0].id), title: rows[0].title, body: rows[0].body } : null;
}

export async function listReports(namespace: string, limit = 10) {
  await ensure();
  const rows = await query<{ id: string | number; title: string; created_at: Date }>(
    "SELECT id, title, created_at FROM reports WHERE namespace = $1 ORDER BY id DESC LIMIT $2",
    [namespace, limit],
  );
  return rows.map((r) => ({ id: Number(r.id), title: r.title, createdAt: r.created_at }));
}

export async function getReport(namespace: string, id: number) {
  await ensure();
  const rows = await query<{ id: string | number; title: string; body: string }>(
    "SELECT id, title, body FROM reports WHERE namespace = $1 AND id = $2",
    [namespace, id],
  );
  return rows[0] ? { id: Number(rows[0].id), title: rows[0].title, body: rows[0].body } : null;
}

La commande

Dans handleIncoming (chapitre 9), /rapport <sujet> remplace simplement le message par une consigne précise : rédiger en Markdown, utiliser recall, enregistrer avec saveReport, puis répondre avec le rapport. Sans sujet, l'agent fait le point sur la conversation et sa mémoire.

C'est le modèle qui choisit d'appeler saveReport : sur un très long rapport, vérifie de temps en temps dans la table reports qu'il l'a bien fait.

Pour un rapport régulier

Comme l'agent est un processus permanent, un planificateur interne suffit (une boucle setInterval, ou une bibliothèque de cron) : il appelle handleIncoming avec « /rapport point quotidien », puis envoie le texte avec sendText à ton chat Telegram. Sur un hébergeur qui endort les conteneurs, utilise plutôt le cron de la plateforme pour appeler une route de ton serveur. Le chapitre suivant ajoute la lecture à voix haute.

Lire les rapports ailleurs

La commande /rapports liste les derniers rapports et /voix <numéro> en lit un. Une route GET qui renvoie la table reports est facile à ajouter à app.ts ; protège-la avec checkAccess, ces documents sont privés.

Point de contrôle

  1. /rapport état de l'architecture de mon projet sur Telegram → le rapport arrive (découpé en plusieurs messages s'il est long).
  2. Dans ta base : SELECT id, title, created_at FROM reports; montre une ligne.