#30The RAG run: search → ground → answerMediumLLMsML System DesignAgentic AI
The RAG run: search → ground → answer
Background
The v0.2 agent retrieves first, then answers only from what it retrieved:
query → search(query) → format context → LLM(system + "Context:…\n\nQuestion:…") → grounded answer
Problem statement
Implement rag_run(query, search, llm) that runs the full retrieve-then-answer pipeline.
Input
query— the user question string.search— callablequery -> list[str](the search tool).llm— callablemessages -> str(the chat model).
Output
Returns the LLM's answer string. Internally:
docs = search(query).context = "\n".join(f"- {d}" for d in docs).- messages = system "Answer based ONLY on the provided context. If the context doesn't cover the question, say so." + user
f"Context:\n{context}\n\nQuestion: {query}". - return
llm(messages).
Examples
Example 1 — the answer is grounded in the retrieved context
search = (q -> ["AlphaCode used CodeContests."])
llm = (messages -> messages[-1]["content"]) # echoes the user message
rag_run("What benchmark?", search, llm)
# -> "Context:\n- AlphaCode used CodeContests.\n\nQuestion: What benchmark?"
Constraints
- Call
search(query), format docs as bullets, build the two messages, returnllm(messages). - The user message must be exactly
f"Context:\n{context}\n\nQuestion: {query}". - The system message must instruct the model to answer only from the context.
Notes
- The agent never sees the search backend or the model — only their interfaces. Swap either without touching this loop.
Python
Loading...
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Reference example: answer grounded in retrieved context
- •Sample: system message instructs context-only answering
- •Example: multiple docs become bullet lines