first commit
This commit is contained in:
@@ -0,0 +1,195 @@
|
||||
import chromadb
|
||||
from chromadb.config import Settings as ChromaSettings
|
||||
from typing import List, Dict, Any, Optional
|
||||
import logging
|
||||
|
||||
from app.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ChromaDBClient:
|
||||
"""ChromaDB 客户端封装,使用 PersistentClient 嵌入模式"""
|
||||
|
||||
def __init__(self):
|
||||
self.client = chromadb.PersistentClient(
|
||||
path=settings.chromadb_path,
|
||||
settings=ChromaSettings(anonymized_telemetry=False)
|
||||
)
|
||||
self._knowledge = None
|
||||
self._questions = None
|
||||
self._init_collections()
|
||||
|
||||
def _init_collections(self):
|
||||
"""初始化两个集合,确保使用 cosine 空间"""
|
||||
# Knowledge 集合
|
||||
self._knowledge = self.client.get_or_create_collection(
|
||||
name="knowledge",
|
||||
metadata={
|
||||
"hnsw": {"space": "cosine"}
|
||||
}
|
||||
)
|
||||
|
||||
# Questions 集合
|
||||
self._questions = self.client.get_or_create_collection(
|
||||
name="questions",
|
||||
metadata={
|
||||
"hnsw": {"space": "cosine"}
|
||||
}
|
||||
)
|
||||
|
||||
logger.info("ChromaDB collections initialized with cosine space")
|
||||
|
||||
@property
|
||||
def knowledge(self):
|
||||
return self._knowledge
|
||||
|
||||
@property
|
||||
def questions(self):
|
||||
return self._questions
|
||||
|
||||
# ==================== 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(
|
||||
documents=chunks,
|
||||
embeddings=embeddings,
|
||||
metadatas=metadatas,
|
||||
ids=ids
|
||||
)
|
||||
|
||||
def search_knowledge(
|
||||
self,
|
||||
query_embedding: List[float],
|
||||
help_type_id: str,
|
||||
top_k: int
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""在 knowledge 集合中搜索,按 help_type_id 过滤"""
|
||||
# 解析 help_type_id (逗号分隔字符串)
|
||||
type_ids = [t.strip() for t in help_type_id.split(",") if t.strip()]
|
||||
|
||||
where_filter = {"help_type_id": {"$in": type_ids}} if type_ids else None
|
||||
|
||||
results = self._knowledge.query(
|
||||
query_embeddings=[query_embedding],
|
||||
n_results=top_k,
|
||||
where=where_filter,
|
||||
include=["documents", "metadatas", "distances"]
|
||||
)
|
||||
|
||||
return self._format_results(results)
|
||||
|
||||
def delete_by_file_id(self, file_id: int) -> None:
|
||||
"""根据 file_id 删除文档块"""
|
||||
self._knowledge.delete(where={"file_id": file_id})
|
||||
|
||||
# ==================== Questions 集合操作 ====================
|
||||
|
||||
def get_question_by_id(self, help_id: int) -> Optional[Dict[str, Any]]:
|
||||
"""通过确定性 ID 精确查找问题"""
|
||||
deterministic_id = f"q-{help_id}"
|
||||
try:
|
||||
results = self._questions.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.upsert(
|
||||
ids=[deterministic_id],
|
||||
documents=[question],
|
||||
embeddings=[embedding],
|
||||
metadatas=[{
|
||||
"help_id": help_id,
|
||||
"help_type_id": help_type_id,
|
||||
"state": state,
|
||||
"timestamp": int(__import__('time').time())
|
||||
}]
|
||||
)
|
||||
|
||||
def search_questions(
|
||||
self,
|
||||
query_embedding: List[float],
|
||||
help_type_id: str,
|
||||
top_k: int,
|
||||
threshold: float
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""在 questions 集合中语义搜索"""
|
||||
type_ids = [t.strip() for t in help_type_id.split(",") if t.strip()]
|
||||
|
||||
where_filter = {"help_type_id": {"$in": type_ids}} if type_ids else None
|
||||
|
||||
results = self._questions.query(
|
||||
query_embeddings=[query_embedding],
|
||||
n_results=top_k,
|
||||
where=where_filter,
|
||||
include=["documents", "metadatas", "distances"]
|
||||
)
|
||||
|
||||
return self._format_results(results)
|
||||
|
||||
def delete_question(self, help_id: int) -> None:
|
||||
"""删除问题"""
|
||||
deterministic_id = f"q-{help_id}"
|
||||
self._questions.delete(ids=[deterministic_id])
|
||||
|
||||
def _format_results(self, results: Dict) -> List[Dict[str, Any]]:
|
||||
"""格式化 ChromaDB 查询结果"""
|
||||
formatted = []
|
||||
if results["ids"] and results["ids"][0]:
|
||||
for i, doc_id in enumerate(results["ids"][0]):
|
||||
formatted.append({
|
||||
"id": doc_id,
|
||||
"document": results["documents"][0][i],
|
||||
"metadata": results["metadatas"][0][i],
|
||||
"distance": results["distances"][0][i],
|
||||
"score": 1.0 - results["distances"][0][i] # cosine similarity = 1 - distance
|
||||
})
|
||||
return formatted
|
||||
|
||||
def health_check(self) -> Dict[str, Any]:
|
||||
"""健康检查"""
|
||||
try:
|
||||
# 尝试获取集合信息
|
||||
knowledge_count = self._knowledge.count()
|
||||
questions_count = self._questions.count()
|
||||
return {
|
||||
"status": "healthy",
|
||||
"knowledge_count": knowledge_count,
|
||||
"questions_count": questions_count
|
||||
}
|
||||
except Exception as e:
|
||||
return {
|
||||
"status": "unhealthy",
|
||||
"error": str(e)
|
||||
}
|
||||
|
||||
|
||||
# 单例实例
|
||||
chromadb_client = ChromaDBClient()
|
||||
Reference in New Issue
Block a user