LangChain最详细教程之Model I/O(二)Prompt Template
目录
简介
一、 介绍与分类
二、PromptTemplate
1、两种实例化方式
1.1、使用构造方法
1.2、调用from_template()
2、两种新的结构形式
2.1、部分提示词模版
2.2、组合提示词的使用
3、format() 与 invoke()
4、结合大模型的使用
三、ChatPromptTemplate
1、两种实例化方式
1.1、使用构造方法
1.2、调用from_messages()
2、模板调用的几种方式
2.1、用 invoke()
2.2、用format()
2.3、用format_messages()
2.4、用format_prompt()
3、更丰富的实例化参数类型
3.1、元组构成的列表
3.2、字符串
3.3、字典类型
3.4、消息类型
3.5、Chat提示词模板类型
3.6、消息提示词模板类型
4、结合大模型的使用
5、插入消息列表:MessagePlaceholder
四、少量示例的提示词模板的使用
1、FewShotPromptTemplate
2、FewShotChatMessagePromptTemplate
3、Example selectors(示例选择器)
五、PipelinePromptTemplate
六、自定义提示词模版
七、从文档中加载Prompt
1、yaml格式提示词
2、 json格式提示词
总结
简介
本系列教程将以「系统梳理 + 实战落地」为核心,从基础到进阶全面拆解 LangChain—— 这个目前最流行的大语言模型(LLM)应用开发框架。之前对langchain进行了系统的概述,现在我们就来详细看看每一个板块。
LangChain最详细教程之Model I/O(一)调用模型
一、 介绍与分类
- 以 字典 作为输入,其中每个键代表要填充的提示模板中的变量。
- 输出一个 PromptValue 。这个 PromptValue 可以传递给 LLM 或 ChatModel,并且还可以转换为字符串或消息列表。
- PromptTemplate :LLM提示模板,用于生成字符串提示。它使用 Python 的字符串来模板提示。
- ChatPromptTemplate :聊天提示模板,用于组合各种角色的消息模板,传入聊天模型。
- XxxMessagePromptTemplate :消息模板词模板,包括:SystemMessagePromptTemplate、
- HumanMessagePromptTemplate、AIMessagePromptTemplate、
- ChatMessagePromptTemplate等
- FewShotPromptTemplate :样本提示词模板,通过示例来教模型如何回答
- PipelinePrompt :管道提示词模板,用于把几个提示词组合在一起使用。
- 自定义模板 :允许基于其它模板类来定制自己的提示词模板。
- 调用format()方法时,可以传入一个或多个参数,这些参数将被顺序替换进占位中。
- str.format()提供了灵活的方式来构造字符串,支持多种格式化选项。
# 使用位置参数
info = "Name: {0}, Age: {1}".format("Jerry", 25)
print(info)
# 使用关键字参数
info = "Name: {name}, Age: {age}".format(name="Tom", age=25)
print(info)
# 使用字典解包
person = {"name": "David", "age": 40}
info = "Name: {name}, Age: {age}".format(**person)
print(info)
二、PromptTemplate
- template:定义提示词模板的字符串,其中包含 文本 和 变量占位符(如{name}) ;
- input_variables: 列表,指定了模板中使用的变量名称,在调用模板时被替换;
- partial_variables:字典,用于定义模板中一些固定的变量名。这些值不需要再每次调用时被替换。
1、两种实例化方式
1.1、使用构造方法
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)
1.2、调用from_template()
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、部分提示词模版
方式1: 在PromptTemplate的构造方法或from_template()方法内,使用partial_variables设置
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()
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、组合提示词的使用
from langchain_core.prompts import PromptTemplatetemplate = (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()
调用format()
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()
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、结合大模型的使用
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
- 支持 System / Human / AI 等不同角色的消息模板
- 对话历史维护
(role: str | type, content: str | list[dict] | list[object])
- 其中 role 是:字符串(如 "system" 、 "human" 、 "ai" )
1、两种实例化方式
1.1、使用构造方法
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()
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()
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()
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、元组构成的列表
(最常用、最基础、最简单)
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、字符串
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、字典类型
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、消息类型
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提示词模板类型
- 本质 :预定义了 role="human" 的 MessagePromptTemplate,且无需无需手动指定角色
- 模板化 :支持使用变量占位符,可以在运行时填充具体值
- 格式化 :能够将模板与输入变量结合生成最终的聊天消息
- 输出类型 :生成 HumanMessage 对象( content + role="human" )
- 设计目的 :简化用户输入消息的模板化构造,避免重复定义角色
- 角色指定 :可以为每条消息指定角色(如 "system"、"human"、"ai") 等,角色灵活。
- 模板化 :支持使用变量占位符,可以在运行时填充具体值
- 格式化 :能够将模板与输入变量结合生成最终的聊
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、消息提示词模板类型
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、结合大模型的使用
# 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
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.prompts.chat import MessagesPlaceholderchat_prompt_template = ChatPromptTemplate.from_messages([("system", "你是一个AI助手,你的名字叫{name}"),MessagesPlaceholder(variable_name="msgs")
])chat_prompt_template.invoke({"name": "小智","msgs": [HumanMessage(content="我的问题是:1 + 2 * 3 = ?")]
})
四、少量示例的提示词模板的使用
- 前者:使用 FewShotPromptTemplate 或 FewShotChatMessagePromptTemplate
- 后者:使用 Example selectors(示例选择器)
1、FewShotPromptTemplate
未提供示例的情况
import os
import dotenv
from langchain_core.prompts import FewShotPromptTemplate
from langchain_openai import ChatOpenAIdotenv.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
import os
import dotenv
from langchain_openai import ChatOpenAI
from langchain_core.prompts import PromptTemplatefrom langchain_core.prompts import FewShotPromptTemplatedotenv.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
- 自动将示例格式化为聊天消息( HumanMessage / AIMessage 等)
- 输出结构化聊天消息( List[BaseMessage] )
- 保留对话轮次结构
实例化
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())
# 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 ChatOpenAIdotenv.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(示例选择器)
- 语义相似选择 :通过余弦相似度等度量方式评估语义相关性,选择与输入问题最相似的 k 个示例。
- 长度选择 :根据输入文本的长度,从候选示例中筛选出长度最匹配的示例。增强模型对文本结构的理解。比语义相似度计算更轻量,适合对响应速度要求高的场景。
- 最大边际相关示例选择 :优先选择与输入问题语义相似的示例;同时,通过惩罚机制避免返回同质化的内容
关于余弦相似度后面才会详细讲
# 1.导入相关包
from langchain_community.vectorstores import Chroma
from langchain_core.example_selectors import SemanticSimilarityExampleSelector
import os
import dotenv
from langchain_openai import OpenAIEmbeddingsdotenv.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
- 将复杂提示拆解为多个处理阶段,每个阶段使用独立的提示模板
- 前一个模板的输出作为下一个模板的输入变量
- 使用场景:解决单一超大提示模板难以维护的问题
了解一下就行
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)
六、自定义提示词模版
- 自定义类继承提示词基类模版BasePromptTemplate
- 重写format、format_prompt、from_template方法
# 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的版本控制。
- 当我们的prompt模板数据较大时,我们可以使用外部导入的方式进行管理和维护。
1、yaml格式提示词
prompt.yaml
_type:
"prompt"
input_variables:
["name","what"]
template:
"请给{name}讲一个关于{what}的故事
from langchain_core.prompts import load_prompt
import dotenvdotenv.load_dotenv()prompt = load_prompt("prompt.yaml", encoding="utf-8")
# print(prompt)
print(prompt.format(name="年轻人", what="滑稽"))
2、 json格式提示词
prompt.json
{
"_type": "prompt",
"input_variables": ["name", "what"],
"template": "请{name}讲一个{what}的故事。"
}
from langchain_core.prompts import load_prompt
from dotenv import load_dotenvload_dotenv()prompt = load_prompt("prompt.json",encoding="utf-8")
print(prompt.format(name="张三",what="搞笑的"))
总结
提示词这部分内容特别多,还比较绕容易让人迷糊,我在学习的时候也被搞的头大、后来发现有些东西我们了解看看就行,掌握一种最基本的就行,其他的知道有这一回事,后面三个提示词了解就行,不需要我们着重去掌握,看看就行
