AI Engineering · Build lab 9 of 14
Build an AI agent with LangGraph in Python: state, tools, memory and human approval
Rebuild the lab 4 agent loop with LangGraph: a support agent with typed state, a model node, a ToolNode with three order tools, a conditional edge, a step limit, memory per conversation thread, a human approval pause before any refund, and every step streamed. Tested with a fake model.
⏱ 75 minIntermediate💸 Free (local model)8 steps
Python 3.12uvOllamallama3.2:3bLangGraph 1.2langchain-openai 1.8pytest
Overview video
What you will build
A customer support agent for a small online shop, on the command line. A customer asks about an order; the agent looks it up, checks the refund policy and, when a refund is due, pauses and asks a person to approve it before any money moves. It remembers what was said earlier in the same conversation, and it prints every step as it happens.
In lab 4 you wrote the agent loop by hand: send the tools, read the tool calls, run them, append the results, repeat, stop after a few rounds. Here you hand that loop to LangGraph. You describe it as a small graph, nodes (functions) joined by edges (what runs next), and LangGraph runs it. In return you get things that are hard to write by hand: the state saved after every step, memory per conversation, and a clean way to pause in the middle of a run and continue later.
Everything is tested with a scripted fake model, so the tests need no model and run in under a second.
Before you start
- Lab 4 done: Tool calling by hand. This lab rebuilds its loop, so you should know what a tool call, a
role: "tool"message and atool_call_idare. Step 3 maps each piece of lab 4 to its LangGraph replacement. - Lab 1 for the settings: Your first LLM call.
.envandconfig.pyare the same. - Python you will see: Type hints and Pydantic (
Annotated,TypedDict) and Functions, closures and decorators (@toolis a decorator, and the model node is a closure). Each new piece is explained where it appears. - The ideas behind it (8 minutes each): The agent loop and Agent memory.
Setup
S1Install uv (the Python project tool)
uv installs Python for you, creates the virtual environment and manages packages. One tool instead of pyenv + venv + pip. Already have it from an earlier lab? Skip to the next item.
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" everything's installed!
S2Check uv works
The export PATH=... line makes uv work in this terminal right away. New terminal windows find it on their own (the installer added it to your shell settings). On Windows, open a new terminal after installing.
uv --version uv 0.x.y
S3Install Ollama (runs models on your machine)
Download it from ollama.com/download and open it once. It runs a small server on port 11434 that speaks the same chat API as the hosted providers, tool calling included. Any current version works; if yours is older than 0.3, update it.
ollama --version ollama version is 0.x.y
S4Pull the model (llama3.2:3b, about 2 GB)
Skip this if you pulled it for an earlier lab. An agent needs a model that was trained to call tools; llama3.2:3b was, and it runs on most laptops without a GPU.
ollama pull llama3.2:3b pulling manifest ... success
S5Check the model supports tools
ollama show prints the model's details. tools must be listed under Capabilities; without it, every request this agent sends is refused (Troubleshooting has the error).
ollama show llama3.2:3b Model
architecture llama
parameters 3.2B
...
Capabilities
completion
tools
... Create the project
A fresh project with LangGraph, the LangChain model wrapper and pytest, plus the settings from lab 1.
uv init creates the project folder and pyproject.toml (the project file, like package.json or pom.xml). --python 3.12 makes the project use Python 3.12 (uv downloads it if needed); langchain-openai needs 3.11 or newer, so an older default Python would fail. uv add installs packages into the project's own virtual environment and records them, so uv sync can recreate it anywhere.
Packages, pinned to versions this lab was tested with (== means exactly this version):
- langgraph: runs the agent as a graph, saves its state, pauses and resumes it.
- langchain-core: the shared building blocks LangGraph uses: message classes (
HumanMessage,AIMessage,ToolMessage) and the@tooldecorator. - langchain-openai:
ChatOpenAI, a model class that talks to any OpenAI-compatible API, Ollama included. It uses the sameopenaiSDK as labs 1 to 4 underneath. - python-dotenv reads
.env, and pytest runs the tests (a dev dependency).
Then create the four files below. .env and config.py are the same as in lab 1. llm.py builds the model in one function, so the graph can take a model as a parameter and the tests can pass a fake one.
# Local model through Ollama (free). Ollama ignores the key, but the SDK needs a value.
LLM_BASE_URL=http://localhost:11434/v1
LLM_API_KEY=ollama
LLM_MODEL=llama3.2:3b
# A hosted API instead: change these three lines, nothing else.
# LLM_BASE_URL=https://api.your-provider.com/v1
# LLM_API_KEY=sk-...
# LLM_MODEL=the-model-name - Ollama's OpenAI-compatible API, under
/v1. Tool calls use the same endpoint as a plain chat call.line 2 - Ollama does not check keys, but the SDK needs a value. A real provider does check: keep this file out of git.line 3
import os
from dataclasses import dataclass
from dotenv import load_dotenv
load_dotenv() # read .env into environment variables (real env vars win)
@dataclass(frozen=True)
class Settings:
base_url: str
api_key: str
model: str
def settings() -> Settings:
return Settings(
base_url=os.environ.get("LLM_BASE_URL", "http://localhost:11434/v1"),
api_key=os.environ.get("LLM_API_KEY", "ollama"),
model=os.environ.get("LLM_MODEL", "llama3.2:3b"),
) load_dotenv()copies.envintoos.environ. Variables already set in your shell win, which is what you want on a server.line 6frozen=Truemakes the settings read-only, like a Java record.line 9
.venv/
__pycache__/
.env
graph.md - Never commit
.env: one day it holds a real key.line 3 - Step 3 writes a diagram of the graph to
graph.md. It is generated, so it stays out of git.line 4
from langchain_openai import ChatOpenAI
from config import settings
def make_model() -> ChatOpenAI:
s = settings()
return ChatOpenAI(
base_url=s.base_url,
api_key=s.api_key,
model=s.model,
temperature=0,
timeout=120,
max_retries=2,
) ChatOpenAIis LangChain's model class for OpenAI-compatible APIs. LangGraph works with any LangChain chat model; this one fits because Ollama speaks the OpenAI API.line 1- A function, not a global: the real program calls it, tests never do (they pass a fake model instead, step 8).line 6
- The same three settings as every lab. Changing
.envmoves the agent to a hosted API with no code change.line 9 - Temperature 0: the most likely token every time. Which tool to call should be predictable, not creative.line 12
- Seconds per request. One question can take four or five requests in a row, and a local model on a CPU is slow, so this is generous on purpose.line 13
- Retries network errors, 429 and 5xx, as in lab 1.line 14
uv init --python 3.12 support-agent
cd support-agent
uv add langgraph==1.2.24 langchain-openai==1.8.5 langchain-core==1.8.5 python-dotenv
uv add --dev pytest Initialized project `support-agent` at `.../support-agent` Using CPython 3.12.x Creating virtual environment at: .venv Resolved 46 packages in 600ms Installed 44 packages in 80ms + langchain-core==1.8.5 + langchain-openai==1.8.5 + langgraph==1.2.24 + openai==3.60.0 + python-dotenv==1.2.4 ...
Stuck on this step?
uv: command not found- Run
export PATH="$HOME/.local/bin:$PATH"(macOS and Linux), or open a new terminal so the installer's PATH change applies. - uv also created
main.py - Newer uv versions write a hello-world
main.py. You replace it in step 4, so leave it.
Three tools, with @tool
Write the shop's tools as plain functions and let one decorator turn each into a tool the model can call.
First the data. store.py is a fake order database: three orders and a list of refunds. A real app would query its orders service and payment provider here; the agent does not care where the data comes from.
Then the tools. In lab 4 you wrote make_tool and Toolbox yourself: read the function's name, docstring and type hints with inspect, build a Pydantic model for the arguments, export its JSON Schema. LangChain's @tool decorator does all of that in one line. It wraps the function in a tool object that has a name, a description (the docstring), an argument schema (from the type hints), and an invoke() method that validates the arguments and calls your function.
Three tools:
- lookup_order returns an order's item, total, status and delivery date.
- check_refund_policy says whether an order can be refunded and the most that can be refunded: it must be delivered, within 30 days, and not refunded before.
- issue_refund moves money. It checks the policy again itself instead of trusting that the model called
check_refund_policyfirst. Rules that matter live in code, not in the prompt: a model can skip an instruction, but it cannot skip a line of Python.
When something is wrong (an unknown order id, a refund that is not allowed), the tools return an error dict instead of raising. The model reads it as the tool result and can tell the customer, exactly like the error messages in lab 4 step 6.
from datetime import date
# A fixed "today", so the refund window gives the same answers every time you run the lab.
# A real app would use date.today().
TODAY = date(2026, 11, 20)
REFUND_WINDOW_DAYS = 30
# Fake order database. A real tool would query your orders service here.
ORDERS = {
"A1001": {"item": "Wireless headphones", "total": 79.0, "status": "delivered", "delivered_on": "2026-11-08"},
"A1002": {"item": "USB-C cable", "total": 12.5, "status": "shipped", "delivered_on": None},
"A1003": {"item": "Running shoes", "total": 120.0, "status": "delivered", "delivered_on": "2026-09-30"},
}
REFUNDS: list[dict] = [] # every refund issued, in order - A fixed date, so A1001 is always 12 days old and A1003 always 51. With
date.today()the outputs in this lab would change every day.line 5 - Order id to order. The values are plain JSON types (strings, numbers,
None), because tool results travel to the model as JSON text.line 9 list[dict]is a type hint for the variable; Python does not enforce it. The tests read this list to check that money moved, or did not.line 15
from datetime import date
from langchain_core.tools import tool
from store import ORDERS, REFUND_WINDOW_DAYS, REFUNDS, TODAY
def find_order(order_id: str) -> tuple[str, dict | None]:
key = order_id.strip().upper()
return key, ORDERS.get(key)
def refund_decision(order_id: str) -> dict:
"""The refund policy as plain code: the single source of truth for both tools below."""
key, order = find_order(order_id)
if order is None:
return {"order_id": key, "eligible": False, "reason": "no such order"}
if any(r["order_id"] == key for r in REFUNDS):
return {"order_id": key, "eligible": False, "reason": "already refunded"}
if order["status"] != "delivered":
return {"order_id": key, "eligible": False, "reason": f"not delivered yet (status: {order['status']})"}
days = (TODAY - date.fromisoformat(order["delivered_on"])).days
if days > REFUND_WINDOW_DAYS:
return {"order_id": key, "eligible": False, "reason": f"delivered {days} days ago; the limit is {REFUND_WINDOW_DAYS}"}
return {"order_id": key, "eligible": True, "max_amount": order["total"], "reason": f"delivered {days} days ago"}
@tool
def lookup_order(order_id: str) -> dict:
"""Look up an order by its id, like A1001. Returns the item, total, status and delivery date."""
key, order = find_order(order_id)
if order is None:
return {"error": f"no order {order_id!r}; order ids look like A1001"}
return {"order_id": key, **order}
@tool
def check_refund_policy(order_id: str) -> dict:
"""Check whether an order can be refunded, and the most that can be refunded. Call it before issue_refund."""
return refund_decision(order_id)
@tool
def issue_refund(order_id: str, amount: float, reason: str) -> dict:
"""Refund money for an order to the customer. Only after check_refund_policy said it is eligible."""
decision = refund_decision(order_id)
if not decision["eligible"]:
return {"error": f"refund refused: {decision['reason']}"}
if not 0 < amount <= decision["max_amount"]:
return {"error": f"amount must be more than 0 and at most {decision['max_amount']}"}
REFUNDS.append({"order_id": decision["order_id"], "amount": amount, "reason": reason})
return {"status": "refunded", "order_id": decision["order_id"], "amount": amount}
TOOLS = [lookup_order, check_refund_policy, issue_refund] toolis a decorator: writing@toolabove a function replaces the function with a tool object built from it, like an annotation that also wraps the method.line 3- A plain helper, not a tool: the model never sees it.
tuple[str, dict | None]means "a pair of a string and a dict or None"..strip().upper()accepts " a1001 " too.line 8 - The policy as ordinary code, used by both refund tools. One function, one set of rules, easy to unit test.line 13
any(...)is true if at least one refund has this order id, likestream().anyMatch(...)in Java.line 18date.fromisoformat("2026-11-08")parses the date; subtracting two dates gives atimedelta, and.daysis its length in days.line 22- From here on,
lookup_orderis aStructuredToolobject, not a plain function. Call it withlookup_order.invoke({"order_id": "A1001"}).line 28 - The docstring becomes the description the model reads. "like A1001" shows the model what an id looks like.line 30
{"order_id": key, **order}builds a new dict: the id first, then every key oforderspread in, like{orderId, ...order}in JavaScript.line 34- Descriptions can carry instructions too: "Call it before issue_refund" helps the model plan the order of calls.line 39
- Never trust that the model checked first: the tool checks again, every time.line 46
- Python allows chained comparisons:
0 < amount <= maxmeans0 < amount and amount <= max. It stops a model from refunding more than was paid, or a negative amount.line 49 - The side effect: money moves. For now it happens with nobody asking. Step 7 puts a person in front of this line.line 51
- The list the graph uses, in the order the model sees them.line 55
import json
from langchain_core.utils.function_calling import convert_to_openai_tool
from tools import TOOLS, check_refund_policy, lookup_order
print(lookup_order.invoke({"order_id": "A1001"}))
print(lookup_order.invoke({"order_id": "b42"}))
for order_id in ["A1001", "A1002", "A1003"]:
print(check_refund_policy.invoke({"order_id": order_id}))
print(type(lookup_order).__name__, lookup_order.name)
print(json.dumps(convert_to_openai_tool(TOOLS[2]), indent=2)) convert_to_openai_toolbuilds the exact{"type": "function", ...}entry that goes into the request astools=.bind_tools(step 3) calls it for every tool.line 3.invoke()takes the arguments as a dict, validates them against the schema and calls your function. A wrong type or a missing argument raises an error before your code runs.line 7type(x).__name__is the class name, likex.getClass().getSimpleName()in Java.line 12TOOLS[2]isissue_refund: the schema shows the three required arguments the model must send.line 13
uv run try_tools.py {'order_id': 'A1001', 'item': 'Wireless headphones', 'total': 79.0, 'status': 'delivered', 'delivered_on': '2026-11-08'}
{'error': "no order 'b42'; order ids look like A1001"}
{'order_id': 'A1001', 'eligible': True, 'max_amount': 79.0, 'reason': 'delivered 12 days ago'}
{'order_id': 'A1002', 'eligible': False, 'reason': 'not delivered yet (status: shipped)'}
{'order_id': 'A1003', 'eligible': False, 'reason': 'delivered 51 days ago; the limit is 30'}
StructuredTool lookup_order
{
"type": "function",
"function": {
"name": "issue_refund",
"description": "Refund money for an order to the customer. Only after check_refund_policy said it is eligible.\n A person approves every refund before any money moves.",
"parameters": {
"properties": {
"order_id": {
"type": "string"
},
"amount": {
"type": "number"
},
"reason": {
"type": "string"
}
},
"required": [
"order_id",
"amount",
"reason"
],
"type": "object"
}
}
} show_specs.py: the same {"type": "function", "function": {...}} shape, with required coming from the parameters that have no default. @tool is lab 4's make_tool with more polish, not magic. Keep tools small, typed and testable on their own: everything after this step is about when they run, never about what they do.Stuck on this step?
TypeError: 'StructuredTool' object is not callable- After
@tool, calllookup_order.invoke({"order_id": "A1001"}), notlookup_order("A1001"). If you also want the plain function, keep it undecorated and wrap it separately:lookup_tool = tool(lookup_order). ValueError: Function must have a docstring if description not provided- Every
@toolfunction needs a docstring: it is the description the model reads. Add a"""..."""line right under thedef.
The graph: state, a model node, a tool node and one loop
Describe lab 4's loop as a graph and look at its shape, before sending a single request.
A LangGraph agent has three parts.
The state is the data that flows through the graph. Here it is one field, messages: the conversation so far. State is a TypedDict, which describes the keys and value types of a plain dict, like a TypeScript interface for an object. The interesting part is Annotated[list[AnyMessage], add_messages]. The second item, add_messages, is a reducer: when a node returns {"messages": [reply]}, LangGraph does not replace the list with your one-element list. It calls add_messages(old_list, [reply]), which appends the new messages (and replaces a message that has the same id, which you rarely need). If you know Redux: a node returns an update, the reducer merges it into the state.
Nodes are functions that take the state and return an update. There are two:
- agent sends the system prompt plus the messages to the model and returns its reply, an
AIMessage. The reply has either text (an answer) ortool_calls. - tools is LangGraph's ready-made
ToolNode. It reads the tool calls in the lastAIMessage, runs each tool, and returns oneToolMessageper call, carrying the matchingtool_call_id. An unknown tool name or invalid arguments become an error message for the model instead of a crash.
Edges say what runs next. START -> agent always. After agent, a conditional edge: tools_condition looks at the last message and returns "tools" if it has tool calls, or END if it is a final answer. After tools, always back to agent, so the model sees the results. That back edge is the loop.
What each piece of lab 4 became:
messages = [...]andmessages.append(...): themessagesstate field and itsadd_messagesreducer.Toolbox.specs()sent on every request:model.bind_tools(TOOLS), once.- The
for c in msg.tool_calls:block that runs each call and appends a tool message with its id:ToolNode. if not msg.tool_calls: return ...: the conditional edge withtools_condition.for request in range(1, max_steps + 1)andTooManySteps: therecursion_limitsetting andGraphRecursionError(step 4).
Before any of this runs, compile() checks the graph (every edge points to a node that exists, there is a way in from START) and returns an object you can invoke() or stream(). show_graph.py builds it and prints its nodes and edges. It sends no request: creating ChatOpenAI only stores settings.
from typing import Annotated, TypedDict
from langchain_core.messages import AnyMessage, SystemMessage
from langgraph.graph import START, StateGraph
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode, tools_condition
from tools import TOOLS
SYSTEM = (
"You are a support agent for an online shop. Use the tools to look up orders and refunds. "
"Answer in one or two short sentences."
)
class State(TypedDict):
messages: Annotated[list[AnyMessage], add_messages]
def tool_failed(error: Exception) -> str:
"""Any exception inside a tool becomes a message the model can read, never a crash (as in lab 4)."""
return f"Tool error: {error}"
def build_graph(model, checkpointer=None):
model_with_tools = model.bind_tools(TOOLS)
def agent(state: State) -> dict:
reply = model_with_tools.invoke([SystemMessage(SYSTEM)] + state["messages"])
return {"messages": [reply]}
builder = StateGraph(State)
builder.add_node("agent", agent)
builder.add_node("tools", ToolNode(TOOLS, handle_tool_errors=tool_failed))
builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", tools_condition)
builder.add_edge("tools", "agent")
return builder.compile(checkpointer=checkpointer) TypedDictandAnnotatedcome from the standardtypingmodule. On Python 3.12 nothing extra is needed.line 1- LangChain's message classes are lab 4's role dicts as objects:
SystemMessageisrole: "system",HumanMessageis"user",AIMessageis"assistant",ToolMessageis"tool".AnyMessageis the type that means "any of them".line 3 STARTandENDare the graph's entry and exit.StateGraphis the builder.line 4ToolNodeandtools_conditionare the two ready-made pieces that replace most of lab 4's loop.line 6- The state's shape: a dict with one key,
messages. A node may return just the keys it changes.line 16 Annotated[T, extra]is typeTwith extra information attached. Python ignores it; LangGraph readsadd_messagesfrom it and uses it to merge updates into this key.line 17- Called by
ToolNodewhen a tool raises an exception you did not expect: the message becomes the tool result, so the model reads it and the run goes on, as in lab 4 step 6. (Unknown tool names and invalid arguments are handled byToolNodeitself.)line 20 - The model is a parameter (dependency injection): the real program passes
ChatOpenAI, tests pass a fake.checkpointeris for memory, step 6.line 25 bind_toolsreturns a new object that sends the three tool schemas with every request. The originalmodelis unchanged.line 26- The agent node. It is defined inside
build_graph, so it can usemodel_with_toolsfrom the enclosing function: a closure, like a Java lambda capturing a local variable.line 28 - The system message is added on every call but never stored in the state, so it cannot pile up.
invokesends one chat request and returns anAIMessage.line 29 - Return only the change. The reducer appends
replyto the existing messages.line 30 - A node is a name plus a function. The name is what edges and the printout refer to.line 33
- The conditional edge: after
agent, calltools_condition(state)and go where it says,"tools"orEND.line 36 - The back edge. Without it the graph would stop after running the tools, and the model would never see the results.line 37
compile()validates the graph and returns the runnable agent.line 38
from pathlib import Path
from agent import build_graph
from llm import make_model
graph = build_graph(make_model()) # builds the graph only: no request is sent to the model
g = graph.get_graph()
print("nodes:", ", ".join(g.nodes))
for edge in g.edges:
kind = "conditional" if edge.conditional else "always"
print(f" {edge.source} -> {edge.target} ({kind})")
Path("graph.md").write_text("```mermaid\n" + g.draw_mermaid() + "```\n")
print("diagram written to graph.md") - Building the graph sends nothing:
make_model()only stores settings, andbind_toolsonly remembers the tools. Requests happen ininvokeandstream.line 6 get_graph()returns a description of the compiled graph: its nodes and edges.line 7g.nodesis a dict keyed by node name;", ".join(...)over a dict joins its keys.line 9- Python's conditional expression:
a if condition else biscondition ? a : bin Java.line 11 draw_mermaid()returns the graph as Mermaid text. GitHub, GitLab and many editors draw it when it sits in a ````mermaid``` block in a Markdown file.line 14
uv run show_graph.py nodes: __start__, agent, tools, __end__ __start__ -> agent (always) agent -> __end__ (conditional) agent -> tools (conditional) tools -> agent (always) diagram written to graph.md
agent runs, then either the run ends (agent -> __end__) or the tools run (agent -> tools) and the model is asked again (tools -> agent). __start__ and __end__ are how START and END are named inside the graph. The graph is the same loop, but now it is data that LangGraph can run, save after each step, pause and draw.Stuck on this step?
ValueError: Found edge ending at unknown nodetool``- A name in
add_edgedoes not match a name inadd_node. Names are plain strings, so a typo like"tool"instead of"tools"is only found bycompile(). - The model never sees the tool results; the run stops after
[tools] - The back edge
builder.add_edge("tools", "agent")is missing. Without it the graph ends after the tools node.
Run it, stream every step, and set a step limit
Ask a real question and watch each node run, with a hard cap on how long the agent may loop.
graph.stream(input, config, stream_mode="updates") runs the graph and gives you an update each time a node finishes: a dict from the node name to what it returned, like {"agent": {"messages": [AIMessage(...)]}}. show.py prints those updates one line per message, so you watch the agent think: which tool it wants, what the tool returned, and the answer. Other modes exist: "values" gives the whole state after each step, and "messages" gives the model's tokens as they are written, for a chat UI.
The input is the initial state: a dict with the first HumanMessage. The model gets the system message, then this.
The step limit. Every node run is one step, so a question that needs one tool takes three steps: agent, tools, agent. recursion_limit caps the steps of one run; past it LangGraph raises GraphRecursionError, the job lab 4's TooManySteps did. Set it yourself: the default in LangGraph 1.2 is 10007 steps, which for a model stuck calling the same tool is thousands of paid requests. A limit of 12 allows six requests to the model.
Errors from the model server are the same openai exceptions as in lab 1, because ChatOpenAI uses the openai SDK underneath.
import json
from langchain_core.messages import AIMessage, ToolMessage
def short(text: str, width: int = 100) -> str:
text = " ".join(str(text).split())
return text if len(text) <= width else text[: width - 3] + "..."
def print_update(update: dict) -> None:
"""Print one step of the graph: which node ran and the messages it added."""
for node, change in update.items():
for msg in change["messages"]:
if isinstance(msg, AIMessage) and msg.tool_calls:
for call in msg.tool_calls:
print(f"[{node}] wants {call['name']}({json.dumps(call['args'])})")
elif isinstance(msg, AIMessage):
print(f"[{node}] answer: {msg.content}")
elif isinstance(msg, ToolMessage):
print(f"[{node}] {msg.name} -> {short(msg.content)}") - Squashes whitespace and cuts long text to one line, so the printout stays readable.
str(text)also accepts content that is not a string.line 6 - One entry per node that finished in this step.
.items()gives (key, value) pairs, likeentrySet()in Java.line 13 isinstance(x, C)isx instanceof C.msg.tool_callsis a list of dicts withname,argsandid. LangChain already parsed the arguments from the JSON string for you; in lab 4 you calledjson.loadsyourself.line 15json.dumps(call["args"])prints the arguments as JSON, the way the model sent them.line 17ToolNodestores the tool name on eachToolMessage, and turns the dict the tool returned into JSON text: that is why you seetrueandnullinstead of Python'sTrueandNone.line 21
import sys
import openai
from langchain_core.messages import HumanMessage
from langgraph.errors import GraphRecursionError
from agent import build_graph
from config import settings
from llm import make_model
from show import print_update
STEP_LIMIT = 12
question = " ".join(sys.argv[1:]) or "Where is my order A1002?"
graph = build_graph(make_model())
config = {"recursion_limit": STEP_LIMIT}
try:
for update in graph.stream({"messages": [HumanMessage(question)]}, config, stream_mode="updates"):
print_update(update)
except GraphRecursionError:
sys.exit(f"Stopped: the agent hit the step limit ({STEP_LIMIT} steps) without a final answer.")
except openai.APITimeoutError:
sys.exit("The model took too long. Try a shorter question.")
except openai.APIConnectionError:
sys.exit("Cannot reach the model server. Is Ollama running? (open the app or run: ollama serve)")
except openai.NotFoundError:
sys.exit(f"Model '{settings().model}' not found. Run: ollama list")
except openai.BadRequestError as e:
sys.exit(f"The server rejected the request (does this model support tools?): {e}") - At most 12 steps per run: six model requests and five tool rounds in between.line 12
sys.argvis the command-line arguments. With none, ask about A1002.line 14- The run's settings.
recursion_limitis the step limit; step 6 adds more keys here.line 16 streamis a generator: each loop turn runs the graph until the next node finishes, then hands you that node's update. Nothing runs until the loop asks for the next item.line 19- The step limit was hit: say so clearly instead of printing a stack trace.line 21
- Timeout before connection error on purpose:
APITimeoutErroris a subclass ofAPIConnectionError, and Python uses the firstexceptthat matches.line 23 - Ollama answers HTTP 400 when the model has no tool support; the SDK raises it as
BadRequestError.line 29
uv run main.py "Where is my order A1002?" [agent] wants lookup_order({"order_id": "A1002"})
[tools] lookup_order -> {"order_id": "A1002", "item": "USB-C cable", "total": 12.5, "status": "shipped", "delivered_on": ...
[agent] answer: Your order A1002, a USB-C cable, has shipped and is on its way to you. uv run main.py "Please refund order A1001, the headphones broke": the agent looks the order up, checks the policy and refunds 79.0 with nobody asking you. That is the problem step 7 solves.Stuck on this step?
- The answer says the order is "on its way" but there is no
[tools]line - The model answered from imagination without calling a tool. Run it again; step 5 makes this much rarer and catches it in code.
Stopped: the agent hit the step limit (12 steps)- The model kept calling tools. Read the printout: usually it repeats a call that keeps returning an error. Make that error say what to send instead, or try a bigger model (
llama3.1:8b, about 5 GB). - It takes 20+ seconds before the first line
- Normal the first time: Ollama loads the model into memory. Each step after that is one model request, a few seconds each on a laptop CPU.
Small models skip tools: make it robust
Catch the reply where the model invents order details instead of looking them up, and give it one nudge.
A 3-billion-parameter model sometimes answers "Your order A1002 has been delivered!" without calling lookup_order. It sounds right and is made up. Bigger models do this less, never zero. Three layers make it rare and harmless:
- Say exactly when to use each tool. The system prompt now names the tool ("For any question about an order, call lookup_order first") and the order of calls for refunds. Small models follow short, specific rules much better than "use the tools".
- Temperature 0, already set in
llm.py, so the model does not wander off the most likely choice. - Check in code.
needs_lookupasks: does the newest customer message contain an order id, and has no tool run since? If the model answered anyway, the agent node sends the request once more with a short instruction (the nudge) appended, and keeps only the second reply. The invented answer never enters the state, so the customer never sees it.
Why not force a tool call? bind_tools(TOOLS, tool_choice="any") makes the model call a tool on every request, so it could never write its final answer and the run would only end at the step limit. A rule in code that fires only when an answer is clearly missing its facts does the job without that cost. The nudge is sent at most once per reply; if the model still skips the tool, its answer goes through and the evals lab is where you measure how often that happens.
import re
from typing import Annotated, TypedDict
from langchain_core.messages import AnyMessage, HumanMessage, SystemMessage, ToolMessage
from langgraph.graph import START, StateGraph
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode, tools_condition
from tools import TOOLS
SYSTEM = (
"You are a support agent for an online shop. "
"For any question about an order, call lookup_order first; never guess order details. "
"Before issue_refund, always call check_refund_policy. "
"Answer in one or two short sentences."
)
NUDGE = "You did not call a tool. Call lookup_order with the order id first, then answer from its result."
ORDER_ID = re.compile(r"\b[A-Z]\d{4}\b", re.IGNORECASE)
class State(TypedDict):
messages: Annotated[list[AnyMessage], add_messages]
def tool_failed(error: Exception) -> str:
"""Any exception inside a tool becomes a message the model can read, never a crash (as in lab 4)."""
return f"Tool error: {error}"
def needs_lookup(messages: list[AnyMessage]) -> bool:
"""True when the newest user message names an order and no tool has run since it."""
last_user = max(i for i, m in enumerate(messages) if isinstance(m, HumanMessage))
names_order = ORDER_ID.search(messages[last_user].content) is not None
used_tool = any(isinstance(m, ToolMessage) for m in messages[last_user + 1 :])
return names_order and not used_tool
def build_graph(model, checkpointer=None):
model_with_tools = model.bind_tools(TOOLS)
def agent(state: State) -> dict:
prompt = [SystemMessage(SYSTEM)] + state["messages"]
reply = model_with_tools.invoke(prompt)
if not reply.tool_calls and needs_lookup(state["messages"]):
reply = model_with_tools.invoke(prompt + [reply, HumanMessage(NUDGE)])
return {"messages": [reply]}
builder = StateGraph(State)
builder.add_node("agent", agent)
builder.add_node("tools", ToolNode(TOOLS, handle_tool_errors=tool_failed))
builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", tools_condition)
builder.add_edge("tools", "agent")
return builder.compile(checkpointer=checkpointer) - Name the tool and the situation. "Never guess order details" tells the model what not to do.line 13
- The nudge: a direct instruction, sent only when the first reply skipped the tool.line 17
- A compiled regular expression, like
Pattern.compilein Java.r"..."is a raw string, so\breaches the regex as written: a word boundary.[A-Z]\d{4}is one letter and four digits, like A1001.line 18 enumerategives (index, item) pairs.max(...)over the indexes of theHumanMessages is the position of the newest one.line 32.searchfinds the pattern anywhere in the text and returnsNonewhen there is no match.line 33messages[last_user + 1 :]is every message after it (a slice).any(...)is true if one of them is aToolMessage.line 34- Build the prompt once, so the retry can reuse it.line 42
reply.tool_callsis an empty list when the model answered in text, and an empty list is false in Python.line 44- The retry sends the first reply plus the nudge, so the model sees what it did wrong. Only the new reply is returned: neither the guess nor the nudge is saved in the state.line 45
uv run main.py "Hi, is my order A1003 delivered yet?" [agent] wants lookup_order({"order_id": "A1003"})
[tools] lookup_order -> {"order_id": "A1003", "item": "Running shoes", "total": 120.0, "status": "delivered", "delivered_on"...
[agent] answer: Yes, your running shoes (order A1003) were delivered on 30 September 2026. Stuck on this step?
- The model calls
lookup_orderfor every message, even "thanks" - The rule says "for any question about an order". If it still over-calls, that is cheap and harmless for a read-only tool. Over-calling a tool with side effects is not, and step 7 guards that one.
- The tool call appears as JSON text in the answer, like
{"name": "lookup_order", "parameters": {...}} - The model wrote the call as text and Ollama did not recognise it. Update Ollama and use
llama3.2:3b, notllama3.2:1b, which does this more often.
Memory across turns: a checkpointer and a thread id
The agent remembers what was said earlier in the same conversation, and nothing from other conversations.
So far every run starts from nothing. Ask "How much did it cost?" after asking about A1002, and the model has no idea which order you mean: it only sees the messages you pass in.
A checkpointer fixes that. When you compile the graph with one, LangGraph saves the whole state after every step, under a thread id you choose in the config: {"configurable": {"thread_id": "customer-42"}}. The next run with the same thread id loads the saved state first, and the add_messages reducer appends your new HumanMessage to it. A thread id is like a session id: one per conversation. A different id starts an empty conversation.
main.py now treats each command-line argument as one turn of the same conversation, and prints how many messages the thread holds at the end. graph.get_state(config) returns the saved state of a thread; .values is the state dict.
InMemorySaver keeps the saved states in a Python dict. It is perfect for learning and tests, and everything is gone when the process exits. Production uses a checkpointer backed by a database, from the packages langgraph-checkpoint-sqlite (SqliteSaver) or langgraph-checkpoint-postgres (PostgresSaver): same graph code, one different object passed to compile().
import sys
import openai
from langchain_core.messages import HumanMessage
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.errors import GraphRecursionError
from agent import build_graph
from config import settings
from llm import make_model
from show import print_update
STEP_LIMIT = 12
def run_turn(graph, config: dict, question: str) -> None:
for update in graph.stream({"messages": [HumanMessage(question)]}, config, stream_mode="updates"):
print_update(update)
questions = sys.argv[1:] or ["Where is my order A1002?"]
graph = build_graph(make_model(), checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "customer-42"}, "recursion_limit": STEP_LIMIT}
try:
for question in questions:
print(f"you: {question}")
run_turn(graph, config, question)
except GraphRecursionError:
sys.exit(f"Stopped: the agent hit the step limit ({STEP_LIMIT} steps) without a final answer.")
except openai.APITimeoutError:
sys.exit("The model took too long. Try a shorter question.")
except openai.APIConnectionError:
sys.exit("Cannot reach the model server. Is Ollama running? (open the app or run: ollama serve)")
except openai.NotFoundError:
sys.exit(f"Model '{settings().model}' not found. Run: ollama list")
except openai.BadRequestError as e:
sys.exit(f"The server rejected the request (does this model support tools?): {e}")
saved = graph.get_state(config).values["messages"]
print(f"[memory] thread customer-42 now holds {len(saved)} messages") - The in-memory checkpointer. A database-backed one has the same interface.line 5
- One turn: stream the run for one new customer message. The config carries the thread id, so LangGraph loads the history first.line 16
- Each command-line argument is one turn.
sys.argv[1:]is a list of strings;or [...]gives a default when it is empty.line 21 - Pass the checkpointer to
compile()throughbuild_graph. Create it once and reuse it: a newInMemorySaveris an empty memory.line 22 configurableholds per-run values the graph reads;thread_idis the one checkpointers use. A real app would use a conversation or user id here.line 23- Read the saved state back: the full message list of this thread after the last turn.line 40
uv run main.py "Where is my order A1002?" "How much did it cost?" you: Where is my order A1002?
[agent] wants lookup_order({"order_id": "A1002"})
[tools] lookup_order -> {"order_id": "A1002", "item": "USB-C cable", "total": 12.5, "status": "shipped", "delivered_on": ...
[agent] answer: Your order A1002, a USB-C cable, has shipped and is on its way to you.
you: How much did it cost?
[agent] answer: Your USB-C cable cost $12.50.
[memory] thread customer-42 now holds 6 messages lookup_order result from the first turn is still in the thread's messages, so the model can read the price from it. Six messages: the first question, the tool call, the tool result, the answer, the second question, the second answer. Memory is just "send the earlier messages again", which also means every turn costs more tokens than the last. Long conversations need trimming or summarising (Agent memory covers both).Stuck on this step?
- The second turn does not know the order
- Check that both turns use the same
config(samethread_id) and the same compiled graph. A newInMemorySaver()or a new process starts with empty memory. ValueError: Checkpointer requires one or more of the following 'configurable' keys: thread_id, ...- With a checkpointer, every run needs
{"configurable": {"thread_id": ...}}in its config.
A person approves every refund: interrupt and resume
The run pauses right before money moves, shows a person what is about to happen, and continues only after a yes.
One line in issue_refund changes everything: answer = interrupt({...}). The first time it runs, interrupt() pauses the whole graph: LangGraph saves the state with the checkpointer, stops, and the stream gives you one last update, {"__interrupt__": (Interrupt(value={...}),)}, carrying the dict you passed. Nothing after that line has run: no money has moved.
Your code shows the request to a person and resumes the same thread with graph.stream(Command(resume="approve"), config). LangGraph loads the saved state and runs the paused node, tools, again from its start. This time interrupt() does not pause: it returns the resume value, "approve" or "reject", and the tool goes on from there.
That restart is the one rule to remember: code before interrupt() runs twice, once before the pause and once after. Keep it free of side effects. Here it only reads (refund_decision), and the money moves only after the approval. If one reply asked for several tools at once, ToolNode runs all of them again too, which is fine for read-only tools.
Why inside the tool, and not a rule in the prompt? The model cannot talk its way past a line of Python. LangGraph also offers compile(interrupt_before=["tools"]), which pauses before every tool call, lookups included; putting interrupt() in the one dangerous tool pauses only when it matters. Pausing needs a checkpointer (the saved state is what you resume from), which step 6 added.
run_turn now loops: stream until the run ends or pauses; if it paused, ask, and stream again with the Command. ask_human reads the answer with input(). To try it without typing, pipe the answer in: echo y | sends "y" to the program's input.
from datetime import date
from langchain_core.tools import tool
from langgraph.types import interrupt
from store import ORDERS, REFUND_WINDOW_DAYS, REFUNDS, TODAY
def find_order(order_id: str) -> tuple[str, dict | None]:
key = order_id.strip().upper()
return key, ORDERS.get(key)
def refund_decision(order_id: str) -> dict:
"""The refund policy as plain code: the single source of truth for both tools below."""
key, order = find_order(order_id)
if order is None:
return {"order_id": key, "eligible": False, "reason": "no such order"}
if any(r["order_id"] == key for r in REFUNDS):
return {"order_id": key, "eligible": False, "reason": "already refunded"}
if order["status"] != "delivered":
return {"order_id": key, "eligible": False, "reason": f"not delivered yet (status: {order['status']})"}
days = (TODAY - date.fromisoformat(order["delivered_on"])).days
if days > REFUND_WINDOW_DAYS:
return {"order_id": key, "eligible": False, "reason": f"delivered {days} days ago; the limit is {REFUND_WINDOW_DAYS}"}
return {"order_id": key, "eligible": True, "max_amount": order["total"], "reason": f"delivered {days} days ago"}
@tool
def lookup_order(order_id: str) -> dict:
"""Look up an order by its id, like A1001. Returns the item, total, status and delivery date."""
key, order = find_order(order_id)
if order is None:
return {"error": f"no order {order_id!r}; order ids look like A1001"}
return {"order_id": key, **order}
@tool
def check_refund_policy(order_id: str) -> dict:
"""Check whether an order can be refunded, and the most that can be refunded. Call it before issue_refund."""
return refund_decision(order_id)
@tool
def issue_refund(order_id: str, amount: float, reason: str) -> dict:
"""Refund money for an order to the customer. Only after check_refund_policy said it is eligible.
A person approves every refund before any money moves."""
decision = refund_decision(order_id)
if not decision["eligible"]:
return {"error": f"refund refused: {decision['reason']}"}
if not 0 < amount <= decision["max_amount"]:
return {"error": f"amount must be more than 0 and at most {decision['max_amount']}"}
answer = interrupt({"order_id": decision["order_id"], "amount": amount, "reason": reason})
if answer != "approve":
return {"status": "not approved", "note": "a person declined this refund; say that support will follow up"}
REFUNDS.append({"order_id": decision["order_id"], "amount": amount, "reason": reason})
return {"status": "refunded", "order_id": decision["order_id"], "amount": amount}
TOOLS = [lookup_order, check_refund_policy, issue_refund] interruptpauses the graph from inside any node or tool that runs in it.line 4- A docstring can span lines. The model reads this description too, so it knows a person is involved.line 47
- Runs before the pause **and again** after it, so it must only read.
refund_decisiononly reads.line 48 - The pause. The dict is what the person sees: everything they need to decide. On resume, this same call returns the value passed to
Command(resume=...).line 53 - Anything but an explicit "approve" means no. The tool result tells the model what to say to the customer.line 54
- Money moves only here, after a person said yes.line 56
import sys
import openai
from langchain_core.messages import HumanMessage
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.errors import GraphRecursionError
from langgraph.types import Command
from agent import build_graph
from config import settings
from llm import make_model
from show import print_update
STEP_LIMIT = 12
def ask_human(request: dict) -> str:
print(f"[approval] refund {request['amount']} for order {request['order_id']} ({request['reason']})")
try:
typed = input("Approve? [y/N] ")
except EOFError: # nothing left to read (piped input ran out): treat as no
typed = ""
if not sys.stdin.isatty():
print(typed) # piped input is not shown on screen, so show what was read
return "approve" if typed.strip().lower() in ("y", "yes") else "reject"
def run_turn(graph, config: dict, question: str) -> None:
inputs = {"messages": [HumanMessage(question)]}
while True:
paused = None
for update in graph.stream(inputs, config, stream_mode="updates"):
if "__interrupt__" in update:
paused = update["__interrupt__"][0]
else:
print_update(update)
if paused is None:
return
inputs = Command(resume=ask_human(paused.value))
questions = sys.argv[1:] or ["Where is my order A1002?"]
graph = build_graph(make_model(), checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "customer-42"}, "recursion_limit": STEP_LIMIT}
try:
for question in questions:
print(f"you: {question}")
run_turn(graph, config, question)
except GraphRecursionError:
sys.exit(f"Stopped: the agent hit the step limit ({STEP_LIMIT} steps) without a final answer.")
except openai.APITimeoutError:
sys.exit("The model took too long. Try a shorter question.")
except openai.APIConnectionError:
sys.exit("Cannot reach the model server. Is Ollama running? (open the app or run: ollama serve)")
except openai.NotFoundError:
sys.exit(f"Model '{settings().model}' not found. Run: ollama list")
except openai.BadRequestError as e:
sys.exit(f"The server rejected the request (does this model support tools?): {e}")
saved = graph.get_state(config).values["messages"]
print(f"[memory] thread customer-42 now holds {len(saved)} messages") Commandis how you send instructions into a paused graph;Command(resume=value)continues it.line 7requestis the dict thatissue_refundpassed tointerrupt().line 18input(prompt)prints the prompt and waits for a line from the keyboard, likeScanner.nextLine()in Java.line 20EOFError: there is no more input, for exampleecho y |was used up or nothing was piped. No answer is a no.line 21isatty()is true when input comes from a real keyboard. Piped text is not shown on screen, so print it to keep the transcript readable.line 23- The first run starts with the new message. After a pause,
inputsbecomes aCommandinstead.line 29 - A paused run ends with this special update instead of a node name.line 33
- A tuple of
Interruptobjects, one per pause; this agent pauses for one refund at a time..valueis the dict frominterrupt().line 34 - The run ended normally: the turn is over.line 38
- Resume the same thread (
configstill hascustomer-42) with the person's answer, and loop to stream the rest of the run.line 39
echo y | uv run main.py "Please refund order A1001, the headphones arrived broken" you: Please refund order A1001, the headphones arrived broken
[agent] wants lookup_order({"order_id": "A1001"})
[tools] lookup_order -> {"order_id": "A1001", "item": "Wireless headphones", "total": 79.0, "status": "delivered", "deliv...
[agent] wants check_refund_policy({"order_id": "A1001"})
[tools] check_refund_policy -> {"order_id": "A1001", "eligible": true, "max_amount": 79.0, "reason": "delivered 12 days ago"}
[agent] wants issue_refund({"order_id": "A1001", "amount": 79.0, "reason": "headphones arrived broken"})
[approval] refund 79.0 for order A1001 (headphones arrived broken)
Approve? [y/N] y
[tools] issue_refund -> {"status": "refunded", "order_id": "A1001", "amount": 79.0}
[agent] answer: I have refunded $79.00 for your broken headphones on order A1001.
[memory] thread customer-42 now holds 8 messages echo n | and watch the other path: the tool returns not approved, and the model tells the customer that support will follow up. Run it with no echo and type the answer yourself. Then try uv run main.py "Refund order A1003": the policy refuses (51 days), so the agent never even reaches the approval. With a database checkpointer, the pause can last as long as you like: the approver can answer hours later, from another process, by resuming the same thread id.Stuck on this step?
RuntimeError: Cannot use Command(resume=...) without checkpointer- Resuming loads the saved state, so the graph must be compiled with a checkpointer (
build_graph(model, checkpointer=InMemorySaver())), and the resume must use the same graph and the samethread_id. - The approval never shows; the agent says it refunded anyway
- Look for an
[tools] issue_refundline. If there is none, the model only claimed a refund in text: no money moved (check with a bigger model, and see the troubleshooting list). If there is one withrefundedand no approval line before it, yourtools.pyis still the step 2 version. - Windows:
echo y | ... - It works the same in PowerShell. Or leave
echo y |out and typeywhen asked.
Test the graph with a scripted fake model
Tests for the tools and every path through the graph, in under a second, with no model.
The graph uses two things from the model: bind_tools(tools) once, and invoke(messages) returning an AIMessage. A fake only has to have those two methods. Python checks attributes when the code runs, not types at compile time ("duck typing"), so no interface or mocking library is needed: ScriptedModel returns the replies you script, in order, and records every prompt it was sent.
The tests build real graphs with the fake and check each path: no tool, one tool, an unknown tool, the nudge, the step limit, approval yes and no, and memory per thread. conftest.py is a file pytest reads automatically; its fixture empties the refund list before and after every test, so tests cannot affect each other.
graph.invoke(...) is the non-streaming twin of stream: it runs to the end (or to a pause) and returns the final state. When the run paused, that state has an "__interrupt__" key.
import pytest
from store import REFUNDS
@pytest.fixture(autouse=True)
def no_refunds():
REFUNDS.clear() # every test starts with an empty refund list
yield
REFUNDS.clear() - A fixture is setup code pytest runs for tests.
autouse=Truemeans "for every test", like JUnit's@BeforeEachand@AfterEachin one.line 6 yieldhands control to the test; the lines after it run when the test is done, even if it failed.line 9
from store import REFUNDS
from tools import check_refund_policy, issue_refund, lookup_order, refund_decision
def test_lookup_finds_an_order_in_any_case():
assert lookup_order.invoke({"order_id": " a1002 "})["status"] == "shipped"
def test_lookup_explains_an_unknown_id():
assert "order ids look like A1001" in lookup_order.invoke({"order_id": "b42"})["error"]
def test_policy_allows_a_recent_delivery():
decision = check_refund_policy.invoke({"order_id": "A1001"})
assert decision["eligible"] is True
assert decision["max_amount"] == 79.0
def test_policy_refuses_not_delivered_and_too_old():
assert refund_decision("A1002")["reason"] == "not delivered yet (status: shipped)"
assert refund_decision("A1003")["reason"] == "delivered 51 days ago; the limit is 30"
def test_policy_refuses_a_second_refund():
REFUNDS.append({"order_id": "A1001", "amount": 79.0, "reason": "broken"})
assert refund_decision("A1001")["reason"] == "already refunded"
def test_refund_rechecks_the_policy_before_asking_anyone():
result = issue_refund.invoke({"order_id": "A1003", "amount": 10, "reason": "late"})
assert result["error"] == "refund refused: delivered 51 days ago; the limit is 30"
result = issue_refund.invoke({"order_id": "A1001", "amount": 500, "reason": "broken"})
assert result["error"] == "amount must be more than 0 and at most 79.0"
assert REFUNDS == [] - Tools are called with
.invokeand a dict, exactly asToolNodecalls them.line 6 - The plain policy function is the easiest thing to test: no tool wrapper, no graph.line 20
- Both of these return before
interrupt()is reached, so the tool can run outside a graph. A call that got as far asinterrupt()would need a running graph, whichtest_agent.pyprovides.line 29
import json
import pytest
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.errors import GraphRecursionError
from langgraph.types import Command
from agent import NUDGE, build_graph
from store import REFUNDS
def wants(name: str, call_id: str, **args) -> AIMessage:
"""A scripted model reply that asks for one tool call."""
return AIMessage(content="", tool_calls=[{"name": name, "args": args, "id": call_id}])
class ScriptedModel:
"""Stands in for ChatOpenAI: returns the scripted replies in order and records every prompt."""
def __init__(self, *replies: AIMessage):
self.replies = list(replies)
self.prompts = []
self.tool_names = []
def bind_tools(self, tools):
self.tool_names = [t.name for t in tools]
return self
def invoke(self, messages):
self.prompts.append(list(messages))
return self.replies.pop(0)
def kinds(messages) -> list[str]:
return [type(m).__name__ for m in messages]
def test_no_tool_needed():
model = ScriptedModel(AIMessage("Hello! How can I help?"))
result = build_graph(model).invoke({"messages": [HumanMessage("hi")]})
assert result["messages"][-1].content == "Hello! How can I help?"
assert model.tool_names == ["lookup_order", "check_refund_policy", "issue_refund"]
assert isinstance(model.prompts[0][0], SystemMessage)
def test_tool_call_then_answer():
model = ScriptedModel(wants("lookup_order", "c1", order_id="A1002"), AIMessage("It has shipped."))
result = build_graph(model).invoke({"messages": [HumanMessage("Where is A1002?")]})
assert kinds(result["messages"]) == ["HumanMessage", "AIMessage", "ToolMessage", "AIMessage"]
tool_msg = result["messages"][2]
assert tool_msg.tool_call_id == "c1"
assert json.loads(tool_msg.content)["status"] == "shipped"
def test_an_unknown_tool_becomes_a_message():
model = ScriptedModel(wants("cancel_order", "c1", order_id="A1001"), AIMessage("I cannot cancel orders."))
result = build_graph(model).invoke({"messages": [HumanMessage("Cancel A1001")]})
assert result["messages"][2].content.startswith("Error: cancel_order is not a valid tool")
assert result["messages"][-1].content == "I cannot cancel orders."
def test_a_skipped_tool_gets_one_nudge():
model = ScriptedModel(
AIMessage("It is on its way!"),
wants("lookup_order", "c1", order_id="A1002"),
AIMessage("It has shipped."),
)
result = build_graph(model).invoke({"messages": [HumanMessage("Where is my order A1002?")]})
assert model.prompts[1][-1].content == NUDGE
assert "It is on its way!" not in [m.content for m in result["messages"]]
assert result["messages"][-1].content == "It has shipped."
def test_step_limit_stops_a_model_that_never_answers():
model = ScriptedModel(*[wants("lookup_order", f"c{i}", order_id="A1001") for i in range(20)])
with pytest.raises(GraphRecursionError):
build_graph(model).invoke({"messages": [HumanMessage("A1001?")]}, {"recursion_limit": 6})
def refund_graph(*replies):
model = ScriptedModel(wants("issue_refund", "r1", order_id="A1001", amount=79.0, reason="broken"), *replies)
config = {"configurable": {"thread_id": "t1"}}
return build_graph(model, checkpointer=InMemorySaver()), config
def test_refund_waits_for_a_person_then_runs():
graph, config = refund_graph(AIMessage("Refunded 79.0."))
paused = graph.invoke({"messages": [HumanMessage("Refund A1001, it broke")]}, config)
assert paused["__interrupt__"][0].value == {"order_id": "A1001", "amount": 79.0, "reason": "broken"}
assert graph.get_state(config).next == ("tools",)
assert REFUNDS == []
done = graph.invoke(Command(resume="approve"), config)
assert REFUNDS == [{"order_id": "A1001", "amount": 79.0, "reason": "broken"}]
assert done["messages"][-1].content == "Refunded 79.0."
def test_rejected_refund_moves_no_money():
graph, config = refund_graph(AIMessage("A person will follow up."))
graph.invoke({"messages": [HumanMessage("Refund A1001")]}, config)
done = graph.invoke(Command(resume="reject"), config)
assert REFUNDS == []
assert json.loads(done["messages"][2].content)["status"] == "not approved"
def test_memory_is_per_thread():
model = ScriptedModel(AIMessage("Hi Sam."), AIMessage("You are Sam."), AIMessage("I do not know."))
graph = build_graph(model, checkpointer=InMemorySaver())
sam = {"configurable": {"thread_id": "sam"}}
graph.invoke({"messages": [HumanMessage("I am Sam.")]}, sam)
graph.invoke({"messages": [HumanMessage("Who am I?")]}, sam)
graph.invoke({"messages": [HumanMessage("Who am I?")]}, {"configurable": {"thread_id": "other"}})
assert kinds(model.prompts[1]) == ["SystemMessage", "HumanMessage", "AIMessage", "HumanMessage"]
assert kinds(model.prompts[2]) == ["SystemMessage", "HumanMessage"]
assert len(graph.get_state(sam).values["messages"]) == 4 - Builds an
AIMessagethat asks for one tool call, asChatOpenAIwould after parsing the model's reply.**argscollects keyword arguments into a dict.line 13 - The fake model: just the two methods the graph uses.line 18
- The real
bind_toolsreturns a new object; returningselfis enough here, and it records which tools were bound.line 28 - Records a **copy** of the prompt, then returns the next scripted reply, like
queue.poll().line 31 - The class name of each message, for easy comparisons like
["HumanMessage", "AIMessage", ...].line 36 - The system prompt is sent first on every request.line 44
- The four messages of a one-tool run: question, tool call, tool result, answer.line 50
ToolNodeturned the unknown tool into an error message for the model instead of raising.line 59- The second prompt ends with the nudge, and the invented first reply never reaches the state.line 70
- A model that never stops: 20 tool calls queued, but a limit of 6 steps stops it after 3 requests.line 78
- The run paused: the interrupt value is the approval request, the next node to run is
tools, and no money has moved yet.line 90 - Resume with the same config. The tool runs again from its start,
interrupt()returns"approve", and the refund happens.line 93 - The second request on thread
samincludes the first turn; the request on threadotherstarts fresh.line 113
uv run pytest -q .............. [100%] 14 passed in 0.40s
llama3.2:3b picks the right tool for a given question is a different question, answered by running a set of example conversations against the real model and scoring them: that is the evals lab.Stuck on this step?
14 passed, 17 warningswithDeprecationWarning: 'asyncio.iscoroutinefunction' is deprecatedfromlangsmith- Harmless: uv picked a newer Python than 3.12 (look for
Using CPython 3.15in theuv syncoutput), and a LangChain dependency still calls a function that Python 3.15 deprecates. Your code is fine. To match this lab exactly, runuv python pin 3.12in the project folder, thenuv sync. IndexError: pop from empty list- The graph asked the fake model for more replies than the test scripted. Usually a tool result made the run go one more round than you expected: print
model.promptsto see every request. ModuleNotFoundError: No module named 'agent'- Run pytest from the project folder (where
agent.pyis) withuv run pytest -q.
Check it works
Two checks: the tests pass with no model, and a real two-turn conversation goes from a lookup in turn one to a policy check, an approval and a refund in turn two, where the customer never repeats the order id.
Your path may differ: the model may look the order up again in turn two, or skip the policy check (the refund tool checks anyway). What matters is that an approval line comes before any issue_refund -> result, and that the run ends with an answer.
The output below is a real run on llama3.2:3b, and it shows a third path: after the policy check the model asked the customer whether to go ahead, in text, instead of calling issue_refund. That is a safe and reasonable choice, and the approval never showed because no refund was attempted. The thread remembers everything (8 messages), so add a third turn to finish it: echo y | uv run main.py "My order is A1001." "The headphones broke. Can I get a refund?" "Yes, please refund it." Now the refund call, the approval and the result should follow.
uv run pytest -q && echo y | uv run main.py "My order is A1001." "The headphones broke. Can I get a refund?" 14 passed in 0.20s
you: My order is A1001.
[agent] wants lookup_order({"order_id": "A1001"})
[tools] lookup_order -> {"order_id": "A1001", "item": "Wireless headphones", "total": 79.0, "status": "delivered", "deliv...
[agent] answer: Your order A1001 has been successfully located. It is currently in the delivered status and was shipped on November 8, 2026.
you: The headphones broke. Can I get a refund?
[agent] wants check_refund_policy({"order_id": "A1001"})
[tools] check_refund_policy -> {"order_id": "A1001", "eligible": true, "max_amount": 79.0, "reason": "delivered 12 days ago"}
[agent] answer: Since your order A1001 is eligible for a refund and you have not exceeded the maximum refund amount of $79.00, we can proceed with issuing a refund. Would you like us to process the refund now?
[memory] thread customer-42 now holds 8 messages Troubleshooting
openai.BadRequestError: Error code: 400 ... does not support tools
The model has no tool support in Ollama. Run ollama show <model> and look for tools under Capabilities. llama3.2:3b, llama3.1:8b and the qwen2.5 models have it.
The agent answers with order details it never looked up
The model skipped the tool. Step 5's check catches it when the message names an order id. For other questions, make the system prompt name the tool for that situation, keep temperature 0, and try a bigger model: llama3.1:8b follows tools far more reliably than a 3B model.
GraphRecursionError: Recursion limit of 12 reached without hitting a stop condition
The agent looped. Read the streamed steps: usually the same tool call returns the same error again and again. Make the error say what to send instead, or check that the tool result answers the question. Raise the limit only if the task really needs more rounds.
A paused run cannot be resumed, or resuming starts a new conversation
Resume with the same compiled graph (so the same checkpointer) and the same thread_id. With InMemorySaver the pause lives only in this process: if the program exits, it is gone. Use SqliteSaver or PostgresSaver when the approval comes later or from somewhere else.
Something happened twice after an approval (an email sent, a log line written twice)
Code in a node or tool before interrupt() runs again when the graph resumes. Move side effects after the interrupt() call, or into a separate node that runs after the approval.
The tool call shows up as JSON text in the answer
The model wrote the call as text instead of a real tool call. Update Ollama and use llama3.2:3b or bigger; llama3.2:1b does this often.
What changes in production
- Use a durable checkpointer.
PostgresSaverkeeps every thread and every pause in your database, so a conversation survives restarts, runs on any server instance, and an approval can arrive hours later through an admin page that callsCommand(resume=...). - Make risky actions safe to repeat. A resumed tool runs again from its start, and networks retry. Do side effects only after the approval, and send an idempotency key (like the order id plus the refund number) to the payment provider, so a refund can never happen twice.
- Record every approval: who approved, what exactly (order, amount, reason from the
interruptpayload), and when. Check that the approver is allowed to approve that amount; the person is a guard only if the right person is asked. - Limit everything:
recursion_limitper run, a timeout per model request and per tool, and the size of each thread. Every turn re-sends the history, so trim or summarise long threads before they get slow and expensive. - Log the stream. Each update from
stream_mode="updates"is one step: node name, tool calls, tool results. Sending them to your logs or tracing (the tracing lab) is how you find out why an agent did something.
Interview angle
“How would you build an agent that can issue refunds, and keep it safe?”
I would model it as a graph: a state holding the messages, a model node that calls the LLM with the tools bound, a tool node that runs the requested tools and appends their results, and a conditional edge that loops back to the model until it answers. The tools are typed functions; the refund policy is plain code that the refund tool re-checks itself, so the model cannot skip it. The refund tool pauses the graph with an interrupt before any money moves; the state is saved by a checkpointer, a person sees the order, amount and reason, and the graph resumes with their decision. I cap the steps with a recursion limit, keep side effects after the approval and idempotent, use a database checkpointer with a thread id per conversation, and log every step. Unit tests use a scripted fake model; whether the model picks the right tools is measured separately with evals.
Clean up
InMemorySaver stores nothing on disk, so there is nothing to clear. graph.md is generated; delete it any time, show_graph.py writes it again. Keep the project: the MCP lab exposes tools like these to any client, and the evals lab measures how well the agent picks them.
rm -f graph.mdrm -f graph.mdRemove-Item graph.md -ErrorAction SilentlyContinue Practice
No model needed: these run in your browser and check your answer.
Write the add_messages reducer
LangGraph merges what a node returns into the state with a reducer. Write merge_messages(left, right) for messages as dicts with an "id" and a "content": return a new list where each message in right either replaces the message in left with the same id (in its place) or is appended at the end. Do not change left. If right has the same id twice, the later one wins. The starter just joins the lists, so a reply with an existing id shows up twice.
def merge_messages(left, right):
# left: the messages already in the state; right: the messages a node returned
return left + right
old = [{"id": "1", "content": "Where is A1002?"}, {"id": "2", "content": "Let me check."}]
print(merge_messages(old, [{"id": "2", "content": "It has shipped."}]))
Hint
Copy `left` with `list(left)`. Keep a dict from id to position in the copy. For each message in `right`: if its id is in the dict, overwrite that position; otherwise append it and record its new position.
A tiny graph runner with a step limit
Write the core of what compile() gives you. run_graph(nodes, routes, start, state, limit): nodes maps a name to a function that takes the state and returns a dict of changes; routes maps a name to a function that takes the new state and returns the next node's name, or "END". Starting at start, run a node, merge its changes into the state ({**state, **changes}), ask its route where to go, and repeat. Return the state at "END". Run at most limit nodes; if that is not enough, raise RecursionError (LangGraph's GraphRecursionError is a subclass of it). The starter silently returns instead.
def run_graph(nodes, routes, start, state, limit):
# nodes: {name: function(state) -> dict of changes}
# routes: {name: function(state) -> next node name, or "END"}
current = start
for _ in range(limit):
state = {**state, **nodes[current](state)}
nxt = routes[current](state)
if nxt == "END":
return state
current = nxt
return state # the limit ran out: what should happen here instead?
nodes = {"count": lambda s: {"n": s["n"] + 1}}
routes = {"count": lambda s: "END" if s["n"] >= 3 else "count"}
print(run_graph(nodes, routes, "count", {"n": 0}, limit=10))
Hint
Loop with `for _ in range(limit):` around the run-merge-route steps and `return state` when the route says `"END"`. If the loop finishes without returning, the limit ran out: `raise RecursionError(...)` after the loop.
The full project
Every file from this lab, as it is after the last step.