Agentic RAG in Python: Make Retrieval a Tool the Agent Decides to Call

8 min read

The problem: the facts the agent needs are in your documents, not in the model

The trip helper's model knows nothing about Casa Azul's breakfast hours or the price of a day pass in the travel guide. That information lives in a document. If the agent answers from training data, it will either refuse or, worse, produce a confident and specific answer that is simply made up.

The usual fix is retrieval augmented generation (RAG): search the documents for passages related to the question and give those passages to the model along with the question. The LLM Fundamentals course covers RAG as a concept. This lesson builds the agent version of it.

Classic RAG retrieves on every request. That is wasteful when the question needs no documents ("what is 15 plus 27?"), and clumsy when the first search misses and a second, better query is needed. Agentic RAG turns retrieval into a tool. The agent decides whether to search, what to search for, and whether to search again. Your code still checks that the answer is actually grounded in what was retrieved.

The guide: a small made-up document

Save this as guide.txt. Every hotel and pass in it is fictional:

text
Casa Azul (hotel LIS-01) serves breakfast from 7:30 to 10:30. Late checkout until 1 pm costs 15 EUR.

Hotel Miradouro (hotel LIS-02) has a rooftop bar that opens at 6 pm. The hotel has no elevator.

Ryokan Hana (hotel KYO-01) serves a set vegetarian dinner if you ask one day ahead. Shoes stay at the entrance.

Fjord Inn (hotel OSL-01) lends guests warm boots and umbrellas for free at the front desk.

Getting around Lisbon in this guide: the made-up Blue Card day pass costs 7 EUR and covers trams and the metro.

Getting around Kyoto in this guide: the made-up Green Pass costs 900 JPY for one day of city buses.

Quiet mornings in Kyoto: this made-up guide suggests the Lantern Path walk, which opens at 8 am and is quiet before 9 am.

One topic per paragraph keeps chunking trivial: split on blank lines. Real documents need a smarter splitter (by heading, or by a few hundred tokens with some overlap), but the agent side of the code stays the same.

Retrieval as a tool

This reuses embed from lesson 8's memory_store.py, so keep that file in the same folder. Save this as guide_search.py:

python
# file: guide_search.py
from pathlib import Path

import numpy as np

from memory_store import embed  # the helper from the long-term memory lesson

# guide.txt is a small made-up travel guide, one topic per paragraph.
CHUNKS = [p.strip() for p in Path("guide.txt").read_text().split("\n\n") if p.strip()]
CHUNK_VECTORS = embed(CHUNKS)  # embed the whole guide once, at startup


def search_guide(query: str, k: int = 2) -> dict:
    scores = CHUNK_VECTORS @ embed([query])[0]
    best = np.argsort(-scores)[:k]
    return {"results": [{"cite": f"[g{i}]", "score": round(float(scores[i]), 2), "text": CHUNKS[i]} for i in best]}


SEARCH_TOOL = {"type": "function", "function": {
    "name": "search_guide",
    "description": "Search the travel guide for hotel details, local transport passes and activities. "
                   "Use it for any question about those topics. Returns passages, each with a cite label like [g3].",
    "parameters": {"type": "object", "properties": {
        "query": {"type": "string", "description": "A short search query, e.g. 'Casa Azul breakfast hours'"}},
        "required": ["query"]}}}

if __name__ == "__main__":
    print(search_guide("When can I eat breakfast at Casa Azul?"))

The guide is embedded once at startup. Each search embeds the query, scores every chunk with one dot product, and returns the top two passages with their scores and a cite label such as [g0].

Run it directly and the tested output, with all-minilm, ranked the Casa Azul breakfast passage first with a score of 0.82, and an unrelated Kyoto passage second at 0.42. The gap between those scores is typical: the right passage stands out, and the second result is filler. Returning a couple of extra passages is usually fine; the model can ignore them.

The tool description does the routing

The description of search_guide names the topics it covers: hotel details, local transport passes and activities. That sentence is what lets the model decide when to search. If you add documents about a new topic, update the description, or the model will not know to search for it.

The query parameter description includes an example ("Casa Azul breakfast hours"). Short keyword style queries tend to embed closer to the matching passage than a full chatty question.

The agent, with grounding checks

Save this as rag_agent.py:

python
# file: rag_agent.py
import json
import re

from guide_search import SEARCH_TOOL, search_guide
from llm import client, MODEL

SYSTEM = ("You are a trip helper with a travel guide you can search with the search_guide tool. "
          "You do not know hotel or transport facts yourself: always call search_guide for them. "
          "Answer from the returned passages and cite them with their cite label, like [g3]. "
          "Questions that need no guide, like arithmetic, you answer directly.")

CITATION = re.compile(r"\[g\d+\]")


def check_answer(answer: str, retrieved: set[str]) -> str | None:
    """Return a correction for the model, or None if the answer is acceptable."""
    if "search_guide" in answer:
        return "Do not describe the search. Call the search_guide tool now."
    cited = set(CITATION.findall(answer))
    if cited - retrieved:
        return (f"You cited {sorted(cited - retrieved)} but did not retrieve it. "
                "Call search_guide, then answer only from what it returns.")
    return None


def answer_with_forced_retrieval(question: str) -> str:
    """Fallback: retrieve in code, then let the model only write the answer."""
    result = search_guide(question)
    print("  fallback: retrieved", [r["cite"] for r in result["results"]], "in code")
    return client.chat.completions.create(
        model=MODEL,
        messages=[{"role": "system", "content": "Answer only from these passages and cite them. "
                   "If they do not contain the answer, say you do not know.\n" + json.dumps(result)},
                  {"role": "user", "content": question}],
        temperature=0,
    ).choices[0].message.content


def run_agent(question: str, max_steps: int = 5, max_corrections: int = 2) -> str:
    messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": question}]
    retrieved: set[str] = set()
    corrections = 0
    for _ in range(max_steps):
        msg = client.chat.completions.create(
            model=MODEL, messages=messages, tools=[SEARCH_TOOL], temperature=0
        ).choices[0].message
        messages.append(msg)
        if not msg.tool_calls:
            problem = check_answer(msg.content or "", retrieved)
            if not problem:
                return msg.content
            if corrections < max_corrections:
                corrections += 1
                print("  correction:", problem)
                messages.append({"role": "user", "content": problem})
                continue
            return answer_with_forced_retrieval(question)  # never return an ungrounded answer
        for call in msg.tool_calls:
            args = json.loads(call.function.arguments)
            result = search_guide(**args)
            ids = [r["cite"] for r in result["results"]]
            retrieved.update(ids)
            print(f"  search_guide({args['query']!r}) -> {ids}")
            messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})
    return "Stopped at the step limit."


if __name__ == "__main__":
    for q in ["When does breakfast end at Casa Azul?",
              "How much is a day of buses in Kyoto?",
              "What is 15 plus 27?"]:
        print("Q:", q)
        print("A:", run_agent(q), "\n")

The loop is the familiar one from lesson 2, with three additions:

  1. It records what was retrieved. Every cite label returned by search_guide goes into the retrieved set.
  2. check_answer inspects the final answer before accepting it:
    • If the answer mentions search_guide in text, the model described a search instead of calling the tool. The code tells it to call the tool.
    • If the answer cites a label that was never retrieved, the citation is invented. The code tells it to search and answer only from results.
  3. A fallback that does not depend on the model. If corrections run out, answer_with_forced_retrieval runs the search in code and asks the model only to write an answer from those passages. The agent never returns an answer that failed the check.
sequenceDiagram
    autonumber
    actor U as User
    participant A as Agent loop
    participant M as Model
    participant G as search_guide
    U->>A: Breakfast hours at Casa Azul?
    A->>M: question + search_guide tool
    M-->>A: call search_guide, Casa Azul breakfast hours
    A->>G: embed query, score every chunk
    G-->>A: top 2 passages with cite labels [g0], [g2]
    Note over A: retrieved = {g0, g2}
    A->>M: tool result
    M-->>A: 7:30 to 10:30 [g0]
    A->>A: check_answer: cited labels were retrieved
    A-->>U: Grounded answer
    Note over A,G: If checks keep failing: retrieve in code,<br/>then ask the model to answer from it

Diagram: The model decides to search, the code records what was retrieved, and check_answer rejects invented citations.

Why the checks exist: what happened in testing

These checks were not designed up front. They were added because of what qwen2.5:1.5b actually did during testing.

First version, with a system prompt saying "call search_guide first and answer only from the passages... If the passages do not contain the answer, say you do not know." The model skipped the tool for both guide questions and answered "I do not know." It followed the "say you do not know" instruction without ever searching.

Second version, with a prompt saying "You do not know hotel or transport facts yourself: always call search_guide for them." The arithmetic question was answered directly, which is correct. But for the breakfast question, the model skipped the tool and produced an answer with a citation, [chunk 0], and invented hours that were not in the guide. For the bus question, it wrote a sentence describing what it would search for, as text, instead of calling the tool.

Third version, with the checks. Corrections fixed the bus question, but the breakfast question kept citing [chunk 0] without searching, even after two corrections. The labels were chunk_id numbers then, and a small number like 0 is easy for the model to produce from nothing.

Final version, with labels changed to the less guessable [g0] form, plus the fallback. In the tested run:

  • Breakfast at Casa Azul: the model called search_guide('Casa Azul breakfast hours') on its own and answered 7:30 to 10:30, citing [g0]. It also cited [g2], the unrelated second passage it had retrieved, which the check allows because it was retrieved.
  • A day of buses in Kyoto: the model first described the search in text, got one correction, then called the tool and answered 900 JPY, citing the passages it retrieved.
  • 15 plus 27: answered 42 directly, with no search.

So the final answers were right and grounded, but not because the small model behaved perfectly. Code caught its mistakes. With a larger model the corrections fire less often; the checks cost nothing when they do not fire, so keep them.

Animation: A citation must point at a passage that search_guide actually returned. Invented ones are flagged, then retrieval runs in code.

What the checks can and cannot catch

check_answer catches two specific failures: a described instead of called tool, and citations to passages that were never retrieved. It does not prove that the answer matches the passage it cites. A model could retrieve [g0], cite it, and still state the wrong hours.

Stronger options, in increasing cost:

  • Quote check: require the answer to quote key numbers, then check that each number appears in a cited passage. Cheap and catches many invented figures.
  • Second model call as a judge: ask a model whether each claim in the answer is supported by the cited passages. Costs an extra call; lesson 14 discusses this style of check in evals.
  • Structured answers: ask for {"answer": ..., "quotes": [...]} with the structured outputs from lesson 5, then verify each quote is a substring of a retrieved passage.

Classic RAG or agentic RAG?

Classic RAGAgentic RAG
When it searchesevery requestwhen the model decides
Queriesthe user's question as iswritten by the model, can be refined
Model callsusually oneone or more per question
Failure modeirrelevant passages on unrelated questionsskipping the search and answering from memory
Control in codesimpleneeds checks like check_answer

The fallback in rag_agent.py is classic RAG: retrieve in code, then generate. That is a useful pattern in itself. Agentic RAG first, with classic RAG as the safety net, gives the flexibility of the agent with a floor on answer quality.

Common mistakes

  • Asking for "I do not know" without requiring a search first. Small models take the easy exit.
  • Short numeric citation ids that the model can produce without retrieving anything.
  • Trusting citations. Check that cited passages were actually retrieved in this run.
  • Tool descriptions that do not name the topics. The model cannot route to a tool it does not know covers the question.
  • Huge chunks. Retrieval returns a whole chunk; if a chunk is a full chapter, the useful sentence gets buried and the context fills up.

What to try next

  • Ask "What does the Blue Card cover?" and "Which hotel lends umbrellas?" and check the citations.
  • Ask a question the guide cannot answer, such as "Is there a gym at Casa Azul?", and see whether the model admits the guide does not say.
  • Set max_corrections=0 to see how often the fallback is needed with your model.
  • Add the quote check: extract numbers from the answer with a regex and verify each one appears in a retrieved passage.

Module 3 is done: the agent manages its context, remembers across sessions, and looks things up when it needs to. Module 4 is about control: how the agent plans multi step tasks, when it should stop, and when to split work between several agents.

Sources