编程助手学Python--Deepseek对提示词自定义模板StringPromptTemplate的理解
StringPromptTemplate
是一种用于生成字符串提示的模板类,通常用于构建基于语言模型的应用程序。它允许你定义一个包含占位符的字符串模板,并在运行时动态填充这些占位符,生成最终的提示文本。
主要功能
- 模板字符串:定义一个包含占位符的字符串模板。
- 变量填充:在运行时将占位符替换为具体的值。
- 灵活性:支持多种格式的模板字符串(如 f-string、Jinja2 等)。
核心属性和方法
template
:字符串模板,包含占位符(如{variable}
)。input_variables
:模板中需要填充的变量列表。format(\**kwargs)
:将模板中的占位符替换为传入的变量值,生成最终的字符串。
使用场景
- 生成静态或动态提示文本。
- 构建复杂的提示结构,结合多个变量。
- 与其他模板类(如
ChatPromptTemplate
)结合使用,生成多轮对话提示。
示例代码
1. 基本用法
from langchain.prompts import StringPromptTemplate
# 定义一个模板
template = "请告诉我关于{subject}的信息。"
prompt_template = StringPromptTemplate(input_variables=["subject"], template=template)
# 填充变量
prompt = prompt_template.format(subject="人工智能")
print(prompt)
# 输出: "请告诉我关于人工智能的信息。"
2. 使用 f-string 格式
StringPromptTemplate
支持 f-string 格式的模板字符串。
template = "请告诉我关于{subject}的信息。它的应用领域包括{fields}。"
prompt_template = StringPromptTemplate(input_variables=["subject", "fields"], template=template)
# 填充变量
prompt = prompt_template.format(subject="人工智能", fields="机器学习、自然语言处理")
print(prompt)
# 输出: "请告诉我关于人工智能的信息。它的应用领域包括机器学习、自然语言处理。"
3. 结合其他模板类
StringPromptTemplate
可以与其他模板类(如 ChatPromptTemplate
)结合使用,生成复杂的提示。
python
复制
from langchain.prompts import ChatPromptTemplate, HumanMessagePromptTemplate
# 定义用户消息模板
human_template = HumanMessagePromptTemplate.from_template("请告诉我关于{subject}的信息。")
# 定义聊天提示模板
chat_prompt = ChatPromptTemplate.from_messages([human_template])
# 填充变量
prompt = chat_prompt.format_prompt(subject="人工智能").to_messages()
print(prompt)
# 输出: [HumanMessage(content='请告诉我关于人工智能的信息。')]
高级用法
1. 自定义模板格式
StringPromptTemplate
支持自定义模板格式(如 Jinja2)。
from langchain.prompts import StringPromptTemplate
# 使用 Jinja2 格式的模板
template = "请告诉我关于{{ subject }}的信息。它的应用领域包括{{ fields }}。"
prompt_template = StringPromptTemplate(input_variables=["subject", "fields"], template=template, template_format="jinja2")
# 填充变量
prompt = prompt_template.format(subject="人工智能", fields="机器学习、自然语言处理")
print(prompt)
# 输出: "请告诉我关于人工智能的信息。它的应用领域包括机器学习、自然语言处理。"
2. 动态生成模板
你可以根据需要动态生成模板字符串。
def generate_template(topic):
return f"请告诉我关于{topic}的信息。"
template = generate_template("人工智能")
prompt_template = StringPromptTemplate(input_variables=[], template=template)
# 生成提示
prompt = prompt_template.format()
print(prompt)
# 输出: "请告诉我关于人工智能的信息。"
总结
StringPromptTemplate
是一个灵活且强大的工具,适用于生成各种文本提示。它的核心功能包括:
- 定义包含占位符的模板字符串。
- 动态填充变量,生成最终的提示文本。
- 支持多种模板格式(如 f-string、Jinja2 等)。
通过与其他模板类(如 ChatPromptTemplate
)结合使用,StringPromptTemplate
可以构建复杂的提示结构,满足多轮对话或动态生成提示的需求。