# 1.1 Agent loop

An LLM in a while-loop: emit tool_use, observe tool_result, repeat until end_turn.

1. Single inference: one prompt, no environment feedback.
2. stop_reason = tool_use: the runtime executes the call.
3. tool_result is appended to messages[] as ground truth.
4. The loop repeats until stop_reason = end_turn.

- **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 })
```

## References

- [Building effective agents](https://www.anthropic.com/engineering/building-effective-agents) (Anthropic)
- [Unrolling the Codex agent loop](https://openai.com/index/unrolling-the-codex-agent-loop/) (OpenAI)
- ["Agent" may finally have a useful definition](https://simonwillison.net/2025/Sep/18/agents/) (Simon Willison)
- [Running agents](https://openai.github.io/openai-agents-python/running_agents/) (OpenAI)
- [12-factor agents](https://github.com/humanlayer/12-factor-agents) (HumanLayer)
