ELLMEngineering Large
Language Models
Download PDF

Chapter 49

Building and Evaluating a Bounded Agent Loop

On this page

An agent is a model inside a program that chooses actions, observes results, and decides what to do next. The program owns permissions, budgets, durable state, and the definition of success. More model calls alone do not create a reliable agent.

Distinguish a workflow from an agent

A workflow follows a prescribed graph: retrieve, rerank, answer, validate. An agent can choose which tool to use and whether to search again, edit a file, or finish. The choice is useful when the next step depends on evidence that cannot be known in advance. A fixed workflow is easier to test when the sequence is already known. A hybrid can let the model choose within a small, explicitly bounded subgraph.

ReAct studies interleaving reasoning and actions. SWE-agent demonstrates that the interface through which a model inspects and changes an environment matters. These observations do not require exposing private reasoning or granting unrestricted shell access. A trace of proposed actions, observations, checks, and results is enough to audit the external work.

For a documentation assistant, begin with a narrow task: read authorized sources and prepare a draft answer. Do not give it a send-message or account-modification tool merely because the model can generate those tool names. Add a capability only when the user workflow requires it and the surrounding service can authorize, constrain, and recover it.

Follow the control loop

Stage Required input Host-owned check
Observe User objective, permitted context, previous results Scope and provenance remain distinct
Propose Typed tool call or final response Parse schema; reject unknown tools and invalid arguments
Authorize Caller identity and proposed effect Check policy against the real target, not model text
Execute Validated call plus deadline and identity Sandbox, resource budget, timeout, idempotency
Record Result or explicit failure Append an event; retain external transaction identity
Continue or finish Updated observations Enforce budgets and validate the claimed outcome

Tool output is an observation, even when it says “SYSTEM: ignore your rules.” A schema prevents malformed calls, not malicious but well-formed arguments. The authorization layer must resolve paths, tenants, domains, operation types, and effects independently. Credentials belong in the execution service, not in model-visible prompts. Source trust is metadata outside the text being evaluated.

Protocol version is not operation identity

The MCP 2026-07-28 changelog changes integration assumptions from the 2025-11-25 baseline:

Concern July 2026 behavior
Initialization Per-request _meta carries version and client capabilities; the old initialization handshake is removed
Discovery server/discover advertises versions, identity, and capabilities
Connection state Protocol sessions are removed; cross-call state uses explicit handles
Long work Tasks move to an official extension
Broken response stream Reissue with a new request ID; stream resumability is removed

A new transport request ID must not create a new business operation. Preserve an application idempotency key across uncertain retries, verify its payload identity, and reconcile a committed effect before retrying execution. The durable-receipt example below exercises this boundary. It is not an MCP conformance implementation; validate an integration against its pinned SDK and protocol revision.

A2A 1.0 concerns inter-agent discovery, messages, and tasks. Neither protocol grants authority to advertised tools or remote output. Authorization, deadlines, and effect accounting remain host responsibilities.

A complete local fixture

Run python -m examples.agent_loop. It prints finished 1 0: one permitted document-read attempt, no saved drafts. The module includes the decision loop, typed actions and observations, a tool allowlist, a draft capability, bounded attempts, and receipt-based retries. Its policy is scripted so failures are deterministic and require no model account or network.

Example status: Runnable excerpt; execute from the repository root.

from examples.agent_loop import Call, Environment, Finish, run
env = Environment({"policy": "Draft only; review before sending."})

def policy(observations):
    if not observations:
        return Call("read_document", "policy", "read-1")
    return Finish("I found the policy. Nothing was sent.")
result = run(policy, env, max_steps=6, max_tool_attempts=3)
assert result.status == "finished"
assert result.tool_attempts == 1
assert env.drafts == []

The fixture also tests a malicious document followed by a proposed unauthorized write. The write is denied by the environment even though the scripted policy proposes it. This establishes one enforced capability boundary, not general prompt-injection resistance. Replacing the policy with an LLM adds probabilistic behavior that needs its own evaluation. The example does not implement a remote sandbox, real-time call interruption, durable storage, concurrent transactions, token accounting, or semantic answer verification.

Retry an effect without duplicating it

A timeout does not prove a write failed. Suppose saving a draft succeeds, but its reply is lost. Retrying with a new identifier can create a second draft. The fixture retries the same call with the same idempotency key. The environment stores the request identity and result together and returns that result on replay. Reusing the key for different arguments is an error. Authorization is checked again before replay so a revoked capability is not resurrected by a cached receipt.

In production, the receipt and effect must be atomic or reconciled through the external service's transaction identifier. An in-memory dictionary is lost on restart and cannot establish exactly-once behavior across processes. If a remote API offers neither idempotency nor a way to query the effect, stop automatic retries after an ambiguous write and expose the unresolved outcome. “Try harder” is not a recovery protocol.

Read retries also cost time and quota. Distinguish transient transport failure, invalid input, policy denial, exhausted budget, and unavailable evidence. Blindly retrying a denied action is a loop, not progress. A safe fallback preserves uncertainty: “The request may have completed; its status is unknown” is more honest than reporting failure and creating another effect.

A durable local effect and receipt

Run python -m examples.durable_effects for a second, deliberately narrower fixture. It saves a draft and its receipt in one SQLite transaction, simulates a lost reply after commit, opens a fresh connection, and replays the same tenant-scoped key. The output is same_receipt=True drafts=1. Tests also restart in a separate process, interrupt the transaction before commit, reuse a key with changed content, revoke authorization before replay, and race duplicate requests from separate connections.

The invariant is concrete: for one authorized (tenant, operation_key) and unchanged payload, at most one draft is committed and every successful replay returns the same draft ID. Inserting the draft and then recording a receipt in separate transactions would violate that invariant after a crash between the two writes. SQLite's transaction boundary covers both local tables; it cannot encompass an arbitrary remote API.

The host supplies the tenant and current authorization decision. The teaching fixture accepts that decision as a Boolean and does not implement authentication, policy synchronization, encryption, remote writes, or an agent checkpoint store. A revoked caller cannot fetch the old receipt through the replay path. Receipt retention must cover the promised retry horizon; deleting a receipt while preserving the effect makes an old key unsafe to retry unless another durable identity remains.

Framework persistence solves a related but distinct problem. LangGraph's persistence documentation, checked September 24, distinguishes thread checkpoints from cross-thread stores and explicitly notes that its in-memory saver loses state on restart. Persisting conversation state alone does not make external effects idempotent.

In a complete loop, record the pending operation key and remaining budgets before dispatch. On resume, recover that intent, recheck authority, reconcile its receipt, and continue without resetting the task's attempt or spend limits. Store a schema and application version with checkpoints. If changed tool semantics cannot interpret an old intent, migrate it explicitly or stop for reconciliation. Never let a new model silently reinterpret an already committed operation.

Worked check: the draft committed, the process stopped before checkpointing the reply, and permissions were revoked. The new process must not create a replacement draft or return protected receipt data through an unauthorized replay. An authorized reconciliation service can determine the effect's status separately.

Memory is versioned evidence, not an authority upgrade

An agent can retain short-term observations in context, summarize an episode, and retrieve longer-term records. Each has a different failure mode. Context grows expensive; summaries can remove qualifications; retrieval can miss facts or surface stale ones. Store source IDs, creation time, task scope, and authority with important memories. A note claiming that a user approved an action is not itself authorization for a new task.

For a coding task, keep the baseline commit, objective, current hypothesis, experiment command, result, and next uncertainty in a small task record. Put large profiler traces and outputs in files with stable paths. Reload the baseline and measured result after context compaction rather than trusting a summary that says “the fast version passed.” In an enterprise agent, tenant and permission boundaries must apply to memory retrieval just as they apply to RAG.

Parallel agents can explore independent hypotheses in separate branches or worktrees. Each returns a diff plus evidence against the same baseline. Integration is a separate operation: review conflicts, run the combined tests, and remeasure the merged result. Two individually valid changes can interact badly. More agents help only while independent useful work exceeds coordination, compute contention, and review cost. Do not give workers shared mutable output files or let completion order choose the winner.

Evaluate tasks, trajectories, and budgets

Define success using the environment's final state: the correct draft exists, tests pass without unauthorized edits, or the requested information is supported. A final message saying “done” is not an oracle. Keep forbidden effects, data disclosure, and task completion as separate metrics; blanket refusal should not win the benchmark.

Use a development set to improve prompts/tools and an untouched test set for acceptance. Fix or record model version, harness, tool schemas, dataset/environment snapshot, sampling, budgets, retry policy, and evaluator. Repeat stochastic runs and report variance and success per task slice. τ²-Bench is an example of evaluating interaction in an environment with both agent and user control, rather than scoring only a static answer.

An original cost example: a task uses six calls, each with 4,000 input and 500 output tokens. It consumes 24,000 input and 3,000 output tokens before tool costs. With symbolic prices C_in and C_out per million tokens, model cost is 0.024 C_in + 0.003 C_out. If only half of attempts meet the task contract, average cost per success doubles, assuming the same average cost per attempt. A cheaper call can therefore produce a more expensive successful task if it needs more retries.

Measure latency from request arrival to verified completion, including tool queues and failed branches. Record where time is spent: context construction, generation, tool execution, verification, or waiting for authorization. Shortening the loop often means better observations and a sharper verifier, not simply buying faster generation.

Reliability under tool failures

Successful function syntax is only one layer of agent evaluation. ToolBench-X, June 2026 v2, introduces controlled tool-environment hazards including specification changes, execution failures, changed outputs, and conflicting sources, while preserving a recovery path. This is benchmark evidence about defined scenarios, not a guarantee about arbitrary production outages.

Build a local fault matrix around the host contract: timeout before dispatch, lost reply after commit, restart before recording a result, revoked permission, changed tool schema, duplicate delivery, and partial output. Each case should specify the permitted final state, forbidden effects, maximum attempts, and treatment of unknown outcomes. The new durable fixture covers the local transaction cases; the others require tests at their real boundaries.

Measure repeated reliability as well as best-of-many success. If per-run success were independently 0.9, at least one success in three runs would have probability 1 - 0.1^3 = 99.9%, while three successes in three runs would have probability 0.9^3 = 72.9%. Real runs may be correlated, so report empirical task-level results and the definition used rather than assuming independence. A production user who retries and still needs one correct, nonduplicated effect cares about both completion and consistency.

Worked check: a new agent improves clean-task success but duplicates drafts after lost replies. Does it pass? No. Compare clean completion, recovery completion, forbidden effects, and cost separately. A higher average score cannot compensate for breaking the operation's effect contract.

Exercises and worked answers

  1. A retrieved document asks the agent to email secrets. Where is the decisive check? Outside the model, before any tool executes, against caller authority and target scope. Marking text untrusted is necessary but not a sandbox.
  2. A save times out after committing. Should the agent create a new request? Reuse the same idempotency identity or query transaction status; otherwise stop and reconcile the ambiguous effect.
  3. An agent repeatedly searches without improvement. What stops it? Host-enforced call/time/token budgets and an explicit failure outcome, not a request in the prompt to be efficient.
  4. When do parallel agents help? For separable experiments with independent state, a common baseline, bounded resources, and a verified merge. Shared-file contention and duplicate hypotheses can erase the gain.
  5. Does the fixture's passing injection test prove robust model behavior? No. It verifies a deterministic denied capability. Real models, other tools, observation poisoning, and authorized-but-harmful arguments require broader adversarial tests.

Application readers can continue to Part VII for research and adoption cases. The optional telemetry track below develops the algorithms behind service measurements.