Sub topic 3
Giving Every Chunk a Stable Identifier
This chapter assumes you can write basic Python, have a retrieval step that returns text chunks, and know what a hash function is. Citations only work if code can map a marker in the answer back to exactly one chunk. That mapping starts with identifiers.
Two identifiers, two jobs
Each chunk needs two identifiers that serve different purposes.
- The stable id belongs to the chunk permanently. It goes in your index, logs and evaluation data.
- The display number (1, 2, 3...) exists for one request only. The model sees it and cites it, because short numbers are easy to copy correctly.
Keep the two separate. If the model cited stable ids, it could mistype a 12-character hash and you would have to repair it. If you stored display numbers in logs, they would point at different chunks tomorrow.
What metadata to store
Store enough to find the source again, show it to a user, and check quotes later.
| Field | Purpose |
|---|---|
| `id` | Stable identifier for logs and evaluation |
| `url` | Link shown to the user |
| `title` | Readable label |
| `start` | Character offset of the chunk in the document |
| `text` | The exact text the model saw |
Generating the stable id
An id built from the content and location has two useful properties. The same chunk always gets the same id when you re-index. If the text changes, the id changes, so a stale citation cannot silently point at new content.
import hashlib
def make_chunk_id(url, start, text):
"""Derive a short, deterministic id from where the chunk lives and what it says."""
raw = f"{url}|{start}|{text}".encode("utf-8")
return hashlib.sha256(raw).hexdigest()[:12]
def make_chunk(url, title, start, text):
return {
"id": make_chunk_id(url, start, text),
"url": url,
"title": title,
"start": start,
"text": text,
}
def number_sources(chunks):
"""Map display numbers (starting at 1) to chunks for one request."""
return {i: chunk for i, chunk in enumerate(chunks, start=1)}
chunk_a = make_chunk("https://example.com/retries", "Retries", 0,
"Failed requests are retried up to three times.")
chunk_b = make_chunk("https://example.com/timeouts", "Timeouts", 120,
"The default timeout is 30 seconds.")
lookup = number_sources([chunk_a, chunk_b])
print(lookup[2]["url"])
print(len(lookup[1]["id"]))
print(chunk_a["id"] == make_chunk_id(chunk_a["url"], 0, chunk_a["text"]))This prints the second URL, 12, and True. The lookup dictionary is the table you will use later to check markers and build links. Save it with the request log so you can audit any answer afterwards.
Common mistakes
- Using list position as the only id. Position changes whenever ranking changes, so old logs become unreadable.
- Hashing only the text. Two documents that contain the same boilerplate sentence then share an id, and you cannot tell which one was cited.
- Starting numbers at 0. Models and readers expect
[1]first. Starting at 0 also makes a missing marker easy to confuse with a falsy value in code. - Reusing numbers across turns. In a multi-turn chat, renumber each request or keep one table for the whole conversation. Do not mix the two.
Exercise
Two chunks from different pages both contain the sentence "Contact support for help." Your id function hashes only the chunk text. What goes wrong, and how do you fix it?
Show answer
Both chunks get the same id, so a log entry or citation cannot tell the pages apart. Include the URL and the start offset in the hashed string, as makechunkid does, so each chunk's id depends on its location as well as its text.