Skip to content
Blog

Dynamic Task Decomposition: Agents That Break Goals into Sub-Agent Assignments

How to build autonomous planner agents in Google ADK that break high-level objectives into structured sub-tasks and dynamically dispatch assignments to specialized worker agents.

Published on • November 29, 2026

AI Assistant

Complex real-world objectives—such as “Build a competitor analysis report on three FinTech companies,” “Migrate this legacy Python 2 script to modern typed Python 3.12,” or “Plan a 5-day corporate conference in Tokyo”—cannot be executed in a single shot. Attempting to solve them in one prompt leads to truncated outputs, missing steps, and shallow analysis.

The solution is Dynamic Task Decomposition: an autonomous Planner agent analyzes the macro goal, decomposes it into an ordered list of discrete sub-tasks, and dynamically assigns each task unit to specialized worker agents.

In this tutorial, we will build a complete task decomposition and execution engine in Google Agent Development Kit (ADK) leveraging Pydantic plan representations and dynamic dispatching.


1. Architectural Blueprint: Planner-Worker Engine

The decomposition lifecycle consists of four distinct phases:

  1. Decomposition (Planning): The Planner ingests the broad user goal and generates a structured Plan (a Directed Acyclic Graph or ordered task list).
  2. State Initialization: The Plan is stored in session.state["task_plan"] with statuses initialized to PENDING.
  3. Execution & Dispatch: Tasks are picked up and dispatched to the appropriate specialist agent (Researcher, Analyst, Formatter).
  4. Synthesis: Once all sub-tasks reach COMPLETED, the final aggregator compiles the unified deliverable.
                      [User Goal: "Analyze Competitor Cloud X"]
                                          │
                                          ▼
                      ┌───────────────────────────────────────┐
                      │             Planner Agent             │
                      │  - Breaks goal into discrete steps    │
                      │  - Emits JSON TaskPlan to state       │
                      └───────────────────────────────────────┘
                                          │
                                          ▼
                      ┌───────────────────────────────────────┐
                      │       Shared Session Task Plan        │
                      │  - Task 1: Pricing Review (DONE)      │
                      │  - Task 2: Security Review (PENDING)  │
                      │  - Task 3: Feature Matrix (PENDING)   │
                      └───────────────────────────────────────┘
                                    /     \
                       Task 2 Dispatched   Task 3 Dispatched
                                  /         \
                                 ▼           ▼
                      ┌──────────────┐   ┌──────────────┐
                      │Sec Specialist│   │Feature Spec. │
                      └──────────────┘   └──────────────┘

2. Defining the Structured Task Models

We model tasks and plans using Pydantic:

from enum import Enum
from typing import List, Optional, Dict, Any
from pydantic import BaseModel, Field

class TaskStatus(str, Enum):
    PENDING = "pending"
    IN_PROGRESS = "in_progress"
    COMPLETED = "completed"
    FAILED = "failed"

class SubTask(BaseModel):
    task_id: int = Field(description="Unique incremental integer identifier.")
    title: str = Field(description="Short summary of the sub-task.")
    worker_role: str = Field(description="Assigned specialist: 'researcher', 'coder', or 'editor'.")
    instructions: str = Field(description="Detailed instructions and acceptance criteria.")
    status: TaskStatus = Field(default=TaskStatus.PENDING)
    result_data: Optional[str] = Field(default=None)

class TaskPlan(BaseModel):
    macro_goal: str
    subtasks: List[SubTask]

3. Implementing the Planner and Specialist Workers

In Google ADK, we can represent the Planner and the Specialists cleanly:

import json
from google.adk.agents import Agent
from google.genai import types as genai_types

# 1. Specialized Workers
researcher = Agent(
    name="web_researcher",
    model="gemini-3.8-flash",
    description="Researches market trends, pricing models, and competitor features.",
    instruction="""
    You are a Market Research Specialist.
    Perform the requested research thoroughly and summarize your findings in concise bullet points.
    """,
    output_key="last_worker_result",
)

technical_coder = Agent(
    name="code_specialist",
    model="gemini-3.8-flash",
    description="Writes code, generates benchmark scripts, and inspects APIs.",
    instruction="""
    You are a Senior Software Engineer.
    Implement clean, documented, and tested solutions for the assigned task.
    """,
    output_key="last_worker_result",
)

# 2. Planner Agent
planner_agent = Agent(
    name="strategic_planner",
    model="gemini-3.8-flash",
    description="Decomposes high-level goals into 2 to 4 discrete, actionable subtasks.",
    instruction="""
    You are a Strategic Project Planner.
    Analyze the user's high-level goal and break it down into 2-4 sequential sub-tasks.
    Assign each task to either 'web_researcher' or 'code_specialist'.
    Output your plan as valid JSON matching this schema:
    {
      "macro_goal": "<user goal>",
      "subtasks": [
        {"task_id": 1, "title": "...", "worker_role": "web_researcher", "instructions": "..."},
        {"task_id": 2, "title": "...", "worker_role": "code_specialist", "instructions": "..."}
      ]
    }
    """,
    generate_content_config=genai_types.GenerateContentConfig(temperature=0.1),
    output_key="raw_task_plan",
)

4. Implementing the Orchestration Dispatcher

We build a custom coordinator agent that parses the plan and executes tasks sequentially:

from typing import AsyncGenerator
from google.adk.agents import BaseAgent
from google.adk.agents.invocation_context import InvocationContext
from google.adk.events import Event

class DynamicPlanExecutor(BaseAgent):
    """Parses the generated plan from state and delegates each sub-task to specialists."""

    def __init__(self, name: str, workers: Dict[str, Agent]):
        super().__init__(name=name)
        self.workers = workers

    async def _run_async_impl(
        self, ctx: InvocationContext
    ) -> AsyncGenerator[Event, None]:
        raw_plan = ctx.session.state.get("raw_task_plan", "{}")
        # Clean json
        clean = raw_plan.replace("```json", "").replace("```", "").strip()
        try:
            plan_dict = json.loads(clean)
            plan = TaskPlan(**plan_dict)
        except Exception as err:
            yield Event(author=self.name, content=f"Failed to parse plan: {str(err)}")
            return

        yield Event(author=self.name, content=f"Plan generated: {len(plan.subtasks)} subtasks to execute.")

        accumulated_results = []

        # Iterate and execute each subtask
        for task in plan.subtasks:
            worker = self.workers.get(task.worker_role)
            if not worker:
                yield Event(author=self.name, content=f"No worker available for role: {task.worker_role}")
                continue

            yield Event(author=self.name, content=f"Starting Task #{task.task_id}: {task.title} (Worker: {task.worker_role})")

            # Execute sub-agent turn with task instructions
            task_prompt = f"Goal: {plan.macro_goal}\nTask: {task.title}\nInstructions: {task.instructions}"
            async for ev in worker.run_async(ctx):
                if ev.content:
                    yield ev

            task_output = ctx.session.state.get("last_worker_result", "")
            accumulated_results.append(f"### Task {task.task_id}: {task.title}\n{task_output}")

        # Final Synthesis
        summary_report = f"# Final Consolidated Report: {plan.macro_goal}\n\n" + "\n\n".join(accumulated_results)
        ctx.session.state["final_decomposed_report"] = summary_report
        yield Event(author=self.name, content="All subtasks completed successfully!")

5. Wiring the Full Workflow

import asyncio
from google.adk.agents import SequentialAgent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService

workers_map = {
    "web_researcher": researcher,
    "code_specialist": technical_coder,
}

full_task_engine = SequentialAgent(
    name="dynamic_decomposition_engine",
    sub_agents=[
        planner_agent,
        DynamicPlanExecutor(name="plan_executor", workers=workers_map),
    ],
)

async def main():
    session_service = InMemorySessionService()
    runner = Runner(agent=full_task_engine, session_service=session_service)
    session = await session_service.get_or_create("project_plan_01")

    prompt = "Research the top 2 features of Python 3.13 free-threading (PEP 703) and provide a benchmark code snippet."
    print(f"User Request: {prompt}\n")

    async for event in runner.run_async(session=session, message=prompt):
        if event.author == "plan_executor":
            print(f">> {event.content}")

    print("\n================ COMPLETED REPORT ================")
    print(session.state.get("final_decomposed_report"))

if __name__ == "__main__":
    asyncio.run(main())

6. Key Production Best Practices

  1. Max Sub-Task Limits: Constrain the Planner to a maximum of 4–5 sub-tasks per user request. Overly granular plans (e.g., 20 micro-tasks) increase latency and token consumption exponentially.
  2. Re-Planning on Step Failure: If a sub-task worker returns an unrecoverable error, pass the error back to the Planner agent to generate a revised sub-plan rather than halting the entire pipeline.
  3. Persist State Milestones: Store each completed sub-task’s output in persistent storage (e.g., Firestore or Cloud SQL) so if a network timeout occurs mid-plan, the engine can resume without repeating earlier steps.

Takeaway: Dynamic task decomposition unlocks the ability to tackle complex, multi-stage enterprise projects with precision and modular accountability.

Sources