Chapter 07 / 12 · AI Engineering

Context and retrieval

Choosing which few passages of the help centre the model reads for each question, measuring that choice, and tracing a wrong answer back to the stage that lost the right passage.

The model chapter ended with a fix: when the assistant answered a withdrawal question from its training data, the team put the right help-centre article into the prompt and told the model to answer from it. That raises the question this chapter is about. The help centre has about 1,200 articles, and the product documentation (order types, margin rules, the charges schedule) adds a few hundred pages more. For each customer question, which few passages should the model read?

Choosing them at request time is called retrieval, and the pattern of retrieving passages, placing them in the prompt and asking the model to answer from them is called retrieval-augmented generation, or RAG. The idea fits in a sentence. Getting it to work means making decisions at every stage: how to cut documents into pieces, how to search them, how many to keep, where to put them, and how to tell, when an answer is wrong, which stage lost the right passage. We will make each decision for the assistant and then follow one wrong answer back to its cause.

Why not send the whole help centre

The first option to rule out is the simplest: include everything. The 1,200 articles average about 900 words, roughly 1,200 tokens each, which is about 1.44 million tokens; the product documentation brings the total to around 1.75 million. Some current models accept contexts of a million tokens or more, so in a few cases this might even fit.

At the illustrative prices from the inference chapter, 1.75 million input tokens cost $1.75 per turn, or about $0.18 if all of it were read from cache. The pilot’s turns with 3,000 tokens of retrieved passages cost about $0.003 for those passages. That is a difference of 60 to 600 times, on every turn of every conversation. Prefill for 1.75 million tokens would also take many seconds before the first word appeared. And more text is not simply more help: the model must find the two relevant paragraphs among thousands, and the next sections show that models use passages less reliably when they are buried in the middle of a long context.

So the assistant retrieves. The target is three to five passages, a few thousand tokens, chosen per question.

Chunking decides what can ever be found

Retrieval works on pieces of documents, called chunks, small enough that several fit in the prompt and focused enough that each is about one thing. The team’s first version cut every article into fixed windows of 500 tokens. That produced about 3,500 chunks and one serious problem.

The article “Withdrawing funds” has three sections: how to place a withdrawal request, a table of cut-off times and when requests placed before or after them are processed, and reasons a withdrawal can fail. The 500-token window happened to end just after the heading “Cut-off times”, so the table landed at the start of the next chunk. That chunk contained times and phrases like “processed the same working day”, and no mention of withdrawals at all. A question like “I requested a withdrawal at 4pm, when will I get it?” had nothing in that chunk to match against. The answer existed in the help centre and could not be retrieved.

The second version splits along the documents’ own structure: one chunk per section, tables kept whole, long sections divided at paragraph boundaries with a small overlap so a sentence that depends on the previous one is not orphaned. Each chunk is prefixed with its location, “Withdrawing funds › Cut-off times”, so even a chunk that is mostly a table carries the words that say what it is about. Each chunk also carries metadata outside its text: the article id, the date it was last updated, and whether the article is current or archived. This produced about 4,400 chunks averaging around 400 tokens. Chunking costs nothing at query time, and it sets the ceiling on everything after it: a passage that was cut badly cannot be rescued by a better search.

Embedding search, and the questions it gets wrong

The deep learning chapter introduced embeddings: vectors placed so that similar meanings sit close together. An embedding model turns each chunk into a vector of, say, 1,024 numbers once, when the help centre is indexed. At query time it turns the customer’s question into a vector the same way, and the search returns the chunks whose vectors have the highest cosine similarity to it. This is what finds “withdrawal still pending” when the article says “funds transfer to your bank is in progress”.

At 4,400 chunks, the search itself is trivial: comparing the query with every chunk is about 4.5 million multiply-adds, which takes around a millisecond on an ordinary CPU. Approximate nearest-neighbour indexes such as HNSW exist for collections of millions or billions of vectors, where comparing against everything is too slow. They trade a little recall for speed. For the assistant, an exact search over every vector is faster to build, easier to reason about, and misses nothing, so the team uses that and will revisit if the corpus grows a hundredfold.

Embedding search fails in a predictable way. It captures the gist of text, which is what we want for paraphrases, and it blurs exact terms, which is what we do not want for names, codes and acronyms. A customer who asks “what is the GTT charge?” wants the article on good-till- triggered orders, but the question’s vector sits near every article about orders and charges, and the right one may not rank first. Keyword search, using a scoring method such as BM25 that rewards documents containing the query’s rarer words, finds “GTT” immediately, and it is poor at paraphrases. The two fail on different questions, which is the argument for running both.

Running both gives two ranked lists that must be merged. Their scores are on different scales, so a common method ignores the scores and uses only the ranks. Reciprocal rank fusion gives each chunk 1 / (60 + rank) from each list and adds them up; 60 is a conventional constant that stops the top ranks from dominating. Suppose chunk A is first in keyword search and eighth in embedding search: it gets 1/61 + 1/68 = 0.0311. Chunk B is third and second: 1/63 + 1/62 = 0.0320. B ranks higher. A chunk that both methods consider reasonably good beats one that only one method loves, which is usually the right bias.

question+ conversationrewritestandalone querykeyword searchbm25 · top 50vector searchembeddings · top 50fuserrf · ~80 uniquererankcross-encoder · keep 5log the ids at every stage: when an answer is wrong, find the stage where the right passage fell out
The question is rewritten to stand alone, searched two ways, fused and reranked. Logging the chunk ids at every stage is what makes a wrong answer traceable.

Two steps the first version skipped

The first is rewriting the query. In a conversation, the latest message is often not a good search query on its own. A customer who earlier mentioned selling shares and asking for a withdrawal then writes “and how long does that usually take?” Embedded as is, that message matches anything about durations. A small, fast model call rewrites it as a standalone question, “how long does a withdrawal of sale proceeds take to reach the bank”, using the conversation so far, and that is what gets searched. It costs one extra short call, around a couple of hundred milliseconds with a small model, and it fixed most of the failures on follow-up questions.

The second is reranking. The embedding model compresses each chunk into one vector before it has seen any question, so it cannot know which details of the chunk the question will care about. A reranker, usually a model called a cross-encoder, reads the question and a chunk together and scores how well the chunk answers it. That is far more accurate and far too slow to run on all 4,400 chunks, so it runs on the 50 or so candidates the two searches produce, and keeps the best five. Scoring 50 pairs typically takes tens to a few hundred milliseconds, depending on the reranker’s size and hardware. The pipeline uses cheap, broad methods to avoid missing the right chunk and an expensive, precise one to pick from what they found.

Measuring the retrieval separately from the answer

When an answer is wrong, there are two very different possibilities. Either the right passage never reached the model, or it did and the model misused it. Prompt changes can only help with the second. To tell them apart, the team built a small labelled set: 120 real customer questions from the transcripts, each tagged by a support agent with the article and section that answers it. It took two agents two afternoons.

Two numbers summarise retrieval on that set. Recall at k is the fraction of questions whose correct chunk appears anywhere in the top k results. Mean reciprocal rank averages 1/rank of the correct chunk across questions, counting zero when it is missing, so it rewards putting the right chunk near the top. For three questions whose correct chunks rank first, third and not at all, it is (1 + 1/3 + 0) / 3 = 0.44.

With the first version (fixed windows, embedding search only, no rewriting or reranking), recall at 5 was 64%, while recall at 50 was 90%. That gap is informative. For about a quarter of the questions, the right chunk was found but ranked too low to reach the prompt, which is a ranking problem that hybrid search and reranking address. For the remaining 10%, it was not in the top 50 at all, which points at chunking, vocabulary, or a gap in the help centre itself. After the changes above, recall at 5 rose to 86%. Several of the remaining misses turned out to be questions the help centre did not answer, which became a list of articles for the content team to write. No change to the model or the prompt would have found any of this.

Predict first

Recall at 5 is 86% and recall at 20 is 95%. A colleague proposes passing 20 chunks to the model instead of 5, since the right one is then present more often. What happens to cost per conversation, and do answers get better?

Show the worked answer

Cost rises sharply. Fifteen extra chunks of about 400 tokens is 6,000 more input tokens per turn, uncached because they change every turn. Over a four-turn conversation that is 24,000 tokens, about $0.024 at $1 per million, which roughly doubles the conversation’s cost from the inference chapter. Time to first token rises with the longer prefill.

Answers do not reliably improve. The right chunk is present 9 points more often, but every answer now comes with 15 or more passages that do not answer the question, several of which look as if they might, such as the article on adding funds next to the article on withdrawing them. Studies of long contexts have found that models use information placed in the middle of a long prompt less reliably than information at its start or end. When the team tested 20 chunks on the labelled questions, some answers improved and others got worse by drawing on a near-miss passage. The cheaper route to those 9 points is a better reranker, which keeps k at 5.

Budgeting the context window

Every turn’s prompt is assembled under a token budget, decided in advance rather than discovered on the bill. The team’s budget for a typical turn:

PartTokensHow it is kept within budget
System prompt and examples≈1,500reviewed like code; cached, since it never changes between calls
Tool definitions≈400short descriptions, only the tools this deployment uses
Conversation history≤1,200last three turns verbatim, older turns replaced by a short summary
Retrieved passages≈2,000 to 3,000five reranked chunks, each with its article id and section path
Customer’s question≈300long pasted text is truncated with a note to the model
Reserved for the reply≈500a maximum output length on the call

The order follows the inference and prompting chapters: stable parts first for caching, passages after the history, the question last, so the question and its evidence are the last things the model reads. Each passage is wrapped with its id so the reply can cite it, and the orchestration code checks that every id the reply cites was actually supplied in this turn. A reply that cites nothing, or cites an id that was not supplied, is not sent; the assistant says it could not find the answer and offers a ticket.

The answer built on the wrong passage

Before the reranker and metadata existed, a customer asked: “I sold shares this morning. How long until I can withdraw the money to my bank?” The assistant replied that funds are usually available instantly, cited an article, and was wrong. Here is how the team traced it, stage by stage, using the chunk ids logged for that request.

The rewritten query was fine. Embedding search returned, in first place, a chunk from “Adding funds via UPI”, which explains that money added through UPI is credited instantly. The question and that chunk share almost every important idea (money, bank, how long, available) and differ in direction, which embeddings capture weakly. In second place came a chunk from an archived article describing an older settlement cycle. The correct chunk, from “Withdrawing sale proceeds”, was ninth in embedding search and fourth in keyword search, thanks to the words “sold” and “withdraw”. After fusion it was sixth, one place outside the five that reached the prompt.

So the model received two misleading passages and not the right one, and it did what it was told: it answered from the passages it had and cited one. From the model’s side, the answer was grounded. The fault lay entirely in retrieval, and the citation is what made it fast to find, since it pointed straight at the UPI article.

Three changes fixed this class of error. Archived articles were excluded at search time using the metadata, which cost nothing at query time but required the content team to mark articles as archived when policies change, a process step that had not existed. The reranker was added; reading the question and the UPI chunk together, it scored the chunk low, because nothing in it is about taking money out. And the labelled set gained twelve questions about direction-sensitive pairs (adding versus withdrawing funds, buying versus selling, pledging versus unpledging) so that a regression would show up in recall. The costs were a reranker to host and about 150 milliseconds of added latency per turn, and a new obligation on the content team.

When retrieval is the wrong tool

Retrieval over text is for knowledge that lives in documents. The status of a customer’s order lives in the order system, changes by the second, and must be exact; retrieving a passage about order statuses will not tell the assistant whether ORD-88213 executed. That is a lookup, done by calling a tool with the order id, and the agents chapter covers how the assistant decides to make that call and what can go wrong when it does.

Sometimes the corpus is small enough that retrieval is not worth its failure modes. The charges schedule is about 40 short articles, around 25,000 tokens. Placed whole in the cached prefix of every call, it costs about $0.0025 per turn at the cached rate used earlier, and there is no retrieval step to get wrong. For a narrow assistant over a small, stable set of documents, that can be the better design. As context windows grow and cached input gets cheaper, the size at which retrieval starts to pay moves upward, and it is worth redoing this arithmetic every year or so rather than assuming the answer.

Retrieval also cannot fix behaviour. After the changes in this chapter, the assistant usually had the right passages, and some failures remained: replies in a tone the support leads disliked, an output format that drifted on long conversations, a long system prompt that every call paid for. Those are about how the model behaves, not what it knows. The next chapter, Fine-tuning, and when a better prompt wins, takes up when changing the model’s weights is the right answer to that kind of problem, and why it is so often the wrong answer to the problems in this one.