Sub topic 3
Giving Every Chunk a Stable Identifier
This chapter assumes you can write basic Python, call a language model through an API, and read JSON. It also assumes you know that a retrieval-augmented generation (RAG) system splits documents into chunks, stores them in an index, and retrieves some of them for each question. The chapter covers what to attach to each chunk so that a citation can be traced back to it later.
Why identifiers come before citations
A citation is a pointer. A pointer is only useful if it keeps pointing at the same thing. If the model writes [2], your code must be able to answer three questions:
- Which chunk did
[2]mean when the prompt was built? - Does that chunk still exist, and has its text changed since?
- Which document and which part of it did the chunk come from?
Most citation bugs come from skipping this design step. A common shortcut is to cite by the chunk's position in a list, such as results[1]. That works in a demo and breaks in production, because the list order changes on every query.
Two kinds of identifier
Use two identifiers for two different jobs.
| Identifier | Example | Lifetime | Purpose |
|---|---|---|---|
| Stable chunk id | `refund-policy#3-9f2c1a7e` | Lives as long as the chunk's content | Storage, logging, auditing, evaluation labels |
| Display number | `[2]` | One request only | What the model sees and writes in its answer |
The stable id belongs to the chunk. The display number belongs to one prompt. Your code keeps a mapping from display numbers to stable ids for each request. The model never sees the stable id. It only needs short numbers that are easy to copy correctly. Your logs and tests use stable ids, because those still mean something next week.
What a chunk record should contain
At indexing time, store more than the text. A minimal record has these fields:
chunk_id: the stable identifier.doc_id: the identifier of the parent document. Use a slug or database key you control, not a file path that may be renamed.url: where a user can open the source. This is what you render later as a link.position: the index of the chunk within its document, starting at 0.text: the chunk content exactly as it will appear in the prompt.
You can add title, section, page, version, or retrieved_at as needed. Metadata like this also helps later chapters. A title makes rendered citations readable, and a version lets you detect stale sources.
Designing the stable id
A good stable id has three properties:
- Deterministic. Indexing the same document twice gives the same ids. Random UUIDs fail this test unless you persist them carefully.
- Unique. Two different chunks never share an id.
- Change-aware. If the text changes, the id changes, so an old citation can't silently point at new content.
The usual recipe combines the document id, the position, and a short hash of the text.
import hashlib
from dataclasses import dataclass
@dataclass(frozen=True)
class Chunk:
chunk_id: str
doc_id: str
url: str
position: int
text: str
def make_chunk_id(doc_id, position, text):
"""Deterministic id: document, position, and a short hash of the text."""
digest = hashlib.sha256(text.encode("utf-8")).hexdigest()[:8]
return f"{doc_id}#{position}-{digest}"
def chunk_document(doc_id, url, paragraphs):
"""Turn a list of paragraph strings into Chunk records."""
return [
Chunk(
chunk_id=make_chunk_id(doc_id, position, text),
doc_id=doc_id,
url=url,
position=position,
text=text,
)
for position, text in enumerate(paragraphs)
]
if __name__ == "__main__":
chunks = chunk_document(
"refund-policy",
"https://example.com/docs/refunds",
[
"Refunds are available within 30 days of purchase.",
"Digital goods are refunded only if they were not downloaded.",
],
)
for c in chunks:
print(c.chunk_id, "->", c.url)Running this prints two lines. Each begins with refund-policy#0- or refund-policy#1-, followed by an eight-character hash, then the URL. The same input gives the same ids on every run.
Choosing what goes into the hash
The hash input is a design decision, and each option has costs.
| Id scheme | Survives edits elsewhere in the document | Detects text changes | Notes |
|---|---|---|---|
| `doc_id#position` | No, inserting a chunk shifts all later ids | No | Simple, but silently points at new text |
| `doc_id#hash` | Yes | Yes | Two identical paragraphs in one document collide |
| `doc_id#position-hash` | No, position shifts | Yes | Used above. Collision-safe and detects changes |
The scheme above gives up one property: inserting a paragraph early in a document changes the position part for every later chunk. For most systems that is acceptable, because the content hash still tells you whether the text itself changed. If you need ids that survive insertions, drop the position and add a counter only when two chunks in the same document have identical text.
Assigning display numbers per request
After retrieval, build the per-request mapping. This step must also remove duplicates. Retrieval often returns the same chunk twice, for example when a keyword search and a vector search both find it. If you number duplicates separately, the model may cite [1] and [3] for one fact, and your evaluation will count two sources where there is one.
def assign_display_numbers(retrieved):
"""Map display numbers (starting at 1) to unique chunks, keeping retrieval order."""
seen = set()
number_to_chunk = {}
next_number = 1
for chunk in retrieved:
if chunk.chunk_id in seen:
continue
seen.add(chunk.chunk_id)
number_to_chunk[next_number] = chunk
next_number += 1
return number_to_chunkThe numbers start at 1 because people and models both expect numbered references to start there. Starting at 0 invites off-by-one errors, since a model may write [1] for the first source anyway.
Keep this mapping for the whole life of the request. You need it when the answer comes back, to translate [2] into a stable id. Store it with the answer in your logs:
{
"question": "How long do I have to request a refund?",
"answer": "Refunds are available within 30 days of purchase [1].",
"display_map": {
"1": "refund-policy#0-9f2c1a7e",
"2": "refund-policy#1-3b8d44c0"
},
"cited_chunk_ids": ["refund-policy#0-9f2c1a7e"]
}With this record, you can reproduce the prompt, check the citation weeks later, and compare it against a hand-labeled answer during evaluation. The hash values here are illustrative.
Edge cases
- Re-indexing after edits. If a paragraph changes, its chunk id changes. Old logs still refer to the old id, which no longer exists in the index. This is correct behavior: the old citation was about the old text. Keep old records or snapshots if you need to audit past answers.
- Overlapping chunks. If your chunker uses overlap, the same sentence may appear in two chunks with different ids. A model may cite either one. When you evaluate, decide whether to treat them as equivalent, for example by comparing
doc_idinstead ofchunk_id. - Same text in different documents. The
doc_idprefix keeps these ids distinct. That is usually what you want, because the two documents may differ in authority or date. - Very short hashes. Eight hex characters give about four billion values. That is fine within one document, because you only compare ids within a small set. For a global key across millions of chunks, use a longer hash.
- Ids that leak into prompts. Long ids cost tokens and give the model more to mistype. Keep them out of the prompt, as described above.
What this enables
With stable ids and a per-request map, later steps become simple. The next chapter formats the numbered context block for the prompt. Validation can check that every marker is within 1..len(number_to_chunk). Rendering can look up each chunk's url. Evaluation can compare cited_chunk_ids with labeled ones. All of them depend on the identifiers you set up here.
Exercise
A teammate proposes using each chunk's row number in the search results as its id, so the model cites [0], [1], and so on. Give two problems with this, and say what you would store instead.
Show answer
First, the row number is not stable. The same chunk gets a different number for a different query, so a logged citation can't be traced to a chunk later without the saved prompt. Second, it says nothing about the chunk's content or origin. If the document is re-indexed, the number can't show that the text changed. Also, duplicates in the results get separate numbers, and starting at 0 invites off-by-one errors. Store a deterministic chunk id made from the document id, the position, and a hash of the text, plus a per-request map from display numbers (starting at 1) to those ids.
Exercise
Two chunks in the same document contain the identical sentence "See the pricing page." Under the scheme doc_id#hash, what goes wrong, and how does doc_id#position-hash fix it?
Show answer
Both chunks hash to the same value, so they get the same id and one would overwrite or be confused with the other. Adding the position makes the ids differ, because the two chunks sit at different positions in the document.