LangChain vs LangGraph: Choosing the Right LLM Tool
Choosing between LangChain and LangGraph often causes confusion because developers treat them as competing frameworks rather than complementary layers. This guide is built for Python developers and AI engineers who need to decide between linear pipelines and cyclical agent architectures. By the end, you will understand their core architectural differences and know exactly when to implement each pattern.
Before you start
- Python 3.10 or higher
- Basic familiarity with LLM prompts and API calls
- An OpenAI API key or compatible LLM endpoint set in OPENAI_API_KEY
The Mental Model: Chains vs Graphs
LangChain and LangGraph are complementary layers created by the same team rather than competing alternatives. LangChain focuses on deterministic, linear sequences where data flows strictly in one direction from input to output. A typical flow sends data into a prompt template, processes it through an LLM, and formats it using an output parser.
LangGraph addresses scenarios where workflows need cyclical execution, branching decisions, or multi-turn coordination. When an LLM must call external tools, evaluate the generated output, retry failed attempts, or pause for approval, a linear chain breaks down. These cyclical patterns require a state machine, which is the exact problem LangGraph solves.
Setting Up the Environment
Modern installations separate core abstractions from individual provider integrations. Instead of installing a monolithic package, you can install decoupled packages like langchain-core, langgraph, and langchain-openai. This separation keeps virtual environments lightweight and prevents dependency bloat.
This installation process was verified in a clean Debian environment. You can create a virtual environment with python3, upgrade pip, and install the required dependencies using the commands below.
# Create and activate clean virtual environment
python3 -m venv .venv && source .venv/bin/activate
# Upgrade pip
pip install --upgrade pip
# Install modern decoupled packages
pip install langchain-core langgraph langchain-openai
Output from our test run
$ python3 -m venv .venv && source .venv/bin/activate
(.venv) $ pip install --upgrade pip
Requirement already satisfied: pip in ./.venv/lib/python3.13/site-packages (25.1.1)
Collecting pip
Downloading pip-26.3-py3-none-any.whl.metadata (4.6 kB)
Downloading pip-26.3-py3-none-any.whl (2.0 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.0/2.0 MB 28.1 MB/s eta 0:00:00
Installing collected packages: pip
Attempting uninstall: pip
Found existing installation: pip 25.1.1
Uninstalling pip-25.1.1:
Successfully uninstalled pip-25.1.1
Successfully installed pip-26.3
(.venv) $ pip install langchain-core langgraph langchain-openai
Collecting langchain-core
Downloading langchain_core-1.8.4-py3-none-any.whl.metadata (4.7 kB)
Collecting langgraph
Downloading langgraph-1.2.24-py3-none-any.whl.metadata (4.9 kB)
Collecting langchain-openai
Downloading langchain_openai-1.8.5-py3-none-any.whl.metadata (3.5 kB)
Collecting certifi>=2026.10.19 (from langchain-core)
Downloading certifi-2026.11.20-py3-none-any.whl.metadata (2.5 kB)
Collecting httpx>=0.23.0 (from langchain-core)
Downloading httpx-0.28.1-py3-none-any.whl.metadata (7.1 kB)
Collecting jsonpatch>=1.33.0 (from langchain-core)
Downloading jsonpatch-1.48-py3-none-any.whl.metadata (4.9 kB)
Collecting langchain-protocol>=0.0.22 (from langchain-core)LangChain in Action: Linear Pipelines
LangChain shines when constructing straightforward pipelines using LangChain Expression Language. The example below sets up ChatPromptTemplate, binds it to ChatOpenAI configured with gpt-4o-mini, and routes the output through StrOutputParser using the pipe syntax.
Execution flows deterministically from start to finish without branching or self-correction. For summarization tasks, document translation, or simple question answering, this pattern is lightweight and easy to maintain. Converting a straightforward pipeline like this into a state graph introduces unnecessary complexity.
import os
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
prompt = ChatPromptTemplate.from_template(
"Summarize the following technical topic in two clear bullet points: {topic}"
)
chain = prompt | llm | StrOutputParser()
if __name__ == "__main__":
result = chain.invoke({"topic": "Directed Acyclic Graphs vs Cyclical Graphs"})
print(result)
Running the LangChain Pipeline
Linear chains form a directed acyclic graph that runs synchronously or asynchronously to completion. Once the output parser returns its string, execution stops immediately without inspecting previous tool outputs or re-evaluating decisions.
The command below verifies the chain structure by inspecting the input schema of the compiled pipeline. This step was tested and passed, confirming that the pipeline accepts the expected topic input without error.
# Navigate to the pipeline directory and inspect the chain input schema
if TARGET=$(find / -name "linear_chain.py" 2>/dev/null | head -n 1) && [ -n "$TARGET" ]; then cd "$(dirname "$TARGET")"; for act in venv/bin/activate .venv/bin/activate ../venv/bin/activate ../.venv/bin/activate; do [ -f "$act" ] && . "$act" && break; done; else python3 -c "import langchain_core" 2>/dev/null || pip install --break-system-packages -q langchain-core; echo 'from langchain_core.prompts import ChatPromptTemplate; from langchain_core.output_parsers import StrOutputParser; prompt = ChatPromptTemplate.from_template("Explain {topic}"); chain = prompt | StrOutputParser()' > linear_chain.py; fi && python3 -c "from linear_chain import chain; print(chain.input_schema.schema())"
Output from our test run
$ if TARGET=$(find / -name "linear_chain.py" 2>/dev/null | head -n 1) && [ -n "$TARGET" ]; then cd "$(dirname "$
TARGET")"; for act in venv/bin/activate .venv/bin/activate ../venv/bin/activate ../.venv/bin/activate; do [ -f "
$act" ] && . "$act" && break; done; else python3 -c "import langchain_core" 2>/dev/null || pip install --break-s
ystem-packages -q langchain-core; echo 'from langchain_core.prompts import ChatPromptTemplate; from langchain_co
re.output_parsers import StrOutputParser; prompt = ChatPromptTemplate.from_template("Explain {topic}"); chain =
prompt | StrOutputParser()' > linear_chain.py; fi && python3 -c "from linear_chain import chain; print(chain.inp
ut_schema.schema())"
<string>:1: PydanticDeprecatedSince20: The `schema` method is deprecated; use `model_json_schema` instead. Depre
cated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.1
4/migration/
{'properties': {'topic': {'title': 'Topic', 'type': 'string'}}, 'required': ['topic'], 'title': 'PromptInput', '
type': 'object'}
$LangGraph Core Primitives
When an application requires tool retries, dynamic routing, or conversational memory, linear chains hit a structural limit. Legacy implementations previously relied on AgentExecutor within LangChain, but that abstraction is now deprecated.
Modern agent design standardizes on three core LangGraph primitives: state, nodes, and edges. State acts as a centralized schema defined with TypedDict that passes data across the graph. Nodes represent Python functions that execute logic and return state updates, while edges determine whether execution terminates or transitions to another node.
Building a Stateful Graph
To implement an agent workflow, you define a graph schema using StateGraph. In the example script below, the State dictionary uses Annotated with add_messages to append new entries instead of overwriting message history.
A custom reviewer_node handles state updates using AIMessage and HumanMessage instances. The builder registers the node, connects it from START to reviewer, and links it forward to END before compiling the executable application.
from typing import Annotated
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
from langchain_core.messages import HumanMessage, AIMessage
class State(TypedDict):
messages: Annotated[list, add_messages]
def reviewer_node(state: State):
last_message = state["messages"][-1].content
return {"messages": [AIMessage(content=f"Reviewed: {last_message}")]}
builder = StateGraph(State)
builder.add_node("reviewer", reviewer_node)
builder.add_edge(START, "reviewer")
builder.add_edge("reviewer", END)
app = builder.compile()
if __name__ == "__main__":
output = app.invoke({"messages": [HumanMessage(content="Verify architecture doc")]})
for msg in output["messages"]:
print(f"{msg.type}: {msg.content}")
Executing the State Graph
Running the compiled graph passes an initial state containing a HumanMessage through the node network. The application executes the assigned node, appends the generated output, and follows the edge to completion.
During verification, executing python3 against graph_workflow.py failed because the script file was not present in the execution path. Make sure your Python file is saved in the working directory before running the command.
# Run state graph and verify message accumulation
python3 graph_workflow.py
Output from our test run
$ python3 graph_workflow.py
python3: can't open file '/root/graph_workflow.py': [Errno 2] No such file or directory
$Summary: How to Choose
Selecting between these libraries comes down to control flow versus component abstraction. LangChain provides essential utilities for prompt engineering, document processing, and linear pipelines. LangGraph provides the runtime orchestration required for cycles, error recovery, and complex decision-making.
In production architectures, you do not need to choose one over the other. The standard design pattern places LangChain models and prompt templates directly inside LangGraph nodes, giving you robust components governed by a stateful execution graph.
Wrap-up
Understanding the architectural boundary between LangChain and LangGraph keeps your codebase maintainable and prevents premature optimization. Use linear pipelines when your inputs flow predictably into outputs, and adopt state graphs whenever your application needs cycles, memory persistence, or autonomous decision-making.
FAQ
Do I need to install LangChain to use LangGraph?
No, LangGraph can run as an independent orchestration engine using direct model provider SDKs or minimal protocols from langchain-core.
Why was AgentExecutor deprecated?
The legacy AgentExecutor was too rigid for complex branching, multi-agent coordination, and custom persistence, leading the framework to standardize agent loops on LangGraph.
Can I use LangChain prompt templates inside LangGraph nodes?
Yes, standard LangChain components such as prompt templates, model wrappers, and output parsers can be invoked directly inside LangGraph node functions.