Spaces:
Sleeping
Sleeping
Implement core RAG pipeline: PDF parsing, vector index, and rule expert
Browse files- src/ingestion/pdf.py: PyMuPDF-based PDF parser with section detection
and token-aware chunking (~500 tokens, 50 overlap)
- src/rag/vectorstore.py: ChromaDB vector store with OpenAI embeddings
(text-embedding-3-small), build and retrieve functions
- scripts/build_index.py: End-to-end pipeline script (PDF → chunks → index)
- src/expert/query.py: Rule expert using RAG + Claude API (Sonnet)
with structured answers and source citations
- prompts/expert/base.md: Add language-matching instruction
(answer language matches question language)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Files changed (5)
- prompts/expert/base.md+1
- scripts/build_index.py+29-17
- src/expert/query.py+99-11
- src/ingestion/pdf.py+187-24
- src/rag/vectorstore.py+105-9
9 unmodified lines1011121314159 unmodified lines- Wenn eine Regel unklar oder nicht im vorliegenden Material steht, sage das deutlich- Halte Antworten kurz und direkt – keine unnötigen Einleitungen- Interpretiere keine Regeln frei – bleib strikt beim Regeltext## Kontext (aus Regelwerk / FAQ)9 unmodified lines101112131415169 unmodified lines- Wenn eine Regel unklar oder nicht im vorliegenden Material steht, sage das deutlich- Halte Antworten kurz und direkt – keine unnötigen Einleitungen- Interpretiere keine Regeln frei – bleib strikt beim Regeltext- WICHTIG: Antworte IMMER in der Sprache der Frage. Deutsche Frage → Deutsche Antwort. English question → English answer.## Kontext (aus Regelwerk / FAQ)
4 unmodified lines5678910111213141516171819202122232425262728293031321 unmodified line3435363738394 unmodified linesVerwendung:python scripts/build_index.py --game stalkerPipeline:1. PDFs aus data/raw/<game>/ lesen2. Text extrahieren und in Chunks aufteilen (src/ingestion/pdf.py)3. Chunks in ChromaDB indexieren (src/rag/vectorstore.py)TODO:- Pipeline orchestrieren- Fortschrittsanzeige (tqdm)- Inkrementelles Update (nur neue Dokumente indexieren)"""import argparsedef build_game_index(game: str) -> None:"""Vollständige Pipeline: PDF-Dateien → Chunks → Vektordatenbank.Args:game: Spielname (z.B. "stalker")"""raise NotImplementedError("TODO: Pipeline orchestrieren")if __name__ == "__main__":1 unmodified lineparser.add_argument("--game", required=True, help="Spielname (z.B. stalker)")args = parser.parse_args()print(f"Baue Index für '{args.game}'...")build_game_index(args.game)print("Fertig.")4 unmodified lines567891011121314151617181920212223242526272829303132333435363738394041424344451 unmodified line47484950514 unmodified linesVerwendung:python scripts/build_index.py --game stalker"""import argparseimport osfrom tqdm import tqdmfrom src.ingestion.pdf import parse_pdffrom src.rag.vectorstore import build_indexdef build_game_index(game: str, data_dir: str = "data/raw") -> None:"""Vollständige Pipeline: PDF-Dateien → Chunks → Vektordatenbank."""game_dir = os.path.join(data_dir, game)if not os.path.isdir(game_dir):raise FileNotFoundError(f"Kein Datenverzeichnis: {game_dir}")pdf_files = [f for f in sorted(os.listdir(game_dir)) if f.endswith(".pdf")]if not pdf_files:raise FileNotFoundError(f"Keine PDFs in {game_dir}")print(f"Verarbeite {len(pdf_files)} PDFs für '{game}'...\n")all_chunks = []for filename in pdf_files:pdf_path = os.path.join(game_dir, filename)print(f" 📄 {filename}")chunks = parse_pdf(pdf_path, game)print(f" → {len(chunks)} Chunks")all_chunks.extend(chunks)print(f"\nGesamt: {len(all_chunks)} Chunks")print(f"\nBaue Vektorindex auf...")build_index(all_chunks, game)if __name__ == "__main__":1 unmodified lineparser.add_argument("--game", required=True, help="Spielname (z.B. stalker)")args = parser.parse_args()build_game_index(args.game)print("\nFertig.")
10 unmodified lines111213141516171819202122232425262728293031323334353637383940419 unmodified lines5152535455565758596010 unmodified linesresult = answer_question("Wie viele Aktionen hat ein Spieler?", game="stalker")print(result["answer"])print(result["sources"])TODO:- Prompt aus prompts/expert/base.md laden- Chunks via src/rag/vectorstore.retrieve() holen- Claude API aufrufen (claude-sonnet-4)- Antwort mit Quellen strukturiert zurückgeben"""import argparsedef answer_question(question: str, game: str) -> dict:"""Beantwortet eine Regelfrage mit Quellenangabe.Args:question: Die Regelfragegame: Spielname (z.B. "stalker")Returns:Dict mit:- answer (str): Die Regelantwort- sources (list[str]): Quellen (z.B. ["Regelwerk S.12", "FAQ S.2"])- chunks (list[dict]): Die verwendeten RAG-Chunks (für Debug)"""raise NotImplementedError("TODO: RAG + Claude API Integration")if __name__ == "__main__":9 unmodified lineselse:print(f"Regelexperte für {args.game} gestartet. Eingabe mit ENTER, beenden mit 'exit'.\n")while True:question = input("Frage: ").strip()if question.lower() in ("exit", "quit", "q"):breakif question:result = answer_question(question, args.game)print(f"\n{result['answer']}")print(f"Quellen: {', '.join(result['sources'])}\n")10 unmodified lines11121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251269 unmodified lines13613713813914014114214314414514614714810 unmodified linesresult = answer_question("Wie viele Aktionen hat ein Spieler?", game="stalker")print(result["answer"])print(result["sources"])"""import argparseimport osimport reimport anthropicfrom dotenv import load_dotenvfrom src.rag.vectorstore import retrieveload_dotenv()PROMPT_PATH = os.path.join(os.path.dirname(__file__), "..", "..", "prompts", "expert", "base.md")MODEL = "claude-sonnet-4-20250514"# Spielnamen-Mapping für den PromptGAME_DISPLAY_NAMES = {"stalker": "S.T.A.L.K.E.R. The Board Game",}_client = Nonedef _get_client() -> anthropic.Anthropic:global _clientif _client is None:_client = anthropic.Anthropic()return _clientdef _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 sourcesdef answer_question(question: str, game: str, k: int = 6) -> dict:"""Beantwortet eine Regelfrage mit Quellenangabe.Args:question: Die Regelfragegame: Spielname (z.B. "stalker")k: Anzahl der RAG-ChunksReturns:Dict mit:- answer (str): Die Regelantwort- sources (list[str]): Quellen- chunks (list[dict]): Die verwendeten RAG-Chunks (für Debug)"""# 1. Relevante Chunks holenchunks = retrieve(question, game, k=k)# 2. Prompt zusammenbauenprompt_template = _load_prompt()display_name = GAME_DISPLAY_NAMES.get(game, game)context = _format_chunks(chunks)# System-Teil und User-Teil trennensystem_prompt = prompt_template.split("## Kontext")[0]system_prompt = system_prompt.replace("{{spielname}}", display_name)# Alles nach "## System Prompt" als System-Prompt verwendensystem_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 aufrufenclient = _get_client()response = client.messages.create(model=MODEL,max_tokens=1024,system=system_prompt,messages=[{"role": "user", "content": user_message}],)answer = response.content[0].textsources = _extract_sources(chunks)return {"answer": answer,"sources": sources,"chunks": chunks,}if __name__ == "__main__":9 unmodified lineselse: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):breakif question.lower() in ("exit", "quit", "q"):breakif question:result = answer_question(question, args.game)print(f"\n{result['answer']}")print(f"\nQuellen: {', '.join(result['sources'])}\n")
4 unmodified lines56789101112131415161718192021222324252627282930313233347 unmodified lines42434445464748495051525354555657584 unmodified linesVerwendung:from src.ingestion.pdf import parse_pdfchunks = parse_pdf("data/raw/stalker/rulebook_v1.pdf", game="stalker")TODO:- pdfplumber für Text-Extraktion mit Seitenzahlen- Abschnittserkennung anhand Schriftgröße / Fettschrift- Chunking mit ~500 Tokens, 50 Token Überlapp- Chunk-Grenzen immer an Absatz-/Abschnittsgrenzen- Metadaten: source, page, section, game"""def parse_pdf(pdf_path: str, game: str) -> list[dict]:"""Parst ein PDF und gibt eine Liste von Chunks zurück.Args:pdf_path: Pfad zur PDF-Dateigame: Spielname (z.B. "stalker")Returns:Liste von Chunk-Dicts mit Feldern:id, source, page, section, text, game"""raise NotImplementedError("TODO: Implementierung mit pdfplumber")def chunk_text(7 unmodified lines) -> list[dict]:"""Teilt Text in RAG-kompatible Chunks auf.Args:text: Der zu teilende Textpage: Seitenzahl (für Quellenangaben)section: Abschnittsname (z.B. "Players Phase")source: Quelldokument (z.B. "rulebook_v1")game: Spielnamechunk_size: Maximale Chunk-Größe in Tokensoverlap: Überlapp zwischen Chunks in TokensReturns:Liste von Chunk-Dicts"""raise NotImplementedError("TODO: Chunking-Logik mit tiktoken")4 unmodified lines5678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777 unmodified lines8586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202214 unmodified linesVerwendung:from src.ingestion.pdf import parse_pdfchunks = parse_pdf("data/raw/stalker/STALKER_rules.pdf", game="stalker")"""import osimport reimport unicodedataimport fitz # PyMuPDFimport tiktoken# Tokenizer für Chunk-Größenberechnung_enc = tiktoken.encoding_for_model("gpt-4")def _clean_text(text: str) -> str:"""Bereinigt extrahierten PDF-Text von Artefakten."""# Garbled Unicode-Header/Footer-Artefakte entfernen (z.B. ǽǻ | T½aü«Ä£...)text = re.sub(r"^[^\n]*[½¼¾«»æÞÄ£ɮɫȅȆƄƨȷ]{3,}[^\n]*$", "", text, flags=re.MULTILINE)# Seitenzahl-Footer entfernen (z.B. "12 | Mission Map | Tiles & Spaces |")text = re.sub(r"^\d+\s*\|[^\n]*\|?\s*$", "", text, flags=re.MULTILINE)# Mehrfache Leerzeilen zusammenfassentext = re.sub(r"\n{3,}", "\n\n", text)return text.strip()def _detect_sections(doc: fitz.Document) -> list[dict]:"""Extrahiert Seiten mit Abschnittserkennung basierend auf Schriftgröße.Returns:Liste von dicts: {page, section, text}"""pages = []current_section = "Introduction"for page_num in range(len(doc)):page = doc[page_num]text = page.get_text()if not text or len(text.strip()) < 20:continue# Abschnittserkennung: Suche nach großen/fetten Überschriftenblocks = page.get_text("dict")["blocks"]for block in blocks:if "lines" not in block:continuefor line in block["lines"]:for span in line["spans"]:# Große Schrift (>= 14pt) und Großbuchstaben = Section Headerif span["size"] >= 14 and span["text"].strip():candidate = span["text"].strip()# Nur sinnvolle Überschriften (mind. 3 Buchstaben, nicht nur Zahlen)if len(candidate) >= 3 and re.search(r"[A-Za-z]{3,}", candidate):current_section = candidatecleaned = _clean_text(text)if cleaned:pages.append({"page": page_num + 1, # 1-basiert"section": current_section,"text": cleaned,})return pagesdef _token_count(text: str) -> int:return len(_enc.encode(text))def chunk_text(7 unmodified lines) -> list[dict]:"""Teilt Text in RAG-kompatible Chunks auf.Grenzen werden an Absätzen/Sätzen ausgerichtet."""if _token_count(text) <= chunk_size:return [{"id": f"{source}_p{page}_chunk0","source": source,"page": page,"section": section,"text": text,"game": game,}]# An Absätzen splittenparagraphs = re.split(r"\n\n+", text)chunks = []current_chunk = ""chunk_idx = 0for para in paragraphs:para = para.strip()if not para:continuecandidate = (current_chunk + "\n\n" + para).strip() if current_chunk else paraif _token_count(candidate) <= chunk_size:current_chunk = candidateelse:# Aktuellen Chunk speichernif current_chunk:chunks.append({"id": f"{source}_p{page}_chunk{chunk_idx}","source": source,"page": page,"section": section,"text": current_chunk,"game": game,})chunk_idx += 1# Overlap: letzte Sätze für Kontext mitnehmensentences = re.split(r"(?<=[.!?])\s+", current_chunk)overlap_text = ""for s in reversed(sentences):candidate_overlap = (s + " " + overlap_text).strip()if _token_count(candidate_overlap) <= overlap:overlap_text = candidate_overlapelse:breakcurrent_chunk = (overlap_text + "\n\n" + para).strip() if overlap_text else paraelse:# Einzelner Paragraph ist zu groß -> Satz-weise splittensentences = re.split(r"(?<=[.!?])\s+", para)for sent in sentences:candidate = (current_chunk + " " + sent).strip() if current_chunk else sentif _token_count(candidate) <= chunk_size:current_chunk = candidateelse:if current_chunk:chunks.append({"id": f"{source}_p{page}_chunk{chunk_idx}","source": source,"page": page,"section": section,"text": current_chunk,"game": game,})chunk_idx += 1current_chunk = sent# Letzten Chunk speichernif current_chunk:chunks.append({"id": f"{source}_p{page}_chunk{chunk_idx}","source": source,"page": page,"section": section,"text": current_chunk,"game": game,})return chunksdef parse_pdf(pdf_path: str, game: str, chunk_size: int = 500, overlap: int = 50) -> list[dict]:"""Parst ein PDF und gibt eine Liste von Chunks zurück.Args:pdf_path: Pfad zur PDF-Dateigame: Spielname (z.B. "stalker")chunk_size: Maximale Chunk-Größe in Tokensoverlap: Überlapp zwischen Chunks in TokensReturns:Liste von Chunk-Dicts mit Feldern:id, source, page, section, text, game"""source = os.path.splitext(os.path.basename(pdf_path))[0]doc = fitz.open(pdf_path)pages = _detect_sections(doc)all_chunks = []for page_data in pages:chunks = chunk_text(text=page_data["text"],page=page_data["page"],section=page_data["section"],source=source,game=game,chunk_size=chunk_size,overlap=overlap,)all_chunks.extend(chunks)return all_chunksif __name__ == "__main__":import jsonimport sysif len(sys.argv) < 2:print("Verwendung: python -m src.ingestion.pdf <pdf_path> [game]")sys.exit(1)pdf_path = sys.argv[1]game = sys.argv[2] if len(sys.argv) > 2 else "stalker"chunks = parse_pdf(pdf_path, game)print(f"Extrahiert: {len(chunks)} Chunks aus {pdf_path}")for c in chunks[:3]:print(f"\n--- {c['id']} (S.{c['page']}, {c['section']}) ---")print(c["text"][:200] + "...")
6 unmodified lines789101112131415161718194 unmodified lines242526272829306 unmodified lines3738394041426 unmodified linesfrom src.rag.vectorstore import build_index, retrievebuild_index(chunks, game="stalker")results = retrieve("Wie viele Aktionen hat ein Spieler?", game="stalker")TODO:- ChromaDB lokal aufsetzen (data/processed/<game>/chroma_db/)- Embedding-Funktion: OpenAI text-embedding-3-small- Hybrid Search: Semantisch (Embeddings) + Keyword (BM25)- Reranking nach Abschnitt-Relevanz"""def build_index(chunks: list[dict], game: str) -> None:4 unmodified lineschunks: Liste von Chunk-Dicts (aus src/ingestion/pdf.py)game: Spielname – bestimmt den Speicherort"""raise NotImplementedError("TODO: ChromaDB Indexierung")def retrieve(query: str, game: str, k: int = 5) -> list[dict]:6 unmodified linesk: Anzahl zurückzugebender ChunksReturns:Liste der k relevantesten Chunks mit Metadaten"""raise NotImplementedError("TODO: Retrieval-Logik")6 unmodified lines789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960614 unmodified lines666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071086 unmodified lines1151161171181191201211221231241251261271281291301311321331341351361371386 unmodified linesfrom src.rag.vectorstore import build_index, retrievebuild_index(chunks, game="stalker")results = retrieve("Wie viele Aktionen hat ein Spieler?", game="stalker")"""import osimport chromadbimport openaifrom dotenv import load_dotenvload_dotenv()CHROMA_BASE_DIR = "data/processed"EMBEDDING_MODEL = "text-embedding-3-small"COLLECTION_PREFIX = "rules"_openai_client = Nonedef _get_openai_client() -> openai.OpenAI:global _openai_clientif _openai_client is None:_openai_client = openai.OpenAI()return _openai_clientdef _embed(texts: list[str]) -> list[list[float]]:"""Erzeugt Embeddings via OpenAI API."""client = _get_openai_client()# OpenAI erlaubt max 2048 Inputs pro Requestall_embeddings = []batch_size = 512for i in range(0, len(texts), batch_size):batch = texts[i : i + batch_size]resp = client.embeddings.create(model=EMBEDDING_MODEL, input=batch)all_embeddings.extend([d.embedding for d in resp.data])return all_embeddingsdef _get_chroma_client(game: str) -> chromadb.ClientAPI:persist_dir = os.path.join(CHROMA_BASE_DIR, game, "chroma_db")os.makedirs(persist_dir, exist_ok=True)return chromadb.PersistentClient(path=persist_dir)def _get_collection(game: str) -> chromadb.Collection:client = _get_chroma_client(game)collection_name = f"{COLLECTION_PREFIX}_{game}"return client.get_or_create_collection(name=collection_name,metadata={"hnsw:space": "cosine"},)def build_index(chunks: list[dict], game: str) -> None:4 unmodified lineschunks: Liste von Chunk-Dicts (aus src/ingestion/pdf.py)game: Spielname – bestimmt den Speicherort"""collection = _get_collection(game)# Bestehende Daten löschen für sauberen Rebuildexisting = collection.count()if existing > 0:print(f" Lösche {existing} bestehende Einträge...")all_ids = collection.get()["ids"]collection.delete(ids=all_ids)texts = [c["text"] for c in chunks]ids = [c["id"] for c in chunks]metadatas = [{"source": c["source"],"page": c["page"],"section": c["section"],"game": c["game"],}for c in chunks]print(f" Erstelle Embeddings für {len(texts)} Chunks...")embeddings = _embed(texts)print(f" Indexiere in ChromaDB...")# ChromaDB erlaubt max ~41666 pro upsertbatch_size = 500for i in range(0, len(ids), batch_size):end = min(i + batch_size, len(ids))collection.add(ids=ids[i:end],embeddings=embeddings[i:end],documents=texts[i:end],metadatas=metadatas[i:end],)print(f" ✓ {len(ids)} Chunks indexiert in '{collection.name}'")def retrieve(query: str, game: str, k: int = 5) -> list[dict]:6 unmodified linesk: Anzahl zurückzugebender ChunksReturns:Liste der k relevantesten Chunks mit Metadaten und Score"""collection = _get_collection(game)query_embedding = _embed([query])[0]results = collection.query(query_embeddings=[query_embedding],n_results=k,include=["documents", "metadatas", "distances"],)chunks = []for i in range(len(results["ids"][0])):chunks.append({"id": results["ids"][0][i],"text": results["documents"][0][i],"score": 1 - results["distances"][0][i], # Cosine similarity**results["metadatas"][0][i],})return chunks
prompts/expert/base.md+1
scripts/build_index.py+29-17
src/expert/query.py+99-11
src/ingestion/pdf.py+187-24
src/rag/vectorstore.py+105-9