About this notebook
Companion to Module 7: Planning and reflection. Every cell below was executed with the offline backend, so you can reproduce these outputs exactly with no API key. Download the notebook (.ipynb)
A ReAct agent decides one step at a time from what it can see. That is fine for short tasks. On a task with several parts, or one where a tool fails along the way, it tends to lose parts, repeat a failing call or answer too early. This notebook gives the same task to four agents, which differ only in two extra tools. Neither tool does any work in the world. Each one adds text to the context:
- the task: a question with three parts, a currency conversion and a tool that fails;
- ReAct alone: one search for three things, then a retry of the failing tool;
- a plan tool: a to-do list the model writes and sees again on every step;
- a reflection tool: an assessment the model writes, plus facts the harness adds, which leads to a new plan;
- the four combinations compared, in steps and tokens;
- what reflection cannot do on its own.
Which model answers here?
With no
MODELset, the offline policy model answers, with rules written for this task. Without a plan tool it searches once and works with what comes back. Given a failing tool, it retries once and then gives up. It useswrite_todosandreflectin the way the tool descriptions ask. A live model shows these failure modes some of the time, and its plans and reflections can be wrong in ways these rules never are. The rules act each failure out on purpose, so that the effect of each tool can be seen on its own. The tools, and what the harness does with their output, are the same with any model.
from agentlab.nbsetup import setup
nb = setup("07_planning_reflection", packs=["planning"])
llm = nb.llmLLM backend
offline policy model (deterministic, rule-based, no API key used)
1. The task
The tools are the handbook search from Notebook 5b, the calculator, and a market exchange rate service that is down. That last one is a stand-in for any external API on a bad day. Its error message even says “try again later”:
from agentlab import Agent, tool
from agentlab.rag import Retriever, chunk_corpus, load_handbook, make_retrieval_tool
from agentlab.tools import calculator_tool
retriever = Retriever(chunk_corpus(load_handbook(), "structure", max_chars=600))
search_handbook = make_retrieval_tool(retriever, name="search_handbook", k=3)
class ServiceUnavailable(Exception):
"""What a rate API raises when it is down."""
@tool
def get_exchange_rate(currency: str) -> str:
"""Get today's market exchange rate, in units of `currency` per 1 US dollar.
Args:
currency: Three-letter currency code, for example "NOK".
"""
raise ServiceUnavailable("the rate service is not responding (HTTP 503); "
"try again later")
TASK = ("I am going to Oslo for three nights. What is the most I can claim, in US dollars, "
"for lodging, the meal per diem and the airport train both ways?")Here is the answer key, worked out by hand from four handbook pages. The lodging cap is
NOK 1,800 a night (travel-lodging). The per diem is NOK 750 for each night away
(travel-per-diem). The Airport Express costs NOK 230 each way
(travel-ground-transport). Reports use the fixed quarterly rate of 10.50 NOK per US
dollar (travel-currency). That page also says not to use live market rates, so the rate
service was the wrong source even when it worked.
answer_key = (3 * 1800 + 3 * 750 + 2 * 230) / 10.50
print(f"answer key: USD {answer_key:,.2f}")answer key: USD 772.38
Every agent in this notebook gets the same instructions, model, step limit and three base
tools. run_config adds the extra tools, runs the task, and records what happened.
show_steps prints one line per step: the tool calls the model made together, and
whether each one worked.
from agentlab.memory import count_tokens
from agentlab.types import Message, ToolCall, ToolResult
INSTRUCTIONS = "You are a travel expense assistant for the company handbook."
BASE_TOOLS = [search_handbook, get_exchange_rate, calculator_tool]
async def run_config(extra_tools):
agent = Agent(model=llm, tools=BASE_TOOLS + extra_tools, instructions=INSTRUCTIONS,
max_steps=16)
first = len(llm.calls)
result = await agent.run(TASK)
result.requests = [request for request, _ in llm.calls[first:]]
return result
def describe(call: ToolCall) -> str:
a = call.arguments
if call.name == "write_todos":
done = sum(t["status"] == "completed" for t in a["todos"])
return f"write_todos({done} of {len(a['todos'])} done)"
if call.name == "reflect":
return f"reflect(need_replan={a.get('need_replan', False)})"
value = next(iter(a.values()), "")
value = value if len(value) <= 40 else value[:37] + "..."
return f'{call.name}("{value}")'
def steps_of(result) -> list[list[tuple[str, str]]]:
"""For each step: (tool name or 'answer', 'ok' / 'error')."""
status = {x.tool_call_id: x.status for e in result.context.events for x in e.content
if isinstance(x, ToolResult)}
steps = []
for event in result.context.events:
calls = [x for x in event.content if isinstance(x, ToolCall)]
if calls:
steps.append([(c.name, "ok" if status.get(c.tool_call_id) == "success"
else "error", describe(c)) for c in calls])
elif event.author != "user" and any(isinstance(x, Message) for x in event.content):
steps.append([("answer", "ok", "answer")])
return steps
def show_steps(result) -> None:
for i, step in enumerate(steps_of(result), 1):
line = " + ".join(d + (" -> ERROR" if s == "error" else "") for _, s, d in step)
print(f"{i:>3} {line}")2. ReAct on its own
The first agent has only the three base tools:
react = await run_config([])
show_steps(react)
print()
print(react.output) 1 search_handbook("I am going to Oslo for three nights. ...")
2 get_exchange_rate("NOK") -> ERROR
3 get_exchange_rate("NOK") -> ERROR
4 answer
I could not get an exchange rate: get_exchange_rate failed 2 times (ServiceUnavailable: the rate service is not responding (HTTP 503); try again later). Here is what I found, in NOK:
- per diem: 3 days x NOK 750 = NOK 2,250 [travel-per-diem]
- airport train: 2 rides x NOK 230 = NOK 460 [travel-ground-transport]
Total: NOK 2,710.
Two things went wrong, and the answer hides both. First, the agent searched once, with the whole question. The search returned three passages, none of them the lodging page:
first_search = react.context.events[2].content[0]
print([line for line in first_search.content[0].splitlines() if "] source:" in line])['[1] source: travel-per-diem', '[2] source: travel-per-diem', '[3] source: travel-ground-transport']
The answer lists the per diem and the train and leaves lodging out without saying so. It reads like a complete answer, even though most of the money is missing. Second, the rate service failed and the agent tried the same call again. “Try again later” invites that, and a few seconds later is not later. After two failures it gave up and answered in the wrong currency.
The book lists the failure modes of ReAct on long tasks: losing direction by doing too much at once, answering with partial information, forgetting what it already found, and repeating a failed action instead of looking for another way. This run shows the first, second and fourth. All of them have the same cause. At every step the agent asks only “what should I do next?” It never asks what the whole task needs, or whether the work so far is on track.
3. A plan the model writes
PlanningTool adds a tool called write_todos. Its argument is the whole plan, a list of
steps, each with a status. The tool does two things. It stores the plan in
context.state, and on every later step it adds the current plan to the instructions
through process_llm_request. So the plan is always in view, even when the call that
wrote it has scrolled out of the context or been compacted away (Notebook 6a). Its
description tells the model when not to use it, because a plan for a one-step question
only costs tokens:
from agentlab.planning import PLAN_HEADER, PlanningTool, ReflectionTool
print(PlanningTool().description)Create or update your task plan. WHEN TO USE: tasks with several parts or several steps of research, where it is easy to lose track of what is left. WHEN NOT TO USE: a question one tool call can answer. HOW TO USE: send the whole list every time. Mark finished steps 'completed', the step you are starting 'in_progress', the rest 'pending'. Change the steps when you learn that the plan does not work.
planned = await run_config([PlanningTool()])
show_steps(planned)
print()
print(planned.output) 1 write_todos(0 of 5 done) + search_handbook("Oslo lodging cap per night")
2 write_todos(2 of 5 done) + search_handbook("Oslo airport train fare")
3 write_todos(3 of 5 done) + get_exchange_rate("NOK") -> ERROR
4 get_exchange_rate("NOK") -> ERROR
5 answer
I could not get an exchange rate: get_exchange_rate failed 2 times (ServiceUnavailable: the rate service is not responding (HTTP 503); try again later). Here is what I found, in NOK:
- lodging: 3 nights x NOK 1,800 = NOK 5,400 [travel-lodging]
- per diem: 3 days x NOK 750 = NOK 2,250 [travel-per-diem]
- airport train: 2 rides x NOK 230 = NOK 460 [travel-ground-transport]
Total: NOK 8,110.
The plan has one step for each part of the question, so the agent searched for each part separately. The lodging search also returned the per diem table, so that step was ticked off without a search of its own. Here is what the model saw at the start of step 4, after the base instructions:
step4 = planned.requests[3]
print(next(text for text in step4.instructions if text.startswith(PLAN_HEADER)))Your current plan (keep it up to date with write_todos): [x] Find the Oslo lodging cap per night [x] Find the Oslo meal per diem [x] Find the Oslo airport train fare [>] Get the exchange rate to US dollars with get_exchange_rate [ ] Add everything up and convert to US dollars with the calculator
All three amounts are found, so the plan fixed the partial answer. It did nothing for the failing tool. The agent retried, gave up and answered in NOK. A plan says what to do. It does not notice that one way of doing it has stopped working.
4. Reflection: checking, then changing the plan
ReflectionTool adds reflect(analysis, need_replan). The model writes its own
assessment of where it stands, which becomes part of the context for the next step. As in
the book, the description lists the moments to use it: after a tool fails, when combining
results, and before the final answer.
print(ReflectionTool().description)Pause and assess progress before continuing. WHEN TO USE: after a tool fails or returns something unexpected; when results from different sources must be combined; before giving the final answer, to check that every part of the task is done. WHEN NOT TO USE: after every routine step.
Planning and reflection form a loop. The plan says what to do next. After acting, the agent reflects. If things are on track it moves to the next step. If not, it changes the plan:
+--------------+ +---------------------+ +----------------------+
----> | write_todos | ---> | act: search, call, | ---> | reflect: on track? |
| (the plan) | | compute | | (+ facts on record) |
+--------------+ +---------------------+ +----------------------+
^ ^ | |
| +------ yes: next step -+ |
+----------------------------- no: need_replan=True -------------+both = await run_config([PlanningTool(), ReflectionTool()])
show_steps(both)
print()
print(both.output) 1 write_todos(0 of 5 done) + search_handbook("Oslo lodging cap per night")
2 write_todos(2 of 5 done) + search_handbook("Oslo airport train fare")
3 write_todos(3 of 5 done) + get_exchange_rate("NOK") -> ERROR
4 reflect(need_replan=True)
5 write_todos(3 of 5 done) + search_handbook("exchange rate Norwegian krone US dollar")
6 write_todos(4 of 5 done) + calculator("(3 * 1800 + 3 * 750 + 2 * 230) / 10.5")
7 write_todos(5 of 5 done) + reflect(need_replan=False)
8 answer
You can claim at most USD 772.38 for this trip:
- lodging: 3 nights x NOK 1,800 = NOK 5,400 [travel-lodging]
- per diem: 3 days x NOK 750 = NOK 2,250 [travel-per-diem]
- airport train: 2 rides x NOK 230 = NOK 460 [travel-ground-transport]
Total NOK 8,110, converted at 10.50 NOK per US dollar [travel-currency]. The handbook says to use this table, not a live market rate.
After the first failure the agent reflected instead of retrying, and asked for a new plan.
The next write_todos replaced the rate step. Here are the plan versions before and after
that change:
versions = both.context.state["plan_versions"]
changed = next(i for i in range(1, len(versions))
if versions[i].splitlines()[3][4:] != versions[i - 1].splitlines()[3][4:])
print(f"version {changed}:\n{versions[changed - 1]}\n")
print(f"version {changed + 1}:\n{versions[changed]}")version 3: [x] Find the Oslo lodging cap per night [x] Find the Oslo meal per diem [x] Find the Oslo airport train fare [>] Get the exchange rate to US dollars with get_exchange_rate [ ] Add everything up and convert to US dollars with the calculator version 4: [x] Find the Oslo lodging cap per night [x] Find the Oslo meal per diem [x] Find the Oslo airport train fare [>] Find the exchange rate to US dollars in the handbook [ ] Add everything up and convert to US dollars with the calculator
The reflection tool does more than store the model’s text. Its result adds what the harness knows for certain: how far the plan has got, and which tools have failed since the last reflection. Here are both reflections, the model’s analysis and then what the tool returned:
from agentlab.display import wrap
calls = {x.tool_call_id: x for e in both.context.events for x in e.content
if isinstance(x, ToolCall)}
for event in both.context.events:
for x in event.content:
if isinstance(x, ToolResult) and x.name == "reflect":
print(wrap("model: " + calls[x.tool_call_id].arguments["analysis"], 90))
print(wrap("tool: " + x.content[0], 90))
print()model: get_exchange_rate failed (ServiceUnavailable: the rate service is not responding (HTTP...), so calling it again now will probably fail too. The amounts are in NOK and the answer must be in US dollars. The handbook may publish the rate to use for expenses: replace this step with a handbook search. tool: Reflection recorded (REPLAN NEEDED). Plan: 3 of 5 steps completed. Not done: Get the exchange rate to US dollars with get_exchange_rate; Add everything up and convert to US dollars with the calculator. Tool error since the last reflection: get_exchange_rate: ServiceUnavailable: the rate service is not responding (HTTP 503); try again later model: Self-check against the question: lodging, per diem, airport train are all included, the rate 10.5 comes from travel-currency, and the total is USD 772.38. Every part of the question is answered. tool: Reflection recorded. Plan: 5 of 5 steps completed. Every step is done.
The second reflection is the self-check before answering. Here it found nothing wrong. To see one that does, run the fourth combination: reflection without a plan.
5. The four combinations
reflect_only searches once, like ReAct, and finds the same two parts. Its self-check
compares the result with the question, finds no amount for lodging, and goes back for
it:
reflect_only = await run_config([ReflectionTool()])
show_steps(reflect_only) 1 search_handbook("I am going to Oslo for three nights. ...")
2 get_exchange_rate("NOK") -> ERROR
3 reflect(need_replan=True)
4 search_handbook("exchange rate Norwegian krone US dollar")
5 calculator("(3 * 750 + 2 * 230) / 10.5")
6 reflect(need_replan=False)
7 search_handbook("Oslo lodging cap per night")
8 calculator("(3 * 1800 + 3 * 750 + 2 * 230) / 10.5")
9 reflect(need_replan=False)
10 answer
Now the four runs side by side. “Parts” counts the parts of the question with an amount in
the answer. “Tokens” is the estimated input over all steps, because every step re-sends
the growing context. The last two columns split out what the plan costs: the plan
re-shown in the instructions, and the write_todos calls and results that stay in the
history and are re-sent with it.
import json
import re
from agentlab.llm.pricing import estimate_tokens
runs = {"ReAct": react, "plan": planned, "reflect": reflect_only, "plan + reflect": both}
def parts_in(answer: str) -> int:
return sum(f"- {p}:" in answer for p in ("lodging", "per diem", "airport train"))
rows = {}
for name, result in runs.items():
steps = steps_of(result)
usd = re.search(r"USD ([\d,.]+\d)", result.output or "")
rows[name] = {
"steps": len(steps),
"calls": sum(len(s) for s in steps if s[0][0] != "answer"),
"failed": sum(st == "error" for s in steps for _, st, _ in s),
"parts": parts_in(result.output or ""),
"answer": f"USD {usd.group(1)}" if usd else "NOK only",
"tokens": sum(count_tokens(r) for r in result.requests),
"shown": sum(estimate_tokens(t) for r in result.requests for t in r.instructions
if t.startswith(PLAN_HEADER)),
"history": sum(estimate_tokens(json.dumps(x.arguments)) if isinstance(x, ToolCall)
else estimate_tokens(x.content[0])
for r in result.requests for x in r.contents
if isinstance(x, (ToolCall, ToolResult))
and x.name == "write_todos"),
}
print(f"{'agent':15s}{'steps':>6}{'calls':>6}{'failed':>7}{'parts':>6}{'answer':>12}"
f"{'tokens':>8}{'plan shown':>11}{'plan hist':>10}")
for name, r in rows.items():
print(f"{name:15s}{r['steps']:6d}{r['calls']:6d}{r['failed']:7d}{r['parts']:4d}/3"
f"{r['answer']:>12}{r['tokens']:8,}{r['shown']:11,}{r['history']:10,}")
print(f"\nanswer key: USD {answer_key:,.2f}")
a, b = rows["plan + reflect"], rows["reflect"]
print(f"plan + reflect against reflect: {a['steps'] - b['steps']:+d} steps, "
f"{a['tokens'] - b['tokens']:+,} tokens, of which the plan: "
f"{a['shown'] + a['history']:,}")agent steps calls failed parts answer tokens plan shown plan hist ReAct 4 3 2 2/3 NOK only 2,716 0 0 plan 5 7 2 3/3 NOK only 7,627 296 1,555 reflect 10 9 1 3/3 USD 772.38 14,177 0 0 plan + reflect 8 13 1 3/3 USD 772.38 18,312 515 4,134 answer key: USD 772.38 plan + reflect against reflect: -2 steps, +4,135 tokens, of which the plan: 4,649
Each tool fixes a different failure:
- The plan fixed the missing part, in advance, by turning the question into a checklist. It did nothing for the broken tool.
- Reflection fixed the broken tool. It also caught the missing part, but only after the fact: the reflect-only agent computed a wrong total first, then searched and computed again, so it took the most steps.
- Neither is free. Each reflection is a step of its own: a full model call that
re-sends the whole context. The plan costs more than it looks. Showing it in the
instructions is cheap. Most of its cost is the
write_todoscalls and their results. Each one carries the whole list, stays in the history, and is re-sent on every later step. So “plan + reflect” takes fewer steps than “reflect” but sends more tokens, and the plan accounts for the difference.
The figure shows the same runs step by step.
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.patches import Patch
BLUE, RUST, GREEN, GREY = "#2c5f9e", "#b5523b", "#2c7d54", "#81796f"
style = {"search_handbook": {"color": BLUE}, "get_exchange_rate": {"color": RUST},
"reflect": {"color": GREEN}, "calculator": {"color": GREY},
"answer": {"color": "white", "edgecolor": GREY, "hatch": "////"}}
labels = {"search_handbook": "search", "get_exchange_rate": "rate service (fails)",
"reflect": "reflect", "calculator": "calculator", "answer": "answer"}
fig, ax = plt.subplots(figsize=(6.4, 3.4))
for row, (name, result) in enumerate(reversed(list(runs.items()))):
for x, step in enumerate(steps_of(result), 1):
main = next((n for n, _, _ in step if n != "write_todos"), "write_todos")
ax.bar(x, 0.6, bottom=row - 0.3, width=0.85, linewidth=1, **style[main])
if any(n == "write_todos" for n, _, _ in step):
ax.plot(x, row + 0.42, "o", color="#333333", markersize=3.5)
last = len(steps_of(result))
ax.text(last + 0.7, row, rows[name]["answer"], va="center", fontsize=9,
color=GREEN if rows[name]["answer"] == f"USD {answer_key:,.2f}" else RUST)
ax.set_yticks(range(len(runs)), list(reversed(list(runs))))
ax.set_xticks(range(1, max(r["steps"] for r in rows.values()) + 1))
ax.set_xlim(0.4, 13.4)
ax.set_ylim(-0.6, len(runs) - 0.35)
ax.set_xlabel("step")
ax.spines[["top", "right", "left"]].set_visible(False)
ax.tick_params(axis="y", length=0)
handles = [Patch(facecolor=s["color"], edgecolor=s.get("edgecolor", s["color"]),
hatch=s.get("hatch"), label=labels[k]) for k, s in style.items()]
handles.append(Line2D([], [], marker="o", color="#333333", linestyle="", markersize=3.5,
label="plan rewritten"))
fig.legend(handles=handles, loc="lower center", ncol=3, frameon=False, fontsize=8.5)
fig.subplots_adjust(left=0.17, right=0.98, top=0.97, bottom=0.31)
plt.show()
What each agent did at each step. Colour shows the step's main action: a search, a call to the failing rate service, a reflection, the calculator or the final answer. A dot above a step means the plan was rewritten in the same step. Only the two agents with reflection reach a US dollar answer; the plan saves the reflect-only agent's extra round.
6. What reflection cannot do
The reflections above were correct because the rules that wrote them can see the whole request and never fool themselves. A live model’s reflection is more text from the same model that made the mistake. It can be confidently wrong (“all parts are done”). Huang et al. (2023) found that asking a model to review its own reasoning, with no outside signal, often fails to improve the answer and sometimes makes it worse. Reflexion (Shinn et al., 2023) gets its gains from an outside signal, such as failing unit tests or a task’s success or failure, which the model turns into a written lesson for its next attempt. Reflection is most useful when it has something to check against: a test, an error message, a score, or the record of what actually happened.
That is why ReflectionTool reports facts from the record alongside the model’s text.
Give it the plan-only agent’s context and an overconfident assessment:
claim = "Everything the question asks for is done; I am ready to answer."
print(wrap(await ReflectionTool()(planned.context, analysis=claim), 90))Reflection recorded. Plan: 3 of 5 steps completed. Not done: Get the exchange rate to US dollars with get_exchange_rate; Add everything up and convert to US dollars with the calculator. Tool error since the last reflection: get_exchange_rate: ServiceUnavailable: the rate service is not responding (HTTP 503); try again later Tool error since the last reflection: get_exchange_rate: ServiceUnavailable: the rate service is not responding (HTTP 503); try again later
The tool output contradicts the claim: the plan is unfinished and a tool has failed. The model sees both on its next step. A harness can go further. It can refuse a final answer while the plan has open steps, or check the answer with a separate verifier, which is what Module 10’s graders do.
Try this
PlanningToolreturns the whole plan as its result, although the plan is also shown in the instructions on every step. Make it return only “Plan saved (n of m done).” How much of the “plan hist” column goes away?- Make
get_exchange_ratework and return"10.80". Which answer does “plan + reflect” give now, and does the handbook allow it? Nothing in this notebook’s tools would catch it. What would you add: an instruction, a check in the self-check, or a tool that knows the policy?- Remove the WHEN NOT TO USE paragraph from
PlanningTool’s description and, with a live model (MODELset), ask “What is the lodging cap per night in Oslo?”. Does the model now write a plan for a one-step question? Count the extra tokens.- Write a
before_llmcallback (like the context manager in Notebook 6a) that, while the plan has open steps, lists them in the instructions and setsrequest.tool_choice = "required". With a live model, what does the plan-only agent do instead of giving up?
nb.usage()| model calls | input tokens | output tokens | cost |
|---|---|---|---|
| 27 (fake: 27) | ≈ 42,832 | ≈ 1,874 | ≈ USD 0.0503 (reference price) |