Agent loop
latest messagemessage historyunused
- Single inference: one prompt, no environment feedback.
- stop_reason = tool_use: the runtime executes the call.
- tool_result is appended to messages[] as ground truth.
- The loop repeats until stop_reason = end_turn.
Notes & references
Use when
Step count is unpredictable and actions depend on environment feedback.
Avoid
Unbounded loops: always cap max_turns, tokens and wall-clock.
messages = [{ role: "user", content: task }]
while True:
reply = llm.create(messages, tools)
messages.append(reply)
if reply.stop_reason == "end_turn":
return reply.text # done
results = [run(call) for call in reply.tool_calls]
messages.append({ role: "user", content: results })
- Building effective agentsAnthropic
- Unrolling the Codex agent loopOpenAI
- "Agent" may finally have a useful definitionSimon Willison
- Running agentsOpenAI
- 12-factor agentsHumanLayer