asa / scripts /lib /chat /prompt_loader.py
defenestrate's picture
ASA Space: squashed history (instructions and settings live in the private pack)
526950e
Raw History Blame Contribute Delete
3.41 kB
"""Read chat-tutor prompts from prompts/student-chat/*.md.
The seven section names are fixed in PROMPT_NAMES; load_prompt() rejects
any other name to make the boundary explicit (path traversal, typos,
arbitrary callers all fail loud).
Bundle hashing — load_prompt_manifest() and load_prompt_bundle_id() —
lives in this module too (added in Task 3) so the loader is the single
source of truth for "which prompts exist and what they say."
"""
from __future__ import annotations
import hashlib
import json
from pathlib import Path
from scripts.lib.runtime_config import PROMPT_ROOT
PROMPT_NAMES: tuple[str, ...] = (
"baseline_name_guardrail",
"sources_footer_instructions",
"assessment_aware",
"explain_mode",
"role_description",
"faculty_voice_and_framing",
"course_context",
"authenticated_instructor",
"review_mode",
"user_notes",
)
# Test affordance: when set, replaces the default path resolution.
# Production code never assigns to this. Tests set it to a tmp_path.
_PROMPT_ROOT: Path | None = None
# Cache of (name -> body). Populated lazily on first read.
_CACHE: dict[str, str] = {}
def _resolve_root() -> Path:
"""Return the directory holding prompts/student-chat/*.md."""
if _PROMPT_ROOT is not None:
return _PROMPT_ROOT
return PROMPT_ROOT
_BUNDLE_ID_CACHE: list[str] = [] # one-element holder; cleared by _reset_cache
def _reset_cache() -> None:
"""Clear the module-level cache. Intended for tests."""
_CACHE.clear()
_BUNDLE_ID_CACHE.clear()
def load_prompt(name: str) -> str:
"""Read prompts/student-chat/<name>.md, cached after first call.
Raises ValueError if `name` is not in PROMPT_NAMES.
Raises FileNotFoundError if the file is missing.
Returns the file body with trailing whitespace stripped.
"""
if name not in PROMPT_NAMES:
raise ValueError(
f"{name!r} is not a registered prompt. "
f"Valid names: {PROMPT_NAMES}"
)
cached = _CACHE.get(name)
if cached is not None:
return cached
path = _resolve_root() / f"{name}.md"
body = path.read_text(encoding="utf-8").rstrip()
_CACHE[name] = body
return body
def load_prompt_manifest() -> list[dict]:
"""Return ordered metadata for all PROMPT_NAMES.
Each entry: {"name": str, "path": str, "sha256": str}. The path is
REPO-RELATIVE ("prompts/student-chat/<name>.md") so the manifest is
identical in this repo and in the HF Space — absolute paths would
make the bundle id environment-dependent.
"""
manifest: list[dict] = []
for name in PROMPT_NAMES:
body = load_prompt(name)
digest = hashlib.sha256(body.encode("utf-8")).hexdigest()
manifest.append({
"name": name,
"path": f"prompts/student-chat/{name}.md",
"sha256": f"sha256:{digest}",
})
return manifest
def load_prompt_bundle_id() -> str:
"""Stable sha256 over the ordered prompt manifest.
Cached at the loader level. Tests call _reset_cache() to invalidate.
"""
if _BUNDLE_ID_CACHE:
return _BUNDLE_ID_CACHE[0]
payload = json.dumps(
load_prompt_manifest(),
sort_keys=True,
ensure_ascii=False,
).encode("utf-8")
digest = hashlib.sha256(payload).hexdigest()
bid = f"sha256:{digest}"
_BUNDLE_ID_CACHE.append(bid)
return bid