Prompt Template
Prompt Template 是包含变量占位符的 Prompt 模板,运行时用实际值替换。它是 Prompt 管理和上下文组装的基础构件。
#type / concept
#status / evergreen
#tech / ai
[!info] related notes
- 所属 MOC: AI Agent Application MOC
- 相关: Prompt Management, System Prompt
Prompt Template
一句话定义
Prompt Template 是包含变量占位符的 Prompt 模板。模板定义了 Prompt 的结构,运行时用实际值(用户信息、检索结果、工具描述等)替换占位符,生成最终的 Prompt。
核心原理
模板语法
# 简单变量替换
template = "你好,{name}!请问有什么可以帮助你的?"
prompt = template.format(name="张三")
# 多行模板
template = """
你是一个{role}助手。
用户信息:
{user_profile}
当前任务: {task}
请基于以上信息回答。
"""
# 条件块(用 Jinja2)
template = """
{% if context %}
参考资料:
{{ context }}
{% endif %}
问题: {{ question }}
"""
安全的变量注入
class SafePromptTemplate:
def __init__(self, template: str):
self.template = template
def render(self, **kwargs) -> str:
# 对用户输入做转义
safe_kwargs = {}
for key, value in kwargs.items():
if isinstance(value, str):
safe_kwargs[key] = self._sanitize(value)
else:
safe_kwargs[key] = value
return self.template.format(**safe_kwargs)
def _sanitize(self, text: str) -> str:
# 移除潜在的 Prompt 注入
text = text.replace("{", "\\{").replace("}", "\\}")
return text
常见坑
- 变量名拼错: 模板里写
{user_profil}但传入的是user_profile - 不做安全转义: 用户输入包含
}导致模板解析错误 - 模板太长: 超过上下文窗口限制
- 不做模板测试: 模板变更后没有验证