[ PROMPT_NODE_22942 ]
prompt-templates
[ SKILL_DOCUMENTATION ]
# 提示词模板系统
## 模板架构
### 基础模板结构
python
class PromptTemplate:
def __init__(self, template_string, variables=None):
self.template = template_string
self.variables = variables or []
def render(self, **kwargs):
missing = set(self.variables) - set(kwargs.keys())
if missing:
raise ValueError(f"缺少必需变量: {missing}")
return self.template.format(**kwargs)
# 使用示例
template = PromptTemplate(
template_string="将 {text} 从 {source_lang} 翻译为 {target_lang}",
variables=['text', 'source_lang', 'target_lang']
)
prompt = template.render(
text="Hello world",
source_lang="English",
target_lang="Spanish"
)
### 条件模板
python
class ConditionalTemplate(PromptTemplate):
def render(self, **kwargs):
# 处理条件块
result = self.template
# 处理 if 块: {{#if variable}}content{{/if}}
import re
if_pattern = r'{{#if (w+)}}(.*?){{/if}}'
def replace_if(match):
var_name = match.group(1)
content = match.group(2)
return content if kwargs.get(var_name) else ''
result = re.sub(if_pattern, replace_if, result, flags=re.DOTALL)
# 处理 for 循环: {{#each items}}{{this}}{{/each}}
each_pattern = r'{{#each (w+)}}(.*?){{/each}}'
def replace_each(match):
var_name = match.group(1)
content = match.group(2)
items = kwargs.get(var_name, [])
return '\n'.join(content.replace('{{this}}', str(item)) for item in items)
result = re.sub(each_pattern, replace_each, result, flags=re.DOTALL)
# 最后,渲染剩余变量
return result.format(**kwargs)
# 使用示例
template = ConditionalTemplate("""
分析以下文本:
{text}
{{#if include_sentiment}}
提供情感分析。
{{/if}}
{{#if include_entities}}
提取命名实体。
{{/if}}
{{#if examples}}
参考示例:
{{#each examples}}
- {{this}}
{{/each}}
{{/if}}
""")
### 模块化模板组合
python
class ModularTemplate:
def __init__(self):
self.components = {}
def register_component(self, name, template):
self.components[name] = template
def render(self, structure, **kwargs):
parts = []
for component_name in structure:
if component_name in self.comp