跳转到主要内容
嵌入(Embeddings)是表示任何类型数据的方式,使其能够完美适配各种 AI 驱动的工具和算法。它们可以表示文本、图像,以及即将支持的音频和视频。Chroma 集合会对嵌入进行索引,从而实现对所代表数据的高效相似度搜索。创建嵌入有很多选择,既可以使用安装的库在本地创建,也可以通过调用 API 来创建。 Chroma 为流行的嵌入提供商提供了轻量级包装器,方便您在应用中使用它们。您可以在创建 Chroma 集合时设置一个嵌入函数,在添加和查询数据时会自动调用,或者您也可以直接手动调用它们。 对于 TypeScript 用户,Chroma 为多家嵌入模型提供商提供了包。Chromadb Python 包则内置了所有的嵌入函数。 我们欢迎为社区添加新嵌入函数的拉取请求(Pull Requests)。

默认:all-MiniLM-L6-v2

Chroma 的默认嵌入函数使用 Sentence Transformersall-MiniLM-L6-v2 模型来创建嵌入。该模型可以创建句子和文档嵌入,适用于广泛的任务。此嵌入函数在您的本地机器上运行,可能需要下载模型文件(这会自动完成)。如果您在创建集合时未指定嵌入函数,Chroma 将默认其为 DefaultEmbeddingFunction
collection = client.create_collection(name="my_collection")

使用嵌入函数

嵌入函数可以链接到集合,并在您调用 addupdateupsertquery 时自动使用。
# Set your OPENAI_API_KEY environment variable
from chromadb.utils.embedding_functions import OpenAIEmbeddingFunction

collection = client.create_collection(
    name="my_collection",
    embedding_function=OpenAIEmbeddingFunction(
        model_name="text-embedding-3-small"
    )
)

# Chroma will use OpenAIEmbeddingFunction to embed your documents
collection.add(
    ids=["id1", "id2"],
    documents=["doc1", "doc2"]
)
您也可以直接使用嵌入函数,这在调试时非常方便。
from chromadb.utils.embedding_functions import DefaultEmbeddingFunction

default_ef = DefaultEmbeddingFunction()
embeddings = default_ef(["foo"])
print(embeddings) # [[0.05035809800028801, 0.0626462921500206, -0.061827320605516434...]]

collection.query(query_embeddings=embeddings)

自定义嵌入函数

您可以创建自己的嵌入函数供 Chroma 使用;只需实现 EmbeddingFunction 接口即可。
from typing import Dict, Any
from chromadb import Documents, EmbeddingFunction, Embeddings
from chromadb.utils.embedding_functions import register_embedding_function

@register_embedding_function
class MyEmbeddingFunction(EmbeddingFunction):

    def __init__(self, model):
        self.model = model

    def __call__(self, input: Documents) -> Embeddings:
        # embed the documents somehow
        return embeddings

    @staticmethod
    def name() -> str:
        return "my-ef"

    def get_config(self) -> Dict[str, Any]:
        return dict(model=self.model)

    @staticmethod
    def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction":
        return MyEmbeddingFunction(config['model'])
我们欢迎贡献!如果您创建了一个您认为对他人有用的嵌入函数,请考虑提交拉取请求