LangChain and LangGraph

One library gives you a ready agent. The other lets you draw the process yourself. They share the same engine.

BeginnerIntermediateExpert · 13 min read · Last updated:

In short

LangChain provides model and tool integrations and a ready-made agent, built with create_agent and shaped by middleware. LangGraph is the runtime underneath: you describe state, nodes and edges, and it saves checkpoints so that runs can pause and resume. Start with create_agent when a tool-using loop is enough, and draw a graph when the process has steps you want to control.

What you will learn: the main components, building an agent with limits and approval, writing a graph, how state updates combine, persistence and interrupts, testing offline and planning upgrades.
Prerequisites: The Agent Loop: Observe, Reason, Plan, Act, Reflect and Graphs, State Machines, Parallelism and Sagas.

Versions used

Checked in November 2026 and run with langchain 1.5.2 and langgraph 1.2.24 in Python. The examples use a scripted model or no model, so they run without an API key. Both projects also publish JavaScript packages, which these listings do not cover.

Beginner Components and a first agent

How the pieces relate

Your applicationtools, prompts, rules
LangChaincreate_agent, middleware, messages
LangGraphstate, nodes, checkpoints, interrupts
Integration packagesmodel providers, stores, retrievers
You may use LangGraph without LangChain's agent, and drop down to it when needed.
ComponentWhat it is
Chat modelA common interface over providers' conversational models
MessageA typed item: human, AI, system or tool result
ToolA function with a name, description and input schema
AgentThe loop that calls the model and tools
MiddlewareCode that runs around model and tool calls
CheckpointerSaves the state of a conversation or run
StoreKeeps information across separate threads
Older tutorials

LangGraph 1.0 deprecated its create_react_agent helper in favor of LangChain's create_agent. Much material online predates this and older chain classes. Check the version a tutorial was written for before copying it.

An agent with a limit and an approval

The agent below can look up an order and send an email. One middleware caps model calls for each run. Another pauses before the email tool so a person can decide. A checkpointer is required, because a paused run has to be saved somewhere.

from langchain.agents import create_agent
from langchain.agents.middleware import (HumanInTheLoopMiddleware,
                                         ModelCallLimitMiddleware)
from langchain_core.language_models.fake_chat_models import (
    FakeMessagesListChatModel)
from langchain_core.messages import AIMessage
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command


class ScriptedModel(FakeMessagesListChatModel):
    """Offline stand-in that accepts tools and replays set replies."""

    def bind_tools(self, tools, **kwargs):
        return self


def order_status(order_id: str) -> str:
    """Look up the delivery status of one order."""
    return f"{order_id}: delayed, due in 3 days"


def send_email(to: str, body: str) -> str:
    """Send an email to a customer."""
    print("  EMAIL SENT to", to)
    return "sent"


def call(name, call_id, **args):
    return AIMessage(content="", tool_calls=[
        {"name": name, "args": args, "id": call_id}])


model = ScriptedModel(responses=[
    call("order_status", "c1", order_id="A-17"),
    call("send_email", "c2", to="sam@example.com", body="3 day delay"),
    AIMessage(content="Sam has been told about the delay."),
])

agent = create_agent(
    model,
    tools=[order_status, send_email],
    system_prompt="Help with orders. Facts come from tools only.",
    middleware=[
        ModelCallLimitMiddleware(run_limit=5, exit_behavior="end"),
        HumanInTheLoopMiddleware(interrupt_on={"send_email": True}),
    ],
    checkpointer=InMemorySaver(),
)

config = {"configurable": {"thread_id": "case-1"}}
result = agent.invoke({"messages": "Tell Sam about order A-17"}, config)
request = result["__interrupt__"][0].value["action_requests"][0]
print("waiting for approval:", request["name"], request["args"]["to"])

result = agent.invoke(
    Command(resume={"decisions": [{"type": "approve"}]}), config)
for message in result["messages"]:
    calls = [c["name"] for c in getattr(message, "tool_calls", [])]
    print(f"{message.type:6} {message.content or calls}")

Output:

waiting for approval: send_email sam@example.com
  EMAIL SENT to sam@example.com
human  Tell Sam about order A-17
ai     ['order_status']
tool   A-17: delayed, due in 3 days
ai     ['send_email']
tool   sent
ai     Sam has been told about the delay.

The email is not sent until the second call, which resumes the same thread_id with an approval. The printed messages show the full record: the request, each tool call, each result and the final answer. Inspecting that list is the first debugging step for any agent.

What a reviewer can decide

Approval is more than yes. In the version used here the human-in-the-loop middleware defines four decision types: approve, edit the arguments, reject with a reason, and respond, where the person supplies the reply. You choose which are allowed for each tool. Whatever you allow, show the exact arguments, record who decided, and validate edited values as strictly as model output. See Human-in-the-Loop and Approval Gates.

Writing tools the model can use well

In the example, a plain function with type hints and a docstring became a tool. The model sees only the name, the description and the argument schema, so vague wording produces wrong calls. Say what the tool does, when to use it, what each argument means and what it returns when nothing is found.

WeakBetter
get_data(x)order_status(order_id) with the identifier format described
Returns a full database rowReturns only the fields needed for the task
Raises a stack traceReturns a short error the model can act on
Takes a user identifier from the modelTakes identity from trusted runtime context

The last row is a security rule. Values such as the current user or tenant belong in the runtime context that your server sets, not in arguments the model can invent.

Structured answers

When other code consumes the result, ask for a typed response with create_agent's response_format option and still validate business rules. A response can match a schema and be wrong: a well-formed refund amount may exceed the order total. See Tool Testing and Observability for checks around tools.

Middleware

Middleware is where cross-cutting behavior goes, so tools stay simple.

NeedKind of middleware
Bound cost and loopsModel and tool call limits
Survive provider troubleModel retry and fallback
Keep context smallSummarization or context editing
Protect dataDetection and redaction of personal information
Require a personHuman in the loop
Your own ruleA custom class or hook

Order matters, since each layer sees what the others have changed. Test the combination. A retry layer around an action that is not safe to repeat can perform it twice.

Intermediate Graphs, state and persistence

When to draw a graph

An agent loop lets the model choose each next step. A graph lets you decide the structure and place model calls only where judgment is needed. Use a graph when some steps must always happen, in order, or when a path needs review.

Start
assess
routeover 500?
reviewpause for a person
pay
Small amounts go straight from the route to payment.
from typing import TypedDict

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, interrupt


class Claim(TypedDict):
    amount: int
    decision: str
    log: list


def assess(state: Claim):
    return {"log": state["log"] + ["assessed"]}


def route(state: Claim) -> str:
    return "review" if state["amount"] > 500 else "pay"


def review(state: Claim):
    print("  review node entered")  # printed again on resume
    answer = interrupt({"approve claim of": state["amount"]})
    return {"decision": answer, "log": state["log"] + ["reviewed"]}


def pay(state: Claim):
    decision = state["decision"] or "auto-approved"
    return {"decision": decision, "log": state["log"] + ["paid"]}


def after_review(state: Claim) -> str:
    return "pay" if state["decision"] == "approved" else END


builder = StateGraph(Claim)
builder.add_node("assess", assess)
builder.add_node("review", review)
builder.add_node("pay", pay)
builder.add_edge(START, "assess")
builder.add_conditional_edges("assess", route, ["review", "pay"])
builder.add_conditional_edges("review", after_review, ["pay", END])
builder.add_edge("pay", END)
graph = builder.compile(checkpointer=InMemorySaver())

for claim_id, amount in [("claim-1", 120), ("claim-2", 900)]:
    config = {"configurable": {"thread_id": claim_id}}
    state = {"amount": amount, "decision": "", "log": []}
    out = graph.invoke(state, config)
    if "__interrupt__" in out:
        print(claim_id, "paused:", out["__interrupt__"][0].value)
        print("  next node:", graph.get_state(config).next)
        out = graph.invoke(Command(resume="approved"), config)
    print(claim_id, out["decision"], out["log"])

Output:

claim-1 auto-approved ['assessed', 'paid']
  review node entered
claim-2 paused: {'approve claim of': 900}
  next node: ('review',)
  review node entered
claim-2 approved ['assessed', 'reviewed', 'paid']
The interrupted node starts again

The line "review node entered" appears twice for the second claim. On resume, LangGraph runs the whole node from its first line, and interrupt then returns the resume value. Anything placed before the interrupt therefore runs again. Put actions with effects in a later node, or make them safe to repeat.

Reading the parts

  • State is a typed record that every node can read.
  • A node is a function that returns only the keys it wants to change.
  • An edge fixes what runs next; a conditional edge chooses using a function.
  • Compile checks the structure and attaches the checkpointer.
  • A thread identifies one saved history.

How updates combine

By default a new value replaces the old one. When two nodes write the same key in one step, you need a reducer that says how to merge them. Here history appends and latest is replaced.

import operator
from typing import Annotated, TypedDict

from langgraph.graph import END, START, StateGraph


class State(TypedDict):
    latest: str                                  # last write wins
    history: Annotated[list, operator.add]       # writes are appended


def source_a(state: State):
    return {"history": ["a"]}


def source_b(state: State):
    return {"history": ["b"]}


def summarize(state: State):
    return {"latest": "+".join(sorted(state["history"]))}


builder = StateGraph(State)
for node in (source_a, source_b, summarize):
    builder.add_node(node.__name__, node)
builder.add_edge(START, "source_a")
builder.add_edge(START, "source_b")              # runs alongside a
builder.add_edge(["source_a", "source_b"], "summarize")
builder.add_edge("summarize", END)
graph = builder.compile()

for update in graph.stream({"latest": "", "history": []},
                           stream_mode="updates"):
    for node, change in sorted(update.items()):
        print(node, change)

Output:

source_a {'history': ['a']}
source_b {'history': ['b']}
summarize {'latest': 'a+b'}

The two sources run in the same step, and the summary waits for both. The summary sorts the history, so it does not depend on which branch happened to finish first. Design reducers and consumers so that order between parallel branches does not matter, or record an explicit order.

Persistence and durability

The in-memory saver is for learning and tests; everything disappears when the process ends. In production use a database-backed checkpointer, and treat its contents as sensitive data with a retention rule.

Durability modeWhen state is writtenTrade-off
exitWhen execution leaves the graphFastest; a crash mid-run can lose progress
asyncWhile the next step is runningBalance; a small window remains
syncBefore the next step startsSafest of the three; more waiting

No mode removes the gap between an external action and the record of it. Use operation keys, as described in Reliable Tool Execution and Error Recovery.

Designing state

Put in stateKeep out of state
Identifiers and decisionsSecrets and access tokens
Counters and limits usedLarge files; store a reference
References to evidenceLive connections or clients
What is pending and whyValues you can cheaply recompute

Threads and cross-thread memory

A checkpointer remembers one thread. A store holds facts that should be available in other threads, such as a user's preferred language. Decide who may read each namespace, how a person can correct or delete what is stored, and what must never be written. Agent Memory Types and Persistence gives the wider picture.

Thread identifiers are access keys

Anyone who can supply a thread identifier may continue that conversation unless your application checks ownership. Derive or verify it on the server from the signed-in user.

Expert Testing, observing and upgrading

Testing offline

Test each node as a plain function. Test routing with hand-built state. Test the whole graph with a scripted model, as above. LangChain's core package includes fake chat models; the example adds a bind_tools method so an agent can use one.

  • Each branch of every conditional edge is taken in some test
  • Resume is tested after approval, rejection and a long delay
  • A killed process resumes correctly with the real checkpointer
  • The recursion and call limits are reached on purpose and handled
  • Old saved state loads after a change to the state type

Debugging a run that went wrong

  1. Print the message list and find the first step that surprised you.
  2. Check what the model was shown at that point, including any trimming or summary.
  3. For a graph, read the saved state for the thread and see which node is next.
  4. Use the checkpoint history to compare state before and after the suspect node.
  5. Reproduce with a scripted model, then add the case to your tests.

Saved checkpoints also allow a run to be replayed or forked from an earlier point. Nodes after that point execute again, including their external calls, so replay against test services.

Illustrative failure, not a real incident

An agent emails a customer twice. The trace shows one approval. The cause is a node that sends the email and then calls interrupt to ask about a follow-up, so resuming runs the send again. Moving the send into its own node before the question, with an operation key, fixes it.

Streaming and tracing

stream returns progress while the graph runs, either whole state, updates from each node or model tokens, depending on the mode. Show users meaningful progress rather than raw internals. For traces you can use LangSmith, the vendor's hosted product, or send telemetry to other tools; check what is uploaded and where before enabling either. See Tool Testing and Observability.

Growing beyond one graph

A compiled graph can be used as a node in another graph. That lets teams own separate parts, but the boundary needs a defined input and output. Multi-agent designs are often a supervisor node that routes to subgraphs. Add agents only when separate instructions, tools or permissions justify them; see Supervisor and Orchestrator-Worker Patterns.

Upgrades and support

The projects state that their 1.0 releases are long-term support lines, and that LangGraph will avoid breaking changes until 2.0. According to the release policy, the earlier LangChain 0.3 and LangGraph 0.4 lines receive maintenance until December 2026, so projects still on them should plan to move now. Integration packages version separately, so pin them too and test provider upgrades.

Changing a graph with runs in flight

ChangeRisk to paused runs
Add an optional state keyUsually safe if code handles absence
Rename or remove a keySaved state no longer matches
Rename or remove a nodeA run waiting there cannot continue
Reorder interrupts inside a nodeResume values may match the wrong question

Version the graph, keep the old one until its runs finish, or write a migration and test it on copies of real checkpoints.

When something else fits better

If a single request handles the whole job and nothing pauses, a short loop with a provider SDK is easier to read. If your organization already runs a durable workflow engine, calling models from that engine may serve better than adding a second runtime. Choosing Frameworks: Lock-In, Upgrades and Benchmarks sets out how to compare.

Common mistakes

MistakeBetter practice
Following pre-1.0 tutorials unchangedCheck current documentation and versions
Side effects before interruptMove them to a later node or make them repeatable
In-memory saver in productionUse durable storage and test restarts
One huge state with everythingSmall typed state with references
A graph with a single agent nodeUse create_agent directly
Trusting a client-supplied thread IDCheck ownership on the server

Checklist

  • The choice between agent and graph follows from the process
  • Every run has call limits
  • Risky tools require approval with a durable checkpointer
  • Parallel writes have reducers and order does not change results
  • Interrupted nodes are safe to run twice
  • State holds no secrets and has a retention rule
  • Versions are pinned and paused runs are considered in releases

Frequently asked questions

Do I need LangChain to use LangGraph?

No. Nodes are ordinary functions and can call any model client. LangChain adds integrations and the ready-made agent.

Is a graph the same as a state machine?

They are closely related. A LangGraph graph moves between nodes while carrying shared state, and can run branches in parallel.

What happens if a node raises an error?

The run stops unless a retry policy or your code handles it. With a checkpointer you can resume from saved progress after fixing the cause.

Can I use my own database for checkpoints?

Checkpointer integrations exist for common databases, and the interface can be implemented. Test it with restarts and concurrent requests.

References and further reading

Next steps