CHAPTER 02 · The Agent Loop Pattern · 1 / 8
The essential loop
Stripped to its core, every agent loop is:
messages = [system_prompt, ...history, user_message]
repeat up to N times:
response = model.call(messages, tools)
if response has no tool calls:
return response.text # the model is done
results = run(response.tool_calls) # execute the actions
messages.append(response) # record what the model did
messages.append(results) # record what the tools returned
That's it. The model is given the conversation and the tool catalog; it either answers or asks for tools; if it asks, you run them, append both the request and the results, and call again. The loop ends when the model answers without requesting tools (or a cap is hit).
This simple structure is deceptively powerful: by chaining tool calls, the model can read a file, use what it learned to search an API, use those results to draft a document, and finally summarise, all from a single user message, with the loop carrying it through.