Module 4 · Next-generation RAG architectures

Agentic RAG and retrieval tool routing

6 min read

A classic RAG pipeline searches once, before answering, with the question as is. If the search misses, the answer is bad, and nothing can make up for the error. In an agentic RAG, search becomes a tool the model uses when it sees fit: it chooses its query, reads the results, searches again with other words or in another category, reads a full article, then answers. This lesson builds that agent with Claude and discusses its costs.

From pipeline to agent

PipelineAgent
SearchesOne, alwaysZero, one or several, decided by the model
QueryThe question (or its rewrite)Phrased by the model, one per sub-topic
Multi-source questionsOne search for two topicsOne search per topic, naturally
LatencyPredictableVariable (several round trips)
CostOne generation callSeveral calls, with a growing history

The tools

Prism gives the agent two tools: a hybrid search, filterable by category, and reading a full article.

{
    "name": "search_help_center",
    "description": "Recherche hybride (sens + mots-clés) dans le centre d'aide Nimbus. "
                   "Renvoie au plus 5 passages avec l'identifiant de leur article. "
                   "Formule une requête courte et précise ; relance avec d'autres mots "
                   "si les résultats ne répondent pas.",
    "input_schema": {...},
},

The tool description is a prompt: it tells the model what the tool does, what it returns, and how to use it well ("a short, precise query", "retry with other words if the results do not answer"). The category parameter is an enumeration: the model cannot invent a nonexistent category. And the filter is applied by the code, not by the model:

if name == "search_help_center":
    category = args.get("category")
    where = (lambda c: c.category == category) if category else None
    hits = self.retriever.search(args["query"], 5, where)

This is also where access control belongs (lesson 2.3): the tool filters according to the authenticated user, never according to an argument supplied by the model.

The loop

for turn in range(1, self.max_turns + 1):
    response = client.messages.create(model=config.MODEL, max_tokens=4096, system=SYSTEM,
                                      tools=TOOLS, messages=messages)
    llm.USAGE.add("agent", response.usage)
    # La réponse complète (réflexion, texte, appels d'outils) retourne dans l'historique
    messages.append({"role": "assistant", "content": response.content})
    if response.stop_reason != "tool_use":
        result.answer = "".join(b.text for b in response.content if b.type == "text").strip()
        result.turns = turn
        return result
    results = []
    for block in response.content:
        if block.type == "tool_use":
            result.tool_calls.append((block.name, dict(block.input)))
            results.append({"type": "tool_result", "tool_use_id": block.id,
                            "content": self._run_tool(block.name, block.input)})
    messages.append({"role": "user", "content": results})

Three details matter:

  • The full content of each response goes back into the history, not just the text: tool call blocks (and thinking blocks, if any) must be sent back as is.
  • All tool calls of a turn receive their result in a single message, each linked by its tool_use_id. The model can launch two searches in parallel, one per topic.
  • The loop is bounded (max_turns = 6): beyond that, the agent hands over with a clear message instead of looping indefinitely and burning tokens.

The system prompt

SYSTEM = """Tu es l'assistant du support de la boutique Nimbus. Utilise les outils pour trouver
l'information avant de répondre : ne réponds jamais de mémoire, car les règles de la boutique te
sont inconnues. Si une question a plusieurs volets, cherche chacun. Cite les identifiants d'articles
utilisés entre crochets. Si l'information est introuvable après deux ou trois recherches, dis-le
simplement."""

(Use the tools before answering: never answer from memory, because the store's rules are unknown to you. If a question has several parts, search for each. Cite the article identifiers in brackets. If the information cannot be found after two or three searches, say so simply.) Each sentence addresses an observed failure: answering from memory with "plausible" rules from another store, handling only one part of a compound question, searching forever. The prompt explains why ("the store's rules are unknown to you"): a model that understands the reason generalizes better than a model following a prohibition.

What the agent does on a compound question

For "What is the supplier of the Lift desk and how long are its motors under warranty?", the agent launches one search per part — the decomposition of lesson 3.3, done naturally, with no dedicated step. In offline mode, Prism's fake agent reproduces this behavior (two searches, answer on the third turn) to check the loop's mechanics; with Claude, the quality of the queries and of the answer becomes real.

The cost

Each turn sends the whole history back to the model: the question, previous calls, every passage already read. An agent that runs three searches of five passages consumes far more input tokens than a pipeline that runs one. To keep it under control:

  • return compact results (identifier, title, passage text; no useless metadata);
  • limit the number of passages per search and the number of turns;
  • use prompt caching on the stable start of the conversation (system, tools);
  • route: a pipeline for simple questions, the agent only for complex questions or when the pipeline fails.

When to prefer the agent

The agent is justified when questions are varied and often compound, when several sources of different kinds are available (help center, order database, catalog in SQL), or when a missed first search must be recoverable. For a stream of simple, repetitive questions, a hybrid pipeline with re-ranking is faster, cheaper and more predictable.

Key takeaways

  • Agentic RAG turns search into a tool: the model decides when, how and how many times to search.
  • Tool descriptions are prompts; filters and permissions are applied by the code.
  • The loop sends back each response's full content, answers every tool call of a turn, and stops after a maximum number of turns.
  • The history grows with every turn: compact results, limited turns, prompt caching.
  • Route: a pipeline for simple questions, the agent for complex ones.

Practice

  1. With an API key, run the agent on the six multi-source questions and count the searches and tokens consumed.
  2. Add an order_status(order_id) tool that reads a fictional order, and ask a question combining an order and the return policy.
  3. Implement a router: pipeline if the re-ranker's best score exceeds a threshold, agent otherwise.

Resources