LangGraph: Agents as Graphs
Generative & Agentic AI · Agent Frameworks & Protocols · Advanced · 30 min
Model an agent as a state machine: typed state with reducers, nodes, conditional edges and loops, a recursion limit, checkpointers for memory and resume, human approval with interrupts, streaming and subgraphs, then ship it on Bedrock AgentCore Runtime.
A board game. The board is the graph, the squares are nodes, and the arrows tell you where to go next. Some squares have a sign: roll the dice, and the number picks the arrow. After every move you photograph the board, so if the game is interrupted you can set it up again exactly as it was.
The idea in everyday words
Think of a hospital patient's chart. Every department (triage, X-ray, the doctor) reads the chart, adds its notes and hands it on. A rule on the chart decides the next stop: 'if the X-ray shows a fracture, go to the cast room, otherwise go home'. The chart is the state, the departments are nodes, the rules are edges, and the photocopy made after every visit is the checkpoint that lets a new nurse pick up exactly where the last one stopped.
Why a graph? From a loop to a state machine
A chain (previous lesson) is a straight line: A then B then C. An agent is not a straight line. It loops: the model asks for a tool, the tool runs, the model looks again, and maybe asks for another tool. Real workflows also branch (refunds over $200 need a manager), pause (wait for a human) and resume hours later.
You could write all of that as a while loop with ifs (you did, in Build a ReAct Agent from Scratch). LangGraph makes the same thing explicit as a graph:
| Piece | What it is | Hospital version |
|---|---|---|
| State | one shared dict every node reads and updates | the patient's chart |
| Node | a function: state in, a partial update out | a department |
| Edge | where to go next, always | "after triage, go to the doctor" |
| Conditional edge | a function that reads the state and picks the next node | "fracture? cast room : home" |
| START / END | the entry and the exit | admission and discharge |
| Checkpointer | saves the state after every step | the photocopy of the chart |
Execution moves in super-steps: the nodes that are ready run (in parallel if there are several), their updates are merged into the state, the edges pick the next nodes, and a checkpoint is saved. The run ends when nothing is left to run.
When to use which: create_agent (LangChain) when the standard model-calls-tools loop is enough; LangGraph directly when you need your own steps, branches, approvals or several agents. Both run on the same engine, so you can start with one and move to the other.
Key idea: an agent is a state machine. Drawing it as a graph makes every possible path visible, testable and resumable.
State, reducers, nodes and edges
The state is a TypedDict. Each key can have a reducer: a rule for merging a node's update into the current value. No reducer means overwrite. operator.add on a list means append.
import operator
from typing import Annotated
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
class State(TypedDict):
messages: Annotated[list, operator.add] # reducer: append
route: str # no reducer: overwrite
def agent(state: State):
# call the model here; return ONLY the keys you change
return {"messages": ["AI: call get_weather(Paris)"], "route": "tools"}
def tools(state: State):
return {"messages": ["Tool: 18C, sunny"]}
def pick_next(state: State) -> str: # the conditional edge
return state["route"]
builder = StateGraph(State)
builder.add_node("agent", agent)
builder.add_node("tools", tools)
builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", pick_next, {"tools": "tools", "end": END})
builder.add_edge("tools", "agent") # the loop back
graph = builder.compile()
graph.invoke({"messages": ["User: What is the weather in Paris?"]})
Nodes return partial updates, not the whole state. The graph merges them with the reducers. Here is exactly what a reducer does, in plain Python:
import operator
state = {"messages": ["User: hi"], "route": "agent"}
update = {"messages": ["AI: hello"], "route": "end"}
reducers = {"messages": operator.add}
for key, value in update.items():
if key in reducers:
state[key] = reducers[key](state[key], value) # append
else:
state[key] = value # overwrite
print(state)
For chat agents, LangGraph ships MessagesState: a state with one messages key whose reducer add_messages appends new messages and replaces a message with the same id (useful for edits). The path map in add_conditional_edges ({"tools": "tools", "end": END}) documents every possible route and lets the graph be drawn and checked; a router returning a value with no route is an error, not a silent exit.
Key idea: nodes say what changed, reducers decide how changes merge, and edges decide what runs next.
The ReAct loop as a graph, and the recursion limit
The classic tool-calling agent is two nodes and a loop:
START → agent ──(asked for a tool?)──yes──→ tools ─┐
↑ │
└────────────────────────────────────────┘
└──no──→ END
With a real model on Amazon Bedrock and the prebuilt helpers:
from langchain.chat_models import init_chat_model
from langgraph.graph import StateGraph, MessagesState, START
from langgraph.prebuilt import ToolNode, tools_condition
llm = init_chat_model("<bedrock model id>", model_provider="bedrock_converse").bind_tools(tools)
def call_model(state: MessagesState):
return {"messages": [llm.invoke(state["messages"])]}
builder = StateGraph(MessagesState)
builder.add_node("agent", call_model)
builder.add_node("tools", ToolNode(tools)) # runs every tool call in the last message
builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", tools_condition) # → "tools" or END
builder.add_edge("tools", "agent")
graph = builder.compile()
A loop needs a guard. If the model keeps asking for tools, the graph would run forever (and you pay for every call). LangGraph counts super-steps and raises GraphRecursionError when a run exceeds the recursion limit. Recent versions use a very high default (older releases used 25), so set your own small limit for each call:
graph.invoke(inputs, config={"recursion_limit": 12}) # a top-level config key
Catch the error and return a friendly "I could not finish" instead of a stack trace. Combine it with the guards from the ReAct lesson: a step budget, a token or cost budget, and detecting the same tool call repeated.
Key idea: every cycle in a graph needs a way out: a condition that ends it, plus a hard limit for when the condition never comes true.
Checkpoints, memory, human approval and streaming
Compile the graph with a checkpointer and LangGraph saves a snapshot of the state at every super-step, grouped by a thread id (one conversation or one job):
from langgraph.checkpoint.memory import InMemorySaver
graph = builder.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "user-42-chat-7"}}
graph.invoke({"messages": [{"role": "user", "content": "Hi, I'm Ada"}]}, config)
graph.invoke({"messages": [{"role": "user", "content": "What's my name?"}]}, config) # remembers
graph.get_state(config) # the latest snapshot: values, next nodes, tasks
graph.get_state_history(config) # every snapshot, newest first ("time travel")
What checkpoints give you: memory across turns, resume after a crash (completed steps are not redone), time travel (replay from an older checkpoint) and human-in-the-loop. InMemorySaver is for tests; in production use a durable store. On AWS the langgraph-checkpoint-aws package provides DynamoDBSaver (DynamoDB, with large payloads offloaded to S3) and AgentCoreMemorySaver (Amazon Bedrock AgentCore Memory, keyed by actor_id and thread_id); PostgresSaver on Amazon Aurora PostgreSQL also works. Long-term facts that cross threads go in a store (LangGraph's store interface) or AgentCore Memory's long-term records.
Human approval. Inside a node, interrupt() pauses the run and saves it. Later you resume the same thread with Command(resume=...), and that value becomes the return value of interrupt():
from langgraph.types import interrupt, Command
def approve_refund(state):
ok = interrupt({"question": "Refund $250 for order A1?"}) # pauses here
return {"approved": ok}
graph.invoke({"order": "A1", "amount": 250}, config) # stops at the interrupt
graph.invoke(Command(resume=True), config) # a manager clicked Approve
One trap: on resume the node starts again from its first line. Code before interrupt() runs twice, so never charge a card or send an email before it: do side effects after the approval, or in the next node, and make them idempotent. (interrupt_before=["tools"] at compile time is a static breakpoint, mainly for debugging.)
Streaming shows progress while the agent works: graph.stream(inputs, config, stream_mode="updates") yields each node's update as it finishes; "values" yields the full state after each step; "messages" yields LLM tokens as they are generated; "custom" carries your own progress events.
Key idea: the checkpointer turns a function call into a durable, pausable, inspectable process.
Subgraphs, multi-agent, and shipping on AWS
Subgraphs. A compiled graph can be a node in another graph. Build a "research" graph and a "writer" graph, test each alone, then compose them. With subgraphs=True on stream you also see the inner steps.
Multi-agent. Common shapes (see Multi-Agent Systems): a supervisor node that routes to specialist agents (each one a node or subgraph), handoffs where a node returns Command(goto="billing_agent", update={...}) to change the state and jump in one step, and fan-out with Send to run one node per item in parallel (map-reduce) and merge the results with a reducer.
Deploying on Amazon Bedrock AgentCore Runtime. AgentCore hosts any framework. Wrap the compiled graph in an entrypoint:
from bedrock_agentcore.runtime import BedrockAgentCoreApp
app = BedrockAgentCoreApp()
graph = builder.compile(checkpointer=checkpointer) # e.g. AgentCoreMemorySaver
@app.entrypoint
def invoke(payload, context):
config = {"configurable": {"thread_id": context.session_id, "actor_id": payload["user_id"]},
"recursion_limit": 12}
out = graph.invoke({"messages": [{"role": "user", "content": payload["prompt"]}]}, config)
return {"result": out["messages"][-1].content}
app.run()
Package it as a container (the AgentCore starter toolkit CLI can configure, build and deploy it; check the docs for the current commands), give the runtime an IAM role that may call Bedrock, and call it with a runtime session id. Each session runs in its own isolated microVM; durable state lives in the checkpointer, not in local variables. Add AgentCore Gateway for tools, Identity for OAuth, and Observability for traces. (In production, take the user id from the validated token, not from the payload.)
Which one?
| Option | You write | Control | Pick it when |
|---|---|---|---|
| Hand-written loop | everything | total | learning, or a tiny agent with no extra dependencies |
| Amazon Bedrock Agents | config: instructions, action groups, KBs | the managed loop, with prompt overrides | a standard task agent, little code, AWS-managed |
| Strands Agents (AWS, open source) | a model, a prompt, tools; the model drives the loop | high, code-first | model-driven agents on AWS, quick to build |
| LangGraph | the graph: state, nodes, edges | the most explicit | fixed steps mixed with LLM steps, branches, approvals, resume, many agents |
Strands and LangGraph agents both run on AgentCore Runtime. Elsewhere: Google Vertex AI Agent Engine and Azure AI Foundry Agent Service host agents (including LangGraph ones); LangChain also offers its own hosted deployment service.
Key idea: pick the least machinery that gives you the control you need, and keep state in a durable checkpointer so the host can scale and restart freely.
Step by step
- Start:
State: messages = ["User: What is the weather in Paris?"]. Entry node: agent. Recursion limit 10. messages has the append reducer; route has none (overwrite).
- agent runs:
Its first scripted reply: messages += ["AI: call get_weather(Paris)"], route = "tools". The state is merged and checkpoint 1 is saved.
- Conditional edge:
The edge after agent reads state.route = "tools" and looks it up in the path map {tools → tools, end → END}. Next node: tools.
- tools runs:
messages += ["Tool: 18C, sunny"]. route is not in the update, so it stays "tools". Checkpoint 2. The plain edge tools → agent closes the loop.
- agent again:
Second visit, second scripted reply: messages += ["AI: It is 18C and sunny in Paris."], route = "end". Checkpoint 3.
- Done:
route = "end" maps to END. Status done, path [agent, tools, agent], 4 messages, 3 checkpoints. With interrupt_before = [tools] the run would have stopped before tools, waiting for approval.
Code example
# A mini StateGraph: the ideas behind LangGraph in plain Python.
# Nodes are functions that return partial updates; reducers merge them; edges route.
import operator
class MiniGraph:
def __init__(self, reducers):
self.reducers, self.nodes, self.edges = reducers, {}, {}
def add_node(self, name, fn):
self.nodes[name] = fn
def add_edge(self, src, dst):
self.edges[src] = lambda state: dst
def add_conditional_edges(self, src, router, path_map):
def pick(state):
key = router(state)
if key not in path_map:
raise ValueError("no route for %r from %s" % (key, src))
return path_map[key]
self.edges[src] = pick
def invoke(self, state, entry, recursion_limit=10):
checkpoints, node = [], entry
while node != "END":
if len(checkpoints) == recursion_limit:
raise RuntimeError("GraphRecursionError: hit %d steps" % recursion_limit)
for key, value in self.nodes[node](state).items():
merge = self.reducers.get(key)
state = {**state, key: merge(state[key], value) if merge else value}
checkpoints.append((node, state)) # a new dict each step, so this is a snapshot
node = self.edges[node](state)
return state, checkpoints
# A fake model: asks for the weather tool once, then answers.
def agent(state):
if any(m.startswith("Tool:") for m in state["messages"]):
return {"messages": ["AI: It is 18C and sunny in Paris."], "route": "end"}
return {"messages": ["AI: call get_weather(Paris)"], "route": "tools"}
def tools(state):
return {"messages": ["Tool: 18C, sunny"]}
g = MiniGraph(reducers={"messages": operator.add})
g.add_node("agent", agent)
g.add_node("tools", tools)
g.add_conditional_edges("agent", lambda s: s["route"], {"tools": "tools", "end": "END"})
g.add_edge("tools", "agent")
final, saved = g.invoke({"messages": ["User: Weather in Paris?"]}, entry="agent")
print("path:", [node for node, _ in saved])
print("last message:", final["messages"][-1])
print("checkpoint 1 had", len(saved[0][1]["messages"]), "messages")
# A model that never stops asking for tools: the recursion limit saves us.
g.add_node("agent", lambda s: {"messages": ["AI: search again"], "route": "tools"})
try:
g.invoke({"messages": ["User: find everything"]}, entry="agent", recursion_limit=5)
except RuntimeError as e:
print(e)Complexity
- Time: O(limit × u): at most `limit` node runs, each merging an update of size u (copying the state for its checkpoint)
- Space: O(limit × s): one snapshot of the state (size s) per step; real checkpointers store only what changed
Interview tips
Explain LangGraph's model: state with reducers, nodes, edges, conditional edges, super-steps. How is the ReAct loop expressed as a graph?
How do you stop an agent graph from looping forever, and what do you return to the user when it does hit the limit?
What does a checkpointer give you (memory, resume, time travel, human-in-the-loop) and what would you use on AWS (DynamoDBSaver, AgentCoreMemorySaver, Postgres on Aurora)?
Walk through a human approval step with interrupt and Command(resume=...). What happens to code that runs before the interrupt?
LangGraph vs Bedrock Agents vs Strands Agents vs a hand-written loop: how would you choose for a refund workflow with a manager approval, and where would you host it?
Challenge: Run a tiny StateGraph
Write run_graph(graph, state, limit): a mini LangGraph runner.
graph is a dict:
"entry": the first node."nodes": node name → a list of scripted updates (a fake LLM). The k-th time a node runs it returns update number k; after the list runs out it repeats its last update. An empty list means{}."edges": node name → either a node name (always go there) or a conditional edge{"key": k, "map": {...}}: readstate[k]and go tomap[state[k]]."END"ends the run."reducers"(optional): key →"append"(the value is a list; add it to the end of the current list,[]if missing). Any other key is overwritten."interrupt_before"(optional): node names to pause before.
Loop until the current node is "END". Before running a node, check in this order:
- The node is not in
nodes→ raiseValueError. - Already
limitnodes have run → stop with status"recursion_limit". - The node is in
interrupt_before→ stop with status"interrupted".
Then run it: merge its update, add its name to path, and save a copy of the state in checkpoints. Follow its edge: no edge, or a conditional value missing from the map → raise ValueError.
Return {"status", "next", "path", "state", "checkpoints"}, where next is the node that was about to run (None when done). Do not change the caller's state.
graph = {"entry": "a", "nodes": {"a": [{"x": 1}], "b": [{"x": 2}]},
"edges": {"a": "b", "b": "END"}}
run_graph(graph, {}, 5)
# → {"status": "done", "next": None, "path": ["a", "b"], "state": {"x": 2},
# "checkpoints": [{"x": 1}, {"x": 2}]}
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- LangGraph docs: Graph API (state, reducers, edges, recursion limit) (Medium)
- LangGraph docs: Interrupts (human-in-the-loop) (Medium)
- LangGraph docs: Persistence and checkpointers (Medium)
- AWS docs: Use any agent framework on AgentCore Runtime (LangGraph example) (Hard)
More in Agent Frameworks & Protocols
Previous: LangChain Essentials · Next: Agent2Agent (A2A) Protocol