4、提示词工程:PromptTemplate基础、FewShotPromptTemplate、ChatPromptTemplate、提示词最佳实践
好,咱们进入提示词工程这个环节。说实话,这是LangChain里最基础也最容易被低估的部分。很多人觉得提示词嘛,不就是写个字符串丢给模型?其实没那么简单。我在项目中踩过不少坑,今天把这些经验掰开揉碎了讲给你听。
4.1 PromptTemplate基础:从硬编码到模板化
先聊聊最基础的PromptTemplate。它的作用很简单——把变量塞进固定的提示词模板里。你想想看,如果每次调用都要手写完整的提示词,那代码得多冗余?
from langchain.prompts import PromptTemplate
# 定义一个模板
template = "请用{style}的风格,写一段关于{topic}的简介,字数控制在{word_limit}以内。"
prompt = PromptTemplate(
input_variables=["style", "topic", "word_limit"],
template=template
)
# 填充变量
formatted_prompt = prompt.format(
style="幽默风趣",
topic="Python异步编程",
word_limit="200"
)
print(formatted_prompt)
# 输出:请用幽默风趣的风格,写一段关于Python异步编程的简介,字数控制在200以内。
我个人习惯把模板单独抽出来放在配置文件里。为什么?因为业务方经常改提示词,你总不想为了改一句话重新部署代码吧?
4.2 FewShotPromptTemplate:给模型打个样
接下来是FewShotPromptTemplate。说白了,就是给模型提供几个示例,让它照着你的路子走。我在做客服意图识别时用过这个,效果比单纯写指令好得多。
from langchain.prompts import FewShotPromptTemplate, PromptTemplate
# 示例数据
examples = [
{"input": "我想退货", "intent": "退货申请"},
{"input": "什么时候发货", "intent": "物流查询"},
{"input": "你们产品有质量问题", "intent": "投诉建议"},
]
# 示例模板
example_prompt = PromptTemplate(
input_variables=["input", "intent"],
template="用户说:{input}\n意图:{intent}"
)
# 构建FewShot提示词
few_shot_prompt = FewShotPromptTemplate(
examples=examples,
example_prompt=example_prompt,
prefix="请根据以下示例,识别用户意图:",
suffix="用户说:{user_input}\n意图:",
input_variables=["user_input"],
example_separator="\n\n"
)
# 使用
result = few_shot_prompt.format(user_input="能帮我查下快递吗")
print(result)
嗯,这里要注意一个细节:示例的数量不是越多越好。我试过给10个示例,结果模型反而被带偏了。一般来说,3-5个高质量的示例就够了。你想想看,给模型喂一堆垃圾示例,还不如不给。
4.3 ChatPromptTemplate:对话场景的利器
如果你做的是聊天机器人,那ChatPromptTemplate就是你的主力。它支持System、Human、AI三种消息角色,能更精细地控制对话流程。
from langchain.prompts import ChatPromptTemplate, HumanMessagePromptTemplate, SystemMessagePromptTemplate
# 构建聊天模板
chat_template = ChatPromptTemplate.from_messages([
SystemMessagePromptTemplate.from_template(
"你是一个{role},请用{style}的语气回答问题。"
),
HumanMessagePromptTemplate.from_template("{user_input}"),
])
# 填充变量
messages = chat_template.format_messages(
role="资深Python导师",
style="耐心细致",
user_input="什么是装饰器?"
)
# 输出消息列表
for msg in messages:
print(f"{msg.type}: {msg.content}")
我个人特别喜欢from_messages这个设计。它把对话结构清晰地表达出来,比手动拼接字符串优雅多了。而且,你可以在System消息里塞各种约束条件——比如「不要回答政治问题」、「每次回答控制在3句话以内」。
| 消息类型 | 作用 | 使用场景 |
|---|---|---|
| SystemMessage | 设定模型角色和行为 | 角色扮演、行为约束 |
| HumanMessage | 模拟用户输入 | 用户提问、指令 |
| AIMessage | 模拟模型回复 | 多轮对话历史 |
4.4 提示词最佳实践:血泪教训总结
这部分是我最想跟你分享的。做了这么多项目,有些坑真的是拿加班换来的。
4.4.1 明确指令,别让模型猜
很多新手喜欢写「帮我分析一下这段代码」,然后模型就开始自由发挥了。你应该说:「请分析以下Python代码的时间复杂度,并给出优化建议,用中文回答。」越具体,结果越可控。
4.4.2 控制输出格式
我在做数据提取时,经常要求模型输出JSON格式。但模型有时候会加一些额外说明文字,导致解析失败。后来我学乖了,在提示词里明确写:「只输出JSON,不要任何其他文字。」
template = """
从以下文本中提取信息,输出JSON格式:
文本:{text}
要求:
- 只输出JSON,不要任何其他文字
- JSON字段:name, age, occupation
"""
4.4.3 分步思考(Chain-of-Thought)
对于复杂推理任务,让模型一步步思考效果更好。你可以加一句「请逐步推理,最后给出结论」。这招在数学题、逻辑推理场景特别管用。
4.4.4 负面示例也很重要
除了告诉模型「要做什么」,有时候还得告诉它「不要做什么」。比如:「不要使用专业术语,用小学生都能听懂的话解释。」或者:「如果不知道答案,直接说不知道,不要编造。」
4.5 实战:组合使用
最后,咱们看看怎么把这些东西组合起来。假设你要做一个代码审查助手:
from langchain.prompts import ChatPromptTemplate, FewShotPromptTemplate, PromptTemplate
# 1. 定义示例
examples = [
{"code": "x = 1 + 2", "review": "代码简洁,但建议使用有意义的变量名"},
{"code": "for i in range(len(lst)): print(lst[i])", "review": "建议直接遍历列表:for item in lst: print(item)"},
]
# 2. 示例模板
example_prompt = PromptTemplate(
input_variables=["code", "review"],
template="代码:{code}\n审查意见:{review}"
)
# 3. FewShot模板
few_shot = FewShotPromptTemplate(
examples=examples,
example_prompt=example_prompt,
prefix="你是一个资深代码审查员,请审查以下代码:",
suffix="代码:{code}\n审查意见:",
input_variables=["code"]
)
# 4. 嵌入Chat模板
chat_template = ChatPromptTemplate.from_messages([
SystemMessagePromptTemplate.from_template("你是一个资深Python代码审查员,请用中文回答。"),
HumanMessagePromptTemplate.from_template(few_shot.template),
])
# 使用
messages = chat_template.format_messages(code="a = [1,2,3]; print(a[3])")
print(messages[1].content)
你看,这样组合起来,既有示例引导,又有角色设定,效果比单一模板好得多。我在团队里推广这种模式后,代码审查的准确率提升了至少30%。
好了,提示词工程这块就聊到这儿。记住,提示词不是写一次就完事的,它需要不断迭代优化。下次咱们聊聊更高级的玩法——如何用LangChain的PipelinePromptTemplate做多步骤提示词编排。