""" Walkthrough Step-Expander ========================== Lädt Walkthrough-Definitionen und expandiert einzelne Steps via RAG + Claude zu natürlichem Sprechtext. Verwendung: from src.expert.walkthrough import load_walkthrough, expand_step wt = load_walkthrough("stalker") text = expand_step("stalker", "campaign", "overview", "welcome", "de") """ import json import os import re import anthropic from dotenv import load_dotenv from src.rag.vectorstore import retrieve load_dotenv() WALKTHROUGH_DIR = os.path.join( os.path.dirname(__file__), "..", "..", "data", "walkthrough" ) PROMPTS_DIR = os.path.join( os.path.dirname(__file__), "..", "..", "prompts" ) MODEL = "claude-sonnet-4-20250514" GAME_DISPLAY_NAMES = { "stalker": "S.T.A.L.K.E.R. The Board Game", } _client = None def _get_client() -> anthropic.Anthropic: global _client if _client is None: _client = anthropic.Anthropic() return _client def load_walkthrough(game: str) -> dict: """Lädt die Walkthrough-Definition für ein Spiel.""" path = os.path.join(WALKTHROUGH_DIR, f"{game}.json") with open(path, "r", encoding="utf-8") as f: return json.load(f) def _load_prompt_template(template_name: str) -> str: """Lädt ein Prompt-Template aus prompts/.""" path = os.path.join(PROMPTS_DIR, f"{template_name}.md") with open(path, "r", encoding="utf-8") as f: return f.read() def _find_step(walkthrough: dict, mode: str, phase_id: str, step_id: str) -> dict | None: """Findet einen Step in der Walkthrough-Definition.""" mode_data = walkthrough.get("modes", {}).get(mode) if not mode_data: return None for phase in mode_data.get("phases", []): if phase["id"] == phase_id: for step in phase.get("steps", []): if step["id"] == step_id: return step return None def _format_rag_context(chunks: list[dict]) -> str: """Formatiert RAG-Chunks als Kontext.""" parts = [] for i, chunk in enumerate(chunks, 1): source_label = chunk["source"].replace("_", " ") parts.append( f"### Quelle {i}: {source_label}, Seite {chunk['page']} " f"({chunk['section']})\n\n{chunk['text']}" ) return "\n\n---\n\n".join(parts) def expand_step( game: str, mode: str, phase_id: str, step_id: str, lang: str = "de", ) -> dict: """ Expandiert einen Walkthrough-Step zu natürlichem Sprechtext. Args: game: Spielname (z.B. "stalker") mode: Spielmodus ("campaign" oder "zone_survival") phase_id: Phase-ID (z.B. "overview") step_id: Step-ID (z.B. "welcome") lang: Sprache ("de" oder "en") Returns: Dict mit: - text (str): Generierter Sprechtext - sources (list[str]): Verwendete Quellen """ walkthrough = load_walkthrough(game) step = _find_step(walkthrough, mode, phase_id, step_id) if not step: return {"text": "Schritt nicht gefunden.", "sources": []} # RAG-Kontext holen all_chunks = [] for query in step.get("rag_queries", []): chunks = retrieve(query, game, k=3) all_chunks.extend(chunks) # Duplikate entfernen (nach ID) seen_ids = set() unique_chunks = [] for c in all_chunks: if c["id"] not in seen_ids: seen_ids.add(c["id"]) unique_chunks.append(c) # Prompt-Template laden und füllen template = _load_prompt_template(step["prompt_template"]) display_name = GAME_DISPLAY_NAMES.get(game, game) mode_title = walkthrough["modes"][mode]["title"] rag_context = _format_rag_context(unique_chunks) if unique_chunks else "Kein zusätzlicher Kontext verfügbar." # Template-Variablen ersetzen prompt_text = template prompt_text = prompt_text.replace("{{spielname}}", display_name) prompt_text = prompt_text.replace("{{modus}}", mode_title) prompt_text = prompt_text.replace("{{kontext}}", rag_context) prompt_text = prompt_text.replace("{{sprache}}", "Deutsch" if lang == "de" else "English") # Zusätzliche step-spezifische Variablen for key, value in step.get("variables", {}).items(): prompt_text = prompt_text.replace(f"{{{{{key}}}}}", str(value)) # System-Prompt vom User-Prompt trennen (am ersten ## Kontext oder ## Aufgabe) system_part = re.split(r"\n##\s+(Kontext|Aufgabe)", prompt_text)[0].strip() # Bereinige Markdown-Header aus System-Teil system_part = re.sub(r"^#.*?\n+", "", system_part).strip() user_part = f"## Regelwerk-Kontext\n\n{rag_context}\n\nGeneriere jetzt den Sprechtext für diesen Schritt." # Claude API aufrufen client = _get_client() response = client.messages.create( model=MODEL, max_tokens=1024, system=system_part, messages=[{"role": "user", "content": user_part}], ) text = response.content[0].text # Quellen extrahieren sources = [] seen_sources = set() for c in unique_chunks: label = f"{c['source'].replace('_', ' ')} S.{c['page']}" if label not in seen_sources: seen_sources.add(label) sources.append(label) return {"text": text, "sources": sources} def get_prerendered_step(game: str, mode: str, phase_id: str, step_id: str) -> dict | None: """ Lädt einen vorgerenderten Walkthrough-Step. Returns: Dict mit text, sources, audio_url oder None wenn nicht vorhanden. """ base = os.path.join(WALKTHROUGH_DIR, "prerendered", game, mode) filename = f"{phase_id}__{step_id}" json_path = os.path.join(base, f"{filename}.json") audio_path = os.path.join(base, f"{filename}.mp3") if not os.path.exists(json_path): return None with open(json_path, "r", encoding="utf-8") as f: data = json.load(f) result = {"text": data["text"], "sources": data.get("sources", [])} if os.path.exists(audio_path): result["audio_url"] = f"/api/walkthrough/audio/{game}/{mode}/{phase_id}/{step_id}" return result