rag_adapter.py 33 KB

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