Spaces:
Sleeping
Sleeping
File size: 5,862 Bytes
ebf20cf 8a2dc22 037b655 08f87f1 037b655 08f87f1 ebf20cf 08f87f1 037b655 08f87f1 037b655 08f87f1 037b655 08f87f1 037b655 08f87f1 037b655 08f87f1 037b655 8a2dc22 ebf20cf 08f87f1 ebf20cf 08f87f1 | 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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | """
Vektordatenbank (ChromaDB)
==========================
Speichert und durchsucht Regeltext-Chunks via Embeddings.
Verwendung:
from src.rag.vectorstore import build_index, retrieve
build_index(chunks, game="stalker")
results = retrieve("Wie viele Aktionen hat ein Spieler?", game="stalker")
"""
import json
import logging
import os
import chromadb
import openai
from dotenv import load_dotenv
logger = logging.getLogger("arkanum")
load_dotenv()
CHROMA_BASE_DIR = "data/processed"
EMBEDDING_MODEL = "text-embedding-3-small"
COLLECTION_PREFIX = "rules"
_openai_client = None
def _get_openai_client() -> openai.OpenAI:
global _openai_client
if _openai_client is None:
_openai_client = openai.OpenAI()
return _openai_client
def _embed(texts: list[str]) -> list[list[float]]:
"""Erzeugt Embeddings via OpenAI API."""
client = _get_openai_client()
# OpenAI erlaubt max 2048 Inputs pro Request
all_embeddings = []
batch_size = 512
for 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_embeddings
def _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:
"""
Baut den Vektorindex für ein Spiel auf.
Args:
chunks: Liste von Chunk-Dicts (aus src/ingestion/pdf.py)
game: Spielname – bestimmt den Speicherort
"""
collection = _get_collection(game)
client = _get_openai_client()
# Bestehende Daten löschen für sauberen Rebuild
existing = collection.count()
if existing > 0:
logger.info(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
]
# Embeddings in Batches erstellen mit Fortschritt
logger.info(f"Erstelle Embeddings für {len(texts)} Chunks...")
embeddings = []
embed_batch_size = 512
for i in range(0, len(texts), embed_batch_size):
batch = texts[i : i + embed_batch_size]
end = min(i + embed_batch_size, len(texts))
logger.info(f" Embeddings: {end}/{len(texts)} ({end * 100 // len(texts)}%)")
resp = client.embeddings.create(model=EMBEDDING_MODEL, input=batch)
embeddings.extend([d.embedding for d in resp.data])
# ChromaDB-Indexierung mit Fortschritt
logger.info(f"Indexiere {len(ids)} Chunks in ChromaDB...")
batch_size = 500
for 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],
)
logger.info(f" Indexiert: {end}/{len(ids)} ({end * 100 // len(ids)}%)")
logger.info(f"✓ {len(ids)} Chunks indexiert in '{collection.name}'")
return embeddings
def load_cached_index(game: str) -> bool:
"""Lädt den Index aus der Cache-Datei. Returns True bei Erfolg."""
cache_path = os.path.join(CHROMA_BASE_DIR, game, "index_cache.json")
if not os.path.exists(cache_path):
return False
logger.info(f"Lade Index aus Cache: {cache_path}")
with open(cache_path, "r", encoding="utf-8") as f:
cache = json.load(f)
chunks = cache["chunks"]
ids = [c["id"] for c in chunks]
texts = [c["text"] for c in chunks]
embeddings = [c["embedding"] for c in chunks]
metadatas = [
{
"source": c["source"],
"page": c["page"],
"section": c["section"],
"game": c["game"],
}
for c in chunks
]
collection = _get_collection(game)
batch_size = 500
for 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],
)
logger.info(f" Cache-Import: {end}/{len(ids)} ({end * 100 // len(ids)}%)")
logger.info(f"✓ {len(ids)} Chunks aus Cache geladen")
return True
def retrieve(query: str, game: str, k: int = 5) -> list[dict]:
"""
Sucht die k relevantesten Chunks für eine Frage.
Args:
query: Die Suchanfrage (Regelfrage des Nutzers)
game: Spielname
k: Anzahl zurückzugebender Chunks
Returns:
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
|