Single-Agent, Router and Retrieval Patterns

One well-built agent handles more than most teams expect. Learn its anatomy and its two closest relatives.

BeginnerIntermediateExpert · 13 min read · Last updated:

In short

A single agent is one decision loop with instructions, a model, a few tools, bounded state and clear limits. Basic tool calling is its smallest form. A router sends each request to a specialized path, and a retrieval agent decides what to search and answers from evidence. Start with the simplest pattern that passes your tests, and add parts only for failures you can name.

What you will learn: the parts of a production single agent, tool-calling flow, router design and measurement, retrieval agents, state, failure handling and when to move on.
Prerequisites: What Is an AI Agent? Anatomy and Goals, Agent Tools, Function Calling and Tool Registries and RAG Explained and Agentic RAG.

Beginner The core pattern

Choose the smallest pattern

PatternUse it whenMain weakness
Single model callOne input, one output, no actionsNo fresh facts or effects
Fixed workflowSteps are known in advancePoor with unexpected cases
Basic tool callingA question needs a lookup or an actionLimited planning
RouterRequests fall into distinct kindsMisrouting
Retrieval agentAnswers depend on documents and may need several searchesCost and weak evidence
Single agent loopThe next step depends on what was foundVariable behavior

The patterns combine: a router may send one kind of request to a fixed workflow and another to an agent loop.

Anatomy of a production single agent

Entryidentity, limits, input checks
Context builderinstructions, state, evidence
Modelanswer or request a tool
Policy and toolsvalidate, authorize, execute
Exitcheck output, record outcome
↺ Tool results return to the context builder until a stop rule applies
The model decides; surrounding code controls.
PartProduction duty
InstructionsRole, task, boundaries; versioned and tested
ContextSelect what is needed; label sources
ToolsFew, clear and permission checked
StateWhat has happened in this task
Stop rulesGoal met, step, time and cost budgets, repeats
FallbackAsk, hand over or decline
TraceEvery decision and call

Define the agent before building it

A short written definition prevents most later arguments about behavior. Keep it with the code and review changes to it.

FieldExample for a help desk agent
UsersSigned-in employees
GoalAnswer policy questions and report ticket status
Out of scopePay disputes, legal questions, changes to accounts
ToolsSearch policies, read own tickets, create a draft ticket
LimitsSix steps, a time limit and a cost limit per request
HandoverSupport queue, with the conversation and evidence
SuccessCorrect, cited answers and tickets accepted without rework

Each row suggests tests. "Out of scope" becomes refusal cases, "limits" becomes a runaway case and "handover" becomes a check that the receiving person gets what they need.

Basic tool calling

  1. Send the request with the available tool definitions.
  2. The model replies with text or with a tool name and arguments.
  3. Your code validates, authorizes and runs the call.
  4. Send the result back.
  5. The model answers or asks for another call, within a limit.

Even this small flow needs error handling for unknown tools, invalid arguments, failures and empty results.

Bound the loop

The program below uses scripted functions in place of a model so that the control behavior is repeatable.

"""A bounded single-agent loop with a scripted stand-in for the model."""

def get_stock(item):
    return {"lamp": 0, "desk": 4}.get(item, "unknown item")

def find_substitute(item):
    return {"lamp": "desk lamp mini"}.get(item, "none")

TOOLS = {"get_stock": get_stock, "find_substitute": find_substitute}

def run(model, max_steps=5):
    history, seen = [], set()
    for step in range(1, max_steps + 1):
        action = model(history)
        if action[0] == "answer":
            return f"done in {step} steps: {action[1]}"
        _, name, argument = action
        if name not in TOOLS:
            history.append((action, "error: unknown tool"))
            continue
        if (name, argument) in seen:
            return f"stopped at step {step}: repeated call to {name}"
        seen.add((name, argument))
        history.append((action, TOOLS[name](argument)))
    return f"stopped: step limit {max_steps}, hand over to a person"

def good(history):
    if not history:
        return ("tool", "get_stock", "lamp")
    if len(history) == 1:
        return ("tool", "find_substitute", "lamp")
    return ("answer", f"Out of stock. Alternative: {history[-1][1]}")

def stuck(history):
    return ("tool", "get_stock", "lamp")

def wandering(history):
    return ("tool", "get_stock", f"item-{len(history)}")

for model in (good, stuck, wandering):
    print(f"{model.__name__:<10} {run(model)}")

Output:

good       done in 3 steps: Out of stock. Alternative: desk lamp mini
stuck      stopped at step 2: repeated call to get_stock
wandering  stopped: step limit 5, hand over to a person

The well-behaved run finishes in three steps. The stuck one is stopped at its first repeat, and the wandering one at the step limit with a handover. Real repeat detection needs care: reading a status again after waiting is legitimate, so compare calls together with state or allow a stated number of repeats. See Agent Decisions: Confidence, Stopping, Loops and Budgets.

Decide what the model sees

Most behavior changes come from context, so build it deliberately. Put stable instructions first, then the user's rights and relevant facts, the task state, the retrieved evidence and the latest message. Offer only the tools that make sense for this user and step. Trim old tool results once their facts have been recorded in state. Keep text from outside clearly separated from your instructions. Log which versions of instructions, tools and sources were used, so that a strange answer can be reproduced. See What Is Context Engineering? Stack and Token Budgets.

Check the result before it leaves

  • Does the output match the required format?
  • Do cited sources exist and support the statements?
  • Does a claimed action have a matching successful tool result?
  • Does it expose data the user may not see?
  • Is anything required missing, such as a warning or next step?

Use ordinary code for exact checks and reserve model-based judging for qualities that code cannot measure. Decide what happens on failure: one correction attempt, a safe standard reply or a handover.

Intermediate Router

The router pattern

Request
Routerrules, classifier or model
Billing pathown tools and instructions
Technical pathown evidence sources
Personunclear or out of scope
Each path stays small and can be tested alone.
Router typeStrengthWeakness
RulesCheap and predictableBrittle wording
Trained classifierFast, measurableNeeds labeled data
Model with fixed choicesHandles varied languageCost, latency, can still be wrong
"""A small router with a fallback, measured on labeled requests."""
import re

ROUTES = {
    "billing": {"invoice", "charge", "refund", "payment", "bill"},
    "technical": {"error", "crash", "login", "password", "bug"},
    "shipping": {"delivery", "parcel", "tracking", "shipping", "arrive"},
}

def route(text, minimum=1, margin=1):
    words = set(re.findall(r"[a-z]+", text.lower()))
    scores = sorted(((len(words & keys), name)
                     for name, keys in ROUTES.items()), reverse=True)
    (best, name), (second, _) = scores[0], scores[1]
    if best < minimum or best - second < margin:
        return "human"
    return name

LABELED = [
    ("I was charged twice on my invoice", "billing"),
    ("Login error after password reset", "technical"),
    ("Where is my parcel? Tracking is empty", "shipping"),
    ("Refund the delivery charge", "billing"),
    ("The app crashes when I open a bill", "technical"),
    ("My order never showed up", "shipping"),
    ("Do you offer student discounts?", "human"),
    ("Payment page shows a bug", "technical"),
]

correct = sent_on = wrong = 0
for text, expected in LABELED:
    chosen = route(text)
    correct += chosen == expected
    if chosen != expected:
        kind = "fell back" if chosen == "human" else "MISROUTED"
        sent_on += chosen == "human"
        wrong += chosen != "human"
        print(f"{kind:<10} expected {expected:<10} got {chosen:<9} {text}")
print(f"correct {correct}/{len(LABELED)}, "
      f"unneeded fallbacks {sent_on}, misroutes {wrong}")

Output:

MISROUTED  expected technical  got billing   The app crashes when I open a bill
fell back  expected shipping   got human     My order never showed up
fell back  expected technical  got human     Payment page shows a bug
correct 5/8, unneeded fallbacks 2, misroutes 1

The keyword router gets five of eight right. Two failures are harmless fallbacks to a person; one sends a crash report to billing. Treat the two kinds separately, because a misroute is usually worse. Tune thresholds on one set and measure on another, and replace the scoring with a classifier or model while keeping this harness.

  • Provide a fallback route and monitor how often it is used.
  • Allow rerouting when a path discovers it is wrong, with a limit.
  • Handle mixed requests by splitting or asking.
  • Never let the route grant permission. Each path still authorizes the user.

Keep the router honest

Count requests per route, fallbacks, reroutes and complaints by route. Read a sample from every route each week while the system is new, since a confident wrong route produces no error message. When a new kind of request appears, add examples to the test set first, then decide whether it needs its own path. Avoid dozens of tiny routes: neighboring categories become hard to separate and every path needs an owner. If two routes share tools, instructions and tests, merge them. Record the router version and its choice in the trace so that downstream failures can be traced back to it.

The retrieval agent

Simple retrieval-augmented generation searches once and answers. A retrieval agent decides whether to search, where, with what query, whether the results are enough and when to stop.

Question
Plan searchsource and query
Retrievepermission filtered
Judge evidencerelevant, current, enough?
Answer with citationsor say it is not known
↺ Rewrite the query or try another source, within a budget
The stop decision matters as much as the search.
  • Filter by the user's rights before text reaches the model.
  • Limit searches and total retrieved text.
  • Prefer authoritative and current sources, and show dates.
  • Check that each citation supports its sentence.
  • Treat retrieved text as data, not instructions.

Measure retrieval and answers separately, as described in RAG Evaluation, Grounding and Debugging. If one search nearly always suffices, the simpler pipeline is better.

When retrieval agents go wrong

SymptomLikely causeTry
Searches repeat with small changesNo stop rule or poor result summariesCap searches; report what was already tried
Confident answer, weak sourceNo sufficiency checkRequire evidence per claim
Old policy quotedStale index or missing datesFilter by validity and show dates
"Not found" for known factsWrong source or vocabulary mismatchHybrid search and better source descriptions
Slow and costlyToo much text returnedRank, trim and read sections on demand

Combining the patterns

A realistic assistant often uses all four. The router recognizes the kind of request. Policy questions go to a retrieval path with no write tools. Status questions use basic tool calling against one system. Open problems go to an agent loop with a few tools and a tighter budget. Changes go to a fixed workflow with approval. Giving each path only the tools and data it needs reduces both confusion and the damage that a mistake can cause. Test each path alone and then the whole system with requests that sit between paths, which is where most surprises appear.

Expert Running it

State and conversation

Keep short task state in a structured record: goal, facts gathered, actions taken, open questions. Rebuild context from it instead of resending an ever-growing transcript. When tasks outlast a request, move to the design in Stateful and Long-Running Agent Architecture. Add long-term memory only with rules for consent, correction and deletion, as in Agent Memory Types and Persistence.

Failure handling

FailureResponse
Model service unavailableRetry within budget, fall back or queue
Invalid tool requestReturn a specific error; limit corrections
Tool outcome unknownLook up before repeating
No evidenceSay so; offer next step
Budget reachedStop with progress and handover
Policy denialExplain; do not work around

What to trace

For each run keep the request identifier, user and tenant, route chosen, versions, evidence identifiers, tool calls with outcomes, stop reason, tokens, time and cost. The stop reason deserves its own field: finished, asked the user, handed over, budget reached, denied or error. Its distribution is an early warning. A rising share of budget stops suggests wandering; a rising share of handovers suggests new kinds of request or a failing source.

Release checklist for the pattern

Evaluate on representative tasks, including refusals and failures. Compare with a plain workflow to confirm the agent adds value. Release to a small group, watch task success, handovers, latency and cost, and keep a quick way to turn off actions while leaving read-only help available.

Latency and cost

Each loop step adds a model call and often a tool call, and context tends to grow with every step. Measure time and cost per completed task, not per call. Cheap improvements include removing unused tools from context, returning smaller results, running independent read calls in parallel, caching stable content and using a smaller model for routing if it passes the tests. Show progress to users during longer tasks and let them stop it. Set targets for the slowest few percent as well as the average.

When one agent is not enough

Consider more structure when instructions conflict across tasks, the tool list grows until selection suffers, different parts need different permissions, or work can proceed in parallel. Try routing and better tools first. Several agents add coordination, cost and new failures; see Single-Agent vs Multi-Agent Systems.

Illustrative example: a help desk grows in stages

A team starts with retrieval over policy pages. Users then ask for ticket status, so they add one read tool. Later, password resets arrive, which need an approval step, so a router sends those to a fixed workflow. Each addition follows a measured failure, and the evaluation set grows with it.

The handover is part of the design

A handover that loses information makes people repeat themselves and distrust the agent. Pass the original request, what was checked, results with their sources, anything already changed and the reason for stopping. Tell the user what happens next and when. Let the receiving person mark whether the handover was needed and whether the summary was right. Those two marks give you labeled examples for the router and the stop rules at almost no extra cost.

A build order that works

  1. Write twenty to fifty realistic tasks with expected outcomes.
  2. Try a single model call and record what fails.
  3. Add retrieval for missing knowledge.
  4. Add read tools for live facts.
  5. Add a bounded loop if steps depend on results.
  6. Add write tools with permissions and approval.
  7. Add routing when distinct kinds of work interfere.

Revisit the choice of pattern after real use. If one route handles most traffic with a single predictable step, turn it into ordinary code and keep the model for the parts that need judgment.

Common mistakes

  • Starting with several agents.
  • Unlimited loops.
  • A router with no fallback or measurement.
  • Searching without checking whether results help.
  • Placing permissions in instructions.
  • Keeping the whole history forever.
  • Judging the design from a demonstration.

Checklist

  • The chosen pattern is the simplest that passes tests.
  • Entry, policy and exit checks exist outside the model.
  • Step, time and cost budgets are enforced.
  • Routing has a measured fallback.
  • Retrieval respects permissions and cites sources.
  • State is structured and bounded.
  • Failures have defined responses.
  • Every run can be traced.

Frequently asked questions

Is a router an agent?

Usually it is one decision point inside a workflow. The label matters less than testing its choices and giving it a safe fallback.

How many tools can one agent have?

There is no fixed number. Watch selection accuracy and context size, and group or route tools when they start to interfere.

Do I need a framework?

No. A direct loop is a good way to learn. Frameworks help with state, streaming and pauses once those needs appear.

Retrieval agent or plain retrieval?

Use plain retrieval when one search answers most questions. Add decision making when sources vary or queries often need refinement.

References and further reading

Next steps