agent loops — tool_use and the request/tool/respond cycle9 / 9
stop_reason, tool_use, tool_result — the loop every agent runs
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
messageslist, starting with one user turn. - Calls
fake_model(messages)up tomax_iterationstimes. - On
stop_reason == "end_turn": return the dict{"ok": True, "answer": <text>, "rounds": <iterations used>}. - On
stop_reason == "tool_use": run the tool by callingfake_tool(name, input), append the assistant turn + a user turn with atool_resultcarrying the tool's output, increment count, and continue. - If
max_iterationsis 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
⌘↵ runs the editor.
Booting Python…
Output
[promptdojo:~]$ _