目录
[一、 介绍与分类](#一、 介绍与分类)
[3、format() 与 invoke()](#3、format() 与 invoke())
[2.1、用 invoke()](#2.1、用 invoke())
2、FewShotChatMessagePromptTemplate
[3、Example selectors(示例选择器)](#3、Example selectors(示例选择器))
[2、 json格式提示词](#2、 json格式提示词)
简介
本系列教程将以「系统梳理 + 实战落地」为核心,从基础到进阶全面拆解 LangChain------ 这个目前最流行的大语言模型(LLM)应用开发框架。之前对langchain进行了系统的概述,现在我们就来详细看看每一个板块。
LangChain最详细教程之Model I/O(一)调用模型
一、 介绍与分类
Prompt Template 是LangChain中的一个概念,接收用户输入,返回一个传递给LLM的信息(即提示 词prompt)。 在应用开发中,固定的提示词限制了模型的灵活性和适用范围。所以,prompt template 是一个 模板化 的字符串 ,你可以将 变量插入到模板 中,从而创建出不同的提示。调用时:
-
以 字典作为输入,其中每个键代表要填充的提示模板中的变量。
-
输出一个 PromptValue。这个 PromptValue 可以传递给 LLM 或 ChatModel,并且还可以转换为字符串或消息列表。
有几种不同类型的提示模板: -
PromptTemplate:LLM提示模板,用于生成字符串提示。它使用 Python 的字符串来模板提示。
-
ChatPromptTemplate:聊天提示模板,用于组合各种角色的消息模板,传入聊天模型。
-
XxxMessagePromptTemplate:消息模板词模板,包括:SystemMessagePromptTemplate、
-
HumanMessagePromptTemplate、AIMessagePromptTemplate、
-
ChatMessagePromptTemplate等
-
FewShotPromptTemplate:样本提示词模板,通过示例来教模型如何回答
-
PipelinePrompt:管道提示词模板,用于把几个提示词组合在一起使用。
-
自定义模板:允许基于其它模板类来定制自己的提示词模板。
str.format()
Python的 str.format() 方法是一种字符串格式化的手段,允许在 字符串中插入变量 。使用这种方法,可 以创建包含 占位符 的字符串模板,占位符由花括号 {} 标识。
- 调用format()方法时,可以传入一个或多个参数,这些参数将被顺序替换进占位中。
- str.format()提供了灵活的方式来构造字符串,支持多种格式化选项。
在LangChain的默认设置下, PromptTemplate 使用 Python 的 str.format() 方法进行模板化。这样在模型接收输入前,可以根据需要对数据进行预处理和结构化。
python
# 使用位置参数
info = "Name: {0}, Age: {1}".format("Jerry", 25)
print(info)
python
# 使用关键字参数
info = "Name: {name}, Age: {age}".format(name="Tom", age=25)
print(info)
python
# 使用字典解包
person = {"name": "David", "age": 40}
info = "Name: {name}, Age: {age}".format(**person)
print(info)
二、PromptTemplate
PromptTemplate类,用于快速构建 包含变量 的提示词模板,并通过 传入不同的参数值 生成自定义的提示词。
主要参数介绍:
- **template:**定义提示词模板的字符串,其中包含 文本和 变量占位符(如{name});
- input_variables: 列表,指定了模板中使用的变量名称,在调用模板时被替换;
- **partial_variables:**字典,用于定义模板中一些固定的变量名。这些值不需要再每次调用时被替换。
函数介绍:
format():给input_variables变量赋值,并返回提示词。利用format() 进行格式化时就一定要赋值,否则会报错。当在template中未设置input_variables,则会自动忽略。
1、两种实例化方式
1.1、使用构造方法
python
from langchain_core.prompts import PromptTemplate
#1、创建PromptTemplate的实例
#参数中必须要指明:input_variables 、template
prompt_template = PromptTemplate(
template="你是一个{role},你的名字叫{name}",
input_variables=["role","name"],
)
# print(prompt_template)
#2、填充实例中的变量。暂且使用format()
prompt = prompt_template.format(role="人工智能专家",name="小智")
print(prompt)
可以直观的看到PromptTemplate可以将template中声明的变量topic准确提取出来,使prompt更清晰。
1.2、调用from_template()
python
from langchain_core.prompts import PromptTemplate
#1、创建PromptTemplate的实例
prompt_template = PromptTemplate.from_template(template="你是一个{role},你的名字叫{name}")
# print(prompt_template)
#2、填充实例中的变量。暂且使用format()
prompt = prompt_template.format(role="人工智能专家",name="小智")
print(prompt)
2、两种新的结构形式
2.1、部分提示词模版
在生成prompt前就已经提前初始化部分的提示词,实际进一步导入模版的时候只导入除已初始化的变量即可。
方式1: 在PromptTemplate的构造方法或from_template()方法内,使用partial_variables设置
python
from langchain.prompts import PromptTemplate
#定义多变量模板
template = PromptTemplate.from_template(
template="请评价{product}的优缺点,包括{aspect1}和{aspect2}。",
partial_variables={"aspect1":"电池续航"}
)
#使用模板生成提示词
prompt_1 = template.format(product="智能手机",aspect2="拍照质量")
print(prompt_1)
方式2:调用方法partial()
python
from langchain.prompts import PromptTemplate
#定义多变量模板
template = PromptTemplate(
template="请评价{product}的优缺点,包括{aspect1}和{aspect2}。",
input_variables=["product", "aspect1", "aspect2"],
# partial_variables={"aspect1":"电池续航","aspect2":"拍照质量"}
)
# partial()调用完以后,不会对调用者这个模板对象产生影响;而其返回值是一个新的模板
template1 = template.partial(aspect1="电池续航",aspect2="拍照质量")
#使用模板生成提示词
prompt_1 = template1.format(product="智能手机")
print("提示词1:",prompt_1)
2.2、组合提示词的使用
python
from langchain_core.prompts import PromptTemplate
template = (
PromptTemplate.from_template(template = "Tell me a joke about {topic}")
+ ", make it funny"
+ "\n\nand in {language}"
)
prompt = template.format(topic="sports", language="spanish")
print(prompt)
3、format() 与 invoke()
只要对象是RunnableSerializable接口类型,都可以使用invoke(),替换前面使用format()的调用方式。
format(),返回值为字符串类型;invoke(),返回值为PromptValue类型,接着调用to_string()返回字符串。
调用format()
python
from langchain.prompts import PromptTemplate
#定义多变量模板
template = PromptTemplate.from_template(
template="请评价{product}的优缺点,包括{aspect1}和{aspect2}。")
#使用模板生成提示词
prompt_1 = template.format(product="智能手机", aspect1="电池续航", aspect2="拍照质量")
print(prompt_1)
print(type(prompt_1))
调用invoke()
python
from langchain.prompts import PromptTemplate
#定义多变量模板
template = PromptTemplate.from_template(
template="请评价{product}的优缺点,包括{aspect1}和{aspect2}。")
#使用模板生成提示词
# prompt_1 = template.format(product="智能手机", aspect1="电池续航", aspect2="拍照质量")
prompt_1 = template.invoke(input={"product":"智能手机","aspect1":"电池续航","aspect2":"拍照质量"})
print(prompt_1)
print(type(prompt_1))
4、结合大模型的使用
python
from langchain_openai import ChatOpenAI
import os
import dotenv
#加载配置文件
dotenv.load_dotenv()
os.environ["OPENAI_BASE_URL"] = os.getenv("OPENAI_BASE_URL")
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY1")
# 获取对话模型:
chat_model = ChatOpenAI(
model="gpt-4o-mini",
max_tokens=500
)
# 生成提示词模板
template = PromptTemplate.from_template(
template="请评价{product}的优缺点,包括{aspect1}和{aspect2}。")
# 给模板的变量赋值
prompt = template.invoke(input={"product":"智能手机","aspect1":"电池续航","aspect2":"拍照质量"})
# 调用大模型,将提示词传入
response= chat_model.invoke(prompt)
print(response)
print(type(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")
1、两种实例化方式
1.1、使用构造方法
python
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
# 创建实例
chat_prompt_template = ChatPromptTemplate(
messages=[
("system", "你是一个AI助手,你的名字叫{name}"),
("human", "我的问题是{question}")
],
input_variables=["name", "question"],
)
response = chat_prompt_template.invoke(input={"name": "小智", "question": "1 + 2 * 3 = ?"})
print(response)
print(type(response)) #<class 'langchain_core.prompt_values.ChatPromptValue'>
print(len(response.messages))
1.2、调用from_messages()
python
from langchain_core.prompts import ChatPromptTemplate
# 创建实例
chat_prompt_template = ChatPromptTemplate([
("system", "你是一个AI助手,你的名字叫{name}"),
("human", "我的问题是{question}")
])
response = chat_prompt_template.invoke({"name": "小智", "question": "1 + 2 * 3 = ?"})
print(response)
print(type(response)) #<class 'langchain_core.prompt_values.ChatPromptValue'>
print(len(response.messages))
2、模板调用的几种方式
- invoke():传入的是字典,返回ChatPromptValue
- format():传入变量的值,返回str
- format_messages(): 传入变量的值,返回消息构成的list
- format_prompt(): 传入变量的值,返回ChatPromptValue
2.1、用 invoke()
2.2、用format()
上面两个跟之前一样就不举例了
2.3、用format_messages()
python
from langchain_core.prompts import ChatPromptTemplate
# 创建实例
chat_prompt_template = ChatPromptTemplate.from_messages([
("system", "你是一个AI助手,你的名字叫{name}"),
("human", "我的问题是{question}")
])
response = chat_prompt_template.format_messages(name="小智", question="1 + 2 * 3 = ?")
print(response)
print(type(response)) #from langchain_core.prompts import ChatPromptTemplate
# 创建实例
chat_prompt_template = ChatPromptTemplate.from_messages([
("system", "你是一个AI助手,你的名字叫{name}"),
("human", "我的问题是{question}")
])
response = chat_prompt_template.format_messages(name="小智", question="1 + 2 * 3 = ?")
print(response)
print(type(response)) #<class 'list'>
2.4、用format_prompt()
python
from langchain_core.prompts import ChatPromptTemplate
# 创建实例
chat_prompt_template = ChatPromptTemplate.from_messages([
("system", "你是一个AI助手,你的名字叫{name}"),
("human", "我的问题是{question}")
])
response = chat_prompt_template.format_prompt(name="小智", question="1 + 2 * 3 = ?")
print(response)
print(type(response)) #<class 'langchain_core.prompt_values.ChatPromptValue'>
3、更丰富的实例化参数类型
本质:不管使用构造方法、还是使用from_message()来创建ChatPromptTemplate的实例,本质上来讲,传入的都是消息构成的列表。
从调用上来讲,我们看到,不管使用构造方法,还是使用from_message(),messages参数的类型都是列表,但是列表的元素的类型是多样的。元素可以是:字符串类型、字典类型、消息类型、元组构成的列表(最常用、最基础、最简单)、Chat提示词模板类型、消息提示词模板类型
3.1、元组构成的列表
(最常用、最基础、最简单)
python
from langchain_core.prompts import ChatPromptTemplate
# 创建实例
#第1种方式
chat_prompt_template1 = ChatPromptTemplate(
messages=[
("system", "你是一个AI助手,你的名字叫{name}"),
("human", "我的问题是{question}")
]
)
#第2种方式
chat_prompt_template2 = ChatPromptTemplate.from_messages([
("system", "你是一个AI助手,你的名字叫{name}"),
("human", "我的问题是{question}")
])
#
response = chat_prompt_template1.invoke({"name": "小智", "question": "1 + 2 * 3 = ?"})
3.2、字符串
python
from langchain_core.prompts import ChatPromptTemplate
# 创建实例
chat_prompt_template = ChatPromptTemplate.from_messages([
"我的问题是{question}" #默认的角色是:human !
])
#
response = chat_prompt_template.invoke({"question": "1 + 2 * 3 = ?"})
print(response)
3.3、字典类型
python
from langchain_core.prompts import ChatPromptTemplate
# 创建实例
chat_prompt_template = ChatPromptTemplate.from_messages([
{"role": "system", "content": "我是一个人工智能助手,我的名字叫{name}"},
{"role": "human", "content": "我的问题是{question}"},
])
#
response = chat_prompt_template.invoke({"name": "小智", "question": "1 + 2 * 3 = ?"})
print(response)
3.4、消息类型
python
from langchain_core.messages import SystemMessage, HumanMessage
from langchain_core.prompts import ChatPromptTemplate
# 创建实例
chat_prompt_template = ChatPromptTemplate.from_messages([
SystemMessage(content="我是一个人工智能助手,我的名字叫{name}"),
HumanMessage(content="我的问题是{question}")
])
#
# response = chat_prompt_template.invoke({"name":"小智", "question":"1 + 2 * 3 = ?"})
response = chat_prompt_template.invoke({})
print(response)
3.5、Chat提示词模板类型
LangChain提供不同类型的MessagePromptTemplate。最常用的是
SystemMessagePromptTemplate 、 HumanMessagePromptTemplate 和
AIMessagePromptTemplate ,分别创建系统消息、人工消息和AI消息,它们是 ChatMessagePromptTemplate的特定角色子类。
ChatMessagePromptTemplate的特定角色子类。
- 本质:预定义了 role="human" 的 MessagePromptTemplate,且无需无需手动指定角色
- 模板化:支持使用变量占位符,可以在运行时填充具体值
- 格式化:能够将模板与输入变量结合生成最终的聊天消息
- 输出类型:生成 HumanMessage 对象( content + role="human")
- 设计目的 :简化用户输入消息的模板化构造,避免重复定义角色
SystemMessagePromptTemplate、AIMessagePromptTemplate:类似于上面,不再赘述
ChatMessagePromptTemplate,用于构建聊天消息的模板。它允许你创建可重用的消息模板,这些 模板可以动态地插入变量值来生成最终的聊天消息
- 角色指定:可以为每条消息指定角色(如 "system"、"human"、"ai") 等,角色灵活。
- 模板化:支持使用变量占位符,可以在运行时填充具体值
- 格式化:能够将模板与输入变量结合生成最终的聊
python
from langchain_core.prompts import ChatPromptTemplate
# 使用 BaseChatPromptTemplate(嵌套的 ChatPromptTemplate)
nested_prompt_template1 = ChatPromptTemplate.from_messages([
("system", "我是一个人工智能助手,我的名字叫{name}")
])
nested_prompt_template2 = ChatPromptTemplate.from_messages([
("human", "很高兴认识你,我的问题是{question}")
])
prompt_template = ChatPromptTemplate.from_messages([
nested_prompt_template1,
nested_prompt_template2
])
prompt_template.format_messages(name="小智", question="你为什么这么帅?")
3.6、消息提示词模板类型
python
from langchain_core.prompts import ChatPromptTemplate, HumanMessagePromptTemplate, SystemMessagePromptTemplate
# 创建消息模板
system_template = "你是一个专家{role}"
system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)
human_template = "给我解释{concept},用浅显易懂的语言"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
# 组合成聊天提示模板
chat_prompt = ChatPromptTemplate.from_messages([
system_message_prompt, human_message_prompt
])
# 格式化提示
formatted_messages = chat_prompt.format_messages(
role="物理学家",
concept="相对论"
)
print(formatted_messages)
4、结合大模型的使用
python
# 1、提供大模型
from langchain_openai import ChatOpenAI
import os
import dotenv
#加载配置文件
dotenv.load_dotenv()
os.environ["OPENAI_BASE_URL"] = os.getenv("OPENAI_BASE_URL")
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY1")
# 获取对话模型:
chat_model = ChatOpenAI(
model="gpt-4o-mini"
)
# 2、通过Chat提示词模板,创建提示词
from langchain_core.prompts import ChatPromptTemplate
# 创建实例
chat_prompt_template = ChatPromptTemplate.from_messages([
("system", "你是一个AI助手,你的名字叫{name}"),
("human", "我的问题是{question}")
])
prompt_response = chat_prompt_template.invoke({"name": "小智", "question": "1 + 2 * 3 = ?"})
# 3、通过大模型调用提示词,得到响应数据
response = chat_model.invoke(prompt_response)
print(response)
5、插入消息列表:MessagePlaceholder
当你不确定消息提示模板使用什么角色,或者希望在格式化过程中 插入消息列表 时,该怎么办? 这就需要使用 MessagesPlaceholder,负责在特定位置添加消息列表。
**使用场景:**多轮对话系统存储历史消息以及Agent的中间步骤处理此功能非常有用
python
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.prompts.chat import MessagesPlaceholder
chat_prompt_template = ChatPromptTemplate.from_messages([
("system", "你是一个AI助手,你的名字叫{name}"),
MessagesPlaceholder(variable_name="msgs")
])
chat_prompt_template.invoke({
"name": "小智",
"msgs": [HumanMessage(content="我的问题是:1 + 2 * 3 = ?")]
})
四、少量示例的提示词模板的使用
在构建prompt时,可以通过构建一个 少量示例列表 去进一步格式化prompt,这是一种简单但强大的指导生成的方式,在某些情况下可以 显著提高模型性能 。 少量示例提示模板可以由 一组示例 或一个负责从定义的集合中选择 一部分示例 的示例选择器构建。
- 前者:使用 FewShotPromptTemplate或 FewShotChatMessagePromptTemplate
- 后者:使用 Example selectors(示例选择器)
每个示例的结构都是一个 字典 ,其中 键 是输入变量, 值 是输入变量的值。
1、FewShotPromptTemplate
未提供示例的情况
python
import os
import dotenv
from langchain_core.prompts import FewShotPromptTemplate
from langchain_openai import ChatOpenAI
dotenv.load_dotenv()
os.environ['OPENAI_API_KEY'] = os.getenv("OPENAI_API_KEY1")
os.environ['OPENAI_BASE_URL'] = os.getenv("OPENAI_BASE_URL")
chat_model = ChatOpenAI(model="gpt-4o-mini",
temperature=0.4)
res = chat_model.invoke("2 🦜 9是多少?")
print(res.content)
使用FewShotPromptTemplate
python
import os
import dotenv
from langchain_openai import ChatOpenAI
from langchain_core.prompts import PromptTemplate
from langchain_core.prompts import FewShotPromptTemplate
dotenv.load_dotenv()
os.environ['OPENAI_API_KEY'] = os.getenv("OPENAI_API_KEY1")
os.environ['OPENAI_BASE_URL'] = os.getenv("OPENAI_BASE_URL")
chat_model = ChatOpenAI(model="gpt-4o-mini")
# 创建PromptTemplate的实例
example_prompt = PromptTemplate.from_template(
template="input:{input}\noutput:{output}",
)
# 提供一些示例
examples = [
{"input": "北京天气怎么样", "output": "北京市"},
{"input": "南京下雨吗", "output": "南京市"},
{"input": "武汉热吗", "output": "武汉市"}
]
# 创建FewShotPromptTemplate的实例
few_shot_template = FewShotPromptTemplate(
example_prompt=example_prompt,
examples = examples,
suffix="input:{input}\noutput:", #声明在示例后面的提示词模板
input_variables=["input"],
)
few_shot_template.invoke({"input":"天津会下雨吗?"})
2、FewShotChatMessagePromptTemplate
除了FewShotPromptTemplate之外,FewShotChatMessagePromptTemplate是专门为 聊天对话场 景 设计的少样本(few-shot)提示模板,它继承自 FewShotPromptTemplate ,但针对聊天消息的格式进行了优化。
特点 :
- 自动将示例格式化为聊天消息( HumanMessage/ AIMessage 等)
- 输出结构化聊天消息( List[BaseMessage])
- 保留对话轮次结构
实例化
python
from langchain.prompts import (
FewShotChatMessagePromptTemplate,
ChatPromptTemplate
)
# 1.示例消息格式
examples = [
{"input": "1+1等于几?", "output": "1+1等于2"},
{"input": "法国的首都是?", "output": "巴黎"}
]
# 2.定义示例的消息格式提示词模版
msg_example_prompt = ChatPromptTemplate.from_messages([
("human", "{input}"),
("ai", "{output}"),
])
# 3.定义FewShotChatMessagePromptTemplate对象
few_shot_prompt = FewShotChatMessagePromptTemplate(
example_prompt=msg_example_prompt,
examples=examples
)
# 4.输出格式化后的消息
print(few_shot_prompt.format())
python
# 1.导入相关包
from langchain_core.prompts import (FewShotChatMessagePromptTemplate, ChatPromptTemplate)
# 2.定义示例组
examples = [
{"input": "2🦜2", "output": "4"},
{"input": "2🦜3", "output": "6"},
]
# 3.定义示例的消息格式提示词模版
example_prompt = ChatPromptTemplate.from_messages([
('human', '{input} 是多少?'),
('ai', '{output}')
])
# 4.定义FewShotChatMessagePromptTemplate对象
few_shot_prompt = FewShotChatMessagePromptTemplate(
examples=examples, # 示例组
example_prompt=example_prompt, # 示例提示词词模版
)
# 5.输出完整提示词的消息模版
final_prompt = ChatPromptTemplate.from_messages(
[
('system', '你是一个数学奇才'),
few_shot_prompt,
('human', '{input}'),
]
)
#6.提供大模型
import os
import dotenv
from langchain_openai import ChatOpenAI
dotenv.load_dotenv()
os.environ['OPENAI_API_KEY'] = os.getenv("OPENAI_API_KEY1")
os.environ['OPENAI_BASE_URL'] = os.getenv("OPENAI_BASE_URL")
chat_model = ChatOpenAI(model="gpt-4o-mini",
temperature=0.4)
chat_model.invoke(final_prompt.invoke(input="2🦜4")).content
3、Example selectors(示例选择器)
前面FewShotPromptTemplate的特点是,无论输入什么问题,都会包含全部示例。在实际开发中,我 们可以根据当前输入,使用示例选择器,从大量候选示例中选取最相关的示例子集。
使用的好处:避免盲目传递所有示例,减少 token 消耗的同时,还可以提升输出效果。
示例选择策略:语义相似选择、长度选择、最大边际相关示例选择等
- 语义相似选择:通过余弦相似度等度量方式评估语义相关性,选择与输入问题最相似的 k 个示例。
- 长度选择:根据输入文本的长度,从候选示例中筛选出长度最匹配的示例。增强模型对文本结构的理解。比语义相似度计算更轻量,适合对响应速度要求高的场景。
- 最大边际相关示例选择:优先选择与输入问题语义相似的示例;同时,通过惩罚机制避免返回同质化的内容
关于余弦相似度后面才会详细讲
python
# 1.导入相关包
from langchain_community.vectorstores import Chroma
from langchain_core.example_selectors import SemanticSimilarityExampleSelector
import os
import dotenv
from langchain_openai import OpenAIEmbeddings
dotenv.load_dotenv()
# 2.定义嵌入模型
os.environ['OPENAI_API_KEY'] = os.getenv("OPENAI_API_KEY1")
os.environ['OPENAI_BASE_URL'] = os.getenv("OPENAI_BASE_URL")
embeddings_model = OpenAIEmbeddings(
model="text-embedding-ada-002"
)
# 3.定义示例组
examples = [
{
"question": "谁活得更久,穆罕默德·阿里还是艾伦·图灵?",
"answer": """
接下来还需要问什么问题吗?
追问:穆罕默德·阿里去世时多大年纪?
中间答案:穆罕默德·阿里去世时享年74岁。
""",
},
{
"question": "craigslist的创始人是什么时候出生的?",
"answer": """
接下来还需要问什么问题吗?
追问:谁是craigslist的创始人?
中级答案:Craigslist是由克雷格·纽马克创立的。
""",
},
{
"question": "谁是乔治·华盛顿的外祖父?",
"answer": """
接下来还需要问什么问题吗?
追问:谁是乔治·华盛顿的母亲?
中间答案:乔治·华盛顿的母亲是玛丽·鲍尔·华盛顿。
""",
},
{
"question": "《大白鲨》和《皇家赌场》的导演都来自同一个国家吗?",
"answer": """
接下来还需要问什么问题吗?
追问:《大白鲨》的导演是谁?
中级答案:《大白鲨》的导演是史蒂文·斯皮尔伯格。
""",
},
]
# 4.定义示例选择器
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}")
# for example in selected_examples:
# print("\n")
# for k, v in example.items():
# print(f"{k}: {v}")
五、PipelinePromptTemplate
用于将多个提示模板按顺序组合成处理管道 ,实现分阶段、模块化的提示构建。它的核心作用类似于软件开发中的 管道模式 (Pipeline Pattern),通过串联多个提示处理步骤,实现复杂的提示生成逻辑。
特点 :
- 将复杂提示拆解为多个处理阶段,每个阶段使用独立的提示模板
- 前一个模板的输出作为下一个模板的输入变量
- 使用场景:解决单一超大提示模板难以维护的问题
说明: PipelinePromptTemplate在langchain 0.3.22版本中被标记为过时,在 langchain-core==1.0
之前不会删除它。
了解一下就行
python
from langchain_core.prompts.prompt import PromptTemplate
# 阶段1:问题分析
analysis_template = PromptTemplate.from_template("""
分析这个问题:{question}
关键要素:
""")
# 阶段2:知识检索
retrieval_template = PromptTemplate.from_template("""
基于以下要素搜索资料:
{analysis_result}
搜索关键词:
""")
# 阶段3:生成最终回答
answer_template = PromptTemplate.from_template("""
综合以下信息回答问题:
{retrieval_result}
最终答案:
""")
# 逐步执行管道提示
pipeline_prompts = [
("analysis_result", analysis_template),
("retrieval_result", retrieval_template)
]
my_input = {"question": "量子计算的优势是什么?"}
# print(pipeline_prompts)
# [('analysis_result', PromptTemplate(input_variables=['question'], input_types={},
partial_variables={}, template='\n分析这个问题:{question}\n关键要素:\n')), ('retrieval_result',
PromptTemplate(input_variables=['analysis_result'], input_types={}, partial_variables={},
template='\n基于以下要素搜索资料:\n{analysis_result}\n搜索关键词:\n'))]
for name, prompt in pipeline_prompts:
# 调用当前提示模板并获取字符串结果
result = prompt.invoke(my_input).to_string()
# 将结果添加到输入字典中供下一步使用
my_input[name] = result
# 生成最终答案
my_output = answer_template.invoke(my_input).to_string()
print(my_output)
六、自定义提示词模版
在创建prompt时,我们也可以按照自己的需求去创建自定义的提示模版。
步骤 :
- 自定义类继承提示词基类模版BasePromptTemplate
- 重写format、format_prompt、from_template方法
python
# 1.导入相关包
from typing import List, Dict, Any
from langchain.prompts import BasePromptTemplate
from langchain.prompts import PromptTemplate
from langchain.schema import PromptValue
# 2.自定义提示词模版
class SimpleCustomPrompt(BasePromptTemplate):
"""简单自定义提示词模板"""
template: str
def __init__(self, template: str, **kwargs):
# 使用PromptTemplate解析输入变量
prompt = PromptTemplate.from_template(template)
super().__init__(
input_variables=prompt.input_variables,
template=template,
**kwargs
)
def format(self, **kwargs: Any) -> str:
"""格式化提示词"""
# print("kwargs:", kwargs)
# print("self.template:", self.template)
return self.template.format(**kwargs)
def format_prompt(self, **kwargs: Any) -> PromptValue:
"""实现抽象方法"""
return PromptValue(text=self.format(**kwargs))
@classmethod
def from_template(cls, template: str, **kwargs) -> "SimpleCustomPrompt":
"""从模板创建实例"""
return cls(template=template, **kwargs)
# 3.使用自定义提示词模版
custom_prompt = SimpleCustomPrompt.from_template(
template="请回答关于{subject}的问题:{question}"
)
# 4.格式化提示词
formatted = custom_prompt.format(
subject="人工智能",
question="什么是LLM?"
)
print(formatted)
七、从文档中加载Prompt
一方面,将想要设定prompt所支持的格式保存为JSON或者YAML格式文件。
另一方面,通过读取指定路径的格式化文件,获取相应的prompt。
目的与使用场景:
- 为了便于共享、存储和加强对prompt的版本控制。
- 当我们的prompt模板数据较大时,我们可以使用外部导入的方式进行管理和维护。
1、yaml格式提示词
prompt.yaml
python
_type:
"prompt"
input_variables:
["name","what"]
template:
"请给{name}讲一个关于{what}的故事
python
from langchain_core.prompts import load_prompt
import dotenv
dotenv.load_dotenv()
prompt = load_prompt("prompt.yaml", encoding="utf-8")
# print(prompt)
print(prompt.format(name="年轻人", what="滑稽"))
2、 json格式提示词
prompt.json
python
{
"_type": "prompt",
"input_variables": ["name", "what"],
"template": "请{name}讲一个{what}的故事。"
}
python
from langchain_core.prompts import load_prompt
from dotenv import load_dotenv
load_dotenv()
prompt = load_prompt("prompt.json",encoding="utf-8")
print(prompt.format(name="张三",what="搞笑的"))
总结
提示词这部分内容特别多,还比较绕容易让人迷糊,我在学习的时候也被搞的头大、后来发现有些东西我们了解看看就行,掌握一种最基本的就行,其他的知道有这一回事,后面三个提示词了解就行,不需要我们着重去掌握,看看就行