This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Deep Dives (Stage 1)

One level deeper on the core Stage 0 topics — the parts that pay off in real systems.

Stage 1 goes deeper on the topics introduced in Foundations. Where Stage 0 answered what and when, Stage 1 answers how — the strategies, patterns, and trade-offs that show up when you build real systems.

Roadmap

The dives follow the same spine as the Stage 0 modules — prompts, then data, then agents, then operating:

flowchart LR
    A[Prompt patterns] --> B[Vector databases] --> C[Types of RAG] --> D[Advanced RAG]
    D --> E[Agent patterns] --> F[Agent memory] --> M[Multi-agent] --> SE[Self-improving] --> CU[Computer use]
    CU --> G[Adaptation] --> H[Evaluation in practice] --> RE[RAG evaluation]

In this section

  1. Prompt patterns — reasoning techniques, structured output, decomposition, optimization.
  2. Vector databases — ANN indexes (HNSW, IVF, PQ), metadata filtering, choosing a store.
  3. Types of RAG — the RAG family; architecture, control loop, or technique, and how to choose.
  4. Advanced RAG — chunking, hybrid retrieval, re-ranking, query transforms.
  5. Agent patterns — the ReAct loop, tool design, multi-agent, reflection.
  6. Agent memory — the memory types, and when each one earns its place.
  7. Multi-agent systems — topologies, and a shared knowledge graph as team memory.
  8. Self-improving agents — getting better without changing the weights.
  9. Computer use & real-time — agents that act in the world, not just answer.
  10. Adaptation — choosing between prompting, RAG, and fine-tuning.
  11. Evaluation in practice — eval sets, LLM-as-judge, offline vs online, regression testing.
  12. RAG evaluation — the four RAGAS metrics, and splitting retrieval failures from generation failures.

1 - Prompt Patterns

Reasoning techniques, structured output, decomposition, and prompt optimization.

Builds on Prompt Engineering in Foundations. Patterns for harder tasks where a single well-formed prompt isn’t enough.

Reasoning techniques

  • Chain-of-thought — ask for step-by-step reasoning before the answer; helps on multi-step problems.
  • Self-consistency — sample several reasoning paths and take the majority answer; trades cost for reliability.
  • Least-to-most — solve easier sub-problems first, then use them to solve the harder one.

Structured output

When the output feeds another system, constrain its shape:

  • Ask for JSON against an explicit schema; validate and retry on failure.
  • Prefer native function/tool calling or structured-output modes over parsing free text.
  • Keep schemas small and flat; describe each field.

Decomposition and chaining

Split a big task into a chain of smaller prompts, each with one job and a checkable output. Easier to test, debug, and swap. Prefer chaining over one mega-prompt when steps have distinct goals (extract → transform → format).

A concrete chain — “turn this support email thread into a ticket”:

  1. Extract — pull customer, product, and complaint from the thread → JSON.
  2. Transform — classify severity and route to a team, from the JSON only.
  3. Format — render the ticket in the tracker’s template.

Each step is testable on its own; when routing is wrong you debug step 2, not one giant prompt.

Few-shot selection

Examples steer format and style — but which examples matters:

  • Pick examples close to the current input (retrieve them dynamically for variety).
  • Cover edge cases and the exact output format.
  • Too many examples waste context and can overfit to their phrasing.

Optimization

  • Iterate against a small eval set, not vibes (see Evaluation in practice).
  • Change one thing at a time; keep a prompt changelog.
  • Use prompt caching for stable prefixes (instructions, few-shot blocks) to cut cost and latency.

Anti-patterns

  • Cramming many unrelated jobs into one prompt.
  • Vague success criteria (“make it good”).
  • Relying on examples to fix a task the instructions never state clearly.

Sources

  • Wei et al., Chain-of-Thought Prompting Elicits Reasoning in LLMs (2022) — arXiv:2201.11903
  • Wang et al., Self-Consistency Improves Chain of Thought Reasoning (2022) — arXiv:2203.11171
  • Zhou et al., Least-to-Most Prompting (2022) — arXiv:2205.10625

2 - Vector Databases

From storing an embedding to similarity search at scale — the nine core ideas, basic to advanced.

Goal

Understand what happens inside the “vector store” box of every RAG diagram — from what a single record holds, to how a query finds its nearest matches, to how that stays fast across millions of embeddings, and which store to pick.

What’s in a record

An embedding turns text into a vector — a list of numbers that captures meaning. A vector database stores one record per chunk:

FieldExampleUsed for
iddoc42#chunk3reference, updates, dedup
vector[0.021, -0.184, …] (e.g. 384–1536 dims)similarity search
metadata{source, lang, date, plan}filtering + citations
contentthe original textreturned to the model as context

The vector is what you search by; the metadata and content are what you filter and return. Keeping the source in metadata is what lets RAG cite where an answer came from.

How similarity search works

“Similar meaning → nearby vectors” needs a definition of nearby. Three distance metrics do the job:

  • Cosine similarity — the angle between vectors; ignores length. The default for text embeddings, and what most models are trained for.
  • Dot product — like cosine but sensitive to magnitude; used when vectors are normalized (then it equals cosine) or when magnitude carries signal.
  • Euclidean (L2) — straight-line distance; common for image and spatial vectors.

Use the same metric your embedding model was trained with — usually cosine for text.

A query then does Top-K retrieval: embed the query with the same model, score it against stored vectors, return the K closest (K ≈ 3–10 for RAG). K is a dial — too small starves the model of context, too large floods it with weak matches.

flowchart LR
    Q[Query text] --> E[Embed - same model]
    E --> S[Score by cosine similarity]
    S --> K[Take Top-K nearest]
    K --> R[Return content + metadata]

Why it stays fast — ANN

Scoring the query against every stored vector (exact / brute-force search) is fine for 10k vectors, hopeless for 100M at query time. Vector databases trade a little recall for a lot of speed with ANN (approximate nearest neighbor) indexes: they return almost certainly the closest matches, orders of magnitude faster.

flowchart LR
    Q[Query vector] --> IDX[ANN index]
    IDX --> C[Candidate neighbors]
    C --> F[Filter by metadata]
    F --> K[Top-K results]

The three index ideas

IndexIntuitionTrade-off
HNSW — hierarchical graphA highway network: coarse links get you to the right region fast, local links find the exact neighborsBest recall/speed for most workloads; index lives in RAM
IVF — inverted file / partitionsCluster vectors into buckets; search only the few buckets nearest the queryLess memory, fast to build; recall drops if the right bucket is missed
PQ — product quantizationCompress vectors into short codes; compare codes instead of full vectors10–100× memory savings; some precision lost — often combined with IVF

You rarely implement these — but the knobs you will tune (HNSW’s efSearch, IVF’s nprobe) are all the same dial: check more candidates → better recall, more latency.

Metadata filtering

Real queries are rarely pure similarity: “passages like this query — but only from the 2026 handbook, in English, for the Pro plan.” The store filters on the metadata fields during (not after) the search. Filtering after the search silently starves results: the top-K may all fail the filter, leaving you with nothing.

In a RAG pipeline

The vector database is the retrieval half of RAG:

  • Offline — chunk documents, embed each chunk, store id + vector + metadata + content.
  • Online — embed the question, Top-K search (with metadata filters), hand the returned content to the model as grounded context, cite from the metadata.

Retrieval quality caps answer quality — see Advanced RAG for chunking, hybrid search, and re-ranking on top of this.

Choosing a store

SituationReach for
You already run Postgres; ≤ a few million vectorspgvector — one less system, SQL joins with your data
Library inside your own process (batch, research)FAISS — no server at all
Quick prototyping, local-firstChroma
Managed service, zero opsPinecone
Self-hosted at large scale, rich filteringQdrant / Milvus / Weaviate

The honest default: start with pgvector. Move to a dedicated store when scale, latency, or filtering demands it — not before.

Strengths & limitations

  • Strengths — millisecond semantic search at scales exact search can’t touch; metadata filters make retrieval precise; ANN recall is tunable per query.
  • Limitations — approximate: relevant items can be missed, and you must measure recall (see Evaluation in practice); indexes cost RAM and rebuild time; one more system to run, back up, and keep in sync with the source documents — often the flakiest part of a RAG pipeline.

Sources

3 - Types of RAG

The RAG family — standard, advanced, self-correcting, graph, multimodal, agentic — and which is an architecture, a control loop, or a technique.

Goal

Work out which “RAG” someone means, and pick the right one for your data, your accuracy bar, and your budget. “RAG” has grown into a family, and its members are not all the same kind of thing. This section separates them.

The family

VariantWhat is differentRead more
Standard (naive) RAGFixed pipeline: retrieve top-k, augment, generateRAG
Advanced RAGSame shape, better retrieval: hybrid search, re-ranking, query transformsAdvanced RAG
Self-correcting RAGGrades the retrieval or the answer, and retriesThis section
Graph RAGRetrieves entities and relationships, not isolated chunksThis section
Multimodal RAGRetrieves images, tables, audioThis section
Agentic RAGAn agent decides when and what to retrieve, and iteratesAgentic RAG

Architecture, loop, or technique

This is the distinction that clears up the confusion. The family above mixes three different kinds of thing, and they are three axes, not three bins. Every RAG system has a shape and a flow, so one variant can sit on more than one axis.

AxisWhat it changesMembers
Architecturethe shape: what you retrieve fromStandard, Graph, Multimodal
Control loopthe flow: retrieve once, or grade and retryCRAG, Self-RAG
Techniqueone step inside any of the abovehybrid search, re-ranking, query transforms

Advanced RAG is not a fourth kind. It is the technique row, bundled: a standard architecture with better retrieval steps inside it. See Advanced RAG.

Agentic RAG moves on two axes at once. The agent chooses what to retrieve from, which is shape, and it decides when to stop, which is flow. That is exactly why published lists disagree about where to put it.

So “we use hybrid search” and “we use agentic RAG” are not the same kind of statement. The first names a step, the second names a whole system.

Lists of “six RAG architectures” usually flatten all three axes into one row of six, which is why no two of them agree. Hybrid search is the clearest case: combining dense and keyword retrieval is one step on the technique axis, so it lives inside an architecture. A list that puts it beside Graph RAG is comparing a step to a system.

In this section

The three variants nothing else in the vault owns get their own page:

PageIn one lineReach for it when…
Graph RAGIndex entities and relationships, retrieve a connected subgraphThe answer needs two or three linked facts
Multimodal RAGRetrieve images, tables, and audio, not only proseThe meaning lives in the media
Self-correcting RAGCRAG and Self-RAG grade the work and retryA wrong answer costs more than a slow one

Choosing one

Ratings are relative to standard RAG on the same corpus. They are qualitative on purpose: your numbers depend on your data.

VariantAccuracy gainAdded latencyAdded costComplexityWorth it when
StandardbaselinebaselinebaselinelowPlain text, direct lookups
Advancedmediumsmall, one re-rank passsmalllow to mediumRetrieval is the bottleneck, which it usually is
Self-correctinghigh on accuracy-critical querieshigh, an extra model call and sometimes a second retrievalhighmediumA wrong answer is expensive
Graphhigh on multi-hop and corpus-wide questionsmedium at query timehigh at ingest, a model pass over the whole corpushighThe value is in the relationships
Multimodalhigh when the answer is in the mediasmall at query timemedium at ingest, one call per media itemmediumSources are not prose
Agentichigh on multi-step questionshighest, several loops per questionhighesthighThe question genuinely needs several steps

There is no best architecture. Read the row that matches your failure, not the row with the highest accuracy.

Which one?

flowchart TD
    Start[Need RAG] --> Shape{What shape is your data}
    Shape -->|entities and relationships| Graph[Graph RAG]
    Shape -->|images, tables, audio| MM[Multimodal RAG]
    Shape -->|plain text| R{Is retrieval good enough}
    R -->|yes| Naive[Standard RAG]
    R -->|no| Adv[Advanced RAG - hybrid and rerank]
    Graph --> Cost{Is a wrong answer expensive}
    MM --> Cost
    Naive --> Cost
    Adv --> Cost
    Cost -->|yes| SC[Add a self-correcting loop]
    Cost -->|no| Multi{Needs multi-step reasoning}
    SC --> Multi
    Multi -->|yes| Agentic[Agentic RAG]
    Multi -->|no| Ship[Ship it]

Where to go next

Start simple. Move to advanced when retrieval is the bottleneck, add a loop when a wrong answer is expensive, and go agentic only when the question genuinely needs multi-step reasoning.

Sources

3.1 - Graph RAG

Retrieval over entities and the relationships between them, not isolated chunks.

Retrieve the connections, not just the passages.

What it is

Standard RAG stores documents as isolated chunks. Each chunk is retrieved on its own similarity to the question, and nothing in the index records that chunk 12 and chunk 87 are about the same company. Graph RAG indexes entities and the relationships between them, then retrieves a connected subgraph instead of a ranked list.

flowchart TD
    Q[Question] --> S[Standard RAG index]
    Q --> G[Graph RAG index]
    S --> SC[Chunk 12 - Chunk 87 - Chunk 3]
    SC --> SO[Top-k passages, unconnected]
    G --> N1[Acme Corp]
    N1 -->|supplies| N2[Beta Ltd]
    N2 -->|owned by| N3[Delta Group]
    N3 -->|in litigation with| N1
    N1 --> GO[A connected subgraph]

How it works

Three things happen at ingest time, not at query time:

  1. Extract. A model reads each chunk and pulls out entities and the relations between them.
  2. Resolve. Duplicates are merged, so “Acme”, “Acme Corp.” and “ACME” become one node.
  3. Store. The result is written as a graph of nodes and edges.

At query time the system finds entry-point nodes for the question, then walks the edges to collect connected facts. Microsoft’s GraphRAG adds one more step: it clusters the graph into communities and pre-writes a summary of each, so a broad question can be answered from summaries rather than from raw chunks.

The same structure is used elsewhere in this vault for a different job. See Multi-agent systems for the knowledge graph as shared memory between agents. Here it is a retrieval index. The extract and resolve steps are the same; that page adds the steps an agent team needs on top.

When to use it

  • Multi-hop questions, where the answer needs two or three linked facts.
  • “What connects X and Y” questions, which similarity search cannot express.
  • Corpus-wide questions, such as “what are the recurring themes across all incident reports”, where no single chunk holds the answer.

Do not use it for direct lookups. If the question is “what is our refund window”, a chunk already contains the answer and the graph earns nothing.

Example

Ask a supplier assistant: “Which of our suppliers are owned by a company we are in litigation with?”

Standard RAG retrieves the supplier list and the litigation memo as two separate chunks. The model has no way to join them, so it either guesses or says it cannot tell. Graph RAG walks supplies to owned by to in litigation with and returns the path, so the answer names the supplier and shows why.

The cost

Building the graph means running a model over the whole corpus at ingest, plus an entity resolution pass. Documents that change need re-ingesting. That is far more expensive than embedding chunks, and it is the reason to reach for Graph RAG only when the value really is in the relationships.

Sources

  • Edge et al., From Local to Global: A Graph RAG Approach to Query-Focused Summarization (2024) — arXiv:2404.16130

3.2 - Multimodal RAG

Retrieving images, tables, and audio, not only text.

When the answer is in a diagram, not a paragraph.

What it is

Retrieval where the source material is not prose: wiring diagrams, scanned invoices, chart images, slide decks, call recordings. A text-only index can find the page that mentions the thing, but not the thing itself.

This is about retrieval. For the model’s ability to read images and audio as input, see Multimodality.

Two designs

flowchart TD
    subgraph D1[Design 1 - one shared embedding space]
      A1[Images and text] --> ME[Multimodal embedding model]
      Q1[Text question] --> ME
      ME --> V1[(One vector store)]
    end
    subgraph D2[Design 2 - describe, then index the text]
      A2[Images, tables, audio] --> CAP[Model writes a text description]
      CAP --> TE[Text embedding model]
      TE --> V2[(Text vector store)]
      V2 --> ORIG[Pointer back to the original file]
    end

How it works

Design 1 embeds pictures and words into the same vector space, so a text question retrieves an image directly. This is the CLIP idea. It is elegant, and it needs a multimodal embedding model that handles your domain well.

Design 2 runs a vision model over each image or table at ingest, writes a text description, and indexes that description. Keep a pointer to the original file so the answer can show it.

Design 2 is usually the better starting point. The retrieval stack stays the text stack you already run, the descriptions are searchable and auditable, and a wrong description is something a human can read and fix. Parsing and OCR at ingest belong to the pipeline in Building a RAG system.

When to use it

When the meaning lives in the media. If your images are decorative and every fact is also in the prose, index the prose and stop.

Example

An equipment support assistant. The fix for error code E-14 is printed in a wiring diagram, and the manual text only says “see figure 4”.

A text-only index retrieves the sentence with E-14 in it, and the assistant answers “see figure 4”, which helps nobody. With design 2 the diagram was described at ingest, so the retrieved context includes “figure 4 shows relay K3 between the controller and the pump”. The answer now names the part, and attaches the original image.

The cost

Describing media is one model call per item at ingest, and descriptions can be wrong in ways that are hard to notice. Spot-check the descriptions for your highest-value documents rather than trusting the whole corpus.

Sources

  • Radford et al., Learning Transferable Visual Models From Natural Language Supervision (2021) — arXiv:2103.00020

3.3 - Self-Correcting RAG

CRAG and Self-RAG — loops that grade the retrieval or the answer, and retry when it is not good enough.

Check the retrieval before you trust it.

What it is

Standard RAG retrieves once and answers, whatever came back. A self-correcting design adds a grading step and a way to retry. Two named designs do this, and they grade different things:

  • CRAG grades the retrieved chunks, before generating.
  • Self-RAG grades its own draft answer, after generating, and can skip retrieval entirely when the question does not need it.
flowchart TD
    Q[Question] --> R[Retrieve]
    R --> G{CRAG grades the retrieved chunks}
    G -->|correct| GEN[Generate]
    G -->|ambiguous| REF[Keep the good parts and add a web search]
    G -->|incorrect| NEW[Discard and search elsewhere]
    REF --> GEN
    NEW --> GEN
    GEN --> S{Self-RAG asks is each claim supported}
    S -->|no| R
    S -->|yes| OUT[Answer with citations]

That diagram simplifies both papers in one way each. In CRAG the refine pass also runs on the correct branch, not only on ambiguous. And the Self-RAG retry edge is how agent frameworks commonly implement it; in the paper the model generates from several retrieved passages in parallel, and the reflection tokens pick the best-supported one.

How they differ

CRAGSelf-RAG
What it gradesthe retrieved chunksits own draft answer
Whenbefore generatingafter generating
Who decidesa small retrieval evaluator modelthe generator itself, using reflection tokens it was trained to emit
Fallback when the grade is badrefine the chunks, or search the web insteadretrieve again, or decline to answer
Always retrievesyesno, it first decides whether retrieval is needed
Extra cost per queryone evaluator callone or more extra generation passes

When to use it

When a wrong answer costs more than a slow answer. Regulated advice, medical or legal summaries, and anything a customer will act on without checking.

It is not free, and it is not a substitute for fixing retrieval. If the grader keeps returning “incorrect”, the problem is upstream. Fix chunking and hybrid search first, in Advanced RAG, and add the loop on top of retrieval that already works.

Example

An internal policy assistant is asked: “Can a contractor expense a business-class flight?”

Retrieval returns the travel policy, which is written for employees, and nothing about contractors. Standard RAG answers from the employee policy and is confidently wrong.

  • CRAG grades that context as ambiguous. It keeps the general travel section, drops the employee-only clauses, and runs a second search scoped to contractor agreements.
  • Self-RAG drafts the answer first, finds that the claim “contractors may book business class” has no supporting passage, and retrieves again before answering. If the second pass finds nothing, it says the policy does not cover this case.

Both reach the same place. CRAG gets there by doubting the input, Self-RAG by doubting itself.

The cost

Every graded query costs at least one extra model call, and the loop can run more than once. Latency roughly doubles in the bad case. A common compromise is to run the loop only on queries a confidence score already flagged, rather than on all traffic. See the confidence scoring and escalation stage in Building a RAG system.

Sources

  • Asai et al., Self-RAG: Learning to Retrieve, Generate, and Critique through Self-Reflection (2023) — arXiv:2310.11511
  • Yan et al., Corrective Retrieval Augmented Generation (2024) — arXiv:2401.15884

4 - Advanced RAG

Chunking, hybrid retrieval, re-ranking, query transforms, and RAG evaluation.

Builds on RAG in Foundations. Basic RAG often under-performs because of retrieval quality, not the model. These techniques target that.

In the Types of RAG family these are the technique axis: steps you add inside any architecture, not an architecture of their own.

Chunking strategies

How you split documents strongly affects retrieval quality.

StrategyIdeaWhen
Fixed-sizeSplit every N tokens with overlapSimple, uniform text
RecursiveSplit on structure (headings → paragraphs → sentences)Most documents
SemanticSplit where meaning shifts (embedding distance)Dense, mixed-topic text
Document-awareRespect tables, code blocks, sectionsPDFs, technical docs

Keep chunks self-contained; add a small overlap (e.g. 10–20%) so context isn’t cut mid-thought.

Retrieval: dense, sparse, hybrid

  • Dense — embedding similarity; captures meaning and paraphrase.
  • Sparse — keyword match (BM25); captures exact terms, names, codes.
  • Hybrid — combine both, then fuse scores (e.g. Reciprocal Rank Fusion). Usually the strongest default, since each covers the other’s blind spots.

Why hybrid wins, in one query: “error E-4012 when the invoice sync times out.” Dense retrieval finds passages about invoice synchronization timeouts (meaning) but misses the exact code; sparse finds every mention of E-4012 (exact term) but not the paraphrased troubleshooting doc. Fused, the right page ranks first.

Re-ranking

Retrieve a wide set (e.g. top 50), then re-score with a cross-encoder re-ranker that reads query and passage together, and keep the top few. More accurate than embedding similarity alone, at extra cost — so apply it only to the shortlist.

Context compression

Retrieved chunks carry a lot of text that doesn’t answer the question — it wastes tokens and dilutes the model’s attention. Context compression trims each chunk to just the relevant part before it reaches the model:

  • Extractive — keep only the sentences that match the query (a small model or filter scores each sentence).
  • Abstractive — summarize the chunk down to its query-relevant facts.

Example: a 1,200-token policy chunk retrieved for “what’s the refund window?” compresses to the two sentences stating the 30-day window — cheaper, and more faithful, because the model isn’t distracted by the surrounding text. Apply it after re-ranking, on the final shortlist; skip it when chunks are already tight.

Query transformation

The user’s question is often not the best search query.

  • Multi-query — generate several rephrasings, retrieve for each, merge.
  • HyDE — generate a hypothetical answer, embed that, and search with it.
  • Decomposition — break a complex question into sub-questions retrieved separately.

Evaluating RAG

Measure retrieval and generation separately:

  • Context precision / recall — did retrieval surface the right passages?
  • Faithfulness — is the answer grounded in those passages?
  • Answer relevance — does it actually address the question?

See Evaluation in practice.

Common failure modes

  • Chunks too large (noise) or too small (lost context).
  • Retrieval misses exact terms → add sparse/hybrid.
  • Right passages retrieved but ranked low → add re-ranking.
  • Answer drifts from context → tighten the prompt and check faithfulness.

Sources

  • Gao et al., Precise Zero-Shot Dense Retrieval without Relevance Labels (HyDE) (2022) — arXiv:2212.10496
  • Jiang et al., LLMLingua: Compressing Prompts for Accelerated Inference (2023) — arXiv:2310.06839
  • Reimers & Gurevych, Sentence-BERT (2019, cross-encoders for re-ranking) — arXiv:1908.10084
  • Es et al., RAGAS: Automated Evaluation of Retrieval Augmented Generation (2023) — arXiv:2309.15217
  • Lewis et al., Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (2020) — arXiv:2005.11401

5 - Agent Patterns

The ReAct loop, tool design, memory, multi-agent, and reflection.

Builds on Agents in Foundations. Patterns for making agents reliable rather than just capable.

The ReAct loop

Most agents run a Reason → Act → Observe loop: the model reasons about the next step, calls a tool (act), reads the result (observe), and repeats until done. Explicit reasoning between actions improves tool choice and makes traces debuggable.

Tool design

Tools are the agent’s API to the world — design them like a good API.

  • Few, well-named tools beat many overlapping ones.
  • Clear descriptions and typed parameters; the model picks tools from these.
  • Return concise, structured results; trim noise before it re-enters context.
  • Make tools idempotent where possible, and validate inputs (see Guardrails).

Planning

  • Decomposition — break a goal into ordered sub-tasks before acting.
  • Plan-and-execute — plan once, then execute steps (cheaper, more predictable) vs. re-planning every step (more adaptive).

Memory

  • Short-term — the working context for the current task (recent steps, scratchpad).
  • Long-term — facts persisted across sessions, usually retrieved via RAG.
  • Summarize or evict old steps so context stays within the window.

Multi-agent

Split work across specialized agents when one context can’t hold it all:

  • Orchestrator–worker — a coordinator delegates sub-tasks to focused workers.
  • Review/critique — one agent produces, another checks.

More agents means more coordination cost — use it only when a single agent genuinely struggles. See Multi-agent systems for topologies and shared knowledge-graph memory.

Reflection

Have the agent evaluate its own output against the goal and retry if it falls short. Cheap and effective for tasks with a checkable result (tests pass, schema valid, sources cited).

Concretely, a coding agent with reflection: write the patch → run the tests → two fail → read the failures, revise → re-run → green → done. The check (the test suite) is what makes reflection work; without a checkable result, the agent just grades its own homework.

Common failure modes

  • Loops — repeating the same action; add step limits and loop detection.
  • Hallucinated tools/args — constrain with schemas and validate calls.
  • Context bloat — summarize; don’t append everything forever.
  • No stopping condition — define explicit success criteria.

Sources

6 - Agent Memory

The seven types of memory an agent can have — and when each one earns its place.

Goal

Know the kinds of memory an agent can have, what each one is, and — most importantly — when each one earns its place. Memory is the most over-engineered part of agent design: every type you add is state to store, retrieve, secure, and keep fresh. Each type has its own page; this is the map.

Start from one fact

The model itself remembers nothing between calls — its only “memory” is whatever the harness puts in the context window this turn. Working memory is that window; the other six types are strategies for persisting things outside the model and loading them back in when relevant.

flowchart LR
    subgraph Persisted[Persisted outside the model]
      SM[Semantic - facts]
      EM[Episodic - past events]
      PM[Procedural - how-to]
      XM[External - documents]
      PR[Prospective - to-do later]
    end
    Persisted -->|retrieve when relevant| W[Working memory - the context window]
    Param[Parametric - baked in weights] --> LLM[Model call]
    W --> LLM

The seven types

TypeIn one lineAdd it when…
WorkingThe active context windowAlways — the baseline
SemanticDurable facts and preferencesUsers repeat themselves across sessions
EpisodicPast events and outcomesThe agent repeats old mistakes
ProceduralHow to do tasksIt re-derives the same procedure every run
ExternalDocuments in a vector DB (RAG)Knowledge is large and changes often
ParametricKnowledge baked into the weightsNever at runtime — it’s always there
ProspectiveThings to do laterLong-horizon jobs that resume after interruption

Symptom → memory

Work backwards from failure, not forwards from the taxonomy:

SymptomWhat’s missing
Forgets instructions mid-taskWorking memory management (trim/summarize), not more storage
Asks the user the same thing every sessionSemantic
Repeats a mistake it made last weekEpisodic
Solves a routine task differently (and worse) each timeProcedural
Doesn’t know your documentsExternal (RAG)
Knowledge is outdatedParametric limit — RAG or fine-tune, no runtime fix
Loses the thread of a long, interrupted jobProspective

Example — a support agent’s memory stack

Turn 1 of a session: the harness loads the ticket thread (working), the customer’s plan and language (semantic), a note that this customer’s last issue was mis-escalated (episodic), the refund runbook (procedural), and retrieves the relevant policy passages (external). Five types, one context window — each loaded because a past failure demanded it, not because the diagram had a box for it.

Strengths & limitations

  • Strengths — continuity across sessions is what separates an assistant from a stateless chatbot; episodic + procedural memory is how agents get better instead of starting from zero each run.
  • Limitations — stored memories go stale and confidently wrong (a moved customer, a changed policy); retrieval can surface the wrong memory, which poisons the turn; personal facts raise privacy and retention duties (see Responsible AI); every store is infrastructure to run and sync.

Start with working memory only. Add one type at a time, when a real symptom appears — never all seven because a diagram showed seven.

Sources

6.1 - Working Memory

The active context window — everything the model can see right now.

The active context window.

What it is

Everything the model can “see” this turn: the current messages, the system prompt, tool outputs, and reasoning steps. It’s the agent’s scratchpad — and the only memory the model truly has, since the model is stateless between calls.

flowchart LR
    C[Client - web or app] --> W[Working memory - context window: messages, system prompt, tool outputs]
    W --> LLM[Model]
    W <--> CP[Checkpointer - thread id]

When you need it

Always — it’s the baseline every agent runs on, managed by the harness. A checkpointer keyed by a thread id lets a conversation pause and resume.

Where it lives

In the context window itself — nothing is persisted elsewhere. The engineering is context management: as it fills, you trim or summarize old turns, or the run breaks.

Example

Ask “what did I just say?” and the agent answers by looking back in the window — no store, no retrieval, just what’s in context right now.

6.2 - Semantic Memory

Durable facts, preferences, and profiles — knowledge that lasts across sessions.

Knowledge that lasts.

What it is

A persistent store of facts, preferences, and profiles about users or topics — the things that should survive across sessions and be applied consistently.

flowchart LR
    A[Agent] --> S[Semantic memory - facts, preferences, profiles]
    S <--> DB[(Vector DB / profile store)]
    S --> U[Personalized, consistent answers]

When you need it

Users repeat themselves across sessions, or answers must be personalized and consistent — without the user re-stating the same context every time.

Where it lives

A vector DB or a structured profile store, written when a durable fact appears and retrieved when relevant to the current turn.

Example

The agent stores “user prefers metric units” once and applies it in every future session — the user never has to say it again.

  • Vector databases — where durable facts are stored and searched.
  • Distinct from external memory: semantic is learned about the user, external is your documents.

6.3 - Episodic Memory

A record of past events and outcomes — experiences that teach.

Experiences that teach.

What it is

A record of past events: full conversations, task outcomes, successes and failures, with timestamps. It’s how an agent learns from its own history instead of restarting from zero.

flowchart LR
    E[Conversations, task runs, events] --> EM[Episodic memory - outcomes, successes, failures]
    EM <--> LOG[(Event log DB)]
    EM --> R[Recall past - learn - avoid repeats]

When you need it

The agent repeats mistakes it already made, or you need an audit trail of what happened and why.

Where it lives

An event/log store, retrieved by similarity to the current situation.

Example

Reflexion: the agent writes a self-reflection after each failed attempt, stores it, and reuses it next time — reaching 91% on a coding benchmark versus GPT-4’s 80%. Episodic memory is how an agent gets better run over run.

Sources

  • Shinn et al., Reflexion: Language Agents with Verbal Reinforcement Learning (2023) — arXiv:2303.11366

6.4 - Procedural Memory

Knowledge of how to do things — skills, workflows, and rules.

Knowledge of how to do things.

What it is

Knowledge of how tasks get done: skills, workflows, tool-use patterns, and behavioral rules. Tools give an agent capabilities; procedural memory gives it procedures.

flowchart LR
    T[Task or goal] --> P[Procedural memory - skills, workflows, rules]
    P <--> SK[(Skills / procedures store)]
    P --> X[Apply a known procedure]

When you need it

The agent re-derives the same procedure on every run instead of reusing a known-good one.

Where it lives

Skills, tool schemas, prompt templates, and scripts — a library the agent draws on.

Example

Voyager (a Minecraft agent) builds a library of executable skills and, for new tasks, reuses and composes existing ones instead of solving from scratch.

Sources

  • Wang et al., Voyager: An Open-Ended Embodied Agent with Large Language Models (2023) — arXiv:2305.16291

6.5 - External Memory

Outside knowledge in a vector DB, fetched at inference — this is RAG.

Bring outside knowledge in.

What it is

Knowledge kept outside the model in a vector DB and fetched at inference by similarity search. This is RAG, seen through the lens of memory.

flowchart LR
    Q[Question] --> Emb[Embed query] --> Sim[Similarity search]
    Sim --> DB[(Vector DB - embeddings, metadata, sources)]
    DB --> TopK[Top-K chunks] --> Ctx[Inject into context] --> LLM[Model answers]

When you need it

The knowledge is too large to keep in the context window and changes often — so you look it up on demand instead of baking it in.

Where it lives

A vector database, holding embeddings, metadata, and source references for citations.

Example

A support agent embeds your docs, stores them, and retrieves the most relevant chunks when a user asks — grounding the answer and citing the source.

6.6 - Parametric Memory

Knowledge baked into the model’s weights — instant, but frozen at the training cutoff.

Knowledge baked into the weights.

What it is

Knowledge learned during training and stored directly in the model’s weights: language, reasoning patterns, world knowledge, facts. No retrieval — it’s just there.

flowchart LR
    Q[Question] --> LLM[LLM - parametric memory in weights: language, world knowledge, facts]
    LLM --> A[Answer - instant, no retrieval]

When you need it

You don’t add it at runtime — it’s always present, the fastest and cheapest memory. The design question is what to rely on it for versus fetch externally.

The trade-off

Instant and free at inference, but frozen at the training cutoff and hard to update or audit. Fill gaps with external memory (fresh, citable) or fine-tuning (new behavior) — never at runtime.

Example

The model knows what a REST API is without being told, but won’t know a library released last month. The first is parametric; the second needs external memory.

6.7 - Prospective Memory

Things the agent plans to do next — remembered across interruptions.

Remember what you plan to do next.

What it is

Future intentions and scheduled goals the agent has committed to but not yet executed: pending tasks, goal stacks, reminders. It’s how a long-horizon agent survives interruptions.

flowchart LR
    A[Agent - interrupted mid-task] --> Store[Prospective store - pending tasks, goals, reminders]
    Store --> Trig{Trigger - time or event}
    Trig --> Resume[Reload intent and continue]

When you need it

Long-horizon agents that must act on future events — not just respond to the current turn — and jobs that span interruptions or restarts.

Where it lives

A task queue, goal stack, or reminder log, fired by a time / event / agent trigger.

Example

An agent finishes step 2 of 5, gets interrupted, and logs “resume at step 3 with these inputs.” When it restarts it reads the intent and continues exactly where it left off, instead of losing the thread.

7 - Multi-Agent Systems

When to split work across many agents — and how a shared knowledge graph gives the team a memory.

Goal

Understand when several agents beat one, how they coordinate, and the hard problem that shows up the moment they run for a long time: agents have no long-term memory. The answer this page builds toward is a shared knowledge graph — a memory the whole team reads and writes.

Single vs. multi-agent

Start from the vault’s default: the fewest moving parts that solve the task. A single agent with good tools handles most work, and it’s cheaper and easier to debug. Reach for multiple agents only when:

  • The task splits into independent sub-tasks that can run in parallel (research five topics at once).
  • It needs distinct roles that shouldn’t share one context (a maker and an independent checker, or a planner and specialized workers).
  • One agent’s context window can’t hold the whole job.

Multi-agent is not free: every agent is more model calls, more coordination, and more ways to fail. Most “we need multi-agent” problems are really one agent that needs better tools.

Topologies

flowchart TB
    subgraph Supervisor[Supervisor / worker]
      L[Lead agent] --> W1[Worker] & W2[Worker] & W3[Worker]
      W1 & W2 & W3 --> L
    end
    subgraph Pipeline[Sequential pipeline]
      A[Agent A] --> B[Agent B] --> C[Agent C]
    end
    subgraph Checker[Maker / checker]
      M[Maker] --> Ck[Checker]
      Ck -->|feedback| M
    end
  • Supervisor / worker — a lead agent decomposes the goal, delegates to workers, and synthesizes their results. Anthropic’s research system uses this: a lead researcher plans and spawns subagents for each part. Best when sub-tasks parallelize.
  • Sequential pipeline — each agent transforms and passes to the next (extract → analyze → write). Best when stages are ordered and distinct.
  • Maker / checker — one agent produces, another independently verifies. The loop-engineering validator pattern, split across two agents so the checker isn’t grading its own work.

The hard problem — a team with no memory

An agent has no long-term memory: everything it knows lives in the context window. When a conversation ends or overflows the window, that “memory” is gone. For a single agent you manage this with the memory types (semantic, episodic, …). But with many agents running for hours or days, each one is a new employee every session — and they can’t share what they learned. Passing full transcripts between agents doesn’t scale and loses provenance.

Knowledge graph as shared memory

The fix: instead of each agent remembering privately, all agents read and write one shared knowledge graph — nodes are entities, edges are relationships, and every fact carries its source. Knowledge becomes persistent, traceable, and reusable across agents and sessions. Anthropic’s pipeline for building and using it has five stages:

flowchart LR
    Ex[Extract - entities and relations from docs] --> Re[Resolve - merge aliases of the same thing]
    Re --> As[Assemble - one connected graph with provenance]
    As --> Q[Query - pull the subgraph an agent needs]
    Q --> Rp[Repeat - update the graph after each pass]
    Rp -.-> Ex
  • Extract — pull entities and subject–predicate–object triples from each document (a cheap model, one call per doc, guided by a schema).
  • Resolve — merge different names for the same thing (“Edwin Aldrin” → “Buzz Aldrin”) using meaning, not string overlap — a stronger model reasons over descriptions.
  • Assemble — build canonical nodes and typed edges into one connected graph, with provenance on every triple (which document it came from).
  • Query — pull just the subgraph an agent needs to reason, so every answer can cite a specific edge.
  • Repeat — write new facts back after each pass, so the graph grows instead of resetting.

With this shared memory, workers write findings to the graph, a checker fact-checks against it, and a long-running job can resume overnight instead of starting over. The team stops being a set of strangers and starts working on the company’s shared knowledge.

Two different “graphs” — don’t conflate them

The word graph is overloaded here:

  • Knowledge graph (this page) — a data structure: nodes = entities, edges = relations. It’s shared memory.
  • Execution graph (graph engineering) — a control-flow structure: nodes = agents/steps, edges = what runs next. It’s the wiring.

A multi-agent system often uses both: an execution graph routes the work, a knowledge graph remembers it.

Strengths & limitations

  • Strengths — parallelism and specialized roles tackle work one agent can’t; a shared knowledge graph gives durable, citable memory across agents and sessions, and makes fact-checking and resumption possible.
  • Limitations — coordination multiplies cost, latency, and failure modes; a knowledge graph is a real pipeline to build and maintain (extraction and entity resolution are imperfect and can poison the graph) — heavier than a vector DB, so use it when relationships and provenance matter, not for plain lookup. Start with one agent; add agents, then shared graph memory, only when a real symptom demands it.

Sources

8 - Self-Improving Agents

How an agent gets better over time without changing the model’s weights.

Goal

Understand how an agent can improve run over run without any retraining — no weight changes, no fine-tuning. The model stays frozen; what changes is what surrounds it. This matters because retraining is slow and expensive, but a well-designed agent can still learn from its own experience at runtime.

Two ways to “learn”

Weight-changingWeight-frozen (this page)
MechanismFine-tuning / RL — update the modelMemory, reflection, and skills around a fixed model
SpeedSlow, offline, needs data + computeInstant, at runtime
What improvesThe model’s raw capabilityHow well the agent applies a fixed capability
CeilingCan raise the model’s skillBounded by the base model — better use, not new ability

Self-improvement here is the second column: the base model’s ability is a ceiling, but most agents perform well below it because they forget, repeat mistakes, and re-derive procedures. Closing that gap is where the gains are.

The three mechanisms

flowchart LR
    T[Attempt a task] --> O[Observe result]
    O --> R[Reflect - what went wrong or right]
    R --> S[Store the lesson - memory or skill]
    S --> T2[Next attempt - starts smarter]
    W[(Model weights - unchanged)] -.-> T
    W -.-> T2
  • Reflection — the agent evaluates its own output against the goal and retries. Within a task this fixes errors; across tasks, stored reflections prevent repeats. Reflexion showed this: an agent that writes a self-reflection after each failure reached 91% on a coding benchmark versus 80% without — same model, better use of it.
  • Episodic memory — remembering past outcomes so a mistake made last week isn’t made again. See episodic memory.
  • Procedural memory / skill-building — packaging a solved task into a reusable skill. Voyager builds a growing library of executable skills and composes them for new tasks, so it genuinely gets more capable over a session — without touching weights. See procedural memory.

Example — an agent that learns to deploy

A deploy agent fails because it forgot to run migrations. It reflects (“migrations must run before restart”), stores that as an episodic lesson, and later packages the full deploy sequence as a procedural skill. Next week, faced with a new service, it recalls the lesson and reuses the skill — succeeding first try. The model never changed; the system around it learned.

Learning from traces

The three mechanisms work inside one task. Improving the agent across many tasks needs a different input, because it needs a different source of truth. In ordinary software the truth about behaviour is the code. In an agent it isn’t — the same code produces a different run every time, so what actually happened only exists in the trace: the context it was given, the tools it called, the results that came back, and the verdict on the output.

A second agent, running after the fact over a batch of traces, reads them for a failure that repeats:

  • a tool called with the wrong arguments, run after run;
  • a tool never called at all, because nothing in the context told the agent it existed;
  • a preference the user stated once and the agent keeps ignoring.

It then proposes the fix, and the fix lands in one of two places:

  • Procedural — the prompt, tool descriptions, and skills: how the work gets done.
  • Semantic — stored facts and preferences: an assistant that learns to write formally to your manager and casually to your team.

The semantic half only works if corrections have a write path. When a user blocks an over-casual draft to their manager, that correction has to be consolidated into a durable preference, not just applied to the one message — otherwise the same mistake comes back next week. See semantic memory for where it is stored.

What to change first

When the analysis finds a repeating failure, resist rewriting the architecture. Most agent failures are not the model wasn’t smart enough; they are the model didn’t have the right information. Work down this list, and stop as soon as the failure stops:

  1. Memory and skills — it lacked a fact or a procedure it should have had.
  2. Prompts and tool descriptions — it had what it needed and used it wrong.
  3. Tools — it needed a capability nothing gave it.
  4. Architecture — only when the agent keeps failing something that is not allowed to fail, such as a compliance step. Then take the decision away from the model and make it a deterministic step in code.

Each rung costs more to change and more to live with. The top two cover most of it.

None of this merges safely without evals. A new prompt or a newly stored preference can fix one case and quietly break five others, so every proposed change runs against an eval set first. Until that set is trustworthy, a human approves the merge — the level 4 placement in the four levels of loops.

Where it fits

Self-improvement is the payoff of the memory types working together, applied in a loop. In a multi-agent system a shared knowledge graph makes the learning collective — one agent’s lesson helps the whole team.

Strengths & limitations

  • Strengths — improvement without the cost and latency of retraining; the agent adapts to your environment and mistakes; gains compound as memory and skills accumulate.
  • Limitations — bounded by the base model — it can’t learn a skill the model fundamentally lacks (that needs fine-tuning); stored lessons go stale or wrong and can entrench a bad habit as easily as a good one; more memory/skills means more retrieval noise. Verify what gets stored, and prune it — a self-improving loop with no quality gate self-degrades.

Sources

  • Shinn et al., Reflexion: Language Agents with Verbal Reinforcement Learning (2023) — arXiv:2303.11366
  • Wang et al., Voyager: An Open-Ended Embodied Agent with Large Language Models (2023) — arXiv:2305.16291
  • Huang et al., Large Language Models Can Self-Improve (2022) — arXiv:2210.11610
  • Runkle, The Art of Loop Engineering (2026) — langchain.com

9 - Computer Use & Real-Time Interaction

Agents that act in the world — controlling a screen, speaking, and responding in real time.

Goal

Most of this vault is about agents that read and write text. This page is about agents that act in the world: control a computer’s screen, hold a voice conversation, or drive a device. The model is the same; what changes is the interface between it and reality.

Computer use — the loop

Computer use lets an agent operate a GUI the way a person does: it’s given a screenshot, decides an action (click here, type this, scroll), the harness executes it on the real screen, and the agent sees the next screenshot. It’s the agent loop, but the tool is a mouse and keyboard.

flowchart LR
    S[Screenshot of screen] --> M[Model - reason about what to do]
    M --> A[Action - click x,y / type / scroll]
    A --> Ex[Harness executes on the real UI]
    Ex --> S
    M --> D[Done - task complete]

Example: “book the cheapest flight to Hanoi next Friday.” The agent screenshots the browser, clicks the search box, types the route, reads the results, picks the cheapest, and fills the form — each step chosen from what it just saw. It works with any software, including apps with no API, because it uses the same interface a human does.

Real-time and embodied variants

  • Voice / real-time — the same reasoning, but latency is the constraint. Speech-to-text in, the model reasons, text-to-speech out — fast enough to feel like conversation. Used for phone agents and live assistants.
  • Robotics / embodiment — the “screen” becomes sensors and the “click” becomes a motor command. Far harder (the physical world is unforgiving), but the loop is the same: perceive → reason → act → perceive.

How this differs from multimodality

Multimodality is about input — the model can see an image or hear audio. Computer use is about action — the model does something in a live environment and reacts to the consequence. Multimodality is a prerequisite (the agent must see the screen to act on it), but acting in a loop is the new part.

Strengths & limitations

  • Strengths — works with software that has no API (legacy apps, any website); automates end-to-end human workflows; the same skill generalizes across tools.
  • Limitations — slow and brittle (a moved button breaks it; each step is a full model call on an image); and the biggest one — it can take real, hard-to-undo actions, so it’s a serious security and oversight surface. Sandbox it, gate irreversible actions behind approval, and never point it at a system where a wrong click is catastrophic.

Sources

10 - Adaptation: Fine-tuning vs RAG vs Prompting

How to choose between prompting, RAG, and fine-tuning — and how to combine them.

Three ways to adapt a foundation model to your task, from cheapest to most involved.

The three levers

LeverChangesBest for
PromptingThe input onlyBehavior, format, simple tasks
RAGThe input + external knowledgeFresh, private, or citable facts
Fine-tuningThe model’s weightsConsistent style/format, narrow skills

When to use which

  • Prompting — start here. Fast, no infrastructure. Enough for most format and behavior needs.
  • RAG — when the model needs knowledge it doesn’t have: changing data, private documents, or answers that must cite sources. See Advanced RAG.
  • Fine-tuning — when you need a consistent behavior prompting can’t reliably produce (a fixed style, tone, or output schema), or to teach a narrow skill. It does not reliably add fresh factual knowledge — use RAG for that.

Fine-tuning, briefly

  • Full fine-tuning updates all weights — expensive, rarely needed.
  • PEFT / LoRA trains small adapter layers instead — far cheaper, and adapters are easy to store and swap. The usual default when you do fine-tune.
  • Needs a curated, labeled dataset; quality and coverage matter more than size.

Cost and data trade-offs

  • Prompting: near-zero setup; cost is per-request tokens.
  • RAG: needs an ingestion + vector store pipeline; update data without retraining.
  • Fine-tuning: upfront training cost and a dataset; must retrain to change behavior.

Combining them

These aren’t exclusive. A common production stack is fine-tune for form + RAG for knowledge: fine-tune so the model reliably answers in your voice and schema, and use RAG to feed it current, grounded facts at query time.

Example: a support bot fine-tuned (LoRA) on a few thousand of your best agent replies — so it always sounds like your team and always emits the ticket schema — while RAG pulls the customer’s plan and this week’s known issues. Swap either part alone and it breaks: prompt-only tone drifts; fine-tuned knowledge goes stale.

Sources

  • Hu et al., LoRA: Low-Rank Adaptation of Large Language Models (2021) — arXiv:2106.09685
  • Lewis et al., Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (2020) — arXiv:2005.11401

11 - Evaluation in Practice

Eval sets, LLM-as-judge, offline vs online, and regression testing.

Builds on Model Evaluation in Foundations. Metrics only help if you evaluate systematically. This is how to actually run evaluation.

Build an eval set

  • Collect real inputs (or realistic ones) with known-good outputs or acceptance criteria.
  • Cover the common cases and the edge cases — the ones that break in production.
  • Start small (20–50 examples) and grow it as you find failures; every bug becomes a case.
  • Version it; treat it like test data.
  • Mine your traces for cases. Real runs are the cheapest source of realistic inputs, and the ones that already went wrong are the ones worth keeping.

Keep two kinds of case, and don’t mix their purpose:

  • Unit-style — narrow, cheap, and expected to pass. These guard against regressions; a failure here means something broke.
  • Integration-style — end-to-end and genuinely hard. These are the score you are trying to climb; a failure here is the current frontier, not a bug.

When there is no right answer — common for open-ended or research tasks — you can’t collect known-good outputs, so build the rubric instead. Have a person label a small batch of real outputs as good or bad and say why; those reasons become the rubric a judge applies to everything after. The human labels also stay the yardstick you calibrate the judge against.

LLM-as-judge

For open-ended outputs where exact-match doesn’t work, use a strong model to grade responses against a rubric.

  • Give the judge explicit criteria and a scale; ask for a reason, then a score.
  • Prefer pairwise comparisons (A vs B) — more reliable than absolute scores.
  • Validate the judge against some human labels; watch for bias (length, position, self-preference).

A minimal rubric, to make it concrete:

Grade the answer 1–5 for faithfulness: 5 = every claim is supported by the provided context; 3 = minor unsupported details; 1 = contradicts the context. First quote the unsupported claims, then give the score.

Offline vs online

  • Offline — run the eval set in CI before shipping a change. Fast feedback, controlled.
  • Online — measure real usage: user feedback, thumbs up/down, task success, escalations.
  • Offline catches regressions; online catches what your eval set missed. You need both.

RAG evaluation

Evaluate retrieval and generation separately — context precision and recall for retrieval, faithfulness and answer relevance for generation. That split is what tells you whether a bad answer came from retrieval or from generation, and it is the whole reason RAG needs its own method. The metrics, the golden set, and RAGAS in full: RAG evaluation.

Regression testing

  • Run the eval set in CI on every prompt, model, or pipeline change.
  • A stored memory or skill is a change too. An agent that rewrites its own prompts and memory edits its behaviour without touching the code, so it needs the same gate — that gate is what makes self-improvement safe to merge.
  • Fail the build on a drop past a threshold.
  • Pin the model version; a provider update is itself a change to evaluate.

Pitfalls

  • Testing on examples you tuned against (leakage).
  • One aggregate score hiding failures on a key slice — break results down by category.
  • Trusting a judge you never validated.

Sources

12 - RAG Evaluation

Measuring a RAG pipeline by splitting retrieval from generation — the four RAGAS metrics and how to build the golden set.

Why “the answer was wrong” is never a useful bug report for a RAG system.

Goal

Find out which half of a RAG pipeline is failing. A single end-to-end score tells you the system is bad; it never tells you whether to fix chunking, the retriever, or the prompt. This page is the RAG-specific companion to Evaluation in practice.

Split the pipeline first

RAG has two independently breakable halves, and they fail in ways that look identical from the outside:

flowchart LR
    Q[Question] --> R[Retrieve chunks]
    R --> G[Generate answer]
    G --> A[Answer]
    R -.measured by.-> M1[Context precision and recall]
    G -.measured by.-> M2[Faithfulness and answer relevance]
The failureWhat it looks likeWhere to fix it
The right chunk was never retrievedConfident, fluent, wrongChunking, embeddings, hybrid search, re-ranking
The right chunk was retrieved and ignoredAnswer contradicts a source it was givenPrompt, context ordering, model choice
The right chunk was retrieved and buriedAnswer is vague or partialTop-K, re-ranking, context length

Measure retrieval before you touch generation. Retrieval quality caps answer quality — no prompt fixes a context that never contained the answer, and most teams spend weeks on prompts for what was a chunking bug.

The four metrics

These are the RAGAS metrics, and each one deliberately looks at a different triple of question, context, and answer:

MetricQuestion it asksInputsFix when it is low
Context recallDid we retrieve everything needed to answer?question, context, ground truthChunk size, embedding model, top-K, hybrid search
Context precisionAre the retrieved chunks actually relevant, and ranked well?question, contextRe-ranking, metadata filters, lower top-K
FaithfulnessIs every claim in the answer supported by the context?context, answerPrompt, model, context ordering
Answer relevanceDoes the answer actually address the question?question, answerPrompt, query understanding

Two pairs, and the pairs behave differently. Recall and precision trade off: raising top-K lifts recall and drops precision, and the sweet spot is workload-specific. Faithfulness and answer relevance are nearly independent: an answer can be perfectly grounded and useless (“the document does not specify”), or fluent, on-topic, and entirely invented.

Faithfulness is the one to watch. It is the direct measurement of hallucination in a grounded system, and it is the metric a casual eye-test misses most often, because an ungrounded claim reads exactly like a grounded one.

Building the golden set

The metrics are worthless without data that reflects your corpus.

  • Start from real queries. Pull them from logs. Invented questions are cleaner, easier, and systematically unlike what users actually ask.
  • Annotate the source, not just the answer. For each question record which chunk or document should be retrieved. This is what makes context recall computable, and it is the annotation teams skip and later regret.
  • Cover the shapes, not just the topics. Include multi-hop questions, questions whose answer is not in the corpus (the correct answer is “I don’t know” — and a system that invents one here is the most dangerous failure), near-duplicate documents, and questions answerable only from a table or image.
  • Synthetic generation is a starting point. Having a model generate question–answer pairs from your documents bootstraps coverage quickly, but it inherits a bias toward questions that are easy to answer from a single chunk. Review a sample by hand.
  • 100–200 well-chosen examples beat 10,000 generated ones. The set has to be small enough that someone actually reads the failures.

RAGAS vs a plain LLM judge

RAGAS is a library of these reference metrics, mostly implemented as LLM-as-judge prompts with a defined decomposition — faithfulness, for example, splits the answer into atomic claims and checks each against the context, rather than asking “is this grounded?” in one shot.

Use RAGASUse your own judge
WhyStandard, comparable, no prompt design neededYour rubric, your domain, your definition of correct
Best forGetting a baseline in an afternoon; tracking the four standard axesDomain criteria RAGAS has no metric for — citation format, regulatory tone, required disclaimers

They are not exclusive, and the usual answer is both: RAGAS for the four standard axes, a custom judge for what your product specifically demands.

Either way, validate the judge before you trust it. Hand-label 30–50 examples, check the judge agrees, and only then start making decisions from its scores. An unvalidated judge produces a number that moves — which is worse than no number, because it looks like evidence.

Wire it into CI

The metrics only pay off as a gate. Run the golden set on every change to chunking, the embedding model, top-K, the retriever, the prompt, or the model version — and pin the model version, because a provider update is itself a change to evaluate. Fail the build when faithfulness or context recall drops past a threshold, and break the report down by question category so one aggregate score cannot hide a collapse on a slice that matters.

Strengths & limitations

  • Strengths — localises a failure to retrieval or generation in one run; faithfulness gives a concrete, trackable hallucination number; most of it needs no human-written ground truth, so it runs cheaply in CI on every change.
  • Limitations — LLM-judge metrics are noisy and drift when the judge model changes, so pin it; context recall needs annotated ground truth, which is the expensive part; the scores are relative, not absolute, and chasing 1.0 is a waste; and none of these metrics capture latency, cost, or tone, which users notice just as fast as correctness.

Where to go next

Sources