File size: 1,848 Bytes
ad8bc9a
 
 
5324a16
ad8bc9a
 
 
 
 
45b7965
ad8bc9a
5324a16
 
 
 
 
 
 
 
 
 
ad8bc9a
 
 
 
 
 
 
 
 
 
5324a16
 
 
 
 
 
 
 
 
 
 
 
ad8bc9a
 
 
5324a16
45b7965
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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)