Code Lab / Challenge 10

Minimal Agent Loop with Tool Use

MediumTool-calling agent loop with a mock LLM

The problem, as an interviewer would set it

Implement the core loop of a tool-using agent, with the LLM mocked out so the
loop's control flow can be tested deterministically.

Model protocol - the "LLM" is any callable `llm(history) -> dict` returning:
    {"tool": "<name>", "args": {...}}   # tool call request
    {"final": "<text>"}                 # finished, return this answer

Implement:

    run_agent(llm, tools, task, max_iterations=8) -> AgentResult
        - history starts as [{"role": "user", "content": task}]
        - each model action is appended as {"role": "assistant", "content": action}
        - tool output (or an error string) is appended as
          {"role": "tool", "content": <observation>} and the loop continues
        - unknown tool or a tool raising -> feed the error text back to the
          model as the observation; do NOT crash the loop
        - stop when the model returns "final", or after max_iterations model
          calls (AgentResult.stopped_at_limit = True, output = None)

Tools to provide:
    calculator(expression) - safe arithmetic via the `ast` module (no eval()!)
    convert(value, from_unit, to_unit) - km/m/mi and kg/lb via base units
    lookup(key) - small in-memory fact table
What interviewers look for

Clean state machine, tool-result feedback into context, max-iteration and error handling

A strong solution demonstrates:
- The agent loop is just: model -> action -> execute -> observe -> repeat.
  Everything else (planning, reflection) layers on top of this skeleton.
- Errors are observations, not exceptions: feeding "unknown tool" back lets
  the model self-correct - exactly how production agents recover.
- A safe calculator: walking the AST whitelist (constants, + - * / ** %),
  never eval()/exec() on model output. Safe means bounded cost too: with
  Python ints, "9 ** 9 ** 9" builds a number with hundreds of millions of
  digits and hangs the worker, so evaluate in floats (overflow raises
  immediately) or cap exponents.
- Injecting `llm` and the tool registry makes the loop unit-testable
  without network calls.
Common mistakes: eval() on model-generated strings; no iteration cap
(runaway loops burn tokens/money); swallowing tool errors instead of
returning them to the model; mutating a shared history list across runs.
Follow-ups: parallel tool calls in one turn, with call ids so each result
maps back to its request (how native tool-calling APIs pair them); token
and wall-clock budgets in addition to iteration caps; detecting a stuck
loop (same tool, same args, repeated); JSON Schema tool definitions with
argument validation before execution (the shape MCP tools and
function-calling APIs share); human approval gates for side-effecting
tools; persisting history for resumability.

Write your own version first. The reference solution and its tests are one click away when you are ready.

Next challenge