Sub topic 4
Building a numbered context block
This chapter assumes you can write basic Python, call a language model through an API, and read JSON. It also assumes you know what a retrieval-augmented generation (RAG) pipeline is. Retrieval has already returned some chunks. Your job now is to turn them into a context block that the model can cite and your code can check.
Why number the sources
The model needs a short label for each source. A label such as [2] is cheap to write, easy to spot in the answer, and easy to look up in code. If you ask the model to cite a URL or a title, it can mistype or invent one. A number is simpler. Your code owns the mapping from number to chunk, and the model only repeats the number.
The previous chapter gave every chunk a stable identifier and metadata, such as a URL. Here you create a second label, the display number. It exists only for one prompt.
The context builder
This function takes a list of chunks and returns one string. Each chunk has a url and a text.
def build_context(chunks):
"""chunks: list of dicts with 'url' and 'text'. Sources are numbered from 1."""
blocks = []
for i, chunk in enumerate(chunks, start=1):
blocks.append(f"[{i}] ({chunk['url']})\n{chunk['text']}")
return "\n\n".join(blocks)Try it on two chunks:
chunks = [
{"url": "https://example.com/docs/limits", "text": "The API allows 100 requests per minute."},
{"url": "https://example.com/docs/errors", "text": "Failed requests are retried up to three times."},
]
print(build_context(chunks))The output is:
[1] (https://example.com/docs/limits)
The API allows 100 requests per minute.
[2] (https://example.com/docs/errors)
Failed requests are retried up to three times.Three details matter here:
enumerate(chunks, start=1)numbers from 1. People and models both expect the first source to be[1]. Starting at 0 invites off-by-one mistakes.- The blank line between blocks marks where one source ends and the next begins.
- The URL appears next to the number. This helps the model, and it helps you when you read logs.
Keep the numbering map
The string is only half of the result. After the model answers, you must turn [2] back into a chunk. The list you passed to build_context already does that, because source n is chunks[n - 1]. The rule only holds if you keep the list in the same order and do not change it between building the prompt and checking the answer.
Common errors
- Reordering after the prompt is built. If you sort or deduplicate the chunks after building the context,
[2]in the answer points to the wrong chunk. Build the context from the final list and keep that list. - Numbers that restart across turns. In a chat, each turn gets its own context block. Store the list for each turn with the answer, or old markers will not resolve.
- Chunk text that contains markers. A chunk may include text like
[1]from its own footnotes. The model may confuse these with your labels. If this happens often, use a different label style or strip such markers from the text. - Too many chunks. Each added chunk costs tokens and gives the model more chances to cite the wrong one. Pass only the top few.
Exercise
A pipeline builds the context from chunks A, B and C, so they are numbered [1], [2] and [3]. Before checking the answer, a developer sorts the list by URL, and the order becomes C, A, B. The answer cites [1]. Which chunk does the code treat as the cited source, and which chunk did the model mean? How do you prevent this?
Show answer
The code treats C as the cited source because it is now first in the list. The model meant A, which was [1] in the prompt. Prevent it by building the context from the final list and not changing the list's order afterward, or by storing the exact list used for the prompt and checking against that.