Files
HenryandClaude Code 26e13ff032 feat: Agent 工作区初始提交(源码+文档+Skills)
包含 CodeAgent 前后端源码、SKILLS、MCP、demo 代码与工作区文档。
排除依赖缓存、运行数据、备份与二进制附件,规则见 .gitignore。

Co-Authored-By: Claude Code <[email protected]>
2026-11-13 13:48:41 +08:00

192 lines
6.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
向量存储模块
============
【功能说明】
封装 Chroma 向量库的连接、入库、检索、删除能力,
对应《核心诉求》的「持久化存入向量数据库」与「智能检索」环节。
【技术选型理由】
1. 选 Chroma(决策点 5 已锁定):嵌入式、免 Docker、数据落 D 盘,
Windows 单机场景最省事;Postgres/Milvus 平迁通道已在接口层预留。
2. 用 PersistentClient 指定 D 盘目录,而非默认内存/用户目录——
硬约束 6 要求向量库数据也必须落 D:\\Agent。
3. 检索用 similarity_search_with_score(L2 距离),
同时返回分数,便于前端展示「相关度」与设定召回阈值。
【实现思路】
- KnowledgeVectorStore 封装 collection 的增删查;
- 入库时把 chunk 文本 + metadata 一起写入,检索结果可回溯到源文件;
- 支持按 source 批量删除(重建索引时按文件增量替换)。
【潜在风险与应对】
风险1:Chroma 目录被并发进程锁定。
应对:单例连接 + 启动时校验目录可写;Windows 下避免多进程同开。
风险2:metadata 值含非法类型(Chroma 只接受 str/int/float/bool)。
应对:入库前统一清洗,非标量转字符串。
风险3:检索空集合或库损坏。
应对:捕获异常返回空结果 + warning,不抛给上层(硬约束 5)。
"""
from __future__ import annotations
import logging
from pathlib import Path
from typing import Any
logger = logging.getLogger("agent.knowledge.vectorstore")
def _sanitize_metadata(meta: dict[str, Any]) -> dict[str, Any]:
"""
清洗 metadata 为 Chroma 可接受的标量类型。
【规则】str/int/float/bool/None 保留(None 丢弃),
其他类型转字符串;列表取 join。
"""
clean: dict[str, Any] = {}
for key, value in meta.items():
if value is None:
continue
if isinstance(value, (str, int, float, bool)):
clean[key] = value
elif isinstance(value, (list, tuple)):
clean[key] = ", ".join(str(v) for v in value)
else:
clean[key] = str(value)
return clean
class KnowledgeVectorStore:
"""Chroma 向量库封装(决策点 5:实现可平迁)"""
def __init__(
self,
persist_dir: Path,
collection_name: str,
embedding_provider: Any,
) -> None:
import chromadb
from chromadb.config import Settings as ChromaSettings
self._persist_dir = Path(persist_dir)
self._persist_dir.mkdir(parents=True, exist_ok=True)
self._collection_name = collection_name
self._embedding = embedding_provider
# PersistentClient 强制数据落 D 盘指定目录
self._client = chromadb.PersistentClient(
path=str(self._persist_dir),
settings=ChromaSettings(anonymized_telemetry=False),
)
self._collection = self._client.get_or_create_collection(
name=collection_name,
metadata={"hnsw:space": "l2"},
)
logger.info(
"向量库已连接:目录=%s,集合=%s,当前条数=%d",
self._persist_dir,
collection_name,
self._collection.count(),
)
@property
def count(self) -> int:
"""当前集合中的向量条数。"""
return self._collection.count()
def add_documents(
self,
texts: list[str],
metadatas: list[dict[str, Any]],
ids: list[str],
) -> int:
"""
批量入库。
【返回】实际写入条数。
【要求】texts / metadatas / ids 三者长度一致。
"""
if not texts:
return 0
if not (len(texts) == len(metadatas) == len(ids)):
raise ValueError("texts / metadatas / ids 长度必须一致")
clean_metas = [_sanitize_metadata(m) for m in metadatas]
embeddings = self._embedding.embed_documents(texts)
self._collection.add(
documents=texts,
metadatas=clean_metas,
ids=ids,
embeddings=embeddings,
)
logger.info("向量入库完成:%d 条", len(texts))
return len(texts)
def search(self, query: str, top_k: int = 5) -> list[dict[str, Any]]:
"""
语义检索。
【返回】列表,每项含 text / metadata / score(L2 距离,越小越相似)。
【降级】检索失败返回空列表并记 warning,不抛异常。
"""
try:
if self._collection.count() == 0:
logger.warning("向量库为空,检索返回空结果")
return []
query_emb = self._embedding.embed_query(query)
result = self._collection.query(
query_embeddings=[query_emb],
n_results=min(top_k, self._collection.count()),
include=["documents", "metadatas", "distances"],
)
except Exception as exc: # noqa: BLE001 - 检索失败降级为空
logger.warning("向量检索失败:%s", exc)
return []
docs = result.get("documents", [[]])[0] or []
metas = result.get("metadatas", [[]])[0] or []
dists = result.get("distances", [[]])[0] or []
hits: list[dict[str, Any]] = []
for text, meta, dist in zip(docs, metas, dists):
hits.append(
{
"text": text,
"metadata": meta or {},
"score": float(dist) if dist is not None else None,
}
)
return hits
def delete_by_source(self, source: str) -> int:
"""
按来源文件删除全部 chunk(重建索引时用)。
【返回】删除条数。
"""
try:
existing = self._collection.get(where={"source": source})
ids = existing.get("ids", []) or []
if not ids:
return 0
self._collection.delete(ids=ids)
logger.info("按来源删除 %d 条:%s", len(ids), source)
return len(ids)
except Exception as exc: # noqa: BLE001
logger.warning("按来源删除失败:%s %s", source, exc)
return 0
def clear(self) -> None:
"""清空整个集合(重建索引时用)。"""
try:
self._client.delete_collection(self._collection_name)
self._collection = self._client.get_or_create_collection(
name=self._collection_name,
metadata={"hnsw:space": "l2"},
)
logger.info("向量集合已清空并重建:%s", self._collection_name)
except Exception as exc: # noqa: BLE001
logger.warning("清空向量集合失败:%s", exc)