Tous les chapitres

MémoireChapitre 7 · 20 min de lecture

Mémoire à long terme

Schéma, embeddings, recherche par similarité, et les outils remember / recall.

Le modèle de données

Une seule table, memories. Chaque ligne est un passage : une note mémorisée par l'agent ou un extrait de document. Le champ namespace reçoit l'id du preset, ce qui isole les mémoires de chaque agent.

agent-example/src/lib/memory.ts

import { embed, embedMany, rerank } from "ai";
import { query } from "./db";

/** text-embedding-3-small returns 1536 numbers. Change both together. */
export const EMBEDDING_MODEL = "openai/text-embedding-3-small";
const DIMENSIONS = 1536;

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

/** Creates the extension, the table and the index once per server instance. */
export function ensureSchema(): Promise<void> {
  return (ready ??= (async () => {
    await query("CREATE EXTENSION IF NOT EXISTS vector");
    await query(`
      CREATE TABLE IF NOT EXISTS memories (
        id         BIGSERIAL PRIMARY KEY,
        namespace  TEXT NOT NULL,
        kind       TEXT NOT NULL,
        source     TEXT,
        content    TEXT NOT NULL,
        embedding  vector(${DIMENSIONS}) NOT NULL,
        created_at TIMESTAMPTZ NOT NULL DEFAULT now()
      )`);
    await query(
      "CREATE INDEX IF NOT EXISTS memories_embedding_idx ON memories USING hnsw (embedding vector_cosine_ops)",
    );
    await query(
      "CREATE INDEX IF NOT EXISTS memories_namespace_idx ON memories (namespace)",
    );
  })().catch((error) => {
    ready = null; // allow a retry on the next call
    throw error;
  }));
}

const toVector = (values: number[]) => `[${values.join(",")}]`;

export type MemoryKind = "note" | "document";

export async function addMemories(
  namespace: string,
  kind: MemoryKind,
  passages: string[],
  source?: string,
): Promise<number> {
  if (passages.length === 0) return 0;
  await ensureSchema();
  const { embeddings } = await embedMany({ model: EMBEDDING_MODEL, values: passages });
  for (let i = 0; i < passages.length; i++) {
    await query(
      "INSERT INTO memories (namespace, kind, source, content, embedding) VALUES ($1, $2, $3, $4, $5::vector)",
      [namespace, kind, source ?? null, passages[i], toVector(embeddings[i])],
    );
  }
  return passages.length;
}

/** Re-ingesting a document must replace it, not duplicate it. */
export async function deleteBySource(namespace: string, source: string): Promise<void> {
  await ensureSchema();
  await query("DELETE FROM memories WHERE namespace = $1 AND kind = 'document' AND source = $2", [namespace, source]);
}

export type Hit = { content: string; kind: string; source: string | null; score: number };

export type SearchOptions = {
  /** Drop passages whose cosine similarity is below this (0 to 1). */
  minScore?: number;
  /**
   * A reranking model, "provider/model" (default: the RERANK_MODEL env var, otherwise no reranking).
   * Vector search finds passages that are *near*; a reranker reads the question and each passage
   * together and reorders them by how well they actually answer.
   */
  rerankModel?: string;
};

export async function searchMemories(
  namespace: string,
  question: string,
  topK: number,
  { minScore = 0, rerankModel = process.env.RERANK_MODEL }: SearchOptions = {},
): Promise<Hit[]> {
  await ensureSchema();
  const { embedding } = await embed({ model: EMBEDDING_MODEL, value: question });
  // With a reranker, fetch more candidates than we keep, then let it choose.
  const candidates = rerankModel ? Math.min(topK * 4, 40) : topK;
  const rows = await query(
    `SELECT content, kind, source, 1 - (embedding <=> $1::vector) AS score
       FROM memories
      WHERE namespace = $2
      ORDER BY embedding <=> $1::vector
      LIMIT $3`,
    [toVector(embedding), namespace, candidates],
  );
  const hits = (rows as Array<Record<string, unknown>>)
    .map((r) => ({
      content: String(r.content),
      kind: String(r.kind),
      source: r.source === null ? null : String(r.source),
      score: Number(r.score),
    }))
    .filter((h) => h.score >= minScore);

  return rerankModel && hits.length > 1 ? rerankHits(question, hits, topK, rerankModel) : hits.slice(0, topK);
}

export async function rerankHits(
  question: string,
  hits: Hit[],
  topN: number,
  model: Parameters<typeof rerank>[0]["model"],
): Promise<Hit[]> {
  const { ranking } = await rerank({ model, query: question, documents: hits.map((h) => h.content), topN });
  // `score` becomes the reranker's relevance: it is what the agent shows the model.
  return ranking.map((r) => ({ ...hits[r.originalIndex], score: r.score }));
}

/** Splits a document into overlapping passages of roughly `size` characters. */
export function chunkText(text: string, size = 1000, overlap = 150): string[] {
  const clean = text.replace(/\r\n/g, "\n").trim();
  const paragraphs = clean.split(/\n{2,}/);
  const chunks: string[] = [];
  let current = "";
  for (const paragraph of paragraphs) {
    if (current && current.length + paragraph.length + 2 > size) {
      chunks.push(current);
      current = current.slice(-overlap) + "\n\n" + paragraph;
    } else {
      current = current ? current + "\n\n" + paragraph : paragraph;
    }
  }
  if (current) chunks.push(current);
  return chunks;
}

Points clés :

  • Création paresseuse du schéma (ensureSchema) : pas de migration à lancer pour le tutoriel. En production réelle, passe à un outil de migrations.
  • Embeddings via l'AI Gateway : embed et embedMany prennent une chaîne openai/text-embedding-3-small (1536 dimensions). Si tu changes de modèle, change DIMENSIONS et recrée la table.
  • <=> est la distance cosinus ; 1 - distance donne un score de similarité. L'index hnsw accélère la recherche.
  • Les valeurs sont toujours passées en paramètres ($1, $2…) : jamais de texte concaténé dans le SQL.

Les outils de l'agent

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

import { tool } from "ai";
import { z } from "zod";
import { addMemories, searchMemories } from "../lib/memory";

export function memoryTools(namespace: string, topK: number, minScore = 0.25) {
  return {
    recall: tool({
      description:
        "Search long-term memory and the knowledge base for passages relevant to a question. Use it before answering about the user's project or documentation.",
      inputSchema: z.object({
        query: z.string().describe("What to look for, phrased as a short question or keywords"),
      }),
      execute: async ({ query }) => {
        const hits = await searchMemories(namespace, query, topK, { minScore });
        if (hits.length === 0) return { found: false as const, passages: [] };
        return {
          found: true as const,
          passages: hits.map((h) => ({
            text: h.content,
            from: h.source ?? h.kind,
            relevance: Number(h.score.toFixed(2)),
          })),
        };
      },
    }),
    remember: tool({
      description:
        "Store a durable fact, decision or convention for future conversations. Never store secrets or personal data.",
      inputSchema: z.object({
        fact: z.string().min(5).describe("One self-contained sentence"),
      }),
      execute: async ({ fact }) => {
        await addMemories(namespace, "note", [fact]);
        return { stored: true as const };
      },
    }),
  };
}
  • recall : recherche sémantique. Le modèle l'appelle quand une question touche au projet ou à la documentation.
  • remember : stocke un fait durable. La description lui interdit les secrets et données personnelles ; ne compte pas que sur ça et relis ce qui est stocké de temps en temps.

Ils sont branchés dans buildAgent() (chapitre 4) uniquement si DATABASE_URL est défini.

Point de contrôle

Avec npm run chat (preset Dev Lead) :

  1. « Souviens-toi : on utilise Next.js, TypeScript strict et Postgres. »
  2. Quitte et relance npm run chat (nouvelle conversation, mêmes souvenirs).
  3. « Quelle est ma stack ? » : l'agent doit appeler recall et répondre correctement.