Module 4: Planning and Control·Lesson 10 of 15·8 min read

ReAct vs Plan-and-Execute Agents, With Python Code for Both

The problem: multi-step tasks need a strategy, not only a loop

Ask the trip helper "I have 300 USD. Find a Lisbon hotel under 100 EUR a night and tell me if I need an umbrella there." That is three lookups: a currency conversion, a hotel search, a forecast. The agent loop from lesson 2 can handle it, but how does it decide what to do first, and when it has done enough?

There are two classic answers:

  1. ReAct: think one step, act one step, look at the result, repeat. The plan forms as the agent goes.
  2. Plan-then-execute: write the whole plan first, then carry out each step, then combine the results.

Both are simple enough to build by hand. This lesson builds each one for the trip helper, runs them, and compares where each one breaks.

ReAct: reasoning and acting, interleaved

ReAct comes from a research paper by Yao and colleagues, "ReAct: Synergizing Reasoning and Acting in Language Models". The idea is to have the model write a short thought before each action, then see the result of the action as an observation, in a repeating pattern:

text
Thought: what I need next
Action: a tool call
Observation: the tool result
... repeat ...
Final Answer: the answer

The paper used plain text prompts, because native tool calling APIs did not exist yet. The agent loop you built in lesson 2 is a modern descendant: the model's tool calls are the actions and the tool messages are the observations. What it usually lacks is the visible "Thought" step.

To see the original idea clearly, the code below implements ReAct the text way, with no tools parameter at all.

ReAct in text, from scratch

This file uses run_tool from lesson 4's trip_tools.py. Save it as react_agent.py:

python
# file: react_agent.py
"""ReAct in its original text form: Thought, Action, Observation, repeat."""
import json
import re

from llm import client, MODEL
from trip_tools import run_tool

PROMPT = """Answer the question using these tools:
get_weather: {"city": "<name>"}
convert_currency: {"amount": <number>, "from_currency": "<ISO>", "to_currency": "<ISO>"}
search_hotels: {"city": "<name>", "max_price_eur": <int>}

Use exactly this format, one Action per reply:
Thought: what you need to do next
Action: tool_name {"json": "arguments"}

After you see an Observation, continue with a new Thought.
When you know the answer, reply with:
Thought: I have what I need
Final Answer: the answer for the user"""

ACTION = re.compile(r"Action:\s*(\w+)\s*(\{.*\})", re.DOTALL)

def react(question: str, max_steps: int = 6) -> str:
    transcript = f"Question: {question}\n"
    for step in range(max_steps):
        reply = client.chat.completions.create(
            model=MODEL,
            messages=[{"role": "system", "content": PROMPT}, {"role": "user", "content": transcript}],
            stop=["Observation:"],  # the model must not invent the tool result
            temperature=0,
        ).choices[0].message.content.strip()
        print(reply, "\n")
        transcript += reply + "\n"
        if "Final Answer:" in reply:
            return reply.split("Final Answer:", 1)[1].strip()
        match = ACTION.search(reply)
        if not match:
            observation = 'No valid Action found. Write: Action: tool_name {"arg": "value"}'
        else:
            observation = run_tool(match.group(1), match.group(2))
        print("Observation:", observation, "\n")
        transcript += f"Observation: {observation}\n"
    return "Stopped at the step limit."

if __name__ == "__main__":
    print("ANSWER:", react("I have 300 USD. How much is that in EUR, and is it raining in Kyoto?"))

How it works:

  • The prompt teaches the format. It lists each tool with an example of its JSON arguments and shows the exact Thought, Action, Final Answer lines.
  • stop=["Observation:"] is the key trick. The stop parameter tells the server to stop generating when the model writes that text. Without it, the model would happily write its own made-up observation and continue as if the tool had run.
  • A regular expression parses the Action line into a tool name and a JSON string, which go to run_tool. If parsing fails, the observation says so and the model gets another try.
  • The transcript is one growing string, sent as the user message on each turn.

In the tested run with qwen2.5:1.5b on Ollama, for "I have 300 USD. How much is that in EUR, and is it raining in Kyoto?", the model wrote a thought, called convert_currency, got 276 EUR, wrote another thought, called get_weather for Kyoto, and finished with a final answer that included both results: 276 EUR and light rain with a 70% chance.

Text ReAct works without any tool calling support on the server, which is useful for models that do not support tools. Its weakness is parsing: if the model drifts from the format, the regex misses, and you need fallbacks. Native tool calls avoid that, which is why the rest of the course uses them.

Plan-then-execute

The alternative separates thinking from doing. One model call writes a plan. Then each step runs on its own. Then a final call writes the answer from the step results.

Save this as plan_execute.py:

python
# file: plan_execute.py
from typing import Literal

from pydantic import BaseModel, ConfigDict

from llm import client, MODEL
from trip_tools import TOOLS, run_tool


ToolName = Literal["get_weather", "convert_currency", "search_hotels"]


class Plan(BaseModel):
    model_config = ConfigDict(extra="forbid")
    steps: list[ToolName]  # the tools to use, in order. Short plans are easier for small models.


def make_plan(task: str) -> Plan:
    response = client.chat.completions.create(
        model=MODEL,
        messages=[
            {"role": "system", "content": "You plan before acting. List the tools needed for the task, "
             "in order, one tool per step, 1 to 4 steps. Tools: get_weather (forecast for a city), "
             "convert_currency (money between currencies), search_hotels (hotels in a city under a price)."},
            {"role": "user", "content": task},
        ],
        response_format={"type": "json_schema", "json_schema": {
            "name": "plan", "schema": Plan.model_json_schema(), "strict": True}},
        temperature=0,
        max_tokens=200,  # a plan is short; this stops a model that loops inside the JSON
    )
    choice = response.choices[0]
    if choice.finish_reason == "length":
        raise RuntimeError("The plan was cut off at max_tokens. Try again or use a larger model.")
    return Plan.model_validate_json(choice.message.content)


def execute_step(task: str, tool: str, notes: list[str]) -> str:
    """A small tool loop that does exactly one step, with the task and earlier results as context."""
    tools = [t for t in TOOLS if t["function"]["name"] == tool]  # only the planned tool
    messages = [
        {"role": "system", "content": "Do only the current step by calling the tool, then report the "
         "tool result in one sentence. Do not add facts that are not in the tool result."},
        {"role": "user", "content": f"Overall task: {task}\nResults so far: {notes or 'none'}\n"
                                    f"Current step: use {tool} for the part of the task it covers."},
    ]
    for _ in range(3):
        msg = client.chat.completions.create(model=MODEL, messages=messages, tools=tools, temperature=0).choices[0].message
        messages.append(msg)
        if not msg.tool_calls:
            return msg.content
        for call in msg.tool_calls:
            result = run_tool(call.function.name, call.function.arguments)
            print(f"    {call.function.name}({call.function.arguments}) -> {result[:90]}")
            messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
    return "Step did not finish."


def plan_and_execute(task: str) -> str:
    plan = make_plan(task)
    print("PLAN:", " -> ".join(plan.steps))
    notes = []
    for i, tool in enumerate(plan.steps, 1):
        print(f"STEP {i}: {tool}")
        report = execute_step(task, tool, notes)
        print("   report:", report)
        notes.append(f"Step {i} ({tool}): {report}")
    final = client.chat.completions.create(
        model=MODEL,
        messages=[{"role": "system", "content": "Answer the task using only the step results. "
                   "If a result is missing, say what is missing instead of guessing."},
                  {"role": "user", "content": f"Task: {task}\nStep results:\n" + "\n".join(notes)}],
        temperature=0,
    )
    return final.choices[0].message.content


if __name__ == "__main__":
    print("\nANSWER:", plan_and_execute(
        "I have 300 USD. Find a Lisbon hotel under 100 EUR a night and tell me if I need an umbrella there."))

The three phases:

  1. make_plan asks for a plan with the strict json_schema response format from lesson 5. The pydantic Plan class allows only the three real tool names, through Literal, so the plan cannot name a tool that does not exist. max_tokens=200 caps the reply, and a length finish reason raises a clear error.
  2. execute_step runs a small tool loop for one step. It gives the model only the tool for that step, plus the original task and the notes from earlier steps.
  3. The final call gets only the task and the step reports, with no tools, and writes the answer.

What happened when plan-then-execute was tested

This one took several attempts, and the failures are the most useful part of the lesson.

Attempt 1: rich plans. The first Plan schema had steps with a tool name and a free text instruction. The plan came back with the right three tools, but step 1 called get_weather for "London", a city the task never mentioned. The weather step's instruction did not carry the city, and the step executor guessed. Steps 2 and 3 then produced no tool calls, and the final answer named a hotel that is not in the data.

Attempt 2: instructions that repeat every detail. The system prompt asked each instruction to repeat all the details it needs. The small model then never finished the plan: it kept generating inside the JSON until the run was stopped after several minutes. Adding max_tokens turned that into a clear error, "The plan was cut off at max_tokens", instead of a hang.

Attempt 3: the version above. The plan is now just a list of tool names, and each step receives the full task text. In the tested run:

  • The plan was get_weather -> convert_currency -> search_hotels.
  • Every step called its tool with correct arguments: Lisbon weather (sunny, 10% rain), 300 USD to 276 EUR, and Casa Azul at 95 EUR.
  • The final synthesis call was the weak link. The model invented extra "steps" in its answer and said an umbrella was needed in Lisbon, despite a 10% chance of rain in the step results it was given.

So the execution phase was fully correct, and the last call still produced a wrong conclusion from correct data. The same small model made the same umbrella mistake in the single agent run in lesson 12. This is a model quality limit, not a planning bug, and it is exactly the kind of error the eval harness in lesson 14 exists to catch.

Comparing the two

ReActPlan-then-execute
When it decidesone step at a timeeverything up front
Adapts to surprisesyes, every observation can change the next steponly if you add replanning
Model callsone per step, plus the answerone plan, one or more per step, one answer
Easy to inspectthe trace shows reasoning step by stepthe plan is a clear object you can show, check or approve
Typical failurewandering or repeating stepsa bad plan, or details lost between steps

Some practical guidance:

  • Use a ReAct style loop by default. For most tasks with a handful of tools, the plain agent loop with native tool calls is simpler and adapts as it goes.
  • Use plan-then-execute when the plan itself is useful. You can show it to a user for approval before anything runs, check it in code, or run independent steps in parallel.
  • Pass context explicitly between steps. Attempt 1 failed because a step did not know the city. Every step should get what it needs, either the full task or the earlier results.
  • Cap every phase. The planning call needs max_tokens, each step needs a step limit, and the whole run needs the budgets from lesson 11.

Anthropic's "Building effective agents" describes these as points on a spectrum, from fixed workflows where code decides the steps, to agents where the model decides. A plan with a fixed tool list is closer to a workflow; ReAct is closer to an agent.

flowchart TD
    subgraph R["ReAct"]
        R1["Thought: what I need next"] --> R2["Action: one tool call"]
        R2 --> R3["Observation: the tool result"]
        R3 --> R4{"Enough to answer?"}
        R4 -->|no| R1
        R4 -->|yes| R5["Final Answer"]
    end
    subgraph P["Plan-then-execute"]
        P1["make_plan: list of tool names"] --> P2["execute_step 1"]
        P2 --> P3["execute_step 2"]
        P3 --> P4["execute_step 3"]
        P4 --> P5["Final call: task + step reports"]
    end

Diagram: ReAct decides one step at a time. Plan-then-execute writes the plan first, then runs each step.

Animation: ReAct picks each step after the last observation. Plan-then-execute writes the plan first, so it can be checked before anything runs.

Common mistakes

  • No stop sequence in text ReAct, so the model writes its own observations.
  • Plans with free text that loses details, such as a step that does not repeat the city.
  • No limit on plan length, so a small model can loop inside the JSON.
  • Trusting the final synthesis. Correct step results do not guarantee a correct answer. Test the answer, not only the steps.
  • Replanning on every step, which turns plan-then-execute into a slower ReAct.

What to try next

  • Remove stop=["Observation:"] from react_agent.py and look at what the model writes after its first action.
  • Ask the plan-then-execute agent a question that needs only one tool and check whether it plans one step.
  • Add a replanning step: if a step's report contains an error, call make_plan again with the notes so far.
  • Change the final synthesis prompt to include "Base the umbrella advice on the rain chance: below 0.3 means no umbrella" and see whether the answer improves.

Next: making sure no strategy can run away. Step limits, token and cost budgets, and retries that only retry what can actually succeed.

Sources

Try it yourselfMedium

Run a plan whose steps use earlier results

In plan-and-execute, the model writes all the steps first and your code runs them. Later steps often need earlier results.

Write execute_plan(plan, tools).

- plan is a list of steps {"tool": name, "args": dict}.
- An argument value that is a string like "$0" or "$2" means "the result of step 0" (or step 2). Replace it with that result before calling the tool. Any other value is passed as is.
- A reference to a step that has not run yet, or a tool name that does not exist, raises ValueError.

Return the list of results, one per step.

solution.py
Runs in your browser with Python and NumPy. No model or API key needed.

The worked solution unlocks after your first attempt.

Saved in this browser. Pass the quiz while signed in to count it for the certificate.

Check what you learned

Answer all 3 questions. You need at least 2 right to pass.

1. Why does the text ReAct agent pass stop=["Observation:"]?

2. In testing, where did plan-then-execute finally go wrong?

3. When is plan-then-execute especially useful?