Bounded agent state machines
Choose the simplest useful architecture
An AI agent is an application that uses observations to choose actions toward a goal. A workflow follows a predefined graph; model routing chooses one branch; a planner proposes steps and an executor checks and performs permitted steps. An agent can revise its plan after observing results. In a support queue, a fixed rule is usually sufficient when tickets have known states. Use a model only when ambiguity or changing observations justify its cost. This lesson extends the agent types in Chapter 8, tool execution in Chapter 42 and MCP authorization in Chapter 43. The examples are deterministic stand-ins for model proposals, not actual LLM calls.
def route(ticket): # A fixed policy, not a model or an authorization grant. if ticket == "missing": return "research" if ticket == "resolved": return "finish" return "escalate"
for ticket in ["missing", "resolved", "unknown"]: print(route(ticket))State and transitions
Represent state explicitly: task identity, goal, observations, current phase, permitted actions, resource counters and outcome. An observation is data returned by a fake lookup, not a new instruction. A state machine has named phases and allowed transitions. A simple triage flow is PLAN → VALIDATE → LOOKUP → REVIEW → DONE, with terminal alternatives DENIED, CANCELLED, BUDGET and ESCALATED. A retry returns to LOOKUP only after reserving another unit of work. A terminal run cannot resume through a stale event; a fresh authorized run is required. Keep the graph and transition policy outside the model. The router above returns research, finish or escalate; it grants no tools.
Reserve resources before each action
A step count alone cannot cap token consumption, wall time or spending. In the simulation a lookup has fixed cost (1 step, 2 tokens, 3 fictional cost units, 1 tick). The host checks all four limits before recording the action. Equality with the remaining budget is permitted; exceeding any component stops before the action. In production, reserve conservative upper bounds, enforce real monotonic deadlines and provider limits, record actual usage, and reconcile reservations. A timeout is not proof that a remote write failed. The loop uses a finite list of observations and no real tools.
def run(observations, limits, cancel_at=None): # Trusted, nonnegative integer limits: steps, tokens, cost, ticks. # Each fake lookup reserves one step, two tokens, three cost units, # and one tick. No actual clock, money or external calls. if len(limits) != 4 or any(type(x) is not int or x < 0 for x in limits): raise ValueError("invalid limits") used = [0, 0, 0, 0] trace = [] attempts = 0 for observation in observations: if cancel_at is not None and attempts >= cancel_at: return "cancelled", used, trace proposed = [a+b for a,b in zip(used, (1,2,3,1))] if any(a>b for a,b in zip(proposed, limits)): return "budget", used, trace used = proposed attempts += 1 trace.append("lookup") if observation == "found": return "done", used, trace if observation != "retry": return "escalated", used, trace return "escalated", used, trace
print(run(["retry", "found"], [2,4,6,2]))print(run(["retry", "found"], [1,4,6,2]))print(run(["retry", "found"], [2,4,6,2], 1))Read the trace and handle failure
The first run completes with two lookups and usage [2, 4, 6, 2]. The second stops at the step cap after one lookup. The third sees cancellation before the second lookup. An unexpected observation escalates instead of inventing a result; exhausting the observation list also escalates. Cancellation in this toy is observed at action boundaries only, not while a real request is in flight. A production worker needs cooperative cancellation, a timeout, reconciliation of uncertain external effects and an append-only audit log. Do not treat a model response saying "continue" as a budget extension.
Multiple agents and practice
Separate research and review roles only if they improve measured accuracy or throughput. Pass typed findings and source IDs between roles, share a centrally enforced budget, and keep each role least-privileged. A reviewer agent does not become a human approver. Parallel calls can race, so atomic budget reservations and conflict handling matter. Practice: predict the trace if the cost limit is five, then change the first observation to an unknown string and explain why escalation is appropriate. Reference: ref-ai-bounded-agent-state-machines. Next: bind human decisions to exact proposals.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Bounded agent state machines quiz
Assess workflow boundaries and the local fixture contract.
What distinguishes a bounded agent from a fixed workflow?
When should the host reserve resources?
With limits [2,4,5,2], how many lookups can the fixture perform?
What happens after an unexpected observation in run()?
What is required when multiple agents share a budget?