graph TB
A[LangChain 框架] --> B[Models 模型层]
A --> C[Prompts 提示层]
A --> D[Memory 记忆层]
A --> E[Indexes 索引层]
A --> F[Chains 链式层]
A --> G[Agents 代理层]
B --> B1[GPT-4o]
B --> B2[通义千问]
B --> B3[其他 LLM]
C --> C1[提示管理]
C --> C2[提示优化]
C --> C3[提示序列化]
D --> D1[对话上下文]
D --> D2[历史记录]
E --> E1[文档加载]
E --> E2[文本切割]
E --> E3[向量索引]
F --> F1[组件串联]
F --> F2[数据流转]
G --> G1[工具调用]
G --> G2[决策执行]
style A fill:#7C3AED,color:#fff
style B fill:#06B6D4,color:#fff
style C fill:#06B6D4,color:#fff
style D fill:#06B6D4,color:#fff
style E fill:#06B6D4,color:#fff
style F fill:#06B6D4,color:#fff
style G fill:#06B6D4,color:#fff
graph LR
A[LangChain 0.x] -->|重构| B[LangChain 1.x]
B --> C[langchain-core 抽象基类 + LCEL]
B --> D[langchain-community 社区集成]
B --> E[合作伙伴包 独立库]
B --> F[LangGraph 图编排]
B --> G[LangServe API 服务]
B --> H[LangSmith 调试监控]
style A fill:#ccc
style B fill:#7C3AED,color:#fff
style C fill:#28a745,color:#fff
style D fill:#28a745,color:#fff
style E fill:#28a745,color:#fff
style F fill:#ffc107
style G fill:#ffc107
style H fill:#ffc107
🔧 二、基础应用案例
2.1 案例 1:基础 Chain(Prompt + LLM)
最基础的 LangChain 用法是将 Prompt 模板和 LLM 组合成可执行链。
sequenceDiagram
participant User as 用户
participant Prompt as Prompt 模板
participant LLM as 大语言模型
participant Output as 输出结果
User->>Prompt: 输入变量 {product: "colorful socks"}
Prompt->>Prompt: 格式化模板 "What is a good name for a company that makes {product}?"
Prompt->>LLM: 发送完整 Prompt
LLM->>LLM: 生成回答
LLM->>Output: 返回公司名称建议
Output->>User: 展示结果
Note over Prompt,LLM: 使用管道符 | 组合 chain = prompt | llm
# 1. 创建 Prompt 模板
from langchain_core.prompts import PromptTemplate
prompt = PromptTemplate(
input_variables=["product"],
template="What is a good name for a company that makes {product}?",
)
# 2. 加载 LLM
from langchain_community.llms import Tongyi
llm = Tongyi(
model_name="qwen-turbo",
dashscope_api_key=api_key
)
# 3. 使用管道符 | 组合成 Chain(推荐写法)
chain = prompt | llm
# 4. 调用 invoke 执行
result = chain.invoke({"product": "colorful socks"})
""
2.2 案例 2:Agent + 搜索工具
Agent 可以使用外部工具(如搜索引擎)来增强能力,自主决定何时调用哪些工具。
graph TD
A[用户提问: 今天是几月几号? 历史上的今天有哪些名人出生] --> B[Agent 分析]
B --> C{需要哪些工具?}
C -->|需要实时信息| D[调用 SerpAPI 搜索工具]
D --> E[获取搜索结果]
E --> F[LLM 整合信息]
F --> G[生成最终答案]
G --> H[返回用户]
style A fill:#e3f2fd
style B fill:#7C3AED,color:#fff
style D fill:#28a745,color:#fff
style F fill:#06B6D4,color:#fff
style H fill:#ffc107
graph LR
A[预置工具] --> C[工具集合]
B[自定义工具 @tool 装饰器] --> C
C --> D[Agent]
D --> E[智能调用]
A1[SerpAPI 搜索] --> A
A2[Wikipedia] --> A
A3[llm-math] --> A
B1[Calculator] --> B
B2[自定义函数] --> B
style A fill:#28a745,color:#fff
style B fill:#ffc107
style D fill:#7C3AED,color:#fff
graph TB
A[Memory 记忆类型] --> B[BufferMemory 完整存储]
A --> C[BufferWindowMemory 窗口存储]
A --> D[ConversionMemory 摘要存储]
A --> E[VectorStore-backed Memory 向量存储]
B --> B1[存储所有对话 传给 LLM]
C --> C1[存储最近 K 组对话 传给 LLM]
D --> D1[对话摘要压缩 传给 LLM]
E --> E1[向量数据库存储 相似度匹配检索]
style A fill:#7C3AED,color:#fff
style B fill:#28a745,color:#fff
style C fill:#28a745,color:#fff
style D fill:#28a745,color:#fff
style E fill:#28a745,color:#fff
3.3 案例 4:带记忆的对话链
sequenceDiagram
participant U as 用户
participant C as 对话链
participant M as Memory
participant L as LLM
U->>C: 第一轮: "Hi there!"
C->>M: 保存消息
C->>L: 发送 Prompt + 历史
L->>C: 回复
C->>M: 保存回复
C->>U: 返回结果
U->>C: 第二轮: "What did I just say?"
C->>M: 读取历史
M->>C: 返回历史消息
C->>L: 发送 Prompt + 历史
L->>C: 基于历史回复
C->>M: 保存新对话
C->>U: 返回结果
Note over M: session_id 区分不同会话
""
# 1. 创建带历史占位符的 Prompt
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant."),
MessagesPlaceholder(variable_name="history"), # 历史消息占位符
("human", "{input}")
])
# 2. 创建会话历史存储
from langchain_core.chat_history import InMemoryChatMessageHistory
store = {}
def get_session_history(session_id: str):
if session_id not in store:
store[session_id] = InMemoryChatMessageHistory()
return store[session_id]
# 3. 创建带记忆的对话链
from langchain_core.runnables.history import RunnableWithMessageHistory
conversation = RunnableWithMessageHistory(
chain,
get_session_history,
input_messages_key="input",
history_messages_key="history"
)
# 4. 使用 session_id 区分不同会话
config = {"configurable": {"session_id": "default"}}
output = conversation.invoke({"input": "Hi there!"}, config=config)
🎯 四、ReAct 范式:推理与行动的协同
4.1 什么是 ReAct?
ReAct(Reasoning and Acting)是一种将推理和动作相结合的范式,克服了 LLM 胡言乱语的问题,
同时提高了结果的可解释性和可信赖度。它模拟了人类在执行多步骤任务时的思考过程。
💡 核心洞察
人们在从事一项需要多个步骤的任务时,在步骤和步骤之间,或者动作和动作之间,
一般都会有推理过程。ReAct 将这种人类行为模式应用到 AI Agent 中。
4.2 ReAct 工作流程
graph TD
A[Question 用户问题] --> B[Thought 1 思考需要做什么]
B --> C[Action 1 选择工具]
C --> D[Action Input 1 工具输入]
D --> E[Observation 1 观察结果]
E --> F{是否找到答案?}
F -->|否| G[Thought 2 继续思考]
G --> H[Action 2 选择新工具]
H --> I[Action Input 2 新输入]
I --> J[Observation 2 新结果]
J --> K{是否找到答案?}
K -->|否| L[重复 N 次...]
K -->|是| M[Thought Final 我现在知道答案了]
F -->|是| M
M --> N[Final Answer 最终答案]
style A fill:#e3f2fd
style B fill:#fff3cd
style C fill:#d1ecf1
style E fill:#d4edda
style M fill:#fff3cd
style N fill:#ffc107
stateDiagram-v2
[*] --> Question: 用户提问
Question --> Thought: 分析问题
Thought --> Action: 选择工具
Action --> ActionInput: 准备输入
ActionInput --> Observation: 执行并观察
Observation --> CheckAnswer: 检查是否找到答案
CheckAnswer --> Thought: 否,继续思考
CheckAnswer --> FinalAnswer: 是,得出结论
FinalAnswer --> [*]: 返回用户
note right of Thought
AI 自主推理
决定下一步行动
end note
note right of Action
从工具列表中
选择合适的工具
end note
note right of Observation
执行工具
获取结果
end note
7.3 自动生成的提示词格式
Answer the following questions as best you can.
You have access to the following tools:
<工具1名称>: <工具1描述>
<工具2名称>: <工具2描述>
...
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [工具1, 工具2, ...]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
🌐 八、AI Agent 平台对比
8.1 主流平台概览
工具
核心定位
架构特点
适用场景
LangChain
开源 LLM 应用开发框架
基于链(Chain)的线性或分支工作流,支持 Agent 模式
快速构建 RAG、对话系统、工具调用等线性任务
LangGraph
LangChain 的扩展,专注于复杂工作流
基于图(Graph)的循环和条件逻辑,支持多 Agent 协作
需要循环、动态分支或状态管理的复杂任务
Qwen-Agent
通义千问的 AI Agent 框架
基于阿里云大模型,支持多模态交互与工具调用
开源,集成多种工具,MCP 调用
Coze
字节跳动的无代码 AI Bot 平台
可视化拖拽界面,内置知识库、多模态插件
快速部署社交平台机器人、轻量级工作流
Dify
开源 LLM 应用开发平台
API 优先,支持 Prompt 工程与灵活编排
开发者定制化 LLM 应用,需深度集成或私有化部署
8.2 平台能力对比
graph TB
subgraph Comparison["能力对比维度"]
A[工作流编排]
B[工具调用与扩展性]
C[RAG 检索增强]
D[多模态与部署]
end
A --> A1[LangChain: 线性链]
A --> A2[LangGraph: 循环+条件]
A --> A3[Coze: 可视化拖拽]
A --> A4[Dify: 自然语言定义]
B --> B1[LangChain/Graph: 自定义工具]
B --> B2[Coze: 预置插件生态]
B --> B3[Dify: OpenAPI 集成]
C --> C1[LangChain: 开箱即用]
C --> C2[LangGraph: 手动设计+优化]
C --> C3[Dify/Coze: 基础支持]
D --> D1[Coze: 图像视频+社交平台]
D --> D2[Qwen-Agent: 开源+MCP]
D --> D3[Dify: 私有化部署]
style Comparison fill:#7C3AED,color:#fff
style A fill:#06B6D4,color:#fff
style B fill:#06B6D4,color:#fff
style C fill:#06B6D4,color:#fff
style D fill:#06B6D4,color:#fff
构建一个专业的网络故障诊断系统,集成 DNS 解析、Ping 检查、接口检查、日志分析等多个工具,
实现自动化的网络问题排查。
""
⭐ 十一、最佳实践与建议
11.1 选择合适的架构
场景
推荐方案
理由
简单的问答系统
基础 Chain(Prompt + LLM)
简单高效,无需复杂逻辑
需要实时信息查询
Agent + 搜索工具
能够获取最新信息
多轮对话系统
Chain + Memory
保持上下文连贯性
复杂决策任务
Agent + 多工具 + ReAct
灵活应对复杂场景
固定流程任务
LCEL 链式组合
可控性强,易于维护
多 Agent 协作
LangGraph
支持复杂的状态管理
11.2 工具设计原则
单一职责:每个工具只做一件事,做好一件事
清晰描述:工具的 description 要准确描述功能和使用场景
错误处理:工具要有完善的错误处理机制
输入验证:对输入参数进行严格验证
可测试性:工具应该易于单独测试
11.3 Prompt 设计技巧
明确角色:告诉 AI 它扮演什么角色
清晰指令:使用明确的动词和步骤
提供示例:Few-shot learning 提高准确性
格式约束:明确输出格式要求
思维链:引导 AI 一步步思考
11.4 性能优化建议
graph TB
A[性能优化] --> B[减少 API 调用]
A --> C[优化 Prompt]
A --> D[缓存机制]
A --> E[并行处理]
B --> B1[合并多个请求]
B --> B2[使用更小的模型]
C --> C1[精简提示词]
C --> C2[减少示例数量]
D --> D1[缓存常见查询]
D --> D2[向量索引缓存]
E --> E1[并行调用工具]
E --> E2[异步处理]
style A fill:#7C3AED,color:#fff
style B fill:#28a745,color:#fff
style C fill:#28a745,color:#fff
style D fill:#28a745,color:#fff
style E fill:#28a745,color:#fff