一、 初识LangGraph
LangGraph受到诸多引领智能体(agent)未来发展的企业信赖,包括 Klarna、Replit、Elastic等。 它是一款底层编排框架与运行时环境,用于构建、管理和部署长期运行的有状态智能体。 LangGraph属于底层的工具,它专注于智能体编排所需的核心底层能力,包括持久化执行(durable execution)、流式处理(streaming)、人机协同(human-in-the-loop)等。
示例:
安装: pip install -U langgraph 示例代码:
python
from langgraph.graph import StateGraph, MessagesState, START, END
def mock_llm(state: MessagesState):
return {"messages": [{"role": "ai", "content": "hello world"}]}
graph = StateGraph(MessagesState)
graph.add_node(mock_llm)
graph.add_edge(START, "mock_llm")
graph.add_edge("mock_llm", END)
graph = graph.compile()
graph.invoke({"messages": [{"role": "user", "content": "hi!"}]})
二、核心优势
LangGraph为所有长期运行的有状态工作流或智能体(agent)提供底层支持架构。LangGraph不封装提示词(prompts)或架构,其核心优势如下:
- 持久化执行(Durable execution):构建可跨故障持续运行的智能体,支持长时间执行,且能从中断处恢复任务进度。
- 人机协同(Human-in-the-loop):支持在任意节点检查和修改智能体状态,从而融入人工监督环节。
- 全面的记忆能力(Comprehensive memory):打造有状态智能体,既具备用于实时推理的短期工作记忆,也拥有跨会话的长期记忆。
- 借助LangSmith调试(Debugging with LangSmith):通过可视化工具深入洞察复杂智能体的行为 ------ 这些工具可追踪执行路径、捕捉状态转换,并提供详细的运行时指标。
- 可投入生产环境的部署(Production-ready deployment):依托为应对有状态、长期运行工作流特有挑战而设计的可扩展架构,放心部署复杂的智能体系统。
三、LangGraph生态系统
LangGraph既可独立使用,也能与任意LangChain产品无缝集成,为开发者提供构建智能体(agent)所需的全套工具。若需提升大语言模型(LLM)应用的开发效率,可将LangGraph与以下工具搭配使用:
- LangSmith------ 助力智能体评估(agent evals)与可观测性(observability)。可用于调试性能不佳的 LLM 应用运行过程、评估智能体执行轨迹(agent trajectories)、掌握生产环境中的运行状态,并逐步优化性能。
- LangGraph(平台服务)------ 借助专为长期运行的有状态工作流设计的部署平台,轻松实现智能体的部署与扩展。支持跨团队发现、复用、配置及共享智能体,还可通过Studio中的可视化原型设计快速迭代。
- LangChain------ 提供各类集成能力与可组合组件,简化LLM应用开发流程。其包含基于LangGraph构建的智能体抽象层。
四、LangGraph v1
LangGraph v1 是一款聚焦智能体运行时(agent runtime)稳定性的版本。该版本保留了核心图 API(graph APIs)与执行模型的原有设计,同时优化了类型安全性(type safety)、文档(docs)以及开发者使用体验(developer ergonomics)。
LangGraph v1 旨在与 LangChain v1 版本协同工作 ------LangChain v1 的 create_agent 功能正是基于 LangGraph 构建 ------ 因此,你既可以从高层级抽象开始开发,也能在需要时深入到细粒度控制层面。
下表列出了 LangGraph v1 中所有已弃用的项目:
| 已弃用项目(Deprecated item) | 替代方案(Alternative) |
|---|---|
| create_react_agent | langchain.agents.create_agent |
| AgentState | langchain.agents.AgentState |
| AgentStatePydantic | langchain.agents.AgentState(不再有 Pydantic 状态,no more pydantic state) |
| AgentStateWithStructuredResponse | langchain.agents.AgentState |
| AgentStateWithStructuredResponsePydantic | langchain.agents.AgentState(不再有 Pydantic 状态,no more pydantic state) |
| HumanInterruptConfig | langchain.agents.middleware.human_in_the_loop.InterruptOnConfig |
| HumanInterrupt | langchain.agents.middleware.human_in_the_loop.InterruptOnConfig |
| ActionRequest | langchain.agents.middleware.human_in_the_loop.HITLRequest |
| ValidationNode | 工具会自动验证输入 |
| MessageGraph | 带有 messages 键的 StateGraph,类似 create_agent 所提供的 |
五、构建智能体
LangGraph 提供两种方式构建智能体:Graph API 和 Functional API)
- 若你倾向于将智能体定义为由节点(nodes)和边(edges)构成的图结构,可使用图 API(Graph API)。
- 若你倾向于将智能体定义为单个函数,可使用函数式 API(Functional API)。
5.1 Graph API构建智能体
1. 定义工具与模型
在本示例中,我们将使用 Claude Sonnet 4.5 模型,并定义用于加法、乘法和除法运算的工具。
python
from langchain.tools import tool
from langchain.chat_models import init_chat_model
from config import api_key, api_base
model = init_chat_model(
api_key = api_key,
base_url = api_base,
model = "Qwen/Qwen3-8B",
model_provider = "openai",
temperature = 0,
)
# Define tools
@tool
def multiply(a: int, b: int) -> int:
"""Multiply `a` and `b`.
Args:
a: First int
b: Second int
"""
return a * b
@tool
def add(a: int, b: int) -> int:
"""Adds `a` and `b`.
Args:
a: First int
b: Second int
"""
return a + b
@tool
def divide(a: int, b: int) -> float:
"""Divide `a` and `b`.
Args:
a: First int
b: Second int
"""
return a / b
# Augment the LLM with tools
tools = [add, multiply, divide]
tools_by_name = {tool.name: tool for tool in tools}
model_with_tools = model.bind_tools(tools)
2. 定义状态
图的状态用于存储消息(messages)和大语言模型(LLM)调用次数。
python
from langchain.messages import AnyMessage
from typing_extensions import TypedDict, Annotated
import operator
class MessagesState(TypedDict):
messages: Annotated[list[AnyMessage], operator.add]
llm_calls: int
3. 定义模型节点
模型节点用于调用大语言模型(LLM),并判断是否需要调用工具。
python
from langchain.messages import SystemMessage
def llm_call(state: dict):
"""LLM decides whether to call a tool or not"""
return {
"messages": [
model_with_tools.invoke(
[
SystemMessage(
content="You are a helpful assistant tasked with performing arithmetic on a set of inputs."
)
]
+ state["messages"]
)
],
"llm_calls": state.get('llm_calls', 0) + 1
}
4. 定义工具节点
工具节点用于调用工具并返回结果。
python
from langchain.messages import ToolMessage
def tool_node(state: dict):
"""Performs the tool call"""
result = []
for tool_call in state["messages"][-1].tool_calls:
tool = tools_by_name[tool_call["name"]]
observation = tool.invoke(tool_call["args"])
result.append(ToolMessage(content=observation, tool_call_id=tool_call["id"]))
return {"messages": result}
5. 定义结束逻辑
条件边函数(conditional edge function)用于根据大语言模型(LLM)是否发起了工具调用来决定路由至工具节点(tool node)或进入结束状态。
python
from typing import Literal
from langgraph.graph import StateGraph, START, END
def should_continue(state: MessagesState) -> Literal["tool_node", END]:
"""Decide if we should continue the loop or stop based upon whether the LLM made a tool call"""
messages = state["messages"]
last_message = messages[-1]
# If the LLM makes a tool call, then perform an action
if last_message.tool_calls:
return "tool_node"
# Otherwise, we stop (reply to the user)
return END
6. 构建并编译智能体
智能体通过 StateGraph 类构建,并使用 compile 方法进行编译。
python
# Build workflow
agent_builder = StateGraph(MessagesState)
# Add nodes
agent_builder.add_node("llm_call", llm_call)
agent_builder.add_node("tool_node", tool_node)
# Add edges to connect nodes
agent_builder.add_edge(START, "llm_call")
agent_builder.add_conditional_edges(
"llm_call",
should_continue,
["tool_node", END]
)
agent_builder.add_edge("tool_node", "llm_call")
# Compile the agent
agent = agent_builder.compile()
# Show the agent
from IPython.display import Image, display
display(Image(agent.get_graph(xray=True).draw_mermaid_png()))
# Invoke
from langchain.messages import HumanMessage
messages = [HumanMessage(content="Add 3 and 4.")]
messages = agent.invoke({"messages": messages})
for m in messages["messages"]:
m.pretty_print()
5.2 Functional API构建智能体
python
# Step 1: Define tools and model
from langchain.tools import tool
from langchain.chat_models import init_chat_model
from config import api_key, api_base
model = init_chat_model(
api_key = api_key,
base_url = api_base,
model = "Qwen/Qwen3-8B",
model_provider = "openai",
temperature = 0,
)
# Define tools
@tool
def multiply(a: int, b: int) -> int:
"""Multiply `a` and `b`.
Args:
a: First int
b: Second int
"""
return a * b
@tool
def add(a: int, b: int) -> int:
"""Adds `a` and `b`.
Args:
a: First int
b: Second int
"""
return a + b
@tool
def divide(a: int, b: int) -> float:
"""Divide `a` and `b`.
Args:
a: First int
b: Second int
"""
return a / b
# Augment the LLM with tools
tools = [add, multiply, divide]
tools_by_name = {tool.name: tool for tool in tools}
model_with_tools = model.bind_tools(tools)
from langgraph.graph import add_messages
from langchain.messages import (
SystemMessage,
HumanMessage,
ToolCall,
)
from langchain_core.messages import BaseMessage
from langgraph.func import entrypoint, task
# Step 2: Define model node
@task
def call_llm(messages: list[BaseMessage]):
"""LLM decides whether to call a tool or not"""
return model_with_tools.invoke(
[
SystemMessage(
content="You are a helpful assistant tasked with performing arithmetic on a set of inputs."
)
]
+ messages
)
# Step 3: Define tool node
@task
def call_tool(tool_call: ToolCall):
"""Performs the tool call"""
tool = tools_by_name[tool_call["name"]]
return tool.invoke(tool_call)
# Step 4: Define agent
@entrypoint()
def agent(messages: list[BaseMessage]):
model_response = call_llm(messages).result()
while True:
if not model_response.tool_calls:
break
# Execute tools
tool_result_futures = [
call_tool(tool_call) for tool_call in model_response.tool_calls
]
tool_results = [fut.result() for fut in tool_result_futures]
messages = add_messages(messages, [model_response, *tool_results])
model_response = call_llm(messages).result()
messages = add_messages(messages, model_response)
return messages
# Invoke
messages = [HumanMessage(content="Add 3 and 4.")]
for chunk in agent.stream(messages, stream_mode="updates"):
print(chunk)
print("\n")
六、总结
本文带领大家快速认识LangGraph,了解它的优势和生态系统,以及V1.0版本的变化。文章还介绍了LangGraph构建智能体的两种方式Graph API和Functional API。