AI Run Lab

All chapters

Giving a model access to documents

A handbook can change this morning and be quoted in an answer this afternoon. Retrieval-augmented generation makes that possible by putting a relevant passage into the current request.

Open this chapter with experiments and audio

Where does the new information enter?

Suppose a fictional studio handbook says that visitors must leave by 18:00. Without the handbook, the model has little basis for answering a question about this particular studio. The application first searches the available documents, selects a passage, adds its source identifier and places the passage beside the question. The reader can then check the resulting answer against the same passage.

A practical system has a preparation stage and a question stage. During preparation, split documents into passages and store each passage with its title, version and access permissions. During a question, retrieve only passages the current user may see. When the document changes, replace the old indexed passages. Otherwise two different closing times may both look relevant.

Calculate a retrieval score

A simple baseline counts shared words. For the query studio visitor closing, the passage “Studio visitor closing time is 18:00” shares three distinct words. “Studio materials are on shelf B” shares one. Sorting by overlap puts the closing-time passage first. This works even with no neural network. A paraphrase such as “When must guests leave?” exposes its weakness.

An embedding retriever encodes the query and passages as vectors, then measures similarity. Two normalized vectors with dot product 0.80 point in more similar directions than a pair scoring 0.25. This score depends on the encoder. It is a ranking signal, and a passage can score highly while omitting the requested date or exception. Hybrid retrieval combines a word-based score with a vector-based ranking.

Inspect the winning passage

This baseline runs with ordinary Python 3. Compare the scores before reading the extracted text. Keep the identifier alongside the passage when you send it to a generator. Without the identifier you lose the easy route from an answer back to the source.

import re

docs = {"A": "Studio visitor closing time is 18:00.",
        "B": "Studio materials are on shelf B."}
def words(text):
    return set(re.findall(r"\w+", text.lower()))
query = "studio visitor closing"
ranked = sorted(docs, key=lambda key: -len(words(query) & words(docs[key])))
for key in ranked:
    print(key, len(words(query) & words(docs[key])), docs[key])

Trace an incorrect answer

Check three things in order. Was the required rule in the source collection? Did the selected passage include it? Did the generated answer accurately represent the passage? An error at the first stage requires better coverage. A missing passage at the second stage suggests a search or chunking problem. A wrong answer with the right passage points to how the model uses evidence.

Try splitting a deadline across two passages. One contains the date and the next begins “except for weekend events.” If only the first passage is retrieved, the model has lost a condition. Keeping headings and adjacent sentences together often helps. Larger chunks retain more context but occupy more of the model’s input budget. Evaluate on questions that actually depend on such exceptions.

What should happen if every passage is irrelevant?

The application can report insufficient evidence or ask for a more specific question. Inserting the nearest passage anyway can produce a confident guess.

Lewis et al. · Retrieval-Augmented Generation

A changing fact and a recurring behavior need different interventions

A repair manual changes the lamp replacement interval from 600 to 400 operating hours. The support assistant also keeps omitting the revision number in its answer. Treat those as two test cases. For the changing number, store the new version in the search index, remove or mark superseded passages and retrieve the passage at request time. The generator receives fresh evidence in its input. This is retrieval-augmented generation (RAG). Record the source version beside the answer.

For the recurring format, start with an explicit output field and validate it. If the behavior still fails across varied cases, supervised examples or preference pairs can train it. Tuning changes probabilities across prompts and takes a training and release cycle. RAG updates the evidence available to one request and spends context space. A single application can use both. Test whether the model cites the supplied revision when the index contains deliberately conflicting versions.

Separate an exception from its rule and inspect what reaches the model →

Sources · Lewis et al., 2020 · Ouyang et al., 2022

How to tell a retrieval failure from a reading failure

Suppose 100 questions each have one known supporting passage. The retriever places the gold passage in its top three for 80 questions, so recall@3 is 80%. Given those successful retrievals, the generator supports its answer with that passage in 60 cases. Supported end-to-end success is 60/100, while the conditional success rate is 60/80 = 75%. These denominators answer different questions.

What single intervention helps distinguish the two failures?

Inject the known passage directly into the same generator prompt and hold the rest constant. If it then cites and applies the rule correctly, inspect indexing, filtering and ranking. If the gold excerpt still fails, inspect formatting, context truncation and how the generator uses evidence.

Change the query and inspect the winning passage →