Build the Prompt

Assemble the system instruction, context chunks, and question into one string

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

From retrieved chunks to a prompt

In the previous chapter you saw the three parts of a RAG prompt: system instruction, context, and question. Now you write a function that assembles them into a single string the model can read.

Why the system instruction matters

The first line of the prompt sets two rules:

  1. "Answer using only the context below" — this is grounding. It tells the model to treat the retrieved chunks as its only source of truth, ignoring anything it learned during training.
  2. "If the answer is not in the context, say 'I don't know'" — this is the safety net against hallucination. Without it, the model may invent plausible-sounding facts when the chunks do not contain the answer.

Both rules work together: grounding limits *where* the model looks, and the fallback instruction limits *what* it says when it finds nothing.

How the template is assembled

The build_prompt function takes a question and a list of context chunks. It produces a single string — a prompt template filled with real data.

PartSourceSeparator
System instructionHard-coded in the template
ContextRetrieved chunks joined with "\n\n"Double newline between chunks
QuestionPassed in by the callerPlaced at the end

The double-newline separator between chunks gives the model a clear visual boundary. Without it, two adjacent chunks could blend together and confuse the model about where one piece of evidence ends and the next begins.

def build_prompt(question, context_chunks):
    context = "\n\n".join(context_chunks)
    prompt = f"You are a helpful assistant. Answer the question using only the context below.\nIf the answer is not in the context, say \"I don't know.\"\n\nContext:\n{context}\n\nQuestion:\n{question}"
    return prompt

Instructions

Complete the build_prompt function. The starter code provides the signature.

  1. Create a variable named context. Assign it "\n\n".join(context_chunks).
  2. Create a variable named prompt. Assign it the following f-string exactly:

f"You are a helpful assistant. Answer the question using only the context below.\nIf the answer is not in the context, say \"I don't know.\"\n\nContext:\n{context}\n\nQuestion:\n{question}"

  1. Return prompt.