电子商务网站上线活动策划,学平面设计要多少钱,龙岩公司注册,长沙网站建设260e因为做AI项目的过程中#xff0c;需要处理各种提示词#xff08;prompt#xff09;#xff0c;其中有些是固定的文本#xff0c;有些是会反复修改的。如果是简单的提示词#xff0c;直接用python里面的字符串format()或者replace()函数进行处理即可。对于复杂的#xff… 因为做AI项目的过程中需要处理各种提示词prompt其中有些是固定的文本有些是会反复修改的。如果是简单的提示词直接用python里面的字符串format()或者replace()函数进行处理即可。对于复杂的还是用langchain里面的提示词模板更方便。 为了方便处理llm的promtlangchain提供了提示词模板。具体文档参见官方文档https://api.python.langchain.com/en/latest/core_api_reference.html#module-langchain_core.prompts 常见的类有BasePromptTemplate、PipelinePromptTemplate和PromptTemplate。其中BasePromptTemplate是后面2个类的基类PromptTemplate的直接父类是StringPromptTemplate而StringPromptTemplate的直接父类则是BasePromptTemplate。 BasePromptTemplate中常用的方法有format(),input_variables(),partial(),save()。
PromptTemplate中常用的方法有from_file()、from_template()。
具体使用请参见下面的源码template.txt文件中的内容如下
这是一个测试用的模板文件用于测试模板引擎的功能。
你叫做{ai_name}你是{ai_role},{instructions} template.json中的文件内容如下
{_type: prompt,input_variables: [ai_name,ai_role,instructions],template_path: template.txt
} template.py的代码如下
# coding: utf-8
from langchain_core.prompts.loading import load_prompt
from langchain_core.prompts.pipeline import PipelinePromptTemplate
from langchain_core.prompts.prompt import PromptTemplate# load_prompt 返回的是 BasePromptTemplate
main_prompt_template load_prompt(template.json)
# print(main_prompt_template)partial_variables {}
partial_variables[instructions] 按照给定的思路和上下文回答问题。# 将有值的变量填充到模板中
main_prompt_template main_prompt_template.partial(**partial_variables)
# print(main_prompt_template)# 设置模板中的其它变量
prompt main_prompt_template.format(ai_name胖胖,ai_role智能助手机器人)
print(f******\n{prompt}\n******)
# 会输出******
这是一个测试用的模板文件用于测试模板引擎的功能。
你叫做胖胖你是智能助手机器人,按照给定的思路和上下文回答问题。
******
# 使用PipelinePromptTemplate可以将多个模板组合在一起
templates []
task_template {task_description}task_prompt PromptTemplate.from_template(task_template)
templates.append((task,task_prompt))
print(ftask:{task_prompt.input_variables})resources_template {support_resources}resources_prompt PromptTemplate.from_template(resources_template)
templates.append((resources, resources_prompt))
print(fresources:{resources_prompt.input_variables})final_template 你的任务是:{task}
你可以使用的资源包括:{resources}
final_prompt PromptTemplate.from_template(final_template)
pipeline_prompt PipelinePromptTemplate(final_promptfinal_prompt,pipeline_promptstemplates)
print(fpipeline: {pipeline_prompt.input_variables})pipeline_prompt pipeline_prompt.format(task_description8月份的销售额是多少,support_resources1. 你可以查阅本地文件列表。2. 你可以读取本地文件。)print(f\n{pipeline_prompt}\n)
# 会输出你的任务是:8月份的销售额是多少
你可以使用的资源包括:1. 你可以查阅本地文件列表。2. 你可以读取本地文件。执行python template.py