PRACTITIONERCHAPTER 08

Shipping a retrieval or agent feature

The job around the technique: which shape of system the questions need, who owns the documents, how retrieval and answers are measured apart, what the tools may do, and the one design doc that lets a reviewer say yes

40 MINAI ENGINEERUPDATED 2026-11-21
PREDICT

In the pilot, a teller asking about a fee-waiver limit is given the figure from a circular that was withdrawn in August. Both the old circular and its replacement are in the index. What is the most likely cause, and so the first fix?

A retrieval or agent feature has two jobs, and the second gets less attention. The first is the technique: chunking, search, a rerank, a tool loop. The AI Engineering course teaches it in RAG done properly, agents, tool use, long context against retrieval and hallucination and grounding, and this chapter does not repeat it. The second job is the one a person in the role has to do around the technique: decide the shape, name who owns the documents, set the bar, bound the tools and write it all down so that someone else can say yes or no.

This chapter is about that second job, with Northmere’s branch assistant as the running case. Northmere is a tier-2 bank with 4,800 staff. The circulars are its internal instruction to branches: products, fees, limits, procedures. Branch staff ask questions all day and today they search a shared drive.

The job is a decision, then a document

The shape of a system answering questions over documents is a choice you make once and live with for a year, and it is easy to make it by accident. A prototype built as an agent stays an agent because it works on the demo. A pipeline built from a tutorial stays a pipeline because nobody asked what it cannot do.

The philosophies chapter gives the rule: climb the ladder one rung at a time and move up only when a measurement says the rung below is not enough. For this feature the rungs are a single call with the right passages in it, a fixed pipeline of calls that your code orders, and an agent that decides its own next step. Anthropic’s “Building effective agents” draws the line you will use: a workflow runs along code paths you defined, and an agent directs its own process and tool use. The post presents workflows as the better fit for well-defined tasks and agents for flexible, model-driven decisions. Your task is to find out which one you have.

The decision goes in a design doc, and the doc is the deliverable. It is not ceremony. A design doc for this kind of feature is where three people who will never read your code can still push back: the owner of the documents, the person who will answer for what the assistant says, and whoever pays. How an engineer writes a design doc in general is in writing RFCs and design docs. Here the doc has contents specific to this feature, listed under the Artefact below.

Question types decide the shape

Start from what people ask, not from what you can build. Take a hundred real questions from the pilot, or from the help desk or the shared-drive search log if there is no pilot, and sort them by what answering needs. Northmere’s sample, illustrative, looks like this.

Question type Share of 100 Example What answering needs
Lookup in one circular 58 What is the cash-withdrawal limit on a student account? The right circular found, then read
Which version applies 17 Has the fee-waiver limit changed since the August circular? Two circulars and their dates, with the withdrawn one marked
Needs a live figure 15 What is the rate on a 12-month fixed deposit today? A call to the rates tool; a circular can only be stale
Out of scope 10 Can I take leave on 24 December? A refusal and a pointer elsewhere

Each row asks for something different. The first needs retrieval. The second needs retrieval plus document metadata, and no amount of cleverness in the model fixes a missing date. The third needs no retrieval at all; it needs one tool call that your code can make whenever it recognises the question. The fourth needs the assistant to say it does not know. A design that handles the table is a pipeline with a branch in it. An agent could handle it too, but nothing in the table needs the model to choose its own next step.

Pipeline, agent or long prompt

Three shapes are on the table for a corpus like this, and each wins somewhere.

A fixed pipeline retrieves a few passages, asks the model to answer from them and to cite, and returns. Its cost per answer is bounded by the calls you wrote, its latency is predictable, and each stage can be tested alone. It cannot follow a trail. If the answer needs a second search whose terms depend on the first result, it fails quietly.

An agent given a search tool, a read tool and the rates tool decides for itself what to search, what to open and when to stop. It handles the question that no one planned for. It also costs several model calls per question, because each turn re-sends the growing conversation, and the number of calls varies, so you cannot state a latency or a bill with confidence. The agents chapter covers the loop, its budgets and its stop conditions. Its test of whether you need one is four questions: is the task multi-step and hard to specify, is it valuable enough to pay for more calls, can the model do it, and can its mistakes be caught.

Long context puts the corpus in the prompt and skips retrieval. For a few hundred pages that can be the simplest thing that works, with prompt caching to cut the cost; the long-context chapter has the arithmetic and the evidence that models use the middle of a long prompt less reliably. At Northmere the average circular is about 1,500 tokens (illustrative), so 1,200 of them are about 1.8 million tokens. That is beyond most models’ context windows: a corpus to retrieve from, not to paste.

Put numbers beside the shapes before you argue about them. The prices here are illustrative, not a vendor’s: ₦2,000 per million input tokens, ₦200 per million for a cache read, ₦10,000 per million output tokens.

Shape Calls Input tokens Output tokens Per answer
Fixed pipeline 1 3,800 300 ₦7.60 + ₦3.00 = ₦10.60
Agent, six turns 6 36,000 900 ₦72.00 + ₦9.00 = ₦81.00
All circulars in the prompt, no cache 1 1,800,000 300 ₦3,600 + ₦3
All circulars in the prompt, cached 1 1,800,000 300 ₦360 + ₦3

The agent costs about 7.6 times the pipeline (₦81.00 over ₦10.60) at six turns, and its worst case is whatever your step cap allows. Check the units when you do this sum: input is priced per million tokens, so 3,800 tokens is 0.0038 of a million, which is ₦7.60. The same arithmetic with the unit slipped by a thousand gives a figure that looks harmless and is wrong.

The shape that fits the table is a pipeline with a routed branch: retrieve five circulars with their status and dates, answer and cite; recognise a rate question and call the rates tool from your code. It is not the only defensible shape. An agent is right if the eval shows that real questions need trails the pipeline cannot follow. A long prompt is right for a corpus that fits and a team that will not run an index. Say so in the doc, with the measurement that would change your mind.

The corpus is part of the feature

An index is a copy of documents that other people change. Everything that goes wrong with that copy is your problem, even though the documents are not yours.

Ownership. Maarten’s desk owns the circulars. Your doc names that desk as the owner of the content and you as the owner of the index, and says what happens when they disagree about what is in it. About 40 circulars are published or revised in a month (illustrative); if ingestion takes a week, the assistant is a week behind policy for a quarter of the month.

Supersession. Every circular carries an identifier, a status (current, withdrawn), an effective date and, when it replaces another, the identifier of the one it replaces. Retrieval filters on status; the answer states the effective date. A withdrawn circular is removed from the index or filtered out, and the removal is tested, since a withdrawal is the event most likely to be forgotten.

Entitlements. Some circulars are for treasury, or for team leads only. Document permissions are enforced in the retrieval filter, with the caller’s entitlements, before any text is returned. A line in the prompt asking the model to ignore restricted material is a request, not a control, and the model cannot unsee what it was given. The security view of this, and of what an agent with tools can be talked into, is in AI and agent security.

Structure. The RAG chunking lesson shows the failure that haunts policy documents: the bot quoted the right table and gave the wrong fee, because the chunk cut the table from its heading. Circulars are full of tables of fees and limits. Keep tables whole, index the heading path with each chunk and test the cases that hinge on a figure. The HNSW recall lesson is the companion warning: an approximate index can lose the right document while its latency graph improves, so measure retrieval on your questions after every index change, not only on the embedding model.

Measure retrieval and the answer separately

Retrieval and answers fail for different reasons, so they get different numbers. Recall at k is the share of questions whose source circular appears in the top k. Answer correctness is whether the final answer is right, judged against a written reference. Retrieval sets a ceiling on the answer, and the course chapter explains why the k you measure must be the k you send: if the model sees five passages, recall at five is what counts.

The eval set for this feature is questions with gold circular identifiers and reference answers, sampled in the proportions of the table above, with the out-of-scope questions included on purpose. Building it is the subject of the eval set before the feature chapter, and the course’s building an eval set chapter has the technique. Two points are specific here. The gold labels are Maarten’s desk’s judgement, not yours, so a person from that desk labels them, which is the point made in the map of AI roles. And add three kinds of case the happy path hides: a question whose answer changed because of a supersession, a question whose circular is restricted for the asker, and a question the corpus does not answer.

State a bar for each number before you build. Targets might be recall at five of at least 90% on lookups, at least 90% of answers correct, no answer that presents a withdrawn circular as current, and a correct refusal on every out-of-scope case. These are targets for the pilot to test, not results. Researchers who built RAG systems in three different domains report that a system of this kind can only really be validated in operation and that its robustness grows over time rather than being designed in at the start; read that as a reason for a staged rollout, not for skipping the bar.

If you do give the model tools

Suppose the eval shows the pipeline failing on questions that need a trail, and you choose an agent for those. The agents chapter and the tool-use chapter cover the mechanics. What is yours to decide is the envelope.

  • Read-only first. The three tools here search, read and look up a rate. None of them changes anything. Keep it so until a measurement says a write is worth its risk; a feature that can act has its own abuse cases, and the guardrails, injection and abuse chapter is where that is covered.
  • A step cap and a cost cap. Say how many turns an answer may take, such as eight, and what happens at the cap: the assistant tells the user it could not find an answer. An uncapped loop is a bill you have not read.
  • Descriptions are prompts. Anthropic’s guidance on writing tools for agents recommends fewer, purpose-built tools over many thin ones, precise descriptions written as for a new teammate, and responses of limited size that return what the agent needs. A search tool that returns forty full circulars is a bad tool.
  • Log every step. Query, results, what was opened, the answer. Without that you meet the Why’s problem again: nobody can say why an answer was wrong.
  • The model proposes; your code decides. The rates tool is called with a product code from a list your code holds, not whatever string the model writes.

Not knowing, and citing

A grounded assistant is judged as much by what it declines as by what it answers. Decide, before launch, what it does when retrieval returns nothing relevant: say so, name the desk to ask and log the question, which is also how you find the corpus’s gaps. The hallucination chapter measures how often an abstention instruction holds and shows the citations API, which makes the model point at the passages that support each claim.

Cite the circular identifier and its effective date in every answer. For branch staff a citation is not decoration. It is the thing that lets a teller check, and a manager trust, an answer about a customer’s money. A claim with no citation is treated as unsupported and either removed or flagged.

Cost and rollout

Compare cost per answer with the value of the answer: a teller who finds a limit in ten seconds instead of five minutes (illustrative) saves time worth many times ₦10.60. The budget goes in the doc as a ceiling and a measured figure; the cost, latency and model choice chapter of this track covers choosing the model against it.

Roll out in stages. Pilot with a few branches and read the logs, using the weekly read described in an AI engineer’s week. Add a thumbs-down with a reason and read every one. Gate each change on a paired run of the eval set. Widen only when the pilot meets the bar. A rollback is a switch back to the search page staff already use, so keep that page alive.

Where practitioners disagree

Agent first or pipeline first? Some teams start with a capable model and a search tool because it ships in days and the model handles the unexpected. Others start with a pipeline because it is cheaper, testable and explains its failures. The common compromise is the pipeline with a branch, and a promotion to an agent for the question types that measurement shows the pipeline cannot answer.

Index or search the files? Chunking and embedding a corpus is the standard approach. Some teams now let an agent search documents with keyword tools and read them whole, which skips chunking. It suits small, well-structured corpora and costs more per question; at 1,200 documents with a cost ceiling, an index still earns its keep. Measure both if the corpus is small enough.

Who owns the documents? Engineers want the owner to fix formatting and metadata at source. Owners want engineers to cope with the documents as they are. The usual outcome is a short written standard for new circulars, agreed with the desk, that makes the status and the replaced identifier required fields.

Day to day

A design week for the circulars assistant, with the pilot already running and a design doc due on Friday. The times are an example.

  • Monday. Read 40 pilot conversations at random and every flagged one, a block you keep from the weekly routine. Sort 100 questions into the types. Ask Maarten’s desk for the list of withdrawn circulars and the source of truth for status.
  • Tuesday. Write the eval cases with a person from the desk labelling: gold identifiers and reference answers, including supersession and restricted cases. Run the current pipeline and the agent on the same cases and record both numbers for each.
  • Wednesday. Do the cost table from logged token counts, not estimates. Test the withdrawal path: withdraw a circular in a staging index and check it disappears from answers. Meet security about entitlements in the retrieval filter.
  • Thursday. Draft the design doc and send it to Maarten, the security lead and the product owner before the review, so that the meeting is for disagreement and not for reading.
  • Friday. Review. Record each objection and its owner. Ship only what has passed a paired run of the eval set.
  • Every day. Ten minutes on cost and step counts, since an agent that starts taking more turns shows up there first.

Monthly. Compare the share of questions that end in abstention with the corpus: a rising share means documents are missing. Re-read a hundred conversations. Check ingestion lag against the number of circulars changed.

Quarterly. Replace a fifth of the eval set with fresh questions (a rule of thumb). Re-run the shape decision: prices change, models change and the question mix moves.

When it breaks. If the assistant gives a wrong answer about a limit, switch the affected circular to a banner that sends staff to the source, fix the index, add the case to the set and tell Maarten’s desk what happened. Do not patch the prompt first.

BY ORG SIZE
STARTUPunder 30 people

There may be a few hundred documents, one person who owns both them and the assistant, and no review. Skip the index until you have measured the alternative: a cached long prompt or a plain keyword search over files can be enough, and both are easier to explain. Still write the half-page doc, since you are the only one who will remember why it works this way, and keep thirty real questions with answers that you rerun before every change.

SCALE-UP30 to 300

Documents multiply and each team brings its own. The risk is three pipelines with three chunkers and no shared way to withdraw a document. Agree an owner and a status field for every corpus, one ingestion path and one eval format, and run the design doc review across product, the content owner and security. Resist the urge to give every question to an agent because it handles the odd case; keep the pipeline for the common ones.

ENTERPRISE300 and up

Thousands of documents, many desks and entitlements that differ by role and branch. Permissions, retention and audit decide the design more than retrieval quality does, and a model-risk or legal review will ask for the eval set, the logs and the abstention behaviour in writing. The work is political: getting document owners to supply status and replacement fields, and agreeing who can say the corpus is wrong. Expect to run several indexes behind one front door.

ARTEFACT A design doc for a retrieval or agent feature ~90 MIN
YOU PRODUCEA design doc: questions, corpus, shape with cost, bars, not-knowing behaviour, rollout and how it could be wrong

Template

# Design doc: <feature>, <date>
Owner: <you> · Content owner: <desk> · Reviewers: <security, product, ...>

## 1. The decision needed
<one paragraph: what we are building, for whom, and what you need approved>

## 2. Questions it must answer
| Type | Share of <n> sampled | Example | What answering needs |
|---|---|---|---|

## 3. The corpus
Size: <documents, tokens> · Changes: <per month> · Owner: <desk>
Status and supersession: <fields; how a withdrawn document leaves the index>
Permissions: <who sees what; where it is enforced>

## 4. Shape
| Shape | Calls | Input tokens | Output tokens | Naira per answer | Cannot do |
|---|---|---|---|---|---|
Prices used: <input, cache read, output per million tokens>
Chosen: <shape>, because <reason>. Would change if <measurement>.

## 5. Quality bars
| Measure | Bar | Measured on |
|---|---|---|
Retrieval (recall at k): · Answer correctness: · Withdrawn shown as current: · Correct refusals:

## 6. When it does not know
<what it says, who it points to, what is logged>

## 7. Tools, if any
<tool, read or write, step cap, owner>

## 8. Rollout and watch
<stages, who reads the logs, how a wrong answer becomes an eval case, rollback>

## 9. How this could be wrong
1. <risk> - shown by <measurement>
WORKED EXAMPLE

Northmere Bank is a fictional tier-2 bank with 4,800 staff. Zaynab, an AI engineer, proposes an assistant for branch staff over 1,200 circulars. Figures are illustrative.

1. Decision. Approve a pilot in 12 branches of a pipeline with one routed tool call.

2. Questions (100 sampled from the pilot).

Type Share Answering needs
One-circular lookup 58 Find and read one circular
Which version applies 17 Two circulars, dates, withdrawn marked
Needs a live rate 15 The rates tool
Out of scope 10 A refusal

3. Corpus. 1,200 circulars, about 1,800,000 tokens, about 40 published or revised a month. Maarten’s desk owns the content; Zaynab owns the index. Each circular has an identifier, status, effective date and the identifier it replaces. Withdrawn circulars are removed within one working day, and a staging test withdraws one and checks it vanishes. Permissions are applied in the retrieval filter using the caller’s role.

4. Shape. Pipeline: 3,800 in, 300 out, ₦10.60. Agent at six turns: 36,000 in, 900 out, ₦81.00. Whole corpus in the prompt, cached: ₦360 plus ₦3. Prices: ₦2,000, ₦200 and ₦10,000 per million. Chosen: pipeline, with the rates tool called by code when a classifier flags a rate question. An agent wins if more than 20% of eval questions need a second search that the first result decides; the long prompt wins if the corpus shrinks to a few hundred pages and traffic stays low.

5. Bars. Recall at five at least 90% on lookups; answers at least 90% correct; zero withdrawn circulars shown as current; all 10 out-of-scope cases refused. Measured on the same 100 questions with gold identifiers, plus a superseded, a restricted and an unanswerable case.

6. Not knowing. It says no circular covers the question, names the policy desk and logs the question. Every answer cites identifier and date.

7. Tools. rates only: read-only, called with a product code from a list in code, no loop, owner Zaynab.

8. Rollout. 12 branches, then 40; every step logged, weekly read of 40 conversations; each wrong answer is fixed at source and added to the eval set; rollback is the shared-drive search page.

9. Wrong if. Ingestion lags by more than two days (shown by effective-date checks); supersession questions fall under 85% (shown by the eval).

Now you

You are Zaynab, asked to design an assistant for the complaints team in Northmere’s customer care. Staff ask about 85 procedure documents, about 250,000 tokens in total, owned by three desks. About 6 documents are edited each week. One desk’s documents are restricted to team leads. There are about 1,500 questions a day, and the budget ceiling is ₦25 per answer. A sample of six questions: what is the first step on a card reversal complaint; does the transfer reversal procedure differ from the card one; what is the status of ticket 5521 (there is a read-only case_status tool); what documents does a team lead need to see; can I approve a refund above my limit; what is the cafeteria menu. Prices, illustrative: ₦2,000 per million input tokens, ₦200 per million for cache reads, ₦10,000 per million output tokens. A pipeline uses 4,500 input and 400 output tokens; a cached whole-corpus prompt reads all 250,000 tokens and writes 400. The complication: the team lead wants one document to answer everything, and the procedures change weekly. Produce the design doc, with the cost of each shape.

Self-check

DECIDE

Branch staff at Northmere Bank ask an assistant about 1,200 product and policy circulars, about 40 of them revised each month. A sample of 100 pilot questions shows 58 single-circular lookups, 17 about which version applies, 15 that need a current rate from a read-only rates tool and 10 out of scope. A pipeline costs about ₦10.60 an answer and an agent about ₦81. The pilot has run in 12 branches and the head of retail wants a decision on the design this week. Which shape do you take to the review?

READING
  1. POST
    Building effective agents Anthropic, 2024

    Draws the line between workflows that run along code paths you wrote and agents that direct their own tool use, and the same page describes the retrieval-and-tools building block. Read it to justify the shape in your design doc.

  2. POST
    Introducing Contextual Retrieval Anthropic, 2024

    Reports retrieval failure rates falling from 5.7% to 3.7% with contextual embeddings, to 2.9% with contextual keyword search added, and to 1.9% with reranking. Use it to see which retrieval fix to try after metadata and chunking.

  3. POST
    Writing effective tools for agents, with agents Anthropic, 2025

    Advice on fewer purpose-built tools, precise descriptions, bounded responses and evaluating tools on realistic tasks. It is the guide to the tools section of your doc.

  4. PAPER
    Seven Failure Points When Engineering a Retrieval Augmented Generation System Scott Barnett, Stefanus Kurniawan, Srikanth Thudumu, Zach Brannelly and Mohamed Abdelrazek, 2024

    An experience report from three case studies, in research, education and biomedicine. It supports the staged rollout and the habit of reading real failures. Read: The failure points and the two takeaways about validating in operation.

  5. PAPER
    Lost in the Middle: How Language Models Use Long Contexts Nelson F. Liu and colleagues, 2023

    Shows accuracy often highest when the relevant passage is at the start or end of a long input and falling significantly when it sits in the middle, even for models built for long contexts. It is the evidence behind not pasting a large corpus into the prompt. Read: The position experiments in multi-document question answering.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Cost, latency and choosing the model →