← Back to Table of Contents

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

Reasoning Techniques for Agents
🌳 Tree of Thoughts Explore multiple reasoning branches, evaluate and prune
πŸ”„ Reflexion Reflect on past failures, adjust strategy, retry
⚑ ReAct Interleave reasoning (think) with acting (tool use)
πŸ”— Chain-of-Thought Step-by-step reasoning before answering
πŸ’¬ Direct Prompting Just answer β€” no explicit reasoning

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).

ReAct Trace
πŸ’­ Thought: "I need to find the CEO of Tesla"
⚑ Action: web_search("CEO of Tesla 2026")
πŸ‘€ Observation: "Elon Musk is the CEO of Tesla"
πŸ’­ Thought: "Now I need their net worth"
⚑ Action: web_search("Elon Musk net worth 2026")
πŸ‘€ Observation: "~$250 billion"
βœ… Answer: Formulates final response

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.

Plan-and-Execute Pattern
πŸ“‹ Plan
▢️ Step 1
▢️ Step 2
πŸ” Check
πŸ”„ Replan?
βœ… Done
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.

Reflexion Loop
πŸ“‹ Attempt the task
πŸ” Evaluate: did it work?
βœ… Success β†’ return result
❌ Failure β†’ reflect on what went wrong
πŸ’‘ Generate improved strategy
πŸ”„ Retry with new strategy
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.

Tree of Thoughts
🌱 Problem: "Design a REST API for a todo app"
Path A
RESTful with CRUD endpoints
Path B
GraphQL with single endpoint
Path C
Event-driven with WebSocket
πŸ† Evaluate each β†’ Pick best β†’ Expand

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
Decision Guide: Which Reasoning Strategy?
How complex is the task?
Simple
β†’ CoT or Direct
Medium
β†’ ReAct
Complex
β†’ Plan-and-Execute
Error-prone
β†’ Reflexion

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