Chapter 7 β Planning & Reasoning
βThe real challenge for agents isnβt executing any single step β itβs knowing which steps to take, in what order, and when to change course.β
Why Planning Matters
An LLM can answer questions. An agent with tools can take actions. But planning is what separates a useful agent from a random one. Planning is the ability to:
- Break a complex goal into smaller steps
- Sequence those steps correctly
- Adapt when something goes wrong
- Know when the goal is achieved
The Reasoning Landscape
Chain-of-Thought (CoT)
The simplest reasoning technique. Ask the LLM to think step by step before answering.
# Without CoT
prompt = "What is 27 * 43?"
# LLM might get it wrong
# With CoT
prompt = """What is 27 * 43? Think step by step.
Step 1: 27 * 40 = 1,080
Step 2: 27 * 3 = 81
Step 3: 1,080 + 81 = 1,161
The answer is 1,161."""
For agents, CoT is embedded in the system prompt:
Before taking any action, think through your reasoning step by step:
1. What is the user's goal?
2. What information do I need?
3. What tools should I use?
4. What's my plan?
Then execute the plan one step at a time.
ReAct: Reasoning + Acting
ReAct is the core reasoning pattern for tool-using agents. It interleaves thoughts (reasoning) with actions (tool calls) and observations (tool results).
In production, you implement ReAct by including a βthinkβ step in the system prompt:
system_prompt = """You are a research assistant. For each step:
1. THINK: Explain your reasoning about what to do next
2. ACT: Call a tool if needed
3. OBSERVE: Analyze the tool's output
4. REPEAT until you can answer the user's question
Always show your thinking before acting."""
Plan-and-Execute
For complex tasks, itβs better to plan first, then execute β rather than figuring things out one step at a time.
def plan_and_execute(goal: str):
# Step 1: Generate a plan
plan = llm.generate(f"""
Create a step-by-step plan to achieve this goal: {goal}
Output as a numbered list. Each step should be specific and actionable.
""")
steps = parse_plan(plan)
results = []
for i, step in enumerate(steps):
# Step 2: Execute each step
result = agent.execute(step)
results.append(result)
# Step 3: Check progress
evaluation = llm.generate(f"""
Goal: {goal}
Completed steps: {results}
Remaining steps: {steps[i+1:]}
Is the plan still on track? Should we modify remaining steps?
""")
if "replan" in evaluation.lower():
steps = replan(goal, results, steps[i+1:])
return synthesize_answer(goal, results)
Reflexion: Learning from Mistakes
Reflexion adds a self-reflection loop. When the agent fails, it analyzes why and adjusts its approach.
def reflexion_loop(task: str, max_retries: int = 3):
reflections = []
for attempt in range(max_retries):
# Attempt the task (with past reflections as context)
result = agent.execute(task, past_reflections=reflections)
# Evaluate
success = evaluate(result, task)
if success:
return result
# Reflect on the failure
reflection = llm.generate(f"""
Task: {task}
Attempt #{attempt + 1} failed.
Result: {result}
What went wrong? What should I do differently next time?
Be specific and actionable.
""")
reflections.append(reflection)
return "Failed after maximum retries."
Tree of Thoughts (ToT)
For problems with multiple valid approaches, Tree of Thoughts explores different reasoning paths and picks the best one.
Task Decomposition
Breaking complex tasks into sub-tasks is a planning superpower:
def decompose_task(complex_task: str) -> list[str]:
return llm.generate(f"""
Break this complex task into 3-7 simple, independent sub-tasks:
Task: {complex_task}
Rules:
- Each sub-task should be completable with a single tool call
- Sub-tasks should be ordered by dependency
- Include a final "verify" sub-task
Output as a JSON array of strings.
""")
# Example
subtasks = decompose_task("Create a data analysis report on Q4 sales")
# ["Search for Q4 sales data files",
# "Load and clean the sales data",
# "Calculate key metrics (total revenue, growth rate, top products)",
# "Generate visualizations (bar chart, trend line)",
# "Write the report narrative",
# "Format as PDF with charts embedded",
# "Verify all numbers match the source data"]
Choosing the Right Reasoning Strategy
| Strategy | Best For | Overhead | Reliability |
|---|---|---|---|
| Direct | Simple, single-step tasks | None | Low |
| CoT | Math, logic, step-by-step problems | Low | Medium |
| ReAct | Tasks requiring tool use | Medium | High |
| Plan-and-Execute | Complex multi-step projects | Medium | High |
| Reflexion | Tasks where failure is likely/acceptable | High | Very High |
| Tree of Thoughts | Creative/design tasks with multiple valid solutions | Very High | Highest |
Whatβs Next
So far weβve covered single agents. But what happens when you need multiple agents working together? Thatβs multi-agent systems.
Next: Chapter 8 β Multi-Agent Systems β
β Previous: Chapter 6 β Memory Systems Β· Next: Chapter 8 β Multi-Agent Systems β
Last updated: April 2026