rag_adapter.py 33 KB

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