Implux Field GuideAGENTIC AI · FORWARD DEPLOYED ENGINEERING

A practical reference for designing agents, delivering software, and proving outcomes.

THE PRACTITIONER'S REFERENCE
Questions · Patterns · Practice

Runnable coding lab / Python standard library

Bounded agent loop

A deterministic tool loop with a small allowlist and hard step budget. The exercise is deliberately small: focus on the invariant and tests, then explain what production hardening it would need.

No external packagesSolution and unittest cases includedCopy, run, then extend

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.

  1. Before looking at the solution

    Write down the invariant the code must preserve and one failure case that could violate it.

  2. Run the reference implementation

    Download the single-file lab and run python bounded-agent-loop.py. It uses Python's built-in unittest and needs no network or API key.

  3. Read each test as a requirement

    Identify what the test proves, what it does not prove, and which production boundary remains trusted.

  4. 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

01InvariantWhat must always remain true?
02BoundaryWhich decision belongs in trusted code?
03FailureWhat happens when the result is unknown?
04EvidenceWhich test demonstrates the property?
05ProductionWhat concurrency, persistence, or policy layer is missing?
A concise implementation answer names both the working code path and the assumptions the toy example leaves behind.

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?