Contents

Foundation Model Engineering

Manuscript updated (UTC) · Chapter source on GitHub · Cite this chapter (RIS)

On this page

14.4 RAG Orchestration: Routing and Agents

“How long do I have to cancel a renewal?” and “Can I still cancel my renewal?” use almost the same words. A support assistant can answer the first from the current policy. To answer the second it also needs the caller’s renewal date. Searching the handbook twice will never produce that date.

A RAG orchestrator decides which sources a request needs, what evidence fits in the prompt, and when to stop. Follow those decisions for a fictional subscription service.

1. Query Routing

A public question about the policy takes one handbook lookup. A question about a particular renewal also needs a read-only account lookup. An exact error code deserves a different route again: the previous lesson shows how a lexical search can find an identifier that a semantic search missed.

LLM-Based Routing

Give the routing model a small vocabulary such as policy, my_renewal and clarify. Its output proposes a route. The application still controls which operations can run. A well-formed {"route":"my_renewal"} contains neither the caller’s identity nor a probability that the decision is right.

The Python example replays four possible replies. It only constructs a plan. In a service, the authorization flag comes from the server’s access check, and the account tool binds its lookup to the caller’s authenticated account. No account identifier comes from the model.

import json

def plan(reply, *, can_read_own_renewal):
    try:
        decision = json.loads(reply)
    except (TypeError, ValueError):
        return ("clarify",)

    if decision == {"route": "policy"}:
        return ("read_current_policy",)
    if decision == {"route": "my_renewal"}:
        if can_read_own_renewal:
            return ("read_current_policy", "read_own_renewal")
        return ("sign_in",)
    return ("clarify",)

for reply, allowed in [
    ('{"route":"policy"}', False),
    ('{"route":"my_renewal"}', False),
    ('{"route":"my_renewal"}', True),
    ('{"route":"my_renewal","account":"other"}', True),
]:
    print(plan(reply, can_read_own_renewal=allowed))

The first reply selects the handbook. The same personal-renewal reply gives ('sign_in',) for a visitor and a two-source plan for an authorized customer. The last reply adds an unexpected field, so the planner returns ('clarify',). A refusal, an unrecognized label or malformed JSON also needs a fallback. Even a reply that passes these checks can select the wrong source.

Routing Is a Budgeting Problem, Not Just a Classification Problem

Suppose the router sends a personal question to the public-policy route. The handbook can supply a cancellation window, but the assistant still lacks the date needed for a yes-or-no answer. To evaluate the router, label questions by the evidence they require. Count personal questions that lost their account lookup separately from public questions that triggered an unnecessary sign-in. Also measure retrieval calls per answered question and end-to-end latency.

2. Context Management and “Lost in the Middle”

The two-source plan returns a policy passage and a renewal record. Suppose the model has a 2,048-token window. The instructions and message framing use 448 tokens, the question and conversation use 256, and the application reserves 256 for the answer. That leaves 1,088 tokens for evidence. A 640-token policy passage and a 128-token account record fit, leaving 320. A 512-token FAQ would exceed the budget by 192. These counts are invented for the exercise. Measure with the serving tokenizer and actual message template.

The “Lost in the Middle” Phenomenon [1]

Liu and colleagues moved the answer-bearing document within a multi-document question and varied the position of a target key in a lookup task. For several models and settings, accuracy fell when the evidence was in the middle. Try moving the same policy passage to the start, middle and end with the question, other passages and total length held fixed. Check both the answer and whether its citation supports it. The best order for this service is a measurement. [1]

Context Assembly Is a Policy Layer

Reserve space for the renewal record before adding background material. If you shorten the handbook passage, check that the summary still distinguishes a renewal from a first purchase. A summary can preserve the number of days while silently changing which transactions it covers. Record the policy version and the passage IDs actually sent so you can reconstruct a wrong answer.

3. Agentic RAG: Beyond Linear Pipelines

If the two required sources are known up front, the service can fetch them directly once the access check passes. A loop becomes useful when a result determines the next lookup.

The ReAct Framework (Reasoning + Acting)

ReAct interleaves reasoning and actions so an observation can change the next action. [2] Suppose the handbook says that partner subscriptions follow their provider’s policy. The customer’s authorized renewal record names partner P. The next lookup is P’s current policy. If the account record instead identifies a direct subscription, the assistant can use the handbook and skip that lookup.

Agentic RAG Needs Stop Conditions

Give this example a limit of three source calls per request. The handbook and the renewal record use two calls. One remains for P’s policy. If the third call returns only an expired policy, the answer should identify the missing current rule and offer a support handoff. Repeating the first search would spend more time without resolving the question. Track why the loop stopped and how often customers received a supported answer within the budget.

4. Summary

For one renewal question, three checks catch different mistakes. Did the plan request the right evidence? Did the prompt include the policy exception and the renewal date? Did the final answer cite a rule that applies to this customer? If a citation looks plausible but the answer is wrong, trace the refund-policy incident. The next section looks at a different retrieval problem in which the evidence is spread across relationships.

Quizzes

Quiz 1: Two visitors ask about renewals. Which question can the service answer using the handbook alone? It can give the general cancellation window. To decide whether a particular renewal is still within that window it also needs an authorized record with the renewal date.

Quiz 2: The planner receives valid JSON naming the personal-renewal route. What evidence would tell you how reliable that choice is? Compare the router’s choices with the required sources for labeled questions, including closely worded public and personal requests. The JSON label itself carries no calibrated probability.

Quiz 3: With 320 evidence tokens left, what should happen to a 512-token FAQ? It would exceed the window by 192 tokens. Leave it out if the policy and account record already answer the question. If it contains a necessary exception, extract that passage and measure the new total.

Quiz 4: The third source call returns an expired partner policy. What can the assistant tell the customer? It can explain that the subscription is handled by the partner and that the current cancellation rule is missing. It can offer a handoff. The expired deadline cannot establish current eligibility.

References

  1. Nelson F. Liu et al. (2024). Lost in the Middle: How Language Models Use Long Contexts. Transactions of the Association for Computational Linguistics.
  2. Shunyu Yao et al. (2023). ReAct: Synergizing Reasoning and Acting in Language Models. Paper.