langchain学习随笔02提示词模板PromptTemplate
PromptTemplate是一个模板化的字符串,你可以将变量插到模板中,从而创建不同的提示。
*****************************实例化方式1 使用构造方法*****************************************
from langchain_core.prompts import PromptTemplate
#1. 创建提示词实例,参数中必须要指定的input_variables ,template
template = PromptTemplate(template="请简要描述{topic}的应用。",
input_variables=["topic"])
template2 = PromptTemplate(template="你是一个卓越的{rolename},你的名字叫{name}。",
input_variables=["rolename","name"])
print(template)
# 设置实例中的变量
prompts1 = template.format(topic="机器学习")
prompts2 = template2.format(rolename="生物科学家",name="阿坤")
print("提示词1",prompts1)
print("提示词2",prompts2)
#定义多变量模板
template2 = PromptTemplate(
template="请评价{product}的优缺点,包括{aspect1}和{aspect2}。",input_variables=[ "product", "aspect1", "aspect2"])
#使用模板生成提示词
prompts3 = template2.format(product="智能手机", aspect1="电池续航",aspect2="拍照质量")
prompts4 = template2.format(product="笔记本电脑",aspect1="处理速度",aspect2="便携性")
print("提示词3",prompts3)
print("提示词4",prompts4)
prompt_template = PromptTemplate.from_template("请给我一个关于{topic}的{type}解释")
#传入模板中的变量名
prompt = prompt_template.format(type= "详细",topic= "量子力学")
print(prompt)
输出:
input_variables=['topic'] input_types={} partial_variables={} template='请简要描述{topic}的应用。'
提示词1 请简要描述机器学习的应用。
提示词2 你是一个卓越的生物科学家,你的名字叫阿坤。
提示词3 请评价智能手机的优缺点,包括电池续航和拍照质量。
提示词4 请评价笔记本电脑的优缺点,包括处理速度和便携性。
请给我一个关于量子力学的详细解释
*********************************实例化方式2 使用from_template()****************************
prompt_template = PromptTemplate.from_template(template="你是一名{role},你的名字叫{name}")
#传入模板中的变量名
prompt = prompt_template.format(role= "老师",name= "孔子")
print(prompt)
#定义多变量模板
template2 = PromptTemplate.from_template(
template="请评价{product}的优缺点,包括{aspect1}和{aspect2}。" )
#使用模板生成提示词
prompts3 = template2.format(product="智能手机", aspect1="电池续航",aspect2="拍照质量")
print("提示词3",prompts3)
输出:
你是一名老师,你的名字叫孔子
提示词3 请评价智能手机的优缺点,包括电池续航和拍照质量。
如果提示词模板中没有变量,则format()不需要传参数
full_template ="""
如何高效的学习
答案:"""
partial_template = PromptTemplate.from_template(full_template)
#只需提供剩余变量
print(partial_template.format())
