AI Hints
Home›RAG Tutorial›Conversations and Agents
RAG · Lesson 84 of 120

Agentic RAG

Retrieval as a tool.

⏱ 2 min read▶ Video at 1:22:48🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

So far, our code decides when to search. In agentic RAG, the model decides. Search becomes a tool. The agent can skip it, call it once, or call it several times for a complex question.

Agentic RAG
From the video: Agentic RAG
  • The model decides
  • Search is a tool
  • Zero, one, or many searches

An agent with a search tool

Search help centre is a tool. Its docstring tells the agent what it does. Create agent gives the model that tool. We ask a question with two parts. Run it. The agent searched more than once, and answered both parts.

agentic_rag.pypython
from langchain.agents import create_agent
from langchain.tools import tool
from rag_kit import load_docs, make_chunks, Index

index = Index(make_chunks(load_docs()))

@tool
def search_help_centre(query: str) -> str:
    """Search the Northwind help centre."""
    return "\n\n".join(c["text"] for s, c in index.search(query))

agent = create_agent("google_genai:gemini-flash-lite-latest", tools=[search_help_centre],
                     system_prompt="Answer from the help centre only. Be brief.")
q = "How much is a Basic service, and when is the York shop open?"
out = agent.invoke({"messages": [{"role": "user", "content": q}]})

print("searches:", len([m for m in out["messages"] if m.type == "tool"]))
print(out["messages"][-1].text)
Output
searches: 2
A Basic service costs £49.

The York shop (at 22 Micklegate) is open Monday to Saturday from 9:00 am to 5:30 pm, and
is closed on Sundays.
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss  # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter

def load_docs(folder="data/rag/northwind"):
    return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]

def make_chunks(docs, size=300, overlap=50):
    splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
    return [{"source": d["source"], "text": t.replace("\n", " ")}
            for d in docs for t in splitter.split_text(d["text"])]

embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")

def embed(texts):
    return embedder.encode(texts, normalize_embeddings=True)

class Index:
    def __init__(self, chunks):
        self.chunks = chunks
        self.vectors = embed([c["text"] for c in chunks])

    def search(self, query, k=3):
        scores = self.vectors @ embed([query])[0]
        top = np.argsort(-scores)[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]
Also uses llm.py
from langchain.chat_models import init_chat_model

llm = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)

PROMPT = """Answer the question using only the context below.
If the answer is not in the context, say "I don't know".

Context:
{context}

Question: {question}"""

def answer(question, chunks):
    context = "\n\n".join(f"[{c['source']}] {c['text']}" for c in chunks)
    return llm.invoke(PROMPT.format(context=context, question=question)).text.strip()

Chain or agent?

A RAG chain always searches once. It's fast and predictable. An agent searches when it needs to, as often as it needs to. It handles harder questions, but costs more, and is less predictable.

RAG chain

  • One searchFastPredictable

Agentic RAG

  • Searches as neededHandles hard questionsCosts more

Summary

In agentic RAG, the model decides when and how often to search. Next, corrective RAG.

Key takeaways
  • Search as a tool
  • Agent decides
  • Several searches
Next up: Corrective RAG — grade, then retry