rag_adapter.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. RAG Adapter - RAG 检索适配模块
  5. 封装向量检索功能:
  6. - 向量嵌入 (调用 Modal API)
  7. - 语义搜索
  8. - 重排序
  9. - 混合检索 (向量 + BM25)
  10. """
  11. import asyncio
  12. import sqlite3
  13. import json
  14. import math
  15. import logging
  16. import shutil
  17. from pathlib import Path
  18. from runtime_compat import enable_windows_utf8_stdio
  19. from typing import Dict, List, Optional, Any, Tuple
  20. from dataclasses import dataclass
  21. from collections import Counter
  22. import re
  23. from contextlib import contextmanager
  24. import itertools
  25. import time
  26. from datetime import datetime
  27. from .config import get_config
  28. from .api_client import get_client
  29. from .index_manager import IndexManager
  30. from .observability import safe_log_tool_call
  31. logger = logging.getLogger(__name__)
  32. RAG_SCHEMA_VERSION = "2"
  33. VECTOR_REQUIRED_COLUMNS = (
  34. "chunk_id",
  35. "chapter",
  36. "scene_index",
  37. "content",
  38. "embedding",
  39. "parent_chunk_id",
  40. "chunk_type",
  41. "source_file",
  42. "created_at",
  43. )
  44. @dataclass
  45. class SearchResult:
  46. """搜索结果"""
  47. chunk_id: str
  48. chapter: int
  49. scene_index: int
  50. content: str
  51. score: float
  52. source: str # "vector" | "bm25" | "hybrid"
  53. parent_chunk_id: str | None = None
  54. chunk_type: str | None = None
  55. source_file: str | None = None
  56. class RAGAdapter:
  57. """RAG 检索适配器"""
  58. def __init__(self, config=None):
  59. self.config = config or get_config()
  60. self.api_client = get_client(config)
  61. self.index_manager = IndexManager(self.config)
  62. self._degraded_mode_reason: Optional[str] = None
  63. self._init_db()
  64. @property
  65. def degraded_mode_reason(self) -> Optional[str]:
  66. return self._degraded_mode_reason
  67. def _update_degraded_mode(self) -> None:
  68. self._degraded_mode_reason = None
  69. embed_client = getattr(self.api_client, "_embed_client", None)
  70. status = getattr(embed_client, "last_error_status", None)
  71. if status == 401:
  72. self._degraded_mode_reason = "embedding_auth_failed"
  73. def _init_db(self):
  74. """初始化向量数据库"""
  75. self.config.ensure_dirs()
  76. needs_migration, existing_cols = self._inspect_vectors_schema()
  77. if needs_migration:
  78. backup_path = self._backup_vector_db(reason="schema_migration")
  79. try:
  80. with self._get_conn() as conn:
  81. cursor = conn.cursor()
  82. self._rebuild_vectors_table(cursor, existing_cols)
  83. conn.commit()
  84. logger.warning(
  85. "vectors 表结构已迁移(备份: %s)",
  86. str(backup_path),
  87. )
  88. except Exception:
  89. try:
  90. self._restore_vector_db_from_backup(backup_path)
  91. logger.error("vectors 表迁移失败,已从备份恢复: %s", str(backup_path))
  92. except Exception as restore_exc:
  93. logger.exception("vectors 表迁移失败,且恢复备份失败: %s", restore_exc)
  94. raise
  95. with self._get_conn() as conn:
  96. cursor = conn.cursor()
  97. self._ensure_schema_meta(cursor)
  98. self._ensure_tables(cursor)
  99. conn.commit()
  100. def _table_exists(self, cursor, table_name: str) -> bool:
  101. cursor.execute(
  102. "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?",
  103. (table_name,),
  104. )
  105. return cursor.fetchone() is not None
  106. def _table_columns(self, cursor, table_name: str) -> set[str]:
  107. cursor.execute(f"PRAGMA table_info({table_name})")
  108. return {row[1] for row in cursor.fetchall()}
  109. def _inspect_vectors_schema(self) -> tuple[bool, set[str]]:
  110. with self._get_conn() as conn:
  111. cursor = conn.cursor()
  112. if not self._table_exists(cursor, "vectors"):
  113. return False, set()
  114. cols = self._table_columns(cursor, "vectors")
  115. required_cols = set(VECTOR_REQUIRED_COLUMNS)
  116. return (not required_cols.issubset(cols), cols)
  117. def _backup_vector_db(self, reason: str) -> Path:
  118. db_path = Path(self.config.vector_db)
  119. if not db_path.exists():
  120. raise FileNotFoundError(f"vectors.db 不存在: {db_path}")
  121. backup_dir = self.config.webnovel_dir / "backups"
  122. backup_dir.mkdir(parents=True, exist_ok=True)
  123. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  124. backup_path = backup_dir / f"vectors.db.{reason}.v{RAG_SCHEMA_VERSION}.{timestamp}.bak"
  125. shutil.copy2(db_path, backup_path)
  126. return backup_path
  127. def _restore_vector_db_from_backup(self, backup_path: Path) -> None:
  128. db_path = Path(self.config.vector_db)
  129. shutil.copy2(backup_path, db_path)
  130. def _rebuild_vectors_table(self, cursor, existing_cols: set[str]) -> None:
  131. if not self._table_exists(cursor, "vectors"):
  132. return
  133. cursor.execute("DROP TABLE IF EXISTS vectors_migrating")
  134. cursor.execute("""
  135. CREATE TABLE vectors_migrating (
  136. chunk_id TEXT PRIMARY KEY,
  137. chapter INTEGER,
  138. scene_index INTEGER,
  139. content TEXT,
  140. embedding BLOB,
  141. parent_chunk_id TEXT,
  142. chunk_type TEXT DEFAULT 'scene',
  143. source_file TEXT,
  144. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  145. )
  146. """)
  147. copy_columns = [
  148. col
  149. for col in VECTOR_REQUIRED_COLUMNS
  150. if col in existing_cols
  151. ]
  152. if copy_columns:
  153. cols_sql = ", ".join(copy_columns)
  154. cursor.execute(
  155. f"INSERT OR REPLACE INTO vectors_migrating ({cols_sql}) SELECT {cols_sql} FROM vectors"
  156. )
  157. cursor.execute("DROP TABLE vectors")
  158. cursor.execute("ALTER TABLE vectors_migrating RENAME TO vectors")
  159. def _ensure_schema_meta(self, cursor) -> None:
  160. cursor.execute("""
  161. CREATE TABLE IF NOT EXISTS rag_schema_meta (
  162. key TEXT PRIMARY KEY,
  163. value TEXT NOT NULL,
  164. updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  165. )
  166. """)
  167. cursor.execute(
  168. """
  169. INSERT INTO rag_schema_meta (key, value, updated_at)
  170. VALUES ('schema_version', ?, CURRENT_TIMESTAMP)
  171. ON CONFLICT(key) DO UPDATE SET
  172. value = excluded.value,
  173. updated_at = CURRENT_TIMESTAMP
  174. """,
  175. (RAG_SCHEMA_VERSION,),
  176. )
  177. def _ensure_tables(self, cursor) -> None:
  178. # 向量存储表
  179. cursor.execute("""
  180. CREATE TABLE IF NOT EXISTS vectors (
  181. chunk_id TEXT PRIMARY KEY,
  182. chapter INTEGER,
  183. scene_index INTEGER,
  184. content TEXT,
  185. embedding BLOB,
  186. parent_chunk_id TEXT,
  187. chunk_type TEXT DEFAULT 'scene',
  188. source_file TEXT,
  189. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  190. )
  191. """)
  192. # BM25 倒排索引表
  193. cursor.execute("""
  194. CREATE TABLE IF NOT EXISTS bm25_index (
  195. term TEXT,
  196. chunk_id TEXT,
  197. tf REAL,
  198. PRIMARY KEY (term, chunk_id)
  199. )
  200. """)
  201. # 文档统计表
  202. cursor.execute("""
  203. CREATE TABLE IF NOT EXISTS doc_stats (
  204. chunk_id TEXT PRIMARY KEY,
  205. doc_length INTEGER
  206. )
  207. """)
  208. # 创建索引
  209. cursor.execute("CREATE INDEX IF NOT EXISTS idx_vectors_chapter ON vectors(chapter)")
  210. cursor.execute("CREATE INDEX IF NOT EXISTS idx_vectors_parent ON vectors(parent_chunk_id)")
  211. cursor.execute("CREATE INDEX IF NOT EXISTS idx_vectors_type ON vectors(chunk_type)")
  212. cursor.execute("CREATE INDEX IF NOT EXISTS idx_bm25_term ON bm25_index(term)")
  213. @contextmanager
  214. def _get_conn(self):
  215. """获取数据库连接(确保关闭,避免 Windows 下文件句柄泄漏)"""
  216. conn = sqlite3.connect(str(self.config.vector_db))
  217. try:
  218. yield conn
  219. finally:
  220. conn.close()
  221. def _get_vectors_count(self) -> int:
  222. with self._get_conn() as conn:
  223. cursor = conn.cursor()
  224. cursor.execute("SELECT COUNT(*) FROM vectors")
  225. row = cursor.fetchone()
  226. return int(row[0] or 0) if row else 0
  227. def _get_recent_chunk_ids(self, limit: int, chunk_type: str | None = None) -> List[str]:
  228. if limit <= 0:
  229. return []
  230. with self._get_conn() as conn:
  231. cursor = conn.cursor()
  232. if chunk_type:
  233. cursor.execute(
  234. "SELECT chunk_id FROM vectors WHERE chunk_type = ? ORDER BY chapter DESC, scene_index DESC LIMIT ?",
  235. (chunk_type, int(limit)),
  236. )
  237. else:
  238. cursor.execute(
  239. "SELECT chunk_id FROM vectors ORDER BY chapter DESC, scene_index DESC LIMIT ?",
  240. (int(limit),),
  241. )
  242. return [str(r[0]) for r in cursor.fetchall() if r and r[0]]
  243. def _fetch_vectors_by_chunk_ids(self, chunk_ids: List[str]) -> List[Tuple]:
  244. if not chunk_ids:
  245. return []
  246. # SQLite 参数数量限制(默认 999),这里做分片查询
  247. def _chunks(xs: List[str], size: int = 500):
  248. it = iter(xs)
  249. while True:
  250. batch = list(itertools.islice(it, size))
  251. if not batch:
  252. break
  253. yield batch
  254. rows: List[Tuple] = []
  255. with self._get_conn() as conn:
  256. cursor = conn.cursor()
  257. for batch in _chunks(chunk_ids):
  258. placeholders = ",".join(["?"] * len(batch))
  259. cursor.execute(
  260. f"SELECT chunk_id, chapter, scene_index, content, embedding, parent_chunk_id, chunk_type, source_file FROM vectors WHERE chunk_id IN ({placeholders})",
  261. tuple(batch),
  262. )
  263. rows.extend(cursor.fetchall())
  264. return rows
  265. def _vector_search_rows(
  266. self,
  267. query_embedding: List[float],
  268. rows: List[Tuple],
  269. *,
  270. top_k: int,
  271. ) -> List[SearchResult]:
  272. results: List[SearchResult] = []
  273. for row in rows:
  274. (
  275. chunk_id,
  276. chapter,
  277. scene_index,
  278. content,
  279. embedding_bytes,
  280. parent_chunk_id,
  281. chunk_type,
  282. source_file,
  283. ) = row
  284. if not embedding_bytes:
  285. continue
  286. embedding = self._deserialize_embedding(embedding_bytes)
  287. score = self._cosine_similarity(query_embedding, embedding)
  288. results.append(
  289. SearchResult(
  290. chunk_id=chunk_id,
  291. chapter=chapter,
  292. scene_index=scene_index,
  293. content=content,
  294. score=score,
  295. source="vector",
  296. parent_chunk_id=parent_chunk_id,
  297. chunk_type=chunk_type,
  298. source_file=source_file,
  299. )
  300. )
  301. results.sort(key=lambda x: x.score, reverse=True)
  302. return results[:top_k]
  303. # ==================== 向量存储 ====================
  304. async def store_chunks(self, chunks: List[Dict]) -> int:
  305. """
  306. 存储场景切片的向量
  307. chunks 格式:
  308. [
  309. {
  310. "chapter": 100,
  311. "scene_index": 1,
  312. "content": "场景内容...",
  313. "chunk_type": "scene",
  314. "parent_chunk_id": "ch0100_summary",
  315. "source_file": "正文/第0100章.md#scene_1"
  316. }
  317. ]
  318. 返回存储数量
  319. """
  320. if not chunks:
  321. return 0
  322. # 提取内容用于嵌入
  323. contents = [c.get("content", "") for c in chunks]
  324. # 调用 API 获取嵌入向量(可能包含 None 表示失败)
  325. embeddings = await self.api_client.embed_batch(contents)
  326. if not embeddings:
  327. return 0
  328. # 存储到数据库(跳过嵌入失败的 chunk)
  329. stored = 0
  330. skipped = 0
  331. errors = []
  332. with self._get_conn() as conn:
  333. cursor = conn.cursor()
  334. for chunk, embedding in zip(chunks, embeddings):
  335. if embedding is None:
  336. # 嵌入失败,跳过该 chunk(仅存储 BM25 索引供关键词检索)
  337. skipped += 1
  338. chunk_id = chunk.get("chunk_id")
  339. if not chunk_id:
  340. if chunk.get("chunk_type") == "summary":
  341. chunk_id = f"ch{int(chunk['chapter']):04d}_summary"
  342. else:
  343. chunk_id = f"ch{int(chunk['chapter']):04d}_s{int(chunk['scene_index'])}"
  344. try:
  345. self._update_bm25_index(cursor, chunk_id, chunk.get("content", ""))
  346. except Exception as e:
  347. errors.append(f"BM25 index failed for {chunk_id}: {e}")
  348. continue
  349. chunk_type = chunk.get("chunk_type") or "scene"
  350. chunk_id = chunk.get("chunk_id")
  351. if not chunk_id:
  352. if chunk_type == "summary":
  353. chunk_id = f"ch{int(chunk['chapter']):04d}_summary"
  354. else:
  355. chunk_id = f"ch{int(chunk['chapter']):04d}_s{int(chunk['scene_index'])}"
  356. # 将向量序列化为 bytes
  357. embedding_bytes = self._serialize_embedding(embedding)
  358. cursor.execute("""
  359. INSERT OR REPLACE INTO vectors
  360. (chunk_id, chapter, scene_index, content, embedding, parent_chunk_id, chunk_type, source_file)
  361. VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  362. """, (
  363. chunk_id,
  364. chunk["chapter"],
  365. chunk.get("scene_index", 0) if chunk_type == "scene" else 0,
  366. chunk.get("content", ""),
  367. embedding_bytes,
  368. chunk.get("parent_chunk_id"),
  369. chunk_type,
  370. chunk.get("source_file"),
  371. ))
  372. # 同时更新 BM25 索引
  373. try:
  374. self._update_bm25_index(cursor, chunk_id, chunk.get("content", ""))
  375. except Exception as e:
  376. errors.append(f"BM25 index failed for {chunk_id}: {e}")
  377. stored += 1
  378. try:
  379. conn.commit()
  380. except Exception as e:
  381. logger.error("SQLite commit failed: %s", e)
  382. errors.append(f"SQLite commit failed: {e}")
  383. # 输出警告日志
  384. if skipped > 0:
  385. logger.warning(
  386. "Vector embedding: %s stored, %s skipped (embedding failed)",
  387. stored,
  388. skipped,
  389. )
  390. if errors:
  391. for err in errors[:5]: # 最多显示5条
  392. logger.warning("%s", err)
  393. return stored
  394. def _serialize_embedding(self, embedding: List[float]) -> bytes:
  395. """序列化向量"""
  396. import struct
  397. return struct.pack(f"{len(embedding)}f", *embedding)
  398. def _deserialize_embedding(self, data: bytes) -> List[float]:
  399. """反序列化向量"""
  400. import struct
  401. count = len(data) // 4
  402. return list(struct.unpack(f"{count}f", data))
  403. def _log_query(
  404. self,
  405. query: str,
  406. query_type: str,
  407. results: List[SearchResult],
  408. latency_ms: int,
  409. chapter: int | None = None,
  410. ) -> None:
  411. try:
  412. hit_sources = Counter([r.chunk_type or "unknown" for r in results])
  413. self.index_manager.log_rag_query(
  414. query=query,
  415. query_type=query_type,
  416. results_count=len(results),
  417. hit_sources=json.dumps(hit_sources, ensure_ascii=False),
  418. latency_ms=latency_ms,
  419. chapter=chapter,
  420. )
  421. except Exception as exc:
  422. logger.warning("failed to log rag query: %s", exc)
  423. # ==================== BM25 索引 ====================
  424. def _tokenize(self, text: str) -> List[str]:
  425. """简单分词(中文按字符,英文按单词)"""
  426. # 中文字符
  427. chinese = re.findall(r'[\u4e00-\u9fff]+', text)
  428. chinese_chars = list("".join(chinese))
  429. # 英文单词
  430. english = re.findall(r'[a-zA-Z]+', text.lower())
  431. return chinese_chars + english
  432. def _update_bm25_index(self, cursor, chunk_id: str, content: str):
  433. """更新 BM25 索引"""
  434. # 删除旧索引
  435. cursor.execute("DELETE FROM bm25_index WHERE chunk_id = ?", (chunk_id,))
  436. cursor.execute("DELETE FROM doc_stats WHERE chunk_id = ?", (chunk_id,))
  437. # 分词
  438. tokens = self._tokenize(content)
  439. doc_length = len(tokens)
  440. # 计算词频
  441. tf_counter = Counter(tokens)
  442. # 插入倒排索引
  443. for term, count in tf_counter.items():
  444. tf = count / doc_length if doc_length > 0 else 0
  445. cursor.execute("""
  446. INSERT INTO bm25_index (term, chunk_id, tf)
  447. VALUES (?, ?, ?)
  448. """, (term, chunk_id, tf))
  449. # 更新文档统计
  450. cursor.execute("""
  451. INSERT INTO doc_stats (chunk_id, doc_length)
  452. VALUES (?, ?)
  453. """, (chunk_id, doc_length))
  454. # ==================== 向量检索 ====================
  455. async def vector_search(
  456. self,
  457. query: str,
  458. top_k: int = None,
  459. chunk_type: str | None = None,
  460. log_query: bool = True,
  461. chapter: int | None = None,
  462. ) -> List[SearchResult]:
  463. """向量相似度搜索"""
  464. top_k = top_k or self.config.vector_top_k
  465. start_time = time.perf_counter()
  466. # 获取查询向量
  467. query_embeddings = await self.api_client.embed([query])
  468. if not query_embeddings:
  469. self._update_degraded_mode()
  470. return []
  471. self._degraded_mode_reason = None
  472. query_embedding = query_embeddings[0]
  473. # 从数据库读取所有向量并计算相似度
  474. with self._get_conn() as conn:
  475. cursor = conn.cursor()
  476. if chunk_type:
  477. cursor.execute(
  478. "SELECT chunk_id, chapter, scene_index, content, embedding, parent_chunk_id, chunk_type, source_file FROM vectors WHERE chunk_type = ?",
  479. (chunk_type,),
  480. )
  481. else:
  482. cursor.execute(
  483. "SELECT chunk_id, chapter, scene_index, content, embedding, parent_chunk_id, chunk_type, source_file FROM vectors"
  484. )
  485. results = []
  486. for row in cursor.fetchall():
  487. (
  488. chunk_id,
  489. chapter,
  490. scene_index,
  491. content,
  492. embedding_bytes,
  493. parent_chunk_id,
  494. chunk_type_value,
  495. source_file,
  496. ) = row
  497. if not embedding_bytes:
  498. continue
  499. embedding = self._deserialize_embedding(embedding_bytes)
  500. # 计算余弦相似度
  501. score = self._cosine_similarity(query_embedding, embedding)
  502. results.append(SearchResult(
  503. chunk_id=chunk_id,
  504. chapter=chapter,
  505. scene_index=scene_index,
  506. content=content,
  507. score=score,
  508. source="vector",
  509. parent_chunk_id=parent_chunk_id,
  510. chunk_type=chunk_type_value,
  511. source_file=source_file,
  512. ))
  513. # 排序并返回 top_k
  514. results.sort(key=lambda x: x.score, reverse=True)
  515. results = results[:top_k]
  516. if log_query:
  517. latency_ms = int((time.perf_counter() - start_time) * 1000)
  518. self._log_query(query, "vector", results, latency_ms, chapter=chapter)
  519. return results
  520. def _cosine_similarity(self, a: List[float], b: List[float]) -> float:
  521. """计算余弦相似度"""
  522. dot_product = sum(x * y for x, y in zip(a, b))
  523. norm_a = math.sqrt(sum(x * x for x in a))
  524. norm_b = math.sqrt(sum(x * x for x in b))
  525. if norm_a == 0 or norm_b == 0:
  526. return 0.0
  527. return dot_product / (norm_a * norm_b)
  528. # ==================== BM25 检索 ====================
  529. def bm25_search(
  530. self,
  531. query: str,
  532. top_k: int = None,
  533. k1: float = 1.5,
  534. b: float = 0.75,
  535. chunk_type: str | None = None,
  536. log_query: bool = True,
  537. chapter: int | None = None,
  538. ) -> List[SearchResult]:
  539. """BM25 关键词搜索"""
  540. top_k = top_k or self.config.bm25_top_k
  541. start_time = time.perf_counter()
  542. query_terms = self._tokenize(query)
  543. if not query_terms:
  544. return []
  545. with self._get_conn() as conn:
  546. cursor = conn.cursor()
  547. # 获取文档总数和平均长度
  548. cursor.execute("SELECT COUNT(*), AVG(doc_length) FROM doc_stats")
  549. row = cursor.fetchone()
  550. total_docs = row[0] or 1
  551. avg_doc_length = row[1] or 1
  552. # 计算每个文档的 BM25 分数
  553. doc_scores = {}
  554. for term in set(query_terms):
  555. # 获取包含该词的文档
  556. cursor.execute("""
  557. SELECT b.chunk_id, b.tf, d.doc_length
  558. FROM bm25_index b
  559. JOIN doc_stats d ON b.chunk_id = d.chunk_id
  560. WHERE b.term = ?
  561. """, (term,))
  562. docs_with_term = cursor.fetchall()
  563. df = len(docs_with_term)
  564. if df == 0:
  565. continue
  566. # IDF
  567. idf = math.log((total_docs - df + 0.5) / (df + 0.5) + 1)
  568. for chunk_id, tf, doc_length in docs_with_term:
  569. # BM25 公式
  570. score = idf * (tf * (k1 + 1)) / (tf + k1 * (1 - b + b * doc_length / avg_doc_length))
  571. if chunk_id not in doc_scores:
  572. doc_scores[chunk_id] = 0
  573. doc_scores[chunk_id] += score
  574. # 获取文档内容
  575. results = []
  576. for chunk_id, score in doc_scores.items():
  577. if chunk_type:
  578. cursor.execute(
  579. """
  580. SELECT chapter, scene_index, content, parent_chunk_id, chunk_type, source_file
  581. FROM vectors
  582. WHERE chunk_id = ? AND chunk_type = ?
  583. """,
  584. (chunk_id, chunk_type),
  585. )
  586. else:
  587. cursor.execute(
  588. """
  589. SELECT chapter, scene_index, content, parent_chunk_id, chunk_type, source_file
  590. FROM vectors
  591. WHERE chunk_id = ?
  592. """,
  593. (chunk_id,),
  594. )
  595. row = cursor.fetchone()
  596. if row:
  597. results.append(SearchResult(
  598. chunk_id=chunk_id,
  599. chapter=row[0],
  600. scene_index=row[1],
  601. content=row[2],
  602. score=score,
  603. source="bm25",
  604. parent_chunk_id=row[3],
  605. chunk_type=row[4],
  606. source_file=row[5],
  607. ))
  608. results.sort(key=lambda x: x.score, reverse=True)
  609. results = results[:top_k]
  610. if log_query:
  611. latency_ms = int((time.perf_counter() - start_time) * 1000)
  612. self._log_query(query, "bm25", results, latency_ms, chapter=chapter)
  613. return results
  614. # ==================== 混合检索 ====================
  615. async def hybrid_search(
  616. self,
  617. query: str,
  618. vector_top_k: int = None,
  619. bm25_top_k: int = None,
  620. rerank_top_n: int = None,
  621. chunk_type: str | None = None,
  622. log_query: bool = True,
  623. ) -> List[SearchResult]:
  624. """
  625. 混合检索:向量 + BM25 + RRF 融合 + Rerank
  626. 步骤:
  627. 1. 向量检索 top_k
  628. 2. BM25 检索 top_k
  629. 3. RRF 融合
  630. 4. Rerank 精排
  631. """
  632. vector_top_k = vector_top_k or self.config.vector_top_k
  633. bm25_top_k = bm25_top_k or self.config.bm25_top_k
  634. rerank_top_n = rerank_top_n or self.config.rerank_top_n
  635. start_time = time.perf_counter()
  636. # 小规模:全表向量扫描(召回更稳);大规模:预筛选避免 O(n) 扫描拖慢
  637. vectors_count = await asyncio.to_thread(self._get_vectors_count)
  638. use_full_scan = vectors_count <= int(self.config.vector_full_scan_max_vectors)
  639. if use_full_scan:
  640. # 并行执行向量和 BM25 检索
  641. vector_results, bm25_results = await asyncio.gather(
  642. self.vector_search(query, vector_top_k, chunk_type=chunk_type, log_query=False),
  643. asyncio.to_thread(self.bm25_search, query, bm25_top_k, 1.5, 0.75, chunk_type, False),
  644. )
  645. else:
  646. bm25_candidates = max(
  647. int(self.config.vector_prefilter_bm25_candidates),
  648. int(bm25_top_k),
  649. int(vector_top_k) * 5,
  650. int(rerank_top_n) * 10,
  651. )
  652. recent_candidates = max(
  653. int(self.config.vector_prefilter_recent_candidates),
  654. int(vector_top_k) * 5,
  655. int(rerank_top_n) * 10,
  656. )
  657. bm25_task = asyncio.to_thread(self.bm25_search, query, bm25_candidates, 1.5, 0.75, chunk_type, False)
  658. recent_task = asyncio.to_thread(self._get_recent_chunk_ids, recent_candidates, chunk_type)
  659. embed_task = self.api_client.embed([query])
  660. bm25_candidates_results, recent_ids, query_embeddings = await asyncio.gather(
  661. bm25_task,
  662. recent_task,
  663. embed_task,
  664. )
  665. if not query_embeddings:
  666. self._update_degraded_mode()
  667. return []
  668. self._degraded_mode_reason = None
  669. query_embedding = query_embeddings[0]
  670. candidate_ids = {r.chunk_id for r in bm25_candidates_results}
  671. candidate_ids.update(recent_ids)
  672. rows = await asyncio.to_thread(self._fetch_vectors_by_chunk_ids, list(candidate_ids))
  673. if chunk_type:
  674. rows = [r for r in rows if len(r) > 6 and r[6] == chunk_type]
  675. vector_results = await asyncio.to_thread(
  676. self._vector_search_rows,
  677. query_embedding,
  678. rows,
  679. top_k=int(vector_top_k),
  680. )
  681. # BM25 结果用于融合时只取 top_k
  682. bm25_results = list(bm25_candidates_results)[: int(bm25_top_k)]
  683. # RRF 融合
  684. rrf_scores = {}
  685. k = self.config.rrf_k
  686. for rank, result in enumerate(vector_results):
  687. if result.chunk_id not in rrf_scores:
  688. rrf_scores[result.chunk_id] = {"result": result, "score": 0}
  689. rrf_scores[result.chunk_id]["score"] += 1 / (k + rank + 1)
  690. for rank, result in enumerate(bm25_results):
  691. if result.chunk_id not in rrf_scores:
  692. rrf_scores[result.chunk_id] = {"result": result, "score": 0}
  693. rrf_scores[result.chunk_id]["score"] += 1 / (k + rank + 1)
  694. # 按 RRF 分数排序
  695. sorted_results = sorted(
  696. rrf_scores.values(),
  697. key=lambda x: x["score"],
  698. reverse=True
  699. )
  700. # 取 top candidates 进行 rerank
  701. candidates = [item["result"] for item in sorted_results[:rerank_top_n * 2]]
  702. if not candidates:
  703. final_results: List[SearchResult] = []
  704. latency_ms = int((time.perf_counter() - start_time) * 1000)
  705. if log_query:
  706. self._log_query(query, "hybrid", final_results, latency_ms)
  707. return final_results
  708. # 调用 Rerank API
  709. documents = [c.content for c in candidates]
  710. rerank_results = await self.api_client.rerank(query, documents, top_n=rerank_top_n)
  711. if not rerank_results:
  712. # Rerank 失败,返回 RRF 结果
  713. final_results = [item["result"] for item in sorted_results[:rerank_top_n]]
  714. latency_ms = int((time.perf_counter() - start_time) * 1000)
  715. if log_query:
  716. self._log_query(query, "hybrid", final_results, latency_ms)
  717. return final_results
  718. # 组装最终结果
  719. final_results = []
  720. for r in rerank_results:
  721. idx = r.get("index", 0)
  722. if idx < len(candidates):
  723. result = candidates[idx]
  724. result.score = r.get("relevance_score", 0)
  725. result.source = "hybrid"
  726. final_results.append(result)
  727. latency_ms = int((time.perf_counter() - start_time) * 1000)
  728. if log_query:
  729. self._log_query(query, "hybrid", final_results, latency_ms)
  730. return final_results
  731. def _get_chunks_by_ids(self, chunk_ids: List[str]) -> List[SearchResult]:
  732. rows = self._fetch_vectors_by_chunk_ids(chunk_ids)
  733. results: List[SearchResult] = []
  734. for row in rows:
  735. (
  736. chunk_id,
  737. chapter,
  738. scene_index,
  739. content,
  740. _embedding_bytes,
  741. parent_chunk_id,
  742. chunk_type,
  743. source_file,
  744. ) = row
  745. results.append(
  746. SearchResult(
  747. chunk_id=chunk_id,
  748. chapter=chapter,
  749. scene_index=scene_index,
  750. content=content,
  751. score=0.0,
  752. source="parent",
  753. parent_chunk_id=parent_chunk_id,
  754. chunk_type=chunk_type,
  755. source_file=source_file,
  756. )
  757. )
  758. return results
  759. def _merge_results(
  760. self,
  761. parents: List[SearchResult],
  762. children: List[SearchResult],
  763. ) -> List[SearchResult]:
  764. parent_map = {p.chunk_id: p for p in parents}
  765. merged: List[SearchResult] = []
  766. seen = set()
  767. for child in children:
  768. parent_id = child.parent_chunk_id
  769. if parent_id and parent_id in parent_map and parent_id not in seen:
  770. merged.append(parent_map[parent_id])
  771. seen.add(parent_id)
  772. merged.append(child)
  773. return merged
  774. async def search_with_backtrack(self, query: str, top_k: int = 5) -> List[SearchResult]:
  775. start_time = time.perf_counter()
  776. child_results = await self.hybrid_search(
  777. query,
  778. vector_top_k=top_k * 2,
  779. bm25_top_k=top_k * 2,
  780. rerank_top_n=top_k,
  781. chunk_type="scene",
  782. log_query=False,
  783. )
  784. parent_ids = sorted({r.parent_chunk_id for r in child_results if r.parent_chunk_id})
  785. parents = self._get_chunks_by_ids(parent_ids) if parent_ids else []
  786. merged = self._merge_results(parents, child_results[:top_k])
  787. latency_ms = int((time.perf_counter() - start_time) * 1000)
  788. self._log_query(query, "backtrack", merged, latency_ms)
  789. return merged
  790. # ==================== 统计 ====================
  791. def get_stats(self) -> Dict[str, int]:
  792. """获取 RAG 统计"""
  793. with self._get_conn() as conn:
  794. cursor = conn.cursor()
  795. cursor.execute("SELECT COUNT(*) FROM vectors")
  796. vectors = cursor.fetchone()[0]
  797. cursor.execute("SELECT COUNT(DISTINCT term) FROM bm25_index")
  798. terms = cursor.fetchone()[0]
  799. cursor.execute("SELECT MAX(chapter) FROM vectors")
  800. max_chapter = cursor.fetchone()[0] or 0
  801. return {
  802. "vectors": vectors,
  803. "terms": terms,
  804. "max_chapter": max_chapter
  805. }
  806. # ==================== CLI 接口 ====================
  807. def main():
  808. import argparse
  809. from .cli_output import print_success, print_error
  810. parser = argparse.ArgumentParser(description="RAG Adapter CLI")
  811. parser.add_argument("--project-root", type=str, help="项目根目录")
  812. subparsers = parser.add_subparsers(dest="command")
  813. # 获取统计
  814. subparsers.add_parser("stats")
  815. # 写入索引
  816. index_parser = subparsers.add_parser("index-chapter")
  817. index_parser.add_argument("--chapter", type=int, required=True)
  818. index_parser.add_argument("--scenes", required=True, help="JSON 格式的场景列表")
  819. index_parser.add_argument("--summary", required=False, help="章节摘要文本")
  820. # 搜索
  821. search_parser = subparsers.add_parser("search")
  822. search_parser.add_argument("--query", required=True)
  823. search_parser.add_argument("--mode", choices=["vector", "bm25", "hybrid", "backtrack"], default="hybrid")
  824. search_parser.add_argument("--top-k", type=int, default=5)
  825. search_parser.add_argument("--chunk-type", choices=["scene", "summary"], default=None)
  826. args = parser.parse_args()
  827. # 初始化
  828. config = None
  829. if args.project_root:
  830. from .config import DataModulesConfig
  831. config = DataModulesConfig.from_project_root(args.project_root)
  832. adapter = RAGAdapter(config)
  833. tool_name = f"rag_adapter:{args.command or 'unknown'}"
  834. def emit_success(data=None, message: str = "ok"):
  835. print_success(data, message=message)
  836. safe_log_tool_call(adapter.index_manager, tool_name=tool_name, success=True)
  837. def emit_error(code: str, message: str, suggestion: str | None = None):
  838. print_error(code, message, suggestion=suggestion)
  839. safe_log_tool_call(
  840. adapter.index_manager,
  841. tool_name=tool_name,
  842. success=False,
  843. error_code=code,
  844. error_message=message,
  845. )
  846. if args.command == "stats":
  847. stats = adapter.get_stats()
  848. emit_success(stats, message="stats")
  849. elif args.command == "index-chapter":
  850. scenes = json.loads(args.scenes)
  851. chunks = []
  852. # summary chunk
  853. summary_text = args.summary
  854. if not summary_text and config:
  855. summary_path = config.webnovel_dir / "summaries" / f"ch{args.chapter:04d}.md"
  856. if summary_path.exists():
  857. summary_text = summary_path.read_text(encoding="utf-8")
  858. parent_chunk_id = None
  859. if summary_text:
  860. parent_chunk_id = f"ch{args.chapter:04d}_summary"
  861. chunks.append(
  862. {
  863. "chapter": args.chapter,
  864. "scene_index": 0,
  865. "content": summary_text,
  866. "chunk_type": "summary",
  867. "chunk_id": parent_chunk_id,
  868. "source_file": f"summaries/ch{args.chapter:04d}.md",
  869. }
  870. )
  871. for s in scenes:
  872. scene_index = s.get("index", 0)
  873. chunk_id = f"ch{args.chapter:04d}_s{int(scene_index)}"
  874. chunks.append(
  875. {
  876. "chapter": args.chapter,
  877. "scene_index": scene_index,
  878. "content": s.get("content", ""),
  879. "chunk_type": "scene",
  880. "parent_chunk_id": parent_chunk_id,
  881. "chunk_id": chunk_id,
  882. "source_file": f"正文/第{args.chapter:04d}章.md#scene_{int(scene_index)}",
  883. }
  884. )
  885. stored = asyncio.run(adapter.store_chunks(chunks))
  886. skipped = len(chunks) - stored
  887. result = {"stored": stored, "skipped": skipped, "total": len(chunks)}
  888. if skipped > 0:
  889. emit_success(result, message="indexed_with_warnings")
  890. else:
  891. emit_success(result, message="indexed")
  892. elif args.command == "search":
  893. if args.mode == "vector":
  894. results = asyncio.run(adapter.vector_search(args.query, args.top_k, chunk_type=args.chunk_type))
  895. elif args.mode == "bm25":
  896. results = adapter.bm25_search(args.query, args.top_k, chunk_type=args.chunk_type)
  897. elif args.mode == "backtrack":
  898. results = asyncio.run(adapter.search_with_backtrack(args.query, args.top_k))
  899. else:
  900. results = asyncio.run(adapter.hybrid_search(args.query, args.top_k, args.top_k, args.top_k, chunk_type=args.chunk_type))
  901. payload = [r.__dict__ for r in results]
  902. degraded_reason = adapter.degraded_mode_reason
  903. if degraded_reason:
  904. warnings = [{"code": "DEGRADED_MODE", "reason": degraded_reason}]
  905. print_success(payload, message="search_results", warnings=warnings)
  906. safe_log_tool_call(adapter.index_manager, tool_name=tool_name, success=True)
  907. else:
  908. emit_success(payload, message="search_results")
  909. else:
  910. emit_error("UNKNOWN_COMMAND", "未指定有效命令", suggestion="请查看 --help")
  911. if __name__ == "__main__":
  912. import sys
  913. if sys.platform == "win32":
  914. enable_windows_utf8_stdio()
  915. main()