The Agent Loop
looping until the model is done
Part of: Tool-Using Agent
Real questions sometimes need more than one tool call before the model has enough to answer. "What's the weather in Tokyo, and what's that in Fahrenheit if it's given in Celsius" might call get weather first, then calculator once it has a number. A single request/execute/respond round trip won't cover that. You need a loop that keeps running tools until the model says it's done. The loop, precisely Every turn, check stop reason. If it is "tool use", run the tool and continue. If it is "end turn", stop and print the final text: Notice the loop's shape. Append the assistant's turn every time, then branch on stop reason. If it wants a tool, run it, append the tool result, and go around again. The model sees the new result added to messages and decides what to do next: call another tool, or answer. Why a loop, not a fixed number of round trips You don't know in advance how many tool calls a question needs. Some need zero and are pure chat. Some need one. Some need three chained together. A loop that keeps going until stop reason says otherwise handles all of them with the same code. Hard-coding "call once, then always answer" breaks the moment a question needs two tools. Why this loop
Challenge: Run the Agent Loop