Runoob Tutorial ArchiveEnglish

LangGraph Getting Started Tutorial

LangGraph Getting Started Tutorial

LangGraph is alow-level Agent orchestration frameworkdesigned for building stateful, long-running AI workflows.

Unlike traditional linear LLM call chains, LangGraph models workflows asDirected Graph:

Open source address:https://github.com/langchain-ai/langgraph.

3476ec11 af44 4b4 99a9 894 ffb9c5d3

Imagine you are conducting a symphony orchestra: traditional LLM Chains are like playing a piece from beginning to end, only allowing sequential playback; LangGraph, however, is like a conductor who can adjust the performance order at any time based on the audience's reaction, allowing a movement to repeat or jump to a specific section. It gives AI workflows the intelligence of a "conductor"—the ability to loop, branch, and backtrack, truly achieving complex autonomous decision-making.

Why choose LangGraph?

The table below compares the main differences between traditional LLM Chains and LangGraph:

Feature Traditional LLM Chain LangGraph
Workflow structure Linear, unidirectional execution Graph structure, supports cycles
State management Requires manual management Built-in state persistence
Conditional routing Complex to implement Native support
Human-computer collaboration Requires additional development Built-in support for interrupt
Multi-Agent coordination Difficult to implement First-class support
Debugging tools Limited LangGraph Studio

Applicable Scenarios

LangGraph core architecture StateGraph (state graph) State (shared state) — threading through all nodes START Start node Node A Processing node Node B Decision node END End node Node C Alternative branch Complete Needs more processing Loop

Core concepts

Before starting to write code, first understand the three core concepts of LangGraph.

Graph

The Graph is the blueprint of the entire workflow, defining the complete logical structure of the Agent. It consists of Nodes and Edges:

Original prompt (Chinese, left untranslated)



StateGraph

   |-- Nodes(节点)

   |     |-- node_a

   |     |-- node_b

   |     +-- node_c

   +-- Edges(边)

         |-- START -> node_a

         |-- node_a -> node_b(条件边)

         |-- node_a -> node_c(条件边)

         +-- node_b -> END

State

State is passed throughout the graphshared data structureEach node can read and update State, and the updated State will be passed to the next node.

Original prompt (Chinese, left untranslated)



from typing import TypedDict, Annotated

from langgraph.graph import add_messages



class MyState(TypedDict):

    messages: Annotated[list, add_messages]  # 消息列表(自动追加)

    user_name: str                            # 用户名称

    step_count: int                           # 步骤计数

Important:

Annotated[list, add_messages]

indicates that this field uses

add_messages

as a reducer—new messages will be appended to the list instead of overwriting it. This is the core mechanism of LangGraph state management.

State data flow diagram State {msg: []} Node A Process input State {msg: [A]} Node B Generate response State {msg: [A,B]} END Each node reads the State, performs an operation, and returns the updated partial fields.

Nodes

A node is a regular Python function that receives the current State and returns the updated State (partial fields).

Original prompt (Chinese, left untranslated)



def my_node(state: MyState) -> dict:

    # Read status

    messages = state["messages"]

    

    # Execute operation...

    result = "处理结果"

    

    # Return updated fields (no need to return all fields)

    return {"messages": [{"role": "ai", "content": result}]}

Edges

Edges define the flow between nodes:


Environment setup

Install dependencies

Use domestic mirror to install LangGraph and related dependencies:

Original prompt (Chinese, left untranslated)



# Create a virtual environment (recommended)

python -m venv venv

source venv/bin/activate      # macOS/Linux

# venv\Scripts\activate       # Windows



# Install LangGraph and LangChain

pip install langgraph langchain langchain-openai python-dotenv -i https://mirrors.aliyun.com/pypi/simple/



# Optional: Install development tools

pip install langgraph-cli jupyter -i https://mirrors.aliyun.com/pypi/simple/

Configure API Key

Create the file in the project root directory.envConfigure OpenAI and DeepSeek:

Original prompt (Chinese, left untranslated)



# .env file content



# OpenAI Configuration (International Users)

OPENAI_API_KEY=sk-xxx

OPENAI_BASE_URL=https://api.openai.com/v1



# DeepSeek Configuration (Recommended for domestic users)

DEEPSEEK_API_KEY=sk-xxx

DEEPSEEK_BASE_URL=https://api.deepseek.com

DEEPSEEK_MODEL=deepseek-v4-pro

Prompt:

This article's example supports both OpenAI and DeepSeek. Domestic users are recommended to use DeepSeek, with the API address configured as

https://api.deepseek.com

(without /v1); LangChain will automatically construct the path. The DeepSeek API Key can be created at

https://platform.deepseek.com/api_keys

Verification of installation

The first LangGraph program

Original prompt (Chinese, left untranslated)



import langgraph

print(f"LangGraph 版本: {langgraph.__version__}")


The first LangGraph program

Let's start with the simplest example—a linear workflow with only two nodes.

Instance

from

langgraph.

graph

import

StateGraph

,

START

,

END

from

typing

import

TypedDict

Step 1: Define State

class

SimpleState

(

TypedDict

)

:

    message:

str

processed:

bool

Step 2: Define node function

def

greet_node

(

state: SimpleState

)

dict

:

   

"""Welcome node: generate greeting message"""

   

print

(

f

"[greet_node] Received message: {state['message']}"

)

   

return

{

"message"

: f

"Hello!{state['message']}"

}

def

process_node

(

state: SimpleState

)

dict

:

   

"""Process node: marked as processed"""

   

print

(

f

"[process_node] Processing message: {state['message']}"

)

   

return

{

"processed"

:

True

}

Step 3: Build graph

builder

=

StateGraph

(

SimpleState

)

Add node

builder.

add_node

(

"greet"

,

greet_node

)

builder.

add_node

(

"process"

,

process_node

)

Add edge

builder.

add_edge

(

START

,

"greet"

)

builder.

add_edge

(

"greet"

,

"process"

)

builder.

add_edge

(

"process"

,

END

)

Step 4: Compile graph

graph

=

builder.

compile

(

)

Step 5: Run

result

=

graph.

invoke

(

{

   

"message"

:

"World"

,

   

"processed"

:

False

}

)

print

(

f

"\nFinal result: {result}"

)

Running results:

Original prompt (Chinese, left untranslated)



[greet_node] 收到消息: 世界

[process_node] 处理消息: 你好!世界



最终结果: {'message': '你好!世界', 'processed': True}

Visualized graph structure

You can visualize the graph structure directly in a Jupyter Notebook:

Original prompt (Chinese, left untranslated)



# Visualize in Jupyter Notebook

from IPython.display import Image

Image(graph.get_graph().draw_mermaid_png())



# Or print in Mermaid format

print(graph.get_graph().draw_mermaid())


State management

Define state using TypedDict

Original prompt (Chinese, left untranslated)



from typing import TypedDict, Annotated, Optional

from langgraph.graph.message import add_messages



class AgentState(TypedDict):

    # Message history (add_messages reducer appends instead of overwrites)

    messages: Annotated[list, add_messages]

    

    # Standard fields (direct overwrite)

    user_id: str

    session_id: str

    

    # Optional fields

    error: Optional[str]

    

    # Counter (using operator.add as reducer)

    retry_count: Annotated[int, lambda x, y: x + y]

Define state using Pydantic (recommended for production)



from pydantic import BaseModel, Field

from typing import Annotated

from langgraph.graph.message import add_messages



class ProductionState(BaseModel):

    messages: Annotated[list, add_messages] = Field(default_factory=list)

    user_id: str = ""

    confidence_score: float = 0.0

    

    class Config:

        arbitrary_types_allowed = True

MessagesState (built-in shortcut state)

LangGraph provides built-inMessagesStatedesigned for conversational scenarios:

Original prompt (Chinese, left untranslated)



from langgraph.graph import MessagesState



# MessagesState is equivalent to:

# class MessagesState(TypedDict):

#     messages: Annotated[list[AnyMessage], add_messages]



# Use directly, no customization needed

builder = StateGraph(MessagesState)


Nodes

Standard function nodes

Original prompt (Chinese, left untranslated)



def simple_node(state: AgentState) -> dict:

    # Read status

    last_message = state["messages"][-1]

    

    # Execute operation

    response = f"收到: {last_message.content}"

    

    # Return partial status update

    return {

        "messages": [{"role": "assistant", "content": response}]

    }

LLM call nodes

Instance

import

os

from

dotenv

import

load_dotenv

from

langchain_openai

import

ChatOpenAI

from

langchain_core.

messages

import

SystemMessage

load_dotenv

(

)

Using DeepSeek model

llm

=

ChatOpenAI

(

    model

=

os

.

getenv

(

'DEEPSEEK_MODEL'

,

'deepseek-v4-pro'

)

,

openai_api_key

=

os

.

getenv

(

'DEEPSEEK_API_KEY'

)

,

openai_api_base

=

os

.

getenv

(

'DEEPSEEK_BASE_URL'

,

'https://api.deepseek.com'

)

,

temperature

=

0

)

def

llm_node

(

state:

dict

)

dict

:

   

"Call LLM node"

system_prompt

=

SystemMessage

(

content

=

"You are a helpful assistant."

)

   

   

Merge system prompt with conversation history

messages

=

[

system_prompt

]

[

"messages"

]

   

   

Call LLM

response

=

llm.

invoke

(

messages

)

   

   

return

{

"messages"

:

[

response

]

}

Asynchronous node

Original prompt (Chinese, left untranslated)



import asyncio



async def async_node(state: AgentState) -> dict:

    """异步节点,适合 I/O 密集型操作"""

    # Simulate asynchronous operation (like API call, database query)

    await asyncio.sleep(0.1)

    

    result = await some_async_api_call(state["messages"][-1].content)

    return {"messages": [{"role": "assistant", "content": result}]}



# Using asynchronous graph

result = await graph.ainvoke({"messages": [...]})

Using a class as a node

Original prompt (Chinese, left untranslated)



class RouterNode:

    def __init__(self, llm, system_prompt: str):

        self.llm = llm

        self.system_prompt = system_prompt

    

    def __call__(self, state: AgentState) -> dict:

        """类实例可以作为节点使用"""

        messages = [

            SystemMessage(content=self.system_prompt),

            *state["messages"]

        ]

        response = self.llm.invoke(messages)

        return {"messages": [response]}



# Add class node

router = RouterNode(llm, "你是一个专业的路由助手。")

builder.add_node("router", router)


Edges and conditional routing

Normal edge

Original prompt (Chinese, left untranslated)



# Fixed path: always execute node_b after node_a completes

builder.add_edge("node_a", "node_b")



# End: graph ends after node_a completes

builder.add_edge("node_a", END)

Conditional edge

Conditional edges are a core feature of LangGraph, dynamically determining the next step based on the current State.

Original prompt (Chinese, left untranslated)



def route_after_llm(state: AgentState) -> str:

    """

    路由函数:根据 LLM 的最新输出决定走哪条路径

    返回值必须是已注册节点名称或 END

    """

    last_message = state["messages"][-1]

    

    # If LLM requests to use tools

    if hasattr(last_message, "tool_calls") and last_message.tool_calls:

        return "tools"

    

    # else exit

    return END



# Add conditional edge

builder.add_conditional_edges(

    "llm",              # 源节点

    route_after_llm,    # 路由函数

    {

        "tools": "tool_executor",   # 返回 "tools" 时 -> tool_executor 节点

        END: END                    # 返回 END 时 -> 结束

    }

)

Conditional routing diagram START Router Intent recognition weather_agent Weather query code_agent Code help general_agent General conversation farewell "weather" "code" "other" "goodbye" END

Parallel Execution (Fan-out)

Original prompt (Chinese, left untranslated)



# Parallel branching from one node to multiple nodes

builder.add_edge("start_node", "branch_a")

builder.add_edge("start_node", "branch_b")

builder.add_edge("start_node", "branch_c")



# Multiple nodes converge to one node (Fan-in)

builder.add_edge("branch_a", "merge_node")

builder.add_edge("branch_b", "merge_node")

builder.add_edge("branch_c", "merge_node")

Complete Conditional Routing Example

Instance

import

os

from

dotenv

import

load_dotenv

from

langgraph.

graph

import

StateGraph

,

START

,

END

,

MessagesState

from

langchain_openai

import

ChatOpenAI

from

langchain_core.

messages

import

SystemMessage

,

HumanMessage

load_dotenv

(

)

Initialize LLM

llm

=

ChatOpenAI

(

    model

=

os

.

getenv

(

'DEEPSEEK_MODEL'

,

'deepseek-v4-pro'

)

,

openai_api_key

=

os

.

getenv

(

'DEEPSEEK_API_KEY'

)

,

openai_api_base

=

os

.

getenv

(

'DEEPSEEK_BASE_URL'

,

'https://api.deepseek.com'

)

,

temperature

=

0.7

)

routing function

def

classify_intent

(

state: MessagesState

)

str

:

   

"""Routes to different Agents based on user intent"""

last_message

=

state

[

"messages"

]

[

1

]

    content

=

last_message.

content

.

lower

(

)

   

   

if

"Weather"

in

content

or

"Temperature"

in

content:

       

return

"weather_agent"

   

elif

"code"

in

content

or

"Programming"

in

content:

       

return

"code_agent"

   

elif

"Goodbye"

in

content

or

"Exit"

in

content:

       

return

"farewell"

   

else

:

       

return

"general_agent"

Define each Agent node

def

router_node

(

state: MessagesState

)

dict

:

   

Route node: no processing, only used to trigger route judgment

   

return

{

}

def

weather_node

(

state: MessagesState

)

dict

:

   

"""Weather Agent"""

    response

=

llm.

invoke

(

[

SystemMessage

(

content

=

"You are a weather assistant that answers weather-related questions in a friendly manner. If there is no real-time data, you can give general advice."

)

,

*state

[

"messages"

]

   

]

)

   

return

{

"messages"

:

[

response

]

}

def

code_node

(

state: MessagesState

)

dict

:

   

"""Code Agent"""

response

=

llm.

invoke

(

[

SystemMessage

(

content

=

"You are a programming assistant skilled at answering code questions and providing clear code examples."

)

,

*state

[

"messages"

]

   

]

)

   

return

{

"messages"

:

[

response

]

}

def

general_node

(

state: MessagesState

)

dict

:

   

"""General Agent"""

response

=

llm.

invoke

(

[

SystemMessage

(

content

=

"You are a friendly AI assistant that can answer all kinds of questions."

)

,

*state

[

"messages"

]

   

]

)

   

return

{

"messages"

:

[

response

]

}

def

farewell_node

(

state: MessagesState

)

dict

:

   

"Goodbye Node"

   

return

{

"messages"

:

[

{

"role"

:

"assistant"

,

"content"

:

"Goodbye! Looking forward to communicating with you next time."

}

]

}

Build graph

builder

=

StateGraph

(

MessagesState

)

Add node

builder.

add_node

(

"router"

,

router_node

)

builder.

add_node

(

"weather_agent"

,

weather_node

)

builder.

add_node

(

"code_agent"

,

code_node

)

builder.

add_node

(

"general_agent"

,

general_node

)

builder.

add_node

(

"farewell"

,

farewell_node

)

Add edge

builder.

add_edge

(

START

,

"router"

)

builder.

add_conditional_edges

(

   

"router"

,

classify_intent

,

   

{

       

"weather_agent"

:

"weather_agent"

,

       

"code_agent"

:

"code_agent"

,

       

"general_agent"

:

"general_agent"

,

       

"farewell"

:

"farewell"

,

   

}

)

End after all agent nodes are processed

for

node

in

[

"weather_agent"

,

"code_agent"

,

"general_agent"

,

"farewell"

]

:

builder.

add_edge

(

node

,

END

)

Compile graph

graph

=

builder.

compile

(

)

Test different intents

test_inputs

=

[

   

"What is the weather like in Beijing today?"

,

   

"Write me a Python quicksort"

,

   

"Hello, introduce yourself"

,

   

Goodbye!

]

for

user_input

in

test_inputs:

   

print

(

f

"\nUser: {user_input}"

)

result

=

graph.

invoke

(

{

"messages"

:

[

HumanMessage

(

content

=

user_input

)

]

}

)

   

print

(

f

"Assistant: {result['messages'][-1].content[:100]}..."

)

   

print

(

"-"

50

)

Example of the running result:

Original prompt (Chinese, left untranslated)



用户: 北京今天天气怎么样?

助手: 很抱歉,我没有实时天气数据。不过北京现在是春季,建议您出门时关注天气预报...

--------------------------------------------------



用户: 帮我写一个 Python 快速排序

Assistant: Okay, here is a Python implementation of the quicksort algorithm:



```python

def quicksort(arr):

    if len(arr) <= 1:

        return arr

    ...

--------------------------------------------------



用户: 你好,介绍一下你自己

助手: 你好!我是一个 AI 助手,很高兴为你服务。我可以帮你回答各种问题...

--------------------------------------------------



用户: 再见啦!

助手: 再见!期待下次与你交流。

--------------------------------------------------

Note:

The return value of the conditional routing function must be the name of a node registered in the graph or

END

. If an unregistered name is returned, an error will be thrown during graph execution.


Build a conversational robot

Now, build a robot that supports multi-turn conversations using the knowledge you have learned. This robot can remember the conversation context and achieve a continuous interactive experience.

Example

import

os

from

dotenv

import

load_dotenv

from

langgraph.

graph

import

StateGraph

,

MessagesState

,

START

,

END

from

langchain_openai

import

ChatOpenAI

from

langchain_core.

messages

import

SystemMessage

,

HumanMessage

load_dotenv

(

)

Initialize LLM (using DeepSeek)

llm

=

ChatOpenAI

(

    model

=

os

.

getenv

(

'DEEPSEEK_MODEL'

,

'deepseek-v4-pro'

)

,

openai_api_key

=

os

.

getenv

(

'DEEPSEEK_API_KEY'

)

,

openai_api_base

=

os

.

getenv

(

'DEEPSEEK_BASE_URL'

,

'https://api.deepseek.com'

)

,

temperature

=

0.7

)

SYSTEM_PROMPT

=

"""You are a friendly and professional AI assistant.
Your answers should be:

def

chatbot_node

(

state: MessagesState

)

dict

:

   

Core dialogue node

system

=

SystemMessage

(

content

=

SYSTEM_PROMPT

)

messages

=

[

system

]

[

"messages"

]

response

=

llm.

invoke

(

messages

)

   

return

{

"messages"

:

[

response

]

}

Build graph

builder

=

StateGraph

(

MessagesState

)

builder.

add_node

(

"chatbot"

,

chatbot_node

)

builder.

add_edge

(

START

,

"chatbot"

)

builder.

add_edge

(

"chatbot"

,

END

)

graph

=

builder.

compile

(

)

Multi-turn dialogue function

def

chat

(

conversation_history:

list

,

user_input:

str

)

tuple

[

str

,

list

]

:

   

"""Processes a single turn of dialogue and returns the AI response and updated history"""

conversation_history.

append

(

HumanMessage

(

content

=

user_input

)

)

result

=

graph.

invoke

(

{

"messages"

: conversation_history

}

)

conversation_history

=

result

[

"messages"

]

    ai_response

=

conversation_history

[

1

]

.

content

   

return

ai_response

,

conversation_history

Multi-turn conversation example

history

=

[

]

while

True

:

user_input

=

input

(

"You: "

)

   

if

user_input.

lower

(

)

in

[

"Exit"

,

"exit"

,

"quit"

]

:

       

print

(

"Goodbye!"

)

       

break

   

response

,

history

=

chat

(

history

,

user_input

)

   

print

(

f

"Assistant: {response}\n"

)

Example of running result:

Original prompt (Chinese, left untranslated)



你: 你好,我叫小明

助手: 你好,小明!很高兴认识你。有什么我可以帮助你的吗?



你: 我想学习 Python 编程

Assistant: That's great! Python is a programming language very suitable for beginners. I can help you start from the basics:

1. 首先了解变量和数据类型

2. 学习条件语句和循环

3. 掌握函数的定义和使用

你想从哪个部分开始呢?



你: 你还记得我叫什么吗?

助手: 当然记得,你叫小明!你刚才说想学习 Python 编程,我们可以继续这个话题。



你: 退出

再见!


Tool calling - ReAct Agent

Enabling the Agent to use external tools is one of LangGraph's most powerful features.ReAct(Reason + Act) is the most common Agent pattern: LLM thinks -> selects tool -> executes tool -> observes result -> continues thinking.

ReAct Agent workflow START Agent LLM inference Has tool call? Tools Execute tools Is Return results and continue reasoning END No

Define tools

First, define the tools the Agent can use:

Original prompt (Chinese, left untranslated)



from langchain_core.tools import tool



@tool

def search_web(query: str) -> str:

    """搜索网络获取最新信息。

    

    Args:

        query: 搜索关键词

    

    Returns:

        搜索结果摘要

    """

    # Replace with actual search API in production project

    return f"关于 '{query}' 的搜索结果:这是模拟的搜索结果..."



@tool

def calculate(expression: str) -> str:

    """计算数学表达式。

    

    Args:

        expression: 数学表达式,如 '2 + 2' 或 '100 * 0.8'

    

    Returns:

        计算结果

    """

    import ast

    import operator

    

    # Safe operator mapping

    ops = {

        ast.Add: operator.add,

        ast.Sub: operator.sub,

        ast.Mult: operator.mul,

        ast.Div: operator.truediv,

        ast.Pow: operator.pow,

        ast.USub: operator.neg,

    }

    

    def safe_eval(node):

        if isinstance(node, ast.Expression):

            return safe_eval(node.body)

        elif isinstance(node, ast.Constant):

            return node.value

        elif isinstance(node, ast.BinOp):

            left = safe_eval(node.left)

            right = safe_eval(node.right)

            return ops[type(node.op)](left, right)

        elif isinstance(node, ast.UnaryOp):

            operand = safe_eval(node.operand)

            return ops[type(node.op)](operand)

        else:

            raise ValueError(f"不支持的表达式类型: {type(node)}")

    

    try:

        tree = ast.parse(expression, mode='eval')

        result = safe_eval(tree)

        return f"计算结果: {expression} = {result}"

    except Exception as e:

        return f"计算错误: {str(e)}"



@tool

def get_weather(city: str) -> str:

    """获取指定城市的天气信息。

    

    Args:

        city: 城市名称

    

    Returns:

        天气信息

    """

    # Replace with actual weather API in a real project

    return f"{city} 今日天气:晴,温度 22C,湿度 60%"



tools = [search_web, calculate, get_weather]

Security warning:

Use AST (Abstract Syntax Tree) parsing instead of the calculate tool

eval()

. Directly use

eval()

There is a serious security risk because it can execute arbitrary Python code. In a production environment, be sure to use a safe expression parsing method.

Build ReAct Agent

Instance

import

os

from

dotenv

import

load_dotenv

from

langgraph.

graph

import

StateGraph

,

MessagesState

,

START

,

END

from

langgraph.

prebuilt

import

ToolNode

,

tools_condition

from

langchain_openai

import

ChatOpenAI

from

langchain_core.

tools

import

tool

from

langchain_core.

messages

import

HumanMessage

import

ast

import

operator

load_dotenv

(

)

Define tool

@

tool

def

search_web

(

query:

str

)

str

:

   

"""Search the web to get the latest information."""

   

return

f

Search results for '{query}': These are simulated search results...

@

tool

def

calculate

(

expression:

str

)

str

:

   

"""Calculates a mathematical expression."""

ops

=

{

ast.

Add

:

operator

.

add

,

ast.

Sub

:

operator

.

sub

,

        ast.

Mult

:

operator

.

mul

,

ast.

Div

:

operator

.

truediv

,

ast.

Pow

:

operator

.

pow

,

ast.

USub

:

operator

.

neg

,

   

}

   

   

def

safe_eval

(

node

)

:

       

if

isinstance

(

node

,

ast.

Expression

)

:

           

return

safe_eval

(

node.

body

)

       

elif

isinstance

(

node

,

ast.

Constant

)

:

           

return

node.

value

       

elif

isinstance

(

node

,

ast.

BinOp

)

:

left

=

safe_eval

(

node.

left

)

            right

=

safe_eval

(

node.

right

)

           

return

ops

[

type

(

node.

op

)

]

(

left

,

right

)

       

elif

isinstance

(

node

,

ast.

UnaryOp

)

:

operand

=

safe_eval

(

node.

operand

)

           

return

ops

[

type

(

node.

op

)

]

(

operand

)

       

else

:

           

raise

ValueError

(

f

Unsupported expression type: {type(node)}

)

   

   

try

:

tree

=

ast.

parse

(

expression

,

mode

=

'eval'

)

result

=

safe_eval

(

tree

)

       

return

f

"Calculation result: {expression} = {result}"

   

except

Exception

as

e:

       

return

f

"Calculation error: {str(e)}"

@

tool

def

get_weather

(

city:

str

)

str

:

   

"""Get weather information for a specified city."""

   

return

f

"{city} today's weather: Sunny, temperature 22C, humidity 60%"

tools

=

[

search_web

,

calculate

,

get_weather

]

Initialize LLM and bind tools

llm

=

ChatOpenAI

(

    model

=

os

.

getenv

(

'DEEPSEEK_MODEL'

,

'deepseek-v4-pro'

)

,

openai_api_key

=

os

.

getenv

(

'DEEPSEEK_API_KEY'

)

,

openai_api_base

=

os

.

getenv

(

'DEEPSEEK_BASE_URL'

,

'https://api.deepseek.com'

)

,

temperature

=

0

)

llm_with_tools

=

llm.

bind_tools

(

tools

)

def

agent_node

(

state: MessagesState

)

dict

:

   

"""Agent inference node: calls LLM to decide the next action"""

    response

=

llm_with_tools.

invoke

(

state

[

"messages"

]

)

   

return

{

"messages"

:

[

response

]

}

Build ReAct graph

builder

=

StateGraph

(

MessagesState

)

Add node

builder.

add_node

(

"agent"

,

agent_node

)

builder.

add_node

(

"tools"

,

ToolNode

(

tools

)

)

 

Built-in ToolNode automatically handles tool calls

Add edge

builder.

add_edge

(

START

,

"agent"

)

Conditional routing: If the LLM requests a tool, execute the tool; otherwise, terminate.

builder.

add_conditional_edges

(

   

"agent"

,

    tools_condition

,

 

Built-in routing function

   

{

       

"tools"

:

"tools"

,

END: END

   

}

)

After the tool executes, return to the agent for further reasoning

builder.

add_edge

(

"tools"

,

"agent"

)

graph

=

builder.

compile

(

)

Test

result

=

graph.

invoke

(

{

   

"messages"

:

[

HumanMessage

(

content

=

"What is the weather like in Beijing today? Also, help me calculate 1234 * 5678"

)

]

}

)

for

message

in

result

[

"messages"

]

:

   

print

(

f

"[{message.type}]: {message.content[:200] if message.content else '(Tool call)'}"

)

Streaming output tool calling process

Original prompt (Chinese, left untranslated)



# Stream observation of the Agent's every step

for chunk in graph.stream(

    {"messages": [HumanMessage(content="Search for the latest features of LangGraph")]},

    stream_mode="updates"

):

    for node_name, updates in chunk.items():

        print(f"\n=== 节点: {node_name} ===")

        for msg in updates.get("messages", []):

            if hasattr(msg, "tool_calls") and msg.tool_calls:

                for tc in msg.tool_calls:

                    print(f"  -> 调用工具: {tc['name']}({tc['args']})")

            else:

                print(f"  -> 输出: {msg.content[:200] if msg.content else '(无内容)'}")

Tip:

ToolNode

and

tools_condition

are built-in components of LangGraph.

ToolNode

Automatically parses tool calls returned by the LLM and executes the corresponding tool function;

tools_condition

It is a routing function that checks if the LLM output contains a tool call request; if so, it returns "tools", otherwise it returns END.


Human-in-the-Loop Human-computer collaboration

LangGraph natively supports pausing during workflow execution to wait for manual review or input. This is very useful for sensitive operations that require human confirmation.

Pause execution using interrupt

Original prompt (Chinese, left untranslated)



from langgraph.types import interrupt

from langgraph.checkpoint.memory import MemorySaver



def sensitive_action_node(state: MessagesState) -> dict:

    """执行敏感操作前请求人工审批"""

    last_msg = state["messages"][-1].content

    

    # Pause the execution of the diagram, waiting for manual decision

    human_decision = interrupt({

        "question": "是否批准执行以下操作?",

        "action": last_msg,

        "risk_level": "中等"

    })

    

    if human_decision == "approve":

        return {"messages": [{"role": "assistant", "content": "操作已批准并执行完毕。"}]}

    else:

        return {"messages": [{"role": "assistant", "content": "操作已取消。"}]}



# Must use checkpointer to support interrupt

checkpointer = MemorySaver()

graph = builder.compile(checkpointer=checkpointer)

Complete approval workflow

Instance

import

os

from

dotenv

import

load_dotenv

from

langgraph.

graph

import

StateGraph

,

MessagesState

,

START

,

END

from

langgraph.

types

import

Command

,

interrupt

from

langgraph.

checkpoint

.

memory

import

MemorySaver

from

langchain_core.

messages

import

HumanMessage

load_dotenv

(

)

def

request_node

(

state: MessagesState

)

dict

:

   

"""Receive user request"""

   

return

{

"messages"

: state

[

"messages"

]

}

def

approval_node

(

state: MessagesState

)

dict

:

   

Approval node: Pause and wait for manual approval

last_msg

=

state

[

"messages"

]

[

1

]

.

content

   

   

Pause execution and wait for manual decision

human_decision

=

interrupt

(

{

       

"question"

:

"Do you approve executing the following operation?"

,

       

"action"

: last_msg

   

}

)

   

   

if

human_decision

==

"approve"

:

       

return

{

"messages"

:

[

{

"role"

:

"assistant"

,

"content"

: f

"Operation approved: {last_msg}"

}

]

}

   

else

:

       

return

{

"messages"

:

[

{

"role"

:

"assistant"

,

"content"

:

"Operation was rejected."

}

]

}

def

execute_node

(

state: MessagesState

)

dict

:

   

"""Execute node"""

   

return

{

"messages"

:

[

{

"role"

:

"assistant"

,

"content"

:

"Task execution completed!"

}

]

}

Build graph

builder

=

StateGraph

(

MessagesState

)

builder.

add_node

(

"request"

,

request_node

)

builder.

add_node

(

"approval"

,

approval_node

)

builder.

add_node

(

"execute"

,

execute_node

)

builder.

add_edge

(

START

,

"request"

)

builder.

add_edge

(

"request"

,

"approval"

)

builder.

add_edge

(

"approval"

,

"execute"

)

builder.

add_edge

(

"execute"

,

END

)

Compile the graph using checkpointer

checkpointer

=

MemorySaver

(

)

graph

=

builder.

compile

(

checkpointer

=

checkpointer

)

Use a unique thread_id for each conversation

config

=

{

"configurable"

:

{

"thread_id"

:

"approval-session-001"

}

}

Step 1: Start the diagram, which will pause at the interrupt

print

(

"=== Step 1: Submit request ==="

)

result

=

graph.

invoke

(

   

{

"messages"

:

[

HumanMessage

(

content

=

"Please delete all test data in the database"

)

]

}

,

config

=

config

)

print

(

"Image paused, awaiting approval..."

)

Step 2: Resume execution after manual approval using Command

print

(

"\n=== Step 2: Manual Approval ==="

)

Approval operation

result

=

graph.

invoke

(

Command

(

resume

=

"approve"

)

,

config

=

config

)

print

(

f

"Final result: {result['messages'][-1].content}"

)

To reject, use:

graph.invoke(Command(resume="reject"), config=config)

Set a breakpoint on the edge

Original prompt (Chinese, left untranslated)



# Another way: specify breakpoint at compile time

graph = builder.compile(

    checkpointer=checkpointer,

    interrupt_before=["sensitive_node"],   # 执行该节点前暂停

    # interrupt_after=["review_node"],     # pause after executing this node

)

Important:

checkpointer

is the prerequisite for implementing

interrupt

Without a checkpointer, the graph cannot save the state at pause, and thus cannot continue execution upon recovery. MemorySaver is suitable for development and testing; SqliteSaver or other persistent storage is recommended for production environments.


Persistent Memory

LangGraph provides a built-in state persistence mechanism, allowing Agents to remember conversation history across sessions.

In-memory storage (suitable for development and testing)

Original prompt (Chinese, left untranslated)



from langgraph.checkpoint.memory import MemorySaver



checkpointer = MemorySaver()

graph = builder.compile(checkpointer=checkpointer)



# Use thread_id to distinguish different sessions

config_user_a = {"configurable": {"thread_id": "user-alice"}}

config_user_b = {"configurable": {"thread_id": "user-bob"}}



# Alice's dialogue

graph.invoke({"messages": [HumanMessage(content="My name is Alice")]}, config=config_user_a)

graph.invoke({"messages": [HumanMessage(content="What is my name?")]}, config=config_user_a)

# Agent remembers: your name is Alice



# Bob's dialogue is completely independent

graph.invoke({"messages": [HumanMessage(content="What is my name?")]}, config=config_user_b)

# Agent does not know Bob's name (different thread_id)

SQLite persistent storage (suitable for local projects)

Original prompt (Chinese, left untranslated)



# Install dependencies

# pip install langgraph-checkpoint-sqlite



from langgraph.checkpoint.sqlite import SqliteSaver



# Persist data to file, conversation history remains after program restart

with SqliteSaver.from_conn_string("./chat_memory.db") as checkpointer:

    graph = builder.compile(checkpointer=checkpointer)

    

    config = {"configurable": {"thread_id": "persistent-chat"}}

    

    # First run

    graph.invoke({"messages": [HumanMessage(content="My name is Zhang San")]}, config=config)

    

    # Runs again after program restart, memory still exists

    result = graph.invoke(

        {"messages": [HumanMessage(content="Do you still remember what my name is?")]},

        config=config

    )

View conversation history

Original prompt (Chinese, left untranslated)



# Get the complete state history of a thread

history = list(graph.get_state_history(config))



for snapshot in history:

    print(f"时间: {snapshot.created_at}")

    print(f"消息数: {len(snapshot.values['messages'])}")

    print("---")



# Get current status

current_state = graph.get_state(config)

print(f"当前消息数: {len(current_state.values['messages'])}")

Hint:

thread_id

It is the unique identifier for a session, used to isolate the state of different users or different conversations. All calls with the same thread_id will share the conversation history, and different thread_ids are completely independent. In multi-user scenarios, a user ID or session ID is usually used as the thread_id.


Multi-Agent System

LangGraph excels at coordinating multiple specialized Agents to work together. By breaking down complex tasks to different expert Agents, it can achieve stronger problem-solving capabilities.

Multi-Agent collaboration architecture (Supervisor pattern) Supervisor Supervisor - task assignment Research Agent Information gathering Writing Agent Content creation Review Agent Quality review Assign tasks Assign tasks Return result Return result The Supervisor coordinates expert Agents; each Agent returns its result to the Supervisor, which decides the next step

Master-Slave Architecture (Supervisor Pattern)

Instance

import

os

from

dotenv

import

load_dotenv

from

langgraph.

graph

import

StateGraph

,

MessagesState

,

START

,

END

from

langchain_openai

import

ChatOpenAI

from

langchain_core.

messages

import

SystemMessage

,

HumanMessage

load_dotenv

(

)

Initialize LLM

llm

=

ChatOpenAI

(

    model

=

os

.

getenv

(

'DEEPSEEK_MODEL'

,

'deepseek-v4-pro'

)

,

openai_api_key

=

os

.

getenv

(

'DEEPSEEK_API_KEY'

)

,

openai_api_base

=

os

.

getenv

(

'DEEPSEEK_BASE_URL'

,

'https://api.deepseek.com'

)

,

temperature

=

0

)

Define expert Agent

def

research_agent

(

state: MessagesState

)

dict

:

   

"Research Agent: Responsible for information collection"

system

=

SystemMessage

(

content

=

"You are a professional researcher responsible for collecting and organizing information. Please summarize the key information concisely."

)

response

=

llm.

invoke

(

[

system

]

[

"messages"

]

)

   

return

{

"messages"

:

[

response

]

}

def

writing_agent

(

state: MessagesState

)

dict

:

   

"""Writing Agent: responsible for content creation"""

system

=

SystemMessage

(

content

=

"You are a professional writer responsible for creating content based on existing information. Please keep the content clear and fluent."

)

response

=

llm.

invoke

(

[

system

]

[

"messages"

]

)

   

return

{

"messages"

:

[

response

]

}

def

review_agent

(

state: MessagesState

)

dict

:

   

"""Review Agent: responsible for quality control"""

system

=

SystemMessage

(

content

=

"You are a professional editor responsible for reviewing and improving content quality. Please point out issues and provide suggestions for improvement."

)

response

=

llm.

invoke

(

[

system

]

[

"messages"

]

)

   

return

{

"messages"

:

[

response

]

}

Supervisor Agent decides the flow

def

supervisor_node

(

state: MessagesState

)

dict

:

   

"""Supervisor: coordinates the work of various expert Agents"""

system

=

SystemMessage

(

content

=

"""You are a workflow supervisor.
Decide which Agent should handle the next step based on the task progress.
Analyze the conversation history and return only one of the following: RESEARCH, WRITING, REVIEW, FINISH

)

response

=

llm.

invoke

(

[

system

]

[

"messages"

]

)

   

return

{

"messages"

:

[

response

]

}

def

route_by_supervisor

(

state: MessagesState

)

str

:

   

"""Route based on supervisor decision"""

    last_msg

=

state

[

"messages"

]

[

1

]

.

content

.

strip

(

)

.

upper

(

)

   

   

if

"RESEARCH"

in

last_msg:

       

return

"research"

   

elif

"WRITING"

in

last_msg:

       

return

"writing"

   

elif

"REVIEW"

in

last_msg:

       

return

"review"

   

else

:

       

return

END

Build multi-Agent graph

builder

=

StateGraph

(

MessagesState

)

builder.

add_node

(

"supervisor"

,

supervisor_node

)

builder.

add_node

(

"research"

,

research_agent

)

builder.

add_node

(

"writing"

,

writing_agent

)

builder.

add_node

(

"review"

,

review_agent

)

builder.

add_edge

(

START

,

"supervisor"

)

builder.

add_conditional_edges

(

"supervisor"

,

route_by_supervisor

)

Return to the supervisor after each expert completes

for

agent

in

[

"research"

,

"writing"

,

"review"

]

:

builder.

add_edge

(

agent

,

"supervisor"

)

graph

=

builder.

compile

(

)

Test multi-Agent collaboration

result

=

graph.

invoke

(

{

   

"messages"

:

[

HumanMessage

(

content

=

"Please help me write a short introductory article about Python decorators"

)

]

}

)

print

(

"=== Multi-Agent Collaboration Complete ==="

)

for

i

,

msg

in

enumerate

(

result

[

"messages"

]

)

:

   

print

(

f

"\n[{i+1}] {msg.type}: {msg.content[:150]}..."

)

Subgraph

Encapsulate complex sub-processes as subgraphs for reuse in the main graph:

Original prompt (Chinese, left untranslated)



# Encapsulate complex sub-processes as subgraphs for reuse in the main graph

sub_builder = StateGraph(MessagesState)

sub_builder.add_node("step1", step1_node)

sub_builder.add_node("step2", step2_node)

sub_builder.add_edge(START, "step1")

sub_builder.add_edge("step1", "step2")

sub_builder.add_edge("step2", END)

sub_graph = sub_builder.compile()



# Use subplots in the main figure

main_builder = StateGraph(MessagesState)

main_builder.add_node("preprocessing", preprocess_node)

main_builder.add_node("sub_workflow", sub_graph)  # 直接使用编译好的子图

main_builder.add_node("postprocessing", postprocess_node)



main_builder.add_edge(START, "preprocessing")

main_builder.add_edge("preprocessing", "sub_workflow")

main_builder.add_edge("sub_workflow", "postprocessing")

main_builder.add_edge("postprocessing", END)



main_graph = main_builder.compile()


LangGraph Studio Visualization Debugging

LangGraph Studio is the official visualization development environment that allows you to view the Agent's execution process in real-time, greatly improving development and debugging efficiency.

Install LangGraph CLI



pip install langgraph-cli -i https://mirrors.aliyun.com/pypi/simple/

Create project configuration file

Create in the project root directorylanggraph.jsonConfiguration file:



{

  "dependencies": ["."],

  "graphs": {

    "my_agent": "./my_agent.py:graph"

  },

  "env": ".env"

}

Start the development server



langgraph dev

Access after startinghttp://localhost:8123and you can use LangGraph Studio in the browser.

Main features of Studio

Environment Requirements:

LangGraph Studio requires Docker environment support. Please ensure Docker Desktop is installed and running before starting the development server.


Best Practices and Common Issues

Best Practices

State Design Considerations

Node design considerations

Error handling

Original prompt (Chinese, left untranslated)



def robust_node(state: AgentState) -> dict:

    try:

        result = risky_operation(state)

        return {"messages": [result], "error": None}

    except Exception as e:

        return {

            "error": str(e),

            "messages": [{"role": "assistant", "content": f"操作失败: {e}"}]

        }

Avoid infinite loops

Original prompt (Chinese, left untranslated)



def route_with_limit(state: AgentState) -> str:

    # Set maximum retry count to prevent infinite loop

    if state.get("retry_count", 0) >= 3:

        return END

    

    if needs_retry(state):

        return "retry_node"

    return END

Frequently Asked Questions FAQ

Q1: What if the node return value format is incorrect?

Original prompt (Chinese, left untranslated)



# Error: directly modifying the state object

def bad_node(state):

    state["messages"].append(...)  # 不要直接修改

    return state



# Correct: return fields that need updating

def good_node(state):

    return {"messages": [new_message]}  # 只返回变更字段

Q2: How to pass temporary data between nodes?

Add temporary data to State definition, or use an underscore prefix convention for internal fields:

Original prompt (Chinese, left untranslated)



from typing import TypedDict



class PublicState(TypedDict):

    messages: list  # 对外暴露



class PrivateState(TypedDict):

    messages: list

    _internal_cache: dict  # 以下划线开头约定为内部使用

Q3: How to debug the node execution process?

Original prompt (Chinese, left untranslated)



# Observe the output of each node using stream mode

for event in graph.stream(initial_state, stream_mode="updates"):

    for node_name, state_update in event.items():

        print(f"\n[节点: {node_name}]")

        print(f"更新: {state_update}")

Q4: What is the difference between StateGraph and MessageGraph?

MessageGraphThis is an early version of the API and has limited functionality. It is now recommended to uniformly useStateGraph, it is more flexible and has more complete functions. To process messages, useStateGraph(MessagesState)or a custom State containingmessagesfields.

Note:

MessageGraph

has been deprecated; please use

StateGraph

. If your code is still using MessageGraph, it is recommended to migrate to StateGraph(MessagesState) as soon as possible to get better support and more features.


Summary

This article systematically introduces the core concepts and practical applications of the LangGraph framework. LangGraph enables developers to build complex AI Agents with looping, branching, and state persistence capabilities through graph-structured workflow orchestration. Compared to traditional linear LLM Chains, LangGraph has significant advantages in handling scenarios that require multi-step reasoning, human-computer collaboration, and multi-Agent coordination.

Concepts Description Key Code
StateGraph Directed graph workflow engine, the core of LangGraph StateGraph(MyState)
State Shared state data structure between nodes TypedDict+Annotated
Nodes Function nodes that execute specific operations builder.add_node()
Edges Flow path between nodes, supports conditional branching add_edge()/add_conditional_edges()
ReAct Agent Reasoning + Action loop mode ToolNode+tools_condition
Human-in-Loop Manual approval and intervention mechanism interrupt()+Command(resume=)
Persistence Session memory and state saving MemorySaver/SqliteSaver
Multi-Agent Multi-Expert Collaboration System Supervisor Pattern

Recommended Learning Path

Basic concepts Simple workflow ReAct Agent Human-machine collaboration Multi-Agent LangGraph Studio