本教程通过五个渐进式的实例,带你深入理解 LangChain 的核心概念和实际应用
通过本教程,你将学会:
LangChain 的核心思想是链式操作(Chaining)- 将多个处理步骤通过管道操作符 | 连接起来,形成一个完整的数据处理流水线。
# chain.py - 最简单的链式操作
model = ChatZhipuAI(model="GLM-4-FlashX-250414")
prompt_template = ChatPromptTemplate.from_messages([
("system", "you are a facts expert who knows facts about {animal}."),
("human", "Tell me {fact_count} facts in chinese."),
])
# 🔗 核心:三步链式操作
chain = prompt_template | model | StrOutputParser()
result = chain.invoke({"animal": "cat", "fact_count": 2})输入数据 {"animal": "cat", "fact_count": 2}
↓
📝 prompt_template: 格式化提示模板
↓
🤖 model: AI模型生成回复
↓
📤 StrOutputParser(): 提取纯文本
↓
输出结果: "关于猫的两个事实..."|: 连接不同的处理组件本部分通过手动构建链式操作和调试功能,让你深入理解每个步骤的数据变化过程。
# chain2.py - 详细的链式操作分解
format_prompt = RunnableLambda(lambda x: prompt_template.format_prompt(**x))
invoke_model = RunnableLambda(lambda x: model.invoke(x.to_messages()))
parse_output = RunnableLambda(lambda x: x.content)
# 手动构建的链
chain = RunnableSequence(format_prompt, invoke_model, parse_output)def debug_format_prompt(x):
print(f"输入 x: {x}") # dict
print(f"x 的类型: {type(x)}") # <class 'dict'>
result = prompt_template.format_prompt(**x)
print(f"输出类型: {type(result)}") # ChatPromptValue
return result步骤 | 输入类型 | 输出类型 | 作用 |
|---|---|---|---|
format_prompt | dict | ChatPromptValue | 格式化模板 |
invoke_model | ChatPromptValue | AIMessage | AI推理 |
parse_output | AIMessage | str | 提取文本 |
真实项目中,往往需要多个连续的处理步骤。本部分展示如何构建一个"生成内容→翻译→输出"的完整流水线。
# chain3.py - 多步骤处理链
# 第一个模板:生成动物事实
prompt_template = ChatPromptTemplate.from_messages([
("system", "you are a facts expert who knows facts about {animal}."),
("human", "Tell me {fact_count} facts in chinese."),
])
# 第二个模板:翻译内容
translation_prompt = ChatPromptTemplate.from_messages([
("system", "You are a translator and convert the following text into {language}."),
("human", "Translate the following text into {language}: {text}"),
])
# 数据转换函数
prepare_for_translation = RunnableLambda(
lambda output: {"text": output, "language": "french"}
)
# 🔗 完整的多步骤链
chain = (
prompt_template |
model |
StrOutputParser() |
prepare_for_translation |
translation_prompt |
model |
StrOutputParser()
){"animal": "cat", "fact_count": 2}
↓
📝 生成中文动物事实
↓
🤖 AI生成: "猫的两个事实..."
↓
📤 提取纯文本
↓
🔄 数据转换: {"text": "猫的两个事实...", "language": "french"}
↓
📝 翻译提示模板
↓
🤖 AI翻译: "Deux faits sur les chats..."
↓
📤 提取最终结果当需要对同一数据进行多角度分析时,并行处理能大大提高效率。本部分展示如何同时进行剧情分析和角色分析。
# chain4.py - 并行处理示例
# 电影摘要模板
summary_template = ChatPromptTemplate.from_messages([
("system", "You are a movie critic."),
("human", "Provide a brief summary of the movie {movie_name}.")
])
# 分析函数
def analyze_plot(plot):
plot_template = ChatPromptTemplate.from_messages([
("system", "You are a movie critic."),
("human", "Analyze the plot: {plot}. What are its strengths and weaknesses?"),
])
return plot_template.format_prompt(plot=plot)
# 🔀 并行处理链
chain = (
summary_template |
model |
StrOutputParser() |
RunnableParallel({
"summary": RunnableLambda(lambda x: x), # 保留原始摘要
"branches": RunnableParallel({
"plot": plot_branch_chain,
"characters": character_branch_chain
})
}) |
RunnableLambda(combine_verdicts)
)电影摘要文本
↓
┌─ RunnableParallel ────────────────────┐
│ │
│ 📋 summary: 保留原始摘要 │
│ │
│ 🔀 branches: RunnableParallel │
│ ├─ 📈 plot: 剧情分析 │
│ └─ 👥 characters: 角色分析 │
│ │
└───────────────────────────────────────┘
↓
📊 combine_verdicts: 合并所有结果真实应用中,往往需要根据输入内容的不同特征选择不同的处理路径。本部分展示如何构建智能的反馈处理系统。
# chain5.py - 条件分支处理
# 为不同情感定义不同的处理模板
positive_feedback_template = ChatPromptTemplate.from_messages([
("system", "你是一个乐于助人的助手。"),
("human", "为这条积极反馈生成一封感谢信:{feedback}。"),
])
negative_feedback_template = ChatPromptTemplate.from_messages([
("system", "你是一个乐于助人的助手。"),
("human", "为这条负面反馈生成一个回复:{feedback}。"),
])
# 🌲 条件分支路由
branches = RunnableBranch(
(
lambda x: "positive" in x,
positive_feedback_template | model | StrOutputParser()
),
(
lambda x: "negative" in x,
negative_feedback_template | model | StrOutputParser()
),
(
lambda x: "neutral" in x,
neutral_feedback_template | model | StrOutputParser()
),
escalate_feedback_template | model | StrOutputParser() # 默认分支
)
# 🔗 完整的智能路由链
chain = classification_chain | branches用户反馈
↓
🔍 情感分类: "这个产品很糟糕..."
↓
📊 分类结果: "negative"
↓
🌲 RunnableBranch 决策:
├─ ✅ positive? → 感谢信模板
├─ ✅ negative? → 问题解决模板 ← 选中
├─ ❌ neutral? → 详情询问模板
└─ ❌ default → 人工客服模板
↓
📝 生成针对性回复条件 | 处理策略 | 目标 |
|---|---|---|
积极反馈 | 生成感谢信 | 增强客户满意度 |
负面反馈 | 问题解决方案 | 化解客户不满 |
中性反馈 | 询问更多细节 | 获取有用信息 |
其他情况 | 转人工客服 | 确保服务质量 |
# ✅ 推荐:清晰的链式结构
chain = prompt | model | parser
# ✅ 推荐:适当的错误处理
try:
result = chain.invoke(input_data)
except Exception as e:
print(f"处理失败: {e}")
# ✅ 推荐:调试功能
debug_chain = chain.with_config({"run_name": "debug_run"})RunnableParallelstream() 方法RunnableLambda 添加日志输出