rag_adapter.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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. from .config import get_config
  23. from .api_client import get_client
  24. @dataclass
  25. class SearchResult:
  26. """搜索结果"""
  27. chunk_id: str
  28. chapter: int
  29. scene_index: int
  30. content: str
  31. score: float
  32. source: str # "vector" | "bm25" | "hybrid"
  33. class RAGAdapter:
  34. """RAG 检索适配器"""
  35. def __init__(self, config=None):
  36. self.config = config or get_config()
  37. self.api_client = get_client(config)
  38. self._init_db()
  39. def _init_db(self):
  40. """初始化向量数据库"""
  41. self.config.ensure_dirs()
  42. with self._get_conn() as conn:
  43. cursor = conn.cursor()
  44. # 向量存储表
  45. cursor.execute("""
  46. CREATE TABLE IF NOT EXISTS vectors (
  47. chunk_id TEXT PRIMARY KEY,
  48. chapter INTEGER,
  49. scene_index INTEGER,
  50. content TEXT,
  51. embedding BLOB,
  52. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  53. )
  54. """)
  55. # BM25 倒排索引表
  56. cursor.execute("""
  57. CREATE TABLE IF NOT EXISTS bm25_index (
  58. term TEXT,
  59. chunk_id TEXT,
  60. tf REAL,
  61. PRIMARY KEY (term, chunk_id)
  62. )
  63. """)
  64. # 文档统计表
  65. cursor.execute("""
  66. CREATE TABLE IF NOT EXISTS doc_stats (
  67. chunk_id TEXT PRIMARY KEY,
  68. doc_length INTEGER
  69. )
  70. """)
  71. # 创建索引
  72. cursor.execute("CREATE INDEX IF NOT EXISTS idx_vectors_chapter ON vectors(chapter)")
  73. cursor.execute("CREATE INDEX IF NOT EXISTS idx_bm25_term ON bm25_index(term)")
  74. conn.commit()
  75. @contextmanager
  76. def _get_conn(self):
  77. """获取数据库连接(确保关闭,避免 Windows 下文件句柄泄漏)"""
  78. conn = sqlite3.connect(str(self.config.vector_db))
  79. try:
  80. yield conn
  81. finally:
  82. conn.close()
  83. def _get_vectors_count(self) -> int:
  84. with self._get_conn() as conn:
  85. cursor = conn.cursor()
  86. cursor.execute("SELECT COUNT(*) FROM vectors")
  87. row = cursor.fetchone()
  88. return int(row[0] or 0) if row else 0
  89. def _get_recent_chunk_ids(self, limit: int) -> List[str]:
  90. if limit <= 0:
  91. return []
  92. with self._get_conn() as conn:
  93. cursor = conn.cursor()
  94. cursor.execute(
  95. "SELECT chunk_id FROM vectors ORDER BY chapter DESC, scene_index DESC LIMIT ?",
  96. (int(limit),),
  97. )
  98. return [str(r[0]) for r in cursor.fetchall() if r and r[0]]
  99. def _fetch_vectors_by_chunk_ids(self, chunk_ids: List[str]) -> List[Tuple]:
  100. if not chunk_ids:
  101. return []
  102. # SQLite 参数数量限制(默认 999),这里做分片查询
  103. def _chunks(xs: List[str], size: int = 500):
  104. it = iter(xs)
  105. while True:
  106. batch = list(itertools.islice(it, size))
  107. if not batch:
  108. break
  109. yield batch
  110. rows: List[Tuple] = []
  111. with self._get_conn() as conn:
  112. cursor = conn.cursor()
  113. for batch in _chunks(chunk_ids):
  114. placeholders = ",".join(["?"] * len(batch))
  115. cursor.execute(
  116. f"SELECT chunk_id, chapter, scene_index, content, embedding FROM vectors WHERE chunk_id IN ({placeholders})",
  117. tuple(batch),
  118. )
  119. rows.extend(cursor.fetchall())
  120. return rows
  121. def _vector_search_rows(
  122. self,
  123. query_embedding: List[float],
  124. rows: List[Tuple],
  125. *,
  126. top_k: int,
  127. ) -> List[SearchResult]:
  128. results: List[SearchResult] = []
  129. for row in rows:
  130. chunk_id, chapter, scene_index, content, embedding_bytes = row
  131. if not embedding_bytes:
  132. continue
  133. embedding = self._deserialize_embedding(embedding_bytes)
  134. score = self._cosine_similarity(query_embedding, embedding)
  135. results.append(
  136. SearchResult(
  137. chunk_id=chunk_id,
  138. chapter=chapter,
  139. scene_index=scene_index,
  140. content=content,
  141. score=score,
  142. source="vector",
  143. )
  144. )
  145. results.sort(key=lambda x: x.score, reverse=True)
  146. return results[:top_k]
  147. # ==================== 向量存储 ====================
  148. async def store_chunks(self, chunks: List[Dict]) -> int:
  149. """
  150. 存储场景切片的向量
  151. chunks 格式:
  152. [
  153. {
  154. "chapter": 100,
  155. "scene_index": 1,
  156. "content": "场景内容..."
  157. }
  158. ]
  159. 返回存储数量
  160. """
  161. if not chunks:
  162. return 0
  163. # 提取内容用于嵌入
  164. contents = [c["content"] for c in chunks]
  165. # 调用 API 获取嵌入向量(可能包含 None 表示失败)
  166. embeddings = await self.api_client.embed_batch(contents)
  167. if not embeddings:
  168. return 0
  169. # 存储到数据库(跳过嵌入失败的 chunk)
  170. stored = 0
  171. skipped = 0
  172. with self._get_conn() as conn:
  173. cursor = conn.cursor()
  174. for chunk, embedding in zip(chunks, embeddings):
  175. if embedding is None:
  176. # 嵌入失败,跳过该 chunk(仅存储 BM25 索引供关键词检索)
  177. skipped += 1
  178. chunk_id = f"ch{chunk['chapter']}_s{chunk['scene_index']}"
  179. self._update_bm25_index(cursor, chunk_id, chunk["content"])
  180. continue
  181. chunk_id = f"ch{chunk['chapter']}_s{chunk['scene_index']}"
  182. # 将向量序列化为 bytes
  183. embedding_bytes = self._serialize_embedding(embedding)
  184. cursor.execute("""
  185. INSERT OR REPLACE INTO vectors
  186. (chunk_id, chapter, scene_index, content, embedding)
  187. VALUES (?, ?, ?, ?, ?)
  188. """, (
  189. chunk_id,
  190. chunk["chapter"],
  191. chunk["scene_index"],
  192. chunk["content"],
  193. embedding_bytes
  194. ))
  195. # 同时更新 BM25 索引
  196. self._update_bm25_index(cursor, chunk_id, chunk["content"])
  197. stored += 1
  198. conn.commit()
  199. if skipped > 0:
  200. print(f"[WARN] store_chunks: {skipped} chunks skipped due to embedding failure (BM25 only)")
  201. return stored
  202. def _serialize_embedding(self, embedding: List[float]) -> bytes:
  203. """序列化向量"""
  204. import struct
  205. return struct.pack(f"{len(embedding)}f", *embedding)
  206. def _deserialize_embedding(self, data: bytes) -> List[float]:
  207. """反序列化向量"""
  208. import struct
  209. count = len(data) // 4
  210. return list(struct.unpack(f"{count}f", data))
  211. # ==================== BM25 索引 ====================
  212. def _tokenize(self, text: str) -> List[str]:
  213. """简单分词(中文按字符,英文按单词)"""
  214. # 中文字符
  215. chinese = re.findall(r'[\u4e00-\u9fff]+', text)
  216. chinese_chars = list("".join(chinese))
  217. # 英文单词
  218. english = re.findall(r'[a-zA-Z]+', text.lower())
  219. return chinese_chars + english
  220. def _update_bm25_index(self, cursor, chunk_id: str, content: str):
  221. """更新 BM25 索引"""
  222. # 删除旧索引
  223. cursor.execute("DELETE FROM bm25_index WHERE chunk_id = ?", (chunk_id,))
  224. cursor.execute("DELETE FROM doc_stats WHERE chunk_id = ?", (chunk_id,))
  225. # 分词
  226. tokens = self._tokenize(content)
  227. doc_length = len(tokens)
  228. # 计算词频
  229. tf_counter = Counter(tokens)
  230. # 插入倒排索引
  231. for term, count in tf_counter.items():
  232. tf = count / doc_length if doc_length > 0 else 0
  233. cursor.execute("""
  234. INSERT INTO bm25_index (term, chunk_id, tf)
  235. VALUES (?, ?, ?)
  236. """, (term, chunk_id, tf))
  237. # 更新文档统计
  238. cursor.execute("""
  239. INSERT INTO doc_stats (chunk_id, doc_length)
  240. VALUES (?, ?)
  241. """, (chunk_id, doc_length))
  242. # ==================== 向量检索 ====================
  243. async def vector_search(
  244. self,
  245. query: str,
  246. top_k: int = None
  247. ) -> List[SearchResult]:
  248. """向量相似度搜索"""
  249. top_k = top_k or self.config.vector_top_k
  250. # 获取查询向量
  251. query_embeddings = await self.api_client.embed([query])
  252. if not query_embeddings:
  253. return []
  254. query_embedding = query_embeddings[0]
  255. # 从数据库读取所有向量并计算相似度
  256. with self._get_conn() as conn:
  257. cursor = conn.cursor()
  258. cursor.execute("SELECT chunk_id, chapter, scene_index, content, embedding FROM vectors")
  259. results = []
  260. for row in cursor.fetchall():
  261. chunk_id, chapter, scene_index, content, embedding_bytes = row
  262. embedding = self._deserialize_embedding(embedding_bytes)
  263. # 计算余弦相似度
  264. score = self._cosine_similarity(query_embedding, embedding)
  265. results.append(SearchResult(
  266. chunk_id=chunk_id,
  267. chapter=chapter,
  268. scene_index=scene_index,
  269. content=content,
  270. score=score,
  271. source="vector"
  272. ))
  273. # 排序并返回 top_k
  274. results.sort(key=lambda x: x.score, reverse=True)
  275. return results[:top_k]
  276. def _cosine_similarity(self, a: List[float], b: List[float]) -> float:
  277. """计算余弦相似度"""
  278. dot_product = sum(x * y for x, y in zip(a, b))
  279. norm_a = math.sqrt(sum(x * x for x in a))
  280. norm_b = math.sqrt(sum(x * x for x in b))
  281. if norm_a == 0 or norm_b == 0:
  282. return 0.0
  283. return dot_product / (norm_a * norm_b)
  284. # ==================== BM25 检索 ====================
  285. def bm25_search(
  286. self,
  287. query: str,
  288. top_k: int = None,
  289. k1: float = 1.5,
  290. b: float = 0.75
  291. ) -> List[SearchResult]:
  292. """BM25 关键词搜索"""
  293. top_k = top_k or self.config.bm25_top_k
  294. query_terms = self._tokenize(query)
  295. if not query_terms:
  296. return []
  297. with self._get_conn() as conn:
  298. cursor = conn.cursor()
  299. # 获取文档总数和平均长度
  300. cursor.execute("SELECT COUNT(*), AVG(doc_length) FROM doc_stats")
  301. row = cursor.fetchone()
  302. total_docs = row[0] or 1
  303. avg_doc_length = row[1] or 1
  304. # 计算每个文档的 BM25 分数
  305. doc_scores = {}
  306. for term in set(query_terms):
  307. # 获取包含该词的文档
  308. cursor.execute("""
  309. SELECT b.chunk_id, b.tf, d.doc_length
  310. FROM bm25_index b
  311. JOIN doc_stats d ON b.chunk_id = d.chunk_id
  312. WHERE b.term = ?
  313. """, (term,))
  314. docs_with_term = cursor.fetchall()
  315. df = len(docs_with_term)
  316. if df == 0:
  317. continue
  318. # IDF
  319. idf = math.log((total_docs - df + 0.5) / (df + 0.5) + 1)
  320. for chunk_id, tf, doc_length in docs_with_term:
  321. # BM25 公式
  322. score = idf * (tf * (k1 + 1)) / (tf + k1 * (1 - b + b * doc_length / avg_doc_length))
  323. if chunk_id not in doc_scores:
  324. doc_scores[chunk_id] = 0
  325. doc_scores[chunk_id] += score
  326. # 获取文档内容
  327. results = []
  328. for chunk_id, score in doc_scores.items():
  329. cursor.execute("""
  330. SELECT chapter, scene_index, content
  331. FROM vectors
  332. WHERE chunk_id = ?
  333. """, (chunk_id,))
  334. row = cursor.fetchone()
  335. if row:
  336. results.append(SearchResult(
  337. chunk_id=chunk_id,
  338. chapter=row[0],
  339. scene_index=row[1],
  340. content=row[2],
  341. score=score,
  342. source="bm25"
  343. ))
  344. results.sort(key=lambda x: x.score, reverse=True)
  345. return results[:top_k]
  346. # ==================== 混合检索 ====================
  347. async def hybrid_search(
  348. self,
  349. query: str,
  350. vector_top_k: int = None,
  351. bm25_top_k: int = None,
  352. rerank_top_n: int = None
  353. ) -> List[SearchResult]:
  354. """
  355. 混合检索:向量 + BM25 + RRF 融合 + Rerank
  356. 步骤:
  357. 1. 向量检索 top_k
  358. 2. BM25 检索 top_k
  359. 3. RRF 融合
  360. 4. Rerank 精排
  361. """
  362. vector_top_k = vector_top_k or self.config.vector_top_k
  363. bm25_top_k = bm25_top_k or self.config.bm25_top_k
  364. rerank_top_n = rerank_top_n or self.config.rerank_top_n
  365. # 小规模:全表向量扫描(召回更稳);大规模:预筛选避免 O(n) 扫描拖慢
  366. vectors_count = await asyncio.to_thread(self._get_vectors_count)
  367. use_full_scan = vectors_count <= int(self.config.vector_full_scan_max_vectors)
  368. if use_full_scan:
  369. # 并行执行向量和 BM25 检索
  370. vector_results, bm25_results = await asyncio.gather(
  371. self.vector_search(query, vector_top_k),
  372. asyncio.to_thread(self.bm25_search, query, bm25_top_k)
  373. )
  374. else:
  375. bm25_candidates = max(
  376. int(self.config.vector_prefilter_bm25_candidates),
  377. int(bm25_top_k),
  378. int(vector_top_k) * 5,
  379. int(rerank_top_n) * 10,
  380. )
  381. recent_candidates = max(
  382. int(self.config.vector_prefilter_recent_candidates),
  383. int(vector_top_k) * 5,
  384. int(rerank_top_n) * 10,
  385. )
  386. bm25_task = asyncio.to_thread(self.bm25_search, query, bm25_candidates)
  387. recent_task = asyncio.to_thread(self._get_recent_chunk_ids, recent_candidates)
  388. embed_task = self.api_client.embed([query])
  389. bm25_candidates_results, recent_ids, query_embeddings = await asyncio.gather(
  390. bm25_task,
  391. recent_task,
  392. embed_task,
  393. )
  394. if not query_embeddings:
  395. return []
  396. query_embedding = query_embeddings[0]
  397. candidate_ids = {r.chunk_id for r in bm25_candidates_results}
  398. candidate_ids.update(recent_ids)
  399. rows = await asyncio.to_thread(self._fetch_vectors_by_chunk_ids, list(candidate_ids))
  400. vector_results = await asyncio.to_thread(
  401. self._vector_search_rows,
  402. query_embedding,
  403. rows,
  404. top_k=int(vector_top_k),
  405. )
  406. # BM25 结果用于融合时只取 top_k
  407. bm25_results = list(bm25_candidates_results)[: int(bm25_top_k)]
  408. # RRF 融合
  409. rrf_scores = {}
  410. k = self.config.rrf_k
  411. for rank, result in enumerate(vector_results):
  412. if result.chunk_id not in rrf_scores:
  413. rrf_scores[result.chunk_id] = {"result": result, "score": 0}
  414. rrf_scores[result.chunk_id]["score"] += 1 / (k + rank + 1)
  415. for rank, result in enumerate(bm25_results):
  416. if result.chunk_id not in rrf_scores:
  417. rrf_scores[result.chunk_id] = {"result": result, "score": 0}
  418. rrf_scores[result.chunk_id]["score"] += 1 / (k + rank + 1)
  419. # 按 RRF 分数排序
  420. sorted_results = sorted(
  421. rrf_scores.values(),
  422. key=lambda x: x["score"],
  423. reverse=True
  424. )
  425. # 取 top candidates 进行 rerank
  426. candidates = [item["result"] for item in sorted_results[:rerank_top_n * 2]]
  427. if not candidates:
  428. return []
  429. # 调用 Rerank API
  430. documents = [c.content for c in candidates]
  431. rerank_results = await self.api_client.rerank(query, documents, top_n=rerank_top_n)
  432. if not rerank_results:
  433. # Rerank 失败,返回 RRF 结果
  434. return [item["result"] for item in sorted_results[:rerank_top_n]]
  435. # 组装最终结果
  436. final_results = []
  437. for r in rerank_results:
  438. idx = r.get("index", 0)
  439. if idx < len(candidates):
  440. result = candidates[idx]
  441. result.score = r.get("relevance_score", 0)
  442. result.source = "hybrid"
  443. final_results.append(result)
  444. return final_results
  445. # ==================== 统计 ====================
  446. def get_stats(self) -> Dict[str, int]:
  447. """获取 RAG 统计"""
  448. with self._get_conn() as conn:
  449. cursor = conn.cursor()
  450. cursor.execute("SELECT COUNT(*) FROM vectors")
  451. vectors = cursor.fetchone()[0]
  452. cursor.execute("SELECT COUNT(DISTINCT term) FROM bm25_index")
  453. terms = cursor.fetchone()[0]
  454. cursor.execute("SELECT MAX(chapter) FROM vectors")
  455. max_chapter = cursor.fetchone()[0] or 0
  456. return {
  457. "vectors": vectors,
  458. "terms": terms,
  459. "max_chapter": max_chapter
  460. }
  461. # ==================== CLI 接口 ====================
  462. def main():
  463. import argparse
  464. parser = argparse.ArgumentParser(description="RAG Adapter CLI")
  465. parser.add_argument("--project-root", type=str, help="项目根目录")
  466. subparsers = parser.add_subparsers(dest="command")
  467. # 获取统计
  468. subparsers.add_parser("stats")
  469. # 搜索
  470. search_parser = subparsers.add_parser("search")
  471. search_parser.add_argument("--query", required=True, help="搜索查询")
  472. search_parser.add_argument("--mode", choices=["vector", "bm25", "hybrid"], default="hybrid")
  473. search_parser.add_argument("--top-k", type=int, default=10)
  474. # 索引章节
  475. index_parser = subparsers.add_parser("index-chapter")
  476. index_parser.add_argument("--chapter", type=int, required=True)
  477. index_parser.add_argument("--scenes", required=True, help="JSON 格式的场景列表")
  478. args = parser.parse_args()
  479. # 初始化
  480. config = None
  481. if args.project_root:
  482. from .config import DataModulesConfig
  483. config = DataModulesConfig.from_project_root(args.project_root)
  484. adapter = RAGAdapter(config)
  485. if args.command == "stats":
  486. stats = adapter.get_stats()
  487. print(json.dumps(stats, ensure_ascii=False, indent=2))
  488. elif args.command == "search":
  489. async def do_search():
  490. if args.mode == "vector":
  491. results = await adapter.vector_search(args.query, args.top_k)
  492. elif args.mode == "bm25":
  493. results = adapter.bm25_search(args.query, args.top_k)
  494. else:
  495. results = await adapter.hybrid_search(args.query)
  496. print(f"搜索结果 ({len(results)} 条):")
  497. for r in results:
  498. print(f"\n[{r.source}] 第 {r.chapter} 章 场景 {r.scene_index} (score: {r.score:.4f})")
  499. print(f" {r.content[:100]}...")
  500. asyncio.run(do_search())
  501. elif args.command == "index-chapter":
  502. scenes = json.loads(args.scenes)
  503. chunks = [
  504. {
  505. "chapter": args.chapter,
  506. "scene_index": s.get("index", i),
  507. "content": s.get("summary", "") + "\n" + s.get("content", "")
  508. }
  509. for i, s in enumerate(scenes)
  510. ]
  511. async def do_index():
  512. stored = await adapter.store_chunks(chunks)
  513. print(f"✓ 已索引 {stored} 个场景")
  514. asyncio.run(do_index())
  515. if __name__ == "__main__":
  516. main()