from __future__ import annotations import json import os from functools import lru_cache from pathlib import Path from typing import Any KNOWLEDGE_PATH = Path(__file__).resolve().parent.parent / "data" / "website_knowledge.json" SYSTEM_PROMPT_PATH = Path(__file__).resolve().parent.parent / "data" / "fuugi_system_prompt.md" # Minimal public fallback if FUUGI_SYSTEM_PROMPT secret / file missing. _FALLBACK_PROMPT = """You are Fuugi, the public AI companion for 2B Entertainment. Be natural, direct, calm, precise, and warm. Match the user language. Use the website knowledge JSON below when answering about 2B Entertainment. Do not invent private credentials or internal systems. Website knowledge (JSON): {knowledge} """ @lru_cache(maxsize=1) def load_knowledge() -> dict[str, Any]: with KNOWLEDGE_PATH.open(encoding="utf-8") as handle: data = json.load(handle) if not isinstance(data, dict) or data.get("snapshot_version") != 1: raise RuntimeError("Website knowledge snapshot is invalid.") return data def _load_template() -> str: env = (os.environ.get("FUUGI_SYSTEM_PROMPT") or "").strip() if env and "{knowledge}" in env: return env if SYSTEM_PROMPT_PATH.is_file(): text = SYSTEM_PROMPT_PATH.read_text(encoding="utf-8").strip() # Ignore stub files that lack the placeholder if text and "{knowledge}" in text and not text.startswith("# STUB"): return text return _FALLBACK_PROMPT @lru_cache(maxsize=1) def system_prompt() -> str: serialized = json.dumps(load_knowledge(), ensure_ascii=True, separators=(",", ":")) template = _load_template() if template.count("{knowledge}") != 1: raise RuntimeError("Fuugi system prompt must contain exactly one knowledge placeholder.") return template.replace("{knowledge}", serialized)