---
title: 嵌入
url: https://platform.claude.com/docs/zh-TW/build-with-claude/embeddings
description: 文字嵌入是文字的數值表示，可用於衡量語意相似度。本指南介紹嵌入、其應用，以及如何將嵌入模型用於搜尋、推薦和異常偵測等任務。
---

## 實作嵌入之前

在選擇「embeddings」（嵌入）供應商時，您可以根據自身需求與偏好考量以下幾個因素：

* 資料集大小與領域專精度：模型訓練資料集的大小，以及它與您想要嵌入之領域的相關性。較大或更具領域專精度的資料通常能產生更好的領域內嵌入
* 推論效能：嵌入查詢速度與端到端「latency」（延遲）。對於大規模正式環境部署而言，這是特別重要的考量
* 客製化：是否提供以私有資料持續訓練的選項，或針對非常特定領域進行模型專精化。這可以提升在獨特詞彙上的效能

## 如何透過 Anthropic 取得嵌入

Anthropic 並未提供自己的嵌入模型。MongoDB 旗下的 Voyage AI 是一家提供多種模型和功能的嵌入供應商。

Voyage AI 開發嵌入模型和「reranker」（重新排序器）。其嵌入模型包括通用、多模態、情境化以及領域專用的模型。

本指南其餘部分以 Voyage AI 為主，但您應評估多家嵌入供應商，以找出最適合您特定使用情境的選擇。

## 可用模型

Voyage AI 提供以下文字嵌入模型：

**最新世代**

| 模型               | 上下文長度  | 嵌入維度                  | 說明                                                                                                                                                                                                                |
| ---------------- | ------ | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `voyage-4-large` | 32,000 | 1024（預設）、256、512、2048 | 最佳的通用與多語言檢索品質。詳情請參閱 [Voyage 4 部落格文章](https://blog.voyageai.com/2026/01/15/voyage-4/)。                                                                                                                             |
| `voyage-4`       | 32,000 | 1024（預設）、256、512、2048 | 針對通用與多語言檢索品質最佳化。在品質與效率之間取得平衡。詳情請參閱 [Voyage 4 部落格文章](https://blog.voyageai.com/2026/01/15/voyage-4/)。                                                                                                              |
| `voyage-4-lite`  | 32,000 | 1024（預設）、256、512、2048 | 針對延遲與成本最佳化。詳情請參閱 [Voyage 4 部落格文章](https://blog.voyageai.com/2026/01/15/voyage-4/)。                                                                                                                                |
| `voyage-code-4`  | 32,000 | 1024（預設）、256、512、2048 | 針對**程式碼**檢索和代理式程式設計應用進行最佳化。詳情請參閱 [voyage-code-4 部落格文章](https://blog.voyageai.com/2026/08/13/voyage-code-4/)。                                                                                                      |
| `voyage-4-nano`  | 32,000 | 2048（預設）、256、512、1024 | 開放權重模型（Apache 2.0 授權），您可從 [Hugging Face](https://huggingface.co/voyageai/voyage-4-nano) 下載並自行執行。無法透過 Atlas Embedding and Reranking API 使用。詳情請參閱 [Voyage 4 部落格文章](https://blog.voyageai.com/2026/01/15/voyage-4/)。 |

**前一代**

關於各模型的生命週期狀態和建議的替代模型，請參閱 MongoDB 文件中的 [Model deprecations, lifecycle states, and support](https://www.mongodb.com/docs/voyageai/models/lifecycle/)。

| 模型                 | 上下文長度  | 嵌入維度                  | 說明                                                                                                                                                           |
| ------------------ | ------ | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `voyage-3-large`   | 32,000 | 1024（預設）、256、512、2048 | `voyage-4-large` 的前一世代。詳情請參閱 [voyage-3-large 部落格文章](https://blog.voyageai.com/2025/01/07/voyage-3-large/)。                                                   |
| `voyage-3.5`       | 32,000 | 1024（預設）、256、512、2048 | `voyage-4` 的前一世代。詳情請參閱 [voyage-3.5 部落格文章](https://blog.voyageai.com/2025/05/20/voyage-3-5/)。                                                                 |
| `voyage-3.5-lite`  | 32,000 | 1024（預設）、256、512、2048 | `voyage-4-lite` 的前一世代。詳情請參閱 [voyage-3.5 部落格文章](https://blog.voyageai.com/2025/05/20/voyage-3-5/)。                                                            |
| `voyage-code-3`    | 32,000 | 1024（預設）、256、512、2048 | `voyage-code-4` 的前一世代。詳情請參閱 [voyage-code-3 部落格文章](https://blog.voyageai.com/2024/12/04/voyage-code-3/)。                                                      |
| `voyage-finance-2` | 32,000 | 1024                  | 針對**金融**檢索和 RAG 進行最佳化。詳情請參閱 [voyage-finance-2 部落格文章](https://blog.voyageai.com/2024/06/03/domain-specific-embeddings-finance-edition-voyage-finance-2/)。     |
| `voyage-law-2`     | 16,000 | 1024                  | 針對**法律**檢索和 RAG 進行最佳化。詳情請參閱 [voyage-law-2 部落格文章](https://blog.voyageai.com/2024/04/15/domain-specific-embeddings-and-retrieval-legal-edition-voyage-law-2/)。 |

此外，Voyage AI 還提供以下多模態嵌入模型。請使用 `multimodal_embed()` 而非 `embed()` 來呼叫這些模型：

| 模型                      | 上下文長度  | 嵌入維度                  | 說明                                                                                                                                                                  |
| ----------------------- | ------ | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `voyage-multimodal-3.5` | 32,000 | 1024（預設）、256、512、2048 | 功能豐富的多模態嵌入模型，可將交錯的文字、圖片和影片向量化。包含影片支援，是首個生產等級的影片嵌入模型。詳情請參閱 [voyage-multimodal-3.5 部落格文章](https://blog.voyageai.com/2026/01/15/voyage-multimodal-3-5/)。               |
| `voyage-multimodal-3`   | 32,000 | 1024                  | `voyage-multimodal-3.5` 的前一世代。可將交錯的文字和內容豐富的圖片向量化，例如 PDF 截圖、投影片、表格、圖表等。詳情請參閱 [voyage-multimodal-3 部落格文章](https://blog.voyageai.com/2024/11/12/voyage-multimodal-3/)。 |

以下情境化區塊嵌入模型可產生區塊層級的向量，無需手動補充中繼資料即可捕捉完整的文件上下文。請使用 `contextualized_embed()` 而非 `embed()` 來呼叫這些模型：

| 模型                 | 上下文長度   | 嵌入維度                  | 說明                                                                                                                |
| ------------------ | ------- | --------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `voyage-context-4` | 120,000 | 1024（預設）、256、512、2048 | 針對通用和多語言檢索品質進行最佳化的情境化區塊嵌入。詳情請參閱 [voyage-context-4 部落格文章](https://blog.voyageai.com/2026/06/29/voyage-context-4/)。 |
| `voyage-context-3` | 120,000 | 1024（預設）、256、512、2048 | `voyage-context-4` 的前一世代。詳情請參閱 [voyage-context-3 部落格文章](https://blog.voyageai.com/2025/07/23/voyage-context-3/)。  |

120,000 個 token 的上限適用於您將 `enable_auto_chunking` 設為 `true` 時。否則，所有輸入的 token 總數不得超過 32,000。

Voyage AI 也提供「rerankers」（重新排序器），它接收一個查詢與一份文件清單，並依照與查詢的相關性排序後回傳。請使用 `rerank()` 呼叫這些模型：

| 模型                | 上下文長度  | 說明                                                                                                |
| ----------------- | ------ | ------------------------------------------------------------------------------------------------- |
| `rerank-3`        | 32,000 | 最高準確度。建議用於大多數應用。詳情請參閱 [rerank-3 部落格文章](https://blog.voyageai.com/2026/09/30/rerank-3/)。           |
| `rerank-3-lite`   | 32,000 | 針對延遲和成本進行最佳化。詳情請參閱 [rerank-3 部落格文章](https://blog.voyageai.com/2026/09/30/rerank-3/)。              |
| `rerank-2.5`      | 32,000 | `rerank-3` 的前一世代。詳情請參閱 [rerank-2.5 部落格文章](https://blog.voyageai.com/2025/08/11/rerank-2-5/)。      |
| `rerank-2.5-lite` | 32,000 | `rerank-3-lite` 的前一世代。詳情請參閱 [rerank-2.5 部落格文章](https://blog.voyageai.com/2025/08/11/rerank-2-5/)。 |

需要協助決定使用哪個模型嗎？請參閱 MongoDB 文件中的 [Voyage AI embedding and reranking models overview](https://www.mongodb.com/docs/voyageai/models/)。

## 開始使用 Voyage AI

若要存取 Voyage AI 模型，請在 MongoDB Atlas 中建立模型 API 金鑰：

1. 註冊 MongoDB Atlas 帳戶，或登入。
2. 在您的 Atlas 專案中，於導覽列選擇 **AI Model APIs**，點擊 **Create model API key**，為金鑰命名，然後點擊 **Create**。
3. 為方便起見，將 API 金鑰設定為環境變數：

```bash
export VOYAGE_API_KEY="<your model API key>"
```

更多詳細資訊，請參閱 MongoDB 文件中的 [Voyage AI quick start](https://www.mongodb.com/docs/voyageai/quickstart/)。

您可以使用官方的 [`voyageai` Python 套件](https://github.com/voyage-ai/voyageai-python)或 HTTP 請求來取得嵌入，如以下各節所述。Voyage AI 也有官方的 TypeScript 用戶端。若要搭配 Atlas 的模型 API 金鑰使用，請將其 `environment` 選項設為 `https://ai.mongodb.com/v1`，如 MongoDB 文件中的 [TypeScript client](https://www.mongodb.com/docs/voyageai/api-and-clients/#typescript-client) 所述。

### Voyage AI Python 函式庫

使用以下指令安裝 `voyageai` 套件。若要使用 Atlas 的模型 API 金鑰，您需要 0.3.7 或更新版本。

```bash
pip install -U voyageai
```

接著，您可以建立一個用戶端物件，並開始用它來嵌入您的文字：

```python
import voyageai

vo = voyageai.Client()
# 這會自動使用環境變數 VOYAGE_API_KEY。
# 或者，您也可以使用 vo = voyageai.Client(api_key="<your model API 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` 是一個包含兩個嵌入向量的清單，每個向量包含 1024 個浮點數。執行上述程式碼後，這兩個嵌入會印在螢幕上：

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

建立嵌入時，您可以為 `embed()` 函式指定其他幾個引數。

關於 Python 套件的更多資訊，請參閱 MongoDB 文件中的 [Accessing Voyage AI models](https://www.mongodb.com/docs/voyageai/api-and-clients/)。

### Voyage AI HTTP API

您也可以透過向 Atlas Embedding and Reranking API 傳送 HTTP 請求來取得嵌入。例如，您可以在終端機中透過 `curl` 指令傳送 HTTP 請求：

```bash cURL
curl https://ai.mongodb.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",
    "input_type": "document"
  }'
```

您會收到的回應是一個包含嵌入與 token 用量的 JSON 物件：

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

Atlas 的模型 API 金鑰可搭配 `ai.mongodb.com` 使用，但限定於特定地理區域的金鑰除外，這類金鑰會使用該地理區域的端點。如果您持有的是 Voyage AI 平台的 API 金鑰，請參閱 MongoDB 文件中的 [Migrate your applications to use the Atlas Embedding and Reranking API](https://www.mongodb.com/docs/voyageai/tutorials/migrate-to-atlas/)。

完整的請求和回應參考資料，請參閱 Atlas Embedding and Reranking API 文件中的 [Create text embeddings](https://www.mongodb.com/docs/api/doc/atlas-embedding-and-reranking-api/operation/operation-createembedding)。

### AWS Marketplace

Voyage AI 模型也可透過 [MongoDB 的賣家頁面](https://aws.amazon.com/marketplace/seller-profile?id=c9032c7b-70dd-459f-834f-c1e23cf3d092)在 AWS Marketplace 上取得。相關說明請參閱 MongoDB 文件中的 [Deploy Voyage AI models using AWS Marketplace](https://www.mongodb.com/docs/voyageai/management/aws-marketplace/)。

## 快速入門範例

以下簡短範例展示如何使用嵌入。

假設您有一個包含六份文件的小型語料庫可供檢索

```python
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 AI 將每份文件轉換為嵌入向量。

```python
import voyageai

vo = voyageai.Client()

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

嵌入讓您能在向量空間中進行語意搜尋／檢索。給定一個範例查詢，

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

接著，將其轉換為嵌入，並進行最近鄰搜尋，根據嵌入空間中的距離找出最相關的文件。

```python
import numpy as np

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

# 計算相似度
# Voyage AI 的嵌入向量已正規化為長度 1，因此內積（dot-product）
# 與餘弦相似度（cosine similarity）相同。
similarities = np.dot(doc_embds, query_embd)

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

請注意，`input_type="document"` 和 `input_type="query"` 分別用於嵌入文件和查詢。關於 `input_type` 的更多資訊，請參閱常見問題中的[何時以及如何使用 input\_type 參數？](https://platform.claude.com/docs/zh-TW/build-with-claude/embeddings#faq)。

輸出為第五份文件，它確實是與查詢最相關的文件：

```text wrap
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.
```

如果您正在尋找一套關於如何使用嵌入進行 RAG（包含向量資料庫）的詳細範例，請查看 [RAG 範例](https://platform.claude.com/cookbook/third-party-pinecone-rag-using-pinecone)。

## 常見問題

<AccordionGroup>
  <Accordion title="為什麼 Voyage AI 嵌入具有卓越的品質？">
    嵌入模型與生成式模型類似，依賴強大的神經網路來擷取和壓縮語意上下文。Voyage AI 經驗豐富的 AI 研究團隊最佳化了嵌入過程的每個環節，包括：

    * 模型架構
    * 資料收集
    * 損失函數
    * 最佳化器選擇

    在 [Voyage AI 部落格](https://blog.voyageai.com/)上進一步了解 Voyage AI 的技術方法。
  </Accordion>

  <Accordion title="有哪些嵌入模型可用，我應該使用哪一個？">
    對於通用嵌入，建議的模型為：

    * `voyage-4-large`：最佳品質
    * `voyage-4-lite`：最低延遲與成本
    * `voyage-4`：均衡的效能

    對於檢索，請使用 `input_type` 參數指定文字是查詢還是文件類型。

    領域專用模型：

    * 法律任務：`voyage-law-2`
    * 程式碼檢索和代理式程式設計：`voyage-code-4`
    * 金融相關任務：`voyage-finance-2`

    對於區塊層級和文件層級的檢索：`voyage-context-4`

    對於文字、圖片和影片：`voyage-multimodal-3.5`
  </Accordion>

  <Accordion title="我應該使用哪種相似度函數？">
    您可以將 Voyage AI 嵌入搭配點積相似度、餘弦相似度或歐幾里得距離使用。關於嵌入相似度的說明，請參閱這份[向量相似度指南](https://www.pinecone.io/learn/vector-similarity/)。

    Voyage AI 嵌入已正規化為長度 1，這表示：

    * 餘弦相似度等同於點積相似度，而後者的計算速度更快。
    * 餘弦相似度與歐幾里得距離會產生相同的排序結果。
  </Accordion>

  <Accordion title="字元、單字和 token 之間有什麼關係？">
    請參閱 MongoDB 文件中的 [Tokenization](https://www.mongodb.com/docs/voyageai/tutorials/tokenization/)。
  </Accordion>

  <Accordion title="何時以及如何使用 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.」
  </Accordion>

  <Accordion title="有哪些量化選項可用？">
    嵌入中的「quantization」（量化）會將高精度數值（例如 32 位元單精度浮點數）轉換為較低精度的格式，例如 8 位元整數或 1 位元二進位值，分別將儲存空間、記憶體和成本降低 4 倍和 32 倍。支援的 Voyage AI 模型可透過 `output_dtype` 參數指定輸出資料類型來啟用量化：

    * `float`：每個回傳的嵌入都是 32 位元（4 位元組）單精度浮點數的清單。這是預設值，提供最高的精度／檢索準確度。
    * `int8` 和 `uint8`：每個回傳的嵌入都是 8 位元（1 位元組）整數的清單，範圍分別為 -128 到 127 和 0 到 255。
    * `binary` 和 `ubinary`：每個回傳的嵌入都是 8 位元整數的清單，代表經位元打包、量化的單一位元嵌入值：`binary` 使用 `int8`，`ubinary` 使用 `uint8`。回傳的整數清單長度為嵌入實際維度的 1/8。binary 類型使用偏移二進位法，如以下範例所示。

    > **二進位量化範例**
    >
    > 考慮以下八個嵌入值：-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）。

    關於支援各資料類型的模型，請參閱 Atlas Embedding and Reranking API 文件中的 [Create text embeddings](https://www.mongodb.com/docs/api/doc/atlas-embedding-and-reranking-api/operation/operation-createembedding)。
  </Accordion>

  <Accordion title="如何截斷 Matryoshka 嵌入？">
    Matryoshka 學習會在單一向量中建立由粗到細的表示。支援多種輸出維度的 Voyage AI 模型（例如 `voyage-code-4`）會產生此類 Matryoshka 嵌入。若要從 API 取得較短的向量，請傳入 `output_dimension`（例如 `output_dimension=256`）。若要縮短您已儲存的向量，請保留前段的維度子集來截斷它們，然後再次進行正規化。例如，以下 Python 程式碼示範如何將 1024 維向量截斷為 256 維：

    ```python
    import voyageai
    import numpy as np


    def embd_normalize(v: np.ndarray) -> np.ndarray:
        """
        Normalize the rows of a 2D numpy array to unit vectors by dividing each row by its Euclidean
        norm. Raises a ValueError if any row has a norm of zero to prevent division by zero.
        """
        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-4 向量，預設為 1024 維的浮點數
    embd = vo.embed(["Sample text 1", "Sample text 2"], model="voyage-code-4").embeddings

    # 設定較短的維度
    short_dim = 256

    # 將向量調整為較短維度並進行正規化
    resized_embd = embd_normalize(np.array(embd)[:, :short_dim]).tolist()
    ```
  </Accordion>
</AccordionGroup>

## 定價

如需最新的定價詳情，請參閱 MongoDB 文件中的 [Model pricing](https://www.mongodb.com/docs/voyageai/management/billing/#model-pricing)。
