1. Loop condition
Keep looping while the model's stop_reason is tool_use — it still wants to call a tool.
while (response.stop_reason === "tool_use") {Typorithm · medium
Step 1 of 8 · intro card
Tools & Agents
An agent is a loop: while the model's stop_reason is tool_use, run the requested tool, append the tool_result as a user turn, and call the model again. It ends when stop_reason becomes end_turn. Tools plus this loop enable autonomous multi-step tasks.
An agent is not magic — it is a loop around the same tool-calling request. Each response carries a stop_reason; while it equals tool_use, the model still wants to act.
On every pass you run the tool the model asked for, append the result as a user turn, and call the model again with the full updated message history. The model reads the result and decides what to do next.
The loop exits when stop_reason becomes end_turn, meaning the model is done and has produced its final answer. Tools give the model abilities; this loop lets it chain them into multi-step work.
Loop while stop_reason === "tool_use".
Run the tool, append the result, call again.
Exit when stop_reason becomes end_turn.
while (response.stop_reason === "tool_use") {
const result = runTool(response.content);
messages.push({ role: "user", content: [toolResult(result)] });
response = await client.messages.create({ model, messages, tools });
}Connect each part of the code to the concept before you type.
Keep looping while the model's stop_reason is tool_use — it still wants to call a tool.
while (response.stop_reason === "tool_use") {runTool executes the requested tool against the model's tool_use block.
const result = runTool(response.content);The tool_result is appended as a user turn so the model sees the output.
messages.push({ role: "user", content: [toolResult(result)] });Call the model again with the updated messages so it can take the next step.
response = await client.messages.create({ model, messages, tools });The loop exits once stop_reason is end_turn instead of tool_use.
}Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.