The Loop14 of 37
In [The Loop in Twenty Lines](the-loop-in-twenty-lines) you read mini's agent loop. Here you'll write one yourself, and a fake model will check every request your loop sends.
## The fake model
The exercises run without the internet, so the model is played by FakeModel, already in the starter code. It is given a script: the replies the "model" will write, in order. Each time your loop calls model.create(messages), it returns the next reply, as a dictionary shaped like the real thing:
``json
{"stop_reason": "tool_use",
"content": [
{"type": "thinking", "thinking": ""},
{"type": "tool_use", "id": "toolu_01", "name": "add", "input": {"a": 2, "b": 3}}
]}
`
It also checks each request before it answers, the way the real API would refuse a bad one: the first and last messages must be the user's, the roles must take turns, and every tool call must be answered, by id, in the next message. If your loop sends something wrong, the run stops with bad request: and the reason.
run_tool(block) is written for you, with two tools, add and word_count.
## What to write
run_agent(task, model, max_turns), following its docstring:
- start the conversation with the task;
- each turn, send the conversation and add the reply's whole content as an assistant message;
- on "end_turn", return the reply's text;
- on "tool_use", run every tool call, printing one line for each, then add **one** user message with all the results;
- on any other stop reason, run nothing and return stopped: <reason>;
- after max_turns turns, return stopped: no answer after <max_turns> turns.
The line for each call shows the turn (counting from 1), the tool, its input and the result:
`text
turn 1: add {"a": 2, "b": 3} -> 5
`
Use json.dumps(block["input"], sort_keys=True) for the input. The code below your function prints what you return and how many messages the model was sent each turn. For a script where the model adds 2 and 3 and then answers, the output is:
`text
turn 1: add {"a": 2, "b": 3} -> 5
result: 2 + 3 is 5.
messages sent each turn: 1, 3
``
The second request carries three messages: the task, the model's tool call and your results. If yours says anything else, look at what you append.
Sign in to try this exercise.