保留正文与补采附件。源页面当前未重新核验;具体限制见交付清单。

Revisit consent button We value your privacy We use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking "Accept All", you consent to our use of cookies. Customise Reject All Accept All Customise Consent Preferences We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below. The cookies that are categorised as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more NecessaryAlways Active Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

Functional Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

Analytics Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

Performance Performance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Advertisement Advertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.

Uncategorised Other uncategorised cookies are those that are being analysed and have not been classified into a category as yet. No cookies to display. Reject All Save My Preferences Accept All Toggle SearchToggle Mobile Navigation Publish AI, ML & data-science insights to a global community of data professionals. Sign inSubmit an Article LatestEditor's PicksNewsletterShipAI


Write For TDS LinkedInXToggle Search Agentic AI

LangChain vs LangGraph: 4 Key Differences and When to Use Each

A practical guide to choose the proper tool for your agentic workflows and systems Soner Yıldırım August 13, 20265 min read Photo by Mika Baumeister on Unsplash LangChain came to our lives long before LangGraph. This is a clear indication of LangGraph closing a gap. In other words, LangGraph does things that are more complicated or not possible to do with LangChain. In this article, we'll go over 4 key differences between LangChain and LangGraph, and how they impact the code we write to build agentic workflows. Let's first mention that these are not competing tools. LangGraph is part of the LangChain ecosystem. It is kind of an extension built on top of LangChain.

1. Pipeline vs Loops

Image created with Gemini by author LangChain is a pipeline with a clear direction: Learn this step by step with the interactive AI Agents roadmap. We chain components together but in one direction, which looks like this in code: python

chain = prompt | model | parser 
output = chain.invoke(input)

We can still branch, run steps in parallel, and construct DAGs, but the default abstraction is data being moved forward through a pipeline. This structure is enough for solving many problems such as

However, when it comes to sending backward, we need to write an outer Python loop. Hence, the application handles the rest, not LangChain. On the other hand, LangGraph treats loops as part of the workflow itself. It is basically a graph with nodes and edges.

Thanks to the normal and conditional edges, we can route back to earlier nodes without a hustle. Here is the diagram of a customer service agent I built with LangGraph: Customer represents the input node, AI Agent is the model, price and booking engines are the other nodes. We can go back and forth between nodes.

2. Stateless vs Stateful

A LangChain pipeline does not hold a state within itself. Each runnable usually receives an input and returns an output. State is passed forward in the form of a dictionary, message, or a custom object. This is enough when each step needs only the previous step’s result. However, once we have a more complex workflow with loops or branches, it is on us to track the current draft, validation errors, conversation history, retry counts, etc. We can manage all of that writing extra Python code but, as we mentioned earlier, it's not part of the chain. LangGraph creates stateful agents so the state is part of the graph. We declare a schema for the state, usually in the form of a TypedDict . For example, here is the state object of my customer service agent: python

class AgentState(TypedDict):
    messages: Annotated[list[AnyMessage], add_messages]
    booking_details: BookingDetails
    calculated_price: NotRequired[float | None]
    time_options: NotRequired[list[TimeOption]]
    selected_slot: NotRequired[TimeOption | None]
    status: BookingStatus
    booking_id: NotRequired[str | None]

A node does not have to reconstruct the entire state. It can do partial updates and LangGraph handles it smoothly. In this agent, we have a price engine node, which only updates the calculated_price in the agent state: python

def calculate_price_node(state: AgentState) -> dict[str, Any]:
    return {"calculated_price": calculate_price(state["booking_details"])}

LangGraph then merges that update into the existing state. State fields can also have reduces for values written by multiple nodes or same node multiple times. For example, the messages field of the customer service agent state is updated after every customer message so we have a reduced (add_messages ) for this field ( messages: Annotated[list[AnyMessage], add_messages]). Without a reducer, a new value normally replaces the old value, which is something we should avoid when keeping track of chat history.

3. Human-breaks-the-loop vs Human-in-the-loop

We've witnessed agents making crucial mistakes. So, especially for some critical tasks, we may want to intervene with agents operations. Suppose an agent prepares a database migration, refund, or production deployment. We may want a human-in-the-loop to approve it before agent actually executes. With a conventional LangChain pipeline, the common approach is to build that pause into the application surrounding the pipeline. A typical approach would be:

  1. Run the chain until it proposes an action.
  2. Save the proposal somewhere.
  3. Return control to an API or job queue.
  4. Wait for an approval event.
  5. Reconstruct the required context.
  6. Start the next portion of the workflow.

This approach works but requires a lot of work. It sounds more like a human-breaks-the-loop and reconstructs it. On the other hand, LangGraph provides dynamic interrupt() calls inside nodes. Interrupts allow us to pause graph execution at specific points and wait for external input to continue. When we trigger an interrupt, LangGraph saves the graph state so we don't need to worry about losing information or data. Dynamic interrupts can include a payload and resume with a human response. Here is an example: python

from langgraph.types import interrupt

def approval_node(state: State):
    approved = interrupt({
        "question": "Run this migration?",
        "sql": state["sql"],
    })
    return {"approved": approved}

4. Restarts vs Resume

When a step in a normal chain fails, the simplest way to recover is often to invoke the chain again. This can be an expensive option because preceding model calls, retrieval queries, transformations, other tool calls need to be repeated. We can add caching and write custom resume logic but those would not be part of the chain. Similar to our discussing in previous points, these are handled on the application level, not in LangChain. LangGraph has something called checkpointer, which is a state persistence layer that saves a snapshot of an agent's graph state at every step of execution. In order to activate it, we just need compile the graph with a checkpointer: python

graph.compile(checkpointer=checkpointer)

Checkpoints allows for resuming after a failure rather than restarting the entire workflow. This saves us the cost (both time and money) of executing the successful operations again. We can also inspect the state before a problematic code or restart execution from any of the earlier checkpoints.

When to use which

We can stick with LangChain pipelines when the workflow is mostly predictable and forward-moving such as:

If the control flow is complex and constitutes the major part of our agentic system, we should consider using LangGraph. A typical use case would be coding assistants that generate, test, and repair code. LangGraph is also a better fit for workflows with repeated planning and evaluating actions. As we mentioned in the "restarts vs resume" section, applications that require pause, persist, and resume can advantage from the stateful LangGraph agents. Use LangChain when your application is best understood as a pipeline. Use LangGraph when it is better understood as a stateful system. Thank you for reading!

Register Now to Continue Reading

Unlock Towards Data Science with a Free Account

All articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more. Register for freeSign in to your account


Written By

Soner Yıldırım

See all from Soner Yıldırım Agentic AiArtificial IntelligenceData Science Share This Article

Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program. Write for TDS

Related Articles

Tool Calling, Explained: How AI Agents Decide What to Do Next

Agentic AI Understanding how LLMs interact with the world around them, from returning data to taking action Maria Mouschoutzi June 21, 202611 min read

Don’t Let Claude Grade Its Own Homework

Agentic AI Cross-provider PR review with Codex in GitHub Actions, and why a second opinion from a different lab beats any self-review Ruben Broekx July 15, 202622 min read

How to Set Up a Development Environment for Machine Learning

Machine Learning How to install, activate, and use a virtual environment for machine learning and data science-related tasks Andrea D'Agostino April 28, 20224 min read

What House of Cards Got Right (and Wrong) About Data Science

Data Science Given the recent release of two House of Cards season 5 trailers and the impending release of season 5 of the binge-worthy Netflix series... Matt Brems (he/him) May 22, 20178 min read

When to Use One Model and When to Use a Team of Agents

Agentic AI When Codex is the right shape for the problem, when Claude Code is, and how I split 5 specialist agents between them on dense AI capacity work. Naveen Goel September 14, 202616 min read

Hacking Statistical Significance: Hypothesis Testing with ML Approaches

Machine Learning Test Statistical Significance in any Context Without Assumptions Marco Cerliani January 10, 20236 min read

Vice Presidential and Presidential Debate Analysis using Data Science

Machine Learning Debate Analysis using Data Science: Using YouTube Comments to find the true intent of voters Aadit Kapoor October 24, 20205 min read

The Rise of Semantic Entity Resolution

Agentic AI Building knowledge graphs to power autonomous agents Russell Jurney September 14, 202518 min read

Plan–Code–Execute: Designing Agents That Create Their Own Tools

Agentic AI The case against pre-built tools in Agentic Architectures Partha Sarkar February 4, 20268 min read

Your home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals. Subscribe to Our NewsletterWrite For TDS•About•Advertise•Privacy Policy•Terms of Use © Insight Media Group, LLC 2026•The New Stack•roadmap.sh•Creator Network

Recommended Articles

Close