LangChain:模型I/O之提示词模板

LangChain 的提示词模板(Prompt Templates)是一组预定义或可自定义的模板,用于动态生成提示词(Prompts),帮助开发者更高效地与语言模型交互。

官网:LangChain #prompts

什么是提示词

提示词:是用户输入给AI模型的文本指令或引导信息,用于激发模型生成特定内容。它可以是问题、指令、示例或一段不完整的文本,模型基于此理解任务目标并生成响应。

提示词是用户与AI模型之间的“沟通桥梁”,其设计需结合具体任务、模型能力和用户需求。通过精细调整提示词,可以显著提升模型输出的相关性、准确性和创造性。随着提示工程(Prompt Engineering)的发展,提示词设计正成为AI应用中的关键技能。

提示词模板

基础提示词模板

PromptTemplate:基础提示模板

用途:根据变量动态生成提示词。
示例:生成包含用户输入变量的提示。

1
2
3
4
5
6
7
8
9
10
11
12
13
from langchain.prompts import PromptTemplate

# 定义模板
template = "请写一篇关于{theme}的简短文章。"
prompt = PromptTemplate(
input_variables=["theme"], # 定义变量
template=template,
)

# 使用模板生成提示词
formatted_prompt = prompt.format(theme="气候变化")
print(formatted_prompt)
# 输出:请写一篇关于气候变化的简短文章。

小样本提示词模板

FewShotPromptTemplate:小样本提示模板

用途:通过示例指导模型生成符合要求的回答。
示例:提供翻译示例,引导模型完成翻译任务。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from langchain.prompts import FewShotPromptTemplate, PromptTemplate

# 定义示例
examples = [
{"input": "Hello", "output": "你好"},
{"input": "Goodbye", "output": "再见"},
]

# 定义单个示例的格式
example_template = """
输入:{input}
输出:{output}
"""
example_prompt = PromptTemplate(
input_variables=["input", "output"],
template=example_template,
)

# 组合成小样本模板
few_shot_prompt = FewShotPromptTemplate(
examples=examples,
example_prompt=example_prompt,
prefix="将以下英文翻译成中文:",
suffix="输入:{input}\n输出:",
input_variables=["input"],
)

# 使用模板
formatted_prompt = few_shot_prompt.format(input="Thank you")
print(formatted_prompt)
# 输出:
# 将以下英文翻译成中文:
#
# 输入:Hello
# 输出:你好
#
# 输入:Goodbye
# 输出:再见
#
# 输入:Thank you
# 输出:

聊天提示词模板

ChatPromptTemplate:聊天提示模板

用途:为聊天模型(如 GPT-3.5/4)生成多角色对话格式的提示。
示例:模拟系统、用户和 AI 的对话。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from langchain.prompts import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
)

# 定义系统消息模板
system_template = "你是一个擅长{subject}的助手。"
system_prompt = SystemMessagePromptTemplate.from_template(system_template)

# 定义用户消息模板
human_template = "请解释什么是{concept}。"
human_prompt = HumanMessagePromptTemplate.from_template(human_template)

# 组合聊天模板
chat_prompt = ChatPromptTemplate.from_messages([system_prompt, human_prompt])

# 生成最终提示
formatted_prompt = chat_prompt.format_prompt(
subject="机器学习",
concept="神经网络"
).to_messages()

print(formatted_prompt)
# 输出:
# [
# SystemMessage(content='你是一个擅长机器学习的助手。'),
# HumanMessage(content='请解释什么是神经网络。')
# ]

自定义组合提示词模板

用途:通过管道(Pipeline)或自定义函数组合多个模板。
示例:将多个步骤合并为一个复杂提示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from langchain.prompts import PipelinePromptTemplate

# 定义基础模板
base_template = """{introduction}

{example}

{question}"""
base_prompt = PromptTemplate.from_template(base_template)

# 定义子模板
introduction_template = "你是一个{role}。"
introduction_prompt = PromptTemplate.from_template(introduction_template)

example_template = "示例:{example}"
example_prompt = PromptTemplate.from_template(example_template)

question_template = "问题:{question}"
question_prompt = PromptTemplate.from_template(question_template)

# 组合管道模板
pipeline_prompt = PipelinePromptTemplate(
final_prompt=base_prompt,
pipeline_prompts=[
("introduction", introduction_prompt),
("example", example_prompt),
("question", question_prompt),
],
)

# 使用模板
formatted_prompt = pipeline_prompt.format(
role="翻译官",
example="Hello -> 你好",
question="How are you?"
)

print(formatted_prompt)
# 输出:
# 你是一个翻译官。
#
# 示例:Hello -> 你好
#
# 问题:How are you?

**注意:**PipelinePromptTemplate 已弃用,在 langchain-core==1.0 之前不会移除。

Partial提示词模板

参考:partial-with-functions

在实际业务开过程中,提示词模板的变量可能是分在不同步骤才能获得。使用Partial提示词模板可以帮助逐步构建最终的提示词是模板。

LangChaim 提供 2 种方式支持部分提示词模板。

  1. 使用字符串值进行部分格式化。
  2. 使用函数返回的字符串值进行部分格式化。

在下面的两个示例介绍 2 种方式的动机以及如何在LangChain中实现。

部分字符串填充

想要对提示模板进行部分应用的一个常见场景是:如果您在链中提前获取了部分变量值,而其他变量稍后才可用。

例如,假设您有一个需要两个变量 foobaz 的提示模板。如果在链的早期阶段就获取了 foo 的值,但 baz 的值稍后才能获得,那么在整个链中传递这两个变量可能会非常不便。

此时,可以用 foo 的值对提示模板进行部分应用(partial),然后传递这个已部分应用的模板并直接使用它。以下是一个具体示例:

1
2
3
4
5
6
7
8
from langchain.prompts import PromptTemplate

prompt = PromptTemplate(template="{foo}{bar}", input_variables=["foo", "bar"])
partial_prompt = prompt.partial(foo="foo")

final_template = partial_prompt.format(bar="baz")

print(final_template) # 输出foobaz

还可以在初始化时就使用部分变量初始化提示词模板

1
2
3
4
prompt = PromptTemplate(
template="{foo}{bar}", input_variables=["bar"], partial_variables={"foo": "foo"}
)
print(prompt.format(bar="baz"))

函数返回值填充

另一种常见用法是将函数与部分应用(partial)结合使用。这种场景适用于您有一个变量,且您希望始终通过统一的方式动态获取其值。

一个典型案例是日期或时间的处理。假设您有一个提示模板,需要始终包含当前日期。您既无法在模板中硬编码日期值,也不便每次都将其与其他输入变量一起传递。在这种情况下,使用一个始终返回当前日期的函数来部分应用这个提示模板就会非常便捷。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from datetime import datetime

from langchain_core.prompts import PromptTemplate

def _get_datetime():
now = datetime.now()
return now.strftime("%m/%d/%Y, %H:%M:%S")

prompt = PromptTemplate(
template="Tell me a {adjective} joke about the day {date}",
input_variables=["adjective", "date"],
)
partial_prompt = prompt.partial(date=_get_datetime)
final_prompt = partial_prompt.format(adjective="funny")
print(final_prompt)

# 输出结果:Tell me a funny joke about the day 04/21/2024, 19:43:57

也可以直接使用部分应用变量来初始化提示模板,这种做法在当前工作流程中通常更为合理。

1
2
3
4
5
6
prompt = PromptTemplate(
template="Tell me a {adjective} joke about the day {date}",
input_variables=["adjective"],
partial_variables={"date": _get_datetime},
)
print(prompt.format(adjective="funny"))

外部文件提示词模板

LangChain 支持加载 JSON 和 YAML 格式的提示词模板,用于序列化和反序列化提示词信息。

可以将提示词模板保存到 JSON或YAML文件中,就可对提示词模板进行共享、存储、版本管理。

load_prompt

1
2
3
4
5
6
7
8
from langchain_core.prompts import load_prompt

prompt = load_prompt("prompt.json", encoding="utf-8")

final_prompt = prompt.format(adjective="funny")

print(final_prompt)

prompt.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
"_type": "few_shot",
"input_variables": [
"adjective"
],
"prefix": "Write antonyms for the following words.",
"example_prompt": {
"_type": "prompt",
"input_variables": [
"input",
"output"
],
"template": "Input: {input}\nOutput: {output}"
},
"examples": "examples.json",
"suffix": "Input: {adjective}\nOutput:"
}

examples.json

1
2
3
4
5
6
7
8
9
10
[
{
"input": "happy",
"output": "sad"
},
{
"input": "tall",
"output": "short"
}
]

输出结果

1
2
3
4
5
6
7
8
9
10
Write antonyms for the following words.

Input: happy
Output: sad

Input: tall
Output: short

Input: funny
Output:

总结

  • PromptTemplate:基础变量替换。
  • FewShotPromptTemplate:通过示例指导模型行为。
  • ChatPromptTemplate:生成多角色对话提示。
  • 自定义模板:灵活组合复杂逻辑。

实际使用时,可根据需求选择模板类型,并通过 input_variablesformat() 方法动态替换内容。对于高级场景,还可结合 ExampleSelector 动态选择示例,或通过自定义函数生成提示。

作者

光星

发布于

2025-04-10

更新于

2025-05-24

许可协议

评论