DS DevShelfHub Projects · AI tools
Tutorials / RAG & Vector DBs / Advanced Techniques
RAG Pipeline Intermediate · 16 min read Page 9 of 23

Advanced Techniques

By DevShelfHub

Query expansion, recursive retrieval, knowledge graphs, agentic RAG, and self-reflection for production systems.

Series progress9 / 23
Advanced RAG Techniques — RAG pipeline tutorial

Overview

Basic RAG — retrieve top-K chunks and pass them to an LLM — works well for simple factual Q&A over well-structured documents. It starts failing when questions are ambiguous, when answers span multiple documents, when the LLM needs to reason iteratively, or when your data changes faster than you can re-index. Advanced techniques address each of these failure modes individually.

Recursive retrieval handles long documents by indexing summaries first and drilling into relevant sections on demand. Agentic RAG replaces the fixed retrieve-once loop with a reasoning agent that can retrieve, analyze gaps in its knowledge, and query again before answering. Self-reflection adds a verification pass after generation so hallucinations are caught internally rather than reaching users. Knowledge graphs let the retriever follow entity relationships rather than relying purely on embedding similarity. Adaptive retrieval dynamically adjusts how many documents to fetch based on estimated query complexity.

When adopting these techniques, match the solution to the actual failure mode you observe. If retrieval precision is already high but hallucinations persist, self-reflection and stronger system prompts will help more than adding retrieval complexity. If the right documents are indexed but ranked poorly, reranking and hybrid search are the right levers. Start simple and add complexity only when the data shows you need it.

1. Recursive Retrieval & Summarization

When a single document is too long, retrieve its summary first, then retrieve relevant chunks within it.

Python
Step 1: Index summaries (small)
summaries = [
  {"id": "doc1_summary", "summary": "About tax deductions...", "source_doc": "doc1"},
  ...
]

Step 2: Search summaries
top_summaries = vector_db.search(query_embedding, k=5)

Step 3: Retrieve chunks from relevant docs
relevant_chunks = []
for summary in top_summaries:
    source_doc = summary.source_doc
    chunks = db.query(source_doc, k=10)
    relevant_chunks.extend(chunks)

Result: Top 5 most relevant documents, with best chunks from each.

2. Agentic RAG (Tool Use & ReAct)

Instead of retrieving and answering, let the LLM decide: should I retrieve more docs? Search web? Use a tool?

YAML
agent = create_agent(
    tools=[
        {"name": "search_documents", "description": "Search internal docs"},
        {"name": "search_web", "description": "Search internet"},
        {"name": "query_database", "description": "Query structured data"}
    ],
    llm=gpt4
)

# LLM decides which tool to use
response = agent.run(
    "What's the latest COVID guidance AND historical data?"
)

# Agent logic:
# 1. User asks question
# 2. LLM decides to use "search_documents" + "search_web"
# 3. Executes both tools
# 4. Combines results
# 5. Generates final answer

Best for: Complex questions, multi-step reasoning, uncertain data freshness.

3. Self-Reflection & Verification

Have the LLM verify its own answer against retrieved docs. Catch hallucinations before returning.

PYTHON
Step 1: Generate answer
answer = llm.generate(query, retrieved_docs)

Step 2: Self-verify
verification_prompt = f"""
You just gave this answer: {answer}

Does it match the retrieved documents? If not, correct it.
Documents: {retrieved_docs}
"""

verified = llm.generate(verification_prompt)

Step 3: If confidence low, retrieve more
if verified.confidence < 0.7:
    more_docs = retrieve(query, k=10)
    answer = llm.generate(query, more_docs + retrieved_docs)

return answer

4. Knowledge Graphs for Structured Retrieval

For highly structured data, use knowledge graphs instead of pure semantic search.

Example: Medical RAG

Instead of: "What treatments work for condition X?"

Use graph: Disease X → Treatments → [A, B, C] → Side Effects

Tools: Neo4j, TigerGraph, or LLMs with graph reasoning (Graph RAG pattern)

When to use: Highly interconnected data, entity-based reasoning, compliance domains

5. Adaptive Retrieval (Knowing When to Stop)

Don't always retrieve fixed K documents. Stop when confident you have enough.

PYTHON
def adaptive_retrieve(query, max_docs=20):
    retrieved = []
    confidence = 0
    k = 5

    while confidence < 0.8 and len(retrieved) < max_docs:
        batch = vector_db.search(query, k=k)
        retrieved.extend(batch)

        # Compute confidence: diversity + relevance
        unique_topics = len(set(doc.topic for doc in retrieved))
        avg_score = sum(doc.score for doc in retrieved) / len(retrieved)
        confidence = (unique_topics / k) * avg_score

        k = min(k + 5, 20)  # Increase batch size

    return retrieved[:max_docs]

Benefit: Reduces costs, faster for simple queries, better UX for complex queries.

Notes

Reranking adds 50–200 ms per query

Cross-encoder rerankers score each candidate document jointly with the query through a full forward pass, which is slower than bi-encoder similarity by design. Measure the P95 latency impact on your specific hardware before enabling reranking in production. A lighter bi-encoder re-scorer (sorting by a second embedding model) can recover most of the quality gain at a fraction of the latency cost for latency-sensitive use cases.

Agentic loops must have a hard iteration cap

Without a max_iterations guard, a ReAct agent can loop through repeated retrievals if the retriever returns slightly different results each run or the LLM keeps deciding "I need more information." Cap iterations at 5–10 and return a graceful "insufficient information" response rather than timing out mid-session or accumulating dozens of unbilled LLM calls.

Self-reflection roughly doubles LLM cost for that query

Each verification step is an extra LLM call on a prompt that already contains all retrieved documents. Measure your baseline hallucination rate using RAGAS faithfulness before enabling it. If faithfulness is already above 0.90, the marginal benefit may not justify doubling generation cost. Consider using a smaller model (GPT-3.5 or Claude Haiku) for the verification call and the primary model only for the main generation step.

Knowledge graphs need their own synchronization pipeline

Entity extraction and relationship tagging add a new data pipeline that must stay in sync with source documents. If a document changes, the graph must be updated too — a problem that does not exist with pure vector search. Evaluate the ongoing maintenance overhead before committing to a graph-based architecture for general-purpose RAG; the quality gain is largest for domains with richly structured entity relationships like medical or legal data.

Advanced RAG Techniques FAQ

What is query expansion in RAG?

Query expansion generates multiple phrasings of the user question using an LLM, then retrieves documents for all variants and merges the results. This improves recall for ambiguous or narrow queries.

How does cross-encoder reranking improve RAG?

A cross-encoder scores each retrieved document against the query jointly (not separately), producing more accurate relevance scores than bi-encoder retrieval alone. The top-K documents after reranking are passed to the LLM.

What is recursive retrieval in RAG?

Recursive retrieval uses smaller index chunks to locate relevant sections, then fetches their parent (larger) chunks for the LLM prompt. This balances precision in search with sufficient context for generation.

What is agentic RAG?

Agentic RAG gives the LLM tools to call retrieval multiple times in a reasoning loop. Instead of one retrieval step, the agent can query, analyze results, refine its question, and query again before answering.

When should I use hybrid dense-sparse search?

Hybrid search combines dense (semantic) and sparse (keyword) retrieval, which outperforms either alone on most benchmarks. It is especially useful when users submit keyword queries alongside natural-language questions.