AI Hints
Home›LangGraph Tutorial›Agent Patterns
LangGraph · Lesson 89 of 120

Plan and Execute

Plan first.

⏱ 2 min read▶ Video at 1:36:25🎓 Free
Watch this lesson in the LangGraph courseWatch on YouTube ↗Full LangGraph course

For bigger tasks, it helps to plan first. A planner writes a short list of steps. An executor works through them, one at a time. Then a final step pulls the results together.

Plan and Execute
From the video: Plan and Execute
  • Big tasks
  • Plan first
  • Then execute each step

Planning an event

The model, the plan format, and the state live in a small helper file. The planner uses structured output to return a list of steps, at most three. The execute node does the next step, and stores the result. A routing function loops until every step is done. Run it. We see the plan, then a short result for each step, in order.

plan_execute.pypython
from langgraph.graph import StateGraph, START, END
from plan_setup import model, Plan, State

def plan(s):
    p = model.with_structured_output(Plan).invoke(f"Plan in at most 3 short steps: {s['task']}")
    return {"steps": p.steps[:3]}

def execute(s):
    step = s["steps"][len(s["done"])]
    return {"done": [model.invoke(f"In under 12 words, do: {step}").text.strip()]}

def more(s): return "execute" if len(s["done"]) < len(s["steps"]) else END

b = StateGraph(State); b.add_sequence([plan, execute]); b.add_edge(START, "plan")
b.add_conditional_edges("execute", more)
out = b.compile().invoke({"task": "a Saturday story time for children", "done": []})
for i, (step, result) in enumerate(zip(out["steps"], out["done"]), 1):
    print(f"{i}. {step}\n   -> {result}")
Output
1. Gather children in a cozy circle
   -> Gather close, little ones, and sit in a cozy circle.
2. Read an engaging and interactive story
   -> Dive into a thrilling story and choose your own path!
3. Do a fun themed craft activity
   -> Carve a spooky pumpkin face for Halloween tonight!
Also uses plan_setup.py
import operator
from typing import Annotated, TypedDict
from pydantic import BaseModel
from langchain.chat_models import init_chat_model

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)

class Plan(BaseModel):
    steps: list[str]

class State(TypedDict):
    task: str
    steps: list[str]
    done: Annotated[list[str], operator.add]

When planning helps

Planning helps with multi step tasks, like research, or organising an event. Each step gets a focused prompt. And a human can review the plan before any step runs, using an interrupt.

keyvalue
Multi-stepresearch, events
Focusone step at a time
Reviewinterrupt after planning
Re-planif a step fails

Summary

Plan and execute writes a plan, then works through the steps in a loop. Next, agents that check and improve their own work.

Key takeaways
  • Planner: list of steps
  • Executor loops
  • Results collected
Next up: Reflection — critique and improve