Learning path: Build and Measure a RAG System · Step 6 of 9
RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
Hand the retrieved pieces to the model so every answer can be checked. Number each block, fit 471 tokens into a 330-token budget by dropping the weakest blocks, and run a checker that passes a good reply and finds three problems in a bad one: a wrong number, a block that doesn't exist and a sentence with no citation.
What you will learn
- Assemble a grounded prompt: rules, numbered context blocks, then the question
- Count tokens with tiktoken and drop the weakest blocks to fit a budget
- Write a citation checker that flags missing, made-up and unsupported citations
- Read a checker report on a good reply and a bad one
Before you start
- The RAG Pipeline Explained
- LLM Tokens, Context Windows and Cost
Search has found some pieces. Now we hand them to the model, in a way that lets us check every answer it gives back. Three jobs: number the blocks, fit them inside a token budget, and check the citations. All of it runs without an API key, using a stand-in test model with two scripted replies.
Use the book, but name the page
Think of an open-book exam where every answer needs a page number. The book is our context blocks. The answer sheet is the model's reply, with a page number after each sentence. The marker is our checker: it opens that page and looks for the answer. And there's a page limit on the desk: only so many pages fit. That's the token budget.
An answer you cannot check
Our example is the Brightfield employee handbook. The question: How many days of annual leave do I get, and can I carry any over? Three things go wrong with a careless prompt:
- Paste the pieces with no numbers, and nobody can tell where the answer came from.
- Paste too many, and every piece costs tokens against a limit.
- A reply can cite a source that was never in the prompt.
The prompt, piece by piece
The rules, and what they cost
The rules are plain text at the top of assembly.py, and count_tokens uses tiktoken to price any text:
import tiktoken
ENC = tiktoken.get_encoding("cl100k_base")
RULES = (
"Answer using only the context blocks below.\n"
"After every sentence, cite the block it came from, like [2].\n"
"If the blocks do not contain the answer, say you do not know."
)
def count_tokens(text):
return len(ENC.encode(text))
Rule one: use only the blocks. Rule two: cite every sentence. Rule three: if it isn't there, say you don't know. Together they cost 38 tokens.
Building it, in code
def block_text(number, chunk):
return f"[{number}] ({chunk['heading']}) {chunk['text']}"
def build_prompt(question, chunks, budget=None):
"""Return (prompt, kept, dropped).
Blocks are added in order until the token budget is full."""
fixed = f"{RULES}\n\nContext:\n\nQuestion: {question}\nAnswer:"
used = count_tokens(fixed)
kept, dropped = [], []
for chunk in chunks:
cost = count_tokens(block_text(len(kept) + 1, chunk))
if budget is not None and used + cost > budget:
dropped.append(chunk)
continue
used += cost
kept.append(chunk)
context = "\n".join(block_text(i, c) for i, c in enumerate(kept, 1))
prompt = f"{RULES}\n\nContext:\n{context}\n\nQuestion: {question}\nAnswer:"
return prompt, kept, dropped
block_text puts the number and the heading in front of each piece. The numbers come from the kept list, so they always start at 1 with no gaps. The prompt order is: rules, context, question, then the word Answer: so the model knows where to start.
build_prompt with a budget of 330
The rules and the question go in first, so used starts at 61. Then the loop, best match first:
| Block | Cost | used + cost | Result |
|---|---|---|---|
| Annual Leave | 106 | 167 | kept as [1] |
| Sick Leave | 105 | 272 | kept as [2] |
| Parental Leave | 100 | 372 | over 330, dropped |
| Leaving Brightfield | 99 | 371 | over 330, dropped |
Because of continue, the loop still tries the last piece after one spills. 58 tokens stay free, and only blocks 1 and 2 exist in this prompt.
In the project, retrieve() ranks chunks by shared words with the question, a simple stand-in for vector search, so the example runs with the standard library plus tiktoken. In a real pipeline, the blocks come from your retriever in the same best-first order.
What the checker reads
import re
CITE = re.compile(r"\[(\d+)\]")
def facts(text):
"""The numbers in a sentence, as words or digits, are the facts we can check."""
small = ("one two three four five six seven eight nine ten twelve "
"fifteen sixteen twenty twenty-five thirty forty fifty").split()
found = set(re.findall(r"\d+", text))
found |= {w for w in re.findall(r"[a-z-]+", text.lower()) if w in small}
return found
def check(reply, blocks):
"""blocks: list of block texts, block 1 first. Returns a list of findings, one per problem."""
findings = []
for sentence in re.split(r"(?<=[.!?])\s+", reply.strip()):
cited = [int(n) for n in CITE.findall(sentence)]
if not cited:
findings.append(("no citation", sentence))
continue
for n in cited:
if not 1 <= n <= len(blocks):
findings.append((f"[{n}] does not exist", sentence))
valid = [n for n in cited if 1 <= n <= len(blocks)]
if valid:
support = " ".join(blocks[n - 1].lower() for n in valid)
plain = CITE.sub("", sentence)
missing = sorted(f for f in facts(plain) if f not in support)
if missing:
label = "not in the cited block: " + ", ".join(missing)
findings.append((label, sentence))
return findings
For each sentence: CITE pulls out the numbers in square brackets. No mark at all is a problem. A mark that points past the kept blocks is a problem. And for real blocks, facts collects the numbers in the sentence, as digits or number words like "five", and each one must appear in the cited block. This checker checks numbers only: the word "March" isn't a number, so it never looks for it.
One run, two reports
The two scripted replies:
- Good: Every full-time employee gets twenty-five days of paid annual leave per year [1]. You may carry over up to five unused days, and they must be used by the end of March [1].
- Bad: Every full-time employee gets thirty days of paid annual leave per year [1]. Unused days are paid out in cash every December [4]. Booking is done in the people portal.
main.py assembles the prompt, trims it, and checks both:
retrieved 4 blocks, full prompt 471 tokens
budget 330: kept 2, dropped 2 -> 272 tokens
Answer using only the context blocks below.
After every sentence, cite the block it came from, like [2].
If the blocks do not contain the answer, say you do not know.
Context:
[1] (Annual Leave) Every full-time employee gets twenty-five days of paid annual leave per calendar …
[2] (Sick Leave) If you are unwell, message your manager before ten in the morning on the first day.…
Question: How many days of annual leave do I get, and can I carry any over?
Answer:
--- good reply ---
Every full-time employee gets twenty-five days of paid annual leave per year [1]. You may carry over…
checker: all sentences cited and supported
--- bad reply ---
Every full-time employee gets thirty days of paid annual leave per year [1]. Unused days are paid ou…
checker: 3 problem(s)
not in the cited block: thirty: Every full-time employee gets thirty days of paid annual lea
[4] does not exist: Unused days are paid out in cash every December [4].
no citation: Booking is done in the people portal.
(The blocks and replies are shortened for display in this output; the model sees every word.)
The good reply cites block 1 twice, and block 1 really holds "twenty-five" and "five". The bad reply sounds just as sure of itself, and has three problems: "thirty" isn't in block 1, block 4 was dropped so it doesn't exist, and the last sentence cites nothing. A citation is a claim you can test, and a wrong answer can't hide behind a nice number.
Common mistakes
- Pasting blocks with no ids. Then there's nothing to cite.
- Keeping the original retrieval numbers after dropping blocks. Renumber from the kept list, or "[4]" may point at nothing.
- Filling the budget in random order. Add best match first, so the weakest pieces are the ones that go.
- Stopping the loop at the first block that doesn't fit. A smaller block later may still fit.
- Trusting a citation because it's there. Check that the block exists and that it holds the fact.
Quick recap
| Job | How | In this run |
|---|---|---|
| Number | [n] (heading) text, numbered from the kept list | Blocks [1] and [2] |
| Budget | Add blocks best first until the next one won't fit | 471 down to 272 tokens |
| Check | Cited? Block exists? Fact in the block? | Good reply passes, bad reply has 3 problems |
Try it yourself
Set BUDGET in main.py to 400 and run it again. Using the costs in the table above, predict first: which blocks come back, and how many tokens will the prompt use?
Related course on Udemy
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)Related posts
The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
Ingest, chunk, embed, store, retrieve, rerank and generate, in one Python file. Follow one question through a 26-chunk employee handbook to an answer that cites its source.
Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
Ask one question of a whole collection of vectors: which items are closest to this one? Normalise, score every row with one matrix multiply, keep the top k or everything above a threshold, and check it with NearestNeighbors.
Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
A smart model has never read your company's files, and they change every month. Three ways to give it the facts: paste everything, fine-tune, or retrieve only the right pieces. Follow a refund-policy question through all three and see why RAG wins when documents change.
Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
Swap a toy embedder for a model that learned. Two roads (all-MiniLM-L6-v2 on your machine, or OpenAI's API with your key), three sizes (384, 1,536 and 3,072 numbers), one rule, and three use cases built on the same rank function, with real scores.