RAG Prompt Templates

Grounding instructions, context formatting and teaching the model to say "I don't know".

Last Updated:

Module 11 · Lesson 1 of 6 · Intermediate

RAG Prompt Templates

Grounding instructions, context formatting and teaching the model to say "I don't know".

Retrieval decides what the model sees; the prompt decides how it uses it. A good RAG prompt makes the model answer from the sources, cite them, admit when they are insufficient, and match the tone your users expect. This lesson builds a production-quality RAG prompt piece by piece.

A RAG prompt: system prompt, retrieved sources with ids and metadata, optional conversation history, and final instructions with the question at the end.
Figure 1. The four parts of a RAG prompt, in order.

Part 1: The system prompt

The system prompt is stable across requests. It defines the assistant's role, the grounding rules and the output style. Explain why rules exist; models follow reasoned instructions more sensibly than bare commands.

prompts.py
SYSTEM_PROMPT = """You are the internal help assistant for Zentrix Labs employees. You answer
questions about company policies using the policy excerpts provided with each question.

How to answer:
- Base every statement on the provided sources. Employees act on your answers (booking
  travel, taking leave), so an invented detail can cause real problems for them.
- Cite the source id in square brackets after each statement that uses it, e.g. [2].
- If the sources do not contain the answer, say so plainly and suggest contacting HR at
  [email protected]. Do not fill gaps with general knowledge about other companies.
- If sources disagree, prefer the most recent one and mention the difference.
- Keep answers short: a direct answer first, then the relevant conditions or exceptions.
- Write in plain English for non-specialists."""

Part 2: Formatting the sources

Give each source a short ID for citations, plus the metadata that helps the model judge it: title, section, date and, when relevant, the document's authority or status.

def format_sources(hits: list[dict]) -> str:
    blocks = []
    for i, h in enumerate(hits, start=1):
        m = h.get("metadata", {})
        attrs = " ".join(f'{k}="{v}"' for k, v in
                         [("title", m.get("title")), ("section", m.get("section")),
                          ("date", m.get("date"))] if v)
        blocks.append(f'<source id="{i}" {attrs}>\n{h["text"].strip()}\n</source>')
    return "<sources>\n" + "\n".join(blocks) + "\n</sources>"

Part 3: The user message

Put the sources first, then short task-specific instructions, then the question last.

USER_TEMPLATE = """{sources}

Answer the employee's question using the sources above. Remember to cite source ids,
and say clearly if the sources do not answer the question.

<question>{question}</question>"""

def build_messages(question: str, hits: list[dict], history: list[dict] | None = None) -> list[dict]:
    messages = list(history or [])[-6:]           # recent turns only, if this is a chat
    messages.append({"role": "user",
                     "content": USER_TEMPLATE.format(sources=format_sources(hits), question=question)})
    return messages

Putting it together

import anthropic

client = anthropic.Anthropic()

def generate_answer(question: str, hits: list[dict]) -> str:
    response = client.messages.create(
        model="claude-opus-5-5",
        max_tokens=2000,
        output_config={"effort": "low"},
        system=SYSTEM_PROMPT,
        messages=build_messages(question, hits),
    )
    if response.stop_reason == "refusal":
        return "Sorry, I can't help with that request."
    return "".join(b.text for b in response.content if b.type == "text")

Common prompt mistakes

MistakeEffectFix
No permission to say "I don't know"Model guesses when sources are missingExplicit fallback instruction with a reason
"Only use the context" with no reasonModel may refuse to do simple reasoning over the sourcesExplain that statements must be supported; allow combining sources
Sources without IDs or metadataNo citations; model cannot tell old from newNumbered sources with title and date
Question placed before long contextWeaker use of the contextQuestion last
Timestamps or user IDs in the system promptBreaks prompt cachingPut variable data in the user message
Huge rule lists in capital lettersOver-cautious, rigid answersFewer, clearer rules with reasons

Test the prompt with tricky questions

Keep a small set of adversarial questions and run them after every prompt change:

  • a question the sources do not answer,
  • a question where two sources disagree,
  • a question needing information from two sources combined,
  • a question that tries to make the model ignore its instructions,
  • a question in another language.

Key takeaways

  • A RAG prompt has a stable system prompt, formatted sources, optional history and the question last.
  • Give the model reasons for grounding rules and an explicit way to say the answer is not in the sources.
  • Number sources and include title and date metadata.
  • Keep variable data out of the system prompt so it can be cached.