LangChain Chain 实战:串联多个 AI 任务
单个 AI 搞不定复杂任务?用 Chain 串联多个 AI,自动完成多步骤工作流!
为什么需要 Chain?
场景:写一篇文章
- 步骤 1:生成大纲
- 步骤 2:扩充内容
- 步骤 3:润色文字
- 步骤 4:生成标题
手动搞?太累!用 Chain 自动串联!
🛠️ 3 种 Chain 详解
1. LLMChain(最基础)
python
from langchain.chains import LLMChain
from langchain_openai import ChatOpenAI
from langchain.prompts import PromptTemplate
llm = ChatOpenAI(model="gpt-3.5-turbo")
prompt = PromptTemplate(
input_variables=["topic"],
template="写一篇关于{topic}的 200 字介绍"
)
chain = LLMChain(llm=llm, prompt=prompt)
result = chain.run("人工智能")
print(result)
2. SequentialChain(顺序执行)
python
from langchain.chains import SequentialChain, LLMChain
# 链 1:生成大纲
outline_prompt = PromptTemplate(
input_variables=["topic"],
template="为{topic}生成一个文章大纲"
)
outline_chain = LLMChain(llm=llm, prompt=outline_prompt, output_key="outline")
# 链 2:扩充内容
content_prompt = PromptTemplate(
input_variables=["topic", "outline"],
template="根据大纲{outline},写一篇关于{topic}的文章"
)
content_chain = LLMChain(llm=llm, prompt=content_prompt, output_key="content")
# 链 3:生成标题
title_prompt = PromptTemplate(
input_variables=["content"],
template="为以下文章生成 3 个吸引人的标题:\n{content}"
)
title_chain = LLMChain(llm=llm, prompt=title_prompt, output_key="titles")
# 串联
sequential_chain = SequentialChain(
chains=[outline_chain, content_chain, title_chain],
input_variables=["topic"],
output_variables=["outline", "content", "titles"],
verbose=True
)
result = sequential_chain({"topic": "Python 自动化办公"})
print(f"大纲:{result['outline']}")
print(f"标题:{result['titles']}")
3. TransformChain(数据转换)
python
from langchain.chains import TransformChain
def transform_func(inputs: dict) -> dict:
text = inputs["text"]
word_count = len(text.split())
return {"output": f"这篇文章有{word_count}个字"}
transform_chain = TransformChain(
input_variables=["text"],
output_variables=["output"],
transform=transform_func
)
result = transform_chain({"text": "你好世界"})
print(result["output"]) # 这篇文章有 2 个字
🎯 完整项目:文章生成器
python
"""
AI 文章生成器
功能:
1. 生成大纲
2. 扩充内容
3. 润色文字
4. 生成标题
5. 输出 Markdown 格式
"""
from langchain.chains import SequentialChain, LLMChain
from langchain_openai import ChatOpenAI
from langchain.prompts import PromptTemplate
import json
class ArticleGenerator:
def __init__(self):
self.llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.7)
self._create_chains()
def _create_chains(self):
"""创建各个 Chain"""
# 1. 大纲生成
outline_prompt = PromptTemplate(
input_variables=["topic"],
template="""
为"{topic}"生成一个详细的文章大纲。
要求:
- 包含 5-7 个主要章节
- 每个章节有 2-3 个子要点
- 用 Markdown 格式输出
大纲:
"""
)
self.outline_chain = LLMChain(
llm=self.llm,
prompt=outline_prompt,
output_key="outline"
)
# 2. 内容生成
content_prompt = PromptTemplate(
input_variables=["topic", "outline"],
template="""
根据以下大纲,写一篇关于"{topic}"的完整文章。
要求:
- 2000 字以上
- 语言通俗易懂
- 包含实际案例
- 用 Markdown 格式
大纲:
{outline}
文章:
"""
)
self.content_chain = LLMChain(
llm=self.llm,
prompt=content_prompt,
output_key="content"
)
# 3. 润色优化
polish_prompt = PromptTemplate(
input_variables=["content"],
template="""
润色以下文章:
- 修正语法错误
- 优化句子流畅度
- 增强可读性
- 保持原意
原文:
{content}
润色后:
"""
)
self.polish_chain = LLMChain(
llm=self.llm,
prompt=polish_prompt,
output_key="polished"
)
# 4. 标题生成
title_prompt = PromptTemplate(
input_variables=["content"],
template="""
为以下文章生成 5 个吸引人的标题:
- 每个标题 20 字以内
- 有吸引力但不夸张
- 包含关键词
文章:
{content}
标题(每行一个):
"""
)
self.title_chain = LLMChain(
llm=self.llm,
prompt=title_prompt,
output_key="titles"
)
# 5. 串联所有 Chain
self.full_chain = SequentialChain(
chains=[
self.outline_chain,
self.content_chain,
self.polish_chain,
self.title_chain
],
input_variables=["topic"],
output_variables=["outline", "content", "polished", "titles"],
verbose=True
)
def generate(self, topic, save_path=None):
"""生成文章"""
print(f"📝 开始生成关于"{topic}"的文章...")
# 执行 Chain
result = self.full_chain({"topic": topic})
# 格式化输出
article = {
"topic": topic,
"outline": result["outline"],
"content": result["polished"],
"titles": result["titles"].split("\n"),
"created_at": "2026-06-17"
}
# 保存
if save_path:
with open(save_path, 'w', encoding='utf-8') as f:
json.dump(article, f, ensure_ascii=False, indent=2)
print(f"✅ 文章已保存到 {save_path}")
return article
def main():
generator = ArticleGenerator()
topic = input("请输入文章主题:")
article = generator.generate(topic, save_path="article.json")
print("\n" + "="*60)
print("📄 生成的文章")
print("="*60)
print(f"主题:{article['topic']}")
print(f"\n推荐标题:")
for i, title in enumerate(article['titles'][:3], 1):
print(f" {i}. {title}")
print(f"\n大纲:\n{article['outline']}")
print(f"\n正文(前 500 字):\n{article['content'][:500]}...")
if __name__ == '__main__':
main()
⚠️ 血泪教训
- Chain 不要太长,超过 5 步容易出错
- 每步要验证,中间结果可能有问题
- 温度值调低,Chain 里需要稳定性
- 保存中间结果,调试时很有用
📦 源码获取
下篇预告:《LangChain Agent 入门:让 AI 自主调用工具》
标签: #LangChain #Chain #AI #自动化 #Python