Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 62

LLM-Powered Task Decomposition

This lesson is built with resources from youtube.com, medium.com and 1 more site.

Hello! Welcome back to our journey into AI agents.

In the last lesson, we focused on a critical, practical skill: debugging agent execution flows using LangSmith. You learned how to trace the Thought-Action-Observation loop of a ReAct agent to diagnose failures in reasoning, tool use, and orchestration.

That ReAct agent, while powerful, has a strategic limitation. It decides its next step only after completing the previous one. For complex tasks requiring multiple steps, this is like trying to navigate a city by only deciding which street to take next at every intersection, without ever looking at a map. This can be slow and lead the agent down the wrong path.

To overcome this, we'll explore a more sophisticated architecture: Plan-and-Execute. In this lesson, you will learn how to implement the first and most crucial part of this architecture: a planning component that uses an LLM to decompose a complex task into a clear, multi-step plan.

From ReAct to Plan-and-Execute

The core idea of the Plan-and-Execute paradigm is to separate "thinking" from "doing."

  1. Planner: A component (usually an LLM) that looks at the overall goal and creates a step-by-step plan.
  2. Executor: A component that takes the plan and executes each step, often using tools.

This division of labor makes agents more reliable and efficient for complex tasks.

Plan-Execute Agent Architecture
This diagram shows the basic Plan-and-Execute architecture. A high-level **Task** is first given to a **Planning Agent** to create a series of steps. These steps are then passed to an **Execution Agent**, which uses tools to complete them.
LangChain Plan & Execute AI Agents Architecture
This flowchart illustrates a similar concept, where a user's question is first decomposed into a 'Todo List' (the plan), which is then executed by a 'Backbone Model' through an iterative loop.

Simple Planning: Prompt Chaining

Before building a formal planner, let's consider a simpler pattern you can implement in pure Python: prompt chaining. This is essentially a manually-coded plan, where the output of one LLM call becomes the input for the next. Your backend experience with service orchestration or building multi-step data processing pipelines is conceptually similar.

To see this pattern in action, let's watch a short segment from a video on building agents in Python.

Building AI Agents in Pure Python - Beginner Course

The following video from the 'Building AI Agents in Pure Python' course by Dave Ebbelaar demonstrates 'prompt chaining'. Notice how a complex request (scheduling a calendar event) is broken down into distinct LLM calls for extraction, parsing, and confirmation.

Watch the section on 'Prompt Chaining' from 26:09 to 37:46. Focus on how the problem is manually decomposed into three steps (extract, parse, confirm), each with its own prompt and structured output model. This is a hard-coded plan.

Prompt chaining is effective but rigid. The sequence of steps is fixed in the code. What if we could make the LLM generate this sequence dynamically based on the user's request? That's exactly what a planner does.


Designing a Planner Component

A planner is an agent whose primary job is to create a plan. To build one, we need to define:

  1. The Plan's Structure: What does a plan look like? It's a data structure. As a software engineer, you know the importance of well-defined schemas. We'll use Pydantic to define our plan as a list of structured steps.
  2. The Planner's Prompt: How do we instruct the LLM to generate this plan? We'll use a system prompt that tells the LLM its role is to be a "planner" and to break down the user's goal into a sequence of tasks.
  3. The Planner's Tools (Optional but Powerful): We can even give the planner tools to help it construct the plan. For instance, a tool to add_a_step_to_the_plan. This makes the planning process more explicit and controllable.

Let's explore a practical example from the LangChain community that shows how to build a sophisticated planner.

What is the best way to implement Plan and Execute ...

This forum post on the LangChain website titled 'What is the best way to implement Plan and Execute...' outlines a robust architecture for a planning agent. It uses a parent 'orchestrator' graph where the first step is always to call a dedicated planner agent.

Please read the sections that introduce the 'parent orchestrator' concept, define the OrchestratorState and 'Planner tools', and show the build_planner function. Focus on these key ideas: The shared OrchestratorState acts as the memory or 'scratchpad' for the entire system. The planner has its own tools (choose_next, add_task) that it uses to build and manage the plan within the state. The planner's prompt explicitly tells it how to use these tools to break down a goal.


Implementing the Planner

Now, let's translate those concepts into a working implementation. We'll build the planner component using LangGraph. For this lesson, we will focus only on generating the plan. In the next lesson, we will add the executor.

Step 1: Set up your environment

Make sure you have the necessary libraries installed:

pip install langchain langgraph langchain_openai pydantic

And configure your environment variables for OpenAI (and optionally LangSmith for tracing, as we learned in the last lesson).

import os
# os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY"
# os.environ["LANGCHAIN_TRACING_V2"] = "true"
# os.environ["LANGCHAIN_API_KEY"] = "YOUR_LANGSMITH_API_KEY"

Step 2: Define the State and Plan Structure

First, we define the data structures. The Plan will be a Pydantic model, and AgentState will be a TypedDict to hold our application's state, including the generated plan.

from typing import List, TypedDict
from langchain_core.pydantic_v1 import BaseModel, Field

# The structure of a single step in our plan
class Step(BaseModel):
    """A single step in a plan."""
    step_instruction: str = Field(..., description="The instruction for this step.")

# The structure of the overall plan
class Plan(BaseModel):
    """A plan consisting of a series of steps."""
    steps: List[Step] = Field(..., description="The list of steps to execute.")

# The state for our agent graph
class AgentState(TypedDict):
    input: str # The user's initial request
    plan: Plan # The plan generated by the planner

Step 3: Create the Planner Prompt

Next, we create a prompt template that instructs the LLM to act as a planner and produce output matching our Plan Pydantic model.

from langchain_core.prompts import ChatPromptTemplate

planner_prompt_template = """
You are an expert planner. Your job is to create a step-by-step plan to answer the user's request.
For the given request, create a plan of the steps that need to be taken.
Each step should be a clear and concise instruction.

User's Request:
{input}
"""

planner_prompt = ChatPromptTemplate.from_template(planner_prompt_template)

Step 4: Build the Planner Node

Now, we combine the prompt, an LLM, and our desired output structure (Plan) into a runnable component. This will be a node in our LangGraph.

from langchain_openai import ChatOpenAI

# Initialize the LLM
# Using a powerful model like gpt-4-turbo is good for planning
llm = ChatOpenAI(model="gpt-4-turbo", temperature=0)

# Create the planner by chaining the prompt, LLM, and a structured output parser
planner = planner_prompt | llm.with_structured_output(Plan)

The .with_structured_output(Plan) method is a powerful feature that leverages the LLM's function-calling capabilities to force its output into the Pydantic schema you provide. This ensures the output is a clean, machine-readable plan.

Step 5: Define the Planner Function and Graph

Finally, let's wrap this logic in a function that will serve as our graph's node and build the graph itself.

from langgraph.graph import StateGraph, END

# This function will be a node in our graph. It invokes the planner and updates the state.
async def plan_step(state: AgentState) -> AgentState:
    print("---GENERATING PLAN---")
    plan_result = await planner.ainvoke({"input": state["input"]})
    print(f"Plan: {plan_result}")
    return {"plan": plan_result}

# Define the graph
workflow = StateGraph(AgentState)

# Add the planner node
workflow.add_node("planner", plan_step)

# Set the entry point
workflow.set_entry_point("planner")

# For now, the planner is the only step. We'll add the executor later.
workflow.add_edge("planner", END)

# Compile the graph into a runnable app
app = workflow.compile()

# Let's run it!
async def run_planner():
    complex_request = "Research the performance of NVIDIA's stock in 2023, identify the key drivers for its growth, and write a short summary of the findings."
    
    final_state = await app.ainvoke({"input": complex_request})
    
    print("\n---FINAL PLAN---")
    for i, step in enumerate(final_state['plan'].steps):
        print(f"Step {i+1}: {step.step_instruction}")

import asyncio
asyncio.run(run_planner())

When you run this code, you will see the LLM generate a structured plan for the complex request. For example:

---GENERATING PLAN---
Plan: steps=[Step(step_instruction="Search for NVIDIA's stock performance data for the calendar year 2023, including opening and closing prices."), Step(step_instruction='Analyze the collected data to calculate the percentage growth of NVIDIA stock in 2023.'), Step(step_instruction='Research news articles, analyst reports, and company announcements from 2023 to identify key events and factors influencing the stock price.'), Step(step_instruction="Synthesize the identified drivers, such as AI chip demand, earnings reports, and market trends, into a concise list."), Step(step_instruction='Write a short summary that includes the overall stock performance and the primary reasons for its growth.')]

---FINAL PLAN---
Step 1: Search for NVIDIA's stock performance data for the calendar year 2023, including opening and closing prices.
Step 2: Analyze the collected data to calculate the percentage growth of NVIDIA stock in 2023.
Step 3: Research news articles, analyst reports, and company announcements from 2023 to identify key events and factors influencing the stock price.
Step 4: Synthesize the identified drivers, such as AI chip demand, earnings reports, and market trends, into a concise list.
Step 5: Write a short summary that includes the overall stock performance and the primary reasons for its growth.
Test your understanding!

Modify the complex_request in the run_planner function to be: "Create a Dockerfile for a basic Python FastAPI application, write a simple 'Hello, World' endpoint, and then outline the steps to build and run the Docker container."

Run the code again. Does the planner generate a logical sequence of steps? How does this demonstrate the advantage over a simple ReAct agent for a task that involves creating related artifacts?

Show answer

The planner should generate a logical sequence, something like:

  1. Write the Python code for a simple FastAPI application with a / endpoint that returns "Hello, World".
  2. Create a requirements.txt file listing fastapi and uvicorn.
  3. Write a Dockerfile that starts from a Python base image, copies the application code, installs dependencies from requirements.txt, and sets the command to run the application with uvicorn.
  4. Provide the docker build command to build the image from the Dockerfile.
  5. Provide the docker run command to run the container, mapping the necessary ports.

A simple ReAct agent might struggle with this because the steps are highly dependent. For instance, the Dockerfile content depends on the Python filename, and the docker run command depends on the port exposed in the Dockerfile. By creating a high-level plan first, the agent has a "blueprint" to follow, which is far more reliable for such tasks.


Conclusion

Congratulations! You have successfully implemented the core of a Plan-and-Execute agent: the planner. You've seen how to move beyond the reactive, single-step nature of simple agents to a more strategic approach where the agent first formulates a plan before acting.

Key Takeaways:

  • Plan-and-Execute is an agent architecture that separates planning from execution, making agents more effective for complex, multi-step tasks.
  • A planner is a component, typically powered by an LLM, that decomposes a high-level goal into a sequence of smaller, actionable steps.
  • Using structured output (like Pydantic models) is crucial for ensuring the planner produces a machine-readable plan that can be consumed by other parts of the system.
  • LangGraph allows us to define this workflow clearly, creating a node for the planner and managing the state (which holds the input and the generated plan).

What's Next?

Having a plan is great, but a plan is useless without action. In our next lesson, we will build the other half of this architecture: an executor agent. You will learn how to build an agent that takes the plan we've just generated, iterates through each step, and uses tools to get the job done.