Prompt

Prompt Template(提示词模版)是 LangChain 中的一个概念,接收用户输入,返回一个传递给 LLM 的信息(即提示
词 prompt),通过模板管理大模型的输入。

提示词策略差异

  • 通用模型
    • 需要显式引导推理步骤,比如通过CoT提示,否则可能会忽略关键逻辑
    • 依赖提示词补偿能力短板,比如要求分步骤思考,提供few-shot参考示例等
  • 推理模型
    • 提示语更简洁,只需要明确任务目标和需求,因为模型已经内化了推理逻辑
    • 无需逐步指导,模型会自动生成结构化推理过程。如果强行分步骤拆解,反而会降低其推理能力

提示词关键原则

  • 模型选择
    • 根据任务类型选择,而非模型热度
    • 例如:创意类任务选择通用模型,数学、物理、编程等理科推理类任务选择推理模型
  • 提示词设计
    • 通用模型:结构化、补偿性引导 → 缺什么,补什么
    • 推理模型:简洁指令、聚焦目标、信任其内化能力 → 要什么,直接说
  • 避免误区
    • 不要对通用模型过度信任,如直接问复杂推理问题,需要分步骤进行
    • 不要对推理模型进行启发式(简单)提问,推理模型会给你过于复杂的深度结果
    • 对于复杂问题,推理模型依然会有错误的可能,或存在忽略某些细节的可能,这时需要多次交互

提示词编写原则

  • 具体指导:给予模型明确的指导和约束
  • 简介明了:使用简练、清晰的语言表达
  • 适当引导:通过示例或问题边界引导模型
  • 迭代优化:根据输出结果,持续调整和优化

Prompt 编写框架(重要性排序)

Prompt 组成

  1. 任务(Task):始终以动词开始任务句子(如“生成”、“给予”、“写作”等),明确表达你的最终目标,可以有多个。
  2. 上下文(Context):提供上下文背景、所处环境等。
  3. 示例(Exemplars):提供具体的例子,用于提高输出质量。如果没有示例,也可以让模型帮忙生成。
  4. 角色(Persona):你希望AI扮演的角色,可以是具体的人,也可以是虚构的角色。
  5. 格式(Format):你希望输出的格式,如表格、列表、段落等。
  6. 语气(Tone):指定输出的语气,如正式、非正式、幽默等。

重要性排序

任务 > 上下文 > 示例 > 角色 > 格式 > 语气

  • 如果模型回答不满意,可按照这个顺序依次检查并调整你的 Prompt 内容。
  • 写 prompt 是一个不断尝试和调整的过程。

Prompt 编写技巧

在了解 Prompt 编写原则的基础上,还有一些实用的编写技巧:

  1. 限制模型输出的格式
    明确指定输出的格式(如 JSON、表格、列表等),让结果更结构化、更易使用。

  2. 使用分隔符区分输入的不同部分
    ---###""" 等符号分隔任务指令、上下文、输入文本等模块,避免模型混淆。

  3. 提供样例
    给出 1-2 个输入输出的示例,让模型快速理解你的期望,尤其适合少样本学习场景。

  4. CoT 思维工具
    加入“请分步骤思考”、“先分析原因再给出结论”等引导词,让模型显式地展示推理过程,提升复杂任务的准确性。

  5. 面向不同的角色进行讲解
    让模型代入特定角色(如“作为资深产品经理”、“作为小学老师”),输出的内容会更贴合该角色的视角和专业度。


在应用开发中,固定的提示词限制了模型的灵活性和适用范围。所以,prompt template 是一个 模板化的字符串,你可以将 变量插入到模板 中,从而创建出不同的提示。调用时:

  • 字典 作为输入,其中每个键代表要填充的提示模板中的变量。
  • 输出一个 PromptValue。这个 PromptValue 可以传递给 LLMChatModel,并且还可以转换为字符串或消息列表。

有几种不同类型的提示模板

  • PromptTemplate:LLM 提示模板,用于生成字符串提示。它使用 Python 的字符串来模板提示。
  • ChatPromptTemplate:聊天提示模板,用于组合各种角色的消息模板,传入聊天模型。
  • XxxMessagePromptTemplate:消息模板词模板,包括:SystemMessagePromptTemplateHumanMessagePromptTemplateAIMessagePromptTemplateChatMessagePromptTemplate
  • FewShotPromptTemplate:样本提示词模板,通过示例来教模型如何回答
  • PipelinePrompt:管道提示词模板,用于把几个提示词组合在一起使用。
  • 自定义模板:允许基于其它模板类来定制自己的提示词模板。

PromptTemplate

PromptTemplate类,用于快速构建 包含变量 的提示词模板,并通过 传入不同的参数值 生成自定义的提示词。

主要参数介绍

  • template:定义提示词模板的字符串,其中包含 文本变量占位符(如{name});
  • input_variables:列表,指定了模板中使用的变量名称,在调用模板时被替换;
  • partial_variables:字典,用于定义模板中一些固定的变量名。这些值不需要再每次调用时被替换。

函数介绍

  • format():给input_variables变量赋值,并返回提示词。利用format()进行格式化时就一定要赋值,否则会报错。当在template中未设置input_variables,则会自动忽略。

PromptTemplate 如何获取实例

  1. 方式一:使用构造方法的方式
from langchain_core.prompts import PromptTemplate

prompt_template = PromptTemplate(
    template="你是一个{role}, 你的名字叫{name}",
    input_variables=["role", "name"]
)
  1. 方式二:from_template(),推荐
prompt_template = PromptTemplate.from_template("你是一个{role}, 你的名字叫{name}")

两种特殊结构的使用(部分提示词模版、组合提示词模版)

  1. 部分提示词模版

方法 1:使用 partial_variables 参数,可以做一些变量的初始化

from langchain_core.prompts import PromptTemplate

prompt_template = PromptTemplate.from_template(
    template="你是一个{role}, 你的名字叫{name}",
    partial_variables={
        "role": "前端专家"
    }
)

prompt = prompt_template.format(name="wifi歪f")
print(prompt) # 你是一个前端专家, 你的名字叫wifi歪f

方法 2:使用模版的partial()方法,会返回一个新的模版

from langchain_core.prompts import PromptTemplate

prompt_template = PromptTemplate(
    template="你是一个{role}, 你的名字叫{name}",
    input_variables=["role", "name"]
)

# partial会返回一个新的模版
new_template = prompt_template.partial(role="前端专家", name="wifi歪f")

prompt = new_template.format()
print(prompt)
  1. 组合提示词模版(了解)

就是字符串操作 😂

from langchain_core.prompts import PromptTemplate
template = (
    PromptTemplate.from_template("Tell me a joke about {topic}")
    + ", make it funny"
    + "\n\nand in {language}"
)
prompt = template.format(topic="sports", language="spanish")
print(prompt)

给提示词模版中的变量赋值 format()、invoke()

  • format():参数部分:给变量赋值;返回值:str 类型
  • invoke():参数部分:给变量赋值,使用的是字典形式;返回值:PromptValue 类型
  1. format()
from langchain_core.prompts import PromptTemplate

prompt_template = PromptTemplate(
    template="你是一个{role}, 你的名字叫{name}",
    input_variables=["role", "name"]
)

prompt = prompt_template.format(role="前端专家", name="wifi歪f")
print(prompt) # 你是一个前端专家, 你的名字叫wifi歪f
  1. invoke()
from langchain_core.prompts import PromptTemplate

prompt_template = PromptTemplate(
    template="你是一个{role}, 你的名字叫{name}",
    input_variables=["role", "name"]
)

prompt = prompt_template.invoke(input={
    "role": "前端专家",
    "name": "wifi歪f"
})
print(prompt) # text='你是一个前端专家, 你的名字叫wifi歪f'

这个输出和 js 的模版字符串一样

结合大模型使用

from langchain_core.prompts import PromptTemplate
from langchain_ollama import ChatOllama

chat_model = ChatOllama(
    model="qwen3:0.6b"
)

template = PromptTemplate.from_template(
    template="请评价{product}的优缺点,包括{aspect1}和{aspect2}。"
).invoke(input={
    "product": "智能手机",
    "aspect1": "电池续航",
    "aspect2": "拍照质量"
})

response = chat_model.invoke(template)
print(response)

ChatPromptTemplate

ChatPromptTemplate 是创建聊天消息列表的提示模板。它比普通 PromptTemplate 更适合处理多角色、多轮次的对话场景。

特点

  • 支持 System / Human / AI 等不同角色的消息模板
  • 对话历史维护

参数类型

列表参数格式是 tuple 类型(role :str + content :str 组合最常用)

元组的格式为:
(role: str | type, content: str | list[dict] | list[object])

  • 其中 role 是:字符串(如 "system""human""ai"

实例化方式

PromptTemplate 一样,有两种实例化方法。

from langchain_core.prompts import ChatPromptTemplate

# 方式1:构造函数
chat_prompt_template = ChatPromptTemplate(
    messages=[
        ("system", "你是一个AI助手,你的名字叫{name}"),
        ("human", "我的问题是{question}")
    ],
    input_variables=["name", "question"],
)

# 方式2:调用from_message()
chat_prompt_template2 = ChatPromptTemplate.from_messages(
    messages=[
        ("system", "你是一个AI助手,你的名字叫{name}"),
        ("human", "我的问题是{question}")
    ]
)

实例化参数类型

本质:不管使用构造方法还是使用from_messages()来创建ChatPromptTemplate实例,本质上来讲,传入的都是消息构成的列表。

messages 参数的类型都是列表,但是列表的元素的类型是多样的,该元素可以是:

  • 字符串类型
  • 字典类型
  • 元祖构成的列表
  • 消息类型
  • Chat 提示词模版类型:BaseChatPromptTemplate
  • 消息提示词模版类型:SystemMessagePromptTemplateHumanMessagePromptTemplateAIMessagePromptTemplateChatMessagePromptTemplate
from langchain_core.messages import SystemMessage, HumanMessage
from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate

# message参数形式1:字符串类型
chat_prompt_template = ChatPromptTemplate(["我的问题是{question}"])  # 默认是HumanMessage
chat_prompt_template_1 = ChatPromptTemplate(messages=["我的问题是{question}"])  # messages可以省略
# message参数形式2:字典类型
chat_prompt_template2 = ChatPromptTemplate([
    {"role": "system", "content": "我是一个人工智能助手,我的名字叫{name}"},
    {"role": "human", "content": "我的问题是{question}"}
])
# message参数形式3:元祖类型
chat_prompt_template3 = ChatPromptTemplate([
    ("system", "你是一个AI助手,你的名字叫{name}"),
    ("human", "我的问题是{question}")
])
# message参数形式4:消息类型
chat_prompt_template4 = ChatPromptTemplate([
    SystemMessage(content="你是一个AI助手,你的名字叫{name}"),
    HumanMessage("我的问题是{question}")
])
# message参数形式5:Chat提示词模版类型->`BaseChatPromptTemplate`
template1 = ChatPromptTemplate(["模版1"])
template2 = ChatPromptTemplate(["模版2"])
chat_prompt_template5 = ChatPromptTemplate([
    template1, template2
])
# message参数形式6:消息提示词模版类型->`SystemMessagePromptTemplate`、`HumanMessagePromptTemplate`、`AIMessagePromptTemplate`、`ChatMessagePromptTemplate`
system_message_prompt = SystemMessagePromptTemplate.from_template("system模版")
human_message_prompt = HumanMessagePromptTemplate.from_template("human模版")
chat_prompt_template6 = ChatPromptTemplate([
    system_message_prompt, human_message_prompt
])

形式 4 和形式 6 的区别:在于提示词是否是变量,如果需要动态的就用形式 6

调用提示词模版的方法

  1. invoke():传入的是字典,返回ChatPromptValue
  2. format():传入变量的值,返回 str
  3. format_messages():传入变量的值,返回消息构成的 List
  4. format_prompt():传入变量的值,返回ChatPromptValue
  • invoke()
from langchain_core.prompts import ChatPromptTemplate

chat_prompt_template = ChatPromptTemplate(
    messages=[
        ("system", "你是一个AI助手,你的名字叫{name}"),
        ("human", "我的问题是{question}")
    ],
    input_variables=["name", "question"],
)

prompt = chat_prompt_template.invoke(input={
    "name": "wifi",
    "question": "1+2=?"
})
print(type(prompt)) # <class 'langchain_core.prompts.chat.ChatPromptValue'>
  • format()
from langchain_core.prompts import ChatPromptTemplate

chat_prompt_template = ChatPromptTemplate(
    messages=[
        ("system", "你是一个AI助手,你的名字叫{name}"),
        ("human", "我的问题是{question}")
    ],
    input_variables=["name", "question"],
)

prompt = chat_prompt_template.format(name="wifi", question="1+2=?")
print(type(prompt)) # <class 'str'>
  • format_messages()
from langchain_core.prompts import ChatPromptTemplate

chat_prompt_template = ChatPromptTemplate(
    messages=[
        ("system", "你是一个AI助手,你的名字叫{name}"),
        ("human", "我的问题是{question}")
    ],
    input_variables=["name", "question"],
)

prompt = chat_prompt_template.format_messages(name="wifi", question="1+2=?")
print(type(prompt)) # <class 'list'>
  • format_prompt()
from langchain_core.prompts import ChatPromptTemplate

chat_prompt_template = ChatPromptTemplate(
    messages=[
        ("system", "你是一个AI助手,你的名字叫{name}"),
        ("human", "我的问题是{question}")
    ],
    input_variables=["name", "question"],
)

prompt = chat_prompt_template.format_prompt(name="wifi", question="1+2=?")
print(type(prompt)) # <class 'langchain_core.prompt_values.ChatPromptValue'>
  • 如何实现ChatPromptValuelist[message]、字符串之间的转换
from langchain_core.prompts import ChatPromptTemplate

chat_prompt_template = ChatPromptTemplate(
    messages=[
        ("system", "你是一个AI助手,你的名字叫{name}"),
        ("human", "我的问题是{question}")
    ],
    input_variables=["name", "question"],
)

prompt_value = chat_prompt_template.format_prompt(name="wifi", question="1+2=?")
# invoke也是可以调用to_messages 和 to_string
# prompt_value = chat_prompt_template.invoke(...)

# 将ChatPromptValue类型转为消息构成的list
prompt_value_to_message = prompt_value.to_messages()
print(prompt_value_to_message) # [SystemMessage(content='你是一个AI助手,你的名字叫wifi', additional_kwargs={}, response_metadata={}), HumanMessage(content='我的问题是1+2=?', additional_kwargs={}, response_metadata={})]
print(type(prompt_value_to_message)) # <class 'list'>
# 将ChatPromptValue类型转为string
prompt_value_to_string = prompt_value.to_string()
print(prompt_value_to_string) # System: 你是一个AI助手,你的名字叫wifi\nHuman: 我的问题是1+2=?
print(type(prompt_value_to_string)) # <class 'str'>

插入消息列表:MessagePlaceholder

当不确定消息提示模板使用什么角色,或者希望在格式化(调用invokeformat)过程中插入消息列表时,可使用 MessagesPlaceholder,它负责在特定位置添加消息列表。

使用场景

  • ChatPromptTemplate 模版中的消息类型和个数不确定的时候,就可以使用 MessagesPlaceholder
  • 多轮对话系统存储历史消息、Agent 的中间步骤处理等场景中,此功能非常实用

就类似一个占位,后续用到时再填充

from langchain_core.messages import HumanMessage
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

chat_prompt_template = ChatPromptTemplate.from_messages([
    ('system', "你是一个AI助手,你的名字是{name}"),
    MessagesPlaceholder(variable_name="msg")
])

chat_prompt_template.invoke({
    "name": "wifi",
    # msg可以填入消息列表,会将消息填入MessagesPlaceholder位置
    "msg": [HumanMessage("我的问题是:1+2=?")]
})

少量样本示例的提示词模板 FewShotPromptTemplate

在构建 prompt 时,可以通过构建一个少量示例列表去进一步格式化 prompt,这是一种简单但强大的指导生成的方式,在某些情况下可以显著提高模型性能

少量示例提示模板可以由 一组示例 或一个负责从定义的集合中选择 一部分示例 的示例选择器构建。

  • 前者:使用 FewShotPromptTemplateFewShotChatMessagePromptTemplate
  • 后者:使用 Example selectors(示例选择器)

每个示例的结构都是一个 字典,其中 是输入变量, 是输入变量的值。

FewShotPromptTemplate

FewShotPromptTemplate 需要结合 PromptTemplate 去使用

  • 未提供样式示例
from langchain_ollama import ChatOllama

chat_model = ChatOllama(model="qwen3:0.6b")

res = chat_model.invoke('2 🐢 9是多少?')
print(res.content)
# 您的问题可能涉及数字谜题或游戏,其中符号可能代表数字。例如,如果“2 🐢 9”是一个数字谜题,其中“星星”符号代表数字“9”,那么可能的答案是“2 9”,即数值为29。不过,具体数值需要根据上下文进一步确认。如果您有更多背景信息,欢迎补充说明。

因为 2 🐢 9 的计算方式取决于你所用的符号 “🐢” 的含义。请提供更多信息或者说明这个符号代表什么运算。

  • 使用 FewShotPromptTemplate
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate
from langchain_ollama import ChatOllama

chat_model = ChatOllama(model="qwen3:0.6b")

# 创建PromptTemplate实例
example_prompt = PromptTemplate.from_template(
    template="Input: {input}\nOutput: {output}"
)

# 提供一些示例
examples = [
    {"input": "北京天气怎么样", "output": "北京市"},
    {"input": "南京下雨吗", "output": "南京市"},
    {"input": "武汉热吗", "output": "武汉市"}
]

# 创建FewShotPromptTemplate实例
shot_prompt_template = FewShotPromptTemplate(
    example_prompt=example_prompt,  # 需要PromptTemplate实例
    examples=examples,
    suffix="Input: {input}\nOutput:", # 声明在示例后面的提示模版字符串
    input_variables=["input"] # 传入的变量
)

prompt = shot_prompt_template.invoke({"input": "长沙多少度"})
print(prompt)
# text='Input: 北京天气怎么样\nOutput: 北京市\n\nInput: 南京下雨吗\nOutput: 南京市\n\nInput: 武汉热吗\nOutput: 武汉市\n\nInput: 长沙多少度\nOutput:'

response = chat_model.invoke(prompt)
print(response.content)
# 长沙市

FewShotChatMessagePromptTemplate

除了 FewShotPromptTemplate 之外,FewShotChatMessagePromptTemplate 是专门为聊天对话场景设计的少样本(few-shot)提示模板,它继承自 FewShotPromptTemplate,但针对聊天消息的格式进行了优化。

特点

  • 自动将示例格式化为聊天消息( HumanMessage / AIMessage 等)
  • 输出结构化聊天消息( List[BaseMessage]
  • 保留对话轮次结构

FewShotChatMessagePromptTemplate 需要结合 ChatPromptTemplate 去使用

from langchain_core.prompts import ChatPromptTemplate, \
    FewShotChatMessagePromptTemplate
from langchain_ollama import ChatOllama

chat_model = ChatOllama(model="qwen3:0.6b")

examples = [
    {"input": "2🦜2", "output": "4"},
    {"input": "2🦜3", "output": "6"},
]

example_template = ChatPromptTemplate.from_messages([
    ("human", "{input}是多少?"),
    ("ai", "{output}")
])

few_shot_prompt = FewShotChatMessagePromptTemplate(
    examples=examples,
    example_prompt=example_template,
)
final_prompt = ChatPromptTemplate.from_messages([
    ("system", "你是一个数学专家"),
    few_shot_prompt,
    ('human', '{input}'),
])

response = chat_model.invoke(final_prompt.invoke(input="2🦜4"))
print(response.content) # 8

Example selectors(示例选择器)

前面 FewShotPromptTemplate 的特点是,无论输入什么问题,都会包含全部示例。在实际开发中,我们可以根据当前输入,使用示例选择器,从大量候选示例中选取最相关的示例子集。

使用的好处:避免盲目传递所有示例,减少 token 消耗的同时,还可以提升输出效果。

示例选择策略:语义相似选择、长度选择、最大边际相关示例选择等

  • 语义相似选择:通过余弦相似度等度量方式评估语义相关性,选择与输入问题最相似的 k 个示例。
  • 长度选择:根据输入文本的长度,从候选示例中筛选出长度最匹配的示例。增强模型对文本结构的理解。比语义相似度计算更轻量,适合对响应速度要求高的场景。
  • 最大边际相关示例选择:优先选择与输入问题语义相似的示例;同时,通过惩罚机制避免返回同质化的内容
  • 余弦相似度是通过计算两个向量的夹角余弦值来衡量它们的相似性。它的值范围在-1 到 1 之间:当两个向量方向相同时值为 1;夹角为 90° 时值为 0;方向完全相反时为-1。
  • 数学表达式:余弦相似度 = (A⋅B)/(∣∣A∣∣∗∣∣B∣∣)(A·B) / (||A|| * ||B||)(AB)/(∣∣A∣∣∣∣B∣∣)。其中A⋅BA·BAB是点积,∣∣A∣∣||A||∣∣A∣∣∣∣B∣∣||B||∣∣B∣∣是向量的模(长度)。

示例

  1. 需要提前安装chromadb
# 安装向量数据库
uv pip install chromadb
  1. 还需要使用到 embedding 嵌入模型

这里以 ollama 的mxbai-embed-large:latest为例

  1. 示例代码 1:
from langchain_community.vectorstores import Chroma
from langchain_core.example_selectors import SemanticSimilarityExampleSelector
from langchain_ollama import OllamaEmbeddings

embeddings_model = OllamaEmbeddings(
    model="mxbai-embed-large:latest"
)

examples = [
    {
        "question": "谁活得更久,穆罕默德·阿里还是艾伦·图灵?",
        "answer": """
接下来还需要问什么问题吗?
追问:穆罕默德·阿里去世时多大年纪?
中间答案:穆罕默德·阿里去世时享年74岁。
""",
    },
    {
        "question": "craigslist的创始人是什么时候出生的?",
        "answer": """
接下来还需要问什么问题吗?
追问:谁是craigslist的创始人?
中级答案:Craigslist是由克雷格·纽马克创立的。
""",
    },
    {
        "question": "谁是乔治·华盛顿的外祖父?",
        "answer": """
接下来还需要问什么问题吗?
追问:谁是乔治·华盛顿的母亲?
中间答案:乔治·华盛顿的母亲是玛丽·鲍尔·华盛顿。
""",
    },
    {
        "question": "《大白鲨》和《皇家赌场》的导演都来自同一个国家吗?",
        "answer": """
接下来还需要问什么问题吗?
追问:《大白鲨》的导演是谁?
中级答案:《大白鲨》的导演是史蒂文·斯皮尔伯格。
""",
    },
]

example_selector = SemanticSimilarityExampleSelector.from_examples(
    examples,
    # 这是用于生成嵌入的嵌入类,用于衡量语义相似性
    embeddings_model,
    # 这是用于存储嵌入并进行相似性搜索的 VectorStore 类
    Chroma,
    # 这是要生成的示例数量
    k=1,
)

question = "玛丽·鲍尔·华盛顿的父亲是谁?"
selected_examples = example_selector.select_examples({"question": question})
print(f"与输入最相似的示例:{selected_examples}")
# 与输入最相似的示例:[{'answer': '\n接下来还需要问什么问题吗?\n追问:谁是craigslist的创始人?\n中级答案:Craigslist是由克雷格·纽马克创立的。\n', 'question': 'craigslist的创始人是什么时候出生的?'}]
  1. 示例 2:结合 FewShotPromptTemplate 使用
from langchain_community.vectorstores import Chroma
from langchain_core.example_selectors import SemanticSimilarityExampleSelector
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate
from langchain_ollama import OllamaEmbeddings

embeddings_model = OllamaEmbeddings(
    model="mxbai-embed-large:latest"
)

examples = [
    {
        "question": "谁活得更久,穆罕默德·阿里还是艾伦·图灵?",
        "answer": """
接下来还需要问什么问题吗?
追问:穆罕默德·阿里去世时多大年纪?
中间答案:穆罕默德·阿里去世时享年74岁。
""",
    },
    {
        "question": "craigslist的创始人是什么时候出生的?",
        "answer": """
接下来还需要问什么问题吗?
追问:谁是craigslist的创始人?
中级答案:Craigslist是由克雷格·纽马克创立的。
""",
    },
    {
        "question": "谁是乔治·华盛顿的外祖父?",
        "answer": """
接下来还需要问什么问题吗?
追问:谁是乔治·华盛顿的母亲?
中间答案:乔治·华盛顿的母亲是玛丽·鲍尔·华盛顿。
""",
    },
    {
        "question": "《大白鲨》和《皇家赌场》的导演都来自同一个国家吗?",
        "answer": """
接下来还需要问什么问题吗?
追问:《大白鲨》的导演是谁?
中级答案:《大白鲨》的导演是史蒂文·斯皮尔伯格。
""",
    },
]

example_selector = SemanticSimilarityExampleSelector.from_examples(
    examples,
    # 这是用于生成嵌入的嵌入类,用于衡量语义相似性
    embeddings_model,
    # 这是用于存储嵌入并进行相似性搜索的 VectorStore 类
    Chroma,
    # 这是要生成的示例数量
    k=1,
)

example_prompt = PromptTemplate.from_template(
    template="Input: {question}\nOutput: {answer}",
)

# 结合 FewShotPromptTemplate 使用
prompt = FewShotPromptTemplate(
    example_selector=example_selector,
    example_prompt=example_prompt,
    suffix="Input: {question}\nOutput:"
).invoke(input={
    "question": "玛丽·鲍尔·华盛顿的父亲是谁?"
})
print(prompt)

可以将FewShotPromptTemplate生成的新的提示词传入大模型生成对应内容。

从文档中加载 Prompt(了解)

将想要设定 prompt 所支持的格式保存为 JSON 或者 YAML 格式文件,通过读取指定路径的格式化文件,获取相应的 prompt。

目的与使用场景:

  • 为了便于共享、存储和加强对 prompt 的版本控制
  • 当我们的 prompt 模板数据较大时,我们可以使用外部导入的方式进行管理和维护

如何使用?

  1. 创建一个prompt.yaml文件,内容如下:
_type: 'prompt'
input_variables: ['name', 'what']
template: '请给{name}讲一个关于{what}的故事'
  1. 使用
from langchain_core.prompts import load_prompt
from dotenv import load_dotenv

load_dotenv()

prompt = load_prompt("prompt.yaml", encoding="utf-8")
print(prompt.format(name="年轻人", what="滑稽"))
# 请给年轻人讲一个关于滑稽的故事

json也是一样的

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐