{"slug": "agentic-rag-grade-the-search-rewrite-retry-with-a-cap", "title": "Agentic RAG: grade the search, rewrite, retry with a cap", "summary": "A developer tested an agentic RAG design that grades retrieved results, rewrites failed queries and retries within a cap, finding that on 40 simulated questions a single BM25 search found the right page 20 times, a cap of 2 searches found 32 and a cap of 4 found 38, with the fourth round rescuing nothing. Each extra round cost about 1.2 modeled seconds and a few hundred tokens, and all 20 questions phrased in everyday words failed on the first search while all 20 technical questions succeeded immediately. The writeup cites CRAG, Self-RAG and Anthropic's multi-agent research system as related approaches.", "body_md": "Agentic RAG lets an agent decide when and how to retrieve information while preparing an answer. We tested one design: grade the retrieved results, rewrite a failed query and retry within a cap. In our simulation run on 2026-11-15, one search found the right page for 20 of 40 questions, a cap of 2 searches found 32 and a cap of 4 found 38. Every extra round cost about 1.2 modeled seconds and a few hundred tokens, and the fourth round rescued nothing.\n\nYou type \"Why does the site keep forgetting that I signed in?\" The help page that answers it is titled \"Session cookie expiry\". None of your words appear on that page, so a keyword search ranks other pages above it.\n\nThis is vocabulary mismatch, and we measured it before: in our [RAG retrieval lab](https://systemdesignsimple.com/how-ai-finds-one-line-in-100-pages/), BM25 found 29 of 30 same-word questions but only 4 of 30 reworded ones. Embeddings narrow the gap ([why a search for car finds vehicle](https://systemdesignsimple.com/why-search-for-car-finds-vehicle/)) without closing it. Plain RAG retrieves once, and the model answers from whatever came back.\n\nThe design we tested has three parts:\n\nThe grader only decides whether to continue. Each rewrite starts from the original question, and the steps stack: round 2 adds dictionary synonyms (`forgetting` adds `session cookie expiry`, and the original words stay), round 3 expands technical terms, and round 4 removes terms appearing in more than 4% of documents. Retrieved results do not influence these rewrites. The grader passes when the known answer page is in the top three; no answer is generated or checked.\n\nThe CRAG paper (Yan et al., January 2024) adds a lightweight evaluator that scores the retrieved documents and, based on its confidence, triggers different retrieval actions, including web search ([arXiv 2401.15884](https://arxiv.org/abs/2401.15884)). Self-RAG (Asai et al., October 2023) trains one model to retrieve on demand and critique passages with special reflection tokens ([arXiv 2310.11511](https://arxiv.org/abs/2310.11511)). Anthropic's engineering post of June 13, 2025 says its research subagents, after tool results, \"evaluate quality, identify gaps, and refine their next query\" ([Anthropic Engineering](https://www.anthropic.com/engineering/multi-agent-research-system)).\n\nThe script `labs/ai-33/measure-agentic-search-retries.mjs` builds 200 short made-up tech pages: 40 answer pages, 80 near misses that share one term with an answer page, and 80 filler pages. It asks 40 questions with one known answer page each: twenty in the page's own words, twenty in everyday words the page never uses. Search is plain BM25 (k1 = 1.2, b = 0.75), top 3. Node 22, seed 33; the counts repeat on every run.\n\n```\nsetting            found   technical  everyday  avg rounds  loop tokens/q  modeled s/q\none-shot           20/40   20/20      0/20      1.00        0              0.03\nagentic, cap 2     32/40   20/20      12/20     1.50        321            1.17\nagentic, cap 4     38/40   20/20      18/20     1.75        396            1.46\n```\n\nThe 0 of 20 for everyday wording is built in: those questions avoid the page's words, and BM25 only matches words, so the useful number is how many of them the loop recovers. Technical questions all hit on the first search and never paid for a retry.\n\nThe cap-4 run, round by round:\n\n| Round | Questions that ran it | Found | Estimated tokens | Modeled time added per question | \n|---|---|---|---|---|\n| 1 (first search + grade) | 40 | 20 | 7,081 | 0.59 s | \n| 2 (retry 1) | 20 | 12 | 5,740 | 1.15 s | \n| 3 (retry 2) | 8 | 6 | 2,429 | 1.19 s | \n| 4 (retry 3) | 2 | 0 | 593 | 1.14 s | \n\nEach retry round pays for a rewrite, a search and a grade, and two of those are model calls.\n\nIf most of your traffic hits on the first try, that first grade can cost more than the rescues are worth.\n\nIn Anthropic's data, agents used about 4 times the tokens of chat interactions and multi-agent systems about 15 times. Those figures describe whole agent systems, not this loop. We covered why each agent turn resends the conversation in [why an AI agent re-sends its history](https://systemdesignsimple.com/why-an-ai-agent-re-sends-its-history/).\n\nSet the cap from your logs. Here the third search still found 6 of the 8 questions left; the fourth found 0 of 2. Those two were never in reach of the rewriter:\n\n`everything crawl right top hour`: the word table had no useful entry.` query slower reboot orm eager join`, a database topic.\nThe cap-4 run also sent 2 repeated queries. With this fixed index and deterministic retriever, a repeated query costs a full round and cannot return anything new, so a cheap guard is to stop when the rewriter produces a query it already tried.\n\nAnthropic's post also put an effort rule into its agents' prompts: simple fact-finding needs one agent with 3 to 10 tool calls. This is their task-allocation heuristic; tool calls do not map directly to this lab's search rounds.\n\nWe ran `node labs/ai-33/measure-agentic-search-retries.mjs` on 2026-11-15, and it printed one table with three settings. A single search found 20 of 40 answers, and it found the answer page for none of the 20 everyday-wording questions. With a cap of 4 rounds the agent found 38 of 40, including 18 of the 20 everyday questions.\n\n*Our terminal after the ai-33 run, with the three settings and the round-by-round costs.*\n\nRound 2 rescued 12 questions for 5,740 approximate retry tokens, about 478 per rescue. Rounds 3 and 4 together rescued 6 questions for 3,022 retry tokens, an average of about 504 per rescue, and that average includes round 4, which ran for 2 questions and rescued none. Round 3 on its own worked out to about 405 tokens per rescue. The extra rounds were wasted on the 2 questions that were never found. The memory-leak rewrite drifted into database terms (\"query slower reboot orm eager join\"), and the cache-stampede rewrite only dropped words (\"everything crawl right top hour\") without adding a useful term. Raising the cap from 2 to 4 bought 6 more answers in this lab, and both misses came from the rewriter, so that is the part to watch.\n\nThe official page below confirms that Anthropic's research subagents evaluate tool results, identify gaps and refine their next query.\n\n*Anthropic Engineering's post on how it built its multi-agent research system.*\n\nThis version takes your own `search`, `grade` and `rewrite` and adds a repeated-query stop (the lab logged repeats and kept going, so its totals include them). Real `grade` and `rewrite` calls are model calls that return promises, so both are awaited. Run it with `node agentic-search-loop.mjs`.\n\n```\n// agentic-search-loop.mjs: the loop shape from labs/ai-33, Node 22, no packages\nconst words = (s) => s.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);\n\nexport async function searchWithRetries(question, { search, grade, rewrite, cap = 3 }) {\n  const tried = new Set();\n  let query = question;\n  for (let round = 1; round <= cap; round++) {\n    const key = words(query).join(' ');\n    if (tried.has(key)) return { found: false, reason: 'repeated query', rounds: round - 1 };\n    tried.add(key);\n    const hits = await search(query);\n    if (await grade(question, hits)) return { found: true, rounds: round, hits };\n    if (round < cap) query = await rewrite(question, round + 1);\n  }\n  return { found: false, reason: 'cap reached', rounds: cap };\n}\n\n// demo: two pages, a keyword search and a one-entry synonym table\nconst pages = [\n  { title: 'Session cookie expiry', text: 'session cookie expiry idle timeout' },\n  { title: 'Password reset', text: 'password reset email link' },\n];\nconst SYN = { forgetting: ['session', 'cookie', 'expiry'] };\nconst search = async (q) => pages.filter((p) => words(q).some((w) => words(p.text).includes(w)));\nconst grade = async (_question, hits) => hits.some((p) => p.title === 'Session cookie expiry');\nconst rewrite = async (question, round) =>\n  round >= 2 ? [...words(question), ...words(question).flatMap((w) => SYN[w] || [])].join(' ') : question;\n\nconsole.log(await searchWithRetries('Why does the site keep forgetting me?', { search, grade, rewrite }));\n```\n\nTo run the full lab, use `node measure-agentic-search-retries.mjs` in [labs/ai-33](https://github.com/systemdesignsimple/labs/tree/main/labs/ai-33) (Node 22, no install, no network). It also prints every question that was never found.\n\nIn this run, query expansion recovered vocabulary misses: everyday questions went from 0 of 20 to 18 of 20. Test the loop on representative questions before adopting it, and choose a cap from retrieval gains and cost on held-out traffic. We did not compare against applying the same expansion before the first search, so this experiment does not isolate the benefit of adaptive grading.\n\nThis article describes general patterns with a small simulation. It does not describe any company's private systems or measure any AI product. Numbers come from one run on 2026-11-15 with an answer-key grader and a fixed rewrite table.", "url": "https://wpnews.pro/news/agentic-rag-grade-the-search-rewrite-retry-with-a-cap", "canonical_source": "https://dev.to/systemdesignsimple/agentic-rag-grade-the-search-rewrite-retry-with-a-cap-4ne3", "published_at": "2026-11-23 13:40:05+00:00", "updated_at": "2026-11-23 13:42:38.655150+00:00", "lang": "en", "topics": ["ai-agents", "large-language-models", "ai-tools"], "entities": ["Anthropic", "CRAG", "Self-RAG", "Yan et al.", "Asai et al.", "Node 22"], "also_reported_by": [], "takeaway": "Capping agentic search retries at 2 recovered 12 of 20 everyday-word questions versus 0 for one-shot BM25, while a cap of 4 added only 6 more and its fourth round rescued nothing at roughly 1.2 seconds and a few hundred tokens per round.", "recommendation": {"advice": "Cap query-rewrite retries at 2-3 rounds and skip the grade when first-pass hit rates are high, since the fourth round rescued nothing and each retry costs a rewrite, a search and a grade.", "playbook": "rag-retrieval", "playbook_url": "https://wpnews.pro/playbooks/rag-retrieval"}, "alternates": {"html": "https://wpnews.pro/news/agentic-rag-grade-the-search-rewrite-retry-with-a-cap", "markdown": "https://wpnews.pro/news/agentic-rag-grade-the-search-rewrite-retry-with-a-cap.md", "text": "https://wpnews.pro/news/agentic-rag-grade-the-search-rewrite-retry-with-a-cap.txt", "jsonld": "https://wpnews.pro/news/agentic-rag-grade-the-search-rewrite-retry-with-a-cap.jsonld"}}