Breaking Down Tasks (Task Decomposition) › Making Decomposition Practical

Michael BrenndoerferJuly 19, 20252 min read
AI Agent HandbookAll chapters
Part 9 of 15Planning - Agents with a Plan
Chapter 24Breaking Down Tasks (Task Decomposition) › Making Decomposition Practical
Reading section 7 of 12 · Making Decomposition Practical · 2 minSection 7 of 12 · 2 min

Book contents

Section 7 of 12 · 2 min read

Breaking Down Tasks (Task Decomposition) › Making Decomposition PracticalOne section · Sections in this chapter7 / 12 ↓

Let's build a more complete version of our decomposition system that our assistant can actually use. We'll add structure to make it easier to work with the resulting subtask list.

First, here's a class that handles task decomposition:

In[11]:
Code
## Using Claude Sonnet 4.5 for its superior agent reasoning capabilities
import os
from anthropic import Anthropic
import json
import re
from typing import List, Dict

class TaskDecomposer:
    """Breaks complex tasks into actionable subtasks"""
    
    def __init__(self):
        self.client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
    
    def decompose(self, user_request: str) -> List[Dict]:
        """Decompose a user request into structured subtasks."""
        prompt = f"""You are an AI assistant that excels at breaking down complex tasks.

User request: {user_request}

Decompose this into specific, actionable subtasks in logical order.

Respond ONLY with a JSON array, no other text:
[{{"id": 1, "description": "first subtask"}}, ...]"""

        response = self.client.messages.create(
            model="claude-sonnet-4-5",
            max_tokens=700,
            messages=[{"role": "user", "content": prompt}]
        )
        
        text = response.content[0].text
        # Extract JSON array from response (in case there's extra text)
        match = re.search(r'\[.*\]', text, re.DOTALL)
        if match:
            subtasks_data = json.loads(match.group())
        else:
            subtasks_data = json.loads(text)
        
        # Add status tracking to each subtask
        return [
            {
                "id": task["id"],
                "description": task["description"],
                "status": "pending"
            }
            for task in subtasks_data
        ]

Now let's use it:

In[12]:
Code
decomposer = TaskDecomposer()
request = "Plan my weekend getaway to the mountains."
plan = decomposer.decompose(request)

print("Task Decomposition:")
for task in plan:
    print(f"{task['id']}. [{task['status']}] {task['description']}")
Out[12]:
Console
Task Decomposition:
1. [pending] Determine travel dates and duration of the weekend getaway
2. [pending] Set a budget for transportation, accommodation, food, and activities
3. [pending] Choose specific mountain destination based on distance, weather, and preferences
4. [pending] Research and book accommodation (hotel, cabin, Airbnb, etc.)
5. [pending] Plan transportation method and book if needed (car rental, gas, flights, shuttles)
6. [pending] Check weather forecast for the mountain destination
7. [pending] Create packing list including weather-appropriate clothing, gear, and essentials
8. [pending] Research and list activities available (hiking trails, skiing, sightseeing, restaurants)
9. [pending] Make restaurant reservations if needed
10. [pending] Book any activities or tours that require advance reservations
11. [pending] Plan route and check road conditions or trail conditions
12. [pending] Prepare vehicle or arrange transportation pickup details
13. [pending] Pack bags with clothing, toiletries, medications, and activity gear
14. [pending] Download offline maps and save important contact numbers and confirmations

This gives us a structured plan that we can later execute. Each subtask has an ID (for reference), a description (what to do), and a status (to track progress).

Output might look like:

Task Decomposition:

1. [pending] Find mountain destinations within 2 hours driving
2. [pending] Check weather forecast for this weekend
3. [pending] Research lodging options at chosen destination
4. [pending] Book accommodation for Friday and Saturday night
5. [pending] Plan hiking or activities based on weather
6. [pending] Create packing list for mountain trip

Now our assistant has a concrete plan. In the next sections, we'll see how to actually execute these steps.