🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Advanced RAG: HyDE, Self-RAG and Adaptive Retrieval

đŸŸĸ Free Lesson

Advanced RAG: HyDE, Self-RAG and Adaptive Retrieval

The first version of any retrieval-augmented system is the same five lines: embed the question, take the top five chunks, paste them into a prompt. It works on the demo corpus and then degrades in ways that look identical from the outside — the answer cites nothing, cites the wrong document, or hedges when the evidence is right there. Advanced RAG is not a pile of exotic tricks; it is a disciplined attack on the specific stage where the pipeline lost the thread. Was the query misunderstood? Was the right passage never retrieved? Was it retrieved but outranked by noise? Did the generator have the evidence and still drift? Each answer points to a different intervention, and applying techniques by failure mode rather than by blog post is the difference between a system that improves and one that accretes complexity.

Why Naive Retrieval Plateaus

Users do not phrase questions the way documents are written. A support ticket says the app crashes on export; the runbook says memory allocation failure during serialization of large workspaces. Exact-term mismatch, abbreviation, and questions that require combining three passages all defeat a single similarity search. Meanwhile the chunking you shipped in week one silently determines what can ever be found: a policy split across two chunks loses its conditions, and a table caption separated from its rows loses its meaning.

The fix sequence matters. Correct the query and the corpus before adding model cleverness, because retrieval quality caps everything downstream. Only then add reranking and generation-time critique, which can rescue a near miss but cannot conjure a passage that was never in the candidate set.

Rewriting, Decomposition and HyDE

A query pipeline typically does four things before searching: resolve conversational references, rewrite the question in the vocabulary of the corpus, decompose multi-hop questions into sub-queries, and — when phrasing similarity is the problem — search with a hypothetical answer instead of the question itself. HyDE, hypothetical document embeddings, asks a model to write a plausible answer with no grounding, embeds that draft, and uses it as the probe. The fiction is discarded; what survives is vocabulary that matches how the corpus actually talks.

python
import json
import openai

client = openai.OpenAI()

def rewrite_query(question: str, history: list[str]) -> str:
    convo = "\n".join(history[-4:])
    r = client.chat.completions.create(
        model="gpt-4o-mini",
        temperature=0,
        messages=[
            {"role": "system", "content": (
                "Rewrite the latest user question as a standalone search query. "
                "Resolve pronouns, keep technical terms, drop pleasantries. "
                "Return only the query."
            )},
            {"role": "user", "content": f"Conversation:\n{convo}\n\nQuestion: {question}"},
        ],
    )
    return r.choices[0].message.content.strip()

def hyde_probe(question: str) -> str:
    r = client.chat.completions.create(
        model="gpt-4o-mini",
        temperature=0.7,
        messages=[
            {"role": "system", "content": (
                "Write a short passage that would answer the question. "
                "Use the terminology of technical documentation. "
                "Do not hedge. It does not need to be true."
            )},
            {"role": "user", "content": question},
        ],
    )
    return r.choices[0].message.content

def decompose(question: str) -> list[str]:
    r = client.chat.completions.create(
        model="gpt-4o-mini",
        temperature=0,
        response_format={"type": "json_object"},
        messages=[
            {"role": "system", "content": (
                "Split a multi-part question into the minimum independent "
                "sub-queries. Return JSON with 'sub_queries'. If the question "
                "is single-hop, return it unchanged."
            )},
            {"role": "user", "content": question},
        ],
    )
    return json.loads(r.choices[0].message.content)["sub_queries"]

q = "does the export limit apply to archived workspaces too?"
print("rewritten:", rewrite_query(q, ["why did my export fail?"]))
print("sub-queries:", decompose(q))

Rewriting pays off most on conversational interfaces and paraphrase-heavy traffic. HyDE helps when documents use domain jargon the user does not. Decomposition is worth its latency only for genuinely multi-hop questions, which you can detect from answer completeness rather than guessing.

Candidates, Scores and the Reranker

Vector similarity alone gives you one geometry for both recall and precision. Hybrid search fixes recall by combining sparse retrieval, which matches rare terms and identifiers exactly, with dense retrieval, which matches meaning; reciprocal rank fusion merges the two lists without needing to calibrate their incomparable scores. Reranker models then fix precision: a cross-encoder reads the query and each candidate jointly and scores relevance directly, which is far more accurate than comparing two independently produced vectors, and affordable because it runs on the small set that survived the first stage.

StageWhat it optimizesLatency costTypical lift
Dense retrievalSemantic recallLowBaseline
Sparse plus dense with fusionRare terms, identifiersLowNoticeable on technical corpora
Metadata filtersTenancy, recency, ACLLowCorrectness requirement
Cross-encoder rerankerPrecision in top kMediumLargest single-step gain
Diversity or deduplicationCoverage of distinct sourcesLowLong-form answers

A useful production default is thirty to fifty fused candidates reduced to four or six by a reranker, with hard metadata filters applied before anything runs — permissions are a filter, not a prompt instruction.

When the Model Checks Its Own Work

Retrieval can be perfect and the generator can still drift, so the last line of defense is a critique step that verifies the draft against the retrieved passages. The reliable version is specific: extract every factual claim, check whether a supporting span exists, and either attach a citation or drop the claim. Asking a model to rate its own answer holistically produces confident self-approval, which is exactly the failure you were trying to catch.

python
import json
import openai

client = openai.OpenAI()

CLAIM_CHECK = (
    "You are a fact verifier. Given CONTEXT passages and a CLAIM, decide if the "
    "CONTEXT supports, contradicts, or does not mention the claim. Return JSON "
    "with verdict and the supporting quote."
)

def verify_claim(claim: str, context: str) -> dict:
    r = client.chat.completions.create(
        model="gpt-4o-mini",
        temperature=0,
        response_format={"type": "json_object"},
        messages=[
            {"role": "system", "content": CLAIM_CHECK},
            {"role": "user", "content": f"CONTEXT:\n{context}\n\nCLAIM: {claim}"},
        ],
    )
    return json.loads(r.choices[0].message.content)

def grounded_answer(question: str, passages: list[str]) -> str:
    context = "\n\n".join(f"[{i + 1}] {p}" for i, p in enumerate(passages))
    draft_r = client.chat.completions.create(
        model="gpt-4o-mini",
        temperature=0,
        messages=[
            {"role": "system", "content": (
                "Answer using only the numbered passages. Cite as [n] after "
                "each sentence that comes from a passage. If the passages do "
                "not answer it, say you do not have that information."
            )},
            {"role": "user", "content": f"{context}\n\nQuestion: {question}"},
        ],
    )
    draft = draft_r.choices[0].message.content

    claims = [c.strip() for c in draft.split(". ") if len(c.strip()) > 25]
    kept = []
    for claim in claims:
        verdict = verify_claim(claim, context)
        if verdict.get("verdict") == "supported":
            kept.append(claim)
    return ". ".join(kept) or "I could not ground an answer in the provided passages."

print(grounded_answer("What is the export retention window?", ["..."]))

Self-RAG style training goes further, teaching a model to emit retrieval tokens deciding whether a passage is needed at all, and critique tokens judging whether one is useful. The practical lesson generalizes even if you never train anything: make the model produce evidence judgments as structured output instead of asking it to be careful.

Adaptive Retrieval and Knowing When to Stop

Not every question deserves a search. Asking for retrieval on questions the model already handles adds latency, cost, and — worst of all — distracts it with passages that are topically close but irrelevant. Adaptive systems make three decisions per turn: retrieve or not, how many hops, and whether another round is needed after seeing the first answer.

A simple confidence gate covers the first decision: route to retrieval only when the model's answer is hedged, when the question contains entities absent from a short list of known ones, or when the task is explicitly grounded. For multi-hop flows, iterate with a stopping rule — a hop budget, an unchanged-answer check, and a maximum wall-clock time — because open-ended reflection loops are where a two-hundred-millisecond question becomes an eight-second bill.

python
def should_retrieve(question: str, model_answer: str | None, budget_hops: int = 2) -> dict:
    hedged = any(p in model_answer.lower() for p in
                 ["not sure", "i don't know", "may", "it depends"]) if model_answer else True
    entities = extract_entities(question)
    known = entity_index.contains(entities)
    if model_answer and not hedged and known:
        return {"retrieve": False, "reason": "confident and grounded"}
    return {"retrieve": True, "hops": 1 if len(entities) < 3 else budget_hops,
            "reason": "hedged or unknown entities"}

def run_hops(question: str, max_hops: int = 2) -> dict:
    history, previous = [], None
    for hop in range(1, max_hops + 1):
        query = question if hop == 1 else follow_up(question, previous)
        passages = retriever.search(query, k=6)
        answer = generate(question, passages)
        history.append({"hop": hop, "query": query, "answer": answer})
        if previous == answer or enough_evidence(passages, answer):
            break
        previous = answer
    return {"answer": previous, "hops_used": len(history), "trace": history}

Instrument the gate. If it skips retrieval fifty percent of the time, look at which questions it waved through; a gate that is wrong in the permissive direction shows up as answers with no citations, long before a user complains.

Matching Techniques to Failure Modes

The quickest way to design an advanced RAG system is to log failures, classify them, and apply one targeted fix per class rather than three unrelated improvements at once.

Observed failureWhere it happensFirst fix to tryLater escalation
Answer uses wrong sense of a termQuery understandingHyDE or vocab rewritingDomain-tuned embeddings
Right document never in candidatesRecallHybrid search with fusionQuery decomposition, index rebuild
Candidates present but buriedPrecisionCross-encoder rerankingDiversity, deduplication
Permissions leak across tenantsFilteringHard metadata filters pre-searchPer-partition indexes
Generator ignores good evidenceGenerationGrounded prompt with citationsClaim verification loop
Answer too long or unfocusedGenerationAnswer-length contract, fewer passagesStructured answer schema

Run this table against a labeled set of fifty failures before adopting anything new. Systems that add HyDE, reranking, and a critique loop simultaneously can improve while hiding a regression in one stage, and then nobody knows which change to keep.

Best Practices

  • Fix query and corpus quality before adding generation-time cleverness
  • Apply permission filters before search, never as instructions to the model
  • Use hybrid retrieval for recall and a cross-encoder for precision
  • Verify claims against retrieved spans instead of trusting self-ratings
  • Gate retrieval with an instrumented confidence rule and a hop budget

Key Takeaways

  • Advanced RAG is a targeted response to a diagnosed failure stage
  • HyDE trades a fake answer for vocabulary that matches the corpus
  • Reciprocal rank fusion and reranking cover the two halves of the retrieval problem
  • Claim-level verification catches drift that holistic self-review misses
  • Adaptive retrieval saves cost and attention by deciding when not to search
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement