Plan and Execute › Bringing It Together: A Complete Example
Michael BrenndoerferJuly 21, 20253 min read
AI Agent HandbookAll chapters Part 9 of 15Planning - Agents with a Plan
Plan and Execute › Bringing It Together: A Complete ExampleOne section · Sections in this chapter5 / 10 ↓
Sections in this chapter10
Let's see a full execution cycle for our weekend getaway assistant. We'll use the plan from the previous chapter and execute it with all the error handling and flexibility we've discussed.
In[2]:
Code## Using Claude Sonnet 4.5 for end-to-end plan execution
import os
from anthropic import Anthropic
import json
client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
## Define our tools (simplified for illustration)
tools = [
{
"name": "search_destinations",
"description": "Find destinations within specified travel time",
"input_schema": {
"type": "object",
"properties": {
"max_hours": {"type": "number"},
"origin": {"type": "string"}
}
}
},
{
"name": "search_hotels",
"description": "Search for available hotels in a city",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string"},
"check_in": {"type": "string"},
"check_out": {"type": "string"}
}
}
}
]
def execute_complete_plan(user_request):
"""Full plan-and-execute cycle."""
# Step 1: Create the plan (from previous chapter)
plan_response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=[{
"role": "user",
"content": f"""Create a step-by-step plan for: {user_request}
List each step clearly."""
}]
)
plan_text = plan_response.content[0].text
print(f"Plan created:\n{plan_text}\n")
# Step 2: Execute each step
print("Beginning execution...\n")
results = []
messages = [{
"role": "user",
"content": f"Execute this plan step by step:\n{plan_text}"
}]
# Execute until complete
while True:
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=2048,
tools=tools,
messages=messages
)
# Add assistant response to conversation
messages.append({
"role": "assistant",
"content": response.content
})
# Check if agent wants to use a tool
if response.stop_reason == "tool_use":
# Find the tool use block
tool_use = next(
block for block in response.content
if block.type == "tool_use"
)
print(f"Using tool: {tool_use.name}")
# Simulate tool execution (in real code, call actual APIs)
tool_result = simulate_tool_call(tool_use.name, tool_use.input)
# Add tool result to conversation
messages.append({
"role": "user",
"content": [{
"type": "tool_result",
"tool_use_id": tool_use.id,
"content": json.dumps(tool_result)
}]
})
elif response.stop_reason == "end_turn":
# Agent is done
final_response = next(
block.text for block in response.content
if hasattr(block, "text")
)
print(f"\nFinal result:\n{final_response}")
break
return final_response
## Example usage
result = execute_complete_plan(
"Plan a weekend getaway within 3 hours of San Francisco"
)When you run this, you'll see the agent working through its plan step by step. It might produce output like this:
Plan created:
1. Search for destinations within 3 hours of San Francisco
2. Check weather forecasts for top 3 destinations
3. Search for available hotels in the best option
4. Compile recommendations with activities
Beginning execution...
Using tool: search_destinations
Found destinations: Napa Valley, Lake Tahoe, Monterey
Using tool: search_hotels
Found 12 available hotels in Napa Valley
Final result:
I recommend a weekend in Napa Valley. I found several excellent hotels
with availability, and the weather looks perfect. Here are three options
with different price points, plus suggested wineries and restaurants to visit.The agent moved through each step, used tools when needed, and synthesized everything into a coherent recommendation. If any step had failed (say, no hotels were available in Napa), the agent could have fallen back to the second destination on its list.