What is the Agent Loop?
The agent loop is the fundamental cycle that enables AI agents to interact with their environment autonomously. It consists of observation, reasoning, action, and feedback phases that repeat continuously.
The reality? An agent is just an LLM running in a while loop.
The Four Phases
Observe
Gather information from the environment, tools, and user input.
Think
Reason about the current state and decide on the next action.
Act
Execute the chosen action using available tools.
Learn
Process feedback and update understanding for the next iteration.
The Core Pattern
context = [system_prompt, tool_definitions]
context.append(user_message)
while True:
response = llm(context)
if response.has_tool_call:
# Execute the tool and add result to context
result = execute_tool(response.tool_call)
context.append(response)
context.append(result)
continue # Loop again
else:
# No tool call = final answer
return response.contentWatch It In Action
See how the context builds up through the loop
Travel plan: observe, act, recover
Scripted fictional travel example. Playback duration and token counts are illustrative. The agent may search hotels and propose a reservation; booking requires separate user authorization.
1. User request
Plan a three-day Tokyo trip with a budget of €2,000. Search options; do not book.
Key Takeaways
- 1The loop continues until the task is complete or terminated
- 2Each iteration builds on previous observations and actions
- 3Error handling and recovery are crucial for robust agents
- 4The quality of tools directly impacts agent capabilities