mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 00:59:48 +08:00
PromptManager.clear_cache() and reload_prompts() dropped cached packs but
the fragment lru_cache kept serving the old fragments/*.yaml, so a
reloaded pack still carried the previous rule text. Both now clear it.
Fragments are checked for "{" and "}" when loaded (the expanded text can
pass through str.format()), with a test over every fragment in en and
zh. The notes capability gets a test that its en and zh instructions
include the shared maths rule.
Refs #2975
75 lines
2.7 KiB
Python
75 lines
2.7 KiB
Python
"""Prompt rules shared across prompt packs.
|
|
|
|
A rule that several packs state (for example how to write maths) lives once in
|
|
``fragments/<lang>.yaml``. Prompt YAML references it with ``{{shared:<name>}}``;
|
|
:class:`PromptManager` expands the marker when it loads the pack. Prompts built
|
|
in code call :func:`shared_fragment` directly.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from functools import lru_cache
|
|
from pathlib import Path
|
|
import re
|
|
from typing import Any
|
|
|
|
import yaml
|
|
|
|
_DIR = Path(__file__).resolve().parent / "fragments"
|
|
_MARKER = re.compile(r"\{\{shared:([a-z0-9_]+)\}\}")
|
|
|
|
|
|
@lru_cache(maxsize=8)
|
|
def _fragments(lang: str) -> dict[str, str]:
|
|
path = _DIR / f"{lang}.yaml"
|
|
if not path.exists():
|
|
return {}
|
|
data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
|
|
fragments = {str(k): str(v).strip() for k, v in data.items()}
|
|
for name, text in fragments.items():
|
|
# Expanded text can later pass through str.format().
|
|
if "{" in text or "}" in text:
|
|
raise ValueError(f"Shared prompt fragment {lang}/{name} must not contain braces")
|
|
return fragments
|
|
|
|
|
|
def clear_shared_cache() -> None:
|
|
"""Forget loaded fragments so the next lookup rereads ``fragments/*.yaml``."""
|
|
_fragments.cache_clear()
|
|
|
|
|
|
def _lang(language: str | None) -> str:
|
|
code = str(language or "en").lower()
|
|
return "zh" if code.startswith(("zh", "cn")) else "en"
|
|
|
|
|
|
def shared_fragment(name: str, language: str | None = "en") -> str:
|
|
"""Return shared rule *name* in *language* (English when not translated)."""
|
|
lang = _lang(language)
|
|
text = _fragments(lang).get(name) or _fragments("en").get(name)
|
|
if text is None:
|
|
raise KeyError(f"Unknown shared prompt fragment: {name}")
|
|
return text
|
|
|
|
|
|
def expand_shared(value: Any, language: str | None) -> Any:
|
|
"""Replace every ``{{shared:<name>}}`` marker inside a loaded prompt pack.
|
|
|
|
An unknown name raises :class:`KeyError` and a marker that does not match
|
|
``{{shared:<lowercase_name>}}`` raises :class:`ValueError`: a typo in a
|
|
prompt pack must fail the load, not reach the model as literal text.
|
|
"""
|
|
if isinstance(value, str):
|
|
if "{{shared:" not in value:
|
|
return value
|
|
expanded = _MARKER.sub(lambda m: shared_fragment(m.group(1), language), value)
|
|
if "{{shared:" in expanded:
|
|
start = expanded.index("{{shared:")
|
|
raise ValueError(f"Malformed shared prompt marker: {expanded[start : start + 40]!r}")
|
|
return expanded
|
|
if isinstance(value, dict):
|
|
return {k: expand_shared(v, language) for k, v in value.items()}
|
|
if isinstance(value, list):
|
|
return [expand_shared(v, language) for v in value]
|
|
return value
|