653 lines
24 KiB
Python
653 lines
24 KiB
Python
import chromadb
|
||
from chromadb.config import Settings as ChromaSettings
|
||
from langchain_chroma import Chroma
|
||
from langchain_core.embeddings import Embeddings
|
||
from typing import List, Dict, Any, Optional, Tuple
|
||
import logging
|
||
import time
|
||
|
||
from app.config import settings
|
||
from app.core.bm25_index import Bm25Index
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
|
||
def parse_type_ids(help_type_id: str) -> List[str]:
|
||
"""将逗号分隔的 help_type_id 字符串拆分为数组,供存储和查询统一使用。
|
||
|
||
存储端把 help_type_id 存为数组(如 ["0","1","2","6","8"]),
|
||
查询端用 $contains + $or 做数组包含匹配。两者必须用同一解析函数保证格式一致。
|
||
|
||
兼容新旧端标识:1 和 3 都代表 android 端,2 和 4 都代表 iOS 端。
|
||
早期用 1/2,现在用 3/4。因此若列表含 1 则补 3,含 2 则补 4。
|
||
"""
|
||
if help_type_id is None:
|
||
return []
|
||
type_ids = [t.strip() for t in str(help_type_id).split(",") if t.strip()]
|
||
|
||
# 新旧端标识兼容:1<->3 (android),2<->4 (iOS)
|
||
if "1" in type_ids and "3" not in type_ids:
|
||
type_ids.append("3")
|
||
if "2" in type_ids and "4" not in type_ids:
|
||
type_ids.append("4")
|
||
|
||
return type_ids
|
||
|
||
|
||
def build_type_filter(type_ids: List[str]) -> Optional[Dict[str, Any]]:
|
||
"""为数组类型的 help_type_id 构建 chroma where filter。
|
||
|
||
chroma 对数组字段使用 $contains 操作符(而非 $in)。
|
||
多值匹配需用 $or 组合多个 $contains。
|
||
"""
|
||
if not type_ids:
|
||
return None
|
||
if len(type_ids) == 1:
|
||
return {"help_type_id": {"$contains": type_ids[0]}}
|
||
return {"$or": [{"help_type_id": {"$contains": tid}} for tid in type_ids]}
|
||
|
||
|
||
class ChromaVectorStoreAdapter:
|
||
"""ChromaDB 向量存储适配器,使用 langchain_chroma.Chroma
|
||
|
||
暴露与原 ChromaDBClient 完全一致的公共接口,便于零停机迁移。
|
||
"""
|
||
|
||
def __init__(self, embeddings: Embeddings):
|
||
self._embeddings = embeddings
|
||
self._client = chromadb.PersistentClient(
|
||
path=settings.chromadb_path,
|
||
settings=ChromaSettings(anonymized_telemetry=False)
|
||
)
|
||
logger.info(
|
||
"ChromaDB initialized: version=%s, path=%s",
|
||
chromadb.__version__,
|
||
settings.chromadb_path,
|
||
)
|
||
self._knowledge = None
|
||
self._questions = None
|
||
self._faq = None
|
||
self._init_collections()
|
||
|
||
# BM25 索引
|
||
self._knowledge_bm25: Optional[Bm25Index] = None
|
||
self._questions_bm25: Optional[Bm25Index] = None
|
||
self._faq_bm25: Optional[Bm25Index] = None
|
||
if settings.bm25_enabled:
|
||
self._knowledge_bm25 = Bm25Index("knowledge")
|
||
self._questions_bm25 = Bm25Index("questions")
|
||
self._faq_bm25 = Bm25Index("faq")
|
||
self._init_bm25_consistency()
|
||
|
||
def _init_collections(self):
|
||
"""初始化两个集合,确保使用 cosine 空间"""
|
||
# Knowledge 集合
|
||
self._knowledge = Chroma(
|
||
client=self._client,
|
||
collection_name="knowledge",
|
||
embedding_function=self._embeddings,
|
||
collection_metadata={"hnsw:space": "cosine"},
|
||
)
|
||
|
||
# Questions 集合
|
||
self._questions = Chroma(
|
||
client=self._client,
|
||
collection_name="questions",
|
||
embedding_function=self._embeddings,
|
||
collection_metadata={"hnsw:space": "cosine"},
|
||
)
|
||
|
||
# FAQ 集合
|
||
self._faq = Chroma(
|
||
client=self._client,
|
||
collection_name="faq",
|
||
embedding_function=self._embeddings,
|
||
collection_metadata={"hnsw:space": "cosine"},
|
||
)
|
||
|
||
logger.info("ChromaDB collections initialized with cosine space via LangChain")
|
||
|
||
@property
|
||
def knowledge(self):
|
||
return self._knowledge
|
||
|
||
@property
|
||
def questions(self):
|
||
return self._questions
|
||
|
||
@property
|
||
def faq(self):
|
||
return self._faq
|
||
|
||
# ==================== Knowledge 集合操作 ====================
|
||
|
||
def add_chunks(
|
||
self,
|
||
chunks: List[str],
|
||
embeddings: List[List[float]],
|
||
metadatas: List[Dict[str, Any]],
|
||
ids: List[str]
|
||
) -> None:
|
||
"""批量添加文档块到 knowledge 集合"""
|
||
self._knowledge.add_texts(
|
||
texts=chunks,
|
||
embeddings=embeddings,
|
||
metadatas=metadatas,
|
||
ids=ids
|
||
)
|
||
self._rebuild_knowledge_bm25()
|
||
|
||
def search_knowledge(
|
||
self,
|
||
query_embedding: List[float],
|
||
help_type_id: str,
|
||
top_k: int
|
||
) -> List[Dict[str, Any]]:
|
||
"""在 knowledge 集合中搜索,按 help_type_id 过滤"""
|
||
type_ids = parse_type_ids(help_type_id)
|
||
where_filter = build_type_filter(type_ids)
|
||
|
||
# 使用 similarity_search_by_vector_with_relevance_scores 获取分数
|
||
print(f"[DEBUG] search_knowledge: top_k={top_k}, type_ids={type_ids}, where_filter={where_filter}")
|
||
results = self._knowledge.similarity_search_by_vector_with_relevance_scores(
|
||
embedding=query_embedding,
|
||
k=top_k,
|
||
filter=where_filter,
|
||
)
|
||
print(f"[DEBUG] search_knowledge: raw results count={len(results)}")
|
||
|
||
return self._format_results(results)
|
||
|
||
def search_knowledge_hybrid(
|
||
self,
|
||
query_embedding: List[float],
|
||
query_text: str,
|
||
help_type_id: str,
|
||
top_k: int,
|
||
expanded_words: Optional[List[str]] = None,
|
||
) -> List[Dict[str, Any]]:
|
||
"""混合检索 knowledge 集合:向量检索 + BM25 关键词检索,RRF 融合。
|
||
|
||
BM25 路径使用 jieba 分词并去除停用词(见 bm25_index._tokenize),
|
||
语义路径使用原始文本(保留停用词),两路差异化处理停用词。
|
||
|
||
查询扩展(expanded_words,来自 preprocess 节点):
|
||
- 向量路:每个扩展词单独 embed + 检索,按 doc_id 合并去重,排在原查询结果之后;
|
||
- BM25 路:原问句 + 扩展词拼接成单一查询文本,一次检索;
|
||
- 扩展词为 None/空 时行为与旧版完全一致。
|
||
"""
|
||
# 1. 向量检索(原始文本,保留停用词)+ 扩展词向量检索
|
||
vector_results = self.search_knowledge(query_embedding, help_type_id, top_k)
|
||
if settings.rag_expansion_enabled and expanded_words:
|
||
vector_results = self._expand_vector_search(
|
||
vector_results, expanded_words, help_type_id
|
||
)
|
||
print(f"[DEBUG] vector_results ({len(vector_results)} 条):")
|
||
for i, r in enumerate(vector_results):
|
||
print(f" [{i+1}] id={r['id']} score={r.get('score', 'N/A')} doc={r['document'][:80]}...")
|
||
|
||
# 2. BM25 关键词检索(jieba+去停用词;扩展词拼接进查询文本)
|
||
bm25_query = query_text
|
||
if settings.rag_expansion_enabled and expanded_words:
|
||
bm25_query = query_text + " " + " ".join(expanded_words)
|
||
bm25_results = []
|
||
if self._knowledge_bm25:
|
||
bm25_results = self._knowledge_bm25.search(bm25_query, top_k=top_k)
|
||
print(f"[DEBUG] bm25_results ({len(bm25_results)} 条): query={bm25_query!r}")
|
||
for i, (doc_id, bm25_score) in enumerate(bm25_results):
|
||
print(f" [{i+1}] id={doc_id} bm25_score={bm25_score}")
|
||
|
||
# 3. RRF 融合
|
||
return rrf_fuse(vector_results, bm25_results, settings.rrf_alpha)
|
||
|
||
def _expand_vector_search(
|
||
self,
|
||
base_results: List[Dict[str, Any]],
|
||
expanded_words: List[str],
|
||
help_type_id: str,
|
||
) -> List[Dict[str, Any]]:
|
||
"""扩展词向量检索:批量 embed 扩展词,逐词检索,按 doc_id 合并去重。
|
||
|
||
合并规则:
|
||
- 原查询结果保持原序排前(rank 1..N),扩展结果按分数降序排后;
|
||
- 已存在于原查询结果的 doc_id 不再重复追加(避免 RRF 双计);
|
||
- 扩展结果之间按 doc_id 去重,保留首次出现(search_knowledge 已按分数
|
||
降序返回,同一扩展词内高分先出现;跨扩展词不比较分数)。
|
||
"""
|
||
# 过滤空字符串扩展词(避免 embed 空串产生无效向量)
|
||
expanded_words = [w for w in expanded_words if w.strip()]
|
||
if not expanded_words:
|
||
return base_results
|
||
|
||
try:
|
||
exp_embeddings = self._embeddings.embed_documents(expanded_words)
|
||
except Exception as e:
|
||
logger.warning(f"expand: embed expanded_words 失败,跳过扩展: {e}")
|
||
return base_results
|
||
|
||
# 长度校验:embedding 数量与扩展词不一致时 fail-open(避免 zip 静默截断)
|
||
if len(exp_embeddings) != len(expanded_words):
|
||
logger.warning(
|
||
f"expand: embed_documents 返回 {len(exp_embeddings)} 条,"
|
||
f"期望 {len(expanded_words)} 条,跳过扩展"
|
||
)
|
||
return base_results
|
||
|
||
seen_ids = {r["id"] for r in base_results}
|
||
merged = list(base_results)
|
||
for word, emb in zip(expanded_words, exp_embeddings):
|
||
try:
|
||
exp_results = self.search_knowledge(emb, help_type_id, settings.rag_expansion_top_k)
|
||
except Exception as e:
|
||
# 单个扩展词检索失败不拖垮整个混合检索(fail-open)
|
||
logger.warning(f"expand: 扩展词 {word!r} 检索失败,跳过: {e}")
|
||
continue
|
||
print(f"[DEBUG] expand: word={word!r} results={len(exp_results)} 条")
|
||
for r in exp_results:
|
||
if r["id"] not in seen_ids:
|
||
seen_ids.add(r["id"])
|
||
merged.append(r)
|
||
return merged
|
||
|
||
def delete_by_file_id(self, file_id: int) -> None:
|
||
"""根据 file_id 删除文档块"""
|
||
self._knowledge.delete(where={"file_id": file_id})
|
||
self._rebuild_knowledge_bm25()
|
||
|
||
# ==================== Questions 集合操作 ====================
|
||
|
||
def get_question_by_id(self, help_id: int) -> Optional[Dict[str, Any]]:
|
||
"""通过确定性 ID 精确查找问题"""
|
||
deterministic_id = f"q-{help_id}"
|
||
try:
|
||
# 使用底层 client 直接获取,因为 LangChain Chroma 没有直接暴露 get by id
|
||
results = self._questions._collection.get(
|
||
ids=[deterministic_id],
|
||
include=["documents", "metadatas", "embeddings"]
|
||
)
|
||
if results["ids"]:
|
||
return {
|
||
"id": results["ids"][0],
|
||
"document": results["documents"][0],
|
||
"metadata": results["metadatas"][0],
|
||
"embedding": results["embeddings"][0] if results["embeddings"] else None
|
||
}
|
||
except Exception as e:
|
||
logger.debug(f"Question not found by ID {deterministic_id}: {e}")
|
||
return None
|
||
|
||
def upsert_question(
|
||
self,
|
||
help_id: int,
|
||
question: str,
|
||
embedding: List[float],
|
||
help_type_id: str,
|
||
state: int
|
||
) -> None:
|
||
"""插入或更新问题 (使用确定性 ID)"""
|
||
deterministic_id = f"q-{help_id}"
|
||
self._questions.add_texts(
|
||
texts=[question],
|
||
embeddings=[embedding],
|
||
metadatas=[{
|
||
"id": deterministic_id,
|
||
"help_id": help_id,
|
||
"help_type_id": parse_type_ids(help_type_id),
|
||
"state": state,
|
||
"timestamp": int(time.time())
|
||
}],
|
||
ids=[deterministic_id]
|
||
)
|
||
self._rebuild_questions_bm25()
|
||
|
||
def search_questions(
|
||
self,
|
||
query_embedding: List[float],
|
||
help_type_id: str,
|
||
top_k: int,
|
||
threshold: float
|
||
) -> List[Dict[str, Any]]:
|
||
"""在 questions 集合中语义搜索"""
|
||
type_ids = parse_type_ids(help_type_id)
|
||
where_filter = build_type_filter(type_ids)
|
||
|
||
results = self._questions.similarity_search_by_vector_with_relevance_scores(
|
||
embedding=query_embedding,
|
||
k=top_k,
|
||
filter=where_filter,
|
||
)
|
||
|
||
return self._format_results(results)
|
||
|
||
def search_questions_hybrid(
|
||
self,
|
||
query_embedding: List[float],
|
||
query_text: str,
|
||
help_type_id: str,
|
||
top_k: int,
|
||
) -> List[Dict[str, Any]]:
|
||
"""混合检索 questions 集合:向量检索 + BM25 关键词检索,RRF 融合。
|
||
|
||
BM25 路径使用 jieba 分词并去除停用词,语义路径保留停用词。
|
||
"""
|
||
vector_results = self.search_questions(query_embedding, help_type_id, top_k, threshold=0.0)
|
||
|
||
bm25_results = []
|
||
if self._questions_bm25:
|
||
bm25_results = self._questions_bm25.search(query_text, top_k=top_k)
|
||
|
||
return rrf_fuse(vector_results, bm25_results, settings.rrf_alpha)
|
||
|
||
def search_faq_hybrid(
|
||
self,
|
||
query_embedding: List[float],
|
||
query_text: str,
|
||
help_type_id: str,
|
||
top_k: int,
|
||
) -> List[Dict[str, Any]]:
|
||
"""混合检索 faq 集合:向量检索 + BM25 关键词检索,RRF 融合,group_id 去重。
|
||
|
||
与 search_questions_hybrid 同构(v1 不用 expanded_words,D7)。
|
||
"""
|
||
if self._faq is None:
|
||
# 防御:faq collection 未初始化(审查 M5)
|
||
logger.warning("search_faq_hybrid: faq collection 未初始化")
|
||
return []
|
||
|
||
type_ids = parse_type_ids(help_type_id)
|
||
where_filter = build_type_filter(type_ids)
|
||
|
||
# 1. 向量检索(按 help_type_id 过滤)
|
||
vector_results = self._faq.similarity_search_by_vector_with_relevance_scores(
|
||
embedding=query_embedding,
|
||
k=top_k,
|
||
filter=where_filter,
|
||
)
|
||
vector_results = self._format_results(vector_results)
|
||
|
||
# 2. BM25 关键词检索
|
||
bm25_results = []
|
||
if self._faq_bm25:
|
||
bm25_results = self._faq_bm25.search(query_text, top_k=top_k)
|
||
|
||
# 3. RRF 融合
|
||
fused = rrf_fuse(vector_results, bm25_results, settings.rrf_alpha)
|
||
|
||
# 4. 补充 BM25 独有条目的 document/metadata
|
||
# (rrf_fuse 对仅出现在 BM25 的结果只给空 document 与空 metadata;
|
||
# 而 faq 的答案在 metadata.answer,必须回填才能用于直返与上下文)
|
||
missing = [r for r in fused if not r.get("metadata")]
|
||
if missing:
|
||
try:
|
||
got = self._faq._collection.get(
|
||
ids=[r["id"] for r in missing],
|
||
include=["documents", "metadatas"]
|
||
)
|
||
if not got["ids"]:
|
||
# Chroma 与 BM25 索引不一致(重建不同步),回填必然失败,需告警(审查 M2)
|
||
logger.warning(
|
||
"search_faq_hybrid: %d 个 BM25 条目在 Chroma 中不存在,回填跳过",
|
||
len(missing),
|
||
)
|
||
else:
|
||
by_id = {
|
||
i: (d, m)
|
||
for i, d, m in zip(got["ids"], got["documents"], got["metadatas"])
|
||
}
|
||
for r in missing:
|
||
doc, meta = by_id.get(r["id"], ("", {}))
|
||
r["document"] = doc
|
||
r["metadata"] = meta
|
||
except Exception as e:
|
||
logger.warning(f"search_faq_hybrid: 补充 BM25 条目 metadata 失败: {e}")
|
||
|
||
# 5. group_id 去重(D3):保留 hybrid_score 最高者
|
||
deduped: Dict[str, Dict[str, Any]] = {}
|
||
for r in fused:
|
||
gid = (r.get("metadata") or {}).get("group_id")
|
||
if gid is None:
|
||
# 无 group_id 的条目按 id 保底去重
|
||
deduped.setdefault(r["id"], r)
|
||
continue
|
||
prev = deduped.get(gid)
|
||
if prev is None or r["hybrid_score"] > prev["hybrid_score"]:
|
||
deduped[gid] = r
|
||
|
||
return sorted(deduped.values(), key=lambda r: r["hybrid_score"], reverse=True)
|
||
|
||
def delete_questions(self, help_ids: List[int]) -> None:
|
||
"""批量删除问题:一次删 Chroma,只重建一次 BM25"""
|
||
if not help_ids:
|
||
return
|
||
ids = [f"q-{h}" for h in help_ids]
|
||
self._questions.delete(ids=ids)
|
||
self._rebuild_questions_bm25()
|
||
|
||
def _format_results(self, results: List[tuple]) -> List[Dict[str, Any]]:
|
||
"""格式化 LangChain Chroma 查询结果 (document, distance) 元组列表。
|
||
|
||
注意:langchain-chroma 的 similarity_search_by_vector_with_relevance_scores
|
||
实际返回的是 cosine distance(0 = 完全相同,越大越不像),而非相似度。
|
||
score 字段转换为 similarity = 1 - distance(越高越相似),供阈值过滤使用。
|
||
"""
|
||
formatted = []
|
||
for doc, distance in results:
|
||
formatted.append({
|
||
"id": doc.metadata.get("id", ""),
|
||
"document": doc.page_content,
|
||
"metadata": doc.metadata,
|
||
"distance": distance,
|
||
"score": 1.0 - distance,
|
||
})
|
||
return formatted
|
||
|
||
# ==================== BM25 索引管理 ====================
|
||
|
||
def _rebuild_knowledge_bm25(self) -> None:
|
||
"""重建 knowledge BM25 索引"""
|
||
if not self._knowledge_bm25:
|
||
return
|
||
try:
|
||
data = self._knowledge._collection.get(include=["documents"])
|
||
if not data["ids"]:
|
||
return
|
||
doc_ids = data["ids"]
|
||
texts = data["documents"]
|
||
self._knowledge_bm25.rebuild(doc_ids, texts)
|
||
except Exception as e:
|
||
logger.warning(f"Failed to rebuild knowledge BM25: {e}")
|
||
|
||
def _rebuild_questions_bm25(self) -> None:
|
||
"""重建 questions BM25 索引"""
|
||
if not self._questions_bm25:
|
||
return
|
||
try:
|
||
data = self._questions._collection.get(include=["documents"])
|
||
if not data["ids"]:
|
||
return
|
||
doc_ids = data["ids"]
|
||
texts = data["documents"]
|
||
self._questions_bm25.rebuild(doc_ids, texts)
|
||
except Exception as e:
|
||
logger.warning(f"Failed to rebuild questions BM25: {e}")
|
||
|
||
def _init_bm25_consistency(self) -> None:
|
||
"""启动时校验 BM25 索引与向量库的一致性"""
|
||
if not self._knowledge_bm25 and not self._questions_bm25 and not self._faq_bm25:
|
||
return
|
||
|
||
if self._knowledge_bm25:
|
||
try:
|
||
count = self._knowledge._collection.count()
|
||
self._knowledge_bm25.load_or_rebuild(
|
||
count,
|
||
lambda: self._get_all_knowledge()
|
||
)
|
||
except Exception as e:
|
||
logger.warning(f"Knowledge BM25 init failed: {e}")
|
||
|
||
if self._questions_bm25:
|
||
try:
|
||
count = self._questions._collection.count()
|
||
self._questions_bm25.load_or_rebuild(
|
||
count,
|
||
lambda: self._get_all_questions()
|
||
)
|
||
except Exception as e:
|
||
logger.warning(f"Questions BM25 init failed: {e}")
|
||
|
||
if self._faq_bm25:
|
||
try:
|
||
count = self._faq._collection.count()
|
||
self._faq_bm25.load_or_rebuild(
|
||
count,
|
||
lambda: self._get_all_faq()
|
||
)
|
||
except Exception as e:
|
||
logger.warning(f"FAQ BM25 init failed: {e}")
|
||
|
||
def _get_all_knowledge(self):
|
||
"""获取全部 knowledge 文档 ID 和文本"""
|
||
data = self._knowledge._collection.get(include=["documents"])
|
||
return data["ids"], data["documents"]
|
||
|
||
def _get_all_questions(self):
|
||
"""获取全部 question 文档 ID 和文本"""
|
||
data = self._questions._collection.get(include=["documents"])
|
||
return data["ids"], data["documents"]
|
||
|
||
def _get_all_faq(self):
|
||
"""获取全部 faq 文档 ID 和文本"""
|
||
data = self._faq._collection.get(include=["documents"])
|
||
return data["ids"], data["documents"]
|
||
|
||
def _rebuild_faq_bm25(self) -> None:
|
||
"""重建 faq BM25 索引"""
|
||
if not self._faq_bm25:
|
||
return
|
||
try:
|
||
data = self._faq._collection.get(include=["documents"])
|
||
if not data["ids"]:
|
||
return
|
||
doc_ids = data["ids"]
|
||
texts = data["documents"]
|
||
self._faq_bm25.rebuild(doc_ids, texts)
|
||
except Exception as e:
|
||
logger.warning(f"Failed to rebuild FAQ BM25: {e}")
|
||
|
||
def add_faq_entries(
|
||
self,
|
||
questions: List[str],
|
||
embeddings: List[List[float]],
|
||
metadatas: List[Dict[str, Any]],
|
||
ids: List[str]
|
||
) -> None:
|
||
"""批量添加 FAQ 条目到 faq 集合。
|
||
|
||
texts 存问题(Q),答案(A)在 metadata.answer —— 与草案「仅对 Q 向量化」一致。
|
||
"""
|
||
self._faq.add_texts(
|
||
texts=questions,
|
||
embeddings=embeddings,
|
||
metadatas=metadatas,
|
||
ids=ids
|
||
)
|
||
self._rebuild_faq_bm25()
|
||
|
||
def delete_faq_by_file_id(self, file_id: int) -> None:
|
||
"""根据 file_id 删除 FAQ 条目"""
|
||
self._faq.delete(where={"file_id": file_id})
|
||
self._rebuild_faq_bm25()
|
||
|
||
def health_check(self) -> Dict[str, Any]:
|
||
"""健康检查"""
|
||
try:
|
||
knowledge_count = self._knowledge._collection.count()
|
||
questions_count = self._questions._collection.count()
|
||
faq_count = self._faq._collection.count()
|
||
return {
|
||
"status": "healthy",
|
||
"chromadb_version": chromadb.__version__,
|
||
"knowledge_count": knowledge_count,
|
||
"questions_count": questions_count,
|
||
"faq_count": faq_count
|
||
}
|
||
except Exception as e:
|
||
return {
|
||
"status": "unhealthy",
|
||
"error": str(e)
|
||
}
|
||
|
||
|
||
def rrf_fuse(
|
||
vector_results: List[Dict[str, Any]],
|
||
bm25_results: List[Tuple[str, float]],
|
||
alpha: float = 60.0,
|
||
) -> List[Dict[str, Any]]:
|
||
"""RRF (Reciprocal Rank Fusion) 融合向量检索与 BM25 检索结果。
|
||
|
||
公式: score(doc) = Σ 1/(rank + alpha)
|
||
- 只出现在一路的结果得 1/(rank+alpha)
|
||
- 两路都出现的结果分数叠加,排名越靠前融合分越高
|
||
- alpha 越大越平滑,默认 60
|
||
|
||
Args:
|
||
vector_results: 向量检索结果(含 id/document/metadata/distance/score)
|
||
bm25_results: BM25 检索结果 [(doc_id, score), ...]
|
||
alpha: RRF 平滑参数
|
||
|
||
Returns:
|
||
按融合分降序排列的结果列表,每个元素在原 vector_results 基础上
|
||
增加 "hybrid_score" 字段
|
||
"""
|
||
# 记录每个文档在向量检索中的排名(1-based)
|
||
rank_map = {r["id"]: i + 1 for i, r in enumerate(vector_results)}
|
||
# 记录每个文档在 BM25 检索中的排名(1-based)
|
||
bm25_rank_map = {doc_id: i + 1 for i, (doc_id, _) in enumerate(bm25_results)}
|
||
|
||
# 计算融合分
|
||
fused = []
|
||
for r in vector_results:
|
||
score = 1.0 / (rank_map[r["id"]] + alpha)
|
||
if r["id"] in bm25_rank_map:
|
||
score += 1.0 / (bm25_rank_map[r["id"]] + alpha)
|
||
out = dict(r)
|
||
out["hybrid_score"] = round(score, 6)
|
||
fused.append(out)
|
||
|
||
# 仅出现在 BM25 但未出现在向量结果中的文档(补充召回)
|
||
for doc_id, _ in bm25_results:
|
||
if doc_id not in rank_map:
|
||
fused.append({
|
||
"id": doc_id,
|
||
"document": "",
|
||
"metadata": {},
|
||
"distance": None,
|
||
"score": 0.0,
|
||
"hybrid_score": round(1.0 / (bm25_rank_map[doc_id] + alpha), 6),
|
||
})
|
||
|
||
# 按融合分降序,截断到 rag_top_k(融合会补充 BM25 独有条目导致数量膨胀)
|
||
fused.sort(key=lambda x: x["hybrid_score"], reverse=True)
|
||
fused = fused[:settings.rag_top_k]
|
||
return fused
|
||
|
||
|
||
# 单例实例将在 embeddings.py 初始化后创建
|
||
# 这里提供一个工厂函数
|
||
def create_vector_store_adapter(embeddings: Embeddings) -> ChromaVectorStoreAdapter:
|
||
"""创建向量存储适配器实例"""
|
||
return ChromaVectorStoreAdapter(embeddings)
|
||
|
||
|
||
# 全局单例(延迟初始化)
|
||
_vector_store_adapter = None
|
||
|
||
|
||
def get_vector_store_adapter() -> ChromaVectorStoreAdapter:
|
||
"""获取向量存储适配器单例"""
|
||
global _vector_store_adapter
|
||
if _vector_store_adapter is None:
|
||
from app.core.embeddings import ollama_embeddings_adapter
|
||
_vector_store_adapter = create_vector_store_adapter(ollama_embeddings_adapter)
|
||
return _vector_store_adapter |