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.content🔄
Watch It In Action
See how the context builds up through the loop
Start Loop
Step #0
Loop #1
context = [system_prompt, tool_defs]
while True:
response = llm(context)
if response.has_tool_call:
result = execute_tool(response.tool_call)
context.append(result)
else:
return response.content
Context
0 tokens
Start Loop
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