Your Retriever Was Tuned on Human Queries, Your Agent Writes Its Own

Your RAG system passed its eval set and worked in the chat box. Then you put a retrieval tool in an agent's hands and recall fell off a cliff, while the same eval set kept passing.

Viral RuparelNo. 100 of 10011 min read

A team I was helping had a retrieval system they were proud of, and they had earned it. Hybrid search, a cross-encoder reranker, a recall-at-3 of about 0.9 on their eval set, months of tuning. In the chat product it was excellent. Then they wrapped the same retriever in a tool and handed it to an agent that answered support tickets end to end, and within a week the quality complaints came back. The strange part, the part that had them chasing the model for two days, was that the eval set still passed. Nothing in the retrieval metrics had moved. The agent was simply getting worse answers from a retriever that the dashboard swore was fine.

Before, the retriever is tuned and scored on human questions while the agent sends its own reformulated queries straight past the eval set to the index; after, the agent query is logged, scored on its own eval set, and passed through a bounded tool contract before it reaches the same retriever.
Figure. Agentic retrieval query drift: score the queries the agent actually sends

The queries your agent writes are not the queries you tested

Open the logs and look at what the retriever was actually asked. A human using the chat box typed "what is the refund window." The agent, given the same underlying ticket, searched for "refund eligibility window enterprise annual subscription EU billing policy 2026." Another agent run searched for "refund." A third issued four queries in a row, each a refinement of the last, because the first result did not satisfy its own check.

This is query drift, and it is the gap nobody budgeted for. Your retriever, your reranker, your chunk size, and your top-k were all tuned against a distribution of queries that humans write: one query per question, a handful of words, phrased the way a person phrases a thing they want to know. The agent writes a different distribution entirely. It reformulates. It over-specifies, bolting on every qualifier it can infer from the context. It strips queries down to bare keywords when it is in a hurry. And it fans out, issuing several queries per task where a human issued one. None of that is in your eval set, because your eval set is made of human questions.

The reason the metrics did not move is now obvious. The eval set measures the one distribution the retriever will almost never see again once an agent sits in front of it. You are grading the retriever on an exam it no longer has to sit.

Why a distribution shift breaks a tuned retriever

A retriever is not a fixed function that returns the right answer for any phrasing. It is a stack of components, each with knobs, and every knob was turned to fit the queries you tested. Change the queries and the knobs are wrong.

Dense retrieval degrades under over-specification. When the agent pads "refund window" into a twelve-word query full of qualifiers, the embedding is pulled toward the qualifiers, and the one generic chunk that actually states "refunds are accepted within 30 days" no longer sits near the query vector. The literal page did not change. The query moved away from it. This is the same reason dense vectors are good at meaning and bad at specifics, turned inside out: now the specifics are in the query, and they are the wrong specifics.

The rerank threshold is calibrated to a query shape too. A cross-encoder trained and thresholded on short human questions assigns different score distributions to long agent queries, so the cutoff you chose to return nothing versus three chunks fires at the wrong place. Set it on human queries and it will abstain too eagerly or too rarely on agent queries, and you will not know which until you measure.

Then there is fan-out, which amplifies everything. A human query that misses is one wrong answer. An agent that issues five queries per task and chains them, where each result informs the next, compounds a single bad reformulation into a wrong path. Elastic's engineers make this point plainly: vector similarity alone is insufficient for production agentic workloads, because agentic retrieval has to support multi-hop queries within a single workflow, where one bad hop poisons the rest. The failure is not in any single retrieval. It is in the second query, written from the first query's bad result.

Measure retrieval on the queries the agent sends

The fix starts where the problem is invisible: in what you measure. Stop grading retrieval on human questions and start grading it on the queries the agent actually writes. That means logging the real query string on every retrieval tool call, separately from the user's original request, and building an eval set from those strings.

# Log the query the agent SENT, not the user's request, on every call.
def retrieval_tool(agent_query: str, task_id: str) -> list[Doc]:
    docs = retrieve(agent_query, top_n=3)
    log_event(
        task_id=task_id,
        agent_query=agent_query,          # the drifted string, verbatim
        returned_ids=[d.id for d in docs],
        # grade later: did a human-labeled relevant doc appear here?
    )
    return docs


def recall_at_k(eval_set: list[dict], k: int = 3) -> float:
    """eval_set entries: {"agent_query": str, "relevant_ids": set[str]}

    Built from PRODUCTION agent queries, labeled after the fact. This is the
    distribution the retriever actually faces, so this number is the one that
    predicts agent quality. Your human-question recall does not.
    """
    hits = 0
    for case in eval_set:
        got = {d.id for d in retrieve(case["agent_query"], top_n=k)}
        if got & case["relevant_ids"]:
            hits += 1
    return hits / len(eval_set)

Sample a few hundred agent queries from a week of traffic, label the document that should have come back for each, and run recall at k over that set. When the team above did this, their 0.9 on human questions came out at 0.55 on agent queries. The retriever had not regressed. It had never been measured on the thing it was now doing. This is the same discipline as keeping a living eval set fed from production traces, applied to retrieval: the set that gates releases has to be made of the inputs you actually get, and every production miss becomes the next case.

Give the agent a retrieval tool with a contract

Measuring tells you the gap. Closing it means taking back the parts of the query that break retrieval, without giving up the reformulation that makes agentic search worth having. The lever is the tool contract. A retrieval tool that accepts a free-form string and lets the model pick top-k is a retriever whose query distribution changes every time you edit the prompt. Bound it instead.

# A bounded retrieval tool. The model picks the query text; the server
# owns everything that affects recall and cost.
MAX_QUERIES_PER_TASK = 4

def agent_retrieve(query: str, task: TaskState) -> RetrievalResult:
    norm = normalize_query(query)                 # trim, lowercase, cap length
    if norm in task.seen_queries:                 # dedupe near-identical fan-out
        return RetrievalResult(docs=[], note="duplicate query, already searched")
    if len(task.seen_queries) >= MAX_QUERIES_PER_TASK:
        return RetrievalResult(docs=[], note="query budget exhausted for this task")
    task.seen_queries.add(norm)

    docs = retrieve(norm, top_n=3)                # top_n fixed server-side, not by the model
    if not docs:                                  # explicit abstain path
        return RetrievalResult(docs=[], note="no confident match; do not guess")
    return RetrievalResult(docs=docs, note=None)

Four things in there earn their place. The query budget caps fan-out so one task cannot issue twenty searches and bury the window. The dedupe step collapses the near-identical reformulations an agent loves to emit, the same singleflight logic that stops duplicate work in a tool cache. The fixed top-n takes the candidate count out of the model's hands, because the model will happily ask for fifty chunks and drown itself. And the abstain path matters most: an agent that gets an empty, honest result stops, while an agent handed three loosely related chunks will build a confident answer out of context that does not support it. Returning nothing is a feature.

Re-tune for the agent's query shape

With the contract in place and the agent-query eval set built, you can finally tune the retriever for the distribution it actually serves. Run the same stage-by-stage comparison you would for any retrieval change, but run it on agent queries, and expect different answers than the human set gave you.

Two knobs usually move. Fusion depth often needs to go deeper for agent queries, because an over-specified query ranks the right chunk lower in each channel, so you need to fuse more candidates to catch it before reranking. And the rerank threshold needs re-deriving on the agent score distribution, not inherited from the human one. There is also an indexing-side fix that attacks drift at the root: prepend chunk-specific context before embedding so a chunk carries its own disambiguation. Anthropic's contextual retrieval reports failed retrievals dropping from 5.7% to 1.9% when contextual embeddings, contextual BM25, and reranking are combined, and the reason it helps agents specifically is that a chunk which already names its document and section survives an over-specified query that a bare chunk would miss.

Whatever you change, the window still has a budget. Better retrieval for an agent means putting fewer, denser chunks in front of it, not more, because those chunks accumulate across a multi-step run and every turn resends them, which is where retrieval quality collides with context management in long-running agents. The goal is not to widen the funnel. It is to get the right chunk into the top three for the query the agent wrote.

The parts that bite

The agent query is a moving target. Every prompt edit, every model upgrade, every new tool in the set can shift how the agent phrases its searches. The eval set you built last month was labeled on last month's query distribution. Re-sample it on a schedule, and treat a prompt change that touches the search instructions as a reason to re-check retrieval, the same way you would re-check it after swapping the embedding model.

Over-constraining the tool kills the thing that was good. Reformulation and multi-hop search are why an agent can answer questions a single query cannot. Cap fan-out too hard, or normalize queries too aggressively, and you have turned your agent back into a single-shot retriever with extra steps. The budget and dedupe are there to stop runaway fan-out and duplicates, not to forbid a second, better query.

Labeling agent queries is harder than labeling human ones. A human question has an obvious right answer. An agent's over-specified, multi-clause query sometimes has no single correct document, or has a different right document depending on which hop it is. Label the intent, not the literal string, and when a query genuinely has no good answer in the corpus, mark it as a correct abstain rather than a miss, or your recall number will punish the retriever for doing the right thing.

Fan-out hides in your cost and latency, not just your recall. Agentic tasks can trigger many retrieval operations within a single run. Even when recall is fine, an uncapped agent that searches ten times per ticket pays ten times the retrieval cost and latency. The query budget is a recall control and a spend control at once, which is a rare thing to get for free.

The takeaway

When an agent gives worse answers than your chat product did, do not start with the model and do not trust a retrieval dashboard built on human questions. Pull the logs and read the queries the agent actually sent. They will not look like your eval set, and that difference is usually the whole bug. The retriever was tuned for a distribution that an agent in front of it no longer produces.

The fix is three moves and none of them touch the model. Build the eval set from production agent queries and gate on that number. Wrap retrieval in a tool contract that caps fan-out, dedupes, fixes top-k, and can honestly return nothing. Then re-tune fusion depth and the rerank threshold on the agent distribution, and consider contextual chunking so an over-specified query still lands. Measure the stages separately, on the right queries, and the dashboard will finally tell you the truth.

If your agent gives worse answers than your retrieval metrics say it should, and you are not sure whether it is the model, the chunks, or the queries the agent is writing, book a consultation call and we will read the logs together and find out which one it is.

ShareXLinkedInviralruparel.com/blog/agentic-retrieval-query-drift-recall-collapse

Questions this essay answers

01Why does my RAG work in the chat UI but fail inside an agent?

Because the agent does not send the queries you tuned on. A human types one question and reads the answer. An agent rewrites the task into its own search string, often over-specified or stripped to keywords, and fires several of them per task. Your retriever, your fusion depth, and your rerank threshold were all calibrated against the human distribution, so a shift in query shape quietly drops the right chunk out of the top results. The eval set still passes because it is made of human questions, which is exactly the distribution that no longer reaches the retriever.

02How do I measure retrieval quality for an agent?

Log the actual query string the agent sends on every retrieval call, not the user's original request. Sample a few hundred of those, label the document that should have come back, and compute recall at k over that set. This is the distribution your retriever faces in production. The human eval set tells you how retrieval behaves for queries it will rarely see again once an agent is in front of it. Keep both, but gate releases on the agent-query set, and add every production miss to it.

03Should the agent write its own search queries at all?

Sometimes, but not without a contract. Letting the model emit a free-form query gives you reformulation and multi-hop search, which is powerful, but it also means the query shape drifts with every prompt change. Bound it: cap the number of queries per task, deduplicate near-identical ones, fix top k on the server rather than letting the model choose it, and give the tool an explicit way to return nothing so the agent does not build on noise. You keep the flexibility and take back control of the parts that break retrieval.

04Does a bigger context window fix agent retrieval?

No. A larger window lets you stuff more candidates in, but it moves the failure rather than removing it. The right chunk that your retriever ranked fortieth is still fortieth, and now it sits in the weakly attended middle of a longer prompt where the model is least likely to use it. The fix is upstream, in getting the right chunk into the top few results for the queries the agent actually writes, not in widening the funnel the agent pours noise into.

Working on this in production?I help teams make agents like this reliable. Thirty minutes, no pitch.
Viral Ruparel

Generative AI consultant and full-stack architect. Ex-IBM, former Director of Engineering at a YC W20 startup. Writes about what breaks when agents meet reality.