""" Regelexperte – Multimodale Bildanalyse ======================================= Analysiert Fotos von Spielzuständen, Karten oder Effekten und beantwortet Regelfragen via Claude multimodal + RAG. Verwendung: from src.expert.vision import answer_from_image result = answer_from_image( image_data=base64_bytes, question="Darf ich jetzt diese Aktion ausführen?", game="stalker" ) """ import base64 import os import re import anthropic from dotenv import load_dotenv from src.rag.vectorstore import retrieve load_dotenv() PROMPT_PATH = os.path.join(os.path.dirname(__file__), "..", "..", "prompts", "expert", "vision.md") 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_prompt() -> str: with open(PROMPT_PATH, "r") as f: return f.read() def _format_chunks(chunks: list[dict]) -> str: 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 _extract_sources(chunks: list[dict]) -> list[str]: seen = set() sources = [] for c in chunks: label = f"{c['source'].replace('_', ' ')} S.{c['page']}" if label not in seen: seen.add(label) sources.append(label) return sources def answer_from_image( image_data: bytes, question: str, game: str, media_type: str = "image/jpeg", k: int = 6, ) -> dict: """ Analysiert ein Spielzustand-Foto und beantwortet die Regelfrage. Zweistufig: 1. Claude beschreibt den Spielzustand auf dem Bild 2. Beschreibung + Frage werden als RAG-Query genutzt, dann kombinierte Antwort Args: image_data: Bilddaten als bytes (raw, nicht base64) question: Die Regelfrage des Spielers game: Spielname media_type: MIME-Type des Bildes k: Anzahl RAG-Chunks Returns: Dict mit situation, answer, sources, chunks """ client = _get_client() display_name = GAME_DISPLAY_NAMES.get(game, game) image_b64 = base64.standard_b64encode(image_data).decode("utf-8") # Schritt 1: Spielzustand beschreiben describe_response = client.messages.create( model=MODEL, max_tokens=512, system=( f"Du bist ein Experte für {display_name}. " "Beschreibe präzise was du auf dem Bild siehst: " "Spielkomponenten, Karten, Token, Spielzustand. " "Antworte in der Sprache der Frage." ), messages=[{ "role": "user", "content": [ { "type": "image", "source": { "type": "base64", "media_type": media_type, "data": image_b64, }, }, { "type": "text", "text": f"Beschreibe den Spielzustand auf dem Bild. Frage des Spielers: {question}", }, ], }], ) situation = describe_response.content[0].text # Schritt 2: RAG-Retrieval mit Bildbeschreibung + Frage rag_query = f"{situation}\n\n{question}" chunks = retrieve(rag_query, game, k=k) context = _format_chunks(chunks) # Schritt 3: Kombinierte Antwort mit Bild + Kontext prompt_template = _load_prompt() system_prompt = prompt_template.split("## Aufgabe")[0] system_prompt = re.sub(r"^#.*?\n+", "", system_prompt).strip() system_prompt = system_prompt.replace("{{spielname}}", display_name) answer_response = client.messages.create( model=MODEL, max_tokens=1024, system=system_prompt, messages=[{ "role": "user", "content": [ { "type": "image", "source": { "type": "base64", "media_type": media_type, "data": image_b64, }, }, { "type": "text", "text": ( f"## Erkannter Spielzustand\n\n{situation}\n\n" f"## Regeltext-Kontext\n\n{context}\n\n" f"## Frage des Spielers\n\n{question}" ), }, ], }], ) answer = answer_response.content[0].text sources = _extract_sources(chunks) return { "situation": situation, "answer": answer, "sources": sources, "chunks": chunks, }