作为一名长期从事AI应用开发的工程师,我深刻理解直接调用大模型API的局限性。在实际业务场景中,我们往往需要处理复杂的多步骤流程和条件判断,这正是LangChain的Chain模块大显身手的地方。
Chain不是简单的API封装,而是将大模型能力工程化的关键组件。想象一下,如果没有Chain,我们要实现一个完整的电商客服系统需要:
而使用Chain后,我们可以:
| 链类型 | 适用场景 | 优势 | 局限性 |
|---|---|---|---|
| 基础链(LLMChain) | 单一任务处理 | 简单易用,便于复用 | 无法处理复杂流程 |
| 顺序链(SequentialChain) | 线性多步骤流程 | 自动传递上下文 | 缺乏条件判断能力 |
| 分支链(RouterChain) | 条件路由场景 | 智能分流处理 | 需要配合其他链使用 |
实际项目中,90%的复杂场景都需要组合使用这三种链。接下来我会通过具体案例展示如何灵活运用。
让我们从一个实际的电商运营需求出发:需要根据产品特性自动生成营销文案。传统做法是每次手动编写Prompt,而使用LLMChain可以将其标准化:
python复制from langchain import PromptTemplate, LLMChain
from langchain_openai import ChatOpenAI
# 初始化模型
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.8)
# 定义Prompt模板
prompt_template = PromptTemplate(
input_variables=["product_name", "features", "target_user"],
template="""
你是一名专业电商文案策划师,请为{product_name}创作推广文案:
产品特点:
{features}
目标用户:
{target_user}
要求:
1. 突出3个核心卖点
2. 使用{target_user}群体熟悉的语言风格
3. 包含行动号召语句
4. 限制在150字以内
"""
)
# 创建链实例
copywriting_chain = LLMChain(
llm=llm,
prompt=prompt_template,
verbose=True
)
# 执行链
result = copywriting_chain.run({
"product_name": "智能语音记事本",
"features": "语音转文字、多设备同步、AI摘要生成",
"target_user": "商务人士"
})
关键技巧:
直接获取文本输出往往难以程序化处理,使用输出解析器可以结构化结果:
python复制from langchain.output_parsers import StructuredOutputParser, ResponseSchema
# 定义输出结构
response_schemas = [
ResponseSchema(name="title", description="生成的文案标题"),
ResponseSchema(name="body", description="文案正文内容"),
ResponseSchema(name="keywords", description="提取的关键词列表", type="array")
]
output_parser = StructuredOutputParser.from_response_schemas(response_schemas)
# 在Prompt中加入格式指令
template = """
生成电商文案:
{product_info}
{format_instructions}
"""
prompt = PromptTemplate(
template=template,
input_variables=["product_info"],
partial_variables={"format_instructions": output_parser.get_format_instructions()}
)
chain = LLMChain(llm=llm, prompt=prompt, output_parser=output_parser)
result = chain.run("智能跳绳,可计数、卡路里计算、蓝牙连接")
print(result["keywords"]) # 直接获取关键词列表
让我们构建一个真实的内容生产流程:市场分析→内容生成→SEO优化→多平台适配
python复制from langchain.chains import SequentialChain
# 市场分析链
market_analysis_chain = LLMChain(
llm=llm,
prompt=PromptTemplate(
input_variables=["product"],
template="分析{product}的目标用户画像和核心卖点"
),
output_key="analysis"
)
# 内容生成链
content_chain = LLMChain(
llm=llm,
prompt=PromptTemplate(
input_variables=["analysis"],
template="根据以下分析生成营销内容:\n{analysis}"
),
output_key="content"
)
# SEO优化链
seo_chain = LLMChain(
llm=llm,
prompt=PromptTemplate(
input_variables=["content"],
template="优化以下内容的SEO关键词密度:\n{content}"
),
output_key="seo_content"
)
# 多平台适配链
platform_chain = LLMChain(
llm=llm,
prompt=PromptTemplate(
input_variables=["seo_content"],
template="将以下内容适配到微信、微博、小红书平台:\n{seo_content}"
),
output_key="final_outputs"
)
# 构建顺序链
pipeline = SequentialChain(
chains=[market_analysis_chain, content_chain, seo_chain, platform_chain],
input_variables=["product"],
output_variables=["analysis", "content", "seo_content", "final_outputs"],
verbose=True
)
result = pipeline.run("无线降噪耳机")
避坑指南:
有时我们需要根据输入动态构建链序列:
python复制def build_chain(steps):
chains = []
for step in steps:
chains.append(LLMChain(
llm=llm,
prompt=PromptTemplate(
input_variables=["input"],
template=step["template"]
),
output_key=step["output_key"]
))
return SequentialChain(
chains=chains,
input_variables=["input"],
output_variables=[step["output_key"] for step in steps]
)
steps_config = [
{
"template": "分析{input}的技术原理",
"output_key": "tech_analysis"
},
{
"template": "根据{tech_analysis}生成科普文章",
"output_key": "article"
}
]
dynamic_chain = build_chain(steps_config)
构建能自动分流技术问题、售后咨询、产品推荐的客服系统:
python复制from langchain.chains.router import MultiPromptChain
# 定义各分支Prompt
tech_prompt = PromptTemplate(
template="作为技术支持工程师回答:\n{input}",
input_variables=["input"]
)
sales_prompt = PromptTemplate(
template="作为销售顾问回答:\n{input}",
input_variables=["input"]
)
# 分支配置
prompt_infos = [
{
"name": "technical",
"description": "回答产品使用技术问题",
"prompt_template": tech_prompt
},
{
"name": "sales",
"description": "处理产品购买咨询",
"prompt_template": sales_prompt
}
]
# 构建路由链
router_chain = MultiPromptChain.from_prompts(
llm=llm,
prompt_infos=prompt_infos,
default_chain=LLMChain(llm=llm, prompt=PromptTemplate(template="抱歉,我无法处理这个问题", input_variables=["input"])),
verbose=True
)
# 测试不同输入
print(router_chain.run("耳机连接不上怎么办")) # 走技术分支
print(router_chain.run("这款耳机有优惠吗")) # 走销售分支
性能优化技巧:
对于复杂路由需求,可以自定义决策逻辑:
python复制from langchain.chains.router.llm_router import LLMRouterChain, RouterOutputParser
# 自定义路由模板
CUSTOM_ROUTER_TEMPLATE = """根据用户问题类型选择处理方式:
技术问题 - 包含'怎么'、'如何'、'故障'等词
购买咨询 - 包含'价格'、'优惠'、'购买'等词
其他问题 - 不符合以上特征
用户输入:{input}
请只输出以下JSON格式:
{{
"destination": "technical|sales|default",
"next_inputs": {{"input": "{input}"}}
}}"""
router_prompt = PromptTemplate(
template=CUSTOM_ROUTER_TEMPLATE,
input_variables=["input"],
output_parser=RouterOutputParser()
)
custom_router = LLMRouterChain.from_llm(
llm=llm,
prompt=router_prompt
)
python复制# 技术问题处理流水线
tech_chain = SequentialChain([
LLMChain(...), # 问题诊断
LLMChain(...), # 解决方案生成
LLMChain(...) # 预防建议
])
# 销售咨询流水线
sales_chain = SequentialChain([
LLMChain(...), # 产品推荐
LLMChain(...), # 优惠方案
LLMChain(...) # 购买引导
])
# 顶层路由
router = MultiPromptChain(
router_chain=custom_router,
destination_chains={
"technical": tech_chain,
"sales": sales_chain
},
default_chain=default_chain
)
处理需要多轮交互的场景:
python复制from langchain.chains import TransformChain
def check_completion(inputs):
output = {"continue": not inputs["response"].endswith("?")}
return output
completion_chain = TransformChain(
input_variables=["response"],
output_variables=["continue"],
transform=check_completion
)
loop_chain = SequentialChain(
chains=[
LLMChain(...), # 生成响应
completion_chain # 检查是否结束
],
loop=True,
max_iterations=3
)
缓存策略:对相同输入缓存结果
python复制from langchain.cache import InMemoryCache
langchain.llm_cache = InMemoryCache()
超时控制:
python复制llm = ChatOpenAI(..., request_timeout=30)
批量处理:
python复制chain.apply([{"input": "A"}, {"input": "B"}])
python复制def log_execution(inputs, outputs):
logger.info(f"Input: {inputs}")
logger.info(f"Output: {outputs}")
return outputs
monitoring_chain = TransformChain(
input_variables=["input"],
output_variables=["input"],
transform=log_execution
)
chain = SequentialChain([
monitoring_chain,
processing_chain
])
python复制from langchain.schema import OutputParserException
try:
result = chain.run(input)
except OutputParserException as e:
handle_parsing_error(e)
except APIError as e:
handle_api_error(e)
except Exception as e:
handle_generic_error(e)
经过这些年的实践,我发现Chain的组合使用就像编程中的设计模式,掌握基础模式后,可以灵活应对各种复杂场景。最关键的还是理解业务需求,合理拆解流程,而不是强行套用链结构。