目标:吃透提示词模板与 Chain 核心用法,能独立写出基础问答、串行流程代码,为后续 RAG/Agent 打牢基础。
一、课程核心目标
✅ 掌握 3 种提示词模板的用法与场景 ✅ 理解 Chain 的本质:把组件串成自动化流水线 ✅ 熟练使用 5 种高频链(LLMChain / 顺序链 / 检索链 / 对话链) ✅ 写出可直接运行的示例代码,理解每一步作用
二、Part1:提示词模板精讲(1 小时)
1. 为什么要用提示词模板?
避免手动拼接字符串,实现代码复用、格式统一、易维护,减少错误。
2. 三类模板详解
(1)PromptTemplate:基础单轮模板
- 适用场景:单次独立问答、知识点讲解、固定格式生成
- 核心用法:
input_variables声明变量,template定义格式
python
运行
from langchain.prompts import PromptTemplate
# 1. 定义模板
template = "请用通俗易懂的语言,给前端工程师解释:{knowledge}"
prompt = PromptTemplate(
input_variables=["knowledge"], # 变量名,后续传参必须一致
template=template
)
# 2. 填充变量
formatted_prompt = prompt.format(knowledge="向量数据库")
print(formatted_prompt)
(2)ChatPromptTemplate:对话角色模板
- 适用场景:多轮对话、设定系统角色、区分用户 / 助手消息
- 核心角色:
system(系统规则)、human(用户提问)、ai(模型回复)
python
运行
from langchain.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
("system", "你是资深大模型技术讲师,回答简洁易懂,避免术语堆砌"),
("human", "什么是LangChain的Chain链?"),
("ai", "Chain链就是把多个组件串成一条自动化流水线,自动执行多步骤任务"),
("human", "那它和直接调用大模型有什么区别?")
])
formatted_prompt = prompt.format()
print(formatted_prompt)
(3)FewShotPromptTemplate:少样本提示模板
- 适用场景:约束输出格式、统一回答风格、给模型示例参考
python
运行
from langchain.prompts import FewShotPromptTemplate, PromptTemplate
# 示例数据
examples = [
{"input": "LangChain", "output": "LangChain是用于构建大模型应用的开发框架"},
{"input": "RAG", "output": "RAG是检索增强生成,用于让大模型基于私有文档回答问题"}
]
# 示例模板
example_prompt = PromptTemplate(
input_variables=["input", "output"],
template="问题:{input}\n回答:{output}"
)
# 少样本模板
few_shot_prompt = FewShotPromptTemplate(
examples=examples,
example_prompt=example_prompt,
suffix="问题:{question}\n回答:",
input_variables=["question"]
)
print(few_shot_prompt.format(question="Chain链是什么?"))
三、Part2:Chain 链精讲(2 小时)
1. Chain 的本质
把多个 LangChain 组件(模型、提示词、工具)按顺序组合,实现自动化执行流程,不用分步手动调用。
2. 五大高频链详解(附代码)
(1)LLMChain:基础问答链(入门必学)
- 作用:绑定提示词模板 + 大模型,处理单次独立任务
python
运行
from langchain_openai import OpenAI
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
# 初始化模型
llm = OpenAI(temperature=0.2)
# 定义模板
template = "请用一句话解释:{concept}"
prompt = PromptTemplate(input_variables=["concept"], template=template)
# 组装链
llm_chain = LLMChain(llm=llm, prompt=prompt)
# 执行链
result = llm_chain.run(concept="向量数据库")
print(result)
(2)SimpleSequentialChain:简易顺序链(单入单出)
- 作用:上一步结果直接作为下一步输入,适合简单两步流程
python
运行
from langchain.chains import SimpleSequentialChain, LLMChain
# 第一步:解释名词
chain1 = LLMChain(
llm=llm,
prompt=PromptTemplate(input_variables=["topic"], template="详细解释:{topic}")
)
# 第二步:精简成一句话
chain2 = LLMChain(
llm=llm,
prompt=PromptTemplate(input_variables=["content"], template="精简成一句话:{content}")
)
# 组装顺序链
total_chain = SimpleSequentialChain(chains=[chain1, chain2])
# 执行
result = total_chain.run("大模型RAG")
print(result)
(3)SequentialChain:标准顺序链(多入多出)
- 作用:支持多输入、多输出,适合复杂多步骤业务
python
运行
from langchain.chains import SequentialChain
# 链1:生成原理
chain1 = LLMChain(
llm=llm,
prompt=PromptTemplate(input_variables=["tech"], template="简述{tech}工作原理"),
output_key="principle"
)
# 链2:生成优缺点
chain2 = LLMChain(
llm=llm,
prompt=PromptTemplate(input_variables=["tech"], template="写出{tech}的优缺点"),
output_key="advantage"
)
# 组装多入多出链
all_chain = SequentialChain(
chains=[chain1, chain2],
input_variables=["tech"],
output_variables=["principle", "advantage"]
)
# 执行
res = all_chain.invoke({"tech": "Agent智能体"})
print("原理:", res["principle"])
print("优缺点:", res["advantage"])
(4)RetrievalQA:检索问答链(RAG 专用)
- 作用:自动完成文档检索→上下文拼接→问答生成,用于知识库问答
python
运行
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
from langchain.chains import RetrievalQA
# 假设已有向量库(简化示例)
vectorstore = FAISS.from_texts(["LangChain是大模型应用开发框架"], embedding=OpenAIEmbeddings())
retriever = vectorstore.as_retriever()
# 组装检索问答链
qa_chain = RetrievalQA.from_chain_type(
llm=llm,
chain_type="stuff",
retriever=retriever
)
# 提问
result = qa_chain.run("LangChain是什么?")
print(result)
(5)ConversationChain:对话记忆链
- 作用:搭配记忆组件,实现多轮连贯对话
python
运行
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory
# 初始化记忆
memory = ConversationBufferMemory()
# 对话链
conv_chain = ConversationChain(llm=llm, memory=memory)
# 多轮对话
print(conv_chain.predict(input="我在学习LangChain"))
print(conv_chain.predict(input="帮我总结它的链功能"))
四、Part3:核心参数与易错点(30 分钟)
1. 关键参数区分
表格
| 参数 | 作用 |
|---|---|
input_variables |
提示词模板的输入变量,需与后续传参名一致 |
chains |
顺序链中存放子链的数组 |
output_key |
单条子链的输出标识 |
output_variables |
SequentialChain 的整体输出字段集合 |
run()/invoke() |
链的执行方法,功能等效,新版推荐invoke |
2. 易错点提醒
ConversationChain必须手动传入memory,不会自带记忆SimpleSequentialChain仅支持单入单出,无法传递多个独立变量- 提示词模板变量名必须和传参名完全一致,否则报错
五、课后作业(30 分钟)
- 用
PromptTemplate写一个 "给前端工程师解释技术名词" 的模板,并调用LLMChain执行 - 用
SimpleSequentialChain实现 "翻译英文句子→总结成一句话" 的流程 - 用
SequentialChain实现 "输入一个技术名词,同时输出它的原理和应用场景" - 简答题:区分
PromptTemplate和ChatPromptTemplate的使用场景一、课后作业手把手拆解(带可运行代码)
作业 1:用 PromptTemplate + LLMChain 写 "给前端工程师解释技术名词"
目标:做一个固定格式的 "前端友好型技术解释器"
python
运行
from langchain_openai import OpenAI
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
# 1. 初始化模型
llm = OpenAI(temperature=0.3) # temperature控制回答的"创造性",0.3更严谨
# 2. 定义提示词模板
template = """
你是一个懂前端的大模型讲师,用前端工程师听得懂的大白话,解释下面这个技术名词:
{tech_term}
要求:
1. 类比前端概念(比如组件、API、状态管理)
2. 不超过200字
3. 举一个简单的使用场景
"""
prompt = PromptTemplate(
input_variables=["tech_term"], # 变量名,和模板里的占位符必须一致
template=template
)
# 3. 组装成LLMChain
explain_chain = LLMChain(llm=llm, prompt=prompt)
# 4. 执行调用
result = explain_chain.run(tech_term="向量数据库")
print(result)
作业 2:用 SimpleSequentialChain 实现 "翻译英文句子 → 总结一句话"
目标:感受单入单出的串行流程,上一步结果直接传给下一步
python
运行
from langchain.chains import SimpleSequentialChain, LLMChain
from langchain.prompts import PromptTemplate
# 1. 第一步链:翻译英文句子
translate_chain = LLMChain(
llm=llm,
prompt=PromptTemplate(
input_variables=["sentence"],
template="请把下面的英文句子翻译成中文:{sentence}"
)
)
# 2. 第二步链:把翻译结果总结成一句话
summary_chain = LLMChain(
llm=llm,
prompt=PromptTemplate(
input_variables=["content"],
template="请把下面的内容用一句话总结:{content}"
)
)
# 3. 组装成简易顺序链
total_chain = SimpleSequentialChain(
chains=[translate_chain, summary_chain],
verbose=True # 加这个参数可以看到每一步的执行过程,方便调试
)
# 4. 执行
english_sentence = "LangChain is a framework for developing applications powered by language models."
result = total_chain.run(english_sentence)
print("最终结果:", result)
作业 3:用 SequentialChain 实现 "输入技术名词,同时输出原理 + 应用场景"
目标:掌握多入多出的复杂流程,理解 output_key 和 output_variables
python
运行
from langchain.chains import SequentialChain, LLMChain
# 链1:生成技术原理
principle_chain = LLMChain(
llm=llm,
prompt=PromptTemplate(
input_variables=["tech"],
template="用3句话讲清楚{tech}的工作原理"
),
output_key="principle" # 标记这条链的输出字段名
)
# 链2:生成应用场景
scenario_chain = LLMChain(
llm=llm,
prompt=PromptTemplate(
input_variables=["tech"],
template="列出{tech}的3个实际应用场景"
),
output_key="scenario"
)
# 组装成多入多出顺序链
all_chain = SequentialChain(
chains=[principle_chain, scenario_chain],
input_variables=["tech"], # 声明整体输入变量
output_variables=["principle", "scenario"] # 声明整体要输出的字段
)
# 执行(必须用invoke,传入字典格式)
result = all_chain.invoke({"tech": "RAG"})
print("原理:", result["principle"])
print("应用场景:", result["scenario"])
作业 4:简答题(背诵版标准答案)
题目:区分 PromptTemplate 和 ChatPromptTemplate 的使用场景
6. PromptTemplate :用于单轮独立任务,无角色概念,适合固定格式的文本生成、知识点解释等场景,比如 "给前端解释技术名词"。
7. ChatPromptTemplate :用于多轮对话场景 ,支持划分system/human/ai角色,能设定系统规则、拼接历史对话上下文,适合聊天机器人、智能客服等交互类应用。