Embeddings

文本 embedding 是文本的数值表示,能够衡量语义相似度。本指南介绍 embedding、其应用以及如何使用 embedding 模型进行搜索、推荐和异常检测等任务。


实施 embedding 之前

选择 embedding 提供商时,您可以根据需求和偏好考虑以下几个因素:

  • 数据集大小和领域特异性:模型训练数据集的大小及其与您要嵌入的领域的相关性。更大或更具领域特异性的数据通常能产生更好的领域内 embedding
  • 推理性能:embedding 查找速度和端到端延迟。这是大规模生产部署中特别重要的考虑因素
  • 自定义选项:在私有数据上继续训练的选项,或针对特定领域进行模型专业化。这可以改善特定词汇表上的性能

如何通过 Anthropic 获取 embedding

Anthropic 不提供自己的 embedding 模型。一个提供广泛选项和功能的 embedding 提供商是 Voyage AI,它涵盖了上述所有考虑因素。

Voyage AI 制作最先进的 embedding 模型,并为金融和医疗等特定行业领域提供定制模型,或为个别客户提供定制的微调模型。

本指南的其余部分针对 Voyage AI,但您应该评估各种 embedding 供应商,以找到最适合您特定用例的方案。

可用模型

Voyage 推荐使用以下文本 embedding 模型:

Voyage 4(最新一代)

模型上下文长度Embedding 维度描述
voyage-4-large32,0001024(默认)、256、512、2048最佳的通用和多语言检索质量。详见博客文章
voyage-432,0001024(默认)、256、512、2048针对通用和多语言检索质量优化。平衡质量和效率。详见博客文章
voyage-4-lite32,0001024(默认)、256、512、2048针对延迟和成本优化。详见博客文章
voyage-4-nano32,0001024(默认)、256、512、2048开源权重模型(Apache 2.0 许可证),可在 Hugging Face 上获取。详见博客文章

上一代

模型上下文长度Embedding 维度描述
voyage-3-large32,0001024(默认)、256、512、2048最佳的通用和多语言检索质量。详见博客文章
voyage-3.532,0001024(默认)、256、512、2048针对通用和多语言检索质量优化。详见博客文章
voyage-3.5-lite32,0001024(默认)、256、512、2048针对延迟和成本优化。详见博客文章
voyage-code-332,0001024(默认)、256、512、2048针对代码检索优化。详见博客文章
voyage-finance-232,0001024针对金融检索和 RAG 优化。详见博客文章
voyage-law-216,0001024针对法律长上下文检索和 RAG 优化。同时提升了所有领域的性能。详见博客文章

此外,推荐以下多模态 embedding 模型:

模型上下文长度Embedding 维度描述
voyage-multimodal-3.532,0001024(默认)、256、512、2048丰富的多模态 embedding 模型,可以将交错的文本、图片和视频向量化。包括视频支持,是首个生产级视频 embedding 模型。详见博客文章
voyage-multimodal-332,0001024丰富的多模态 embedding 模型,可以将交错的文本和内容丰富的图片(如 PDF 截图、幻灯片、表格、图表等)向量化。详见博客文章

需要帮助选择文本 embedding 模型?请查看常见问题

Voyage AI 入门

要访问 Voyage embedding:

  1. 在 Voyage AI 网站上注册
  2. 获取 API 密钥
  3. 将 API 密钥设置为环境变量以方便使用:
export VOYAGE_API_KEY="<your secret key>"

您可以通过使用官方的 voyageai Python 包或 HTTP 请求来获取 embedding,如下所述。

Voyage Python 库

可以使用以下命令安装 voyageai 包:

pip install -U voyageai

然后,您可以创建客户端对象并开始使用它来嵌入您的文本:

import voyageai

vo = voyageai.Client()
# 这将自动使用环境变量 VOYAGE_API_KEY。
# 或者,您可以使用 vo = voyageai.Client(api_key="<your secret key>")

texts = ["Sample text 1", "Sample text 2"]

result = vo.embed(texts, model="voyage-4", input_type="document")
print(result.embeddings[0])
print(result.embeddings[1])

result.embeddings 将是一个包含两个 embedding 向量的列表,每个向量包含 1024 个浮点数。运行上述代码后,两个 embedding 将显示在屏幕上:

[-0.013131560757756233, 0.019828535616397858, ...]   # "Sample text 1" 的 embedding
[-0.0069352793507277966, 0.020878976210951805, ...]  # "Sample text 2" 的 embedding

创建 embedding 时,您可以向 embed() 函数指定其他参数。

有关 Voyage Python 包的更多信息,请参阅 Voyage 文档

Voyage HTTP API

您也可以通过请求 Voyage HTTP API 来获取 embedding。例如,您可以在终端中通过 curl 命令发送 HTTP 请求:

curl https://api.voyageai.com/v1/embeddings \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $VOYAGE_API_KEY" \
  -d '{
    "input": ["Sample text 1", "Sample text 2"],
    "model": "voyage-4"
  }'

您将获得的响应是一个包含 embedding 和 token 使用量的 JSON 对象:

{
  "object": "list",
  "data": [
    {
      "embedding": [-0.013131560757756233, 0.019828535616397858 /* ... */],
      "index": 0
    },
    {
      "embedding": [-0.0069352793507277966, 0.020878976210951805 /* ... */],
      "index": 1
    }
  ],
  "model": "voyage-4",
  "usage": {
    "total_tokens": 10
  }
}

有关 Voyage HTTP API 的更多信息,请参阅 Voyage 文档

AWS Marketplace

Voyage embedding 可在 AWS Marketplace 上获取。有关在 AWS 上访问 Voyage 的说明,请参阅 Voyage AWS Marketplace 文档

快速入门示例

以下简要示例展示了如何使用 embedding。

假设您有一个包含六个文档的小型语料库需要检索

documents = [
    "The Mediterranean diet emphasizes fish, olive oil, and vegetables, believed to reduce chronic diseases.",
    "Photosynthesis in plants converts light energy into glucose and produces essential oxygen.",
    "20th-century innovations, from radios to smartphones, centered on electronic advancements.",
    "Rivers provide water, irrigation, and habitat for aquatic species, vital for ecosystems.",
    "Apple's conference call to discuss fourth fiscal quarter results and business updates is scheduled for Thursday, November 2, 2023 at 2:00 p.m. PT / 5:00 p.m. ET.",
    "Shakespeare's works, like 'Hamlet' and 'A Midsummer Night's Dream,' endure in literature.",
]

首先,使用 Voyage 将每个文档转换为 embedding 向量

import voyageai

vo = voyageai.Client()

# 嵌入文档
doc_embds = vo.embed(documents, model="voyage-4", input_type="document").embeddings

Embedding 允许您在向量空间中进行语义搜索/检索。给定一个示例查询,

query = "When is Apple's conference call scheduled?"

接下来,将其转换为 embedding 并进行最近邻搜索,以根据 embedding 空间中的距离找到最相关的文档。

import numpy as np

# 嵌入查询
query_embd = vo.embed([query], model="voyage-4", input_type="query").embeddings[0]

# 计算相似度
# Voyage embedding 已归一化为长度 1,因此点积
# 和余弦相似度是相同的。
similarities = np.dot(doc_embds, query_embd)

retrieved_id = np.argmax(similarities)
print(documents[retrieved_id])

请注意,input_type="document"input_type="query" 分别用于嵌入文档和查询。更多规范可在 Voyage Python 库中找到。

输出将是第 5 个文档,它确实与查询最相关:

Apple's conference call to discuss fourth fiscal quarter results and business updates is scheduled for Thursday, November 2, 2023 at 2:00 p.m. PT / 5:00 p.m. ET.

如果您正在寻找有关如何使用 embedding 进行 RAG 的详细教程集(包括向量数据库),请查看 RAG 教程

常见问题

为什么 Voyage embedding 具有卓越的质量?

Embedding 模型依赖强大的神经网络来捕获和压缩语义上下文,类似于生成模型。Voyage 经验丰富的 AI 研究团队优化了 embedding 过程的每个组件,包括:

  • 模型架构
  • 数据收集
  • 损失函数
  • 优化器选择

在他们的博客上了解更多关于 Voyage 技术方法的信息。

有哪些 embedding 模型可用,应该使用哪个?

对于通用 embedding,推荐的模型是:

  • voyage-4-large:最佳质量
  • voyage-4-lite:最低延迟和成本
  • voyage-4:平衡性能

对于检索,使用 input_type 参数指定文本是查询类型还是文档类型。

领域特定模型:

  • 法律任务:voyage-law-2
  • 代码和编程文档:voyage-code-3
  • 金融相关任务:voyage-finance-2

应该使用哪种相似度函数?

您可以将 Voyage embedding 与点积相似度、余弦相似度或欧氏距离一起使用。关于 embedding 相似度的解释可以在向量相似度指南中找到。

Voyage AI embedding 已归一化为长度 1,这意味着:

  • 余弦相似度等同于点积相似度,而后者计算更快。
  • 余弦相似度和欧氏距离将产生相同的排名。

字符、单词和 token 之间有什么关系?

请参阅此页面

何时以及如何使用 input_type 参数?

对于所有检索任务和用例(例如 RAG),使用 input_type 参数指定输入文本是查询还是文档。不要省略 input_type 或设置 input_type=None。指定输入文本是查询还是文档可以创建更好的密集向量表示,从而提高检索质量。

使用 input_type 参数时,特殊提示会被添加到输入文本前面进行嵌入。具体来说:

📘 input_type 关联的提示

  • 对于查询,提示是"Represent the query for retrieving supporting documents: "。
  • 对于文档,提示是"Represent the document for retrieval: "。
  • 示例
    • input_type="query" 时,查询"When is Apple's conference call scheduled?"将变为"Represent the query for retrieving supporting documents: When is Apple's conference call scheduled?"
    • input_type="document" 时,文档"Apple's conference call to discuss fourth fiscal quarter results and business updates is scheduled for Thursday, November 2, 2023 at 2:00 p.m. PT / 5:00 p.m. ET."将变为"Represent the document for retrieval: Apple's conference call to discuss fourth fiscal quarter results and business updates is scheduled for Thursday, November 2, 2023 at 2:00 p.m. PT / 5:00 p.m. ET."

voyage-large-2-instruct,顾名思义,被训练为响应添加到输入文本前面的额外指令。对于分类、聚类或其他 MTEB 子任务,请使用 voyage-large-2-instruct 指令

有哪些量化选项可用?

Embedding 中的量化将高精度值(如 32 位单精度浮点数)转换为低精度格式(如 8 位整数或 1 位二进制值),分别将存储、内存和成本减少 4 倍和 32 倍。支持的 Voyage 模型通过使用 output_dtype 参数指定输出数据类型来启用量化:

  • float:每个返回的 embedding 是 32 位(4 字节)单精度浮点数列表。这是默认值,提供最高精度/检索准确性。
  • int8uint8:每个返回的 embedding 是 8 位(1 字节)整数列表,范围分别为 -128 到 127 和 0 到 255。
  • binaryubinary:每个返回的 embedding 是 8 位整数列表,表示位打包的量化单比特 embedding 值:binary 使用 int8ubinary 使用 uint8。返回的整数列表长度是实际 embedding 维度的 1/8。二进制类型使用偏移二进制方法,您可以在下面的常见问题中了解更多。

二进制量化示例

考虑以下八个 embedding 值:-0.03955078、0.006214142、-0.07446289、-0.039001465、0.0046463013、0.00030612946、-0.08496094 和 0.03994751。使用二进制量化,小于或等于零的值将被量化为二进制零,正值被量化为二进制一,得到以下二进制序列:0、1、0、0、1、1、0、1。这八位被打包成单个 8 位整数 01001101(最左边的位为最高有效位)。

  • ubinary:二进制序列直接转换并表示为无符号整数(uint8)77。
  • binary:二进制序列表示为有符号整数(int8)-51,使用偏移二进制方法计算(77 - 128 = -51)。

如何截断 Matryoshka embedding?

Matryoshka 学习在单个向量内创建从粗到细的表示。支持多种输出维度的 Voyage 模型(如 voyage-code-3)会生成此类 Matryoshka embedding。您可以通过保留维度的前导子集来截断这些向量。以下 Python 代码演示了如何将 1024 维向量截断为 256 维:

import voyageai
import numpy as np


def embd_normalize(v: np.ndarray) -> np.ndarray:
    """
    将 2D numpy 数组的行归一化为单位向量,方法是将每行除以其欧氏
    范数。如果任何行的范数为零,则引发 ValueError 以防止除以零。
    """
    row_norms = np.linalg.norm(v, axis=1, keepdims=True)
    if np.any(row_norms == 0):
        raise ValueError("Cannot normalize rows with a norm of zero.")
    return v / row_norms


vo = voyageai.Client()

# 生成 voyage-code-3 向量,默认为 1024 维浮点数
embd = vo.embed(["Sample text 1", "Sample text 2"], model="voyage-code-3").embeddings

# 设置较短维度
short_dim = 256

# 调整大小并将向量归一化为较短维度
resized_embd = embd_normalize(np.array(embd)[:, :short_dim]).tolist()

定价

请访问 Voyage 的定价页面获取最新的定价详情。