Sub topic 4
Building a numbered context block
The context block is the part of the prompt that holds your retrieved passages. In this chapter you will turn a ranked list of chunks into a block where every passage has a number the model can cite. You will also keep a list that maps each number back to a source. This chapter assumes you can read basic Python and have a retriever that returns chunks as dictionaries with url and text keys. It also assumes each chunk already has a stable identifier, as covered in the previous chapter.
What the context block must do
The context block is the only link between what the model reads and what your code can check later. It has three jobs:
- Give each passage a short label the model can copy into its answer.
- Keep each passage's text next to its label, so the model does not mix up passages.
- Produce a record that maps each label back to a source, so your code can resolve a citation.
The third job is easy to forget. The model sees [2]. Your code must know that [2] means a specific chunk from a specific URL in this specific request.
The basic builder
This function numbers each chunk starting at 1 and joins the blocks with blank lines.
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)Run on two chunks, it produces this text:
[1] (https://example.com/a)
Failed requests are retried up to three times.
[2] (https://example.com/b)
Timeouts default to 30 seconds.Several choices in this format matter.
- Numbers start at 1. People expect
[1]to be the first source. Zero-based numbers also invite off-by-one errors when you later check ranges. - The marker comes first on its own line. The model sees a clear boundary between sources and can copy the exact marker.
- The URL sits in parentheses after the marker. It gives the model context about where the text came from. It also lets you spot the wrong source when you read a prompt log.
- Blank lines separate sources. Chunks often contain newlines of their own. A blank line plus a leading
[n]is a boundary that is easy to read.
Numbers are per request, not permanent
The number [2] is a position in this prompt. It is not the chunk's identifier. The same chunk may be [2] in one request and [5] in the next, depending on what the retriever returned.
Keep the two ideas apart:
| Concept | Example | Lifetime | Used for |
|---|---|---|---|
| Stable chunk id | `docs/retries.md#3` | Until the document changes | Storage, logging, evaluation labels |
| Prompt number | `[2]` | One request | What the model cites |
The prompt number is a short alias for the stable id. Short numbers are easier for a model to copy exactly than long paths or hashes. The cost is that the alias is meaningless without the lookup list from the same request. If you store an answer, store the resolved stable ids with it. The bare numbers alone cannot be decoded later.
A builder that returns the lookup list
The basic function returns only a string. The version below returns the string and the chunks that actually made it into the prompt. It also enforces a size budget, because retrievers often return more text than your prompt can hold.
def build_context(chunks, max_chars=6000):
"""Return (context, used). used[i - 1] is the chunk labeled [i]."""
blocks = []
used = []
total = 0
for chunk in chunks:
text = chunk["text"].strip()
if not text:
continue
number = len(used) + 1
block = f"[{number}] ({chunk['url']})\n{text}"
separator = 2 if blocks else 0 # the "\n\n" between blocks
if total + separator + len(block) > max_chars:
break
blocks.append(block)
used.append(chunk)
total += separator + len(block)
return "\n\n".join(blocks), used
chunks = [
{"url": "https://example.com/a", "text": "Failed requests are retried up to three times."},
{"url": "https://example.com/b", "text": "Timeouts default to 30 seconds."},
]
context, used = build_context(chunks)
print(context)
print(len(used))Three details in this version are easy to get wrong.
- Numbers come from
len(used), not from the loop index. If you skip an empty chunk, a loop index would leave a gap such as[1],[3]. The model would then cite a number that has no source, or your range check would pass a number that points to the wrong chunk. - The loop stops at the first chunk that does not fit. Retrievers rank chunks by relevance. Stopping keeps the most relevant ones. Skipping a large chunk and adding a smaller, lower-ranked one is possible, but you would then silently reorder the evidence.
usedis what you pass to later steps. Validation and rendering must use the same list the prompt was built from. Do not rebuild it from the originalchunks, which may contain chunks the model never saw.
Budgets: characters now, tokens later
The example budgets by characters because that needs no extra library. Models count tokens, and the ratio of tokens to characters varies by language and content. Treat the character limit as a rough guard. If you need tight control, replace len(block) with a call to your model's tokenizer. The structure of the function stays the same.
Leave room in the budget for the rest of the prompt: the instructions, the question, and the answer. A context that fills the window leaves no space for the reply.
Order and duplicates
Two choices affect answer quality.
Order. Models can pay less attention to material in the middle of a long context. The simplest policy is to keep the retriever's order, with the best chunk first. If you reorder, for example to place the best chunks at the start and end, do it before numbering. The numbers must increase down the page, because a block labeled [3] appearing before [1] confuses readers and models alike.
Duplicates. Retrievers often return overlapping chunks from the same document. If two chunks carry the same text, the model may cite both, and the answer looks better supported than it is. Remove exact duplicates before numbering:
def dedupe_chunks(chunks):
"""Drop chunks whose normalized text was already seen, keeping the first."""
seen = set()
unique = []
for chunk in chunks:
key = " ".join(chunk["text"].lower().split())
if key not in seen:
seen.add(key)
unique.append(chunk)
return uniqueCall dedupe_chunks first, then build_context. Near-duplicates need fuzzier methods, which are outside this chapter.
Text that looks like a marker
Source text is untrusted. A web page might contain the string [7], or a footnote such as see [2] above. That text sits inside your block next to your real markers. The model may mistake it for a source label, and a regex-based validator will treat any [n] in the answer as a citation, wherever the model copied it from.
You have two practical options:
- Accept the risk and rely on validation to catch out-of-range numbers. This catches only numbers beyond your source count. A stray
[2]still looks valid. - Rewrite square-bracket numbers in the source text before inserting it:
import re
def neutralize_markers(text):
"""Replace [n] in source text with (n) so it cannot be mistaken for a marker."""
return re.sub(r"\[(\d+)\]", r"(\1)", text)Apply it to chunk["text"] inside build_context. This changes the displayed text slightly, which matters later if you verify quotes against the original text. Verify quotes against the same transformed text that the model saw, or against the original with the same transformation applied to the quote.
Common mistakes
- Numbering from the original list after filtering. The model cites
[3], but[3]now refers to a different chunk. Number after all filtering, deduplication and trimming. - Dropping the lookup list. Without
used, you cannot turn markers into links or check quotes. - Passing different lists to the prompt and the validator. Return both from one function so they cannot drift apart.
- Including empty chunks. The model sees a numbered source with no content and may cite it anyway.
- Letting one huge chunk fill the budget. Cap the size of a single chunk, or truncate it at a sentence boundary, so that several sources fit.
Exercise
A retriever returns four chunks. The second has empty text. Your builder numbers chunks with the loop index and skips empty ones. The model cites [2] and [3]. Which sources do these numbers point to, and what should you change?
Show answer
The numbers are assigned from the loop index, so the surviving chunks are labeled [1], [3] and [4]. No block is labeled [2], yet [2] passes a range check. If your code resolves [2] by position in the list of used chunks, it resolves to the wrong chunk. [3] is also off by one in that list. Change the builder to number from len(used), so the labels are [1], [2] and [3], and return the used list so that markers resolve against exactly the chunks in the prompt.
Exercise
Why should the validator use the used list returned by build_context rather than the original retrieval result?
Show answer
The prompt may contain only part of the retrieval result, because of empty chunks, duplicates, or the size budget. The numbers the model sees refer to positions in the used list. Validating against the original list would accept citations to chunks the model never saw and would map numbers to the wrong URLs.