The exercise
Implement a bounded tool loop with an allowlist, typed decisions, a step budget, and a clear terminal result. Run the included standard-library tests.
- Before looking at the solution
Write down the invariant the code must preserve and one failure case that could violate it.
- Run the reference implementation
Download the single-file lab and run
python bounded-agent-loop.py. It uses Python's built-inunittestand needs no network or API key. - Read each test as a requirement
Identify what the test proves, what it does not prove, and which production boundary remains trusted.
- Modify one condition
Add a test for cancellation, concurrent requests, revocation, or a corrupted evaluation case. Explain how the design changes.
Download runnable lab and tests ↗
Reference solution
Show the complete solution and tests
from dataclasses import dataclass
from typing import Callable
@dataclass(frozen=True)
class Decision:
tool: str | None = None
argument: str = ""
answer: str | None = None
def run_agent(decide: Callable, tools: dict[str, Callable], max_steps: int = 4) -> str:
if max_steps < 1:
raise ValueError("max_steps must be positive")
history = []
for _ in range(max_steps):
decision = decide(tuple(history))
if decision.answer is not None:
return decision.answer
if decision.tool not in tools:
raise ValueError("tool is not allowed")
result = tools[decision.tool](decision.argument)
history.append((decision.tool, decision.argument, result))
raise RuntimeError("step budget exhausted")
if __name__ == "__main__":
import unittest
class LoopTests(unittest.TestCase):
def test_completes_after_tool(self):
calls = []
def lookup(arg): calls.append(arg); return "found"
decisions = iter([Decision(tool="lookup", argument="x"), Decision(answer="done")])
self.assertEqual(run_agent(lambda _: next(decisions), {"lookup": lookup}), "done")
self.assertEqual(calls, ["x"])
def test_rejects_unlisted_tool(self):
with self.assertRaisesRegex(ValueError, "not allowed"):
run_agent(lambda _: Decision(tool="delete"), {"lookup": lambda _: None})
def test_enforces_step_budget(self):
with self.assertRaisesRegex(RuntimeError, "budget"):
run_agent(lambda _: Decision(tool="lookup"), {"lookup": lambda _: "again"}, 2)
unittest.main()The mental model
State and termination belong to the host application. The model may select among declared actions, but the host validates the choice, applies a hard budget, and decides whether the result is complete.
Limits and production extensions
This toy deliberately omits wall-clock cancellation, authentication, structured schemas, and durable state. Add those at the production boundary; never assume the step cap alone makes a tool safe.
Explain it in an interview
Follow-up prompts
- What race or failure does this example still permit?
- How would you make the result observable without logging secrets?
- Which property belongs in a unit test, integration test, or production alert?