Chroma 教程 收藏

第二步:建库

🎉摘要:本文介绍如何为 Chroma 创建 KnowledgeBase 工具类,封装集合创建、配置、批量灌数据、检索等功能,并演示用 Ollama bge-m3 模型进行向量嵌入,测试文档导入、检索与删除,方便后续搭建 RAG 检索服务。

前面为切分创建了一个几个工具函数,后续直接使用即可。同样的道理,我们为 Chroma 创建一个工具类,用于创建集合、配置集合、灌数据到集合、从集合检索等等功能。方便后续搭建一个 RAG 检索服务使用。

创建一个 KnowledgeBase 类,用来负责 Chroma 相关操作,代码如下:

from __future__ import annotations
from dataclasses import dataclass, field
from typing import Callable, Sequence
import chromadb
from chromadb.api import UpdateCollectionConfiguration, Space
from chromadb.api.collection_configuration import UpdateHNSWConfiguration, CreateCollectionConfiguration, \
    CreateHNSWConfiguration
from chromadb.api.models.Collection import Collection


# 配置类
@dataclass
class KBConfig:
    collection_name: str = "my_kb"      # 注意:集合名至少 3 个字符
    persist_path: str = "./chroma_rag"
    space: str = "cosine"
    ef_search: int = 150
    batch_size: int = 200


# 检索结果封装类
@dataclass
class RetrievedChunk:
    id: str
    text: str
    metadata: dict = field(default_factory=dict)
    distance: float = 0.0
    similarity: float | None = None


class KnowledgeBase:
    """封装的知识库工具"""

    def __init__(self, config: KBConfig, embedder: Callable[[list[str]], list[list[float]]]):
        """
        embedder: 批量文本 -> 批量向量,由外部注入,方便替换模型和加缓存
        """
        self.cfg = config
        self.embedder = embedder
        self.client = chromadb.PersistentClient(path=config.persist_path)
        self.col: Collection = self.client.get_or_create_collection(
            name=config.collection_name,
            embedding_function=None,          # 我自己算向量
            configuration=CreateCollectionConfiguration(
                hnsw=CreateHNSWConfiguration(
                    space=config.space,
                    ef_search=config.ef_search,
                )
            ),
            metadata={
                "kind": "rag",
                "space": config.space
            },
        )

    def add_document(
        self,
        doc_id: str,
        chunks: Sequence[str],
        meta: dict | None = None,
    ) -> int:
        """导入一个文档的所有片段,返回片段数"""
        if not chunks:
            return 0

        base = dict(meta or {})
        base["doc_id"] = doc_id

        ids = [self._chunk_id(doc_id, i) for i in range(len(chunks))]
        metadatas = [
            {**base, "chunk_index": i, "char_len": len(t)}
            for i, t in enumerate(chunks)
        ]

        for start in range(0, len(ids), self.cfg.batch_size):
            end = start + self.cfg.batch_size
            # 调用传递的嵌入函数,计算向量
            vecs = self.embedder(list(chunks[start:end]))
            self.col.upsert(
                ids=ids[start:end],
                embeddings=vecs,
                documents=list(chunks[start:end]),
                metadatas=metadatas[start:end],
            )
        return len(ids)

    def delete_document(self, doc_id: str) -> int:
        """删除一个文档的所有片段,返回片段数"""
        ids = self.col.get(where={"doc_id": doc_id})["ids"]
        if ids:
            self.col.delete(ids=ids)
        return len(ids)

    def search(
        self,
        query: str,
        top_k: int = 5,
        where: dict | None = None,
    ) -> list[RetrievedChunk]:
        """检索片段"""
        # 计算查询问题的向量
        vec = self.embedder([query])[0]
        res = self.col.query(
            query_embeddings=[vec],
            n_results=top_k,
            where=where,
            include=["documents", "metadatas", "distances"],
        )

        out = []
        for id_, doc, meta, dist in zip(
            res["ids"][0], res["documents"][0], res["metadatas"][0], res["distances"][0]
        ):
            out.append(RetrievedChunk(
                id=id_,
                text=doc,
                metadata=meta,
                distance=dist,
                similarity=1 - dist if self.cfg.space == "cosine" else None,
            ))
        return out

    def count(self) -> int:
        """返回总片段数"""
        return self.col.count()

    def tune_for_bulk_load(self):
        """为批量导入优化"""
        self.col.modify(configuration=UpdateCollectionConfiguration(
            hnsw=UpdateHNSWConfiguration(
                sync_threshold=100_000,
                batch_size=1000,
            )
        ))

    def tune_for_serving(self):
        """为在线服务优化"""
        self.col.modify(configuration=UpdateCollectionConfiguration(
            hnsw=UpdateHNSWConfiguration(
                sync_threshold=1000,
                batch_size=100,
                ef_search=self.cfg.ef_search,
            )
        ))

    @staticmethod
    def _chunk_id(doc_id: str, idx: int) -> str:
        """将文档 ID 和片段索引拼成一个唯一的 ID"""
        return f"{doc_id}#{idx}"


# 测试验证,仅直接运行该文件才执行
if __name__ == "__main__":
    import tempfile
    from chromadb.utils.embedding_functions import OllamaEmbeddingFunction

    # 真实环境,用 Ollama 的 bge-m3 模型(先在 ollama 里 pull 并启动服务)
    ef = OllamaEmbeddingFunction(
        url="http://localhost:11434",
        model_name="bge-m3",
        timeout=60,
    )

    # 把 Ollama 的 EF 适配成 KnowledgeBase 要求的签名:
    # 输入一批文本,返回一批向量(list[list[float]])
    def my_embedding_func(texts: list[str]) -> list[list[float]]:
        return ef(texts)

    # 持久化路径用临时目录,跑完不留文件在项目里
    cfg = KBConfig(persist_path=tempfile.mkdtemp(prefix="kb_demo_"))
    kb = KnowledgeBase(cfg, embedder=my_embedding_func)

    # 灌一个文档:直接给若干片段(这里不演示切分,切分见上一节)
    chunks = [
        "退款流程:在订单页点申请退款,3 个工作日内到账。",
        "发票开具:在订单详情页申请电子发票,支持公司抬头。",
        "物流查询:发货后可在物流详情里看到实时进度。",
        "退货政策:签收 7 天内可无理由退货,质量问题免运费。",
    ]
    n = kb.add_document("doc1", chunks, meta={"source": "faq"})
    print(f"导入 {n} 个片段,当前共 {kb.count()} 个")

    # 检索
    hits = kb.search("怎么退款", top_k=2)
    print("检索结果:")
    for h in hits:
        print(f"  sim={h.similarity} text={h.text}")

    # 删除该文档
    removed = kb.delete_document("doc1")
    print(f"删除 {removed} 个片段,当前共 {kb.count()} 个")

运行代码,验证库是否可以正常运行,输出内容如下:

导入 4 个片段,当前共 4 个
检索结果:
  sim=0.7661246061325073 text=退款流程:在订单页点申请退款,3 个工作日内到账。
  sim=0.6486612558364868 text=退货政策:签收 7 天内可无理由退货,质量问题免运费。
删除 4 个片段,当前共 0 个

注意几个设计选择:

  • embedder 是注入的函数,不是写死在里面的。这样换模型、加缓存、做 mock 测试都很容易。

  • embedding_function=None,自己在 add_document 里算向量。速度可控。

  • id 用 “doc_id#序号”格式,天然可重跑(upsert),也方便按文档删除。

  • metadata 里存 doc_id、chunk_index,检索到之后能定位回原文。

  

说说我的看法
全部评论()
没有评论
关于
本网站专注于 Java、数据库(MySQL、Oracle)、Linux、软件架构及大数据等多领域技术知识分享。涵盖丰富的原创与精选技术文章,助力技术传播与交流。无论是技术新手渴望入门,还是资深开发者寻求进阶,这里都能为您提供深度见解与实用经验,让复杂编码变得轻松易懂,携手共赴技术提升新高度。如有侵权,请来信告知:hxstrive@outlook.com
其他应用
公众号