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

1 / 8

0 of 8 steps done

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

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.

Run
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"
You should see
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.

Run
uv --version
You should see
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.

Run
ollama --version
You should see
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.

Run
ollama pull llama3.2:3b
You should see
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).

Run
ollama show llama3.2:3b
You should seeyour text will differ: the model writes it
  Model
    architecture        llama
    parameters          3.2B
    ...

  Capabilities
    completion
    tools
  ...
1

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 @tool decorator.
  • langchain-openai: ChatOpenAI, a model class that talks to any OpenAI-compatible API, Ollama included. It uses the same openai SDK 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.

.env
# 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
  1. Ollama's OpenAI-compatible API, under /v1. Tool calls use the same endpoint as a plain chat call.line 2
  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
config.py
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"),
    )
  1. load_dotenv() copies .env into os.environ. Variables already set in your shell win, which is what you want on a server.line 6
  2. frozen=True makes the settings read-only, like a Java record.line 9
.gitignore
.venv/
__pycache__/
.env
graph.md
  1. Never commit .env: one day it holds a real key.line 3
  2. Step 3 writes a diagram of the graph to graph.md. It is generated, so it stays out of git.line 4
llm.py
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,
    )
  1. ChatOpenAI is 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
  2. A function, not a global: the real program calls it, tests never do (they pass a fake model instead, step 8).line 6
  3. The same three settings as every lab. Changing .env moves the agent to a hosted API with no code change.line 9
  4. Temperature 0: the most likely token every time. Which tool to call should be predictable, not creative.line 12
  5. 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
  6. Retries network errors, 429 and 5xx, as in lab 1.line 14
Run
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
You should seeyour text will differ: the model writes it
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.
2

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_policy first. 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.

store.py
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
  1. 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
  2. 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
  3. 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
tools.py
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]
  1. tool is a decorator: writing @tool above a function replaces the function with a tool object built from it, like an annotation that also wraps the method.line 3
  2. 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
  3. The policy as ordinary code, used by both refund tools. One function, one set of rules, easy to unit test.line 13
  4. any(...) is true if at least one refund has this order id, like stream().anyMatch(...) in Java.line 18
  5. date.fromisoformat("2026-11-08") parses the date; subtracting two dates gives a timedelta, and .days is its length in days.line 22
  6. From here on, lookup_order is a StructuredTool object, not a plain function. Call it with lookup_order.invoke({"order_id": "A1001"}).line 28
  7. The docstring becomes the description the model reads. "like A1001" shows the model what an id looks like.line 30
  8. {"order_id": key, **order} builds a new dict: the id first, then every key of order spread in, like {orderId, ...order} in JavaScript.line 34
  9. Descriptions can carry instructions too: "Call it before issue_refund" helps the model plan the order of calls.line 39
  10. Never trust that the model checked first: the tool checks again, every time.line 46
  11. Python allows chained comparisons: 0 < amount <= max means 0 < amount and amount <= max. It stops a model from refunding more than was paid, or a negative amount.line 49
  12. The side effect: money moves. For now it happens with nobody asking. Step 7 puts a person in front of this line.line 51
  13. The list the graph uses, in the order the model sees them.line 55
try_tools.py
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))
  1. convert_to_openai_tool builds the exact {"type": "function", ...} entry that goes into the request as tools=. bind_tools (step 3) calls it for every tool.line 3
  2. .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 7
  3. type(x).__name__ is the class name, like x.getClass().getSimpleName() in Java.line 12
  4. TOOLS[2] is issue_refund: the schema shows the three required arguments the model must send.line 13
Run
uv run try_tools.py
You should see
{'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"
    }
  }
}
Why this way? Compare the printed schema with lab 4's 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, call lookup_order.invoke({"order_id": "A1001"}), not lookup_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 @tool function needs a docstring: it is the description the model reads. Add a """...""" line right under the def.
3

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) or tool_calls.
  • tools is LangGraph's ready-made ToolNode. It reads the tool calls in the last AIMessage, runs each tool, and returns one ToolMessage per call, carrying the matching tool_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 = [...] and messages.append(...): the messages state field and its add_messages reducer.
  • 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 with tools_condition.
  • for request in range(1, max_steps + 1) and TooManySteps: the recursion_limit setting and GraphRecursionError (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.

agent.py
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)
  1. TypedDict and Annotated come from the standard typing module. On Python 3.12 nothing extra is needed.line 1
  2. LangChain's message classes are lab 4's role dicts as objects: SystemMessage is role: "system", HumanMessage is "user", AIMessage is "assistant", ToolMessage is "tool". AnyMessage is the type that means "any of them".line 3
  3. START and END are the graph's entry and exit. StateGraph is the builder.line 4
  4. ToolNode and tools_condition are the two ready-made pieces that replace most of lab 4's loop.line 6
  5. The state's shape: a dict with one key, messages. A node may return just the keys it changes.line 16
  6. Annotated[T, extra] is type T with extra information attached. Python ignores it; LangGraph reads add_messages from it and uses it to merge updates into this key.line 17
  7. Called by ToolNode when 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 by ToolNode itself.)line 20
  8. The model is a parameter (dependency injection): the real program passes ChatOpenAI, tests pass a fake. checkpointer is for memory, step 6.line 25
  9. bind_tools returns a new object that sends the three tool schemas with every request. The original model is unchanged.line 26
  10. The agent node. It is defined inside build_graph, so it can use model_with_tools from the enclosing function: a closure, like a Java lambda capturing a local variable.line 28
  11. The system message is added on every call but never stored in the state, so it cannot pile up. invoke sends one chat request and returns an AIMessage.line 29
  12. Return only the change. The reducer appends reply to the existing messages.line 30
  13. A node is a name plus a function. The name is what edges and the printout refer to.line 33
  14. The conditional edge: after agent, call tools_condition(state) and go where it says, "tools" or END.line 36
  15. The back edge. Without it the graph would stop after running the tools, and the model would never see the results.line 37
  16. compile() validates the graph and returns the runnable agent.line 38
show_graph.py
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")
  1. Building the graph sends nothing: make_model() only stores settings, and bind_tools only remembers the tools. Requests happen in invoke and stream.line 6
  2. get_graph() returns a description of the compiled graph: its nodes and edges.line 7
  3. g.nodes is a dict keyed by node name; ", ".join(...) over a dict joins its keys.line 9
  4. Python's conditional expression: a if condition else b is condition ? a : b in Java.line 11
  5. 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
Run
uv run show_graph.py
You should see
nodes: __start__, agent, tools, __end__
  __start__ -> agent  (always)
  agent -> __end__  (conditional)
  agent -> tools  (conditional)
  tools -> agent  (always)
diagram written to graph.md
Why this way? Read the edges as the loop from lab 4: 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 node tool``
A name in add_edge does not match a name in add_node. Names are plain strings, so a typo like "tool" instead of "tools" is only found by compile().
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.
4

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.

show.py
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)}")
  1. 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
  2. One entry per node that finished in this step. .items() gives (key, value) pairs, like entrySet() in Java.line 13
  3. isinstance(x, C) is x instanceof C. msg.tool_calls is a list of dicts with name, args and id. LangChain already parsed the arguments from the JSON string for you; in lab 4 you called json.loads yourself.line 15
  4. json.dumps(call["args"]) prints the arguments as JSON, the way the model sent them.line 17
  5. ToolNode stores the tool name on each ToolMessage, and turns the dict the tool returned into JSON text: that is why you see true and null instead of Python's True and None.line 21
main.py
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}")
  1. At most 12 steps per run: six model requests and five tool rounds in between.line 12
  2. sys.argv is the command-line arguments. With none, ask about A1002.line 14
  3. The run's settings. recursion_limit is the step limit; step 6 adds more keys here.line 16
  4. stream is 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
  5. The step limit was hit: say so clearly instead of printing a stack trace.line 21
  6. Timeout before connection error on purpose: APITimeoutError is a subclass of APIConnectionError, and Python uses the first except that matches.line 23
  7. Ollama answers HTTP 400 when the model has no tool support; the SDK raises it as BadRequestError.line 29
Run
uv run main.py "Where is my order A1002?"
You should seeyour text will differ: the model writes it
[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.
Why this way? Three lines, three steps, and the same three moments you printed by hand in lab 4: the model asks, your code runs the tool, the model answers from the result. Now try 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.
5

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:

  1. 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".
  2. Temperature 0, already set in llm.py, so the model does not wander off the most likely choice.
  3. Check in code. needs_lookup asks: 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.

agent.py 18 new or changed lines
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)
  1. Name the tool and the situation. "Never guess order details" tells the model what not to do.line 13
  2. The nudge: a direct instruction, sent only when the first reply skipped the tool.line 17
  3. A compiled regular expression, like Pattern.compile in Java. r"..." is a raw string, so \b reaches the regex as written: a word boundary. [A-Z]\d{4} is one letter and four digits, like A1001.line 18
  4. enumerate gives (index, item) pairs. max(...) over the indexes of the HumanMessages is the position of the newest one.line 32
  5. .search finds the pattern anywhere in the text and returns None when there is no match.line 33
  6. messages[last_user + 1 :] is every message after it (a slice). any(...) is true if one of them is a ToolMessage.line 34
  7. Build the prompt once, so the retry can reuse it.line 42
  8. reply.tool_calls is an empty list when the model answered in text, and an empty list is false in Python.line 44
  9. 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
Run
uv run main.py "Hi, is my order A1003 delivered yet?"
You should seeyour text will differ: the model writes it
[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.
Why this way? The pattern generalises: when the model's output must rest on data, check in code that the data was fetched, and retry with a specific instruction when it was not. It costs one extra request in the rare bad case and nothing in the normal one. Prompt rules make mistakes rarer; code checks make them visible.
Stuck on this step?
The model calls lookup_order for 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, not llama3.2:1b, which does this more often.
6

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().

main.py 12 new or changed lines
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")
  1. The in-memory checkpointer. A database-backed one has the same interface.line 5
  2. One turn: stream the run for one new customer message. The config carries the thread id, so LangGraph loads the history first.line 16
  3. 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
  4. Pass the checkpointer to compile() through build_graph. Create it once and reuse it: a new InMemorySaver is an empty memory.line 22
  5. configurable holds per-run values the graph reads; thread_id is the one checkpointers use. A real app would use a conversation or user id here.line 23
  6. Read the saved state back: the full message list of this thread after the last turn.line 40
Run
uv run main.py "Where is my order A1002?" "How much did it cost?"
You should seeyour text will differ: the model writes it
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
Why this way? The second turn needed no tool: the 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 (same thread_id) and the same compiled graph. A new InMemorySaver() 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.
7

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.

tools.py 6 new or changed lines
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]
  1. interrupt pauses the graph from inside any node or tool that runs in it.line 4
  2. A docstring can span lines. The model reads this description too, so it knows a person is involved.line 47
  3. Runs before the pause **and again** after it, so it must only read. refund_decision only reads.line 48
  4. 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
  5. Anything but an explicit "approve" means no. The tool result tells the model what to say to the customer.line 54
  6. Money moves only here, after a person said yes.line 56
main.py 21 new or changed lines
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")
  1. Command is how you send instructions into a paused graph; Command(resume=value) continues it.line 7
  2. request is the dict that issue_refund passed to interrupt().line 18
  3. input(prompt) prints the prompt and waits for a line from the keyboard, like Scanner.nextLine() in Java.line 20
  4. EOFError: there is no more input, for example echo y | was used up or nothing was piped. No answer is a no.line 21
  5. isatty() 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
  6. The first run starts with the new message. After a pause, inputs becomes a Command instead.line 29
  7. A paused run ends with this special update instead of a node name.line 33
  8. A tuple of Interrupt objects, one per pause; this agent pauses for one refund at a time. .value is the dict from interrupt().line 34
  9. The run ended normally: the turn is over.line 38
  10. Resume the same thread (config still has customer-42) with the person's answer, and loop to stream the rest of the run.line 39
Run
echo y | uv run main.py "Please refund order A1001, the headphones arrived broken"
You should seeyour text will differ: the model writes it
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
Why this way? Run it again with 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 same thread_id.
The approval never shows; the agent says it refunded anyway
Look for an [tools] issue_refund line. 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 with refunded and no approval line before it, your tools.py is still the step 2 version.
Windows: echo y | ...
It works the same in PowerShell. Or leave echo y | out and type y when asked.
8

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.

conftest.py
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()
  1. A fixture is setup code pytest runs for tests. autouse=True means "for every test", like JUnit's @BeforeEach and @AfterEach in one.line 6
  2. yield hands control to the test; the lines after it run when the test is done, even if it failed.line 9
test_tools.py
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 == []
  1. Tools are called with .invoke and a dict, exactly as ToolNode calls them.line 6
  2. The plain policy function is the easiest thing to test: no tool wrapper, no graph.line 20
  3. Both of these return before interrupt() is reached, so the tool can run outside a graph. A call that got as far as interrupt() would need a running graph, which test_agent.py provides.line 29
test_agent.py
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
  1. Builds an AIMessage that asks for one tool call, as ChatOpenAI would after parsing the model's reply. **args collects keyword arguments into a dict.line 13
  2. The fake model: just the two methods the graph uses.line 18
  3. The real bind_tools returns a new object; returning self is enough here, and it records which tools were bound.line 28
  4. Records a **copy** of the prompt, then returns the next scripted reply, like queue.poll().line 31
  5. The class name of each message, for easy comparisons like ["HumanMessage", "AIMessage", ...].line 36
  6. The system prompt is sent first on every request.line 44
  7. The four messages of a one-tool run: question, tool call, tool result, answer.line 50
  8. ToolNode turned the unknown tool into an error message for the model instead of raising.line 59
  9. The second prompt ends with the nudge, and the invented first reply never reaches the state.line 70
  10. A model that never stops: 20 tool calls queued, but a limit of 6 steps stops it after 3 requests.line 78
  11. 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
  12. Resume with the same config. The tool runs again from its start, interrupt() returns "approve", and the refund happens.line 93
  13. The second request on thread sam includes the first turn; the request on thread other starts fresh.line 113
Run
uv run pytest -q
You should see
..............                                                           [100%]
14 passed in 0.40s
Why this way? These tests check your code: the policy, the wiring of the graph, the nudge, the limit, the pause and the memory. Whether 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 warnings with DeprecationWarning: 'asyncio.iscoroutinefunction' is deprecated from langsmith
Harmless: uv picked a newer Python than 3.12 (look for Using CPython 3.15 in the uv sync output), and a LangChain dependency still calls a function that Python 3.15 deprecates. Your code is fine. To match this lab exactly, run uv python pin 3.12 in the project folder, then uv 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.prompts to see every request.
ModuleNotFoundError: No module named 'agent'
Run pytest from the project folder (where agent.py is) with uv 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.

Test
uv run pytest -q && echo y | uv run main.py "My order is A1001." "The headphones broke. Can I get a refund?"
You should see
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. PostgresSaver keeps 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 calls Command(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 interrupt payload), 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_limit per 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.

Run
rm -f graph.md

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.

Exercise
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.

Exercise
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.

Download Python project (.zip)