Files
ai-agent-course/02.LangChain核心组件/02.Prompt模板.md
T
aaronxu 4fb9532f5c 重构 AI 智能体课程:Markdown 化,新增 ReAct 模块与案例
- 按 Python 课件的章节式结构重组为 9 个部分、24 章
- 新增 ReAct 模块:原理与手写实现、LangGraph 实现、create_agent、5 个案例
- 补齐 RAG、LangGraph 工作流、多智能体、任务调度
- 新增 3 个项目实战与部署评估章节
- 统一 '学习目标 / 概念 / 代码 / 小结 / 练习' 结构
2026-10-28 05:08:00 +08:00

253 lines
7.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Prompt 模板
> **本章目标**:把提示词从「字符串拼接」升级为「可复用、可测试、可维护的模板」。
> **前置知识**:第 2.1 章。
> **预计用时**:70 分钟。
## 1. 为什么需要模板
先看一段真实项目里最常见的写法:
```python
prompt = "你是" + role + ",请用" + style + "的语气回答:" + question
```
问题:
- 少一个空格、多一个换行,模型表现就变了;
- 提示词里混着业务变量,改一句话要动代码;
- 同一个提示词在三个文件里复制粘贴,最后版本不一致;
- 无法复用「few-shot 示例」这种结构。
模板要解决的就是:**把「固定的提示词结构」和「变化的变量」分开**。
## 2. PromptTemplate:纯文本模板
适合不需要区分角色的场景(补全类任务、简单抽取)。
```python
# %%
from langchain_core.prompts import PromptTemplate
prompt = PromptTemplate.from_template(
"请用一句话解释「{concept}」,面向{audience}。"
)
# 查看模板变量
print(prompt.input_variables) # ['audience', 'concept']
# 填充
text = prompt.format(concept="向量数据库", audience="大一学生")
print(text)
```
注意 `from_template` 用 `{}` 做占位符。如果提示词里本身要出现花括号(比如 JSON 示例),必须转义成 `{{` 和 `}}`:
```python
prompt = PromptTemplate.from_template(
'输出 JSON:{{"name": "...", "age": 0}}\n用户:{text}'
)
print(prompt.format(text="张三,20 岁"))
```
这是新手最常踩的坑:**JSON 示例忘了双花括号,直接报 `KeyError`**。
## 3. ChatPromptTemplate:聊天消息模板
实际项目 95% 用这个,因为它能区分 system / human / ai。
```python
# %%
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
("system", "你是一名{role},回答风格:{style}。"),
("human", "{question}"),
])
messages = prompt.format_messages(
role="Python 讲师",
style="简洁、给例子",
question="什么是装饰器?",
)
for m in messages:
print(type(m).__name__, "|", m.content)
```
输出:
```text
SystemMessage | 你是一名Python 讲师,回答风格:简洁、给例子。
HumanMessage | 什么是装饰器?
```
`format_messages` 返回的是消息对象,可以直接喂给 `llm.invoke()`,也可以直接塞进链里。
## 4. 三个高频技巧
### 4.1 默认值与 partial
有些变量几乎不变,可以提前「锁死」:
```python
# %%
base = ChatPromptTemplate.from_messages([
("system", "你是{company}的客服,语气{ tone }。"),
("human", "{question}"),
])
# 固定 company,留下 tone 和 question
cs_prompt = base.partial(company="星辰科技")
print(cs_prompt.format(tone="耐心", question="发票怎么开?"))
```
`partial` 的意义:一个基础模板,可以派生出多个业务模板,不用复制。
### 4.2 MessagesPlaceholder:插入历史对话
做多轮对话时,历史消息是「一整个列表」,不是单个变量:
```python
# %%
from langchain_core.prompts import MessagesPlaceholder
prompt = ChatPromptTemplate.from_messages([
("system", "你是一个简洁的助手。"),
MessagesPlaceholder("history"), # 历史消息列表插在这里
("human", "{question}"),
])
history = [
("human", "我叫小明"),
("ai", "你好小明"),
]
msgs = prompt.format_messages(history=history, question="我叫什么?")
for m in msgs:
print(type(m).__name__, "|", m.content)
```
`MessagesPlaceholder` 是后面做「对话代理」「记忆」的基础。
### 4.3 Few-shot:用例子教格式
模型对「例子」的敏感度远高于「描述」。想让它稳定输出某种格式,给 2~3 个例子最有效:
```python
# %%
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate
examples = [
{"text": "这个手机太卡了,还老死机", "label": "性能问题"},
{"text": "快递三天了还没到", "label": "物流问题"},
{"text": "客服态度特别好,点赞", "label": "服务表扬"},
]
example_prompt = PromptTemplate.from_template(
"评论:{text}\n分类:{label}"
)
few_shot = FewShotPromptTemplate(
examples=examples,
example_prompt=example_prompt,
prefix="把用户评论分类到:性能问题 / 物流问题 / 服务表扬 / 其他。",
suffix="评论:{input}\n分类:",
input_variables=["input"],
)
print(few_shot.format(input="屏幕摔坏了能保修吗"))
```
更简单的等价写法是直接把例子写进 `ChatPromptTemplate` 的 human/ai 消息里,效果一样,可读性更好:
```python
prompt = ChatPromptTemplate.from_messages([
("system", "把评论分类到:性能问题/物流问题/服务表扬/其他,只输出类别。"),
("human", "这个手机太卡了,还老死机"),
("ai", "性能问题"),
("human", "快递三天了还没到"),
("ai", "物流问题"),
("human", "{input}"),
])
```
## 5. 把「输出格式」写进提示词
第 2.3 章会讲解析器,但解析器能不能成功,首先取决于提示词有没有把格式说清楚。
```python
# %%
from pydantic import BaseModel, Field
from langchain_core.output_parsers import PydanticOutputParser
class JobInfo(BaseModel):
title: str = Field(description="职位名称")
city: str = Field(description="工作城市")
salary: str = Field(description="薪资范围,如 15k-25k")
skills: list[str] = Field(description="要求的技术栈")
parser = PydanticOutputParser(pydantic_object=JobInfo)
prompt = ChatPromptTemplate.from_messages([
("system", "你是招聘信息抽取助手。\n{format_instructions}"),
("human", "{jd}"),
]).partial(format_instructions=parser.get_format_instructions())
print(prompt.format(jd="招 Python 后端,杭州,15k-25k,要求熟悉 FastAPI、MySQL"))
```
`get_format_instructions()` 会自动生成一段「请输出符合以下 JSON Schema 的内容」,比手写格式说明更可靠。
## 6. 提示词设计的五个要素
一个能稳定工作的提示词,通常包含:
| 要素 | 作用 | 例子 |
| --- | --- | --- |
| 角色 | 限定知识范围与语气 | 「你是一名有 10 年经验的运维工程师」 |
| 任务 | 明确要做什么 | 「判断这段日志的故障等级」 |
| 约束 | 排除不想要的行为 | 「不要编造未出现的信息」 |
| 示例 | 教格式和边界 | 2~3 条输入输出 |
| 输出格式 | 让程序能解析 | 「只输出 JSON,不要解释」 |
反例(几乎一定不稳定):
```text
帮我分析一下这个日志
```
正例:
```text
你是运维工程师。根据日志判断故障等级(P0/P1/P2/P3),并给出最可能的原因。
只输出 JSON:{"level": "...", "reason": "..."}
日志:{log}
```
## 7. 常见错误
| 现象 | 原因 | 解决 |
| --- | --- | --- |
| `KeyError: '\n "name"'` | JSON 示例没转义 | 用 `{{ }}` |
| 变量没被替换 | 用了单花括号但没在 `input_variables` 里 | 检查 `prompt.input_variables` |
| 模型忽略格式要求 | 格式说明放在中间 | 放到 system 末尾或最后一条 human |
| 输出带「好的,以下是」 | 没禁止客套话 | 明确「只输出…,不要任何解释」 |
| 同一个模板表现忽好忽坏 | temperature 太高 | 结构化任务设 0~0.2 |
## 8. 本章小结
- `PromptTemplate` 管纯文本,`ChatPromptTemplate` 管角色消息;
- `partial` 锁定常量,`MessagesPlaceholder` 插入历史,Few-shot 教格式;
- JSON 示例必须双花括号转义;
- 格式约束要写进提示词,解析器才有把握;
- 好提示词 = 角色 + 任务 + 约束 + 示例 + 输出格式。
## 9. 练习
1. 写一个「简历筛选」模板,输入 JD 和简历,输出匹配度(0-100)与三条理由;
2. 用 `partial` 做一个「公司客服」基础模板,再派生「售前」「售后」两个版本;
3. 用 `MessagesPlaceholder` 实现一个带 3 轮历史的问答模板;
4. 故意在 JSON 示例里用单花括号,观察报错信息,再修好。