LangChain 是一套用于构建 AI 智能体(AI Agent)和大语言模型(LLM)应用的开发框架。
LangChain 可以帮助开发者快速构建基于 GPT、Claude、Gemini 等大模型的复杂 AI 应用。
LangChain 由 Harrison Chase 于 2022 年 10 月推出,核心目标是:简化大语言模型应用开发流程。
LangChain提供统一接口,可连接:大模型、Prompt、向量数据库、工具调用、记忆系统以及 Agent 工作流。
目前 LangChain 已成为最热门的 LLM 应用开发框架之一,广泛应用于:智能聊天机器人、RAG 知识库、文档分析、代码生成、AI 自动化等场景。
LangChain 可以做什么?
- AI 聊天机器人(ChatBot)
- RAG 企业知识库
- PDF 文档问答系统
- AI Agent 自动任务执行
- 代码生成与代码分析
- 多轮对话与上下文记忆
- 联网搜索与工具调用
- 工作流自动化系统
第一个 LangChain 程序
以下代码使用 LangChain 调用 OpenAI 模型,并输出 AI 生成内容:
python
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
# 初始化模型
# 初始化模型
llm = ChatOpenAI(
model="qwen3:0.6b", # Local model name (e.g., from Ollama)
base_url="http://127.0.0.1:11434/v1", # Local API server address
api_key="OPENAI_API_KEY" # Typically a placeholder for local servers
)
# Prompt 模板
prompt = ChatPromptTemplate.from_template(
"请解释:{topic}"
)
# 创建 Chain
chain = prompt | llm
# 调用
result = chain.invoke({
"topic": "什么是 Transformer"
})
print(result.content)
运行后,大模型会自动生成关于 Transformer 的解释内容。
LangChain 核心组件
- LLM:连接 OpenAI、Claude、Gemini 等大模型
- PromptTemplate:管理 Prompt 模板
- Chains:构建多步骤 AI 工作流
- Memory:实现多轮对话记忆
- Tools:调用搜索、数据库、API 等工具
- Agents:让 AI 自动决策与执行任务
- Vector Store:连接向量数据库实现 RAG
Agents(智能体)
智能体(Agent)将大语言模型与各类工具相结合,构建出能够针对任务进行推理、自主选择适用工具,并通过迭代逐步求解的系统。
create_agent提供了可直接用于生产环境的智能体实现。
大语言模型智能体通过循环调用工具来实现既定目标。它会持续运行,直至满足停止条件------即模型输出了最终结果,或达到了预设的迭代次数上限。
Functions
create_agent
python
create_agent(
model: str | BaseChatModel,
tools: Sequence[BaseTool | Callable[..., Any] | dict[str, Any]] | None = None,
*,
system_prompt: str | SystemMessage | None = None,
middleware: Sequence[AgentMiddleware[StateT_co, ContextT]] = (),
response_format: ResponseFormat[ResponseT] | type[ResponseT] | dict[str, Any] | None = None,
state_schema: type[AgentState[ResponseT]] | None = None,
context_schema: type[ContextT] | None = None,
checkpointer: Checkpointer | None = None,
store: BaseStore | None = None,
interrupt_before: list[str] | None = None,
interrupt_after: list[str] | None = None,
debug: bool = False,
name: str | None = None,
cache: BaseCache[Any] | None = None,
transformers: Sequence[Callable[[tuple[str, ...]], Any]] | None = None
) -> CompiledStateGraph[AgentState[ResponseT], ContextT, _InputAgentState, _OutputAgentState[ResponseT]]
参数
| 参数名 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| model (必填) | str|BaseChatModel |
(无) | Agent 使用的大语言模型。 可以是字符串标识符(例如 "openai:gpt-4"),也可以是直接的聊天模型实例(例如 ChatOpenAI或其他 LangChain 聊天模型)。 如需查看支持的模型字符串完整列表,请参阅 init_chat_model。 💡 提示:更多信息请参见《模型文档》。 |
| tools | Sequence[BaseTool | Callable | dict]|None |
None |
工具列表。 可以是一系列工具、字典或可调用对象(Callable)。 如果是 None或空列表,Agent 将仅由模型节点组成,不包含工具调用循环。 💡 提示:更多信息请参见《工具文档》。 |
| system_prompt | str|SystemMessage|None |
None |
LLM 的系统提示词(System Prompt)。 可以是字符串(将自动转换为 SystemMessage)或直接传入 SystemMessage实例。在向模型发送请求时,系统消息会被添加到消息列表的开头。 |
| middleware | Sequence[AgentMiddleware] |
() |
应用于 Agent 的中间件序列。 中间件可以在不同阶段拦截和修改 Agent 的行为。 💡 提示:更多信息请参见《中间件文档》。 |
| response_format | ResponseFormat|type|dict|None |
None |
结构化响应的可选配置。 可以是 ToolStrategy、ProviderStrategy或 Pydantic 模型类。 如果提供此参数,Agent 将在对话流程中处理结构化输出。原始模式将根据模型能力被包装到适当的策略中。 💡 提示:更多信息请参见《结构化输出文档》。 |
| state_schema | type[AgentState]|None |
None |
扩展 AgentState的可选 TypedDict 模式。 提供后,将使用此模式代替 AgentState作为合并中间件状态模式的基础模式。这允许用户添加自定义状态字段,而无需创建自定义中间件。 通常建议通过中间件扩展 state_schema,以保持相关扩展限定在对应的钩子(hooks)/ 工具范围内。 |
| context_schema | type[ContextT]|None |
None |
运行时上下文的可选模式。 |
| checkpointer | Checkpointer|None |
None |
可选的检查点保存器(Checkpointer)。 用于持久化图的状态(例如作为聊天记忆),适用于单个线程(例如单次对话)。 |
| store | BaseStore|None |
None |
可选的存储对象(Store)。 用于跨多个线程(例如多个对话/用户)持久化数据。 |
| interrupt_before | list[str]|None |
None |
在执行指定节点前中断的可选节点名称列表。 适用于需要在执行操作前进行用户确认或其他中断的场景。 |
| interrupt_after | list[str]|None |
None |
在执行指定节点后中断的可选节点名称列表。 适用于需要直接返回或对输出进行额外处理的场景。 |
| debug | bool |
False |
是否启用图执行的详细日志。 启用后,将在 Agent 运行时打印有关每个节点执行、状态更新和转换的详细信息。有助于调试中间件行为和理解 Agent 执行流程。 |
| name | str|None |
None |
编译后的状态图(CompiledStateGraph)的可选名称。 将此 Agent 图作为子图节点添加到另一个图中时,会自动使用此名称------这对于构建多 Agent 系统特别有用。 |
| cache | BaseCache[Any]|None |
None |
可选的基础缓存(BaseCache)实例,用于启用图执行的缓存。 |
| transformers | Sequence[Callable]|None |
None |
可选的作用域感知流转换器(StreamTransformer)工厂序列。 除了 Agent 默认值外,注册到编译图中的转换器。每个工厂按作用域调用(factory(scope)),以便子图迷你多路复用器获得新的实例。附加在内置的 ToolCallTransformer之后。 |
model
例子一:
直接model 模型参数使用字符串指明模型
python
from langchain.agents import create_agent
def check_weather(location: str) -> str:
'''Return the weather forecast for the specified location.'''
return f"It's always sunny in {location}"
graph = create_agent(
model="anthropic:claude-sonnet-4-5-20250929",
tools=[check_weather],
system_prompt="You are a helpful assistant",
)
inputs = {"messages": [{"role": "user", "content": "what is the weather in sf"}]}
for chunk in graph.stream(inputs, stream_mode="updates"):
print(chunk)
例子二:
ChatOpenAI方式链接本地大模型
python
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
def check_weather(location: str) -> str:
'''Return the weather forecast for the specified location.'''
return f"It's always sunny in {location}"
# 使用本地 Ollama 模型服务
llm = ChatOpenAI(
model="qwen3:0.6b",
base_url="http://127.0.0.1:11434/v1",
api_key="ollama",
temperature=0.7,
)
graph = create_agent(
model=llm,
tools=[check_weather],
system_prompt="You are a helpful assistant",
)
inputs = {"messages": [{"role": "user", "content": "what is the weather in sf"}]}
for chunk in graph.stream(inputs, stream_mode="updates"):
print(chunk)
tool
python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Date : 2026/5/18
@File : agentLearn-tool.py
@Author : liwei68
@Description : LangChain Agent Tool 定义方式 Demo
"""
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from typing import TypedDict, Annotated
# ============================================================
# 方式一:Callable 方式(函数方式)- 最常用
# ============================================================
def check_weather(location: str) -> str:
"""Return the weather forecast for the specified location."""
return f"It's always sunny in {location}"
def get_current_time(format: str = "%Y-%m-%d %H:%M:%S") -> str:
"""Return the current time in the specified format."""
from datetime import datetime
return datetime.now().strftime(format)
# ============================================================
# 方式二:@tool 装饰器方式 - 推荐方式,功能更强大
# ============================================================
@tool
def search_web(query: str) -> str:
"""Search the web for information about the given query."""
return f"Search results for: {query}"
@tool
def calculate(expression: str) -> str:
"""Evaluate a mathematical expression and return the result."""
try:
result = eval(expression)
return str(result)
except Exception as e:
return f"Error: {e}"
# ============================================================
# 方式三:字典方式定义简单工具
# ============================================================
calculator_dict_tool = {
"name": "calculate_dict",
"description": "A simple calculator that evaluates mathematical expressions. Input should be a valid math expression like '2+2' or '10*5'.",
"func": lambda x: str(eval(x) if x.replace(" ", "").replace(".", "").replace("-", "").isdigit() or "+" in x or "-" in x or "*" in x or "/" in x else "Invalid expression")
}
# 另一种字典方式
greeting_dict_tool = {
"name": "greet",
"description": "Generate a personalized greeting message.",
"func": lambda name: f"Hello, {name}! Welcome!"
}
# ============================================================
# 方式四:Structured Tool 方式(TypedDict)
# ============================================================
class GetWeatherInput(TypedDict):
location: str
unit: Annotated[str, {"choices": ["celsius", "fahrenheit"]}]
@tool
def get_weather_structured(input: GetWeatherInput) -> str:
"""Get weather information for a specific location.
Args:
location: The city name to get weather for
unit: Temperature unit, either 'celsius' or 'fahrenheit'
"""
location = input["location"]
unit = input["unit"]
temp = 72 if unit == "fahrenheit" else 22
return f"The weather in {location} is {temp}°{unit[0].upper()}"
# ============================================================
# 创建 LLM 实例(连接本地 Ollama)
# ============================================================
llm = ChatOpenAI(
model="qwen3:0.6b",
base_url="http://127.0.0.1:11434/v1",
api_key="ollama",
temperature=0.7,
)
def run_demo():
"""运行不同 tool 方式的 demo"""
demos = {
"1": ("Callable 方式 (普通函数)", [check_weather, get_current_time]),
"2": ("@tool 装饰器方式", [search_web, calculate]),
"3": ("字典方式", [calculator_dict_tool, greeting_dict_tool]),
"4": ("Structured Tool 方式", [get_weather_structured]),
}
print("=" * 60)
print("LangChain Agent Tool 定义方式 Demo")
print("=" * 60)
print("\n可选方式:")
for key, (name, _) in demos.items():
print(f" {key}. {name}")
print("\n" + "=" * 60)
def get_tool_name(t):
"""获取工具名称"""
if isinstance(t, dict):
return t.get("name", "unknown")
elif hasattr(t, "name"):
return getattr(t, "name", "unknown")
else:
return "unknown"
def run_with_tools(tool_list, query):
"""使用指定工具运行 agent"""
print(f"\n{'='*60}")
print(f"使用工具: {[get_tool_name(t) for t in tool_list]}")
print(f"查询: {query}")
print("=" * 60)
graph = create_agent(
model=llm,
tools=tool_list,
system_prompt="You are a helpful assistant.",
)
inputs = {"messages": [{"role": "user", "content": query}]}
for chunk in graph.stream(inputs, stream_mode="updates"):
print(chunk)
print()
if __name__ == "__main__":
run_demo()
print("\n--- Demo 1: Callable 方式 (普通函数) ---")
run_with_tools([check_weather, get_current_time], "What is the weather in Beijing?")
print("\n--- Demo 2: @tool 装饰器方式 ---")
run_with_tools([search_web, calculate], "What is 15 + 35?")
print("\n--- Demo 3: 字典方式 ---")
run_with_tools([greeting_dict_tool], "Say hello to Alice")
print("\n--- Demo 4: Structured Tool 方式 ---")
run_with_tools([get_weather_structured], "What's the weather in Tokyo in celsius?")
执行结果
XML
============================================================
LangChain Agent Tool 定义方式 Demo
============================================================
可选方式:
1. Callable 方式 (普通函数)
2. @tool 装饰器方式
3. 字典方式
4. Structured Tool 方式
============================================================
--- Demo 1: Callable 方式 (普通函数) ---
============================================================
使用工具: ['unknown', 'unknown']
查询: What is the weather in Beijing?
============================================================
{'model': {'messages': [AIMessage(content='', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 102, 'prompt_tokens': 186, 'total_tokens': 288, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_provider': 'openai', 'model_name': 'qwen3:0.6b', 'system_fingerprint': 'fp_ollama', 'id': 'chatcmpl-768', 'finish_reason': 'tool_calls', 'logprobs': None}, id='lc_run--019e4090-b2e3-7a70-bab6-abee1d404b16-0', tool_calls=[{'name': 'check_weather', 'args': {'location': 'Beijing'}, 'id': 'call_3qcncdpe', 'type': 'tool_call'}], invalid_tool_calls=[], usage_metadata={'input_tokens': 186, 'output_tokens': 102, 'total_tokens': 288, 'input_token_details': {}, 'output_token_details': {}})]}}
{'tools': {'messages': [ToolMessage(content="It's always sunny in Beijing", name='check_weather', id='813492fb-f647-4cb9-8245-dd3a431efd64', tool_call_id='call_3qcncdpe')]}}
{'model': {'messages': [AIMessage(content="It's always sunny in Beijing. Let me know if you need more information! 😊", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 127, 'prompt_tokens': 225, 'total_tokens': 352, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_provider': 'openai', 'model_name': 'qwen3:0.6b', 'system_fingerprint': 'fp_ollama', 'id': 'chatcmpl-891', 'finish_reason': 'stop', 'logprobs': None}, id='lc_run--019e4090-ba6c-7ce2-a024-68be9c2e0d35-0', tool_calls=[], invalid_tool_calls=[], usage_metadata={'input_tokens': 225, 'output_tokens': 127, 'total_tokens': 352, 'input_token_details': {}, 'output_token_details': {}})]}}
--- Demo 2: @tool 装饰器方式 ---
============================================================
使用工具: ['search_web', 'calculate']
查询: What is 15 + 35?
============================================================
{'model': {'messages': [AIMessage(content='', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 129, 'prompt_tokens': 190, 'total_tokens': 319, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_provider': 'openai', 'model_name': 'qwen3:0.6b', 'system_fingerprint': 'fp_ollama', 'id': 'chatcmpl-262', 'finish_reason': 'tool_calls', 'logprobs': None}, id='lc_run--019e4090-be45-7391-b2ee-5fffee0786fe-0', tool_calls=[{'name': 'calculate', 'args': {'expression': '15 + 35'}, 'id': 'call_7e34smuw', 'type': 'tool_call'}], invalid_tool_calls=[], usage_metadata={'input_tokens': 190, 'output_tokens': 129, 'total_tokens': 319, 'input_token_details': {}, 'output_token_details': {}})]}}
{'tools': {'messages': [ToolMessage(content='50', name='calculate', id='bd73f962-4b50-4226-bf9e-cf6b83aac042', tool_call_id='call_7e34smuw')]}}
{'model': {'messages': [AIMessage(content='The result of 15 + 35 is 50.', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 103, 'prompt_tokens': 228, 'total_tokens': 331, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_provider': 'openai', 'model_name': 'qwen3:0.6b', 'system_fingerprint': 'fp_ollama', 'id': 'chatcmpl-314', 'finish_reason': 'stop', 'logprobs': None}, id='lc_run--019e4090-c242-7cd3-ab73-50cd2f13ee0e-0', tool_calls=[], invalid_tool_calls=[], usage_metadata={'input_tokens': 228, 'output_tokens': 103, 'total_tokens': 331, 'input_token_details': {}, 'output_token_details': {}})]}}
--- Demo 3: 字典方式 ---
============================================================
使用工具: ['greet']
查询: Say hello to Alice
============================================================
{'model': {'messages': [AIMessage(content='', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 162, 'prompt_tokens': 131, 'total_tokens': 293, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_provider': 'openai', 'model_name': 'qwen3:0.6b', 'system_fingerprint': 'fp_ollama', 'id': 'chatcmpl-602', 'finish_reason': 'tool_calls', 'logprobs': None}, id='lc_run--019e4090-c565-7ea1-bbfa-84c4805821a3-0', tool_calls=[{'name': 'greet', 'args': {}, 'id': 'call_h3g64nut', 'type': 'tool_call'}], invalid_tool_calls=[], usage_metadata={'input_tokens': 131, 'output_tokens': 162, 'total_tokens': 293, 'input_token_details': {}, 'output_token_details': {}})]}}
--- Demo 4: Structured Tool 方式 ---
============================================================
使用工具: ['get_weather_structured']
查询: What's the weather in Tokyo in celsius?
============================================================
{'model': {'messages': [AIMessage(content='', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 154, 'prompt_tokens': 200, 'total_tokens': 354, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_provider': 'openai', 'model_name': 'qwen3:0.6b', 'system_fingerprint': 'fp_ollama', 'id': 'chatcmpl-902', 'finish_reason': 'stop', 'logprobs': None}, id='lc_run--019e4090-ca20-7eb1-8f5a-b955348280e5-0', tool_calls=[], invalid_tool_calls=[], usage_metadata={'input_tokens': 200, 'output_tokens': 154, 'total_tokens': 354, 'input_token_details': {}, 'output_token_details': {}})]}}
Process finished with exit code 0
system_prompt
python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Date : 2026/5/18
@File : agentLearn.py
@Author : liwei68
@Description : system_prompt 字符串和 SystemMessage 两种方式 Demo
"""
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
from langchain_core.messages import SystemMessage, HumanMessage
def check_weather(location: str) -> str:
'''Return the weather forecast for the specified location.'''
return f"It's always sunny in {location}"
# 使用本地 Ollama 模型服务
llm = ChatOpenAI(
model="qwen3:0.6b",
base_url="http://127.0.0.1:11434/v1",
api_key="ollama",
temperature=0.7,
)
# ============================================================
# 方式一:字符串方式 (最简单)
# ============================================================
print("=" * 60)
print("方式一:字符串方式 system_prompt")
print("=" * 60)
graph1 = create_agent(
model=llm,
tools=[check_weather],
system_prompt="You are a helpful assistant",
)
inputs1 = {"messages": [{"role": "user", "content": "what is the weather in sf"}]}
for chunk in graph1.stream(inputs1, stream_mode="updates"):
print(chunk)
# ============================================================
# 方式二:SystemMessage 列表方式 (通过 messages 参数)
# ============================================================
print("\n" + "=" * 60)
print("方式二:SystemMessage 列表方式 (通过初始 messages)")
print("=" * 60)
graph2 = create_agent(
model=llm,
tools=[check_weather],
system_prompt="You are a helpful weather assistant.", # 基本 system prompt
)
inputs2 = {
"messages": [
SystemMessage(content="You are a helpful weather assistant that provides accurate weather information."),
SystemMessage(content="Always be concise and friendly in your responses."),
HumanMessage(content="what is the weather in tokyo"),
]
}
for chunk in graph2.stream(inputs2, stream_mode="updates"):
print(chunk)
# ============================================================
# 方式三:组合多个 SystemMessage 到一个字符串
# ============================================================
print("\n" + "=" * 60)
print("方式三:组合多个规则到字符串 prompt")
print("=" * 60)
graph3 = create_agent(
model=llm,
tools=[check_weather],
system_prompt="""You are a helpful assistant that specializes in weather forecasting.
Guidelines:
1. Always use the check_weather tool to get accurate information
2. Provide weather details including temperature and conditions
3. Be concise and friendly in your responses""",
)
inputs3 = {"messages": [{"role": "user", "content": "what is the weather in new york"}]}
for chunk in graph3.stream(inputs3, stream_mode="updates"):
print(chunk)
# ============================================================
# 字符串 prompt 示例集合
# ============================================================
print("\n" + "=" * 60)
print("常用 system_prompt 字符串示例")
print("=" * 60)
examples = {
"简单助手": "You are a helpful assistant.",
"专业角色": "You are an expert software engineer who helps write clean, efficient code.",
"翻译助手": "You are a professional translator. Translate the user's input to English.",
"数据分析": "You are a data analyst. Help users analyze and interpret their data.",
"客服": "You are a friendly customer service representative. Be patient and helpful.",
}
for name, prompt in examples.items():
print(f"\n【{name}】")
print(f" prompt: {prompt}")
middleware
python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Date : 2026/5/19
@File : 01_middleware.py
@Author : liwei68
@Description : create_agent middleware 参数示例
middleware 用于在 agent 执行过程中拦截和处理消息流
"""
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
from langchain.agents.middleware.types import (
AgentMiddleware,
before_agent,
after_agent,
before_model,
after_model,
)
def check_weather(location: str) -> str:
"""Return the weather forecast for the specified location."""
return f"It's always sunny in {location}"
llm = ChatOpenAI(
model="qwen3:0.6b",
base_url="http://127.0.0.1:11434/v1",
api_key="ollama",
temperature=0.7,
)
# 方式一:使用装饰器定义 middleware
@before_agent
def log_before_agent(state, runtime):
"""在 agent 执行前记录日志"""
messages = state.get("messages", [])
print(f"[Before Agent] 收到 {len(messages)} 条消息")
for msg in messages:
if hasattr(msg, "content"):
print(f"[Before Agent] 消息内容: {msg.content[:50]}...")
return state
@after_agent
def log_after_agent(state, runtime):
"""在 agent 执行后记录日志"""
messages = state.get("messages", [])
print(f"[After Agent] 处理完成,当前消息数: {len(messages)}")
return state
@before_model
def log_before_model(state, runtime):
"""在模型调用前记录日志"""
print("[Before Model] 准备调用 LLM 模型...")
return state
@after_model
def log_after_model(state, runtime):
"""在模型调用后记录日志"""
print("[After Model] LLM 模型调用完成")
return state
print("=" * 60)
print("create_agent middleware 参数示例")
print("=" * 60)
print("\nmiddleware 说明:")
print(" - 用于在 agent 执行过程中拦截和处理消息流")
print(" - 支持多种装饰器:")
print(" * @before_agent - 在 agent 执行前")
print(" * @after_agent - 在 agent 执行后")
print(" * @before_model - 在模型调用前")
print(" * @after_model - 在模型调用后")
print(" - middleware 函数签名: def func(state, runtime) -> state")
print(" * state: 当前状态(包含 messages 等)")
print(" * runtime: 运行时信息")
print(" * 返回值: 修改后的 state")
print()
graph = create_agent(
model=llm,
tools=[check_weather],
system_prompt="You are a helpful assistant",
middleware=[log_before_agent, log_after_agent, log_before_model, log_after_model],
)
inputs = {"messages": [{"role": "user", "content": "what is the weather in sf"}]}
for chunk in graph.stream(inputs, stream_mode="updates"):
print(chunk)
response_format
python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Date : 2026/5/19
@File : 02_response_format.py
@Author : liwei68
@Description : create_agent response_format 参数示例
response_format 用于指定 agent 输出的格式结构
支持: Pydantic 模型, dataclasses, TypedDict, JSON schema dict
"""
from typing import TypedDict
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
def check_weather(location: str) -> str:
"""Return the weather forecast for the specified location."""
return f"It's always sunny in {location}"
llm = ChatOpenAI(
model="qwen3:0.6b",
base_url="http://127.0.0.1:11434/v1",
api_key="ollama",
temperature=0.7,
)
class WeatherResponse(TypedDict):
"""天气响应结构 - 定义 agent 输出的格式"""
answer: str
location: str
weather: str
print("=" * 60)
print("create_agent response_format 参数示例")
print("=" * 60)
print("\nresponse_format 说明:")
print(" - 用于指定 agent 输出的格式结构")
print(" - 支持类型:")
print(" * Pydantic 模型")
print(" * dataclasses")
print(" * TypedDict")
print(" * JSON schema dict")
print(" - 可以约束 agent 输出的结构化数据格式")
print()
graph = create_agent(
model=llm,
tools=[check_weather],
system_prompt="You are a helpful assistant. Always provide structured responses.",
response_format=WeatherResponse,
)
inputs = {"messages": [{"role": "user", "content": "what is the weather in sf"}]}
print("response_format=WeatherResponse (TypedDict) 结果:")
print("=" * 60)
for chunk in graph.stream(inputs, stream_mode="updates"):
print(chunk)
state_schema
python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Date : 2026/5/19
@File : 03_state_schema.py
@Author : liwei68
@Description : create_agent state_schema 参数示例
state_schema 用于定义 agent 状态的类型结构
可以使用 TypedDict 或 Pydantic 模型定义状态结构
"""
from typing import TypedDict, Optional
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
def check_weather(location: str) -> str:
"""Return the weather forecast for the specified location."""
return f"It's always sunny in {location}"
llm = ChatOpenAI(
model="qwen3:0.6b",
base_url="http://127.0.0.1:11434/v1",
api_key="ollama",
temperature=0.7,
)
class AgentState(TypedDict):
"""
自定义 Agent 状态结构
属性:
messages: 对话消息列表(必需)
user_name: 用户名称(可选)
session_id: 会话 ID(可选)
metadata: 元数据(可选)
"""
messages: list
user_name: Optional[str]
session_id: Optional[str]
metadata: Optional[dict]
print("=" * 60)
print("create_agent state_schema 参数示例")
print("=" * 60)
print("\nstate_schema 说明:")
print(" - 用于定义 agent 执行过程中的状态结构")
print(" - 可以添加自定义字段如 user_name, session_id 等")
print(" - 增强类型安全性和代码可读性")
print()
graph = create_agent(
model=llm,
tools=[check_weather],
system_prompt="You are a helpful assistant",
state_schema=AgentState, # 指定自定义状态结构
)
inputs = {
"messages": [{"role": "user", "content": "what is the weather in tokyo"}],
"user_name": "Alice",
"session_id": "session_123",
}
for chunk in graph.stream(inputs, stream_mode="updates"):
print(chunk)
context_schema
python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Date : 2026/5/19
@File : 04_context_schema.py
@Author : liwei68
@Description : create_agent context_schema 参数示例
context_schema 用于定义外部上下文的类型结构
允许在调用 agent 时传入额外的上下文信息
"""
from typing import TypedDict, Optional
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
def check_weather(location: str) -> str:
"""Return the weather forecast for the specified location."""
return f"It's always sunny in {location}"
llm = ChatOpenAI(
model="qwen3:0.6b",
base_url="http://127.0.0.1:11434/v1",
api_key="ollama",
temperature=0.7,
)
class ContextSchema(TypedDict):
"""
外部上下文结构定义
属性:
user_id: 用户 ID
user_preferences: 用户偏好设置
system_time: 系统时间
environment: 环境信息
"""
user_id: str
user_preferences: Optional[dict]
system_time: Optional[str]
environment: Optional[str]
print("=" * 60)
print("create_agent context_schema 参数示例")
print("=" * 60)
print("\ncontext_schema 说明:")
print(" - 用于定义外部传入的上下文信息类型")
print(" - 可以在调用 agent 时传入额外的信息")
print(" - 适用于需要用户信息、系统环境等场景")
print()
graph = create_agent(
model=llm,
tools=[check_weather],
system_prompt="You are a helpful assistant that personalizes responses based on user context.",
context_schema=ContextSchema, # 指定上下文结构
)
inputs = {
"messages": [{"role": "user", "content": "what is the weather in sf"}],
}
context = {
"user_id": "user_456",
"user_preferences": {"units": "celsius", "language": "en"},
"system_time": "2026-05-19 10:00:00",
"environment": "production",
}
for chunk in graph.stream(inputs, stream_mode="updates", context=context):
print(chunk)
checkpointer
python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Date : 2026/5/19
@File : 05_checkpointer.py
@Author : liwei68
@Description : create_agent checkpointer 参数示例
checkpointer 用于保存和恢复 agent 的执行状态
支持断点续传、多轮对话状态保存等功能
"""
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
from langgraph.checkpoint.memory import MemorySaver
def check_weather(location: str) -> str:
"""Return the weather forecast for the specified location."""
return f"It's always sunny in {location}"
llm = ChatOpenAI(
model="qwen3:0.6b",
base_url="http://127.0.0.1:11434/v1",
api_key="ollama",
temperature=0.7,
)
print("=" * 60)
print("create_agent checkpointer 参数示例")
print("=" * 60)
print("\ncheckpointer 说明:")
print(" - 用于保存 agent 执行过程中的状态")
print(" - 支持断点续传功能")
print(" - 可以实现多轮对话的状态保持")
print(" - MemorySaver: 内存存储(适合开发/测试)")
print(" - SqliteSaver: SQLite 持久化存储")
print(" - PostgresSaver: PostgreSQL 持久化存储(生产环境)")
print()
checkpointer = MemorySaver()
graph = create_agent(
model=llm,
tools=[check_weather],
system_prompt="You are a helpful assistant",
checkpointer=checkpointer, # 启用状态保存
)
config = {"configurable": {"thread_id": "conversation_1"}}
print("--- 第一次对话 ---")
inputs1 = {"messages": [{"role": "user", "content": "what is the weather in sf"}]}
for chunk in graph.stream(inputs1, stream_mode="updates", config=config):
print(chunk)
print("\n--- 第二次对话(恢复状态) ---")
inputs2 = {"messages": [{"role": "user", "content": "what about london?"}]}
for chunk in graph.stream(inputs2, stream_mode="updates", config=config):
print(chunk)
store
python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Date : 2026/5/19
@File : 06_store.py
@Author : liwei68
@Description : create_agent store 参数示例
store 用于持久化存储 key-value 数据
可以在 agent 执行过程中读写持久化数据
"""
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
from langgraph.store.memory import InMemoryStore
def check_weather(location: str) -> str:
"""Return the weather forecast for the specified location."""
return f"It's always sunny in {location}"
llm = ChatOpenAI(
model="qwen3:0.6b",
base_url="http://127.0.0.1:11434/v1",
api_key="ollama",
temperature=0.7,
)
print("=" * 60)
print("create_agent store 参数示例")
print("=" * 60)
print("\nstore 说明:")
print(" - 用于持久化存储 key-value 数据")
print(" - 可以在多次对话之间共享数据")
print(" - 适用于用户信息缓存、对话历史等场景")
print(" - InMemoryStore: 内存存储(重启后丢失)")
print(" - 支持向量搜索功能(需要配置 embed)")
print()
store = InMemoryStore()
graph = create_agent(
model=llm,
tools=[check_weather],
system_prompt="You are a helpful assistant",
store=store,
)
inputs = {
"messages": [{"role": "user", "content": "what is the weather in paris"}]
}
for chunk in graph.stream(inputs, stream_mode="updates"):
print(chunk)
print("\n--- 存储操作示例 ---")
store.put(namespace=("user_data", "alice"), key="info", value={"name": "Alice", "language": "en"})
result = store.get(namespace=("user_data", "alice"), key="info")
print(f"读取存储数据: {result}")
print("\n--- 列出 namespace 示例 ---")
namespaces = store.list_namespaces()
print(f"所有 namespaces: {namespaces}")
interrupt_before
python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Date : 2026/5/19
@File : 07_interrupt_before.py
@Author : liwei68
@Description : create_agent interrupt_before 参数示例
interrupt_before 用于在特定节点之前中断执行
常用于人工审核、调试、权限控制等场景
"""
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
from langgraph.checkpoint.memory import MemorySaver
def check_weather(location: str) -> str:
"""Return the weather forecast for the specified location."""
return f"It's always sunny in {location}"
llm = ChatOpenAI(
model="qwen3:0.6b",
base_url="http://127.0.0.1:11434/v1",
api_key="ollama",
temperature=0.7,
)
print("=" * 60)
print("create_agent interrupt_before 参数示例")
print("=" * 60)
print("\ninterrupt_before 说明:")
print(" - 在指定的节点执行之前中断")
print(" - 常用于需要人工确认的场景")
print(" - 有效节点名: 'model', 'tools', '*'")
print(" - 配合 checkpointer 实现状态保存和恢复")
print()
checkpointer = MemorySaver()
graph = create_agent(
model=llm,
tools=[check_weather],
system_prompt="You are a helpful assistant",
checkpointer=checkpointer,
interrupt_before=["tools"],
)
config = {"configurable": {"thread_id": "interrupt_demo_1"}}
inputs = {"messages": [{"role": "user", "content": "what is the weather in sf"}]}
print("执行将在工具调用之前中断...")
print("首次调用会停在工具调用前,保存状态")
print()
result = graph.stream(inputs, stream_mode="values", config=config)
try:
for chunk in result:
print(chunk)
except Exception as e:
print(f"中断执行: {e}")
print("\n--- 使用 interrupt_before 实现人工确认流程 ---")
print("1. 在工具调用前中断,等待人工确认")
print("2. 确认后可调用 graph.invoke(None, config=config) 继续执行")
print("3. 或者修改状态后继续")
interrupt_after
python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Date : 2026/5/19
@File : 08_interrupt_after.py
@Author : liwei68
@Description : create_agent interrupt_after 参数示例
interrupt_after 用于在特定节点之后中断执行
常用于结果审核、调试、日志记录等场景
"""
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
from langgraph.checkpoint.memory import MemorySaver
def check_weather(location: str) -> str:
"""Return the weather forecast for the specified location."""
return f"It's always sunny in {location}"
llm = ChatOpenAI(
model="qwen3:0.6b",
base_url="http://127.0.0.1:11434/v1",
api_key="ollama",
temperature=0.7,
)
print("=" * 60)
print("create_agent interrupt_after 参数示例")
print("=" * 60)
print("\ninterrupt_after 说明:")
print(" - 在指定的节点执行之后中断")
print(" - 常用于结果审核、修改响应内容")
print(" - 有效节点名: 'model', 'tools', '*'")
print(" - 配合 checkpointer 实现状态保存和恢复")
print()
checkpointer = MemorySaver()
graph = create_agent(
model=llm,
tools=[check_weather],
system_prompt="You are a helpful assistant",
checkpointer=checkpointer,
interrupt_after=["tools"],
)
config = {"configurable": {"thread_id": "interrupt_demo_2"}}
inputs = {"messages": [{"role": "user", "content": "what is the weather in sf"}]}
print("执行将在工具调用之后中断...")
print("首次调用会停在工具调用后,模型调用前")
print()
result = graph.stream(inputs, stream_mode="values", config=config)
try:
for chunk in result:
print(chunk)
except Exception as e:
print(f"中断执行: {e}")
print("\n--- 使用 interrupt_after 实现结果审核流程 ---")
print("1. 在工具调用后中断,可检查/修改工具返回结果")
print("2. 确认后可调用 graph.invoke(None, config=config) 继续执行")
print("3. 可以修改 ToolMessage 的内容来改变后续处理")
debug
python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Date : 2026/5/19
@File : 09_debug.py
@Author : liwei68
@Description : create_agent debug 参数示例
debug 用于开启调试模式,输出详细的执行信息
便于开发者了解 agent 的执行流程和状态变化
"""
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
def check_weather(location: str) -> str:
"""Return the weather forecast for the specified location."""
return f"It's always sunny in {location}"
llm = ChatOpenAI(
model="qwen3:0.6b",
base_url="http://127.0.0.1:11434/v1",
api_key="ollama",
temperature=0.7,
)
print("=" * 60)
print("create_agent debug 参数示例")
print("=" * 60)
print("\ndebug 说明:")
print(" - 开启调试模式,输出详细的执行信息")
print(" - 显示状态变化、节点执行、工具调用等详细信息")
print(" - 适用于开发调试、问题排查")
print(" - 生产环境建议关闭以提升性能")
print()
graph = create_agent(
model=llm,
tools=[check_weather],
system_prompt="You are a helpful assistant",
debug=True, # 开启调试模式
)
inputs = {"messages": [{"role": "user", "content": "what is the weather in sf"}]}
for chunk in graph.stream(inputs, stream_mode="updates"):
print(chunk)
name
python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Date : 2026/5/19
@File : 10_name.py
@Author : liwei68
@Description : create_agent name 参数示例
name 用于为 agent 指定一个名称
便于在多 agent 系统中识别和引用
"""
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
def check_weather(location: str) -> str:
"""Return the weather forecast for the specified location."""
return f"It's always sunny in {location}"
llm = ChatOpenAI(
model="qwen3:0.6b",
base_url="http://127.0.0.1:11434/v1",
api_key="ollama",
temperature=0.7,
)
print("=" * 60)
print("create_agent name 参数示例")
print("=" * 60)
print("\nname 说明:")
print(" - 为 agent 指定一个唯一的名称")
print(" - 在多 agent 系统中用于识别和路由")
print(" - 便于日志记录和监控")
print(" - 可以通过 name 获取对应的 agent 实例")
print()
weather_agent = create_agent(
model=llm,
tools=[check_weather],
system_prompt="You are a helpful weather assistant",
name="weather_assistant", # 指定 agent 名称
)
print(f"Agent 名称: {weather_agent.name}")
print()
inputs = {"messages": [{"role": "user", "content": "what is the weather in sf"}]}
for chunk in weather_agent.stream(inputs, stream_mode="updates"):
print(chunk)
cache
python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Date : 2026/5/19
@File : 11_cache.py
@Author : liwei68
@Description : create_agent cache 参数示例
cache 用于启用结果缓存,避免重复计算
可以显著提升性能和降低 API 调用成本
"""
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
from langgraph.cache.memory import InMemoryCache
def check_weather(location: str) -> str:
"""Return the weather forecast for the specified location."""
return f"It's always sunny in {location}"
llm = ChatOpenAI(
model="qwen3:0.6b",
base_url="http://127.0.0.1:11434/v1",
api_key="ollama",
temperature=0.7,
)
print("=" * 60)
print("create_agent cache 参数示例")
print("=" * 60)
print("\ncache 说明:")
print(" - 启用 agent 执行结果的缓存")
print(" - 相同输入不再重复执行")
print(" - 适用于相同问题多次查询的场景")
print(" - InMemoryCache: 内存缓存(重启后丢失)")
print(" - RedisCache: Redis 分布式缓存(生产环境)")
print()
cache = InMemoryCache()
graph = create_agent(
model=llm,
tools=[check_weather],
system_prompt="You are a helpful assistant",
cache=cache,
)
inputs = {"messages": [{"role": "user", "content": "what is the weather in sf"}]}
print("--- 第一次调用 ---")
for chunk in graph.stream(inputs, stream_mode="updates"):
print(chunk)
print("\n--- 第二次调用(使用缓存) ---")
for chunk in graph.stream(inputs, stream_mode="updates"):
print(chunk)
print("\n--- 清除缓存 ---")
cache.clear()
print("缓存已清除")
transformers
python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Date : 2026/5/19
@File : 12_transformers.py
@Author : liwei68
@Description : create_agent transformers 参数示例
transformers 用于在输出前对消息进行转换处理
可以实现输出过滤、内容修改、安全检查等功能
"""
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage
def check_weather(location: str) -> str:
"""Return the weather forecast for the specified location."""
return f"It's always sunny in {location}"
llm = ChatOpenAI(
model="qwen3:0.6b",
base_url="http://127.0.0.1:11434/v1",
api_key="ollama",
temperature=0.7,
)
def output_transformer(messages):
"""
输出转换器函数
参数:
messages: 消息列表
功能:
- 在消息返回给用户之前进行转换处理
- 可以过滤敏感信息
- 可以添加格式修饰
- 可以进行内容审核
返回:
转换后的消息列表
"""
transformed = []
for msg in messages:
if isinstance(msg, AIMessage) and msg.content:
original_content = msg.content
if "sunny" in original_content.lower():
modified_content = original_content.replace("sunny", "☀️ sunny")
else:
modified_content = original_content
transformed.append(AIMessage(content=modified_content))
else:
transformed.append(msg)
return transformed
print("=" * 60)
print("create_agent transformers 参数示例")
print("=" * 60)
print("\ntransformers 说明:")
print(" - 在消息输出前进行转换处理")
print(" - 适用于:")
print(" * 敏感信息过滤/脱敏")
print(" * 内容格式修饰(如添加 emoji)")
print(" * 安全审核/内容检查")
print(" * 日志记录")
print()
graph = create_agent(
model=llm,
tools=[check_weather],
system_prompt="You are a helpful assistant",
transformers=[output_transformer], # 添加输出转换器
)
inputs = {"messages": [{"role": "user", "content": "what is the weather in sf"}]}
print("输出转换器示例:将 'sunny' 替换为 '☀️ sunny'")
print()
for chunk in graph.stream(inputs, stream_mode="updates"):
print(chunk)
参考文档
- LangChain 官网: https://www.langchain.com/
- LangChain Python 文档: https://python.langchain.com/
- LangChain JavaScript 文档: https://js.langchain.com/
- LangChain GitHub: https://github.com/langchain-ai/langchain