FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Agent Control Loop

How bounded observe decide act and verify cycles produce controlled autonomy.

Freshness: current•15 min read•Agentic Systems and Protocols

Key Learning Outcomes

  • ✓Trace observe decide act and verify states
  • ✓Define budgets stopping conditions and recovery
  • ✓Separate model choice from application authority
Isometric Diagram LabAI & LLM Systems · 6 steps · 9 min

Agentic Tool Loops & Execution Guardrails

Step through planner-tool cycles, schema validation, sandbox boundaries, and budget circuit breakers.

Open Isometric Walkthrough
Full Technical Reference Document

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.

Goal & Budget Contract
Plan Next Action
Authorize & Execute Tool
Observe & Check Oscillation
Verify Exit & Halt
Conceptual teaching model synthesized from:Building Effective AI AgentsTrustworthy Agents in PracticeUnrolling the Codex agent loop

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 t∈{1,…,N}t \in \{1, \dots, N\} appends new reasoning and observation tokens Δt\Delta_t to the context passed back into step t+1t+1, cumulative prompt tokens billed over an NN-turn loop grow quadratically:

Tprompt(N)=∑t=1N(P0+∑j=1t−1Δj)≈NP0+N(N−1)2ΔˉT_{\text{prompt}}(N) = \sum_{t=1}^{N} \left(P_0 + \sum_{j=1}^{t-1} \Delta_j\right) \approx N P_0 + \frac{N(N-1)}{2}\bar{\Delta}

Here, P0P_0 is the initial prompt plus tool schemas, and Δˉ\bar{\Delta} 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)

Quadrant 1THOUGHT● CURRENT
Quadrant 2ACTIONWAITING
Quadrant 3TOOL_EXECUTIONWAITING
Quadrant 4OBSERVATIONWAITING
Agent Execution Trace (Step 1/6)250 Tokens in Context
THOUGHTUser requested cluster health report. Need to inspect node status table.
Current PhaseTHOUGHT
Total Steps0 / 6
Accumulated Tokens250 tokens
Loop TrapNormal

Quantitative Budget and Latency Modeling

Consider a coding triage agent starting with P0=4000P_0 = 4000 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,600 input tokens.
  • Total output tokens equal 8 * 300 = 2,400 tokens.
  • 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:

  1. Verified Goal (HALT_SUCCESS): Environment postconditions pass an objective oracle (unit tests exit 0, schema check passes, DB row state confirmed), never merely because the model wrote "I have finished."
  2. Dual Resource Caps (HALT_BUDGET): Hard ceiling on both turn count (N≤Nmax⁡N \le N_{\max}) and cumulative token/dollar spend (Ctotal≤Cmax⁡C_{\text{total}} \le C_{\max}), plus wall-clock deadline.
  3. 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 alternating A -> 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 TopologyStep PredictabilityAdaptability to Unknown StateTesting & Eval EffortToken Cost Profile
Deterministic Workflow DAGVery high (fixed branches)Low (only pre-coded conditions)Straightforward unit & integration testsLinear in fixed stages
Bounded Single-Agent ReAct LoopMedium (capped at Nmax⁡N_{\max})High (reacts to live tool errors)Requires trajectory + outcome evalsQuadratic growth without compaction/caching
Unbounded / Recursive Subagent SwarmLow (emergent coordination)Highest for open-ended explorationComplex trace replay & drift analysisMultiplicative 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_SUCCESS to 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_file and run_test with 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.

python
import hashlib, json
from dataclasses import dataclass, field
from typing import Any, Callable, Literal
​
Halt = 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
​
@dataclass
class LoopState:
turns: int = 0; total_tokens: int = 0; cost_usd: float = 0.0
fingerprints: 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", st
step = propose(trace); st.turns += 1
st.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"), st
fp = 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", st
obs, ok = exec_tool(tool, step.get("args", {}))
trace.append({"tool": tool, "ok": ok, "obs": obs[:1500]})
if ok and verify(): return "verified", st
return "budget_turns", st

Knowledge check

Reflect before revealing the guide

Why are turn-count limits alone insufficient for bounding an agent control loop, and what objective signal must gate HALT_SUCCESS?

Prerequisites & Related Concepts (7)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-301Agentic Systems Engineer

Engineer bounded tool-using systems with explicit workflows state protocols evaluation observability security and human control.

27 concepts~29h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next