When One RAG Pass Isn't Enough: Iterating on Agent RAG in Anchr
Anchr started out with a single traditional RAG pipeline: the user asks a question, the system searches for relevant passages, reranks them, feeds the top few chunks to the model, and generates an answer with citations.
1 | User question → Retrieval → Rerank → Build context → Generate answer |
For most factual questions, that pipeline is plenty. Ask “what happens to the old index after a document is re-parsed?” and as long as the knowledge base covers it, a single search pulls up the core material. The model just has to organize it into a clear answer.
But some questions don’t work like that:
Find everything across the design docs related to task recovery, then compare what happens on process restart, network disconnect, and user-initiated cancellation.
You can’t piece that answer together from a handful of pre-fetched chunks. The first search might only surface the notes on Agent run recovery. Reading further, you find it also involves async tasks (Task). Looking up Task brings up the distinction between in-process state and persisted state. By the time you cross-check deployment constraints at the end, your understanding of “recovery” looks nothing like what you started with on round one.
What you search next depends entirely on what you just read. Anchr’s Agent RAG was built for this kind of problem.
Cranking up Top-K still won’t tell you what to search next
In traditional RAG, retrieval happens before generation, and it’s usually a single pass. Not enough material? The obvious move is to raise the candidate count (Top-K) from 10 to 30 or 50, hoping a bigger net will catch everything at once.
If the relevant passages were already in that first recall pool, just ranked too low, raising Top-K actually helps. That’s not what’s happening in the “task recovery” question above. The user’s original prompt never mentions “lease,” “run snapshot,” or “single-instance.” Round one has no way to know it should reserve slots for them.
Worse, widening the candidate pool pulls in noise along with it. Adjacent paragraphs from the same long document tend to hit together, so half of those 30 results end up repeating the same point. The model wastes effort picking through noise, and it still has no way to find a new angle to investigate.
What we actually need is to split the actions apart: use search to find an entry point, then read sequentially to see the surrounding context. Once new leads show up, launch the next search.
1 | Search "Agent recovery" |
So I gave the Agent two distinct tools: search for locating “where things are,” and sequential read for checking “what’s being said right before and after this spot.” Say a search hits this sentence:
Once the new index generation finishes writing and passes visibility checks, promote it to the active version.
The sensible next move is almost always to pull up the neighboring paragraphs: the one before might explain why you can’t overwrite in place, and the one after might cover when old versions get cleaned up. If you run another global semantic search instead, you can easily bounce straight into an unrelated “index versioning” section elsewhere in the docs.
Of course, sequential reading needs a limit. A long document can split into hundreds of chunks; reading it cover to cover requires batching, summarizing, and merging. That kind of heavy work shouldn’t block an interactive Q&A request. When that comes up, it belongs in an independent background job. The online Agent should only decide whether to hand it off to the background, never keep paging through a long file on its own.
Getting tool calling to run is easy; the edge-case rules pile up fast
The first version of the Agent loop was simple: the model takes the user’s question and a list of tools, and decides whether to search, read, or answer directly. The backend runs the tool, appends the result to context, and hands it back to the model for the next turn.
1 | Model decides → Execute tool → Append result → Back to model |
Once that loop starts running, the problem stops being “how do I call a tool?” and turns into “what happens when five edge cases collide at once?”
For instance, the model might emit several tool calls in a single response. If the backend runs them concurrently, the later calls are still operating on stale context from before the first call returned. If the first search already uncovers a new lead, those other pre-planned searches might not even make sense anymore. So in Anchr, tool calls go into a queue and execute serially, one by one. Before each call runs, the system re-checks the budget, checks for duplicates, and checks reading limits.
Once execution is serial, you also have to stop the model from repeating the same call over and over. Right now we check the Tool Call ID (the unique identifier the model assigns to each call) first; if there isn’t one, we compare the tool name and arguments.
Whatever you do, don’t deduplicate by semantic similarity here. If the model searches agent recovery in round one and how agent run recover in round two, they look similar on the surface, but that may well be a useful query rewrite. Calling another model just to judge whether two queries mean the same thing is slow, expensive, and unreliable. So the system only blocks exact duplicates. If the model keeps rephrasing the same search over and over, the overall budget cuts it off.
Deduplication is just the tip of the iceberg. Edge cases pile up fast: what if the budget runs out with two tools still sitting in the queue? If the first tool throws an error, do the remaining ones still run? What if the model finishes writing an answer, only for backend validation to catch bad citation formatting? Add the fact that the user can click “Cancel” at any millisecond, and all that control logic quickly bleeds across model invocation, tool execution, and state persistence into an unreadable tangle.
Eventually I refactored that whole layer into an explicit state machine. Not because every Agent needs a state machine, but because once execution order and termination rules get this complicated, you need a way to isolate and verify them on their own.
Each step of the state machine only cares about three things: the current state, the event that just happened, and what to do next. Side-effecting I/O (calling the model, searching documents) lives completely outside the state machine. Once an operation finishes, its result gets wrapped as a new event and fed back in.
1 | Current state + New event |
Splitting it this way makes testing much easier. Want to test a tricky corner case like “8 tool calls already spent, usable evidence in hand, one search still left in the queue”? Just construct that state in memory, feed it to the state machine, and assert that it transitions cleanly to wrap-up. You don’t need to hit the LLM and search APIs eight times, or hope the model happens to wander down that branch. A state machine doesn’t shrink the number of branches, but it lets you see each one clearly and test it properly.
Still, the state machine only governs “where to go next.” The Agent has another ledger to keep: over the course of this run, what material has it actually seen?
The backend has to keep the ledger of what the model has seen
Tool calling returns structured arguments, but it’s still external input generated by a model. The backend can never trust it blindly.
Say the user scoped this Q&A session to just two documents: System Design and Agent Design. On some turn, the model hallucinates a completely different document ID and passes it to the read tool. The backend can’t query the database just because the ID came from a tool call. It has to verify that the document exists, that the current user has permission to view it, and that it falls inside the selected scope.
We do put the document scope into the prompt to keep the model on track, but access control can never rely on prompts as a fallback. Every check you run on parameters coming from the frontend has to run on parameters coming from the model, including resource permissions and version filtering.
Once unauthorized reads are blocked, the next constraint is what the final answer is allowed to cite.
Traditional RAG feeds context to the model once, so citations obviously come from that single batch. An Agent runs multiple rounds of lookups:
1 | First search → gets chunks A, B, C |
After a few rounds, the model has seen eight chunks, and the conversation history may still contain citation numbers left over from earlier turns. When the model drops a [3] into its final answer, how does the backend know whether [3] refers to a chunk retrieved in this run, a leftover citation from an earlier turn, or an ID the model made up on the spot?
So in Anchr, whenever a tool returns document chunks, the backend logs an entry into a per-run ledger. In the codebase it’s called Evidence Registry, and its sole job is recording the document chunks this run actually retrieved. The final answer is only allowed to cite from this ledger.
When the model submits its answer, the backend runs a strict check against the ledger: does the answer status match the citations? Are all cited IDs actually in the current registry? Is the inline citation syntax valid? If the registry only holds three chunks and the model cites [5], the answer gets rejected outright.
On the first rejection, the system feeds the exact validation error back to the model and gives it one shot to fix the answer using the evidence already in hand. If the second attempt still fails validation, the system stops arguing with it and falls back to a safe no-evidence response, rather than burning tokens trying to patch broken citations.
Of course, this check only guarantees that the citation really came from material retrieved in this run. It cannot prove that the model actually understood the source text. A model can easily cite a real passage while dropping its preconditions. Inline citations exist so users can click straight back to the source and verify; they don’t make the model’s conclusion guaranteed fact.
With the ledger built and citations checked, the Agent can now decide on its own to keep searching and reading. That immediately raises the next question: how long do we let it keep looking?
If hitting the limit just throws an error, all the prior work goes to waste
Traditional RAG is one search plus one generation, so latency is predictable. An Agent can chain turn after turn of model calls and tool runs. Without hard caps, a routine online question can easily turn into an endless research session.
Right now Anchr’s default budget is: at most 12 model steps, 8 tool calls, 90 seconds total wall-clock time, and 30 seconds max per model call. We don’t just check the budget once at the start. Before every model call or tool execution, the system recalculates how much headroom is left.
For example, if the total run cap is 90 seconds and 84 seconds have already elapsed, even though a normal model call gets a 30-second timeout, this final turn cannot be given 30 seconds: it gets 6 seconds at most. Otherwise the 90-second cap is meaningless, and one last slow request can blow right past it.
Sequential reading has its own limit too. Once usable evidence is in hand, a single run is allowed at most two consecutive page-flips. On the third attempt to keep reading forward, the system steps in, refuses to load any more text, and forces the model to wrap up with what it already has. If a question truly needs reading a tens-of-thousands-of-words document end to end, it should have gone to a long-running background task from the start, not kept paging through an online Q&A session.
Setting caps only answers when to stop. The more practical question is what happens to the material we already found when a run hits its limit.
Suppose the Agent ran several rounds of search, collected useful material in the Evidence Registry, and ran out of steps or seconds right before writing the final answer. If you throw a generic “execution failed” error to the frontend at that point, all that work is wasted.
So the moment the budget runs dry, the system checks the ledger first:
1 | Budget exhausted |
That second path is called Evidence Finalizer in the code. Once it enters this stage, all tools are taken away and no further planning is allowed; the input contains only the chunks logged in the current registry. Its job is straightforward: whether or not it found everything, synthesize what is already in hand and give the user something concrete. If the ledger is empty, never fabricate.
If even this finalizer step fails (say the remaining few seconds aren’t enough for the model to finish generating, or the citations still fail validation), the system returns a degraded status (“found partial material, failed to generate a final answer”) instead of pretending it succeeded normally. In Anchr, “found nothing,” “found material but didn’t finish the answer,” and “delivered a verifiable answer” are three distinct business outcomes.
Between budget controls and forced wrap-up, we keep single runs within tens of seconds. Even tens of seconds feels long in a browser, though, which meant rethinking the relationship between the browser connection and the backend job.
Once runs take tens of seconds, you can’t bind them to the browser connection
Traditional RAG takes a few seconds, so the user asks and waits. An Agent routinely runs for tens of seconds across multiple rounds of searching, reading, and reasoning. If the UI just spins a loading indicator, the user has no idea whether it’s still searching or hung.
To fix that, Anchr uses SSE (Server-Sent Events) to stream every backend step to the frontend in real time: planning, which document it’s searching, and which passage it’s reading are all visible on screen. Answer text that can be shown early streams in chunks too; once the full response passes citation validation, the UI reconciles to the final verified state.
There’s a big trap here, though: the SSE connection must never be synonymous with the Agent run itself.
Users refresh tabs, switch Wi-Fi networks, or close their laptops all the time. Any of those drops the connection. If the backend kills the run the moment the socket closes, someone who waited forty seconds and accidentally hit refresh loses all progress.
In our current setup, a dropped connection simply stops the backend from pushing live events down that stream. The Agent keeps running to completion and persists the conversation and final state to the database as usual. When the user reopens the page, it loads the finished result from disk. Architecturally, the live run snapshot in Redis only serves real-time UI updates; the actual source of truth lives in MySQL’s conversation, Run, Step, and Task tables.
Once online runs are decoupled from the browser connection, the “full-document read” handoff falls into place naturally. When the Agent realizes a job won’t fit inside an online turn, it creates a standalone background task, persists the task record, and finishes the current Q&A turn right away. The background task reads the document, summarizes in batches, and merges progress in the background; even if the user closes the browser and walks away, it finishes on its own.
Since a disconnect no longer means cancellation, users who actually want to stop a run call a dedicated cancel endpoint. That introduces a classic concurrency race (nothing to do with AI at all): suppose the Agent just finished writing its answer and is about to commit COMPLETED to the database; in the exact same millisecond, the user clicks cancel, firing a request to write CANCELLED.
1 | Worker thread: checks not cancelled → about to commit COMPLETED |
If your code just checks an isCancelled boolean in a few scattered spots, the two will collide in the millisecond window between “last check passed” and “actually wrote to the database.” So in the implementation, the three terminal states (cancelled, completed, and failed) must contend for the same lock (a shared critical section). Whoever commits first wins: if cancellation lands first, the finished answer arriving a moment later gets discarded; conversely, if the answer already committed, a late cancel request isn’t allowed to overwrite it.
At this point, whether the socket is alive, whether the user cancelled, and whether the backend finished are separated into three independent concerns. You can see the trade-off: giving the Agent multi-round investigation adds real runtime overhead and plenty of new places to break.
Which forces the last question: now that the Agent can do all this, shouldn’t we just delete the fixed RAG pipeline?
Why we kept fixed RAG anyway
On paper, the Agent can search, read, and decide for itself, so it can do everything fixed RAG does. The cost math looks different, though. Suppose the user just asks, “What is the release date of this document?” Fixed RAG does one search and one generation and finishes. Route that through the Agent, and it has to spend at least one model call deciding “I should search,” run the search, and then spend a second model call writing the answer. For a trivial question, that’s an extra LLM round-trip out of thin air, making it slower and more expensive.
So in Anchr, the two paths coexist. Straightforward questions with a clear target default to fixed RAG; complex questions that call for cross-document comparison, following trails across sections, or deciding step by step let the user explicitly toggle Agent mode. The boundary between the two isn’t clean enough yet for an automatic router to get right every time, so for now the choice stays with the user.
There’s a second practical reason to keep fixed RAG around: as a fallback.
Fixed RAG only has two places to fail: retrieval and generation. An Agent has a much longer chain and far more ways to fail: malformed tool arguments, planning loops, tool execution errors, or citation validation failing repeatedly. When configuration permits and the Agent hits an unexpected orchestration error, the system automatically falls back to fixed RAG and runs a plain single-pass retrieval and generation.
Naturally, that fallback can’t preserve answer quality on genuinely complex questions. A question that needed three or four hops across documents will probably get a partial answer from a single search. The fallback isn’t meant to treat the two pipelines as equivalents. It’s there so that when the Agent framework itself hiccups, the user still gets something useful back instead of an empty error screen.
Honestly, this Agent’s capabilities are still pretty narrow. It can only read authorized documents inside Anchr: no web browsing, no code execution, no browser automation. One question runs end to end inside a single workflow, with no multi-agent setup where a Research Agent and a Reviewer Agent pass work back and forth. The only thing it’s trying to nail right now is continuing to investigate along the document’s own threads when one retrieval pass isn’t enough, while keeping permissions, latency budgets, and citation provenance cleanly accounted for on the backend.
Getting tool calling to work is only the first step. Traditional RAG runs down a straight track, whereas an Agent interlocks search, reading, and generation so each step depends on the last. To keep that nondeterminism under control, the backend has to grow a memory of its own: tracking which tools already ran, what evidence is in hand, how much time is left, and whether the run ends as completed, degraded, or cancelled.
None of this shows up in a tool-calling demo, but once you try to turn RAG into a production Agent RAG system, this is where most of the real work lives.
Source code: https://github.com/ryanmeowy/anchr-app