Putting retrieved passages in a prompt
8 min read
The parts of a RAG prompt
A RAG prompt has the same four parts almost everywhere. Each part has one job.
| What it holds | Its job | |
|---|---|---|
| Instruction | Rules for using the sources | Tells the model to answer from the sources and to say when they do not contain the answer |
| Sources | The retrieved passages, each with a number and a file name | Gives the model the facts and gives you something to cite |
| Question | The user's words, unchanged | Says what to answer |
| Format | How to write the answer | Asks for a short answer and the source numbers |
The instruction usually goes in the System promptThe instructions at the start of a prompt that set the model's role, its rules and the format of its answer. It stays the same on every call., the message that sets the model's rules for the whole conversation. The sources and the question go in the user message. Some teams put the question both before and after the sources, because a question read last is easy to answer.
Mark where the sources start and end
Passages are data, not instructions. The model should read them, not obey them. A passage that says "ignore the rules above" is an attempt at Prompt injectionAn attack that hides instructions in text the agent reads, such as a web page or an email. The model may treat the hidden text as a command and act on it., and it is easier to resist when the prompt shows clearly which text is which.
Wrap each passage in a labelled block, such as <source id="1" file="returns.md">, and tell the model in the instruction that text inside the blocks is reference material only. Labels do not make injection impossible, but they reduce the chance that the model treats a source as a command. The numbers also give the model something to cite.
Fit the budget
Sources share the Context windowThe maximum number of tokens a model can process in its context. Depending on the model, the limit can include the answer as well as the input. with the instruction, the question, any conversation history and the reply. So decide a budget for the sources, and add passages in rank order until the next one does not fit.
The program below counts tokens with a rough rule, 1.3 tokens per word. A real system would use the model's own tokeniser. It adds the passages in order and stops when the budget is full.
passages = [
("returns.md", "Return an unused bike within 30 days for a refund."),
("sale.md", "Sale items can be returned within 14 days."),
("warranty.md", "The frame has a 5 year warranty. The battery has a 2 year warranty."),
("shipping.md", "Standard shipping takes 3 to 5 business days. Express shipping takes 1 to 2 business days."),
]
budget = 30
def tokens(text):
return round(len(text.split()) * 1.3)
chosen, used = [], 0
for name, text in passages:
if used + tokens(text) > budget:
break
chosen.append((name, text))
used += tokens(text)
blocks = "\n".join(f'<source id="{number}" file="{name}">\n{text}\n</source>' for number, (name, text) in enumerate(chosen, start=1))
question = "How long do I have to return a sale item?"
print(f"Use only the sources below. Cite them by id. If they do not answer the question, say so.\n\n{blocks}\n\nQuestion: {question}")
print(f"\n{used} of {budget} estimated tokens used, {len(chosen)} of {len(passages)} passages kept")It prints:
Use only the sources below. Cite them by id. If they do not answer the question, say so.
<source id="1" file="returns.md">
Return an unused bike within 30 days for a refund.
</source>
<source id="2" file="sale.md">
Sale items can be returned within 14 days.
</source>
Question: How long do I have to return a sale item?
23 of 30 estimated tokens used, 2 of 4 passages keptTwo passages fit and two were dropped. The loop stopped at the first passage that did not fit instead of skipping it and looking for a smaller one. That keeps the list in rank order, so the passages that are left are the best ones.
Order matters
Models do not read every position in a long prompt equally well. In tests on several models, answers were most accurate when the needed passage was at the start or the end of the context, and worse when it sat in the middle. This effect has been called "lost in the middle", and the paper Lost in the Middle measures it. Newer models reduce the effect, though they do not remove it for every task.
Two habits follow from it.
- Send fewer, better passages instead of filling the window.
- Put the best passage first, or place the two best at the start and the end.
Before you send
- Remove repeats. Two chunks that say the same thing waste budget.
- Keep the source name with each passage. The reply needs it for a citation.
- Leave room for the reply. A budget that fills the whole window leaves nothing to answer with.
- Log the final prompt. When an answer is wrong, the prompt you sent is the first thing to read.
The next Lesson, Citations and honest refusals, covers what the model should write back.
Why wrap each passage in a labelled block?
A source says 'ignore the rules above'.
Labels reduce the chance a source is treated as a command, but do not remove the risk.
What should the loop do when the next passage does not fit the budget?
Passages are in rank order and the budget is nearly full.
Stopping keeps the best passages and avoids filling the window with weaker ones.
Where should the best passage go in a long context?
Models read the middle of long prompts less well.
The 'lost in the middle' effect means the start and the end are used best.
Your reading position is saved
0 of 15 complete
Lesson complete
Putting retrieved passages in a prompt
Up next