【AI大模型学习路线】第三阶段之RAG与LangChain——第十五章(LangChain与Chain组件)LLMChain,Sequential Chain详解 ?
欢迎宝子们点赞、关注、收藏!欢迎宝子们批评指正!
祝所有的硕博生都能遇到好的导师!好的审稿人!好的同门!顺利毕业!
大多数高校硕博生毕业要求需要参加学术会议,发表EI或者SCI检索的学术论文会议论文。详细信息可关注VX “
学术会议小灵通
”或参考学术信息专栏:https://fighting.blog.csdn.net/article/details/148185942
随着大语言模型(LLM)如 GPT-4、Claude、Gemini 的强大能力被挖掘,单轮对话已不能满足实际需求。我们需要将 LLM 封装成结构化组件,支持多轮、多阶段、多工具的复杂任务流程。
这就是 LangChain 提出的 “Chain” 思想,其中最核心的两个组件是:
LLMChain
: 单步执行 + Prompt模板封装SequentialChain
: 多步组合执行 + 数据流转控制LLMChain
是 LangChain 中最基础的 Chain 类型,它负责:
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
# 创建模型
llm = OpenAI(model_name="gpt-3.5-turbo", temperature=0.7)
# 创建 Prompt 模板
prompt = PromptTemplate(
input_variables=["product"],
template="为一款名为 {product} 的新产品撰写一句广告文案。"
)
# 创建 LLMChain
chain = LLMChain(llm=llm, prompt=prompt)
# 执行链
result = chain.run("智能猫砂盆")
print(" 广告文案:", result)
SequentialChain
可以将多个 Chain 串联起来,每一步的输出成为下一步的输入,构建流水线式任务。
支持两种形式:
SimpleSequentialChain
:SequentialChain
(推荐):from langchain.chains import SequentialChain, LLMChain
from langchain.prompts import PromptTemplate
from langchain.llms import OpenAI
llm = OpenAI(model_name="gpt-3.5-turbo", temperature=0.7)
# 第1步:生成产品介绍
product_prompt = PromptTemplate(
input_variables=["product"],
template="请介绍这款产品:{product}"
)
product_chain = LLMChain(llm=llm, prompt=product_prompt, output_key="description")
# 第2步:将产品介绍变成幽默风格广告语
funny_prompt = PromptTemplate(
input_variables=["description"],
template="请将以下产品介绍转为幽默风格广告语:{description}"
)
funny_chain = LLMChain(llm=llm, prompt=funny_prompt, output_key="funny_ad")
# 串联两个链
chain = SequentialChain(
chains=[product_chain, funny_chain],
input_variables=["product"],
output_variables=["description", "funny_ad"],
verbose=True
)
# 执行
result = chain.run({"product": "自清洁智能猫砂盆"})
print("\n 产品介绍:", result["description"])
print(" 幽默广告语:", result["funny_ad"])
特性 | LLMChain |
SequentialChain |
---|---|---|
目标 | 单步任务 | 多步组合任务 |
Prompt | 单一模板 | 多个模板,逐步处理 |
输入输出 | 输入→输出 | 支持多输入、多输出 |
典型应用 | 问答、摘要 | 多步骤推理、文本转换 |
可读性 | 高 | 略复杂 |
随着 RAG、Agent、工具调用的发展,Chain 不再只是调 LLM 的“外壳”,而是:
核心组件 | 功能 |
---|---|
LLMChain |
封装单步 LLM 推理任务(带 Prompt) |
SequentialChain |
多个 Chain 的流水线组合,支持复杂任务 |