improve prompt template handling with safer variable substitution and missing var fallback
This commit is contained in:
parent
3563220385
commit
c57fb7edd1
@ -94,6 +94,15 @@ def department_prompt(
|
||||
"supplements": supplements.strip() or "- 当前无追加数据",
|
||||
"action": "" # 添加 action 变量以避免模板格式化错误
|
||||
}
|
||||
template_vars.setdefault("scratchpad", "")
|
||||
|
||||
# Ensure all declared template variables exist to avoid KeyError
|
||||
try:
|
||||
declared_vars = list(getattr(template, "variables", []) or [])
|
||||
except Exception: # noqa: BLE001
|
||||
declared_vars = []
|
||||
for var in declared_vars:
|
||||
template_vars.setdefault(var, "")
|
||||
|
||||
# Get template and format prompt
|
||||
return template.format(template_vars)
|
||||
|
||||
@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from pathlib import Path
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Dict, List, Optional, TYPE_CHECKING
|
||||
@ -55,11 +56,15 @@ class PromptTemplate:
|
||||
if missing:
|
||||
raise ValueError(f"Missing required context: {', '.join(missing)}")
|
||||
|
||||
# Format template
|
||||
try:
|
||||
result = self.template.format(**context)
|
||||
except KeyError as e:
|
||||
raise ValueError(f"Missing template variable: {e}")
|
||||
pattern = re.compile(r"\{([^{}]+)\}")
|
||||
|
||||
def _replace(match: re.Match[str]) -> str:
|
||||
token = match.group(1)
|
||||
if token in context:
|
||||
return str(context[token])
|
||||
return match.group(0)
|
||||
|
||||
result = pattern.sub(_replace, self.template)
|
||||
|
||||
# Truncate if needed, preserving exact number of characters
|
||||
if self.max_length > 0 and len(result) > self.max_length:
|
||||
|
||||
Loading…
Reference in New Issue
Block a user