Compare commits

..
Author SHA1 Message Date
open-swe-dev[bot] 72bfad91cf Apply patch 2025-07-15 23:46:30 +00:00
open-swe-dev[bot] 7fcb4330ec Apply patch 2025-07-15 23:39:24 +00:00
open-swe-dev[bot] 2126380cf1 Apply patch 2025-07-15 23:37:47 +00:00
open-swe-dev[bot] 290313b7bd Apply patch 2025-07-15 23:36:03 +00:00
open-swe-dev[bot] 5107729c0a Apply patch 2025-07-15 23:34:31 +00:00
+3 d5b8733a40 ci(docs): Add codespell for docs md and py files (#5494)
* docs: Add codespell for markdown files

* update

* remove path

* fix

* update linting guidelines

* chore[deps]: upgrade dependencies with `uv lock --upgrade` (#5471)

Co-authored-by: sydney-runkle <54324534+sydney-runkle@users.noreply.github.com>

* fix(checkpoint): correct logging call to use logger (#5458)

fix[checkpoint]: correct logging call to use logger

* release(langgraph): v0.5.3 (#5498)

bump

* extend to cover python files used for reference docs

* fix(docs): Update the graph image link (#5500)

Update the graph image link

Point to the correct image reference for Map-Reduce and the Send API example

* fix(docs): Update graph-api.md File to reflect correct image (#5499)

Update graph-api.md File to reflect correct image

Referencing to the correct image file

* docs(prebuilt): improve documentation in ToolNode module (#5497)

Update documentation in ToolNode module

* Update changelog via LangGraph Server Changelog Bot

* feat(sdk-py): Show is_studio_user (#5505)

* Update changelog via LangGraph Server Changelog Bot

* fix(docs): Node caching explanation code required a small fix,. (#5473)

fix(docs): Node caching explanation code required a small fix, to avoid confusion to readers. The code had `time.sleep(2)` but the note mentioned one second only.

Co-authored-by: ygicp <yagnesh@infocusp.com>

* fix(langgraph): add `stacklevel=2` to the warnings to point to the caller’s codes (#5457)

chore: add stacklevel=2 to the warnings to point to the caller’s codes

* chore(docs): Improve example in use mcp (#5480)

* Make example more explicit

* Update docs/docs/agents/mcp.md

* fix(docs): update examples link (#5515)

Co-authored-by: ahmed murtaza <ahmed.gmurtaza@gmail.com>

* docs: [LangGraph Server Changelog Bot] Changelog updates for new version(s) (#5514)

Update changelog via LangGraph Server Changelog Bot

* fix readmes

* fix

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: sydney-runkle <54324534+sydney-runkle@users.noreply.github.com>
Co-authored-by: Michael Li <michaelli65535@gmail.com>
Co-authored-by: Sakshi Gupta <64280320+sakshi1989@users.noreply.github.com>
Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
Co-authored-by: Sam Crowder <samecrowder@gmail.com>
Co-authored-by: William FH <13333726+hinthornw@users.noreply.github.com>
Co-authored-by: Yagnesh M. Bhadiyadra <35532869+yagneshmb@users.noreply.github.com>
Co-authored-by: ygicp <yagnesh@infocusp.com>
Co-authored-by: Ahmed Murtaza <ahmed.gmurtaza@hotmail.com>
Co-authored-by: ahmed murtaza <ahmed.gmurtaza@gmail.com>
2025-07-15 19:22:48 +00:00
Lauren Hirata SinghandGitHub 40c0e44b9a docs: Update with links to Forum (#5440)
Also updates some outdated references to LangChain
2025-07-15 14:55:15 -04:00
Mason DaughertyandGitHub b5afec4b2a chore: add PR template (#5491) 2025-07-15 14:48:59 -04:00
Sam CrowderandGitHub d674e1bddd docs: [LangGraph Server Changelog Bot] Changelog updates for new version(s) (#5514)
Update changelog via LangGraph Server Changelog Bot
2025-07-15 11:13:18 -04:00
8c68f739b9 fix(docs): update examples link (#5515)
Co-authored-by: ahmed murtaza <ahmed.gmurtaza@gmail.com>
2025-07-15 15:03:56 +00:00
Eugene YurtsevandGitHub 1500ebd3d7 chore(docs): Improve example in use mcp (#5480)
* Make example more explicit

* Update docs/docs/agents/mcp.md
2025-07-15 15:01:16 +00:00
19 changed files with 139 additions and 524 deletions
+11 -11
View File
@@ -1,29 +1,29 @@
name: "\U0001F41B Bug Report"
description: Report a bug in LangGraph. To report a security issue, please instead use the security option below. For questions, please use the GitHub Discussions.
description: Report a bug in LangGraph. To report a security issue, please instead use the security option below. For questions, please use the LangChain Forum at forum.langchain.com.
labels: [pending,bug]
body:
- type: markdown
attributes:
value: >
value: |
Thank you for taking the time to file a bug report.
Use this to report BUGS in LangGraph. For usage questions, feature requests and general design questions, please use [GitHub Discussions](https://github.com/langchain-ai/langgraph/discussions).
Use this to report BUGS in LangGraph. For usage questions, feature requests and general design questions, please use the [LangChain Forum](https://forum.langchain.com/).
Relevant links to check before filing a bug report to see if your issue has already been reported, fixed or
if there's another way to solve your problem:
[LangGraph Github Discussions](https://github.com/langchain-ai/langgraph/discussions),
[LangGraph Github Issues](https://github.com/langchain-ai/langgraph/issues),
[LangGraph how-to guides](https://langchain-ai.github.io/langgraph/how-tos/).
[LangChain documentation with the integrated search](https://python.langchain.com/docs/get_started/introduction),
[GitHub search](https://github.com/langchain-ai/langgraph),
* [LangChain Forum](https://forum.langchain.com/),
* [LangGraph Github Issues](https://github.com/langchain-ai/langgraph/issues),
* [LangGraph how-to guides](https://langchain-ai.github.io/langgraph/how-tos/).
* [LangChain documentation with the integrated search](https://python.langchain.com/docs/get_started/introduction),
* [GitHub search](https://github.com/langchain-ai/langgraph),
- type: checkboxes
id: checks
attributes:
label: Checked other resources
description: Before submitting this issue, please confirm that you have completed all the steps below by checking each option. These steps help ensure your issue is well-defined, relevant, and actionable.
options:
- label: This is a bug, not a usage question. For questions, please use GitHub Discussions.
- label: This is a bug, not a usage question. For questions, please use the LangChain Forum (https://forum.langchain.com/).
required: true
- label: I added a clear and detailed title that summarizes the issue.
required: true
@@ -38,7 +38,7 @@ body:
attributes:
label: Example Code
description: |
Please add a self-contained, [minimal, reproducible, example](https://stackoverflow.com/help/minimal-reproducible-example) with your use case.
Please add a self-contained, [minimal, reproducible, example](https://stackoverflow.com/help/minimal-reproducible-example) with your use case. Replace this code with your own!
placeholder: |
from langgraph.graph import StateGraph
@@ -78,7 +78,7 @@ body:
attributes:
label: System Info
description: |
python -m langchain_core.sys_info
Run on your machine: `python -m langchain_core.sys_info`
placeholder: |
python -m langchain_core.sys_info
validations:
+2 -4
View File
@@ -1,8 +1,6 @@
blank_issues_enabled: false
version: 2.1
contact_links:
- name: Feature Request
url: https://github.com/langchain-ai/langgraph/discussions/categories/ideas
about: Suggest a feature or an idea
- name: LangChain Forum
url: https://forum.langchain.com/
about: General community discussions and support
about: General community discussions, support, and feature requests
+8 -8
View File
@@ -1,22 +1,22 @@
name: 🔒 Privileged
description: You are a LangChain maintainer, or was asked directly by a maintainer to create an issue here. If not, check the other options.
description: You are a LangGraph maintainer, or was asked directly by a maintainer to create an issue here. If not, check the other options.
body:
- type: markdown
attributes:
value: |
Thanks for your interest in LangChain! 🚀
If you are not a LangChain maintainer or were not asked directly by a maintainer to create an issue, then please start the conversation in a [Question in GitHub Discussions](https://github.com/langchain-ai/langchain/discussions/categories/q-a) instead.
You are a LangChain maintainer if you maintain any of the packages inside of the LangChain repository
or are a regular contributor to LangChain with previous merged merged pull requests.
Thanks for your interest in LangGraph! 🚀
If you are not a LangGraph maintainer or were not asked directly by a maintainer to create an issue, then please start the conversation on the [LangChain Forum](https://forum.langchain.com/) instead.
You are a LangGraph maintainer if you maintain any of the packages inside of the LangGraph repository
or are a regular contributor to LangGraph with previous merged merged pull requests.
- type: checkboxes
id: privileged
attributes:
label: Privileged issue
description: Confirm that you are allowed to create an issue here.
options:
- label: I am a LangChain maintainer, or was asked directly by a LangChain maintainer to create an issue here.
- label: I am a LangGraph maintainer, or was asked directly by a LangGraph maintainer to create an issue here.
required: true
- type: textarea
id: content
+31
View File
@@ -0,0 +1,31 @@
Thank you for contributing to LangGraph! Follow these steps to mark your pull request as ready for review. **If any of these steps are not completed, your PR will not be considered for review.**
- [ ] **PR title**: Follows the format: {TYPE}({SCOPE}): {DESCRIPTION}
- Examples:
- feat(core): add multi-tenant support
- fix(cli): resolve flag parsing error
- docs(openai): update API usage examples
- Allowed `{TYPE}` values:
- feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert, release
- Allowed `{SCOPE}` values (optional):
- langgraph, docs, cli, checkpoint, checkpoint-postgres, checkpoint-sqlite, prebuilt, scheduler-kafka, sdk-py
- Once you've written the title, please delete this checklist item; do not include it in the PR.
- [ ] **PR message**: ***Delete this entire checklist*** and replace with
- **Description:** a description of the change. Include a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/using-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword) if applicable.
- **Issue:** the issue # it fixes, if applicable
- **Dependencies:** any dependencies required for this change
- **Twitter handle:** if your PR gets announced, and you'd like a mention, we'll gladly shout you out!
- [ ] **Add tests and docs**: If you're adding a new integration, you must include:
1. A test for the integration, preferably unit tests that do not rely on network access,
2. An example notebook showing its use. It lives in `docs/docs/integrations` directory.
- [ ] **Lint and test**: Run `make format`, `make lint` and `make test` from the root of the package(s) you've modified. We will not consider a PR unless these three are passing in CI. See [contribution guidelines](https://github.com/langchain-ai/langgraph/blob/main/CONTRIBUTING.md) for more.
Additional guidelines:
- Make sure optional dependencies are imported within a function.
- Please do not add dependencies to `pyproject.toml` files (even optional ones) unless they are **required** for unit tests.
- Most PRs should not touch more than one package.
- Changes should be backwards compatible.
@@ -0,0 +1,11 @@
LangChain
LangGraph
LangSmith
thead
stdio
nd
jupyter
lets
lite
uis
deque
+9 -3
View File
@@ -34,10 +34,16 @@
id: extract_ignore_words
- name: Codespell
uses: codespell-project/actions-codespell@v2
uses: codespell-project/actions-codespell@v2.0
with:
skip: '*.ambr,*.lock,*.ipynb,*.yaml,*.zlib,*.md'
skip: '*.ambr,*.lock,*.ipynb,*.yaml,*.zlib,*.css.map,*.js.map'
ignore_words_list: ${{ steps.extract_ignore_words.outputs.ignore_words_list }}
# We do this to avoid spellchecking cell outputs
- name: Codespell Notebooks
run: make codespell
run: make codespell
- name: Codespell LangGraph Library
run: |
# Change to root directory to check the main LangGraph library
cd ..
codespell --skip="*.ambr,*.lock,*.ipynb,*.yaml,*.zlib,*.css.map,*.js.map,*.pyc,__pycache__/*" --ignore-words-list="${{ steps.extract_ignore_words.outputs.ignore_words_list }}" libs/langgraph/langgraph/
+8 -9
View File
@@ -9,7 +9,7 @@ Here are some things to keep in mind for all types of contributions:
- Follow the ["fork and pull request"](https://docs.github.com/en/get-started/exploring-projects-on-github/contributing-to-a-project) workflow.
- Fill out the checked-in pull request template when opening pull requests. Note related issues and tag relevant maintainers.
- Ensure your PR passes formatting, linting, and testing checks before requesting a review.
- If you would like comments or feedback, please open an issue or discussion and tag a maintainer.
- If you would like comments or feedback, please tag a maintainer.
- Backwards compatibility is key. Your changes must not be breaking, except in case of critical bug and security fixes.
- Look for duplicate PRs or issues that have already been opened before opening a new one.
- Keep scope as isolated as possible. As a general rule, your changes should not affect more than one package at a time.
@@ -20,7 +20,7 @@ For bug fixes, please open up an issue before proposing a fix to ensure the prop
### New features
For new features, please start a new [discussion](https://github.com/langchain-ai/langgraph/discussions), where the maintainers will help with scoping out the necessary changes.
For new features, please start a new [discussion](https://forum.langchain.com/), where the maintainers will help with scoping out the necessary changes.
## Contribute Documentation
@@ -111,7 +111,6 @@ in a more abstract way than how-to guides or tutorials, and should be geared tow
gaining a deeper understanding of the framework. Try to avoid excessively large code examples. The goal here is to
impart perspective to the user rather than to finish a practical project. These guides should cover **why** things work the way they do.
To quote the Diataxis website:
> The perspective of explanation is higher and wider than that of the other types. It does not take the users eye-level view, as in a how-to guide, or a close-up view of the machinery, like reference material. Its scope in each case is a topic - “an area of knowledge”, that somehow has to be bounded in a reasonable, meaningful way.
@@ -187,9 +186,9 @@ Be concise, including in code samples.
## Setup
LangChain documentation consists of two components:
LangGraph documentation consists of two components:
1. Main Documentation: Hosted at [https://langchain-ai.github.io](https://langchain-ai.github.io/langgraph/),
1. Main Documentation: Hosted at [https://langchain-ai.github.io/langgraph/](https://langchain-ai.github.io/langgraph/),
this comprehensive resource serves as the primary user-facing documentation.
It covers a wide array of topics, including tutorials, use cases, integrations,
and more, offering extensive guidance on building with LangGraph.
@@ -250,17 +249,17 @@ make serve-docs
#### Linting
The documentation is linted from the **monorepo root**. To lint it, run the following from there:
To spell check the docs, run the following from the `docs` directory:
```bash
make spellcheck
codespell --skip="*.ambr,*.lock,*.ipynb,*.yaml,*.zlib,*.css.map,*.js.map" --ignore-words-list="infor,thead,stdio,nd,jupyter,lets,lite,uis,deque" .
```
### In-code Documentation
The in-code documentation is autogenerated from docstrings.
For the API reference to be useful, the codebase must be well-documented. This means that all functions, classes, and methods should have a docstring that explains what they do, what the arguments are, and what the return value is. This is a good practice in general, but it is especially important for LangChain because the API reference is the primary resource for developers to understand how to use the codebase.
For the API reference to be useful, the codebase must be well-documented. This means that all functions, classes, and methods should have a docstring that explains what they do, what the arguments are, and what the return value is. This is a good practice in general, but it is especially important for LangGraph because the API reference is the primary resource for developers to understand how to use the codebase.
We generally follow the [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings) for docstrings.
@@ -291,4 +290,4 @@ def my_function(arg1: int, arg2: str) -> float:
This is a description of the return value.
"""
return 3.14
```
```
+2 -2
View File
@@ -73,7 +73,7 @@ While LangGraph can be used standalone, it also integrates seamlessly with any L
- [Guides](https://langchain-ai.github.io/langgraph/how-tos/): Quick, actionable code snippets for topics such as streaming, adding memory & persistence, and design patterns (e.g. branching, subgraphs, etc.).
- [Reference](https://langchain-ai.github.io/langgraph/reference/graphs/): Detailed reference on core classes, methods, how to use the graph and checkpointing APIs, and higher-level prebuilt components.
- [Examples](https://langchain-ai.github.io/langgraph/tutorials/overview/): Guided examples on getting started with LangGraph.
- [Examples](https://langchain-ai.github.io/langgraph/examples/): Guided examples on getting started with LangGraph.
- [LangChain Forum](https://forum.langchain.com/): Connect with the community and share all of your technical questions, ideas, and feedback.
- [LangChain Academy](https://academy.langchain.com/courses/intro-to-langgraph): Learn the basics of LangGraph in our free, structured course.
- [Templates](https://langchain-ai.github.io/langgraph/concepts/template_applications/): Pre-built reference apps for common agentic workflows (e.g. ReAct agent, memory, retrieval etc.) that can be cloned and adapted.
@@ -81,4 +81,4 @@ While LangGraph can be used standalone, it also integrates seamlessly with any L
## Acknowledgements
LangGraph is inspired by [Pregel](https://research.google/pubs/pub37252/) and [Apache Beam](https://beam.apache.org/). The public interface draws inspiration from [NetworkX](https://networkx.org/documentation/latest/). LangGraph is built by LangChain Inc, the creators of LangChain, but can be used without LangChain.
LangGraph is inspired by [Pregel](https://research.google/pubs/pub37252/) and [Apache Beam](https://beam.apache.org/). The public interface draws inspiration from [NetworkX](https://networkx.org/documentation/latest/). LangGraph is built by LangChain Inc, the creators of LangChain, but can be used without LangChain.
+41 -14
View File
@@ -55,14 +55,16 @@ The `langchain-mcp-adapters` package enables agents to use tools defined across
=== "In a workflow"
```python
```python title="Workflow using MCP tools with ToolNode"
from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.graph import StateGraph, MessagesState, START
from langgraph.prebuilt import ToolNode, tools_condition
from langchain.chat_models import init_chat_model
model = init_chat_model("openai:gpt-4.1")
from langgraph.graph import StateGraph, MessagesState, START
from langgraph.prebuilt import ToolNode
# Initialize the model
model = init_chat_model("anthropic:claude-3-5-sonnet-latest")
# Set up MCP client
client = MultiServerMCPClient(
{
"math": {
@@ -80,22 +82,47 @@ The `langchain-mcp-adapters` package enables agents to use tools defined across
)
tools = await client.get_tools()
def call_model(state: MessagesState):
response = model.bind_tools(tools).invoke(state["messages"])
return {"messages": response}
# Bind tools to model
model_with_tools = model.bind_tools(tools)
# Create ToolNode
tool_node = ToolNode(tools)
def should_continue(state: MessagesState):
messages = state["messages"]
last_message = messages[-1]
if last_message.tool_calls:
return "tools"
return END
# Define call_model function
async def call_model(state: MessagesState):
messages = state["messages"]
response = await model_with_tools.ainvoke(messages)
return {"messages": [response]}
# Build the graph
builder = StateGraph(MessagesState)
builder.add_node(call_model)
builder.add_node(ToolNode(tools))
builder.add_node("call_model", call_model)
builder.add_node("tools", tool_node)
builder.add_edge(START, "call_model")
builder.add_conditional_edges(
"call_model",
tools_condition,
should_continue,
)
builder.add_edge("tools", "call_model")
# Compile the graph
graph = builder.compile()
math_response = await graph.ainvoke({"messages": "what's (3 + 5) x 12?"})
weather_response = await graph.ainvoke({"messages": "what is the weather in nyc?"})
# Test the graph
math_response = await graph.ainvoke(
{"messages": [{"role": "user", "content": "what's (3 + 5) x 12?"}]}
)
weather_response = await graph.ainvoke(
{"messages": [{"role": "user", "content": "what is the weather in nyc?"}]}
)
```
@@ -148,4 +175,4 @@ if __name__ == "__main__":
- [MCP documentation](https://modelcontextprotocol.io/introduction)
- [MCP Transport documentation](https://modelcontextprotocol.io/docs/concepts/transports)
- [langchain_mcp_adapters](https://github.com/langchain-ai/langchain-mcp-adapters)
- [langchain_mcp_adapters](https://github.com/langchain-ai/langchain-mcp-adapters)
@@ -4,6 +4,9 @@
---
## v0.2.89 (2025-07-15)
- Decoupled checkpoint writing from thread/run state by removing foreign keys and updated logger to prevent timeout-related failures.
## v0.2.88 (2025-07-14)
- Removed the foreign key constraint for `thread` in the `run` table to simplify database schema.
-465
View File
@@ -1,465 +0,0 @@
# Tech support bot with custom workflows
In this tutorial, you'll build a sophisticated tech support bot using LangGraph that demonstrates how to create custom workflows with conditional routing, loops, and human escalation. This bot will guide users through a structured support process, automatically routing them based on their responses and issue type.
!!! note "About escalation in this tutorial"
This tutorial demonstrates **workflow-based escalation** where the bot completes its workflow and indicates that human support is needed. This is different from LangGraph's **human-in-the-loop** functionality (using `interrupt`) which pauses execution and waits for human input. For human-in-the-loop examples, see the [human-in-the-loop tutorial](../get-started/4-human-in-the-loop.md).
## What you'll learn
By the end of this tutorial, you'll understand how to:
- Create **conditional routing** that adapts based on user responses
- Implement **loops** for iterative troubleshooting
- Handle **human escalation** at multiple decision points
- Use **state management** to track complex multi-step conversations
- Build a complete customer service workflow
## Prerequisites
Before you start this tutorial, ensure you have access to a LLM that supports tool-calling features, such as [OpenAI](https://platform.openai.com/api-keys), [Anthropic](https://console.anthropic.com/settings/keys), or [Google Gemini](https://ai.google.dev/gemini-api/docs/api-key).
## The workflow
Our tech support bot follows a 4-step decision tree:
1. **Warranty Check** - Is the device under warranty?
2. **Issue Classification** - Hardware or software issue?
3. **Basic Troubleshooting** - Have they tried restarting/updating?
4. **Solution Testing** - Did the suggested solution work?
```mermaid
flowchart TD
Start([Start]) --> Step1{Is device under warranty?}
Step1 -->|Yes| Step2{What type of issue?}
Step1 -->|No| RepairChoice{Troubleshoot or speak to human?}
RepairChoice -->|Human| Escalate1[🧑 Escalate to Human]
RepairChoice -->|Troubleshoot| Step2
Step2 -->|Hardware| Escalate2[🧑 Escalate to Human]
Step2 -->|Software| Step3{Tried restarting/updating?}
Step3 -->|No| Suggest[Suggest restart/update]
Step3 -->|Yes| Step4{Try solution - Did it work?}
Suggest --> Step3
Step4 -->|Yes| Success[✅ Issue Resolved]
Step4 -->|No| Escalate3[🧑 Escalate to Human]
classDef stepNode fill:#e1f5fe,stroke:#0277bd,stroke-width:2px
classDef escalateNode fill:#ffebee,stroke:#d32f2f,stroke-width:2px
classDef successNode fill:#e8f5e8,stroke:#388e3c,stroke-width:2px
classDef loopNode fill:#fff3e0,stroke:#f57c00,stroke-width:2px
class Step1,Step2,Step3,Step4,RepairChoice stepNode
class Escalate1,Escalate2,Escalate3 escalateNode
class Success successNode
class Suggest loopNode
```
## 1. Install packages
Install the required packages:
```bash
pip install -U langgraph langsmith langchain-anthropic
```
!!! tip
Sign up for LangSmith to quickly spot issues and improve the performance of your LangGraph projects. LangSmith lets you use trace data to debug, test, and monitor your LLM apps built with LangGraph. For more information on how to get started, see [LangSmith docs](https://docs.smith.langchain.com).
## 2. Define the state
First, define the state structure that will track the conversation and workflow progress:
```python
from dataclasses import dataclass
from typing import List, Optional, Literal
from langchain_core.messages import BaseMessage
# Define all possible workflow steps
WorkflowStep = Literal[
"check_warranty",
"ask_repair_or_continue",
"ask_issue_type",
"check_troubleshooting",
"suggest_troubleshooting",
"offer_solution",
"success",
"escalate"
]
@dataclass
class State:
messages: List[BaseMessage]
is_last_step: bool = False
workflow_step: WorkflowStep = "check_warranty"
# State tracking for our 4-step workflow
warranty_status: Optional[Literal["in", "out"]] = None
wants_human_help: Optional[bool] = None # for out-of-warranty users
issue_type: Optional[Literal["hardware", "software"]] = None
tried_basic_steps: Optional[bool] = None
solution_successful: Optional[bool] = None
```
!!! tip "Concept"
The `State` class tracks both the conversation messages and the workflow progress. Each field represents a decision point in our support process, allowing the bot to remember where the user is in the troubleshooting flow.
## 3. Create tools for state management
Create tools that the LLM can use to update the workflow state based on user responses:
```python
from typing import Literal, Annotated
from langchain_core.messages import ToolMessage
from langchain_core.tools import tool, InjectedToolCallId
from langgraph.types import Command
@tool
def set_warranty_status(
value: Literal["in", "out"],
tool_call_id: Annotated[str, InjectedToolCallId]
) -> Command:
"""Set whether device is under warranty"""
# Determine next step based on warranty status
next_step: WorkflowStep = "ask_repair_or_continue" if value == "out" else "ask_issue_type"
return Command(update={
"warranty_status": value,
"workflow_step": next_step,
"messages": [ToolMessage(content=f"Warranty status set to '{value}'",
tool_call_id=tool_call_id)]
})
@tool
def set_wants_human_help(
value: Literal[True, False],
tool_call_id: Annotated[str, InjectedToolCallId]
) -> Command:
"""Set whether user wants human help for out-of-warranty device"""
# If they want human help, escalate; otherwise continue to issue classification
next_step: WorkflowStep = "escalate" if value else "ask_issue_type"
return Command(update={
"wants_human_help": value,
"workflow_step": next_step,
"messages": [
ToolMessage(content=f"Wants human help: {value}", tool_call_id=tool_call_id)]
})
@tool
def set_issue_type(
value: Literal["hardware", "software"],
tool_call_id: Annotated[str, InjectedToolCallId]
) -> Command:
"""Classify the issue as hardware or software related"""
# Hardware issues escalate immediately; software issues go to troubleshooting
next_step: WorkflowStep = "escalate" if value == "hardware" else "check_troubleshooting"
return Command(update={
"issue_type": value,
"workflow_step": next_step,
"messages": [
ToolMessage(content=f"Issue type set to '{value}'", tool_call_id=tool_call_id)]
})
@tool
def set_tried_basic_steps(
value: Literal[True, False],
tool_call_id: Annotated[str, InjectedToolCallId]
) -> Command:
"""Record whether user has tried basic troubleshooting"""
# If they haven't tried basic steps, suggest them; otherwise offer solution
next_step: WorkflowStep = "suggest_troubleshooting" if not value else "offer_solution"
return Command(update={
"tried_basic_steps": value,
"workflow_step": next_step,
"messages": [
ToolMessage(content=f"Tried basic steps: {value}", tool_call_id=tool_call_id)]
})
@tool
def confirm_troubleshooting_done(
tool_call_id: Annotated[str, InjectedToolCallId]
) -> Command:
"""Confirm user has completed suggested troubleshooting steps"""
next_step: WorkflowStep = "check_troubleshooting"
return Command(update={
"tried_basic_steps": True,
"workflow_step": next_step,
"messages": [
ToolMessage(content="Troubleshooting steps completed", tool_call_id=tool_call_id)]
})
@tool
def set_solution_successful(
value: Literal[True, False],
tool_call_id: Annotated[str, InjectedToolCallId]
) -> Command:
"""Record whether the suggested solution worked"""
# If solution worked, success; otherwise escalate
next_step: WorkflowStep = "success" if value else "escalate"
return Command(update={
"solution_successful": value,
"workflow_step": next_step,
"messages": [
ToolMessage(content=f"Solution successful: {value}", tool_call_id=tool_call_id)]
})
ALL_TOOLS = [
set_warranty_status,
set_wants_human_help,
set_issue_type,
set_tried_basic_steps,
confirm_troubleshooting_done,
set_solution_successful,
]
```
These tools now handle both state updates and workflow transitions. Each tool determines the next step in the workflow based on the user's response, eliminating the need for complex routing logic.
## 4. Set up the chat model
{% include-markdown "../../snippets/chat_model_tabs.md" %}
## 5. Create step-specific prompts
Each workflow step needs a specific prompt to guide the LLM's behavior:
```python
from typing import Dict, List
TOOL_MAP: Dict[WorkflowStep, List] = {
"check_warranty": [set_warranty_status],
"ask_repair_or_continue": [set_wants_human_help],
"ask_issue_type": [set_issue_type],
"check_troubleshooting": [set_tried_basic_steps],
"suggest_troubleshooting": [confirm_troubleshooting_done],
"offer_solution": [set_solution_successful],
}
def get_prompt_for_step(step: WorkflowStep) -> str:
"""Get the appropriate prompt for each workflow step"""
prompts: Dict[WorkflowStep, str] = {
"check_warranty": """
Ask the user whether their device is under warranty.
Use the set_warranty_status tool to record their response as 'in' or 'out'.
""",
"ask_repair_or_continue": """
The device is out of warranty. Ask if they'd like to:
1. Continue troubleshooting themselves, or
2. Speak to a human about repair options
Use the set_wants_human_help tool to record their choice.
""",
"ask_issue_type": """
Ask what issue they are experiencing with their device.
Based on their response, classify it as 'hardware' (physical problems, broken parts)
or 'software' (app crashes, performance issues, etc.).
Use the set_issue_type tool to record the classification.
""",
"check_troubleshooting": """
Ask if they have already tried basic troubleshooting steps like:
- Restarting the device
- Updating the software/app
Use the set_tried_basic_steps tool to record their response.
""",
"suggest_troubleshooting": """
Suggest they try restarting their device and updating the software/app.
Ask them to try these steps and confirm once they're done.
Use the confirm_troubleshooting_done tool once they confirm they've tried.
""",
"offer_solution": """
Suggest they reset the app settings or clear the app cache.
Ask them to try this solution and confirm if it resolved the issue.
Use the set_solution_successful tool to record whether it worked.
""",
}
return prompts.get(step, "Continue helping the user with their issue.")
```
## 6. Create the model node
The model node handles LLM interactions with the appropriate tools for each step:
```python
from typing import Dict, Literal
from langchain.chat_models import init_chat_model
from langchain_core.messages import AIMessage
# Initialize the chat model
llm = init_chat_model("anthropic:claude-3-5-sonnet-latest")
async def call_model(state: State) -> Dict:
"""Call the LLM with appropriate tools for the current step"""
# Handle terminal states
if state.workflow_step == "success":
return {
"messages": [AIMessage(
content="Great! I'm glad we could resolve your issue. Is there anything else I can help you with today?")],
"is_last_step": True
}
elif state.workflow_step == "escalate":
return {
"messages": [AIMessage(
content="I'm going to connect you with one of our human support specialists who can better assist you with this issue. Please hold on while I transfer you.")],
"is_last_step": True
}
# For regular workflow steps, get the appropriate prompt and tools
prompt = get_prompt_for_step(state.workflow_step)
tools = TOOL_MAP.get(state.workflow_step, [])
model = llm.bind_tools(tools)
response = await model.ainvoke(
[{"role": "system", "content": prompt}, *state.messages]
)
return {"messages": [response]}
def should_continue(state: State) -> Literal["tools", "call_model", "__end__"]:
"""Determine whether to call tools or continue with the model"""
# If we've reached a terminal state, stop
if state.is_last_step:
return "__end__"
# If the last message has tool calls, execute them
last_msg = state.messages[-1]
if isinstance(last_msg, AIMessage) and last_msg.tool_calls:
return "tools"
# Otherwise, continue with the model
return "call_model"
```
!!! tip "Concept"
This simplified approach moves all the routing logic into the tools themselves. Each tool determines the next workflow step, eliminating the need for complex conditional routing functions. The `should_continue` function simply decides whether to execute tools or continue with the model.
## 8. Build and compile the graph
Now assemble all the components into a complete workflow:
```python
from langgraph.graph import StateGraph, START, END
from langgraph.prebuilt import ToolNode
builder = StateGraph(State)
# Add nodes
builder.add_node("call_model", call_model)
builder.add_node("tools", ToolNode(ALL_TOOLS))
# Set entry point
builder.add_edge(START, "call_model")
# Add conditional edges
builder.add_conditional_edges(
"call_model",
should_continue,
["tools", "call_model", END]
)
# Tools flow back to model
builder.add_edge("tools", "call_model")
# Compile the graph
graph = builder.compile()
```
## 9. Test the workflow
Run the tech support bot to see how it handles different scenarios:
```python
import asyncio
from langchain_core.messages import HumanMessage, AIMessage
async def run_example():
"""Run an example conversation"""
print("\n🔁 Running Tech Support Workflow...\n")
initial_state = State(
messages=[
HumanMessage(content="Hi, my app is crashing a lot and I can't use it.")],
workflow_step="check_warranty"
)
final_state = await graph.ainvoke(initial_state)
print("\n✅ Conversation Complete!")
print(f"Final workflow step: {final_state.workflow_step}")
print(f"Warranty status: {final_state.warranty_status}")
print(f"Issue type: {final_state.issue_type}")
print(f"Tried basic steps: {final_state.tried_basic_steps}")
print(f"Solution successful: {final_state.solution_successful}")
print("\n💬 Final messages:")
for msg in final_state.messages[-3:]: # Show last 3 messages
if isinstance(msg, HumanMessage):
print(f"User: {msg.content}")
elif isinstance(msg, AIMessage):
print(f"Bot: {msg.content}")
if __name__ == "__main__":
asyncio.run(run_example())
```
!!! tip
You can exit the conversation at any time by typing `quit`, `exit`, or `q`.
## Key concepts demonstrated
This tech support bot showcases several important LangGraph concepts:
### 1. **Conditional routing**
The `route_workflow` function implements complex decision logic based on user responses:
- Warranty status determines the initial path
- Issue type (hardware vs software) triggers different responses
- Solution success determines the final outcome
### 2. **Looping behavior**
Step 3 creates a loop where users who haven't tried basic troubleshooting are guided through it:
```
check_troubleshooting → suggest_troubleshooting → check_troubleshooting
```
### 3. **Human escalation**
Multiple escalation points ensure complex issues reach human agents:
- Out-of-warranty users can choose human help
- Hardware issues automatically escalate
- Failed solutions trigger escalation
### 4. **State management**
The workflow tracks user progress through structured state variables, enabling complex multi-turn conversations.
## Testing different scenarios
Try these conversation paths to see how the bot handles various situations:
1. **In-warranty software issue** → Full troubleshooting flow
2. **Out-of-warranty hardware issue** → Immediate escalation
3. **Software issue with successful solution** → Success completion
4. **Software issue with failed solution** → Escalation
## Next steps
This implementation demonstrates how LangGraph can handle real-world customer service scenarios with sophisticated routing, looping, and escalation logic. You can extend this pattern to build more complex workflows for various business processes.
-1
View File
@@ -270,7 +270,6 @@ nav:
- examples/index.md
- Template applications: concepts/template_applications.md # TODO: make tutorial
- Agentic RAG: tutorials/rag/langgraph_agentic_rag.md
- tutorials/tech-support-bot.md
- Agent Supervisor: tutorials/multi_agent/agent_supervisor.md
- SQL agent: tutorials/sql/sql-agent.md
- Prebuilt chat UI: agents/ui.md
+3 -1
View File
@@ -112,4 +112,6 @@ extend-include = ["*.ipynb"]
[tool.codespell]
# https://mypy.readthedocs.io/en/stable/config_file.html
# comma-separated list
ignore-words-list = "infor"
ignore-words-list = "infor,thead,stdio,nd,jupyter,lets,lite,uis,deque"
# Exclude generated files and directories
skip = "*.ambr,*.lock,*.ipynb,*.yaml,*.zlib,*.css.map,*.js.map"
@@ -314,7 +314,7 @@ class PostgresSaver(BasePostgresSaver):
checkpoint_ns,
checkpoint["id"],
checkpoint_id,
Jsonb(copy),
Jsonb(self.serde.dumps_typed(copy)[1]),
Jsonb(get_checkpoint_metadata(config, metadata)),
),
)
@@ -271,7 +271,7 @@ class AsyncPostgresSaver(BasePostgresSaver):
checkpoint_ns,
checkpoint["id"],
checkpoint_id,
Jsonb(copy),
Jsonb(self.serde.dumps_typed(copy)[1]),
Jsonb(get_checkpoint_metadata(config, metadata)),
),
)
@@ -440,7 +440,7 @@ class ShallowPostgresSaver(BasePostgresSaver):
(
thread_id,
checkpoint_ns,
Jsonb(copy),
Jsonb(self.serde.dumps_typed(copy)[1]),
Jsonb(get_checkpoint_metadata(config, metadata)),
),
)
@@ -773,7 +773,7 @@ class AsyncShallowPostgresSaver(BasePostgresSaver):
(
thread_id,
checkpoint_ns,
Jsonb(copy),
Jsonb(self.serde.dumps_typed(copy)[1]),
Jsonb(get_checkpoint_metadata(config, metadata)),
),
)
+2 -2
View File
@@ -73,7 +73,7 @@ While LangGraph can be used standalone, it also integrates seamlessly with any L
- [Guides](https://langchain-ai.github.io/langgraph/how-tos/): Quick, actionable code snippets for topics such as streaming, adding memory & persistence, and design patterns (e.g. branching, subgraphs, etc.).
- [Reference](https://langchain-ai.github.io/langgraph/reference/graphs/): Detailed reference on core classes, methods, how to use the graph and checkpointing APIs, and higher-level prebuilt components.
- [Examples](https://langchain-ai.github.io/langgraph/tutorials/overview/): Guided examples on getting started with LangGraph.
- [Examples](https://langchain-ai.github.io/langgraph/examples/): Guided examples on getting started with LangGraph.
- [LangChain Forum](https://forum.langchain.com/): Connect with the community and share all of your technical questions, ideas, and feedback.
- [LangChain Academy](https://academy.langchain.com/courses/intro-to-langgraph): Learn the basics of LangGraph in our free, structured course.
- [Templates](https://langchain-ai.github.io/langgraph/concepts/template_applications/): Pre-built reference apps for common agentic workflows (e.g. ReAct agent, memory, retrieval etc.) that can be cloned and adapted.
@@ -81,4 +81,4 @@ While LangGraph can be used standalone, it also integrates seamlessly with any L
## Acknowledgements
LangGraph is inspired by [Pregel](https://research.google/pubs/pub37252/) and [Apache Beam](https://beam.apache.org/). The public interface draws inspiration from [NetworkX](https://networkx.org/documentation/latest/). LangGraph is built by LangChain Inc, the creators of LangChain, but can be used without LangChain.
LangGraph is inspired by [Pregel](https://research.google/pubs/pub37252/) and [Apache Beam](https://beam.apache.org/). The public interface draws inspiration from [NetworkX](https://networkx.org/documentation/latest/). LangGraph is built by LangChain Inc, the creators of LangChain, but can be used without LangChain.
+4
View File
@@ -106,3 +106,7 @@ packages = ["langgraph"]
[tool.pytest.ini_options]
addopts = "--full-trace --strict-markers --strict-config --durations=5 --snapshot-warn-unused"
[tool.codespell]
# Ignore words specific to the LangGraph library code
ignore-words-list = "infor,thead,stdio,nd,jupyter,lets,lite,uis,deque,langgraph,langchain,pydantic,typing,async,await,coroutine,iterable,iterables,serializable,deserializable,checkpointer,checkpointing,stateful,statefulness,prebuilt,prebuilt,supervisor,supervisory,swarm,swarming,multiactor,multiactors,subgraph,subgraphs,workflow,workflows,streaming,streamable,streamed,streamer,streamers,streaming,streamable,streamed,streamer,streamers"