大模型应用开发(十三)_LangChain链式调用2
·
8. LLMChain
Chain 模块是 LangChain 的心脏。它们实现了从单一、孤立的 LLM 调用到多步骤、数据驱动的工作流的飞跃。Chain 的本质是封装和编排,它将复杂的逻辑抽象为简单的输入和输出,极大地提高了代码的复用性和可维护性。
8.1 各种 Chain 解读
| 序号 | 类型 | 解读 |
|---|---|---|
| 1 | LLMChain | 基于大模型构建的最简单、最基本的链。它包含提示模板,能根据用户输入进行格式化,把格式化好的提示传入模型,然后返回 LLM 的响应,同时解析输出。LLMChain 广泛用于整个 LangChain 中,包括其他链和代理中都经常使用。 |
| 2 | SequentialChain(顺序链) | 当你需要多次调用语言模型,并将一个调用的输出作为另一个调用的输入时,顺序链特别有用。SimpleSequentialChain 是顺序链的最简单形式,每个步骤只有一个输入/输出,并且前一步的输出直接作为下一步的输入。SequentialChain 是更通用的顺序链形式,允许多个输入/输出。 |
| 3 | TransformChain(转换链) | 可以通过设置转换函数,对输入文本进行一系列的格式转换。例如,将长文档分割成句子,仅保留前 N 句,以满足 LLM 的令牌限制,然后传入 LLMChain 进行总结或处理。 |
| 4 | RouterChain(路由链) | 包含条件判断和多个目标链。通过调用 LLM,路由链能动态判断条件,从而决定调用哪个目标链执行后续操作。 |
| 5 | APIChain | 允许使用 LLM 与 API 交互以检索相关信息,通过提供与 API 相关的问题来构建链,适合自动化数据查询和操作。 |
| 6 | 工具链(Various Tool Chains) | 包含多种特殊功能链,例如:LLMMathChain(将 LLM 作为数学工具,解决数学问题)、RetrievalQA(通过向量检索构建问答系统),可扩展不同场景下的功能。 |
8.2 如何选择合适的 Chain
| 场景 | 目标 | 推荐 Chain |
|---|---|---|
| 单步问答/生成 | 简单的文本生成或格式化。 | LLMChain |
| 流水线任务 | 需按固定顺序执行多步逻辑。 | SequentialChain |
| 数据预处理/后处理 | 在 LLM 调用前后进行数据清洗或转换。 | TransformChain |
| 功能分发 | 一个应用支持多种功能,需根据输入自动选择。 | RouterChain |
| 调用外部服务 | 根据请求动态构造和执行 Web API 调用。 | APIChain |
| 自主决策与行动 | LLM 需要自主决定使用哪个外部工具来完成任务。 | Agent (包含 Tool Chain 逻辑) |
8.3 部分类型链代码实例
8.3.1 LLMChain

具体代码
from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate
from langchain.output_parsers import CommaSeparatedListOutputParser
from langchain_openai import ChatOpenAI
from langchain.chains import LLMChain
# 1️⃣ 定义输出解析器
output_parser = CommaSeparatedListOutputParser()
parser_instructions = output_parser.get_format_instructions()
# 2️⃣ 定义 ChatPromptTemplate(System + Human)
prompt = ChatPromptTemplate.from_messages([
SystemMessagePromptTemplate.from_template("{parser_instructions}"),
HumanMessagePromptTemplate.from_template("列出S个{subject}色系的十六进制色码。")
])
# 3️⃣ 定义模型
model = ChatOpenAI(model="gpt-3.5-turbo")
# 4️⃣ 创建 LLMChain(自动处理 prompt + model + output_parser)
chain = LLMChain(
llm=model,
prompt=prompt,
output_parser=output_parser
)
# 5️⃣ 调用 Chain
result = chain.invoke({
"subject": "粉红",
"parser_instructions": parser_instructions
})
# 6️⃣ 输出解析后的列表
print("解析后的十六进制色码列表:", result)
8.3.2 SequentialChain

# 简单的生成编剧后,再生成广告文案示例
from langchain.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
from langchain.chains import LLMChain, SimpleSequentialChain
# 🎬 1️⃣ 剧本生成链
script_prompt_tpl = PromptTemplate.from_template(
"你是一名优秀的编剧,请发挥你的想象力,根据以下主题写一个完整的故事脚本。\\n\\n主题:{title}"
)
script_llm = ChatOpenAI(
temperature=0.9,
max_tokens=1024,
model="gpt-3.5-turbo"
)
script_chain = LLMChain(
llm=script_llm,
prompt=script_prompt_tpl
)
# 📢 2️⃣ 广告文案生成链
adv_prompt_tpl = PromptTemplate.from_template(
"你是一名顶级广告文案撰写专家。根据下面的故事概要,写一段简短、有吸引力的广告语,能激发观众想观看的欲望。\\n\\n故事概要:{story}"
)
adv_llm = ChatOpenAI(
temperature=1.3,
max_tokens=300,
model="gpt-3.5-turbo"
)
adv_chain = LLMChain(
llm=adv_llm,
prompt=adv_prompt_tpl
)
# 🔗 3️⃣ 串联成一个顺序链
overall_chain = SimpleSequentialChain(
chains=[script_chain, adv_chain],
verbose=True
)
# 🚀 4️⃣ 执行链
result = overall_chain.invoke("孙悟空大战人工智能")
print("\\n📜 最终广告语:")
print(result)
8.3.3 TransformChain

具体代码
from langchain.prompts import PromptTemplate
from langchain.chains import TransformChain, LLMChain, SimpleSequentialChain
from langchain_openai import ChatOpenAI
# 1️⃣ 读取文本文件
file_content = ""
with open("D:\\python object\\DeepSeek\\LangChain\\Chain\\data.txt", "r", encoding="utf-8") as file:
file_content = file.read()
# 2️⃣ 定义转换函数:提取前 8 段并替换部分字符
def transform_func(data):
text = data["input_text"]
# 提取前 8 段(按换行符分段)
shortened_text = "\\n".join(text.split("\\n")[:8])
# 替换关键字
transformed_shortened_text = (
shortened_text
.replace("PVC", "PersistentVolumeClaim")
.replace("PV", "PersistentVolume")
)
return {"output_text": transformed_shortened_text}
# 3️⃣ 定义 TransformChain
transform_chain = TransformChain(
input_variables=["input_text"],
output_variables=["output_text"],
transform=transform_func
)
# 4️⃣ 定义 LLMChain(使用 ChatOpenAI)
model = ChatOpenAI(
model="gpt-3.5-turbo",
temperature=0.7,
max_tokens=512
)
# 提示模板:要求总结和分析
prompt_template = PromptTemplate.from_template(
"以下是经过预处理的文档内容,请总结其主要主题并说明技术重点:\\n\\n{output_text}"
)
llm_chain = LLMChain(
llm=model,
prompt=prompt_template
)
# 5️⃣ 串联两个链
final_chain = SimpleSequentialChain(chains=[transform_chain, llm_chain], verbose=True)
# 6️⃣ 执行
res = final_chain.run(file_content)
# 7️⃣ 输出结果
print("\\n✅ 模型总结结果:")
print(res)
8.3.4 RouterChain

具体代码
from langchain.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
from langchain_core.runnables import RunnableLambda
# -------------------------------
# 1️⃣ 定义三个专门领域的提示模板
# -------------------------------
# 物理专家
physics_template = """
你是一位物理学家,擅长回答物理相关的问题。
当你不知道问题的答案时,你会直接回答"我不知道"。
问题如下:
{input}
"""
physics_prompt = PromptTemplate.from_template(physics_template)
# 数学专家
math_template = """
你是一位数学家,擅长回答数学相关的问题。
当你不知道问题的答案时,你会直接回答"我不知道"。
问题如下:
{input}
"""
math_prompt = PromptTemplate.from_template(math_template)
# 英语老师
english_template = """
你是一位非常优秀的英语老师,擅长回答英语语法、单词、阅读等问题。
当你不知道问题的答案时,你会直接回答"我不知道"。
问题如下:
{input}
"""
english_prompt = PromptTemplate.from_template(english_template)
# 默认提示
default_template = """
你是一个通用的AI助手,请回答以下问题:
{input}
"""
default_prompt = PromptTemplate.from_template(default_template)
# -------------------------------
# 2️⃣ 创建模型和链(使用现代 | 操作符)
# -------------------------------
model = ChatOpenAI(temperature=0.5, model="gpt-3.5-turbo")
# 使用 | 操作符创建链
physics_chain = physics_prompt | model
math_chain = math_prompt | model
english_chain = english_prompt | model
default_chain = default_prompt | model
# -------------------------------
# 3️⃣ 构造路由提示模板(使用LLM智能路由)
# -------------------------------
destinations = """
physics: 擅长回答物理问题
math: 擅长回答数学问题
english: 擅长回答英语问题
"""
router_template = f"""
你是一个智能问题分类助手。
请根据输入内容判断应该交给哪个专家回答。
可选目的地如下:
{destinations}
请严格返回如下格式:
destination: physics 或 math 或 english 或 default
问题如下:
{{input}}
"""
router_prompt = PromptTemplate.from_template(router_template)
router_chain = router_prompt | model
# -------------------------------
# 4️⃣ 创建智能路由函数
# -------------------------------
def smart_route_question(input_dict):
# 使用LLM进行路由决策
route_result = router_chain.invoke({"input": input_dict["input"]})
destination = route_result.content.strip().lower()
print(f"> 路由结果: {destination}")
# 根据路由结果选择对应的链
if "physics" in destination:
return physics_chain
elif "math" in destination:
return math_chain
elif "english" in destination:
return english_chain
else:
return default_chain
# -------------------------------
# 5️⃣ 创建完整的多路链
# -------------------------------
multi_route_chain = RunnableLambda(smart_route_question)
# -------------------------------
# 6️⃣ 运行测试
# -------------------------------
print("物理问题:")
result1 = multi_route_chain.invoke({"input": "请解释一下量子纠缠是什么。"})
print(result1.content)
print("\\n数学问题:")
result2 = multi_route_chain.invoke({"input": "请计算一下 y=x^2 的导数。"})
print(result2.content)
print("\\n英语问题:")
result3 = multi_route_chain.invoke({"input": "请解释单词 'serendipity' 的意思。"})
print(result3.content)
8.4 UI界面demo
8.4.1 示例1:带UI界面的视频脚本生成模型
运行命令
python -m streamlit run "D:\\python object\\DeepSeek\\LangChain\\VideoScript\\main.py"
You can now view your Streamlit app in your browser.
Local URL: <http://localhost:8501>
Network URL: <http://172.20.10.4:8501>

8.4.2 提示词与代码分离
1.什么叫“代码和提示词混合”?
例如下面这种写法,就是“混合”的:
response = llm.invoke(f"""
你是一个中文诗人。
请写一首关于“{topic}”的七言绝句。
要求:
- 意境优美
- 押韵
""")
而“分离式”的写法通常是:
prompt_template = """
你是一个中文诗人。
请写一首关于“{topic}”的七言绝句。
要求:
- 意境优美
- 押韵
"""
prompt = ChatPromptTemplate.from_template(prompt_template)
response = llm.invoke(prompt.format(topic="春天"))
2.混合写法的优缺点
| 方面 | 优点 | 缺点 |
|---|---|---|
| 开发速度 | 快速编写原型,不必管理模板文件。 | 后期维护困难,逻辑和提示混杂。 |
| 可读性 | 直观、贴近自然语言,适合小脚本。 | 当逻辑变复杂(变量多、条件判断多)时变得难读。 |
| 调试性 | 方便立即改动提示词并测试结果。 | 不容易追踪不同版本的提示。 |
| 可维护性 | 适合一次性实验。 | 无法规模化复用,Prompt 难以独立优化。 |
| 多人协作 | 程序员改提示容易破坏逻辑。 | 难与非程序人员(如产品、Prompt 工程师)协作调整提示。 |
3.最佳实践:提示词与代码分离
如果你打算项目化或长期维护,建议采用 Prompt 模板 + 参数注入 的模式:
✅ 推荐做法 1:模板分离 + 参数注入
# prompts/poem_prompt.txt
"""
你是一个中文诗人。
请写一首关于“{topic}”的七言绝句。
要求:
- 意境优美
- 押韵
"""
# main.py
from langchain import PromptTemplate, LLMChain
from langchain.chat_models import ChatOpenAI
with open("prompts/poem_prompt.txt", "r", encoding="utf-8") as f:
poem_prompt = f.read()
prompt = PromptTemplate.from_template(poem_prompt)
llm = ChatOpenAI(model="gpt-4o")
chain = LLMChain(llm=llm, prompt=prompt)
result = chain.invoke({"topic": "春天"})
print(result["text"])
优势:
- 模板独立管理,易调优;
- 支持版本控制(比如 git diff 提示变化);
- 易于非技术人员修改;
- 同时保证代码逻辑的清晰性。
✅ 推荐做法 2:配置式 Prompt(适合多类型任务)
在大型项目中,你可以把所有提示定义在一个 prompts.yaml 文件中:
poem_prompt: |
你是一个中文诗人。
请写一首关于“{topic}”的七言绝句。
要求:
- 意境优美
- 押韵
qa_prompt: |
你是一个问答助手。请根据以下内容回答用户问题。
内容:{context}
问题:{question}
然后在代码中加载:
import yaml
from langchain import PromptTemplate
prompts = yaml.safe_load(open("prompts.yaml", "r", encoding="utf-8"))
prompt = PromptTemplate.from_template(prompts["qa_prompt"])
这种方式是大规模 LLM 项目(如 LangChain、ChatGLM、LlamaIndex 应用)常见的做法。
✅ 推荐做法 3:提示调试专用模块
在项目中单独创建一个模块 /prompts/debugger.py 或 /prompt_tools/,
写一些辅助函数来查看模板渲染效果:
def preview_prompt(prompt, **kwargs):
print("🔹Prompt Preview:")
print(prompt.format(**kwargs))
这样可以快速在命令行调试模板效果,而不改动主逻辑。
4.总结建议
| 场景 | 推荐方式 |
|---|---|
| 快速测试、小脚本 | 混合式写法 OK |
| 正式项目、多人协作 | 模板分离、结构化管理 |
| 多 Prompt / 多模型任务 | 用 YAML / JSON 管理提示模板 |
| Prompt 调优、版本对比 | 独立文件 + Git 追踪 |
示例2:小红书文案生成

更多推荐



所有评论(0)