rag_adapter.py 33 KB

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