Upload 8 files
Browse files- src/services/rag_service.py +369 -355
src/services/rag_service.py
CHANGED
|
@@ -1,355 +1,369 @@
|
|
| 1 |
-
"""Local keyword retrieval first, with an optional cached semantic index.
|
| 2 |
-
|
| 3 |
-
Initialization never needs an API key to serve the local KB. Dense failures
|
| 4 |
-
leave keyword search available; callers may run initialize in the background.
|
| 5 |
-
"""
|
| 6 |
-
import asyncio
|
| 7 |
-
import hashlib
|
| 8 |
-
import hmac
|
| 9 |
-
import json
|
| 10 |
-
import logging
|
| 11 |
-
import os
|
| 12 |
-
import re
|
| 13 |
-
import time
|
| 14 |
-
from pathlib import Path
|
| 15 |
-
from typing import List
|
| 16 |
-
|
| 17 |
-
from src.config import get_settings
|
| 18 |
-
|
| 19 |
-
logger = logging.getLogger(__name__)
|
| 20 |
-
CHUNK_WORDS = 260
|
| 21 |
-
CHUNK_OVERLAP_WORDS = 40
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
self.
|
| 44 |
-
self.
|
| 45 |
-
self.
|
| 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 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
for
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
if
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local keyword retrieval first, with an optional cached semantic index.
|
| 2 |
+
|
| 3 |
+
Initialization never needs an API key to serve the local KB. Dense failures
|
| 4 |
+
leave keyword search available; callers may run initialize in the background.
|
| 5 |
+
"""
|
| 6 |
+
import asyncio
|
| 7 |
+
import hashlib
|
| 8 |
+
import hmac
|
| 9 |
+
import json
|
| 10 |
+
import logging
|
| 11 |
+
import os
|
| 12 |
+
import re
|
| 13 |
+
import time
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import List
|
| 16 |
+
|
| 17 |
+
from src.config import get_settings
|
| 18 |
+
|
| 19 |
+
logger = logging.getLogger(__name__)
|
| 20 |
+
CHUNK_WORDS = 260
|
| 21 |
+
CHUNK_OVERLAP_WORDS = 40
|
| 22 |
+
# Space variable LIBBEE_EMBEDDING_MODEL. The cache key includes the model name,
|
| 23 |
+
# so changing it rebuilds the semantic index on the next start.
|
| 24 |
+
EMBEDDING_MODEL = os.getenv("LIBBEE_EMBEDDING_MODEL", "").strip() or "text-embedding-3-small"
|
| 25 |
+
LIBRARY_COMPOUND_NEXT = frozenset({
|
| 26 |
+
"card", "cards", "account", "accounts", "fine", "fines", "fee", "fees", "membership",
|
| 27 |
+
"hours", "loan", "loans", "privileges", "access", "website", "catalogue", "catalog",
|
| 28 |
+
"staff", "rooms", "room", "printer", "printing", "app", "id",
|
| 29 |
+
})
|
| 30 |
+
CACHE_SCHEMA = 3 # 3: library compound tokens
|
| 31 |
+
TOKEN_RE = re.compile(r"[^\W_]+(?:[-_][^\W_]+)*", re.UNICODE)
|
| 32 |
+
STOP_WORDS = {"about", "and", "are", "can", "for", "from", "how", "library", "please", "that", "the", "this", "what", "when", "where", "which", "with", "you"}
|
| 33 |
+
# Passages with no shared words are returned only below this FAISS distance
|
| 34 |
+
# (squared L2 on unit vectors: 1.0 is cosine similarity 0.5). Tune with the
|
| 35 |
+
# Space variable RAG_DENSE_ONLY_MAX_DISTANCE; 0 restores keyword-only filtering.
|
| 36 |
+
DENSE_ONLY_MAX_DISTANCE = float(os.getenv("RAG_DENSE_ONLY_MAX_DISTANCE", "1.0") or 0)
|
| 37 |
+
DENSE_ONLY_LIMIT = 2
|
| 38 |
+
HEADER_RE = re.compile(r"^(?:SOURCE|TITLE|AUTHORITY|LAST_REVIEWED|LAST_UPDATED):", re.IGNORECASE)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class RAGService:
|
| 42 |
+
def __init__(self):
|
| 43 |
+
self.vectorstore = None
|
| 44 |
+
self.bm25 = None
|
| 45 |
+
self.bm25_corpus: List[str] = []
|
| 46 |
+
self.bm25_meta: List[dict] = []
|
| 47 |
+
self._embeddings = None
|
| 48 |
+
self._ready = False
|
| 49 |
+
self._kb_hash = ""
|
| 50 |
+
self._status = "not_started"
|
| 51 |
+
self._content_to_idx: dict[str, int] = {}
|
| 52 |
+
self._init_lock = asyncio.Lock()
|
| 53 |
+
|
| 54 |
+
def is_ready(self) -> bool:
|
| 55 |
+
return self._ready
|
| 56 |
+
|
| 57 |
+
def _knowledge_dir(self) -> Path:
|
| 58 |
+
return get_settings().kb_dir
|
| 59 |
+
|
| 60 |
+
def _cache_dir(self) -> Path:
|
| 61 |
+
return get_settings().rag_cache_dir
|
| 62 |
+
|
| 63 |
+
def _hash_knowledge_base(self, txt_files: List[Path]) -> str:
|
| 64 |
+
# Deployments commonly reset mtimes. Hash content plus indexing settings
|
| 65 |
+
# so unchanged data can reuse persisted embeddings across image rebuilds.
|
| 66 |
+
digest = hashlib.sha256()
|
| 67 |
+
digest.update(f"{CACHE_SCHEMA}:{EMBEDDING_MODEL}:{CHUNK_WORDS}:{CHUNK_OVERLAP_WORDS}".encode())
|
| 68 |
+
for path in sorted(txt_files):
|
| 69 |
+
digest.update(path.name.encode("utf-8"))
|
| 70 |
+
digest.update(b"\0")
|
| 71 |
+
digest.update(path.read_bytes())
|
| 72 |
+
digest.update(b"\0")
|
| 73 |
+
return digest.hexdigest()
|
| 74 |
+
|
| 75 |
+
def _cache_paths(self) -> tuple[Path, Path, Path]:
|
| 76 |
+
cache_dir = self._cache_dir()
|
| 77 |
+
return cache_dir / "faiss_index", cache_dir / "bm25_cache.json", cache_dir / "kb_state.json"
|
| 78 |
+
|
| 79 |
+
def _cache_signature(self, faiss_dir: Path, bm25_path: Path) -> str:
|
| 80 |
+
key = get_settings().origin_token.encode("utf-8")
|
| 81 |
+
if not key:
|
| 82 |
+
return ""
|
| 83 |
+
digest = hmac.new(key, digestmod=hashlib.sha256)
|
| 84 |
+
for path in sorted([bm25_path, *faiss_dir.glob("*")]):
|
| 85 |
+
if path.is_file():
|
| 86 |
+
digest.update(path.name.encode("utf-8"))
|
| 87 |
+
digest.update(path.read_bytes())
|
| 88 |
+
return digest.hexdigest()
|
| 89 |
+
|
| 90 |
+
@staticmethod
|
| 91 |
+
def _tokens(value: str) -> List[str]:
|
| 92 |
+
tokens = TOKEN_RE.findall((value or "").casefold())
|
| 93 |
+
# "library" is a stop word because nearly every passage contains it,
|
| 94 |
+
# but in a few fixed combinations it carries the meaning ("library
|
| 95 |
+
# card" is not any card). Those pairs become one extra token, used by
|
| 96 |
+
# both the keyword ranking and the word-match check.
|
| 97 |
+
compounds = [f"library_{nxt}" for cur, nxt in zip(tokens, tokens[1:])
|
| 98 |
+
if cur == "library" and nxt in LIBRARY_COMPOUND_NEXT]
|
| 99 |
+
return tokens + compounds
|
| 100 |
+
|
| 101 |
+
def _build_reverse_index(self) -> None:
|
| 102 |
+
self._content_to_idx = {chunk.strip(): i for i, chunk in enumerate(self.bm25_corpus)}
|
| 103 |
+
|
| 104 |
+
def _build_keyword_index(self):
|
| 105 |
+
from rank_bm25 import BM25Okapi
|
| 106 |
+
files = sorted(self._knowledge_dir().glob("*.txt"))
|
| 107 |
+
kb_hash = self._hash_knowledge_base(files)
|
| 108 |
+
chunks, metadata = self._load_and_chunk_all()
|
| 109 |
+
if not chunks:
|
| 110 |
+
raise ValueError("No usable knowledge-base chunks found")
|
| 111 |
+
bm25 = BM25Okapi([self._tokens(chunk) for chunk in chunks])
|
| 112 |
+
return kb_hash, chunks, metadata, bm25
|
| 113 |
+
|
| 114 |
+
async def initialize(self, openai_api_key: str = "", *, force_rebuild: bool = False) -> None:
|
| 115 |
+
async with self._init_lock:
|
| 116 |
+
started = time.monotonic()
|
| 117 |
+
self._status = "initializing"
|
| 118 |
+
try:
|
| 119 |
+
# File reads, tokenization, and heavy imports must not block the
|
| 120 |
+
# event loop serving /config, health checks, and chat requests.
|
| 121 |
+
kb_hash, chunks, metadata, bm25 = await asyncio.to_thread(self._build_keyword_index)
|
| 122 |
+
self.vectorstore = None
|
| 123 |
+
self._embeddings = None
|
| 124 |
+
self._kb_hash = kb_hash
|
| 125 |
+
self.bm25_corpus, self.bm25_meta, self.bm25 = chunks, metadata, bm25
|
| 126 |
+
self._build_reverse_index()
|
| 127 |
+
self._ready = True
|
| 128 |
+
self._status = "keyword_ready"
|
| 129 |
+
logger.info("RAG keyword index ready: %d chunks in %.2fs", len(chunks), time.monotonic() - started)
|
| 130 |
+
except Exception:
|
| 131 |
+
self._status = ("ready" if self.vectorstore is not None else "keyword_ready") if self._ready else "failed"
|
| 132 |
+
logger.exception("RAG keyword initialization failed; retaining any existing index")
|
| 133 |
+
return
|
| 134 |
+
|
| 135 |
+
if not openai_api_key:
|
| 136 |
+
return
|
| 137 |
+
self._status = "semantic_initializing"
|
| 138 |
+
try:
|
| 139 |
+
def load_embedding_tools():
|
| 140 |
+
from langchain_openai import OpenAIEmbeddings
|
| 141 |
+
from langchain_community.vectorstores import FAISS
|
| 142 |
+
return OpenAIEmbeddings, FAISS
|
| 143 |
+
OpenAIEmbeddings, FAISS = await asyncio.to_thread(load_embedding_tools)
|
| 144 |
+
self._embeddings = OpenAIEmbeddings(
|
| 145 |
+
model=EMBEDDING_MODEL, openai_api_key=openai_api_key,
|
| 146 |
+
request_timeout=15, max_retries=1,
|
| 147 |
+
)
|
| 148 |
+
if not force_rebuild and await asyncio.to_thread(self._try_load_cached_indexes, FAISS):
|
| 149 |
+
self._status = "ready"
|
| 150 |
+
return
|
| 151 |
+
vectorstore = await asyncio.wait_for(
|
| 152 |
+
FAISS.afrom_texts(chunks, self._embeddings, metadatas=metadata), timeout=90
|
| 153 |
+
)
|
| 154 |
+
self.vectorstore = vectorstore
|
| 155 |
+
self._status = "ready"
|
| 156 |
+
try:
|
| 157 |
+
await asyncio.to_thread(self._save_cached_indexes)
|
| 158 |
+
except Exception:
|
| 159 |
+
# An unwritable cache must not disable a working index.
|
| 160 |
+
logger.exception("RAG cache save failed; retrieval remains available")
|
| 161 |
+
logger.info("RAG semantic index ready in %.2fs", time.monotonic() - started)
|
| 162 |
+
except asyncio.CancelledError:
|
| 163 |
+
self._status = "keyword_ready"
|
| 164 |
+
raise
|
| 165 |
+
except Exception:
|
| 166 |
+
self._status = "keyword_ready"
|
| 167 |
+
logger.exception("RAG semantic index unavailable; using keyword retrieval")
|
| 168 |
+
|
| 169 |
+
def _try_load_cached_indexes(self, FAISS, _BM25Okapi=None) -> bool:
|
| 170 |
+
faiss_dir, bm25_path, state_path = self._cache_paths()
|
| 171 |
+
if not (faiss_dir.exists() and bm25_path.exists() and state_path.exists()):
|
| 172 |
+
return False
|
| 173 |
+
try:
|
| 174 |
+
state = json.loads(state_path.read_text(encoding="utf-8"))
|
| 175 |
+
if state.get("kb_hash") != self._kb_hash or state.get("schema") != CACHE_SCHEMA:
|
| 176 |
+
return False
|
| 177 |
+
expected = self._cache_signature(faiss_dir, bm25_path)
|
| 178 |
+
if not expected or not hmac.compare_digest(str(state.get("signature", "")), expected):
|
| 179 |
+
logger.warning("RAG unsigned or modified cache ignored")
|
| 180 |
+
return False
|
| 181 |
+
cached = json.loads(bm25_path.read_text(encoding="utf-8"))
|
| 182 |
+
if cached.get("corpus") != self.bm25_corpus or cached.get("meta") != self.bm25_meta:
|
| 183 |
+
return False
|
| 184 |
+
# FAISS uses pickle internally. Only load bytes authenticated with
|
| 185 |
+
# the origin secret; never load unsigned/user-supplied index files.
|
| 186 |
+
self.vectorstore = FAISS.load_local(
|
| 187 |
+
str(faiss_dir), self._embeddings, allow_dangerous_deserialization=True
|
| 188 |
+
)
|
| 189 |
+
return True
|
| 190 |
+
except Exception:
|
| 191 |
+
logger.warning("RAG cache could not be loaded; rebuilding", exc_info=True)
|
| 192 |
+
return False
|
| 193 |
+
|
| 194 |
+
def _save_cached_indexes(self) -> None:
|
| 195 |
+
if self.vectorstore is None or not get_settings().origin_token:
|
| 196 |
+
return
|
| 197 |
+
faiss_dir, bm25_path, state_path = self._cache_paths()
|
| 198 |
+
faiss_dir.mkdir(parents=True, exist_ok=True)
|
| 199 |
+
self.vectorstore.save_local(str(faiss_dir))
|
| 200 |
+
bm25_tmp = bm25_path.with_suffix(".tmp")
|
| 201 |
+
bm25_tmp.write_text(json.dumps({"corpus": self.bm25_corpus, "meta": self.bm25_meta}, ensure_ascii=False), encoding="utf-8")
|
| 202 |
+
os.replace(bm25_tmp, bm25_path)
|
| 203 |
+
state_tmp = state_path.with_suffix(".tmp")
|
| 204 |
+
state_tmp.write_text(json.dumps({
|
| 205 |
+
"schema": CACHE_SCHEMA, "kb_hash": self._kb_hash,
|
| 206 |
+
"embedding_model": EMBEDDING_MODEL, "chunk_count": len(self.bm25_corpus),
|
| 207 |
+
"signature": self._cache_signature(faiss_dir, bm25_path),
|
| 208 |
+
}), encoding="utf-8")
|
| 209 |
+
os.replace(state_tmp, state_path)
|
| 210 |
+
|
| 211 |
+
def _load_and_chunk_all(self) -> tuple[List[str], List[dict]]:
|
| 212 |
+
all_chunks, all_meta = [], []
|
| 213 |
+
seen: set[str] = set()
|
| 214 |
+
for path in sorted(self._knowledge_dir().glob("*.txt")):
|
| 215 |
+
try:
|
| 216 |
+
text = path.read_text(encoding="utf-8").strip()
|
| 217 |
+
if not text:
|
| 218 |
+
continue
|
| 219 |
+
header, header_lines = {}, set()
|
| 220 |
+
lines = text.splitlines()
|
| 221 |
+
for index, line in enumerate(lines[:8]):
|
| 222 |
+
if HEADER_RE.match(line.strip()):
|
| 223 |
+
key, value = line.split(":", 1)
|
| 224 |
+
header[key.strip().upper()] = value.strip()
|
| 225 |
+
header_lines.add(index)
|
| 226 |
+
body = "\n".join(line for index, line in enumerate(lines) if index not in header_lines)
|
| 227 |
+
metadata = {
|
| 228 |
+
"source": header.get("SOURCE", ""),
|
| 229 |
+
"title": header.get("TITLE", path.stem.replace("_", " ")),
|
| 230 |
+
"filename": path.name,
|
| 231 |
+
"authority": header.get("AUTHORITY", "supplied_library_content"),
|
| 232 |
+
"last_reviewed": header.get("LAST_REVIEWED", ""),
|
| 233 |
+
"last_updated": header.get("LAST_UPDATED", ""),
|
| 234 |
+
}
|
| 235 |
+
for chunk in self._chunk_text(body):
|
| 236 |
+
fingerprint = re.sub(r"\s+", " ", chunk).strip()
|
| 237 |
+
if fingerprint in seen:
|
| 238 |
+
continue
|
| 239 |
+
seen.add(fingerprint)
|
| 240 |
+
all_chunks.append(chunk)
|
| 241 |
+
all_meta.append(dict(metadata))
|
| 242 |
+
except Exception:
|
| 243 |
+
logger.warning("Could not read knowledge file %s", path.name, exc_info=True)
|
| 244 |
+
return all_chunks, all_meta
|
| 245 |
+
|
| 246 |
+
def _chunk_text(self, text: str) -> List[str]:
|
| 247 |
+
# Source files use RESOURCE 01:, all-caps headings without colons,
|
| 248 |
+
# staff names, and === section markers. Keep each entry with its URL.
|
| 249 |
+
sections, current = [], []
|
| 250 |
+
for line in text.splitlines():
|
| 251 |
+
stripped = line.strip()
|
| 252 |
+
is_heading = bool(
|
| 253 |
+
re.match(r"^(?:TOPIC:|RESOURCE\s+\d+:|===)", stripped)
|
| 254 |
+
or (4 <= len(stripped) <= 100 and stripped.isupper()
|
| 255 |
+
and any(char.isalpha() for char in stripped)
|
| 256 |
+
and not stripped.startswith(("http", "SOURCE:", "TITLE:")))
|
| 257 |
+
)
|
| 258 |
+
if is_heading and current:
|
| 259 |
+
sections.append("\n".join(current).strip())
|
| 260 |
+
current = []
|
| 261 |
+
current.append(line)
|
| 262 |
+
if current:
|
| 263 |
+
sections.append("\n".join(current).strip())
|
| 264 |
+
chunks = []
|
| 265 |
+
for section in sections:
|
| 266 |
+
if len(section) < 30 or not self._tokens(section):
|
| 267 |
+
continue
|
| 268 |
+
words = section.split()
|
| 269 |
+
if len(words) <= CHUNK_WORDS:
|
| 270 |
+
chunks.append(section)
|
| 271 |
+
continue
|
| 272 |
+
heading = section.splitlines()[0].strip()
|
| 273 |
+
for start in range(0, len(words), CHUNK_WORDS - CHUNK_OVERLAP_WORDS):
|
| 274 |
+
chunk = " ".join(words[start:start + CHUNK_WORDS])
|
| 275 |
+
if start and len(heading) < 100:
|
| 276 |
+
chunk = heading + "\n" + chunk
|
| 277 |
+
chunks.append(chunk)
|
| 278 |
+
if start + CHUNK_WORDS >= len(words):
|
| 279 |
+
break
|
| 280 |
+
return chunks
|
| 281 |
+
|
| 282 |
+
async def hybrid_search(self, query: str, top_k: int = 5, alpha: float = 0.6) -> List[dict]:
|
| 283 |
+
if not self._ready or self.bm25 is None or not query.strip() or top_k <= 0:
|
| 284 |
+
return []
|
| 285 |
+
# Snapshot before awaiting dense search so an admin rebuild cannot mix
|
| 286 |
+
# old vector document ids with a new corpus/metadata list.
|
| 287 |
+
corpus, metadata, bm25 = self.bm25_corpus, self.bm25_meta, self.bm25
|
| 288 |
+
vectorstore, reverse = self.vectorstore, self._content_to_idx
|
| 289 |
+
tokens = self._tokens(query)
|
| 290 |
+
meaningful = {token for token in tokens if token not in STOP_WORDS and len(token) > 1}
|
| 291 |
+
if not meaningful:
|
| 292 |
+
return []
|
| 293 |
+
fetch_k = min(max(top_k * 3, 15), len(corpus))
|
| 294 |
+
alpha = min(1.0, max(0.0, alpha))
|
| 295 |
+
scores = bm25.get_scores(tokens)
|
| 296 |
+
lexical_indices = sorted(range(len(corpus)), key=lambda idx: float(scores[idx]), reverse=True)
|
| 297 |
+
lexical_indices = [idx for idx in lexical_indices
|
| 298 |
+
if meaningful & set(self._tokens(corpus[idx]))][:fetch_k]
|
| 299 |
+
dense_results = []
|
| 300 |
+
if vectorstore is not None:
|
| 301 |
+
try:
|
| 302 |
+
dense_results = await asyncio.wait_for(
|
| 303 |
+
vectorstore.asimilarity_search_with_score(query, k=fetch_k), timeout=4
|
| 304 |
+
)
|
| 305 |
+
except Exception:
|
| 306 |
+
logger.warning("Semantic retrieval unavailable; using keywords", exc_info=True)
|
| 307 |
+
rrf: dict[int, float] = {}
|
| 308 |
+
dense_distance: dict[int, float] = {}
|
| 309 |
+
for rank, (doc, score) in enumerate(dense_results):
|
| 310 |
+
idx = reverse.get(doc.page_content.strip(), -1)
|
| 311 |
+
if idx >= 0:
|
| 312 |
+
rrf[idx] = rrf.get(idx, 0.0) + alpha / (61 + rank)
|
| 313 |
+
try:
|
| 314 |
+
dense_distance.setdefault(idx, float(score))
|
| 315 |
+
except (TypeError, ValueError):
|
| 316 |
+
pass
|
| 317 |
+
lexical_weight = (1 - alpha) if dense_results else 1.0
|
| 318 |
+
for rank, idx in enumerate(lexical_indices):
|
| 319 |
+
rrf[idx] = rrf.get(idx, 0.0) + lexical_weight / (61 + rank)
|
| 320 |
+
results = []
|
| 321 |
+
# Filter before applying top_k: irrelevant dense hits must not crowd
|
| 322 |
+
# relevant keyword hits out of the candidate pool.
|
| 323 |
+
dense_only_left = DENSE_ONLY_LIMIT
|
| 324 |
+
for idx in sorted(rrf, key=rrf.get, reverse=True):
|
| 325 |
+
overlap = len(meaningful & set(self._tokens(corpus[idx])))
|
| 326 |
+
if not overlap:
|
| 327 |
+
# A paraphrased question can share no words with the passage that
|
| 328 |
+
# answers it ("take books home" vs "borrowing"). Admit such a
|
| 329 |
+
# passage only when the embedding match is very close, and only
|
| 330 |
+
# a couple of them, so weak semantic hits still cannot crowd
|
| 331 |
+
# out keyword hits.
|
| 332 |
+
if dense_only_left <= 0 or dense_distance.get(idx, float("inf")) > DENSE_ONLY_MAX_DISTANCE:
|
| 333 |
+
continue
|
| 334 |
+
dense_only_left -= 1
|
| 335 |
+
results.append({
|
| 336 |
+
"content": corpus[idx], **metadata[idx], "score": round(rrf[idx], 6),
|
| 337 |
+
"lexical_overlap": overlap,
|
| 338 |
+
"retrieval_mode": "hybrid" if dense_results else "keyword",
|
| 339 |
+
})
|
| 340 |
+
if len(results) >= top_k:
|
| 341 |
+
break
|
| 342 |
+
return results
|
| 343 |
+
|
| 344 |
+
def _find_corpus_index(self, content: str) -> int:
|
| 345 |
+
return self._content_to_idx.get(content.strip(), -1)
|
| 346 |
+
|
| 347 |
+
def audit_knowledge_base(self) -> dict:
|
| 348 |
+
files = sorted(self._knowledge_dir().glob("*.txt"))
|
| 349 |
+
titles, duplicates = {}, []
|
| 350 |
+
for path in files:
|
| 351 |
+
try:
|
| 352 |
+
text = path.read_text(encoding="utf-8")[:500]
|
| 353 |
+
title = next((line.split(":", 1)[1].strip() for line in text.splitlines() if line.startswith("TITLE:")), path.stem)
|
| 354 |
+
if title in titles:
|
| 355 |
+
duplicates.append({"title": title, "files": [titles[title], path.name]})
|
| 356 |
+
else:
|
| 357 |
+
titles[title] = path.name
|
| 358 |
+
except OSError:
|
| 359 |
+
continue
|
| 360 |
+
return {"file_count": len(files), "duplicate_titles": duplicates[:20]}
|
| 361 |
+
|
| 362 |
+
def get_stats(self) -> dict:
|
| 363 |
+
return {
|
| 364 |
+
"ready": self._ready, "status": self._status,
|
| 365 |
+
"retrieval_mode": "hybrid" if self.vectorstore is not None else "keyword" if self._ready else "unavailable",
|
| 366 |
+
"chunk_count": len(self.bm25_corpus), "knowledge_dir": str(self._knowledge_dir()),
|
| 367 |
+
"vectorstore_loaded": self.vectorstore is not None, "bm25_loaded": self.bm25 is not None,
|
| 368 |
+
"kb_hash": self._kb_hash,
|
| 369 |
+
}
|