Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Agent Decision Loops
An agent decision loop is the repeated cycle of planning, acting, observing, and deciding. The loop continues until the goal is complete or an exit condition is reached.
The Agent Loop
Most AI agents run in a loop:
Step 1: Observe - look at the current state and any available information
Step 2: Plan - decide what action to take next
Step 3: Act - execute the action using a tool
Step 4: Observe result - read what the tool returned
Step 5: Decide - is the goal complete? If yes, finish. If not, go back to Step 1.
This loop continues until one of these happens:
- The goal is complete
- The agent reaches a maximum number of steps
- The agent encounters an error it cannot handle
- The agent needs human input to continue
Loop Diagram
# Agent decision loop (Python pseudocode)
def agent_loop(goal, tools, max_steps=20):
state = {"goal": goal, "steps_taken": 0, "observations": []}
while state["steps_taken"] < max_steps:
# Step 1: Observe current state
observation = state["observations"][-1] if state["observations"] else None
# Step 2: Decide next action
next_action = decide_next_action(goal, observation, state)
if next_action == "FINISH":
print("Goal complete.")
return state
if next_action == "ESCALATE":
print("Requesting human input.")
return request_human_input(state)
# Step 3: Execute the action
tool_name, tool_args = next_action
result = tools[tool_name].execute(tool_args)
# Step 4: Record the observation
state["observations"].append(result)
state["steps_taken"] += 1
print("Max steps reached. Escalating to human.")
return request_human_input(state)