Contents · 10 sections↓
- 01How do you build a plan-and-execute agent in Python?
- 02ReAct vs plan-and-execute: what's the difference?
- 03How the Reasoning Graph runs your agent
- 04What you need
- 05Build a plan, act, verify, reflect agent, step by step
- 06When the planner can't see the tools
- 07Check with code instead of a model
- 08Limitations
- 09Frequently asked questions
- 10Where to go next
A plan-and-execute agent writes a plan before its first tool call, works through it with tools, and checks the result before it answers. Most AI agents run the ReAct loop instead: the model thinks, calls a tool, reads the result, and repeats until it can answer. ReAct is simple and it works, but sometimes you want more shape: a plan before the first tool call, a check before the answer leaves, a moment of reflection when the check fails. This guide builds that plan-and-execute agent in Python with the Reasoning Graph in Promptise Foundry, compares it with the default ReAct agent on the same analysis task, and shows what each extra step costs. It ends with the cheapest check: a few lines of code that need no model call. Every output is real, printed by the scripts shown with gpt-5-mini.
How do you build a plan-and-execute agent in Python?
You describe each step as a node in a graph, wire the nodes together, and let an engine walk the graph. In Promptise Foundry the graph is a PromptGraph, the steps are nodes such as PlanNode, PromptNode and ValidateNode, and PromptGraphEngine runs it:
tools = agent.tools
graph = PromptGraph("plan-and-execute", mode="static")
graph.add_node(PlanNode("plan", output_schema=Plan, instructions=f"Plan the steps. Tools: {[t.name for t in tools]}"))
graph.add_node(PromptNode("act", tools=tools))
graph.add_node(ValidateNode("verify", output_schema=Verdict, on_pass="__end__", on_fail="act"))
graph.sequential("plan", "act", "verify")
graph.set_entry("plan")
engine = PromptGraphEngine(graph=graph, model=resolve_model("openai:gpt-5-mini"), max_iterations=12)
result = await engine.ainvoke({"messages": [{"role": "user", "content": "Which regions missed their Q3 target?"}]})The planner writes subgoals, the act node works through them with your MCP tools, and the verifier either ends the run on the answer or sends the work back. If you only want a self-check and no new steps, there's a one-word version: build_agent(..., agent_pattern="verify"). The rest of this guide shows both running, adds a reflect step, and compares what each one costs.
[02]
ReAct vs plan-and-execute: what's the difference?
ReAct decides one step at a time. After every tool result the model picks the next action, so it adapts to what it just saw but never commits to an overall plan. Plan-and-execute splits that work in two. A planner writes the steps first, and an executor works through them with tools. A check at the end can send the work back before the answer leaves.
ReAct | Plan-and-execute | |
|---|---|---|
When the plan is made | Never as a whole, one step at a time | Up front, before the first tool call |
Model calls on this guide's task | 2 | 4 (plan, two act rounds, verify) |
Strength | Simple and cheap, and it reacts to each result | Keeps multi-step work in order, and the plan is visible and checkable |
Weakness | Can drift or stop early on long tasks | A plan written without the tools in view misleads the executor, and every extra step costs calls and tokens |
Good fit | Lookups and short tool chains | Multi-step analysis and reports, where the order of steps matters |
Start with ReAct. Add a plan when the model skips or reorders steps on your task, and add a check when a wrong answer is expensive. The ReAct agent pattern explains the loop itself, and AI agent reasoning patterns covers the other shapes, from reflection to debate.
[03]
How the Reasoning Graph runs your agent
Every Promptise agent is a graph, even the default one. build_agent gives you a ReAct graph: one PromptNode named reason that holds the tools and loops until the model stops calling them. A custom pattern is just a bigger graph. Here's the one you'll build:
Rendering diagram…
After each node, the engine picks the next one in a fixed order. If the node called tools, it runs the same node again so the model sees the results. Otherwise it takes, in this order: a next node the node chose itself (this is how ValidateNode routes on pass or fail), a route field in the node's structured output, your edges (always, sequential, when, on_output and friends), the node's transitions, and finally its default_next. If none applies, the run ends.
Promptise ships ten reasoning nodes that come with their own instructions: PlanNode, ThinkNode, ReflectNode, ObserveNode, JustifyNode, CritiqueNode, SynthesizeNode, ValidateNode, RetryNode and FanOutNode. Next to them sit the general ones, such as PromptNode, ToolNode, RouterNode, GuardNode, ParallelNode, HumanNode and the @node decorator, which turns any async function into a step. Nodes also take typed flags from NodeFlag, for example CRITICAL to abort the run if the node fails, RETRYABLE to retry it with backoff, or SKIP_ON_ERROR to skip it after a failed step.
You don't have to build a graph to change the pattern. build_agent takes a name:
agent_pattern | What it builds |
|---|---|
"react" (default) | One tool-using node that loops until the model answers |
"verify" | The same single node, told to plan, solve and check its answer in one response |
"managed" | One node that sees a deduplicated ledger of facts instead of the full tool transcript |
"code-action" | The model writes one Python program that calls your tools in a Docker sandbox |
"peoatr" | Plan, act, think and reflect nodes, then an answer node that writes the reply |
"research" | Search, a verify step, then synthesize |
"deliberate" | Think, plan, act, observe and reflect, then an answer node that writes the reply |
"debate" | A proposer with your tools, a critic and a judge, then an answer node |
"autonomous" | One node that lets the model pick the next step from a pool |
a PromptGraph | Your own graph |
[04]
What you need
Python 3.10 or newer.
Promptise Foundry 1.10.0 or newer from PyPI. Everything here uses the base install:
pip install "promptise>=1.10.0"
export OPENAI_API_KEY="sk-..."An API key for a model provider. The examples use openai:gpt-5-mini; any model with tool calling and structured output works.
[05]
Build a plan, act, verify, reflect agent, step by step
Give the agent a small analysis job
You need a task where a shortcut gives a wrong answer, or a check has nothing to catch. This MCP server has two tools: one returns each region's quarterly target, the other returns monthly gross revenue and refunds. The targets are for net revenue, so an agent that forgets the refunds will think two regions hit their target when they didn't.
from promptise.mcp.server import MCPServer
server = MCPServer("sales")
# A stand-in for your warehouse. Amounts are in USD.
TARGETS = {"Q3": {"North": 300_000, "South": 250_000, "East": 180_000, "West": 220_000}}
REVENUE = {
("North", "Q3"): [("Jul", 104_200, 3_100), ("Aug", 98_750, 2_400), ("Sep", 101_300, 4_050)],
("South", "Q3"): [("Jul", 86_400, 1_200), ("Aug", 82_100, 950), ("Sep", 88_900, 1_650)],
("East", "Q3"): [("Jul", 55_300, 2_900), ("Aug", 61_800, 3_300), ("Sep", 58_050, 2_150)],
("West", "Q3"): [("Jul", 74_900, 1_100), ("Aug", 71_250, 2_600), ("Sep", 76_400, 1_900)],
}
@server.tool()
async def get_targets(quarter: str) -> dict:
"""Get each region's net revenue target for a quarter.
Args:
quarter: The quarter, for example "Q3".
"""
return {"quarter": quarter, "net_revenue_targets": TARGETS.get(quarter.upper(), {})}
@server.tool()
async def get_monthly_revenue(region: str, quarter: str) -> dict:
"""Get a region's gross revenue and refunds for each month of a quarter.
Args:
region: North, South, East or West.
quarter: The quarter, for example "Q3".
"""
rows = REVENUE.get((region.strip().title(), quarter.upper()))
if rows is None:
return {"error": f"No data for {region} in {quarter}."}
return {
"region": region.strip().title(),
"quarter": quarter.upper(),
"months": [{"month": m, "gross": g, "refunds": r} for m, g, r in rows],
}
if __name__ == "__main__":
server.run()Computed straight from the data, this is the answer every agent has to reach. North and West beat their target on gross revenue and miss it on net:
North gross=304,250 refunds=9,550 net=294,700 target=300,000 gap=-5,300 (-1.77%)
South gross=257,400 refunds=3,800 net=253,600 target=250,000 gap=+3,600 (+1.44%)
East gross=175,150 refunds=8,350 net=166,800 target=180,000 gap=-13,200 (-7.33%)
West gross=222,550 refunds=5,600 net=216,950 target=220,000 gap=-3,050 (-1.39%)Run it with the default ReAct loop
Start with the baseline, so you know what any extra structure has to beat. To count model calls and tokens, pass a small LangChain callback in the run's config. It sees every model call, whichever pattern runs:
from langchain_core.callbacks import BaseCallbackHandler
class Usage(BaseCallbackHandler):
"""Count model calls and tokens for one run."""
def __init__(self):
self.calls = self.input_tokens = self.output_tokens = 0
def on_llm_end(self, response, **kwargs):
self.calls += 1
usage = response.generations[0][0].message.usage_metadata or {}
self.input_tokens += usage.get("input_tokens", 0)
self.output_tokens += usage.get("output_tokens", 0)
def __str__(self):
return f"{self.calls} model calls, {self.input_tokens:,} input + {self.output_tokens:,} output tokens"import asyncio
import sys
from promptise import build_agent
from promptise.config import StdioServerSpec
from usage import Usage
QUESTION = "Which regions missed their Q3 revenue target, and by how much in dollars and percent?"
async def main():
agent = await build_agent(
model="openai:gpt-5-mini",
servers={"sales": StdioServerSpec(command=sys.executable, args=["sales_server.py"])},
instructions="You are a sales analyst. Use the sales tools for every number.",
agent_pattern="react", # the default
trace_tools=True,
)
try:
usage = Usage()
result = await agent.ainvoke(
{"messages": [{"role": "user", "content": QUESTION}]},
config={"callbacks": [usage]},
)
print(">>>", result["messages"][-1].content)
print("path:", " -> ".join(agent.last_report.nodes_visited))
print("usage:", usage)
finally:
await agent.shutdown()
asyncio.run(main())→ Invoking tool: get_targets with {'quarter': 'Q3'}
→ Invoking tool: get_monthly_revenue with {'region': 'North', 'quarter': 'Q3'}
→ Invoking tool: get_monthly_revenue with {'region': 'South', 'quarter': 'Q3'}
→ Invoking tool: get_monthly_revenue with {'region': 'East', 'quarter': 'Q3'}
→ Invoking tool: get_monthly_revenue with {'region': 'West', 'quarter': 'Q3'}
…
>>> Regions that missed the Q3 target:
- North — Target: $300,000; Net revenue: $294,700; Shortfall: $5,300 (1.77% of target)
- East — Target: $180,000; Net revenue: $166,800; Shortfall: $13,200 (7.33% of target)
- West — Target: $220,000; Net revenue: $216,950; Shortfall: $3,050 (1.39% of target)
(For reference, South hit $253,600 vs. a $250,000 target — an excess of $3,600 or +1.44%.)
path: reason -> reason
usage: 2 model calls, 953 input + 1,175 output tokensTwo model calls. In the first, the model asked for all five tool calls at once, and Promptise ran them in parallel. In the second, it wrote a correct answer, refunds and all. agent.last_report is the engine's execution report; nodes_visited is the path through the graph; for this graph, each entry is one model call. Since 1.3.0 the report's total_tokens is filled in too; the callback also splits input from output tokens.
Try the built-in verify pattern
Before you build anything, try the one-line change. With agent_pattern="verify", the same single node is told to plan, solve, and check its own work in one response:
agent_pattern="verify",>>> PLAN
- Restate the task: determine which regions missed their Q3 net revenue targets and by how much (dollars and percent).
…
VERIFY
- Re-checked each region by computing total gross minus total refunds (shown above) — results match monthly net sums.
…
FINAL ANSWER
Regions that missed their Q3 revenue target:
- North: missed by $5,300 (1.77% below target).
- East: missed by $13,200 (7.33% below target).
- West: missed by $3,050 (1.39% below target).
…
path: reason -> reason
usage: 2 model calls, 1,091 input + 2,406 output tokensSame two calls, correct again, and about twice the output tokens. Notice where the self-check lives: in the answer. Your users see the plan and the arithmetic, so this pattern suits an analyst's report better than a chat reply.
Build a plan, act, verify, reflect graph
Now the real pattern. Four nodes, each with one job:
from typing import TypedDict
from promptise.engine import PlanNode, PromptGraph, PromptNode, ReflectNode, ValidateNode
class Plan(TypedDict):
subgoals: list[str]
quality_score: int
class Verdict(TypedDict):
passes: bool
issues: list[str]
def plan_act_verify(tools, system_prompt: str = "") -> PromptGraph:
"""Plan, act with tools, verify the draft, and reflect before retrying."""
tool_list = "\n".join(f"- {t.name}: {t.description.splitlines()[0]}" for t in tools)
graph = PromptGraph("plan-act-verify", mode="static")
graph.add_node(
PlanNode(
"plan",
output_schema=Plan,
instructions=(
f"{system_prompt}\n\nPlan how to answer the question with these tools:\n{tool_list}\n\n"
"Write 4 or fewer subgoals, each one step. Never plan to ask the user for data "
"a tool can fetch. Rate the plan from 1 to 5 as quality_score."
),
)
)
graph.add_node(
PromptNode(
"act",
instructions=f"{system_prompt}\n\nWork through the plan with your tools, then write the answer.",
tools=tools,
)
)
graph.add_node(
ValidateNode(
"verify",
criteria=[
"The answer names every region that missed, with the shortfall in dollars and percent",
"Every number in the answer matches the tool results",
"Every sum, difference and percentage is recomputed and correct",
"The answer uses the same definition as the targets (net, not gross)",
],
output_schema=Verdict,
on_pass="__end__",
on_fail="reflect",
)
)
graph.add_node(ReflectNode("reflect", input_keys=["validation"]))
graph.sequential("plan", "act", "verify")
graph.always("reflect", "act")
graph.set_entry("plan")
return graphWhat each node does:
plan is a PlanNode. It asks the model for subgoals and a quality score. When the output has subgoals, the node stores them as the run's plan, and a score below its quality_threshold (3 by default) sends it round to plan again. Later nodes see the plan in their prompt.
act is an ordinary PromptNode with the MCP tools. It loops through tool calls exactly like the ReAct node, then writes a draft.
verify is a ValidateNode. It checks the draft against your criteria and returns passes and issues. Its on_pass and on_fail decide where the run goes. On a pass, __end__ ends the run with the draft as the reply.
reflect is a ReflectNode. It reads the verdict through input_keys=["validation"], validation being where ValidateNode stores its output, and writes down what went wrong before act tries again.
The edges are two lines: sequential chains plan, act and verify, and always sends reflect back to act.
Run the graph with your agent's tools
build_agent connects to your MCP servers and discovers their tools. Hand those tools to the graph, and run it with PromptGraphEngine. A small hook prints each node as it finishes, so you can watch the path:
import asyncio
import sys
from promptise import build_agent, resolve_model
from promptise.config import StdioServerSpec
from promptise.engine import PromptGraphEngine
from plan_act_verify import plan_act_verify
from usage import Usage
QUESTION = "Which regions missed their Q3 revenue target, and by how much in dollars and percent?"
INSTRUCTIONS = "You are a sales analyst. Use the sales tools for every number."
class ShowSteps:
"""Engine hook: print each node as it finishes, with its structured output."""
async def post_node(self, node, result, state):
detail = result.output if isinstance(result.output, dict) else ""
print(f"[{node.name}] {detail}")
return result
async def main():
# build_agent connects to the MCP servers and discovers their tools.
agent = await build_agent(
model="openai:gpt-5-mini",
servers={"sales": StdioServerSpec(command=sys.executable, args=["sales_server.py"])},
trace_tools=True,
)
try:
engine = PromptGraphEngine(
graph=plan_act_verify(agent.tools, INSTRUCTIONS),
model=resolve_model("openai:gpt-5-mini"),
hooks=[ShowSteps()],
max_iterations=12, # a hard cap on node runs, retries included
)
usage = Usage()
result = await engine.ainvoke(
{"messages": [{"role": "user", "content": QUESTION}]},
config={"callbacks": [usage]},
)
print(">>>", result["messages"][-1].content)
print("path:", " -> ".join(engine.last_report.nodes_visited))
print("usage:", usage)
finally:
await agent.shutdown()
asyncio.run(main())[plan] {'subgoals': ["Call get_targets to retrieve each region's Q3 net revenue target.", 'For each region, call get_monthly_revenue for each month in Q3 to get gross revenue and refunds.', "Compute each region's Q3 net revenue (sum of gross minus refunds), then compare to the Q3 target to find absolute shortfall (target - net) and percent shortfall ((shortfall/target)*100) for regions where net < target.", 'Return a list of regions that missed their Q3 target with the dollar shortfall and percent shortfall, plus totals and notes on rounding.'], 'quality_score': 5}
→ Invoking tool: get_targets with {'quarter': 'Q3'}
→ Invoking tool: get_monthly_revenue with {'region': 'North', 'quarter': 'Q3'}
→ Invoking tool: get_monthly_revenue with {'region': 'South', 'quarter': 'Q3'}
→ Invoking tool: get_monthly_revenue with {'region': 'East', 'quarter': 'Q3'}
→ Invoking tool: get_monthly_revenue with {'region': 'West', 'quarter': 'Q3'}
✔ Tool result from get_targets: {"quarter": "Q3", "net_revenue_targets": {"North": 300000, "South": 250000, "East": 180000, "West": 220000}}
…
[act]
[act]
[verify] {'passes': True, 'issues': []}
>>> Regions that missed their Q3 net revenue targets
1) North
- Target: $300,000
- Q3 net revenue: $294,700 (Jul–Sep gross minus refunds)
- Shortfall: $5,300 (1.77%)
2) East
- Target: $180,000
- Q3 net revenue: $166,800
- Shortfall: $13,200 (7.33%)
3) West
- Target: $220,000
- Q3 net revenue: $216,950
- Shortfall: $3,050 (1.39%)
…
path: plan -> act -> act -> verify
usage: 4 model calls, 2,898 input + 3,343 output tokensRead the path: one call to plan, two rounds of act (all five tool calls at once, then the answer), and one call to verify. The verifier passed the draft on the first try, so __end__ ended the run with the act step's answer as the reply, and reflect never ran. The answer is right.
Compare the patterns on the same question
Put the patterns side by side. The fourth row, act followed by a check written in code, comes later in this guide. The numbers are from the runs shown in this guide, one run each, counted by the Usage callback above:
Pattern | Path | Model calls | Input tokens | Output tokens |
|---|---|---|---|---|
react | reason -> reason | 2 | 953 | 1,175 |
verify | reason -> reason | 2 | 1,091 | 2,406 |
plan, act, verify | plan -> act -> act -> verify | 4 | 2,898 | 3,343 |
act, then a code check | act -> act -> check | 2 | 953 | 1,538 |
All four answered correctly. The plan, act, verify graph paid for its structure: four model calls where ReAct made two, and about three times the tokens. verify cost about 1.6 times as much as ReAct, most of it in a longer answer. The code check added a step but no model call.
The value of a step is the mistakes it catches, and a single run can't show that. Before you switch patterns, run your own task several times with each one and compare how often each gets it right, as how to evaluate AI agents shows.
[06]
When the planner can't see the tools
The first version of this graph used PlanNode with its built-in instructions, which don't mention your tools, three criteria without the one that demands every missed region, and max_iterations=3 on verify. Its plans started by getting hold of "the Q3 revenue dataset" as a CSV, a spreadsheet or a pasted table, as if the agent had no tools:
[plan] {'subgoals': ['Obtain the Q3 revenue dataset with columns: Region, Actual_Q3_Revenue (USD), Q3_Target_Revenue (USD) for all regions (deliver as CSV, spreadsheet, or pasted table).', …
→ Invoking tool: get_targets with {'quarter': 'Q3'}
→ Invoking tool: get_monthly_revenue with {'region': 'North', 'quarter': 'Q3'}
→ Invoking tool: get_monthly_revenue with {'region': 'South', 'quarter': 'Q3'}
→ Invoking tool: get_monthly_revenue with {'region': 'East', 'quarter': 'Q3'}
→ Invoking tool: get_monthly_revenue with {'region': 'West', 'quarter': 'Q3'}
…
[act]
[act]
[verify] {'passes': True, 'issues': ['Formatting: The missed-target CSV includes commas inside numeric fields …
>>> I pulled Q3 targets and monthly revenue with the tools, computed net Q3 revenue per region, then calculated dollar and percent shortfalls. Results below.
…
Region,Dollar_Shortfall (USD),Percent_Shortfall (%)
North,-5,300.00,-1.77%
East,-13,200.00,-7.33%
West,-3,050.00,-1.39%
…
Format confirmation: I delivered both the full Q3 dataset and the filtered missed-target table as CSV (pasted above). All numbers were computed from the tool outputs. Would you like these exported as an actual CSV file or spreadsheet?
path: plan -> act -> act -> verify
usage: 4 model calls, 3,013 input + 5,236 output tokensThe act node skipped that step, fetched the data with its tools, and the verifier passed the answer on the first try. The plan still shaped the reply: two CSV tables and an offer to export a file. Fetching the data was the model being sensible, not the graph: the plan told the agent to find data it could already fetch, and nothing in this version stops an act step from doing what the plan says.
Three lessons from that version are in the final graph:
Tell the planner what the tools are. A plan written blind is a guess. The fixed PlanNode gets the tool list and one rule: never plan to ask for data a tool can fetch.
Make "there is an answer" a criterion. An LLM verifier judges what's in front of it, and a draft with no numbers gives the number checks nothing to check. The first criterion now demands every missed region with both numbers.
Cap the loop. The first version passed max_iterations=3 to the verify node, so a verifier that never passes can send the draft back only three times. Without it, a node's default of 10 applies, and behind that the engine's own caps: max_iterations (all node runs, 50 by default) and, when you set it, max_node_iterations (runs of any one node, no limit by default). Keep them as a backstop, and decide what reaching one should do, as the next section shows.
What happens when a node reaches its limit
To see a cap at work, give the verifier a criterion no answer can meet. cap_demo.py builds the Step 4 graph, swaps its verify node for one that also wants the whole answer in under five words, and caps it at three runs:
graph = plan_act_verify(agent.tools, INSTRUCTIONS)
# Swap in a verifier that no answer can satisfy, capped at three runs.
graph.add_node(
ValidateNode(
"verify",
criteria=[
"The answer names every region that missed, with the shortfall in dollars and percent",
"The whole answer is shorter than five words",
],
output_schema=Verdict,
on_pass="__end__",
on_fail="reflect",
max_iterations=3,
)
)Replacing existing node 'verify' in graph 'plan-act-verify'
[plan] {'subgoals': ["Call get_targets to retrieve each region's Q3 net revenue target.", 'For each region, call get_mon …
[act]
[act]
[verify] {'passes': False, 'issues': ['Failed length constraint: response must be shorter than five words but the assist …
[reflect] {'progress': 'Computed Q3 net revenues and identified North, East, and West as missing targets with shortfalls …
[act]
[verify] {'passes': False, 'issues': ["Response includes all named regions and shortfalls, but violates the requirement …
[reflect] {'progress': 'Computed Q3 net revenues and identified North, East, and West missed targets with dollar and per …
[act]
[verify] {'passes': False, 'issues': ['Violated length constraint: reply is much longer than five words.', 'Suggestion: …
[reflect] {'progress': 'Computed Q3 net revenues and identified North, East, and West missed targets with dollar and per …
[act]
Node 'verify' reached its iteration limit (3) in graph 'plan-act-verify'; not running it again
Stuck node 'verify': forcing graph end
>>> Regions that missed their Q3 net revenue targets:
- North — Net $294,700 vs target $300,000: shortfall $5,300 (1.77%)
- East — Net $166,800 vs target $180,000: shortfall $13,200 (7.33%)
- West — Net $216,950 vs target $220,000: shortfall $3,050 (1.39%)
path: plan -> act -> act -> verify -> reflect -> act -> verify -> reflect -> act -> verify -> reflect -> act
usage: 12 model calls, 17,483 input + 13,258 output tokensThe verifier rejected three drafts. When the graph came back to it a fourth time, the engine logged Node 'verify' reached its iteration limit (3) and Stuck node 'verify': forcing graph end, and ainvoke returned normally: the answer is the fourth draft, which no verifier saw. It happens to be right here, but nothing checked it. That's the rule since 1.3.2: a limit reached after the model has answered ends the run normally, and only a limit that stops a tool loop before the model saw the results raises an error, as the next example shows.
If an unchecked draft shouldn't go out, route the node's "error" transition. The engine follows it once the node has used its runs, so you decide what happens instead of the run simply ending. In cap_demo_route.py, a give_up node writes the reply:
@node("give_up")
async def give_up(state):
"""Where the run goes when verify has used its runs: say so instead of sending the last draft."""
state.messages.append(AIMessage("I couldn't verify this answer, so I'm not sending it. A person should check the numbers."))
return NodeResult(node_name="give_up", next_node="__end__")
on_fail="reflect",
max_iterations=3,
transitions={"error": "give_up"}, # where to go once verify has used its 3 runs
)
)
graph.add_node(give_up)In a run with it, verify again rejected three drafts, the path ended … -> act -> give_up, and the reply was the give_up message, not an unchecked draft.
A cap that cuts into a tool loop has no draft to fall back on. limit_demo.py is run_custom.py with the engine's max_iterations set far too low and a try around ainvoke:
engine = PromptGraphEngine(
graph=plan_act_verify(agent.tools, INSTRUCTIONS),
model=resolve_model("openai:gpt-5-mini"),
hooks=[ShowSteps()],
max_iterations=2, # far too low, to hit the cap on purpose
)
try:
result = await engine.ainvoke({"messages": [{"role": "user", "content": QUESTION}]})
print(">>>", result["messages"][-1].content)
except GraphIterationLimitError as exc:
# The cap stopped a tool loop before the model saw the results: there is no answer.
print(f"no answer: {exc.node_name!r} stopped at limit {exc.limit}, waiting on {exc.pending_tools}")[plan] {'subgoals': ["Call get_targets to retrieve each region's Q3 net revenue target.", 'For each region, call get_mon …
→ Invoking tool: get_targets with {'quarter': 'Q3'}
✔ Tool result from get_targets: {"quarter": "Q3", "net_revenue_targets": {"North": 300000, "South": 250000, "East": 180000, "West": 220000}}
[act]
Max iterations (2) reached in graph 'plan-act-verify'
Graph 'plan-act-verify' at node 'act': the run reached the engine's max_iterations (2) before the model gave an answer; the run stopped after a call to get_targets whose result the model never saw
no answer: 'act' stopped at limit 2, waiting on ['get_targets']
path: plan -> actPlan used one of the two node runs and act the other, so the cap stopped the run right after act's first round had called get_targets. The model never saw the result, and there was no answer to return. ainvoke raised GraphIterationLimitError from promptise.engine, a GraphExecutionError that carries the node, the limit and the pending_tools whose results the model never saw. Before 1.3.2 such a run returned the last tool result as if it were the answer.
[07]
Check with code instead of a model
A model checking a model is the expensive way to verify. When the answer can be computed, check it with code: it's free, it's fast, and it can't be talked into passing. The @node decorator turns an async function into a graph step. This one recomputes every shortfall from the raw tool results the engine keeps in state.observations, and sends the agent back with the right numbers if the draft is missing any:
import json
from langchain_core.messages import HumanMessage
from promptise.engine import NodeResult, PromptGraph, PromptNode, node
@node("check")
async def check(state):
"""Recompute every shortfall from the raw tool results and compare it with the draft."""
targets, net = {}, {}
for obs in state.observations:
data = json.loads(obs["result"])
if obs["tool"] == "get_targets":
targets = data["net_revenue_targets"]
elif obs["tool"] == "get_monthly_revenue":
net[data["region"]] = sum(m["gross"] - m["refunds"] for m in data["months"])
draft = state.messages[-1].content.replace(",", "")
wrong = [
f"{region} missed by ${targets[region] - value:,}"
for region, value in net.items()
if value < targets[region] and str(targets[region] - value) not in draft
]
if not wrong:
return NodeResult(node_name="check", next_node="__end__")
state.messages.append(HumanMessage(f"Check failed. The answer must state: {'; '.join(wrong)}. Fix it."))
return NodeResult(node_name="check", next_node="act", output={"wrong": wrong})
def act_then_check(tools, system_prompt: str = "") -> PromptGraph:
"""A ReAct node whose answer is checked by code before it leaves the graph."""
graph = PromptGraph("act-check", mode="static")
graph.add_node(PromptNode("act", instructions=system_prompt, tools=tools, default_next="check"))
graph.add_node(check)
graph.set_entry("act")
return graphRun it like the graph in Step 5, and the path is the ReAct path plus one step that costs nothing:
path: act -> act -> check
usage: 2 model calls, 953 input + 1,538 output tokensThe model got it right here, so to see the failure branch, feed the check a draft that made the classic mistake, using gross revenue instead of net:
next node: act
message added: Check failed. The answer must state: North missed by $5,300; East missed by $13,200; West missed by $3,050. Fix it.The agent goes back to act with the exact numbers it has to explain. A check like this is specific to your task, and that's the point: you know what a correct answer looks like better than a second model does.
[08]
Limitations
The Reasoning Graph is flexible. Plan around these:
A
PromptNodestops after 10 model calls by default. Since 1.3.0 a node's own max_iterations (10 unless you set it, tool-loop rounds included) is enforced. Raise it per node, for example PromptNode("act", ..., max_iterations=25), where a deep tool loop is expected.A cap ends the run, and only sometimes with an error. When a node uses its runs after the model has answered, the run ends normally with the last draft, checked or not. When a cap stops a tool loop before the model saw the results, ainvoke raises GraphIterationLimitError (since 1.3.2). Route the node's "error" transition, or catch the error, wherever a cap can be reached.
Structured outputs are dicts. A pydantic output_schema result arrives as model_dump() in result.output and state.context. Read keys, or re-validate with Verdict.model_validate(...).
The verdict isn't in the reply. Since 1.10.0, a ValidateNode that ends the run leaves the answer it checked as messages[-1]. The verdict is in state.context["validation"] (the node's output_key), where a hook or a later node reads it; ShowSteps prints it from result.output. Before 1.10.0 the verdict's JSON was the last message, so the reply needed a plain step between verify and the end.
Nodes that answer in plain text give nothing to route on. Give a node an output_schema when its answer should decide where the run goes.
Unknown pattern names raise. agent_pattern="plan-act-verify" raises ValueError: Unknown agent_pattern 'plan-act-verify'. Use one of 'react', 'managed', 'code-action', 'verify', 'peoatr', 'research', 'autonomous', 'deliberate', 'debate', or pass a PromptGraph. For a pipeline, pass PromptGraph.pipeline(node_a, node_b); the string "pipeline" raises a ValueError that says so.
A saved graph needs its references to load. Since 1.3.0, save_graph keeps every node setting, but schemas are saved as "module:QualName" references and tools as names. load_graph(path, tools=agent.tools, refs=[Plan, Verdict]) loaded this guide's graph with its routing intact; without refs it raised GraphSerializationError. Lambdas and other objects that can't be written down make save_graph raise.
[09]
Frequently asked questions
Is plan and execute better than ReAct?
Not by default. On this guide's task, ReAct answered correctly with two model calls, and the plan, act, verify graph answered correctly with four, for about three times the tokens. Planning helps when the order of steps matters and the model gets it wrong without guidance, and a planner that can't see what the agent can do writes plans the agent shouldn't follow. Measure on your own task before you switch.
What is a ReAct agent?
An agent that alternates reasoning and acting: the model decides on a tool call, sees the result, and repeats until it can answer. The pattern comes from the 2022 paper ReAct: Synergizing Reasoning and Acting in Language Models. It's what build_agent gives you unless you choose otherwise.
What is a reflection agent?
An agent that reviews its own work and tries again with what it learned. Here, ReflectNode reads the verifier's issues and writes down the mistake and a correction before the act step runs again. Reflection only helps if something real triggers it, so pair it with a verifier that can actually fail, ideally one written in code.
Is the Promptise Reasoning Graph a LangGraph alternative?
It covers the same ground: an agent as a graph of steps with conditional edges and loops. The difference is what a node is. A Promptise node is a whole reasoning step with its own instructions, tools, output schema and routing, and ten of them come ready-made. Promptise builds on LangChain's model and tool interfaces, so LangChain tools and callbacks, like the Usage counter here, work unchanged.
Can I use a different model for some nodes?
Yes. Every PromptNode accepts model_override, and so do the reasoning nodes built on it, such as PlanNode and ValidateNode. It takes either a model object or a string such as "openai:gpt-5-mini". A common split is a small, fast model for planning and checking and a stronger one for the act step.
[10]
Where to go next
Reasoning Graph: the engine, its two modes, and every building block.
Nodes and Node Flags: parameters for every node type and what each flag does.
Prebuilt Patterns and Reasoning Patterns: the built-in graphs and when to pick one.
Building Custom Reasoning: more graph shapes, from pipelines to parallel research.
Edges & Transitions and Hooks: conditional routing, budgets and per-node metrics.
How to Connect MCP Servers to Your AI Agent in Python: where the tools in this guide come from.
Who Decides When an AI Agent Is Done?: success checks in code, LLM judges and budgets as a backstop.
Self-Improving AI Agent: reflection that carries over from one run to the next.