From c57fb7edd1efb311e1942a05ba6b137dbf75d2ef Mon Sep 17 00:00:00 2001 From: Your Name Date: Sat, 11 Oct 2025 21:03:48 +0800 Subject: [PATCH] improve prompt template handling with safer variable substitution and missing var fallback --- app/llm/prompts.py | 9 +++++++++ app/llm/templates.py | 15 ++++++++++----- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/app/llm/prompts.py b/app/llm/prompts.py index a92edc3..132dfef 100644 --- a/app/llm/prompts.py +++ b/app/llm/prompts.py @@ -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) diff --git a/app/llm/templates.py b/app/llm/templates.py index 6dd73d4..9045878 100644 --- a/app/llm/templates.py +++ b/app/llm/templates.py @@ -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: