Answer from the Retrieved Passages

A search that finds the right passages is only half of a question-answering program. The other half hands those passages to a language model and asks it to write the answer from them. Joined, the two halves turn a question into an answer in one pass, and when that answer comes out wrong, the passages the model received show which half is at fault.

Retrieve, then answer

Every question passes through two stages, one after the other. In the first, retrieval, the question is turned into an embedding by the same model that embedded the stored passages. A nearest-neighbour search then keeps the k passages closest to it in meaning. Nothing is generated yet: retrieval only chooses text that already exists.

In the second, generation, a prompt is built from the question and those passages and sent to a language model in one request. The model writes the answer. It sees nothing but that request, so the passages chosen in the first stage are the only facts from your documents it has to work with. This is what retrieval-augmented generation means: retrieved text augments the prompt before the model generates.

  • Question
  • Embed question
  • Nearest k passages
  • Build the prompt
  • Language model
  • Answer
  • Question to Embed question
  • Embed question to Nearest k passages
  • Nearest k passages to Build the prompt
  • Build the prompt to Language model
  • Language model to Answer

Because the answer passes through two stages, a wrong answer can come from either. Retrieval fails when it sends passages that do not hold the answer, so the model cannot possibly give it. Generation can fail with the right passage in front of it: the model misreads it, is distracted by the unrelated passages sent with it, mixes it with something else, or fills a gap from what it learned in training. Each failure has a different fix, so the first job when an answer is wrong is to find out which stage caused it.

True or false?

If the program gives a wrong answer, the language model is the part to blame.

False. The model may never have been given the answer. When retrieval sends the wrong passages, no model could answer correctly from them.

The model sees only the passages retrieval chose, not the rest of the stored documents.

True. Each request stands alone. Whatever is not in the prompt does not exist for the model.

The augmented prompt

The prompt for each question is assembled from three parts, in this order. First come the standing instructions: the same text for every question, saying how to answer, for example to use only the passages given. Then come the retrieved passages, different for every question, marked off so the model can tell where the context starts and ends and which source each passage came from. Last comes the question itself.

Marking off the context matters because the passages are just text, and so is everything else in the prompt. Tags such as <passage> and </passage> draw a clear boundary, and an attribute on the tag can carry the source. Prompting guides from model providers recommend tags like these or a simple labelled format, and report that JSON did poorly for many documents in a long context.

One assembled prompt
SYSTEM
Answer the question using only the passages below.
Keep the answer short.

USER
<passages>
<passage source="loans.md / Borrowing a laptop">
Laptops are lent at the front desk. Bring your staff card.
</passage>
<passage source="loans.md / Loan periods">
Books are lent for 21 days, laptops for 7 days.
</passage>
</passages>

Question: How long can I keep a borrowed laptop?

Placing the passages before the question is not a strict law, and providers say the best order can vary by model, but their guides agree on the general shape: instructions first, the varying context after them, the question at the end.

In code, the prompt becomes a list of messages for one plain model call through an OpenAI-compatible client. The instructions go in a system message, the passages and the question in a user message. The call sends a model name and that list, and the generated text comes back in choices[0].message.content. Newer OpenAI models also accept a developer role for instructions, but system is the pair that most OpenAI-compatible servers understand.

from openai import OpenAI

INSTRUCTIONS = (
    "Answer the question using only the passages below.\n"
    "Keep the answer short."
)

def build_messages(question, passages):
    blocks = [
        f'<passage source="{p["source"]}">\n{p["text"]}\n</passage>'
        for p in passages
    ]
    context = "<passages>\n" + "\n".join(blocks) + "\n</passages>"
    return [
        {"role": "system", "content": INSTRUCTIONS},
        {"role": "user", "content": f"{context}\n\nQuestion: {question}"},
    ]

def answer(client, model, question, passages):
    response = client.chat.completions.create(
        model=model,
        messages=build_messages(question, passages),
    )
    return response.choices[0].message.content

The function build_messages does not decide anything about the answer. It only arranges what retrieval found, which keeps the two stages apart: you can change the search without touching the prompt, and the other way round.

How many passages to send

The search keeps the k nearest passages, and k is a choice. The passage ranked first is only the closest by embedding distance. It is often the right one, but not always: a passage about the same topic can sit nearer the question than the passage that actually holds the answer.

Nearest passages for "How long can I keep a borrowed laptop?"
RankPassageCosine distanceHolds the answer
1Borrowing a laptop: lent at the front desk0.21no
2Loan periods: laptops for 7 days0.26yes
3Printing: colour costs extra0.47no

With k = 1 the model receives only the first row and cannot say how long the loan lasts. With k = 2 or 3 the answer is in the prompt. Sending too few passages is a retrieval miss even when the search ranked well.

Sending many is not free either. Every passage adds input tokens. Every input token is billed, and the model has to read it before it writes its first word, so a longer prompt costs more and makes the reader wait longer. The extra passages are also usually unrelated to the question, and unrelated text can distract the model from the passage that matters. Research on question answering over retrieved documents found that answers stopped improving long before the retriever stopped finding more relevant documents: sending 50 documents instead of 20 improved accuracy by only 1 to 1.5 percentage points.

The response tells you what each choice costs. Its usage.prompt_tokens field counts the tokens in the prompt, so running the same question with different values of k shows how much each extra passage adds. Some OpenAI-compatible servers leave usage empty, so code that reads it should check that it is there.

True or false?

Raising k always makes answers more accurate, because the answer is more likely to be in the prompt.

False. The chance of including the answer rises, but so does the amount of unrelated text, and past a point accuracy stops improving while cost and waiting time keep growing.

The best k depends on the documents and the questions, so it is found by testing.

True. How long the passages are and how spread out an answer tends to be differ between collections. Even research papers choose k by trying values on their own data.

Inspecting the context

When an answer is wrong, the quickest way to find the stage at fault is to read the passages the model received, side by side with its answer. A model request carries no memory of earlier requests, so the messages your program sent are the model's entire input. Printing them shows exactly what it had to work with.

Passages sent, then the answer
Question: How long can I keep a borrowed laptop?

Passages sent (k=2):
  1. loans.md / Borrowing a laptop    distance 0.21
  2. loans.md / Loan periods          distance 0.26

Answer:
  You can keep a borrowed laptop for 7 days.

One question then sorts the failure. Is the answer in the passages that were sent? If it is not, the model never had it, and the fix belongs to retrieval: a larger k, better chunks, or a question phrased closer to the documents. If it is there and the answer is still wrong, the model had what it needed and used it badly, and the fix belongs to generation: clearer instructions, or a clearer way of marking off the passages.

  • Wrong answer
  • Answer in the passages sent?
  • Retrieval miss change k, chunks or search
  • Generation mistake change instructions or prompt
  • Wrong answer to Answer in the passages sent?
  • Answer in the passages sent? to Retrieval miss: no
  • Answer in the passages sent? to Generation mistake: yes

Reading the context also catches answers that look right for the wrong reason. If the model states a fact that appears in none of the passages, it took the fact from its training, and the next question of the same kind may get an invented answer instead.

True or false?

If the passages sent contain the answer but the reply is wrong, changing k is the first thing to try.

False. Retrieval did its job. The model used the right passage badly, so the instructions or the way the passages are presented need work.

A correct answer can still hide a problem if no passage sent contains the fact it states.

True. The model answered from its training rather than from your documents, which it cannot do for facts it never saw.