Spaces:
Sleeping
Sleeping
Download src/expert/query.py from FC-Bit/arkanum: direct link, hf CLI and curl.
- Browser
- Download file 4.46 kB
-
https://huggingface.co/spaces/FC-Bit/arkanum/resolve/main/src/expert/query.py
- Command line
-
hf download hf://spaces/FC-Bit/arkanum/src/expert/query.py
-
curl -L -o query.py https://huggingface.co/spaces/FC-Bit/arkanum/resolve/main/src/expert/query.py
4.46 kB
| """ | |
| Regelexperte – Textbasierte Abfragen | |
| ===================================== | |
| Beantwortet Regelfragen mit Quellenangabe via RAG + Claude API. | |
| Verwendung (CLI): | |
| python src/expert/query.py --game stalker --question "Wie viele Aktionen hat ein Spieler?" | |
| Verwendung (als Modul): | |
| from src.expert.query import answer_question | |
| result = answer_question("Wie viele Aktionen hat ein Spieler?", game="stalker") | |
| print(result["answer"]) | |
| print(result["sources"]) | |
| """ | |
| import argparse | |
| 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", "base.md") | |
| MODEL = "claude-sonnet-4-20250514" | |
| # Spielnamen-Mapping für den Prompt | |
| 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: | |
| """Formatiert RAG-Chunks als Kontext für den Prompt.""" | |
| 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]: | |
| """Extrahiert eindeutige Quellenangaben aus Chunks.""" | |
| 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_question(question: str, game: str, k: int = 6) -> dict: | |
| """ | |
| Beantwortet eine Regelfrage mit Quellenangabe. | |
| Args: | |
| question: Die Regelfrage | |
| game: Spielname (z.B. "stalker") | |
| k: Anzahl der RAG-Chunks | |
| Returns: | |
| Dict mit: | |
| - answer (str): Die Regelantwort | |
| - sources (list[str]): Quellen | |
| - chunks (list[dict]): Die verwendeten RAG-Chunks (für Debug) | |
| """ | |
| # 1. Relevante Chunks holen | |
| chunks = retrieve(question, game, k=k) | |
| # 2. Prompt zusammenbauen | |
| prompt_template = _load_prompt() | |
| display_name = GAME_DISPLAY_NAMES.get(game, game) | |
| context = _format_chunks(chunks) | |
| # System-Teil und User-Teil trennen | |
| system_prompt = prompt_template.split("## Kontext")[0] | |
| system_prompt = system_prompt.replace("{{spielname}}", display_name) | |
| # Alles nach "## System Prompt" als System-Prompt verwenden | |
| system_prompt = re.sub(r"^#.*?\n+", "", system_prompt).strip() | |
| user_message = ( | |
| f"## Kontext (aus Regelwerk / FAQ)\n\n{context}\n\n" | |
| f"## Frage\n\n{question}" | |
| ) | |
| # 3. Claude API aufrufen | |
| client = _get_client() | |
| response = client.messages.create( | |
| model=MODEL, | |
| max_tokens=1024, | |
| system=system_prompt, | |
| messages=[{"role": "user", "content": user_message}], | |
| ) | |
| answer = response.content[0].text | |
| sources = _extract_sources(chunks) | |
| return { | |
| "answer": answer, | |
| "sources": sources, | |
| "chunks": chunks, | |
| } | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description="Regelexperte – interaktive Abfrage") | |
| parser.add_argument("--game", required=True, help="Spielname (z.B. stalker)") | |
| parser.add_argument("--question", help="Direkte Frage (optional, sonst interaktiv)") | |
| args = parser.parse_args() | |
| if args.question: | |
| result = answer_question(args.question, args.game) | |
| print(f"\n{result['answer']}\n") | |
| print(f"Quellen: {', '.join(result['sources'])}") | |
| else: | |
| print(f"Regelexperte für {args.game} gestartet. Eingabe mit ENTER, beenden mit 'exit'.\n") | |
| while True: | |
| try: | |
| question = input("Frage: ").strip() | |
| except (EOFError, KeyboardInterrupt): | |
| break | |
| if question.lower() in ("exit", "quit", "q"): | |
| break | |
| if question: | |
| result = answer_question(question, args.game) | |
| print(f"\n{result['answer']}") | |
| print(f"\nQuellen: {', '.join(result['sources'])}\n") | |