feat: Refine placeholder resolution with enhanced modifiers support
- Updated `resolve_placeholders` in `prompt_executor.py` to support combined modifiers for placeholders, allowing for more flexible output formats. - Enhanced `build_ai_placeholder_caption` in `placeholder_registry.py` to clarify the generation of AI context captions, focusing on descriptions and explanations. - Introduced new helper functions in `placeholder_resolver.py` to streamline the retrieval of descriptions and explanations for placeholders. - Modified tests to cover new functionality, ensuring accurate behavior for combined modifiers and improved placeholder resolution. These changes enhance the usability and clarity of placeholder outputs, providing users with richer contextual information.
This commit is contained in:
1 parent
a9a414b956
commit
4868e44882
5 files changed
+151
-91
No files matched your search
+59
-36
@@ -12,14 +12,17 @@ import re
|
||||
from typing import Dict, Any, Optional
|
||||
from db import get_db, get_cursor, r2d
|
||||
from fastapi import HTTPException
|
||||
from placeholder_resolver import get_catalog_row_for_key
|
||||
|
||||
|
||||
def resolve_placeholders(template: str, variables: Dict[str, Any], debug_info: Optional[Dict] = None, catalog: Optional[Dict] = None) -> str:
|
||||
"""
|
||||
Replace {{placeholder}} with values from variables dict.
|
||||
|
||||
Supports modifiers:
|
||||
- {{key|d}} — angehängter KI-Kontext (ai_caption aus Katalog, sonst description; Katalog nötig)
|
||||
Modifiers (Katalog aus get_placeholder_catalog empfohlen):
|
||||
- {{key|d}} — Wert — description (kurz)
|
||||
- {{key|x}} — nur Erklärung (Katalogfeld ai_caption), ohne Zahlenwert
|
||||
- {{key|d,x}} — Wert — description — Erklärung
|
||||
|
||||
Args:
|
||||
template: String with {{key}} or {{key|modifiers}} placeholders
|
||||
@@ -40,46 +43,66 @@ def resolve_placeholders(template: str, variables: Dict[str, Any], debug_info: O
|
||||
parts = full_placeholder.split('|')
|
||||
key = parts[0].strip()
|
||||
modifiers = parts[1].strip() if len(parts) > 1 else ''
|
||||
mods = {x.strip().lower() for x in modifiers.split(",") if x.strip()}
|
||||
want_d = "d" in mods
|
||||
want_x = "x" in mods
|
||||
|
||||
if key in variables:
|
||||
value = variables[key]
|
||||
# Convert dict/list to JSON string
|
||||
if isinstance(value, (dict, list)):
|
||||
resolved_value = json.dumps(value, ensure_ascii=False)
|
||||
else:
|
||||
resolved_value = str(value)
|
||||
|
||||
# Apply modifiers
|
||||
if 'd' in modifiers:
|
||||
if catalog:
|
||||
caption = None
|
||||
for cat_items in catalog.values():
|
||||
matching = [item for item in cat_items if item['key'] == key]
|
||||
if matching:
|
||||
row = matching[0]
|
||||
caption = (row.get('ai_caption') or row.get('description') or '').strip()
|
||||
break
|
||||
|
||||
if caption:
|
||||
resolved_value = f"{resolved_value} — {caption}"
|
||||
else:
|
||||
# Catalog not available - log warning in debug
|
||||
if debug_info is not None:
|
||||
if 'warnings' not in debug_info:
|
||||
debug_info['warnings'] = []
|
||||
debug_info['warnings'].append(f"Modifier |d used but catalog not available for {key}")
|
||||
|
||||
# Track resolution for debug
|
||||
def _warn(msg: str):
|
||||
if debug_info is not None:
|
||||
resolved[key] = resolved_value[:100] + ('...' if len(resolved_value) > 100 else '')
|
||||
debug_info.setdefault("warnings", []).append(msg)
|
||||
|
||||
return resolved_value
|
||||
else:
|
||||
# Keep placeholder if no value found
|
||||
row = get_catalog_row_for_key(catalog, key) if catalog else None
|
||||
|
||||
if want_x and not want_d:
|
||||
if key not in variables:
|
||||
if debug_info is not None:
|
||||
unresolved.append(key)
|
||||
return match.group(0)
|
||||
expl = (row.get("ai_caption") or "").strip() if row else ""
|
||||
if not expl and catalog is None:
|
||||
_warn(f"Modifier |x für {key}: Katalog fehlt (ai_caption).")
|
||||
out = expl
|
||||
if debug_info is not None:
|
||||
resolved[key] = out[:100] + ("..." if len(out) > 100 else "")
|
||||
return out
|
||||
|
||||
if key not in variables:
|
||||
if debug_info is not None:
|
||||
unresolved.append(key)
|
||||
return match.group(0)
|
||||
|
||||
value = variables[key]
|
||||
if isinstance(value, (dict, list)):
|
||||
resolved_value = json.dumps(value, ensure_ascii=False)
|
||||
else:
|
||||
resolved_value = str(value)
|
||||
|
||||
if not want_d and not want_x:
|
||||
out = resolved_value
|
||||
if debug_info is not None:
|
||||
resolved[key] = out[:100] + ("..." if len(out) > 100 else "")
|
||||
return out
|
||||
|
||||
parts = [resolved_value]
|
||||
if want_d:
|
||||
if row:
|
||||
desc = (row.get("description") or "").strip()
|
||||
if desc:
|
||||
parts.append(desc)
|
||||
else:
|
||||
_warn(f"Modifier |d für {key}: Katalog fehlt (description).")
|
||||
if want_x:
|
||||
expl = (row.get("ai_caption") or "").strip() if row else ""
|
||||
if expl:
|
||||
parts.append(expl)
|
||||
elif catalog is not None:
|
||||
_warn(f"Modifier |x (mit |d) für {key}: ai_caption leer.")
|
||||
|
||||
out = " — ".join(parts)
|
||||
if debug_info is not None:
|
||||
resolved[key] = out[:100] + ("..." if len(out) > 100 else "")
|
||||
return out
|
||||
|
||||
result = re.sub(r'\{\{([^}]+)\}\}', replacer, template)
|
||||
|
||||
# Store debug info
|
||||
@@ -464,7 +487,7 @@ async def execute_prompt_with_data(
|
||||
'today': datetime.now().strftime('%Y-%m-%d')
|
||||
}
|
||||
|
||||
# Load placeholder catalog for |d modifier support
|
||||
# Load placeholder catalog for |d / |x Modifier
|
||||
try:
|
||||
catalog = get_placeholder_catalog(profile_id)
|
||||
except Exception as e:
|
||||
|
||||
Reference in new issue
Block a user