Mental model
An autonomous agent is a bounded state-machine controller (PLAN -> ACT -> OBSERVE -> VERIFY -> HALT), not an unconstrained chat prompt. Deterministic application software owns context construction, tool authorization, dual token-and-cost budget enforcement, oscillation detection, and exit verification, while the language model supplies probabilistic step proposals whenever environmental feedback alters the optimal next move.
Learning outcomes
- Distinguish deterministic workflow DAGs from autonomous ReAct control loops and choose the simplest architecture that handles task variance.
- Trace how context accumulates quadratically across multi-turn agent loops and apply explicit step, token, and dollar budget guards.
- Implement deterministic termination predicates and repeated-state oscillation detection to halt stuck loops before resource exhaustion.
- Build a bounded Python ReAct controller that separates probabilistic model proposals from deterministic verification and stop rules.
Theory
As OpenAI's analysis of unrolling the Codex agent loop highlights, every agent turn invokes the model with the growing conversation prefix—user prompt, assistant reasoning/tool requests, and tool observations—until the model stops emitting tool calls or software interrupts the loop. Anthropic's agent engineering guidance draws a sharp architectural boundary between workflows (predefined code paths orchestrated via fixed DAGs) and agents (loops where the model dynamically directs its own tool invocations based on intermediate observations).
Because each iteration appends new reasoning and observation tokens to the context passed back into step , cumulative prompt tokens billed over an -turn loop grow quadratically:
Here, is the initial prompt plus tool schemas, and is the average tokens added per turn (assistant output plus tool observation). Without KV prefix caching or context compaction, doubling maximum turns from 10 to 20 nearly quadruples the quadratic history-replay term.
ReAct Agent State Machine (Thought → Action → Tool → Observation)
Quantitative Budget and Latency Modeling
Consider a coding triage agent starting with tokens (system instructions plus tool manifests) and adding 1,200 tokens per turn (300 generated output tokens plus 900 observation tokens from test runners or file reads). Over an 8-step loop without prompt caching:
- Total prompt tokens reprocessed equal
8 * 4,000 + (8 * 7 / 2) * 1,200 = 32,000 + 33,600 = 65,600input tokens. - Total output tokens equal
8 * 300 = 2,400tokens. - At \$3.00 per million input tokens and \$15.00 per million output tokens, one full 8-turn trace costs
65,600 * $3.00 / 1e6 + 2,400 * $15.00 / 1e6 = $0.1968 + $0.0360 = $0.2328.
If a loop stalls on a flaky test and runs unbounded to 40 steps, input tokens jump to 40 * 4,000 + 780 * 1,200 = 1,096,000 tokens, pushing single-run cost above \$3.46—nearly 15x higher for zero additional progress.
Termination Predicates and Oscillation Detection
Reliable agent controllers enforce deterministic stopping rules outside the model's reasoning stream:
- Verified Goal (
HALT_SUCCESS): Environment postconditions pass an objective oracle (unit tests exit0, schema check passes, DB row state confirmed), never merely because the model wrote "I have finished." - Dual Resource Caps (
HALT_BUDGET): Hard ceiling on both turn count () and cumulative token/dollar spend (), plus wall-clock deadline. - Oscillation / Cycle Guard (
HALT_OSCILLATION): Tracks a sliding fingerprint of(tool_name, canonical_args_hash, observation_hash). Repeating the exact failing tool invocation 2 or more consecutive times—or alternatingA -> B -> A -> B—triggers immediate loop interruption or model escalation.
Trade-offs
Choosing between fixed DAG workflows, hybrid bounded loops, and open-ended multi-agent swarms determines testability, tail latency, and failure containment.
| Control Topology | Step Predictability | Adaptability to Unknown State | Testing & Eval Effort | Token Cost Profile |
|---|---|---|---|---|
| Deterministic Workflow DAG | Very high (fixed branches) | Low (only pre-coded conditions) | Straightforward unit & integration tests | Linear in fixed stages |
| Bounded Single-Agent ReAct Loop | Medium (capped at ) | High (reacts to live tool errors) | Requires trajectory + outcome evals | Quadratic growth without compaction/caching |
| Unbounded / Recursive Subagent Swarm | Low (emergent coordination) | Highest for open-ended exploration | Complex trace replay & drift analysis | Multiplicative across spawned contexts |
Anthropic's trustworthy-agent research recommends using deterministic outer workflows whenever the stage sequence is known—embedding tiny, step-capped agent loops only around genuinely unpredictable subproblems such as repairing failing compiler errors or navigating dynamic UIs. Maintaining immutable trace logs of every tool proposal, authorization outcome, and verification status also lets engineering teams replay production trajectories offline before expanding step ceilings or tool scopes.
Failure modes and misconceptions
- Self-reported completion without environment verification: An agent claims "All migrations applied and verified" after a tool command returned a non-zero warning or partial diff. Always tie
HALT_SUCCESSto deterministic postcondition checks. - Turn-count-only budgets ("max 15 steps"): A model calling 8 heavy file-read tools in parallel on step 3 can exhaust the entire context window and dollar budget long before reaching step 15. Enforce simultaneous caps on turns, cumulative input+output tokens, and wall-clock time.
- Uncompacted error trace accumulation: Appending ten consecutive 3,000-token stack traces turns the context window into noise, increasing hallucinated retries. Compact stale observations or replace prior failed attempts with concise error summaries.
- Oscillating tool loops ("ping-pong failure"): Without state-fingerprint tracking, an agent alternates indefinitely between
edit_fileandrun_testwith identical syntax errors until budget exhaustion. - Trusting model-selected escalation or retry policies: Allowing the model to override its own step ceiling or disable guardrails collapses loop governance.
Decision scenario
A CI auto-remediation agent monitors broken pull requests and attempts to patch failing unit tests before notifying engineers. Telemetry reveals that 12% of runs stall into 25-step cycles repeatedly running pytest on identical unchanged code, driving p95 run cost from \$0.22 to \$2.90. Redesign the controller as a two-stage hybrid: a deterministic outer DAG runs git_diff and baseline pytest upfront, then hands control to a bounded ReAct loop capped at max_turns = 8, max_total_tokens = 90000, and max_cost_usd = 0.45. Add an oscillation guard that halts immediately with HALT_OSCILLATION if (tool_name, args_hash) repeats twice consecutively without modifying repository state, and require an independent final pytest exit code 0 before marking any fix verified.
Implementation example
This Python bounded ReAct controller enforces turn limits, cumulative token/dollar budgets, action-observation oscillation detection, and deterministic postcondition verification before halting.
pythonimport hashlib, jsonfrom dataclasses import dataclass, fieldfrom typing import Any, Callable, LiteralHalt = Literal["verified", "budget_turns", "budget_cost", "oscillation", "no_action"]@dataclass(frozen=True)class BudgetPolicy:max_turns: int = 8; max_tokens: int = 90_000; max_cost_usd: float = 0.45; max_repeats: int = 2@dataclassclass LoopState:turns: int = 0; total_tokens: int = 0; cost_usd: float = 0.0fingerprints: list[str] = field(default_factory=list)def run_bounded_react(propose: Callable[[list[dict[str, Any]]], dict[str, Any]],exec_tool: Callable[[str, dict[str, Any]], tuple[str, bool]],verify: Callable[[], bool], policy: BudgetPolicy,) -> tuple[Halt, LoopState]:st, trace = LoopState(), []while st.turns < policy.max_turns:if st.total_tokens >= policy.max_tokens or st.cost_usd >= policy.max_cost_usd: return "budget_cost", ststep = propose(trace); st.turns += 1st.total_tokens += int(step.get("tokens_used", 0)); st.cost_usd += float(step.get("cost_usd", 0.0))if not (tool := step.get("tool")): return ("verified" if verify() else "no_action"), stfp = hashlib.sha256(f"{tool}:{json.dumps(step.get('args', {}), sort_keys=True)}".encode()).hexdigest()st.fingerprints.append(fp)if st.fingerprints.count(fp) >= policy.max_repeats: return "oscillation", stobs, ok = exec_tool(tool, step.get("args", {}))trace.append({"tool": tool, "ok": ok, "obs": obs[:1500]})if ok and verify(): return "verified", streturn "budget_turns", st
Knowledge check
Why are turn-count limits alone insufficient for bounding an agent control loop, and what objective signal must gate HALT_SUCCESS?