Single-shot RAG works until it doesn't. You embed a question, retrieve the top-k chunks, stuff them into a prompt, and generate an answer. For straightforward factual lookups — "what's our refund policy?" — this is fine. But ask a question that requires synthesis across multiple documents, or one where the first retrieval misses the mark, and the architecture falls apart silently. The answer looks confident. It's just wrong.
Agentic RAG fixes this by giving the LLM control over retrieval. Instead of one blind fetch, an agent decides what to retrieve, evaluates whether the results are sufficient, and iterates until it has enough context to answer well. The model becomes the orchestrator, not just the generator.
This post walks through building an agentic RAG system using Google's Agent Development Kit (ADK), released at Google I/O 2025. We'll use Gemini 2.5 Flash for reasoning, function calling for tool orchestration, and a vector store for retrieval. The result is a system that handles multi-hop questions, decomposes complex queries, and knows when to say "I don't have enough information."
Why single-shot RAG breaks
Consider this question over a technical documentation corpus: "Compare the authentication mechanisms in v2 and v3 of the API, focusing on what changed for OAuth clients."
Single-shot RAG embeds this query, retrieves chunks that mention authentication, and hopes the top-k results contain both v2 and v3 information plus OAuth-specific details. In practice, the retriever returns chunks mostly about v3 (because it's more recent and better-represented in the corpus), gives a partial answer about v2, and the user gets a plausible but incomplete comparison.
An agentic approach decomposes this into sub-retrievals: (1) find v2 authentication docs, (2) find v3 authentication docs, (3) find OAuth-specific migration notes. Each retrieval is targeted. The agent evaluates each result set for relevance before proceeding.
Architecture
┌─────────────────────────────────────────────────────┐
│ ADK Agent (Gemini 2.5 Flash) │
│ │
│ ┌──────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ retrieve │ │ evaluate_ctx │ │ synthesize │ │
│ │ _chunks │ │ │ │ │ │
│ └──────────┘ └──────────────┘ └──────────────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ Vector Store Self-Reflection Final Answer │
└─────────────────────────────────────────────────────┘The agent has three tools:
retrieve_chunks— queries the vector store with a specific search stringevaluate_context— the agent judges whether retrieved chunks answer the questionsynthesize— generates the final answer from accumulated context
The key insight: the agent calls retrieve_chunks multiple times with different queries based on what it's learned so far. Each call is a targeted retrieval, not a blind keyword match.
Setting up ADK
Install the Agent Development Kit:
pip install google-adk google-genaiADK agents are Python classes with a model, instructions, and tools. Here's the skeleton:
from google.adk import Agent, tool
from google import genai
client = genai.Client()
EMBED_MODEL = "gemini-embedding-2"
GEN_MODEL = "gemini-2.5-flash"Building the retrieval tool
The retrieval tool wraps your vector store. For this example we'll use a NumPy index (same pattern as the multimodal RAG article), but this works identically with pgvector, Pinecone, or Vertex AI RAG Engine.
import numpy as np
# Pre-built index: {"texts": [...], "vectors": np.array, "metadata": [...]}
INDEX = load_index("knowledge_base.pkl")
@tool
def retrieve_chunks(query: str, top_k: int = 5) -> list[dict]:
"""Retrieve relevant text chunks from the knowledge base.
Args:
query: A specific search query targeting the information needed.
top_k: Number of chunks to retrieve.
Returns:
List of chunks with text and metadata.
"""
result = client.models.embed_content(
model=EMBED_MODEL,
contents=f"search_query: {query}",
)
q_vec = np.array(result.embeddings[0].values, dtype=np.float32)
scores = INDEX["vectors"] @ q_vec
top_idx = np.argpartition(-scores, top_k)[:top_k]
top_idx = top_idx[np.argsort(-scores[top_idx])]
return [
{
"text": INDEX["texts"][i],
"score": float(scores[i]),
"source": INDEX["metadata"][i].get("source", "unknown"),
}
for i in top_idx
]The docstring matters — ADK uses it to tell the model what the tool does and how to call it. Be specific about what query should contain.
The evaluation tool
This is where agentic RAG diverges from naive RAG. The agent evaluates whether its retrieved context is sufficient before generating an answer:
@tool
def evaluate_context(
question: str,
retrieved_context: list[str],
) -> dict:
"""Evaluate whether the retrieved context is sufficient to answer the question.
Args:
question: The original user question.
retrieved_context: List of retrieved text chunks.
Returns:
Assessment with 'sufficient' boolean and 'missing' description.
"""
context_block = "\n---\n".join(retrieved_context)
response = client.models.generate_content(
model=GEN_MODEL,
contents=f"""Evaluate whether the following context is sufficient to
fully answer the question. Be strict — if key aspects are missing, say so.
Question: {question}
Context:
{context_block}
Respond in JSON:
{{"sufficient": true/false, "missing": "description of what's missing or empty string"}}""",
config={"response_mime_type": "application/json"},
)
import json
return json.loads(response.text)Assembling the agent
Now we wire it together as an ADK agent. The instruction prompt tells the model how to use its tools in a multi-step retrieval strategy:
rag_agent = Agent(
name="rag_researcher",
model=GEN_MODEL,
instruction="""You are a research agent that answers questions using a knowledge base.
Your workflow:
1. Analyze the question. If it's complex, decompose it into 2-3 specific sub-questions.
2. For each sub-question, call retrieve_chunks with a targeted query.
3. After retrieval, call evaluate_context to check if you have enough information.
4. If context is insufficient, retrieve again with a refined query based on what's missing.
5. Once you have sufficient context, synthesize a comprehensive answer.
Rules:
- Never answer from memory alone. Always retrieve first.
- Use specific, targeted queries — not the raw user question verbatim.
- Maximum 4 retrieval rounds. If still insufficient, answer with what you have and note gaps.
- Cite sources when possible.""",
tools=[retrieve_chunks, evaluate_context],
)Running the agent
ADK provides a Runner that manages the agent's execution loop:
from google.adk import Runner, InMemorySessionService
session_service = InMemorySessionService()
runner = Runner(agent=rag_agent, session_service=session_service)
async def ask(question: str) -> str:
session = await session_service.create_session(agent_name="rag_researcher")
response = await runner.run(
session_id=session.id,
user_message=question,
)
return response.textThe runner handles the tool-call loop automatically. The agent calls tools, receives results, reasons about next steps, and continues until it generates a final text response.
What happens at runtime
For our comparison question about API v2 vs v3 authentication, the agent's execution trace looks like:
Step 1: Decompose → "v2 API authentication mechanism", "v3 API authentication mechanism", "OAuth client migration v2 to v3"
Step 2: retrieve_chunks("v2 API authentication mechanism") → 5 chunks about basic auth, token format
Step 3: retrieve_chunks("v3 API authentication mechanism") → 5 chunks about OAuth2, PKCE flow
Step 4: retrieve_chunks("OAuth client migration v2 to v3") → 5 chunks about breaking changes
Step 5: evaluate_context(question, all_15_chunks) → {"sufficient": true, "missing": ""}
Step 6: Generate comprehensive comparison citing all sourcesTotal: 3 retrieval calls, 1 evaluation, 1 generation. The naive approach would have done 1 retrieval and hoped for the best.
Adding Grounding with Google Search
For questions where your knowledge base might be stale or incomplete, ADK supports grounding with Google Search as a built-in tool:
from google.adk.tools import google_search
grounded_agent = Agent(
name="grounded_researcher",
model=GEN_MODEL,
instruction="...",
tools=[retrieve_chunks, evaluate_context, google_search],
)The agent can now choose between your private knowledge base and the open web. For a question like "what's new in v4?" — which your docs don't cover yet — the agent falls back to web search and returns results with citations.
Production considerations
Cost control. Each agent step is a full LLM call. A 4-step retrieval workflow costs 4x a single-shot RAG call. Mitigations: use Gemini 2.5 Flash (not Pro) for the agent loop, set max_steps in the runner, and cache embeddings aggressively.
Latency. Sequential tool calls add round-trip time. For real-time chat, consider a two-tier approach: fast single-shot RAG for simple queries, escalate to agentic RAG only when confidence is low or the query is complex.
Evaluation. Track three metrics: (1) retrieval recall — are the right chunks being found? (2) answer faithfulness — is the answer grounded in retrieved context? (3) step efficiency — how many retrieval rounds does the agent need on average? Use the RAGAS framework with Gemini as the judge.
Failure modes. The agent can loop retrieving the same irrelevant chunks with slightly different queries. Guard against this by tracking seen chunks and injecting "you've already seen these results" into the evaluation context.
When to use agentic RAG vs. naive RAG
| Question type | Approach |
|---|---|
| Simple factual lookup | Naive RAG (single-shot) |
| Multi-document synthesis | Agentic RAG |
| Comparison questions | Agentic RAG with decomposition |
| Questions requiring current info | Agentic + Google Search grounding |
| High-stakes answers needing verification | Agentic with self-evaluation |
The overhead of agentic RAG is real — more tokens, more latency, more cost. Don't use it for everything. Use it for the queries where single-shot RAG demonstrably fails, and build a routing layer that escalates appropriately.
Conclusion
Agentic RAG isn't a new model or a new embedding technique — it's a control-flow pattern. The model decides what to retrieve, evaluates the results, and iterates. Google's ADK makes this pattern concrete with a clean tool-use framework, and Gemini 2.5 Flash provides the reasoning capability to drive the loop effectively.
The complete code for this article is available as a Colab notebook. Next in this series: evaluating RAG pipelines systematically using Gemini as an LLM judge.
Further reading: