nikeshn commited on
Commit
ae46dcc
·
verified ·
1 Parent(s): ef033e9

Upload 8 files

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