Agentic RAG systems are powerful but introduce new failure modes that don't exist in traditional RAG pipelines. While standard RAG fails in predictable ways (poor retrieval, hallucination, context limits), agentic systems can fail in more complex ways: the agent gets stuck in loops, chooses wrong tools, accumulates too much context, or hallucinates tool invocations entirely.
This post shares hard-won debugging techniques from running Agentic RAG in production. We cover the most common failure patterns, how to detect them early, and concrete mitigation strategies you can implement today.
The Infinite Loop Problem
The most common agentic RAG failure is the infinite loop. The agent keeps taking actions but never reaches a conclusion. This typically happens when:
- The synthesis tool never gets called - The planner keeps thinking it needs more information
- Redundant search cycles - The agent searches for the same thing repeatedly with slight query variations
- Conditional branches that never resolve - The agent evaluates a condition but the state never changes enough to flip the branch
Detection
Log every agent step with iteration number, action type, and a hash of the tool parameters. If you see the same (action, parameter_hash) pair more than twice, you have a loop.
def detect_loop(history, max_repeats=2):
seen = {}
for step in history:
key = (step["action"], hash(str(step["parameters"])))
seen[key] = seen.get(key, 0) + 1
if seen[key] > max_repeats:
return True, key
return False, None
Mitigation
- Hard iteration limits - Cap at 5-7 iterations maximum
- Progress heuristics - Require each step to add new unique content to accumulated context
- State deduplication - Track (tool, parameters) pairs and skip if already executed
- Critique step - Every N iterations, prompt the model: "Have you made progress? Should you synthesize now?"
Planning Errors: Wrong Tool, Wrong Parameters
Agents frequently choose the wrong tool or pass malformed parameters. Common patterns:
- Calling
semantic_searchwhenkeyword_searchwould be more precise (or vice versa) - Passing a
doc_idtoanalyze_documentthat doesn't exist in the retrieved results - Forgetting required parameters like
expressionforcalculate
Detection
Validate tool outputs against expected schemas. Log tool selection reasoning alongside the choice. If the agent provides reasoning but the tool fails validation, that's a planning error.
Mitigation
- Few-shot examples in planning prompt - Show 3-5 examples of correct tool selection for common query types
- Parameter validation with descriptive errors - Return structured error objects that the agent can reason about
- Tool registry with schemas - Enforce JSON Schema validation on all tool inputs
- Self-correction loop - On tool error, feed the error back to the planner with "Try again with corrected parameters"
Context Overflow
Agentic RAG accumulates context across iterations. Without management, this exceeds model context windows.
Detection
Track token count of accumulated_context at each step. Log when it exceeds 70% of the model's context window.
Mitigation
- Summarization checkpoint - Every 2-3 iterations, summarize older context into a condensed form
- Sliding window - Keep only the most recent N tool results in full; summarize the rest
- Relevance filtering - Before each planning step, score context chunks against the original query and drop low-relevance ones
- Token budget per phase - Reserve tokens: 20% for planning prompt, 60% for context, 20% for synthesis
Tool Hallucination
The agent invents tools that don't exist: web_search, database_query, send_email, etc. This happens when the planning prompt doesn't clearly constrain the tool set.
Detection
Maintain a strict tool registry. Any tool call not in the registry is a hallucination. Log these separately from execution errors.
Mitigation
- Explicit tool listing in prompt - Include the exact tool names and signatures in every planning prompt
- Registry enforcement - Reject unknown tools at the execution layer with a clear error
- Negative examples - Add "DO NOT USE" examples to the planning prompt showing common hallucinated tools
Cascading Errors
An early mistake (wrong document retrieved) compounds through subsequent steps. The agent builds a chain of reasoning on faulty premises.
Detection
Implement checkpoint verification: after key milestones (e.g., after retrieving core documents), prompt a verification step: "Does the retrieved information actually answer the sub-question?"
Mitigation
- Checkpoint prompts - Every 2-3 steps, insert a verification step
- Alternative retrieval - If verification fails, trigger a re-search with modified query
- Grounding checks - Before synthesis, verify all cited facts exist in retrieved documents
Observability Stack for Debugging
You can't fix what you can't see. Essential logging for every agent run:
{
"session_id": "uuid",
"query": "user query",
"steps": [
{
"iteration": 1,
"action": "semantic_search",
"parameters": {"query": "...", "top_k": 5},
"reasoning": "Need to find...",
"result": {"status": "success", "result_count": 5, "tokens": 1200},
"latency_ms": 1200
}
],
"final_answer": "...",
"total_iterations": 4,
"total_tokens": 8500,
"total_latency_ms": 4200,
"user_feedback": null
}
Build a simple dashboard showing:
- Iteration distribution across queries
- Tool selection frequency and error rates
- Average tokens per iteration
- Loop detection alerts
- User satisfaction correlation with iteration count
Quick Diagnostic Checklist
When an agentic RAG query fails, check in order:
- Iteration count - Hit max iterations? → Increase limit or improve synthesis trigger
- Tool errors - Any failed tool calls? → Check parameter validation and error messages
- Context size - Exceeded token limit? → Add summarization checkpoint
- Loop detection - Repeated (action, params)? → Add progress heuristic or state deduplication
- Planning quality - Reasoning trace shows confusion? → Add few-shot examples to planning prompt
- Grounding - Citations in final answer missing from retrieved docs? → Add grounding verification step
Start Simple
The best debugging strategy is preventing complexity you don't need. Start with:
- 2 tools: semantic_search + synthesize
- 3 iteration max
- No conditional logic, no multi-hop
Add one tool or capability at a time. Measure impact on task success rate and iteration count. Only add complexity when the data shows you need it.
Real-World Debugging Example
Consider a query: "Compare the Q3 2024 earnings of Microsoft and Google, focusing on cloud revenue growth."
The agent executes:
- Search: "Microsoft Q3 2024 earnings cloud revenue" → Finds Microsoft earnings release
- Analyze: Extract cloud revenue from Microsoft doc
- Search: "Google Q3 2024 earnings cloud revenue" → Finds Alphabet earnings release
- Analyze: Extract cloud revenue from Google doc
- Synthesize: Compare both
But suppose step 3 returns a blog post about Google Cloud rather than the earnings release. The agent extracts "strong growth" from the blog post instead of the actual percentage. Step 5 then compares Microsoft's 20% with Google's "strong growth" — a category error.
This cascading error would be caught by:
- Checkpoint after step 4: "Are both revenue figures concrete percentages?"
- Grounding check before synthesis: "Does 'strong growth' appear in the Google earnings document?"
Measuring Debugging Effectiveness
Track these metrics to validate your debugging improvements:
- Loop detection rate: How often does the loop detector fire?
- Self-correction success rate: After a tool error, how often does the agent recover?
- Iteration reduction: Average iterations before vs. after adding progress heuristics
- Grounding pass rate: Percentage of citations verified against source documents
This post draws on patterns from the Agentic RAG guide published on OpusBazaar. For the full architectural framework, see Agentic RAG: A Practical Framework for Adaptive Retrieval-Augmented Generation.