Skip to content
AgenticAIWiki
  1. Learn
  2. Part 4
  3. 24. Agentic RAG
  4. 24.1

Lesson 24.1 · 1 of 3 · 4 min read · Reviewed 24 Nov 2026

Retrieval as a tool

By the end, you can

  • Expose retrieval as a tool an agent can call.
  • Let the agent decide when and what to search.

From pipeline to tool

naive RAG:     question --> retrieve once --> answer
agentic RAG:   question --> model decides
                             |-- no search needed --> answer
                             |-- search(q1) --> read --> search(q2) --> answer

A search tool definition

{
  "name": "search_docs",
  "description": "Search the company knowledge base. Returns up to 5 passages with ids. Use specific terms; search again with different terms if results don't answer the question.",
  "input_schema": {
    "type": "object",
    "properties": {
      "query": {"type": "string"},
      "doc_type": {"type": "string", "enum": ["policy", "manual", "faq", "any"]},
      "after": {"type": "string", "description": "Only documents updated after this date (YYYY-MM-DD)"}
    },
    "required": ["query"]
  }
}

Result format

Return short passages with ids and titles, not whole documents. Include “no results” clearly, so the agentAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done. can try another query (chapter 34).

Guardrails

  • Cap the number of searches per question (chapter 42).
  • Enforce access filters in the tool, not in the prompt.
  • Ask the agent to cite passage ids in its answer.

Claude’s built-in web search toolWeb search tool: A built-in tool that lets the model search the web and cite results. works the same way for the public web (chapter 37).

Key points

  • In agentic RAG, search is a tool: the model decides whether to search, what query to use, and whether to search again.
  • This handles questions that need no search, one search, or several refined searches.
  • Good search tool design: clear description, filters as parameters, compact results with source ids.
Hands-on labRuns in the Playground

Expose search as a guarded tool

Build a search tool an agent can call, with access filters, a search cap and a clear no-results message enforced in code.

You will have: A search_docs() tool and a toy agent loop that shows no search, one search, and a blocked document type.

Steps

  1. Read the knowledge base: each passage has a doc_type and an id.
  2. Write search_docs(session, query, doc_type): filter by the user's allowed types from the session, return at most 3 short passages with ids.
  3. Return a clear 'no results' message when nothing matches, so the agent can rephrase.
  4. Cap searches at 3 per question and run the three sample questions.

Done when

  • 'Thanks!' triggers no search.
  • An intern's search for legal documents returns no legal passages.
  • A missing topic returns the no-results message, not an empty list.

Open in the Playground No API key needed.

Starter code (Python)
KB = [
    {"id": "hr-2", "type": "policy", "text": "Annual leave: 25 days per year, up to five carried over."},
    {"id": "fin-1", "type": "finance", "text": "Expenses must be claimed within 30 days."},
    {"id": "leg-4", "type": "legal", "text": "Confidential: settlement terms for the 2025 dispute."},
]
ROLES = {"intern": {"policy", "finance"}, "counsel": {"policy", "finance", "legal"}}

class Session:
    def __init__(self, role):
        self.role = role
        self.searches = 0

def search_docs(session, query, doc_type="any"):
    # TODO: cap at 3 searches per session, return "search limit reached" after that
    # TODO: allowed types come from ROLES[session.role], never from the model
    # TODO: match passages containing any query word; return "no results for: <query>" if none
    return []

def toy_agent(session, question):
    if question.lower().startswith("thanks"):
        return "You're welcome!", []
    return "answer", [search_docs(session, question)]

for role, q in [("intern", "Thanks!"), ("intern", "settlement terms"), ("intern", "parking permits")]:
    print(role, "|", q, "|", toy_agent(Session(role), q))
Show a solution
import re

KB = [
    {"id": "hr-2", "type": "policy", "text": "Annual leave: 25 days per year, up to five carried over."},
    {"id": "fin-1", "type": "finance", "text": "Expenses must be claimed within 30 days."},
    {"id": "leg-4", "type": "legal", "text": "Confidential: settlement terms for the 2025 dispute."},
]
ROLES = {"intern": {"policy", "finance"}, "counsel": {"policy", "finance", "legal"}}
MAX_SEARCHES = 3

class Session:
    def __init__(self, role):
        self.role = role
        self.searches = 0

def search_docs(session, query, doc_type="any"):
    if session.searches >= MAX_SEARCHES:
        return "search limit reached"
    session.searches += 1
    allowed = ROLES[session.role]
    words = set(re.findall(r"[a-z]+", query.lower()))
    hits = [p for p in KB if p["type"] in allowed and (doc_type == "any" or p["type"] == doc_type)
            and words & set(re.findall(r"[a-z]+", p["text"].lower()))]
    if not hits:
        return f"no results for: {query} (try other terms)"
    return [f"[{p['id']}] {p['text'][:60]}" for p in hits[:3]]

def toy_agent(session, question):
    if question.lower().startswith("thanks"):
        return "You're welcome!", []
    return "answer", [search_docs(session, question)]

for role, q in [("intern", "Thanks!"), ("intern", "settlement terms"), ("counsel", "settlement terms"), ("intern", "parking permits")]:
    reply, searches = toy_agent(Session(role), q)
    print(f"{role} | {q} | searches: {len(searches)} | {searches[0] if searches else reply}")
s = Session("intern")
print("after 4 searches:", [search_docs(s, "leave") for _ in range(4)][-1])
Quick checkWhat's the main advantage of giving an agent a search tool instead of always retrieving once?
How sure are you?
Pick an answer and how sure you are