Agentic retrieval, long context and memory

Who decides what the model reads: retrieval as a tool the model calls, the second hop and the query that finds it, ReAct, Self-Ask, IRCoT, FLARE and decomposition, evaluators and routers that decide whether to search again, deep-research loops, long context against retrieval with its cost on this laptop, retrieval over an agent's own history, and how to evaluate a whole trajectory. Measured on the topic's 200 HotpotQA questions with Qwen3 1.7B and 4B on an Apple M1 Pro; published results kept apart. A child of Topic: rag-and-retrieval. Data as of October 2026. Reading: 35 min, plus 20 in closed details.

Agentic retrieval in one picture

Agentic retrieval moves the decision of what to read next from the engineer to the model (or to a router, or to nobody, with the whole corpus in the window). It pays only when the next query can name what the last search found, and every extra call re-reads everything before it.

Fig. 1 follows one recorded question through three deciders, the running example's Qwen3-1.7B answering each time; each slab is one model call, its length the prompt tokens, to scale.

  1. One question, one corpus. "Where was the music festival Billy McFarland was charged with wire fraud for supposed to take place?" (answer Great Exuma). Its two gold paragraphs are Billy McFarland (entrepreneur), which the question names, and Fyre Festival, which it does not. The tiles stand for the 9,760 paragraphs; where a tile sits is layout only.
  2. The engineer decides: one search, top 5. The question finds hop 1; Fyre Festival is not among the five. One call of 753 prompt tokens answers "New Orleans": wrong.
  3. The model decides: it writes a query. The agent searches "Billy McFarland" and reads three paragraphs, hop 1 among them. Its second call (580 tokens) re-reads the first call and its output (grey, 231 tokens) and adds the thought and the result (349).
  4. The next query names what it just read. "Fyre Festival" finds hop 2. The third call is 1,061 tokens, 629 of them re-read, and answers "Great Exuma": right, after 1,812 prompt tokens over three calls.
  5. Nobody decides: everything in the window. The question's own 10 paragraphs (both gold among them, eight near-misses) go into one call of 1,933 tokens: "Bahamian island of Great Exuma" (F1 0.57: the right island, extra words).
  6. Over all 200 questions, the three land close. Mean tokens billed and F1: top 5 735 and 0.402; ReAct 2,458 and 0.411; long context 1,455 and 0.456. One question shows how each decider reads; the averages show that none wins by much while the tokens differ severalfold. The chart below places all twelve strategies.

You need: one search done well, The retrieval pipeline; the agent loop and native tool calling down to tokens, Building a harness. The parent, Topic: rag-and-retrieval, compares these strategies in its section 5 (who decides what to read), and its shared runs (src/agent) measured them; this page reuses those recorded runs and adds its own.

hop, bridge question
one gold paragraph to read; a bridge question names the first thing but not the second (Billy McFarland, then the Fyre Festival)
observation
a tool's result, appended to the conversation before the model is called again
step budget
the most tool calls the harness allows before it forces an answer
retrieval evaluator
a separate judgment of whether the results are good enough (CRAG's T5, a cross-encoder, the model itself)
router
a rule, classifier or small model that picks a strategy once, before anything runs
prefill
running every prompt token through the model before the first output token
read-time curation
keeping raw history and selecting from it once the current task is known
The running example
200 questions from HotpotQA's distractor dev split (160 bridge, 40 comparison), each needing two gold paragraphs, over a corpus of 9,760 Wikipedia paragraphs (the root's data README). Search: bge-small-en-v1.5 (33 M parameters), exact. Generator: Qwen3-1.7B at 4 bits (Q4_K_M) in llama.cpp's llama-server on the laptop's GPU, temperature 0. Scores: HotpotQA's official exact match (EM) and token F1. Small models answer worse than frontier ones: read the absolute numbers as a small-model case and the gaps and costs as the finding. This page's own runs (IRCoT, Self-Ask, FLARE, CRAG- and Self-RAG-style checks, routers, budgets, memory, lost in the middle by length, the 4B block) were made on 2026-10-15 with prompts chosen on held-out questions; src/scripts/run_pending.sh reruns them from cache.

Every way of deciding lands within a few points of one good search; the tokens differ tenfold

the engineer (one search, fixed k)a fixed programthe model, at every stepan evaluator or routernobody: everything in the window

F1 against tokens billed per question (every call's whole prompt plus output), Qwen3-1.7B on the topic's 200 two-hop questions measured on Apple M1 Pro. The agent loop (ReAct, 0.411) is level with the top-5 search (0.402) at 3.3 times the tokens; the best point is long context with the question's own 10 paragraphs (0.456), and the same idea with 8k tokens of near-misses is among the worst (0.320). No retrieval at all scores 0.142 (off the chart).

ApproachWho decides what to readModel callsF1 hereTokensPays off when
No retrieval ("closed book")nobody; the model's memory10.14260common knowledge the model was trained on
Single-shot pipeline, top 5the engineer, in advance10.402735the answer is in one or two passages similar to the question
Decompose, then retrieve (a fixed program)the model writes sub-questions once; the program runs them40.3351,961questions with a predictable shape (two hops, a comparison)
Agent loop (ReAct)the model, at every step2 to 50.4112,458multi-hop and exploratory questions
IRCoT (reasoning sentence as query, then a reader)the model's own reasoning text becomes the next query2 to 60.4421,015multi-hop, when the reasoning names the bridge entity
Self-Ask, FLAREexplicit follow-up questions; the model's token confidence2 to 90.286 / 0.4004,112 / 811when the model asks well-formed follow-ups or knows when it is unsure
CRAG-style evaluator (search again?)a cross-encoder decides; the model rewrites the query1 to 20.3321,050when the evaluator can tell good results from bad (barely, here)
Router in front (comparison-word rule)a rule, classifier or small model, once1 + the route0.444 (best here)1,143traffic mixing question types that need different strategies
Long context, gold always in the windownobody; everything is read10.456 (1.5k tok), 0.320 (8k)1,455 / 7,944a small corpus read once or as a whole
Deep researcha planner model and parallel sub-agents, for minutestens to hundredsnot run here (needs a web search API)open-ended reports with citations
Agent memorythe agent, over its own historyanyread-time curation measured in section 9long tasks and repeated sessions

1. Retrieval as a tool, and what each step costs

A pipeline commits to one query and one k before it has seen a result; if that search misses, nothing notices. Handing the search to the model lets it read a result and react. The search is a tool: a function the harness runs for the model. The model sees a tool description, may answer with a tool call (structured text naming the tool and its arguments), the harness runs the search and appends the result as an observation, and the model is called again with everything so far, until it answers or the step budget runs out. That is the reason-then-act loop of ReAct; how a harness renders the tool schema into the chat template and parses the call is on Building a harness. What matters here is what the loop reads and what it pays.

Every call re-reads everything before it

With s the first call's prompt (instructions, tool description, question) and r what each step adds (the model's thought and action plus the observation), n searches and a final answer bill

Tin = (n + 1) s + r · n(n + 1) / 2
s
measured mean 172 tokens for the root's agent
r
measured mean 474 tokens per step
n
searches before the answer (n + 1 model calls)
  1. Call 1: s tokens. Instructions, the tool description and the question: s = 172 tokens on average for the root's agent.
  2. Search 1: the first prompt is read again. The model's thought, its action and the observation add r = 474 tokens; call 2 re-reads all of call 1 (grey) and bills s + r.
  3. Search 2: everything again. Call 3 bills s + 2r. Every call re-reads every call before it, so the bill grows with the square of n.
  4. Searches 3 and 4: the last call alone is the largest. Predict first: how much does the fourth search add, against the first? Call 5 bills s + 4r = 2,069 tokens, (s + 4r) / (s + r), about 3.2 times call 2. The five calls bill 5s + 10r = 5,601 with the mean s and r; the 28 recorded trajectories with four searches billed 6,067 (the formula with their own s and r: 6,205).
  5. The prompt cache: computed once, billed again. llama-server keeps the earlier calls' keys and values (glass), so only the coloured parts are computed: s + 4r with the means, 2,186 recorded for those 28 questions.

Over the 200 recorded trajectories the formula, with s and r measured per question, predicts the billed tokens within 2.5% on average (worst 15%, from r varying between steps) measured; with one search it is exact by construction. On average 1,022 of the 2,258 billed tokens were actually computed. An API with prompt caching bills the re-read part at a discount (the Long-context calculator has dated prices); it does not make each step's generation faster.

The recorded table by number of searches
Searches nQuestionsFormulaBilled (recorded)Actually prefilled (prompt cache on)
169817817506
2841,8671,845941
3193,6763,6961,538
4286,2056,0672,186

What goes into s and r: tool descriptions and result formats

The tool description is text in the system turn, paid on every call. Counted with Qwen3's own chat template (tokenizer only, measured): the question alone is 37 tokens; with the root's text protocol (Thought:, Action: search[...], finish[...], a budget rule) 174; with an OpenAI-style JSON function schema passed as tools=[...] 207; with that schema plus a two-line budget prompt 232. The description is also the main lever on query quality: say what the tool returns and what a good query looks like ("a short query naming one entity or fact"). Every tool added to an agent is paid on every call.

Results per search, same agent measured: 1 paragraph F1 0.452 (1,540 tokens), 3 (the root's run) 0.411 (2,458), 5 0.424 (3,569). One per search scored highest and cost less than three, within noise (one against three: +0.041 (paired 95% interval -0.019 to +0.102)): smaller observations do not hurt this model, because it searches again.

Titles cost a fifteenth of full paragraphs

The same 3 results formatted four ways, mean Qwen3 tokens over the 406 searches the root's 1.7B agent made measured. The first sentence carries more than expected: 287 of the 486 labelled supporting sentences of these 200 questions (59%) are a paragraph's first sentence. That is the case for the two-tool design many agents use: search returns titles and a snippet, read returns one document in full, so full text is paid only when chosen. JSON wrapping costs about 12% more than the same text as a plain list, for no gain.

Budgets and stopping

What the agent did with a budget of 4 (recorded trajectories): it saw both gold paragraphs in 114 of 200, after the first search in 32, the second in 72, the third or fourth in 10, and searched again after already having both 28 times. It stopped too early (answered without ever seeing the second gold paragraph) in 75 trajectories, 52 of them wrong: stopping is a judgment from its own reading, and a small model is overconfident. It repeated a query in 28 trajectories and used the whole budget in 28 (mostly the same ones: stuck loops only the budget ended); 17 times it wrote no parseable action. Long trajectories are mostly failing trajectories, so a tight budget costs little. How to check yours: log every call's prompt tokens and every query with its results; count calls per question, repeated queries, unparseable steps and budget hits. They are cheap and find most loop bugs.

Beyond two searches, the budget buys tokens, not accuracy

The same ReAct agent with a search budget of 1, 2, 3, 4 (the root's run) and 6, 200 questions measured: F1 0.278, 0.400, 0.407, 0.411, 0.407 at 938, 1,702, 2,095, 2,458 and 3,270 tokens. Budget 6 against 4: -0.004 (paired 95% interval -0.043 to +0.036). A budget of 1 forces an answer from 3 paragraphs and falls well below the top-5 pipeline (-0.134 (paired 95% interval -0.196 to -0.071) against the root's budget-4 run).

The tool, runnable, with its real output; the budget and results-per-search runs with intervals

The tool every agent on this page calls (src/scripts/demo_tool.py; real output, paragraphs cut to 160 characters):

def search(query, k=3, exclude=()):
    """bge-small exact search over the 9,760 paragraphs; already-seen paragraphs are skipped"""
    return A.ranking(query, exclude)[:k]

first = search(q["question"])
second = search("Russian Civil War end date", exclude=first)

Question: Alexander Kerensky was defeated and destroyed by the Bolsheviks in the course of a civil war that ended when ?
Observation:
[1] Russian Civil War: The Russian Civil War (Russian: ... November 1917 - October 1922) was a multi-party war in the for...
[2] Alexander Kerensky: Alexander Fyodorovich Kerensky (Russian: ... 4 May 1881 - 11 June 1970) was a Russian lawyer and ...
[3] Kerensky-Krasnov uprising: Kerensky-Krasnov uprising was an attempt by Alexander Kerensky to regain power after the ...
Observation:
[1] Battle of Romanovka: The Battle of Romanovka was fought in June 1919 during the Russian Civil War. ...
[2] Communism in Russia: Communism in Russia began after Tsar Nicholas II lost his power during the February Revolution. ...
[3] Left-wing uprisings against the Bolsheviks: The left-wing uprisings against the Bolsheviks were a series of ...
gold: ['Socialist Revolutionary Party', 'Russian Civil War']

The answer (October 1922) is in the first result; the second gold paragraph (the Socialist Revolutionary Party, which links Kerensky to the war) is never found, and a second search for the war's end date only returns more war. Excluding already-seen paragraphs is a design choice of the root's tool: every search must show something new.

Qwen3's chat template renders a JSON tool as a <tools> block in the system turn and asks for calls inside <tool_call> tags: "native tool calling" is a prompt convention the model was trained on, and the call is text the harness parses (Building a harness shows the full rendering).

2. The second hop: what the next query needs

A bridge question ("Where was the music festival Billy McFarland was charged with wire fraud for supposed to take place?") names the first thing (Billy McFarland) but not the second (the Fyre Festival). The question finds the first paragraph easily: one gold paragraph is in the top 3 for 198 of 200 questions. The second paragraph is about something the question never names, so it ranks low (median rank 3); for 78 questions it is not in the first top 3. What should the second search say?

Predict: for those 78 questions, a second search with the same question (showing the next 3 paragraphs, since the first 3 are excluded) finds the missing gold paragraph for how many?
17 of 78. "Search more" with the same words buys little: the missing paragraph's median rank in that second search is 7. A better query is what helps, as the stepper shows.
Eight recorded questions; pick one:
  1. The question and its two gold paragraphs. Hop 1 (green) is named by the question; hop 2 (orange) is not. The ball is the query; distance from it is a paragraph's rank in that search, on a log scale (the angle is layout only); the shaded disc is the top 3 the tool returns.
  2. First search, with the question. Hop 1 lands in the disc at once; hop 2 sits outside it, because the question never names it.
  3. Search again with the same words. The first 3 are skipped, so the next 3 come back; hop 2 moves in only a little (median rank 7 over the 78 questions that need it): more of the same rarely helps.
  4. The agent's own second query (recorded). The 1.7B wrote it after reading hop 1. When it names the bridge entity, hop 2 lands in the disc; usually it does not (12 of its 55 second queries contained the name).
  5. The sentence hop 1 states, as the query (oracle). What IRCoT would search with: it names the bridge entity, and hop 2 lands in or near the disc (median rank 4). The search tool was never the problem; the query was.
gold paragraph found by the question (hop 1)the missing gold paragraph (hop 2)

So every iterative method in section 3 is a different way of getting the bridge entity into the next query. ReAct lets the model write the query; Self-Ask makes it ask an explicit follow-up question; IRCoT uses its last reasoning sentence verbatim; decomposition writes the sub-questions in advance, so it cannot know the entity unless it fills in the first answer. A larger model writes better queries; a small one benefits from structure that forces the entity in. "Did the next query contain the entity just read" is a cheap trajectory metric (section 6).

Caveats: an oracle upper bound, and a small corpus
The oracle sentence is HotpotQA's labelled supporting sentence, an upper bound for what a reasoning step could write, not a method. This corpus is small (9,760 paragraphs); in the full 5.2-million-paragraph Wikipedia the first hop is harder too (the root's data README: BM25 recall@100 0.740 on BEIR's full HotpotQA against recall@10 0.868 here). In the root's agent runs both gold paragraphs are in a single search's top 3 for 122 of 200 questions.

Naming the bridge entity solves the second hop; the agent rarely names it

Of the 78 questions whose second paragraph is not in the first top 3, how many each second query finds in the top 3 (bge-small, first search's results skipped) measured. The exact entity name finds it every time (its title is the entity). HotpotQA's labelled supporting sentence of hop 1, what a perfect reasoning step would write after reading it, finds it for 37; the question plus that sentence for 50. The 1.7B ReAct agent made a second query for 55 of these questions; where its own first query had not already found hop 2 (50), the second found it in the top 3 for 18 (median rank 22), and only 12 of its 55 second queries contained the entity's name; the decomposition program's second sub-question found it for 11 of 60. The gap between the oracle bars and the agent's is query writing, not retrieval.

3. Loops and programs: ReAct, Self-Ask, IRCoT, FLARE, decomposition

Five published ways to interleave retrieval with generation differ in two things: where the next query comes from and who decides to stop. All are run here on the same 200 questions, tool and generators; the papers' own results are on other models and corpora and sit in the closed blocks.

ReAct: the model writes every query and decides when to stop

think→search(q1)→read→think→search(q2)→...finish[answer]

Most flexible, and it pays the quadratic tokens of section 1 and every failure of a model judging its own progress. Here F1 0.411 at 2,458 tokens and 3.67 s per question (root's run), level with the top 5 (paired difference +0.009, 95% interval -0.060 to +0.081): better on 48 questions, worse on 53. With Qwen3-4B, 0.574 against 0.490 for the top 5: the larger model gets more out of the loop.

Self-Ask: explicit follow-up questions

Follow up: Who directed X?→search→Intermediate answer: Y→So the final answer is: Z

Press et al. 2022 named the compositionality gap: the share of two-hop questions a model gets wrong although it answers both sub-questions right, roughly 40% across GPT-3 sizes. A follow-up question is a well-formed query that usually names the entity. Here F1 0.286 (95% interval 0.231 to 0.345) at 4,112 tokens: the 1.7B rarely decided it was done, ending by itself in 34 of 200 runs and using all 4 follow-ups in 144, often repeating the first one word for word. The 4B ended by itself in 194 of 200.

IRCoT: the last reasoning sentence is the next query

search(question)→sentence 1→search(sentence 1)→..."So the answer is: ..."

Trivedi et al. 2022: retrieve with the question, write one chain-of-thought sentence, search with that sentence, repeat until a sentence contains "answer is:". The oracle "sentence" bar of section 2 is IRCoT's best case here (37 of 78). Here, with a separate reader over everything collected, F1 0.442 (95% interval 0.384 to 0.504) at 1,015 tokens, the best iterative method; but it barely iterated: the 1.7B wrote "So the answer is" in its first sentence for 196 of 200, so the gain comes from a reasoning sentence plus a reader, not from a second retrieval. Given both gold paragraphs it was right 62% of the time, the highest of any strategy. The 4B comes within a few points of its ReAct loop at less than half the tokens.

FLARE: retrieve only when the model is unsure

search(question)→draft, token probabilities→any token < θ?→ yes →search(question + confident part)

Jiang et al. 2023: if any token of the draft sentence has probability below θ, search with the sentence (tokens below β masked) and regenerate; the decision costs nothing extra, since the probabilities come with the tokens. Here (θ 0.8, β 0.4, the paper's 2WikiMultihopQA setting) F1 0.400 (95% interval 0.342 to 0.461) at 811 tokens, level with the top 5 at about its cost. The draft was confident enough to skip the second search for 119 of 200, and a confident draft is not a right one: confidence in a short answer says little about whether the second hop was found.

Decomposition: sub-questions written in advance

split into 1. and 2. (#1)→search(1.)→answer 1→search(2. with #1 filled)→answer

A fixed program: one call plans, the program executes, the model never decides to stop or search again. Easy to bound (always 4 calls here), and it cannot loop; but a sub-question written before reading cannot name the bridge entity unless "#1" is filled correctly (11 of 60 second sub-questions found it). Here F1 0.335 at 1,961 tokens (root's run). LangGraph's plan-and-execute template and most deep-research planners have this shape (section 7).

Search-R1: training the loop instead of prompting it

Jin et al. 2025 train Qwen2.5-3B and 7B with reinforcement learning (PPO; GRPO also tested) to emit <search> queries inside their reasoning; a retriever inserts the results, and only the final answer's exact match is rewarded. The retrieved tokens are masked out of the loss, so the policy is not trained to predict text it did not write. The policy learns when and what to search, which is the query-writing gap of section 2. Not run here (GPU-days); RL itself is on Topic: rl.

The model's size moves every method more than the choice of method does

F1 with Qwen3-1.7B (open dot) and Qwen3-4B (filled dot), same 200 questions, tool and answer prompt (s3; the root's one-call 4B runs used prompt s2, which did not hurt the 4B: 0 wrongly typed yes/no answers, root README) measured. Every method gains between 0.09 and 0.17 F1 from the larger model (the top 5 the least, Self-Ask the most), about as much as separates the best and the worst method at either size. ReAct with Qwen3-4B: 0.574 at budget 4, 0.549 at budget 2 and 0.572 at budget 6.

Published results and the exact protocols run here, method by method

ReAct: Yao et al. 2022, the ReAct paper page: free-text "Thought", a tool "Action", an "Observation", repeated.

Self-Ask (arXiv 2210.03350): the prompt makes the model write "Are follow up questions needed here: Yes." / "Follow up:" / "Intermediate answer:" / "So the final answer is:", each follow-up sent to a search engine. Published (Table 1, Davinci-002): Bamboogle chain of thought 46.4%, Self-Ask 57.6%, Self-Ask with search 60.0%; 2WikiMultiHopQA 29.8, 30.0, 40.1 published. Run here as a chat-model version: each call writes the next line, a follow-up is searched with top 3 and answered from those paragraphs, and a reader answers at the step limit of 4; 5.34 s per question. On 60 held-out questions the original completion-style prompt scored 0.116 (the chat model restarted the question instead of continuing the trace); the chat version 0.365.

IRCoT (arXiv 2212.10509): until "answer is:" or 8 steps, keeping at most 15 paragraphs (BM25, K of 2 to 8 per step, tuned on dev). Published answer F1 (Table 4), one retrieval against IRCoT: HotpotQA 49.7 to 59.1 with Flan-T5-XXL and 53.6 to 60.7 with GPT-3 (code-davinci-002); 2WikiMultihopQA 54.8 to 68.0 with GPT-3 published. Run here with bge-small top 3 per step, at most 4 steps, then a reader over everything collected (IRCoT separates retrieval from reading); the prompt chosen on 60 held-out questions, 0.541 against 0.459 for a variant that forbade answering early; 1.48 s per question.

FLARE (arXiv 2305.06983): published (Table 1, text-davinci-003, 2WikiMultihopQA EM / F1): single retrieval 39.4 / 48.8, question decomposition 47.8 / 56.4, FLARE 51.0 / 59.7 (θ 0.8, β 0.4, Table 9) published. Run here with token probabilities from llama-server's OpenAI-compatible logprobs field: a draft from the top 3, and on low confidence 3 more paragraphs found with the question plus the confident part of the draft.

Search-R1 (arXiv 2503.09516): retriever E5, top 3, 2018 Wikipedia; no format reward. Published: about 24% (7B) and 20% (3B) average improvement over RAG baselines across seven QA sets; average EM 0.304 for RAG against 0.431 for Search-R1 with Qwen2.5-7B base (Table 2) published.

The 4B runs (this page, answer prompt s3) measured: IRCoT 0.548 (1,098 tokens), Self-Ask 0.457 (1,361), FLARE 0.526 (792), CRAG-style 0.458 (1,030); the root's 4B runs: top 5 0.490, decomposition 0.488, long context 0.576.

4. Should I search again? Retrieval evaluators

A pipeline answers from whatever came back; a loop searches again only when the model notices. A retrieval evaluator judges the results separately (good enough, useless, in between), so extra searches are spent only where needed. Two published designs: Self-RAG (Asai et al. 2023) trains the generator itself to emit reflection tokens (Retrieve: search now?; ISREL: is this passage relevant?; ISSUP: is my sentence supported by it?; ISUSE: how useful is the answer); CRAG (Yan et al. 2024) puts a small fine-tuned T5-large in front that scores each document and picks Correct (keep and refine), Incorrect (discard, rewrite the query, search the web) or Ambiguous (both).

The best paragraph's cross-encoder score scores AUROC 0.43 for "both gold in the top 5", below a coin: a very relevant top paragraph usually means the search locked onto the first hop, and the rest are near-copies of it. The second-best score is the useful one (0.64), and agreement between BM25 and dense search is the best single signal (0.69). For multi-hop questions an evaluator must judge the set against everything the question needs, not each result against the question; CRAG's per-document scores were designed for single-hop sets (PopQA, PubHealth, ARC, biographies). No signal predicts the 1.7B's answer well: the best is the second-best cross-encoder score (0.60), and a cross-validated logistic regression on all 8 signals reaches 0.57.

Three evaluator policies, measured. Escalate when the evaluator's best score is below its median (use the agent loop's recorded answer, else the top 5): F1 0.390 (against always-pipeline -0.012, 95% interval -0.055 to +0.034), the same as escalating a random half (0.406). Correct, as CRAG does: thresholds at the 33rd and 67th percentiles split the questions into 66 correct, 68 ambiguous and 66 incorrect; on incorrect the model rewrites the question into keywords and the new top 5 replaces the old, on ambiguous it is added. F1 0.332 (95% interval 0.274 to 0.391) at 1,050 tokens, below the plain top 5 (0.402): throwing away results that found the first hop, because the set "looks wrong", removes half of what a two-hop question needs. Self-check, as an untrained Self-RAG: the same 1.7B asked whether the paragraphs support its top-5 answer said "supported" for 187 of 200 answers, only 77 of them right; falling back to the agent loop on "no" scored 0.420 at 1,632 tokens. An untrained small model is not a critic of its own answers, which is why Self-RAG trains one.

A confident best hit predicts that the second hop is missing

For each signal the pipeline has before generating, the AUROC: the probability that a question where the search succeeded scores higher than one where it failed (0.5 is a coin). Targets: both gold paragraphs in the top 5 (137 of 200) and the pipeline's answer right (F1 at least 0.5, 80 of 200). The cross-encoder is the running example's 22 M ms-marco MiniLM-L6 over the top 5, standing in for CRAG's T5 measured on Apple M1 Pro (CPU), deterministic.

Self-RAG and CRAG in detail, with published results; the AUROC table

Self-RAG (arXiv 2310.11511): Retrieve takes yes, no or continue; ISSUP fully, partially or not; ISUSE 5 to 1. A critic model (Llama2-7B trained on 4k to 20k GPT-4 judgments per token type) labels about 150k training examples offline (145,619), and the generator (Llama2 7B or 13B) is fine-tuned on them; at inference the tokens drive retrieval and a beam search over segments. Published (Table 2): PopQA 54.9 / 55.8% for Self-RAG 7B / 13B against 51.8% for Llama2-chat-13B with retrieval; PubHealth 72.4 / 74.5 against 52.1 published.

CRAG (arXiv 2401.15884): the T5-large (0.77 B) scores each document from -1 to 1; any above an upper threshold means Correct, all below a lower threshold Incorrect, otherwise Ambiguous. Kept documents are cut into strips, scored and filtered ("decompose then recompose"). Thresholds are set per dataset (for PopQA upper 0.59, lower -0.99). Published: on the Self-RAG 7B generator, PopQA 52.8 for plain RAG against 59.8 for CRAG, PubHealth 39.0 against 75.6 (Table 1); the evaluator tells relevant from irrelevant with 84.3% accuracy against 58.0% for ChatGPT prompted to judge (Table 4) published.

Signal (computed before generation)AUROC: both gold in top 5AUROC: answer right
cross-encoder logit of the best of the top 5 (CRAG-style)0.430.54
cross-encoder logit of the second best0.640.60
bge-small cosine of the top 10.640.56
top-1 minus top-3 cosine0.590.47
BM25 and bge-small agree on how many of the top 50.690.58
question contains a comparison word (or, both, first, older, ...)0.620.50
logistic regression on all 8 signals, 5-fold cross-validatedn/a0.57

5. Routers: deciding once, before anything runs

The agent loop costs 2,458 tokens per question against 735 for the pipeline, and most real traffic is easy. A router looks at the question once and sends it to the cheapest strategy likely to answer it. Adaptive-RAG (Jeong et al. 2024) trains a T5-Large classifier on question complexity to choose no retrieval, one search or the multi-step loop, and gets close to always-multi-step accuracy at well under half its time, although its classifier is right only about half the time (details below). Here every router chooses between two recorded strategies per question, so each policy is exact and costs no new generation (the router's own cost is not counted: the signals come from the search the pipeline makes anyway; the cross-encoder adds 58 ms for 10 pairs on this laptop, root pipeline runs).

Most routers land on the grey line between always-pipeline and always-agent: the learned router barely sends anything to the agent, and the evaluator-based one does no better than a random split. One beats the line: the rule that sends questions containing a comparison word (or, both, first, older, ...) to the agent, F1 0.444 at 1,143 tokens, +0.042 over always-pipeline (paired 95% interval +0.003 to +0.081). On the 49 questions with such a word (33 of them HotpotQA comparison questions) the agent scores 0.602 against 0.43 for the pipeline: two named things are two searches, and the loop makes them. The learned router's cross-validated AUROC for "the agent beats the pipeline on this question" is 0.48; the agent won on 48 questions, lost on 53 and tied on 99, and beyond the comparison cue which ones is mostly how a 1.7B model happened to read. The oracle over all 8 recorded strategies would reach 0.731 at 927 tokens, headroom nothing measured here can predict.

A router cannot help when the expensive path is not better. On the mixed set of the root's agent runs (Topic: rag-and-retrieval) (199 questions, about half constructed one-hop), always-pipeline scored 0.512 at 766 tokens, always-agent 0.451, its learned router 0.500 and its LLM router 0.520 (which sent almost nothing to the agent). An Adaptive-RAG-style three-way router prompted to the 1.7B on the 200 two-hop questions labelled 0 none, 0 one and 200 many: right every time, so routing reduced to always-agent (F1 0.411 at 2,458 tokens). How to check a router: put it on the cost-accuracy plane against always-cheap, always-expensive, a random split of the same share and the oracle; it must beat the random split, on your own traffic mix.

Predict: will a router on the evaluator's score beat a random split of the same share? Set the signal, then drag

always one strategy (the two chosen paths are labelled)your policy (curve: every share)random split of the two pathsoracle (best of the two per question)

Intervals are 95% bootstrap intervals over questions (500 resamples, fixed seed). The learned router is a logistic regression on 8 query-time signals, 5-fold cross-validated, so each question's probability comes from a model that never saw it (src/scripts/s_router.py). The comparison-word rule escalates the questions containing one, so its share does not move.

Correction: "agentic RAG loses on FEVER"
In Ferrazzi et al.'s controlled comparison (arXiv 2601.07711) the agentic system used 3.3 times the input tokens and 1.5 times the time, and lost by 64.6 against 87.9 F1 on FEVER published; that FEVER number scores user-intent routing (is the question in scope), not fact verification as it is often quoted, including on the old version of this page.
The policy table with intervals; Adaptive-RAG's published numbers
PolicyF195% intervalTokensSent to the agent
always the top-5 pipeline0.4020.341 to 0.4637360%
rule: comparison word in the question → agent0.4440.381 to 0.5071,14324%
learned router (logistic regression, cross-validated), p ≥ 0.5 → agent0.4070.346 to 0.4687823%
random half → agent0.4060.346 to 0.4661,45250%
CRAG-style evaluator below median → agent0.3900.332 to 0.4501,79450%
always the agent0.4110.349 to 0.4742,458100%
oracle: whichever of the two scored higher0.5550.495 to 0.6161,10824%
oracle over all 8 recorded strategies0.7310.678 to 0.780927n/a

Adaptive-RAG with FLAN-T5-XL reached 46.94 F1 against 48.85 for always multi-step, at 3.60 against 8.81 times the single-step time (Table 1), although the classifier was right only 54.52% of the time (Table 4); a perfect router would have reached 56.28. Per-query times: 0.35 s with no retrieval, 3.08 s with one search, 27.18 s multi-step (Table 3) published.

The loop trades evidence recall for nothing much in reading

rightboth gold read, answer wrong (reading failure)one gold read (retrieval failure, hop 2)no gold read

6. Evaluating a trajectory: where the answer got lost

A final answer is right or wrong, but the run behind it is a sequence of decisions: which query, which results, when to stop. Scoring only the answer cannot tell a retrieval failure from a reading failure, or a lucky guess from a grounded answer. The root splits a pipeline's accuracy as A = rK × pk|K × g (retrieved, placed in the prompt, used); for a trajectory the same split applies to everything the model read along the way, which puts every question of every strategy in one of four bins ("right" = F1 at least 0.5) measured:

Each step adds one strategy's bar; the buttons on the card switch the comparison.

  1. Pipeline, top 10. Right 88 of 200; both gold read 164 times, right given both 51%; one gold read 30, none 1.
  2. Agent loop. Right 90 of 200; both gold read 114 times, right given both 59%; one gold read 56, none 7.

The top-10 pipeline put both gold paragraphs in front of the model for 164 questions, the agent for only 114 (it often stopped early, section 1), long context for all 200. Given both, reading success is similar for every retrieval strategy: agent 59%, top 10 51%, top 5 53%, top 2 58%, the question's own 10 paragraphs 48%, falling to 32% in an 8k window. The biggest single loss is the second hop never read (56 questions for the agent, 53 for the top 5). Re-answering each multi-search trajectory from everything it read, in one prompt without the thoughts, gives F1 0.412 against the agent's own 0.407 on the same 131 questions: what the loop adds is evidence, not better reading.

Two cautions. The agent was right 23 times without reading both gold paragraphs (comparison questions answered yes or no, or from memory; closed book was right on 32): an answer metric credits those. And reading can fail for reasons unrelated to retrieval: the first 1.7B runs used an answer prompt that made the model answer "yes" or "no" to open questions (63 of 200 single-shot answers, found by the root), and the same top 5 scored 0.249 instead of 0.402, a larger gap than between any two architectures here. Counting answers of the wrong type is a one-line check.

Trajectory metrics worth logging

MetricWhat it catchesHere (agent loop, 200 questions)
gold evidence read anywhere in the trajectoryretrieval failure against reading failureboth gold: 114; one: 56; none: 7
searches until the evidence was completeefficiency; wasted searches after it32 at 1, 72 at 2, 10 at 3 or 4; 28 wasted
stopped before the evidence was completeoverconfident stopping75 (52 wrong)
repeated query, unparseable step, budget hitstuck loops and format failures28, 17, 28
next query contains the entity just readthe second-hop query-writing gap12 of 55 second queries (section 2)
right answer without the evidenceguessing, memorisation, leakage23, and wrong with both in hand 47

All of these need gold evidence labels (which paragraphs answer each question). Without labels the same questions go to a judge model ("does this observation contain what the next step needs?"), with the judge's own error measured on a labelled sample: Agent and trajectory evaluation and RAG and retrieval evaluation. The Trajectory comparer shows 40 of the 200 questions step by step under five strategies, with these bins and counters.

7. Deep research: the same loop, for minutes, with parallel sub-agents

Some questions are reports, not facts ("compare the GPU export rules of three countries since 2022"): dozens of searches, more text than one window holds, and a cited write-up. Deep-research systems scale the agent loop with three additions: a planner that splits the task, parallel sub-agents that each research one part in their own context window, and compression of what each found before it returns, so the lead's window holds summaries, not pages. Not run here: each needs a web search API key, and this topic runs without paid APIs; the shapes are read from the open projects' source at pinned commits and the vendors' documentation.

Fig. 4 is the shape of open_deep_research (LangChain, read at commit 1b7d2e8) with its default budgets (the counts are its defaults, the sizes illustrative); Anthropic's Research system has the same orchestrator-worker shape (a lead "spins up 3-5 subagents in parallel", each using "3+ tools in parallel").

  1. A brief, then a lead. The question is clarified and rewritten as a research brief; a supervisor, the lead, plans in its own window.
  2. Researchers in parallel, each with its own window. The lead calls ConductResearch; up to 5 researcher sub-graphs run at once (extra calls are rejected).
  3. Each reads pages the lead never sees. Up to 10 tool calls per researcher; every web page is summarised to about a quarter of its length by a small model before it enters the researcher's window.
  4. Compressed findings return. Each researcher compresses what it found, with inline citations, before returning; the lead sees only the compressed research. The compression step is retrieval in reverse (what of a page to keep) and is where citations are most often lost.
  5. Rounds, then a report. Up to 6 supervisor rounds, then one report with citations, written by the model and never checked in code.

What it costs and buys (vendor claims, on vendor-run evaluations): Anthropic reports that agents "typically use about 4× more tokens than chat interactions, and multi-agent systems use about 15× more", that on BrowseComp "token usage by itself explains 80% of the variance", and that the multi-agent system "outperformed single-agent Claude Opus 4 by 90.2% on our internal research eval" (Anthropic engineering, 13 June 2025) vendor. OpenAI's BrowseComp (arXiv 2504.12516, 1,266 hard-to-find questions) scores GPT-4o 0.6%, GPT-4o with browsing 1.9%, o1 9.9% and Deep Research 51.5% (Table 3; Deep Research was trained on similar data); human trainers solved 29.2% published by OpenAI. Three lessons carry over to a retrieval system you build: the sub-agent's value grows with how much must be read, and its cost is the 15 times tokens; check citations in code (open_deep_research's citations are written by the model and never checked; GPT Researcher only tells the writer not to cite sources it was not given); and stopping is set by budgets in prompts and config, as in section 1, only larger. Context engineering covers sub-agents and compaction as harness techniques; LangChain and LangGraph the graph framework two of these are built on.

System (read on)ShapeDefault budgets and stoppingCompression
open_deep_research, commit 1b7d2e8 (2026-08-10)brief, supervisor, parallel researcher sub-graphs, report6 supervisor rounds, 5 parallel units, 10 tool calls per researcherpages to "about 25-30 percent"; findings compressed with citations
GPT Researcher v3.7.0 (2026-09-26)3 sub-queries plus the original, in parallel; one writer pass; deep mode breadth 3, depth 2one pass, no reflective loop; context 25,000 wordsextractive (BM25 over chunks), not an LLM summary
dzhng/deep-research, commit 1f8f3e2recursive breadth x depth, half the breadth per level; default 4 x 2depth reaches 0only "learnings" carried forward
Anthropic Research (post of 13 June 2025)lead (Claude Opus 4) and 3-5 parallel sub-agents (Sonnet 4)prompt rules: 1 agent and 3-10 tool calls for a simple fact; over ten sub-agents for complex researchsub-agents condense before returning; a CitationAgent places citations
OpenAI deep research (launched 2 Feb 2025)a version of o3 trained for browsing5 to 30 minutes; API max_tool_callsnot disclosed
Gemini Deep Research (docs of 2026-10-13)an agent in Google's Interactions API, background onlyup to 60 minutes; about $1 to $3 per task ($3 to $7 for Max)not disclosed

Products change monthly; the table is dated per row and its latest numbers belong to tech news. Vendor figures are labelled vendor.

The systems read in their source: files, lines and defaults; dated prices and scores

open_deep_research (main at 1b7d2e80): clarify, write a research brief, a supervisor calling ConductResearch, researcher sub-graphs in parallel (asyncio.gather), final report (deep_researcher.py lines 708-716, 303). Supervisor rounds max_researcher_iterations = 6; max_concurrent_research_units = 5 (extra calls rejected); researcher tool calls max_react_tool_calls = 10 (configuration.py lines 64-108); prompt rules "Simple queries: 2-3 search tool calls ... Always stop: After 5" (prompts.py 166-168). Two compression stages: each web page summarised to "about 25-30 percent of the original length" by gpt-4.1-mini; each researcher's findings compressed "verbatim" with inline citations before returning; the supervisor sees only compressed_research.

GPT Researcher v3.7.0 (0957c301): MAX_ITERATIONS = 3 counts sub-queries, not rounds; deep mode recurses with breadth 3, depth 2 (9 nested researchers) and stops at depth 1. BM25 (k1 1.5, b 0.75) over 1,000-character chunks keeps chunks scoring at least half the best, up to 25 (context/select.py, lexical.py); real cost tracking from provider usage (utils/costs.py).

dzhng/deep-research (main at 1f8f3e28): write up to breadth search queries, extract at most 3 "learnings" and follow-up questions each, recurse with half the breadth (src/deep-research.ts 176-294); pages cut to 25,000 tokens; can point at any OpenAI-compatible endpoint, llama-server included.

Anthropic Research: sub-agents search in parallel "before condensing the most important tokens for the lead research agent".

Dated prices and scores vendor: Gemini Deep Research is offered as deep-research-preview-04-2026 and deep-research-max-preview-04-2026 with Google Search, URL context and code execution; Google's April 2026 chart puts Deep Research Max at 85.9% on BrowseComp. OpenAI's deep-research API models (o3-deep-research at $10 / $40 per million input / output tokens, o4-mini-deep-research at $2 / $8) had a shutdown date of 23 July 2026 in OpenAI's docs, read 2026-10-14; background mode was recommended.

8. Long context against retrieval, measured

Qwen3-1.7B and 4B read 32,768 tokens natively (their model cards; the GGUF files declare 40,960), frontier models a million or more. If the documents fit, why retrieve? The root's section 5 prices one query both ways (retrieval against the whole corpus in the window); the published head-to-head results are in this page's closed blocks; this section measures what reading more does to accuracy and what it costs on this laptop. How much of a window a model really uses (effective context) is owned by Long context.

Reading the question's own 10 paragraphs wins; 8k tokens of near-misses loses

Same 200 questions, same 1.7B model and prompt; only how much is read changes (root's recorded runs) measured. More retrieved paragraphs raise the chance that both gold paragraphs are present (top 2: 94 questions, top 10: 164) and buy a little F1: top 2 0.385, top 5 0.402, top 10 0.425, so one plain top-10 search scores above the agent loop (0.411). Long context guarantees them for all 200: the question's own 10 paragraphs (about 1.5k tokens) score 0.456, the best strategy here (+0.054 over the top 5, paired 95% interval +0.003 to +0.108); an 8k window full of on-topic distractors scores 0.320, below every retrieval strategy, at 14.64 s per question. Qwen3-4B: 0.576 and 0.475.

F1 with the gold block at five positions among on-topic distractors, at 5, 10, 40 and 80 paragraphs (mean prompt tokens 749, 1,485, 5,943, 11,890), first 50 questions, Qwen3-1.7B measured. First / middle / last: 5 paragraphs 0.603 / 0.548 / 0.556; 10: 0.641 / 0.519 / 0.569; 40: 0.577 / 0.467 / 0.522; 80: 0.588 / 0.360 / 0.529. At 80 paragraphs a gold block in the middle loses 39% of the F1 it has at the start; the start holds up at every length. With 50 questions each cell is noisy (95% bootstrap intervals about ±0.12): the trend across lengths is the finding. Published, the effect's name: Liu et al. 2023 (arXiv 2307.03172), GPT-3.5-Turbo with 20 documents, 75.8% with the answer document first, 57.2% fifth, 53.8% tenth, 55.4% fifteenth, 63.2% last, against 56.1% with no documents (Tables 1 and 6) published. For retrieval: put the best-ranked passages first and keep the window short.

The root's 20-paragraph position run, 1.7B and 4B; the full grid

Lost in the middle deepens as the window grows

F1 by where the gold block sits, at four window lengths; 50 questions per point, Qwen3-1.7B measured.

What a long prompt costs: prefill

Before its first token the model runs every prompt token through every layer (prefill): a part linear in the prompt length (the weight matrices, once per token) and a part that grows with its square (each token's attention reads all earlier keys and values). A model fitted to the 5,497 generator calls the root recorded (llama-server's own timings, prompt cache on, 1.7B, up to 8,065 tokens), with nnew the tokens computed and nctx the whole prompt:

tprefill = a + b · nnew + c · nnew (nctx − nnew/2) / 1000
a
22.5 ms fixed per call
b
0.830 ms per token (the linear part: about 1,200 tokens per second)
c
0.104 ms per token per thousand tokens of context (attention)

Extrapolated, the model gives about 27 s at 16k tokens and 80 s for a full 32k window, 67% of it attention (at 1,500 tokens attention is 8%); 32k remains an extrapolation. Decoding also slows as the cache grows: about 10.4 + 0.67 ms per output token per thousand tokens of context (fitted on 5,497 calls). The shape (a linear term, an attention term that dominates past a few thousand tokens, a cache that grows with the window) holds on any GPU; datacenter GPUs and FlashAttention kernels change the constants by an order of magnitude or more (not run here). Hosted APIs hide prefill in the time to first token and bill it per token; a cached prefix is billed at a discount and skips the prefill. The Long-context calculator puts both sides together: tokens, dollars at dated list prices, seconds on this laptop, KV memory.

The fitted prefill model holds on held-out calls, and beyond its range up to 15k tokens

Recorded prompt-processing time against the formula, both log scale; a point on the dashed line is predicted exactly. Blue: held-out calls within the fitted range; fitted on half the calls, it predicts the other half within 4.0% on average (3.3% on the 221 calls over 2,000 new tokens). Orange: 49 calls of this page's lost-in-the-middle run at 9k to 15,077 tokens, off by 5.9% on average measured on Apple M1 Pro (Metal). An independent check: the RAG in production child timed 9.34 s to the first token for a 7,611-token prompt; the model gives 9.34 s.

When each wins
Long context: a small, stable corpus read once or as a whole (summarise, find inconsistencies), repeated queries over the same documents with a cached prefix, and no per-user access rules. Retrieval: corpora beyond the window, per-query cost and latency budgets, per-user filtering, and small or mid-size models that read badly with distractors (measured above). They compose: strong readers can take generous retrieval (whole sections, 20 to 50 chunks) and let the window absorb chunking mistakes; on this model, keep the retrieved set small.

Published head-to-heads say the same. More retrieved passages is not monotone: for many long-context models quality "initially improves" and then declines as the count grows, mostly because of hard negatives (passages that look relevant and are not); reordering the retrieved passages, without training, recovers part of it (Jin et al., arXiv 2410.05983, Oct 2024). And there is no single winner: LaRA's 2,326 test cases over 11 models (seven open, four proprietary) found that "the optimal choice between RAG and LC depends on a complex interplay of factors": model size, long-text ability, context length, task type and the retrieved chunks (LaRA, arXiv 2502.09977, Mar 2025). So evaluate recall@k and end-to-end accuracy together across k, on your own questions.

KV cache of these models; advertised against effective context (RULER, NoLiMa)

KV cache at fp16 from the configs (2 × layers × KV heads × head dimension × bytes; sizing in general is on Long context): Qwen3-1.7B 114,688 bytes (112 KiB) per token, so 3.5 GiB for 32k tokens; Qwen3-4B 144 KiB, 4.5 GiB, on a 16 GB machine that also holds the weights.

A window size says what the model accepts, not what it uses. How RULER turns a falling curve into one "effective length" (and the claimed against effective lengths it publishes), the Qwen3 rows of its leaderboard that contradict its own rule, and NoLiMa's drop once question and answer share no words are owned by Long-context and multimodal benchmarks (its RULER and NoLiMa sections).

9. Memory: retrieval over the agent's own history

An agent working for hours, or across sessions, produces more history than fits in its window, and re-reading it all on every step is the quadratic cost of section 1. Agent memory stores that history outside the window and retrieves from it: everything about retrieval carries over, except that the corpus is written by the process that will search it and changes on every step. What to write, when to curate, fact stores (Mem0), temporal graphs (Graphiti) and memory files are owned by Context engineering, which measured all three in a twelve-session experiment. The retrieval question this page measures: once the task is known, which of the agent's own reads should the final step keep? Write-time curation (distil each step into a fact) loses whatever the distillation dropped; read-time curation keeps the raw history and selects with the current task as the query (Just-in-Time Memory argues for it and gains 16.2 points on ALFWorld, mostly from training the curator). The plainest read-time design is also the baseline every memory system must beat: Bao et al. 2026 (arXiv 2610.30755) run "Raw-RAG", dense retrieval plus a reranker over the raw conversation history, against agentic memory systems on LoCoMo, LongMemEval, MEME and MemoryAgentBench, and it "ranks first among the compared memory systems in six of seven benchmark-model settings", by 0.13 to 5.53 points over the strongest one published. Their reading: raw history covers more of the needed evidence, which outweighs the reader using it less efficiently, and even full access to a transformed memory store leaves an accuracy gap, because the transformation already lost information.

Re-answering from the curated memory in one prompt (no thoughts), on the 131 trajectories with at least two searches (the agent's own answers: F1 0.407) measured: everything read 0.412 at 1,131 tokens, the last observation 0.296 at 481, the top 3 by question plus last thought 0.378 at 442. How to check a memory system: plant facts in early turns and ask about them later, measuring recall of the planted memory (did retrieval return it) apart from the answer; add superseded facts (an old address, then a new one) and check the newer wins; log every write, so a wrong answer can be traced to a write that never happened, a retrieval that missed, or a reading failure.

The task's state is the query: retrieving over its own reads keeps both hops at a third of the tokens

The 92 root trajectories that searched at least twice and read both gold paragraphs; what the final step keeps, bge-small similarity, deterministic measured. A sliding window (the last observation only) keeps both gold paragraphs 1 time in 92: in a multi-hop task the first hop is, by construction, not in the last observation. The top 3 read paragraphs by similarity to the question plus the agent's last thought keep both in 85 of 92 at 341 instead of 885 tokens; with the question alone, 75. Top 2 / 4 by question plus thought: 73 / 90 at 225 / 467 tokens.

Published memory systems: the numbers context engineering does not carry

Mem0 (arXiv 2504.19413) extracts facts per turn and updates a store of them; its published latency, token and accuracy figures against full context, and a recorded run of it, are on Context engineering, section 8. Zep's Graphiti (arXiv 2501.13956) stores facts in a temporal graph with validity windows; LongMemEval 71.2% against 60.2% for full context with gpt-4o published by the Zep authors. The Proactive Memory Agent adds the timing question: a second model deciding when to remind the worker.

Depth: design questions

Optional rehearsal; each answer points back to the section that measures it.

IRCoT, Self-Ask, FLARE: where does each next query come from, and who stops?
IRCoT: the last chain-of-thought sentence; it stops on "answer is:". Self-Ask: an explicit "Follow up:" question; it stops on "So the final answer is". FLARE: the draft sentence with unsure tokens masked, and only when some token's probability is below a threshold. ReAct: whatever the model writes, until it calls finish or the budget ends (section 3).
Why mask retrieved tokens in Search-R1's loss?
The policy did not generate them; training it to predict retrieved text would teach it to imitate documents instead of deciding what to search.
What would you log to debug an agentic RAG system?
Every call's prompt tokens and latency, every query and its results, gold or judged relevance of each observation, stop reason, repeats and parse failures; then bin each failure as retrieval, reading, stopping or format (sections 1 and 6).
System design: a research assistant over 2 million internal documents, answers with citations in under a minute, per-user permissions.
Hybrid index (BM25 plus dense) with ACL filters applied at retrieval, a reranker; a router sending lookups to a single-shot pipeline (seconds) and analytical questions to a planner with 3 to 5 parallel sub-agents, each with a tool budget and a compression step that keeps document ids; citations checked in code against the retrieved chunks before the answer is shown; prompt caching for the shared system and tool prefix; budgets per request (tool calls, tokens, wall time) with a partial answer on timeout; trajectory logs and a labelled set of 200 to 500 questions with gold documents to track retrieval recall, stop reasons and answer quality per route. Freshness and deletes as on RAG in production.
Write-time or read-time memory curation?
Documents: write-time (an index), because they cannot know the future question. An agent's own history: keep it raw and curate at read time with the current task as the query, when storage is cheap; distil at write time only what must survive the raw log's deletion (section 9).
The root page's agentic runs in detail (moved here when the root's Agentic lab was retired, 2026-10-24; 5 min)

These are the recorded runs this page reuses (the root page's src/agent). Machine: Apple M1 Pro (8 performance and 2 efficiency cores, 16 GB unified memory), llama.cpp build 11146 with Metal for the generator, PyTorch on the CPU for the search tool's query encoder, October 2026. Generators: Qwen3-1.7B and Qwen3-4B, 4-bit GGUF (Q4_K_M), temperature 0, seed 0, thinking switched off (enable_thinking: false), one request at a time, prompt cache on; outputs are cached by exact prompt, so every number is reproducible without rerunning the models. Search tool: bge-small-en-v1.5, exact search, and the agent is never shown a paragraph twice (each search returns the 3 best paragraphs it has not seen); search time is milliseconds and is included in seconds per question. Qwen3-Embedding lists HotpotQA among its training data, so its HotpotQA results are in-domain, not zero-shot; that is why the search tool is bge-small. Metrics: HotpotQA's official answer normalisation (lowercase, strip punctuation and the articles a, an, the, collapse spaces), exact match and token F1 with its yes/no rule; "gold seen" is the share of the two gold paragraphs that reached any prompt. Each strategy's answer prompt was chosen among two candidates on 60 held-out HotpotQA dev questions (from the other 800 whose paragraphs are in the corpus), never on the 200 test questions. Held-out tuning had picked a prompt without the list of answer forms ("Give only the answer, in as few words as possible"), but a scripting error kept it out of the first 1.7B test runs; every one-call 1.7B row was rerun with the held-out choice, and the first runs are kept as out/strategies_s2prompt.json. The 4B was unaffected: its single-shot, long-context and position runs used the other candidate prompt, made no yes/no mistakes with it, and were not rerun. Not run: the full HotpotQA corpus (5.2 million paragraphs, too large to embed on the laptop), thinking mode (about 8 s per answer, hours for a loop over 200 questions), and long context beyond 8k tokens (prefill alone about 25 s or more per question for the 1.7B, extrapolated from 9.3 s at 7.6k tokens).

  • The second hop, two examples. "Who was born first, Arthur Conan Doyle or Penelope Lively?" (a comparison question) needs two paragraphs, and both names are in the question. "What government position was held by the woman who portrayed Corliss Archer in the film Kiss and Tell?" (a bridge question) needs the film's paragraph, to learn the actress's name, before her paragraph can be searched for. One BM25 search puts both gold paragraphs in the top 10 for 147 of 200 questions. Most second-hop paragraphs still share a few words with the question (median 3 content words against 4 for the first; only 10 of 200 share none): it is the ranking, not total absence, that hides them.
  • Five ways to answer, with Qwen3-4B. The loop pays for its +0.084 with 2,456 tokens per question against 754 (3.3 times) and 6.15 s against 1.98 s. Without retrieval the 4B scores 0.193, so most of what it answers comes from what it reads. The agent saw fewer gold paragraphs than the top 5 did (81% against 84%) and still answered better: it reads 3 paragraphs at a time, chosen for the piece it is missing, instead of 5 chosen for the whole question. Long context came in two sizes: the question's own 10 paragraphs (HotpotQA's "distractor" setting, about 1.4k tokens) and about 8k tokens (the own 10 plus the corpus paragraphs nearest the question). The own 10 (about 1,470 prompt tokens) score 0.576, level with the loop at 60% of its tokens and 3.95 s against 6.15 s; widened to about 8,000 tokens F1 falls to 0.475, below the five-paragraph pipeline, at 7,963 tokens and 28.8 s per question. The corpus is 1.34 million Qwen3 tokens, so a window of 8,000 holds 0.6% of it, and prefill grows faster than linearly (about 0.26 s for a 270-token prompt, about 9.3 s for 7,600 tokens). The 1.7B uses about the same tokens per strategy and roughly half the seconds.
  • Tokens per step, with Qwen3-4B. The prompt carried into the loop's calls grows from 172 tokens at the first call to 613, 1,077, 1,565 and 2,047 at the fifth, while the prompt cache keeps the tokens actually computed near 450 to 530 per call; a cache stores the attention keys and values of a prefix already processed, lowers the price of the re-read prefix (providers bill cached tokens at a discount, not for free) but not the time to generate each step. A question that ends in two calls bills 820 input tokens; one that uses all five bills 5,370, 6.5 times as much. The long trajectories are the failures: the 29 questions that used all four searches score F1 0.18, against 0.673 for the 112 that stopped after two, so a step cap does more than bound cost (past two or three searches the small model was mostly lost). Repeating a query (36 questions) or losing the format (3 questions; 17 for the 1.7B) is how a small model wastes its budget; a loop can also search for the wrong entity or stop early with a plausible guess. The old page's worked example, with illustrative s = 1,500 and r = 2,000 tokens against a pipeline reading 4,000 retrieved tokens once: at 3 searches the agent reads 18,000 tokens (3.3 times the pipeline), at 6 searches 52,500 (9.5 times).
  • Lost in the middle on 20 paragraphs. The same 20 paragraphs per question (the two gold paragraphs kept together as one block, plus the 18 corpus paragraphs bge-small ranks highest among the rest, so the distractors are on topic), with only the position of the gold block changing. Qwen3-4B (100 questions): F1 0.682 first, 0.540 at positions 5 to 6, 0.554 at 10 to 11, 0.599 at 15 to 16 and 0.592 last; first against the middle +0.128: Liu et al.'s shape at a smaller scale, a strong advantage at the very start, a drop of 0.13 to 0.14 in the early middle and only part of it recovered at the end, though the middle slots overlap in their intervals. Qwen3-1.7B (200 questions) shows the U more clearly: 0.496 first, 0.405 and 0.381 in the middle, 0.381 at 15 to 16 and 0.468 last; first against the middle +0.116 (95% interval +0.063 to +0.168), last against the middle +0.087 (+0.045 to +0.130). The practical rule: when stuffing a window, put the best evidence first (or last), and measure on your own model before trusting a long prompt to be read evenly.
  • A router on a mixed set. HotpotQA has no one-hop questions, so Qwen3-4B read one corpus paragraph (never a gold paragraph of the 200) and wrote a question answerable from it alone, with a short answer copied from it; questions whose answer was not in the paragraph, was longer than six words or appeared in the question were dropped. Of 240 paragraphs drawn, 198 questions survived (62,375 tokens, 259 s), split 99 for training and 99 for the test; the mixed test set is 100 two-hop questions plus that one-hop test half. Two routers were trained or prompted without touching the test set: a logistic regression on the question's bge-small vector (free, since the search tool computes it), trained on 400 held-out HotpotQA questions and the one-hop training half, and Qwen3-1.7B asked, with four examples, whether the question needs ONE fact or TWO. Because the 1.7B loop is no better than the pipeline on the two-hop half (0.389 against 0.426) and worse on one-hop questions (0.515 against 0.599), always-pipeline is the best simple policy: 0.512 for 766 tokens and 0.92 s, against 0.451 for 2,652 tokens and 3.39 s for always-agent. The logistic router is right about the question type 74.9% of the time and sends 122 of 199 questions to the loop, which costs accuracy (0.500) and tokens (1,942); even a perfect router (0.493 for 1,841 tokens) is below always-pipeline. With the 4B, whose loop is better on two-hop questions, the same router would pay; that run was not made. Caveat: the constructed one-hop questions are easier to tell apart than real traffic.
  • Published, for comparison. ReAct (Yao et al. 2022; PaLM-540B, HotpotQA, question only, Wikipedia search API, exact match, prompting only): standard 28.7, chain of thought 29.4, act only 25.7, ReAct 27.4, ReAct then CoT-SC 35.1; supervised state of the art 67.5. ReAct's failures: 47% reasoning errors (including loops), 23% search results without the needed information, and 29% of failures were label ambiguity. Self-Route (arXiv 2407.16833 v2, Table 1; LongBench and InfiniteBench subsets): Gemini-1.5-Pro long context 49.70, RAG 37.33, Self-Route 46.41 with 38.4% of long context's tokens; GPT-4o 48.67, 32.60, 48.89 with 61.4% (the paper's prose quotes different values; the table is used here). Li et al. (arXiv 2501.01880) found long context generally ahead on question answering (most on Wikipedia questions) and retrieval ahead on dialogue and general questions.
  • Memory. Everything about retrieval carries over to an agent's own history (chunk it into turns or facts, embed, search with the current goal as the query, rerank, measure whether the needed memory was retrieved), with two differences: the store changes on every step, so writing and forgetting policies matter as much as search, and time matters (a newer fact can overrule an older one).
  • What transfers. A loop costs several generator calls and a growing prompt per question; a router saves most of that on one-hop traffic; long context pays for every token it reads; a fixed decomposition is cheaper and more predictable than a free loop; an entity graph costs one generator call per chunk before the first question. Small models fail more at the "agent" part (choosing a good query, knowing when to stop) than at reading; larger models were trained for exactly this and gain more from a loop.
  • Mistakes and a design, from the old page. Compare an agent with a pipeline at matched reading budgets too: an agent that searches four times reads up to 12 paragraphs, a pipeline given the top 3 reads 3, and part of any gain is just more text (compare at matched paragraphs or tokens, and report the cost next to the accuracy). Do not evaluate with an embedder trained on the benchmark. Exact match alone counts "October 1922" against "1922", or "Yes" against "yes, both are American", as wrong: report F1 too, and read a sample of failures. Use a loop when the question needs information you can only know to look for after reading something (multi-hop, comparisons, research tasks), when the first search often fails and needs reformulation, or when the tools vary (search, SQL, an API). To cut its cost, retrieve better per step (hybrid search, a reranker) so fewer steps are needed, and use a smaller model for planning queries and a larger one only to answer. A design for mixed traffic: ingestion parses, chunks on structure, embeds, builds a BM25 index and stores metadata and access lists per chunk; a router (a small classifier on the query) sends lookups to hybrid search, a reranker and the top 5 with citations, and multi-step questions to a loop with search as a tool (bounded steps, each search filtered by the user's access, observations summarised, a prompt cache for the fixed prefix); evaluation keeps a golden set of both kinds and tracks answer quality, evidence recall, cost and p95 latency per route; operations re-index on change, cache frequent queries and log trajectories for failure review.

Sources: measured results come from the root's recorded agent runs and this page's scripts (src/scripts/), on an Apple M1 Pro, 2026-10-14; published results link their papers and are the authors' or vendors' own runs. Reruns from cache: src/scripts/run_pending.sh (all runs made by 2026-10-15). Old-page corrections: src/coverage.md.