promptdojo_

stop_reason, tool_use, tool_result — the loop every agent runs — step 9 of 9

Checkpoint

One last thing before we move on. Same surface as a write step — but the lesson doesn't complete until this passes.

Final drill. Build a slightly bigger agent loop. Write run_agent(question, max_iterations) that:

  • Maintains a messages list, starting with one user turn.
  • Calls fake_model(messages) up to max_iterations times.
  • On stop_reason == "end_turn": return the dict {"ok": True, "answer": <text>, "rounds": <iterations used>}.
  • On stop_reason == "tool_use": run the tool by calling fake_tool(name, input), append the assistant turn + a user turn with a tool_result carrying the tool's output, increment count, and continue.
  • If max_iterations is exhausted: return {"ok": False, "answer": "capped", "rounds": max_iterations}.

Then the script will run two cases and print each result.

Expected output:

ok=True rounds=2 answer=area is 50
ok=False rounds=2 answer=capped

full-screen editor opens — close anytime to keep reading.