Multi-Step Planning
Have the model break a goal into ordered steps before it starts acting on any of them.
What you will be able to do
- Explain why multi-step goals benefit from planning
- Build a planner using a single LLM call, without tools
- Get the plan back as a clean numbered list, and turn it into Python strings
- Tell planning apart from the ReAct pattern - and connect the two
- Generate plans based on the tools the agent actually has
- Pass the results of earlier steps to the steps after them
- Re-check the goal during execution, and stop when it is met
- Implement a complete planning workflow with Python and Ollama
The idea, in plain English
Imagine asking an agent: "Compare the weather in Mumbai and Delhi and tell me which city is warmer and by how much." That is several operations: get Mumbai’s weather, get Delhi’s weather, pull out the two temperatures, calculate the difference, and present the result.
Instead of deciding what to do from scratch at every step, we can ask the model to write a PLAN before executing anything. This is called multi-step planning, and the idea is simple: first understand the goal; next break it into smaller, ordered steps; then execute the steps one at a time; finally check whether the original goal has been achieved.
A plan is a guess written before anything has run. Our real runs show three ways it goes wrong - steps the agent cannot do, steps that cannot see earlier results, and a plan that goes out of date - and this lesson fixes each one.
Worked example: Comparing the weather in Mumbai and Delhi: plan the steps, run each with ReAct, and stop when the goal is met.
1 - Plan before acting
One call, no tools. The planner is told which tools exist, so it writes steps the agent can do: get Mumbai’s weather, get Delhi’s, extract the temperatures, calculate the difference, write the answer.
A real run of "Compare the weather in Mumbai and Delhi and tell me the temperature difference." The planner wrote five steps; the agent stopped after two.
The idea in everyday life: a birthday party
Someone asks you: "Organize a small birthday party for my friend." Would you start booking things without thinking? Probably not:
- STEP 1 - UNDERSTAND THE GOAL: a small birthday party for a friend.
- STEP 2 - MAKE A PLAN: decide the date and time, find a venue, check its cost, arrange food and a cake, invite the guests, arrange decorations, confirm everything. The list gives you a direction before any work starts.
- STEP 3 - CHECK WHAT YOU CAN ACTUALLY DO: now imagine you are an assistant who can only search for venues and calculate costs. You cannot book a venue, order a cake, send invitations or put up decorations.
- So a plan can look right to a person and still contain steps an agent cannot carry out.
- STEP 4 - TELL THE PLANNER YOUR TOOLS: say up front that the agent has search_venues(location) and calculate(expression).
- STEP 5 - GET A TOOL-AWARE PLAN: for example, 1) search for venues in the area, 2) compare the options, 3) calculate the estimated cost, 4) present the options and costs. Every step is something the agent can do.
- STEP 6 - EXECUTE IT: run the steps one at a time, look at each result, and decide whether to carry on.
Tip: Planning is not just breaking a goal into smaller tasks. It is breaking it into tasks the agent can actually execute.
What is multi-step planning?
Multi-step planning is a technique in which an LLM breaks a complex goal into an ordered list of smaller tasks before any of them is executed. Two parts do the work:
- The PLANNER decides what needs to happen, and in what order. It does not run any tools - it only writes the plan.
- The EXECUTOR carries out each planned step, using the tools the agent has.
User goal: Compare the weather in Mumbai and Delhi.
|
Planner: writes an ordered list of steps (one LLM call, no tools)
|
Executor: 1. Get Mumbai weather
2. Get Delhi weather
3. Extract the temperatures
4. Calculate the temperature difference
5. Write the final answer
|
Result: Mumbai 27°C, Delhi 34°C - a difference of 7°CBuilding our first planner
The planner needs only one LLM call. We use llama3.1, as in the earlier lessons.
- STEP 1 - SET UP: pull the model and install the Python package (commands below).
- STEP 2 - WRITE make_plan(): one call to ollama.chat() with two messages.
- STEP 3 - UNDERSTAND THE PROMPT. The SYSTEM message tells the model how to behave: break the goal into steps, as a numbered list, output only the list, no explanations. The USER message is the goal itself.
- STEP 4 - LOOK AT THE OUTPUT: a plan, and nothing has been executed.
- Why "Output ONLY the numbered list"? Without it, all 4 of our runs began "Here’s a short numbered list of concrete steps...", and one added 22 lines of sub-bullets. With it, 4 of 4 were a clean list - easy to read and easy to process in code.
- Asking for a SHORT plan does not fix the number of steps: the birthday party came back with 7 or 8.
ollama pull llama3.1
pip install ollama # or: uv add ollamaimport ollama
def make_plan(goal):
response = ollama.chat(
model="llama3.1",
messages=[
{"role": "system", "content": "Break the user's goal into a short numbered list of concrete steps. Output ONLY the numbered list."},
{"role": "user", "content": goal}
]
)
return response["message"]["content"]
plan = make_plan("Organize a small birthday party for a friend")
print(plan)1. Decide on a date and time for the party
2. Choose a theme or color scheme for the party
3. Create a guest list and send out invitations
4. Plan the menu and order food and drinks
5. Plan games and activities for the party
6. Prepare decorations and party favors
7. Confirm the party details with the guest of honor
With "Output ONLY the numbered list": 4 of 4 runs a clean list, 7-8 steps
Without it: 4 of 4 runs began "Here's a short numbered list ..."Planning and ReAct are different
You met the ReAct loop in Lesson 1.6. Planning and ReAct answer different questions:
- PLANNING answers "what should happen, and in what order?" It looks at the whole goal once and writes the list.
- REACT answers "how do I complete THIS step?" Thought (what is needed), Action (run a tool), Observation (look at the result) - repeated until the step is done.
- How they work together: 1) the planner writes the plan; 2) the executor takes the first step; 3) ReAct performs it with the tools; 4) the result is collected; 5) the executor moves to the next step; 6) the goal is checked again.
DecidesPlanning: WHAT to do. ReAct: HOW to do one step.Looks atPlanning: the whole goal. ReAct: one step.ProducesPlanning: an ordered list. ReAct: tool calls and a result.LLM callsPlanning: usually one. ReAct: several Thought/Action/Observation rounds.ToolsPlanning: none. ReAct: uses them.Tip: Planning decides WHAT to do. ReAct decides HOW to do each step.
Problem 1: steps the agent cannot execute
We asked: "Compare the weather in Mumbai and Delhi and tell me the temperature difference" - without telling the planner which tools exist.
- The plan looked fine, but it was written for a person. "Note down the temperature in Mumbai" is not something our agent can do - it only has get_weather(city) and calculate(expression).
- THE FIX: describe the available tools in the planner’s prompt. The second plan below uses only steps those tools can perform.
- But ask for PLAIN-LANGUAGE steps, not code. One prompt that showed tool syntax got back calculate(substring(get_weather("Mumbai"), ...)) - nested calls to functions that do not exist.
- Let the ReAct executor decide the actual tool calls. The planner only describes the tasks.
Goal: Compare the weather in Mumbai and Delhi and tell me the temperature difference.
Planner told nothing about the agent:
1. Check the current weather in Mumbai and Delhi.
2. Note down the temperature in Mumbai. <- no tool does this
3. Note down the temperature in Delhi.
4. Calculate the temperature difference between Mumbai and Delhi.
5. Report the temperature difference.
Planner told the tools, asked for plain words:
1. Get the current weather for Mumbai using get_weather("Mumbai")
2. Get the current weather for Delhi using get_weather("Delhi")
3. Extract the temperature values from the weather data for both cities
4. Calculate the temperature difference between the two cities
5. Write the answerTip: Tell the planner which tools exist - but let the executor decide the actual tool calls.
Problem 2: steps cannot see previous results
With a good plan in hand, we ran each step on its own:
- Steps 1 and 2 worked: Mumbai rainy, 27°C; Delhi sunny, 34°C.
- Step 3 ("extract the temperatures") and step 4 ("calculate the difference") both got stuck. They had never seen the weather - nobody passed it to them.
- THE FIX: keep a results list. After each step, add its result to the list.
- Then every step receives three things: the original goal, all the results so far, and "do only this step".
- Now step 3 has the two temperatures in front of it, and the work carries on from one step to the next.
Get the current weather for Mumbai -> rainy, 27°C
Get the current weather for Delhi -> sunny, 34°C
Extract the temperatures -> Agent got stuck - no action found.
Calculate the difference -> Agent got stuck - no action found.Overall goal: Compare the weather in Mumbai and Delhi and tell me the temperature difference.
Results so far:
Step 1: Mumbai is rainy, 27°C
Step 2: Delhi is sunny, 34°C
Do only this step: Extract the temperature values from the weather data for both citiesProblem 3: a plan can become outdated
- A plan is written before execution starts - it is what the model EXPECTS to happen. Real results can change the situation: a file is missing, a restaurant is closed, or the answer turns up earlier than expected.
- THE FIX: re-check the original goal after every step. goal_is_met(goal, results) asks the LLM one question: "Do these results fully achieve the goal?"
- YES - stop, and skip the remaining steps. NO - continue with the next step.
- In one of our runs the answer was YES after step 2 of 5, so steps 3, 4 and 5 were never run.
- Our implementation uses a STATIC plan (written once) with a DYNAMIC goal check. A more advanced agent would also re-plan when a step fails - structured branching and re-planning come with LangGraph in Module 3.
Static planningThe plan is written before execution and followed in order. It is not reconsidered.Dynamic planningThe plan can change during execution: stop early, or write a new plan when results change.This lessonA static plan, with a dynamic check of the goal after every step.Putting everything together: run_plan()
run_plan() fixes all three problems. It has five parts:
- 1. make_plan() - the planner, with a prompt that lists the tools and asks for plain words.
- 2. Parse the plan - a regular expression turns the numbered lines into a Python list: "1. Get Mumbai weather." becomes "Get Mumbai weather.".
- 3. run_agent() - executes each step through the ReAct loop. It is reused from Lesson 1.6 (the version with the tools, the stop sequence and the Action-first check) - not rewritten here.
- 4. goal_is_met() - after every step, checks whether the goal has been achieved.
- 5. The final answer - one last call writes the reply, using only the collected results.
- ask() uses temperature 0, so the planner, the YES/NO check and the final answer are as consistent as possible between runs. That improves consistency - it does not guarantee identical output on every machine.
import re
import ollama
MODEL = "llama3.1"
# Reuses get_weather, calculate, TOOLS and run_agent from Lesson 1.6
# (the version with the stop sequence and the Action-first check).
# 1. The planner prompt: the tools, plain words, only the list
PLANNER_PROMPT = """Break the user's goal into a short numbered list of steps, in plain words.
The steps will be carried out by an agent whose only tools are:
- get_weather(city): the current weather for a city
- calculate(expression): evaluates a maths expression
Only include steps those tools can do, then one last step that writes the answer.
Output ONLY the numbered list."""
# 2. Pick out the numbered lines: "1. Get Mumbai weather." -> "Get Mumbai weather."
STEP = re.compile(r"^\s*\d+[.)]\s+(.+)$", re.MULTILINE)
def ask(system, user):
"""One LLM call with temperature 0 - used by the planner, the check and the answer."""
response = ollama.chat(
model=MODEL,
messages=[{"role": "system", "content": system}, {"role": "user", "content": user}],
options={"temperature": 0},
)
return response["message"]["content"].strip()
def make_plan(goal):
return STEP.findall(ask(PLANNER_PROMPT, goal))
# 4. Has the goal been achieved yet?
def goal_is_met(goal, results):
verdict = ask(
"Answer only YES or NO.",
f"Goal: {goal}\nResults so far:\n{results}\n\nDo these results fully achieve the goal?",
)
return verdict.upper().startswith("YES")
def run_plan(goal):
steps = make_plan(goal)
print("Plan:", *steps, sep="\n ")
results = []
for number, step in enumerate(steps, start=1):
# 3. Execute one step, with the goal and everything found so far
context = "\n".join(results) or "nothing yet"
answer = run_agent(
f"Overall goal: {goal}\nResults so far:\n{context}\n\nDo only this step: {step}"
)
results.append(f"Step {number}: {answer}")
print(f"Step {number} done: {answer}")
# Re-check after every step: the plan was a guess made before anything ran.
if goal_is_met(goal, "\n".join(results)):
print(f"Goal met after step {number} of {len(steps)} - stopping.")
break
# 5. The final answer, from the collected results only
return ask(
"Answer the user's goal in one or two sentences, using only these results.",
f"Goal: {goal}\nResults:\n" + "\n".join(results),
)
result = run_plan("Compare the weather in Mumbai and Delhi and tell me the temperature difference.")
print("Final Answer:", result)Understanding the actual execution results
We ran run_plan() twice on each of two goals:
- All four final answers were correct.
- In one weather run the goal check said YES after step 2 of 5 and stopped. The executor had gone further than asked inside the early steps - fetching both cities and calculating the difference - so the results already answered the question.
- But three tool calls would have been enough for each goal, and the runs we counted made 9 to 14.
- Why? Even with a plan, a small model can repeat tool calls, do the whole goal inside one step, repeat that work in later steps, and ignore the boundaries between steps.
- Planning adds structure. It does not make the executor disciplined.
"Compare the weather in Mumbai and Delhi ..."
run 1 all 5 steps 14 tool calls "the temperature difference ... is 7°C"
run 2 stopped after step 2 of 5 (goal met) "... is 7°C"
"What is 12 * 8, plus the temperature in Delhi?"
run 1 all 5 steps 12 tool calls "... you get a total of 130"
run 2 all 5 steps 9 tool calls "... the overall answer is 130"
Every final answer correct. Three tool calls would have been enough each time.Weather, run 1All 5 steps, 14 tool calls. Correct: 7°C.Weather, run 2Stopped after step 2 of 5 (goal met). Tool calls not recorded. Correct: 7°C.12 * 8 + Delhi temp, run 1All 5 steps, 12 tool calls. Correct: 130.12 * 8 + Delhi temp, run 2All 5 steps, 9 tool calls. Correct: 130.Planning at a glance
make_plan(goal)One call, no tools, a numbered list.
Output ONLY the numbered list.
Parse the stepsTurn the list into Python strings.
re.findall(r"^\s*\d+[.)]\s+(.+)$", text, re.MULTILINE)
Tell it the toolsSo every step is something the agent can do.
- get_weather(city) - calculate(expression)
Results so farWhat each step receives from earlier steps.
Results so far:\n{context}Re-checkStop or re-plan when the plan is out of date.
goal_is_met(goal, results)
Try it yourself
The code does not change. Swap the content string and the program does something else entirely.
“run_plan("Organize a small birthday party for a friend") - our weather and calculator tools cannot do most of these steps. What does the planner write?”
“run_plan("Compare the weather in Mumbai and Delhi and tell me the temperature difference.")”
“run_plan("What is 12 * 8, plus the temperature in Delhi?") - calculation and weather together.”
“run_plan("Book me a table at a restaurant in Mumbai tonight.") - there is no booking tool. Does the planner pretend there is?”
What usually goes wrong
The prompt does not enforce the output format, so the plan arrives wrapped in an introduction and sub-bullets.
✗ "Break the user's goal into a short numbered list of concrete steps."✓ "... Output ONLY the numbered list."It does not know the available tools, so it plans for a person: "note down the temperature", "book a venue".
Asking for code, or showing tool syntax, invites functions that do not exist. Ask for plain-language steps and let ReAct choose the calls.
✗ calculate(substring(get_weather("Mumbai"), ...))✓ Get the current weather for MumbaiPrevious results are not passed on, so a step that needs them has nothing to work with.
✗ for step in steps:
run_agent(step)✓ run_agent(f"Overall goal: {goal}\nResults so far:\n{context}\n\nDo only this step: {step}")It follows the original plan blindly, even when the goal is already met.
The executor does not respect step boundaries. Tell it explicitly to do only the current step - and expect a small model to drift anyway.
Key points
- Plan before acting: a multi-step goal benefits from an ordered plan instead of improvising every action.
- One planner call: generate the plan with a single LLM call, without tools.
- Strict output format: ask the model to output only a numbered list.
- Tool-aware planning: tell the planner which tools are available.
- Plain-language steps: let the planner describe tasks, not write tool-call code.
- Planning + ReAct: planning decides what to do; ReAct carries out each step.
- Maintain context: pass the original goal and the previous results into every step.
- Re-check the goal: stop as soon as the original goal has been achieved.
- Planning has limits: it adds structure, but it does not guarantee efficient execution.
- An intelligent agent knows not just how to act, but which actions are needed, in what order, what each needs, and when to stop.
Quiz
- 1.
1. Why do we create a plan before executing a multi-step task?
- 2.
2. Why should the planner know which tools are available?
- 3.
3. What is the main difference between planning and ReAct?
- 4.
4. Why do we pass previous results to every step?
- 5.
5. What does goal_is_met() do?
- 6.
6. What is the biggest risk of following a plan blindly?
Interview questions
What is multi-step planning in agentic AI?
A technique where an LLM breaks a complex user goal into smaller, ordered steps before executing them, and an executor then carries out the steps one at a time.
What is the difference between planning and ReAct?
Planning determines the sequence of tasks. ReAct performs an individual task through reasoning, tool calls and observations. A practical agent uses a planner for the route and ReAct for each step.
What is the difference between static and dynamic planning?
Static planning generates a plan before execution and follows it. Dynamic planning adjusts during execution - stopping early, or re-planning when results make the original plan wrong.
What makes a plan executable by an AI agent?
Every step can be performed with the agent’s actual tools and capabilities, is written in plain language rather than code, and can see the results of earlier steps.
Why should previous execution results be passed to later steps?
Because later steps often depend on information collected earlier; run in isolation, they have nothing to work with.
How can an agent avoid executing unnecessary steps?
By checking after every step whether the original goal has already been achieved, and stopping when it has.
Does planning guarantee efficient execution?
No. Planning adds structure, but the LLM executor can still repeat tool calls or do unnecessary work - in our runs, 9 to 14 tool calls where 3 would have done.
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...