LangChain vs LangGraph: What’s the Difference?

LangChain vs LangGraph: What's the Difference?

LangChain and LangGraph are related, but they are not competing versions of the same abstraction. LangChain provides a higher-level agent framework, model and tool integrations, and a configurable harness through create_agent. LangGraph is the lower-level orchestration runtime for workflows that need explicit state, nodes, edges, branching, loops, persistence, or interruption and resumption.

The most important current detail is that LangChain agents are built on LangGraph. Choosing LangChain does not mean giving up loops, checkpointing, or human approval. Choosing LangGraph directly means taking responsibility for more of the orchestration.

Quick fix: Start with langchain.agents.create_agent for an ordinary tool-calling agent. Drop down to a LangGraph StateGraph only when you need explicit branches, loops with your own stop conditions, or checkpointed state you control. Both examples below run on a CPU-only Linux box with a local Ollama model, no API key required.

Environment and version assumptions

Current LangChain documentation requires Python 3.10 or newer, while its quickstart recommends a Python 3.11 environment. Provider integrations are separate packages. Record resolved versions because tutorials written for earlier releases can use deprecated imports or agent constructors.

python3 --version
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install -U langchain langchain-openai langgraph
python -m pip freeze | grep -E 'langchain|langgraph'

I ran both examples on Debian 13 with Python 3.13, langchain 1.5.2, langchain-ollama 1.2.0, langgraph 1.2.24, and langchain-core 1.8.5. The LangChain agent used a local qwen2.5:1.5b model served by Ollama 0.40.19 instead of a hosted model, so the outputs below are from that setup.

LangChain: a higher-level agent harness

Use LangChain when you want a conventional tool-using agent without manually defining every node and edge. Its current primary API is langchain.agents.create_agent.

from langchain.agents import create_agent


def get_weather(city: str) -> str:
    """Return fictional weather for a demonstration."""
    return f"It's always sunny in {city}!"


agent = create_agent(
    model="openai:YOUR_TOOL_CAPABLE_MODEL",
    tools=[get_weather],
    system_prompt="Use get_weather for weather questions.",
)

result = agent.invoke({
    "messages": [{
        "role": "user",
        "content": "What's the weather in San Francisco?",
    }]
})

print(result["messages"][-1].content)

For a hosted model, set OPENAI_API_KEY and replace the placeholder with a tool-capable model you can access. To run it locally, install langchain-ollama and use model="ollama:qwen2.5:1.5b". I printed every message in result["messages"] instead of only the last one, which shows the loop the harness ran:

HumanMessage  What's the weather in San Francisco?
AIMessage [{'name': 'get_weather', 'args': {'city': 'San Francisco'}, 'id': 'fd615094-...', 'type': 'tool_call'}]
ToolMessage  It's always sunny in San Francisco!
AIMessage  It's always sunny in San Francisco!

Four messages: the request, a tool call with parsed arguments, the tool result, and the final answer. The whole run took under five seconds on CPU. The tool is deliberately fictional, so the answer is not live weather data.

LangChain is a strong default when the workflow is an ordinary agent loop: receive a request, select a tool, observe the result, and answer. Middleware, guardrails, provider integrations, and memory can be added without rebuilding the loop from scratch.

LangGraph: explicit orchestration and state

The following example uses no model or API key. It demonstrates an intentional cycle, a stop condition, and checkpointed state.

from typing import TypedDict

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


class State(TypedDict):
    count: int


def increment(state: State) -> dict:
    return {"count": state["count"] + 1}


def route(state: State) -> str:
    return "again" if state["count"] < 3 else "done"


builder = StateGraph(State)
builder.add_node("increment", increment)
builder.add_edge(START, "increment")
builder.add_conditional_edges(
    "increment",
    route,
    {"again": "increment", "done": END},
)

graph = builder.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "counter-1"}}

result = graph.invoke({"count": 0}, config)
print(result)
print(graph.get_state(config).values)

It needs no model, so the output is the same on every run. With langgraph 1.2.24 it printed:

{'count': 3}
{'count': 3}

The node returns a partial state-update dictionary. The conditional edge sends execution back to increment until the count reaches three, then routes to END. Compilation is required before invocation.

State, checkpointers, and stores are different

A LangGraph checkpointer saves graph state at execution boundaries and groups it by thread_id. It enables thread-level continuity, recovery, interrupts, and time travel. InMemorySaver is suitable for a demonstration but loses data when the process exits.

A store holds application information across threads, such as user preferences. It is not interchangeable with a checkpointer. For durable checkpointing, the current documentation provides database-backed packages such as PostgreSQL:

python -m pip install -U \
  langgraph-checkpoint-postgres \
  "psycopg[binary]"

A production PostgresSaver needs a running database and initial setup. Do not describe an in-memory example as durable persistence.

When direct LangGraph is justified

  • Deterministic validation must occur before or after a model step.
  • The workflow has explicit branches based on typed state.
  • A bounded refinement or retry cycle must be visible.
  • Parallel nodes merge results using defined reducers.
  • Execution pauses for approval and resumes later.
  • A long-running workflow must recover from a saved checkpoint.
  • Specialized agents need custom routing rather than a standard agent loop.

LangGraph can be used without LangChain and without an LLM. Conversely, LangChain models, tools, or an entire LangChain agent can be used inside a custom graph.

Common failures and what they mean

Missing provider package or credentials

Installing langchain alone does not install every provider integration. Install the provider package and configure its key. An authentication or model-not-found error is not evidence that the LangChain agent loop is broken.

GRAPH_RECURSION_LIMIT

This means the graph reached its configured step limit before terminating. Inspect the routing condition for an unintended cycle. Raise the limit only when a longer workflow is intentional.

result = graph.invoke(
    {"count": 0},
    {"recursion_limit": 100},
)

INVALID_GRAPH_NODE_RETURN_VALUE

A regular StateGraph node returned a string, list, or another unsupported value instead of a state-update dictionary. Return a mapping such as {"count": 1}.

INVALID_CONCURRENT_GRAPH_UPDATE

Parallel nodes wrote the same state field without a reducer. Use separate fields or define a reducer such as an annotated list with operator.add.

Checkpointing fails without thread_id

When using a checkpointer, pass a stable thread identifier under configurable. Use different IDs for unrelated conversations.

Memory disappears after restart

An in-memory saver is process-local. Use a durable checkpointer if state must survive process termination.

An old tutorial imports create_react_agent

Current migration guidance deprecates langgraph.prebuilt.create_react_agent in favor of langchain.agents.create_agent. Pinning old versions may reproduce the tutorial, but it should not be presented as the current primary API.

What I ran into

Two things in the LangGraph example are easy to misread. First, the counter graph saved five checkpoints for one invoke call: len(list(graph.get_state_history(config))) returned 5, one for the input and one after each step. That history is what makes time travel and resumption possible, and it is also why an in-memory checkpointer grows with every step of a long thread.

Second, the recursion limit counts super-steps, not loop iterations you think of as “one turn”. Invoking the same graph with {"recursion_limit": 2} failed immediately:

GraphRecursionError: Recursion limit of 2 reached without hitting a stop condition. You can increase the limit by setting the `recursion_limit` config key.

The counter needs three increments before the router returns done, so a limit of 2 is too low. If you see this error in a real agent, check the stop condition before raising the limit. A limit that only works at 200 usually means the route never returns the end branch.

NeedLangChain create_agentLangGraph StateGraph
Tool-calling loopBuilt inYou define nodes and edges
Custom branching and cyclesThrough middlewareExplicit conditional edges
Checkpointing by thread_idPass a checkpointerPass a checkpointer
Code for the example aboveAbout 20 lines, needs a modelAbout 30 lines, no model
Failure you will meet firstModel does not support tool callsGraphRecursionError or wrong state keys

Decision guide

  • Choose LangChain for a conventional tool-using agent, provider integration, middleware, and faster implementation.
  • Choose LangGraph directly when explicit orchestration is the main requirement.
  • Use both when LangChain components belong inside a custom graph.
  • Use neither when one model call or a deterministic Python function solves the task.

LangGraph is not automatically faster, cheaper, or more accurate. Those outcomes depend on the graph, model calls, tool usage, and application design.

FAQ

Do I need LangGraph if I already use LangChain?

No. create_agent already runs on LangGraph. Install and use LangGraph directly only when you need to shape the graph yourself.

Can I run these examples without an OpenAI key?

Yes. The LangGraph counter needs no model at all, and the LangChain agent works with a local Ollama model through langchain-ollama if the model supports tool calling.

Why does my graph raise GraphRecursionError?

The graph took more super-steps than recursion_limit allows, usually because the router never returns the end branch. Fix the stop condition first.

Is InMemorySaver enough for production?

No. It loses every checkpoint when the process exits. Use a database-backed checkpointer such as the PostgreSQL package.

Related guides

Official references

Leave a Reply