> ## Documentation Index
> Fetch the complete documentation index at: https://apidoc.cometapi.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 嵌入 API

> 使用 CometAPI 的嵌入路由建立向量，用於語意搜尋、分群、推薦和擷取工作流程。

當你的應用程式需要用於語意搜尋、分群、推薦或擷取的向量時，請使用 CometAPI 嵌入。將文字傳送到 `/v1/embeddings`，儲存傳回的向量，然後使用你的向量資料庫進行搜尋。

## 建立嵌入

請從 [Models page](/zh-Hant/overview/models) 或 [model directory](https://www.cometapi.com/models/) 使用支援嵌入的 model ID。以下範例會呼叫與 OpenAI 相容的 Embeddings API。

<Note>
  這些範例使用預留位置 `your-embedding-model-id`。在執行請求之前，請將它替換為 [Models page](/zh-Hant/overview/models) 或 [model directory](https://www.cometapi.com/models/) 中可用的嵌入 model ID。
</Note>

<Tip>
  開啟 [Create embeddings](/api/text/embeddings) 以使用 playground 和端點結構描述。
</Tip>

<CodeGroup>
  ```python Python theme={null}
  import os
  import requests

  response = requests.post(
      "https://api.cometapi.com/v1/embeddings",
      headers={
          "Authorization": "Bearer " + os.environ["COMETAPI_KEY"],
          "Content-Type": "application/json",
      },
      json={
          "model": "your-embedding-model-id",
          "input": "CometAPI lets developers use many model providers.",
      },
      timeout=30,
  )

  response.raise_for_status()
  result = response.json()
  print(len(result["data"][0]["embedding"]))
  ```

  ```javascript Node.js theme={null}
  const response = await fetch("https://api.cometapi.com/v1/embeddings", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.COMETAPI_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: "your-embedding-model-id",
      input: "CometAPI lets developers use many model providers.",
    }),
  });

  if (!response.ok) {
    throw new Error(await response.text());
  }

  const result = await response.json();
  console.log(result.data[0].embedding.length);
  ```

  ```bash cURL theme={null}
  curl https://api.cometapi.com/v1/embeddings \
    -H "Authorization: Bearer $COMETAPI_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "your-embedding-model-id",
      "input": "CometAPI lets developers use many model providers."
    }'
  ```
</CodeGroup>

## 回應範例

成功的回應可能如下所示。回應會為每個輸入項目包含一個向量；下方的向量為了便於閱讀已縮短：

```json theme={null}
{
  "object": "list",
  "data": [
    {
      "object": "embedding",
      "index": 0,
      "embedding": [
        -0.0021,
        -0.0491,
        0.0209
      ]
    }
  ],
  "model": "your-embedding-model-id",
  "usage": {
    "prompt_tokens": 10,
    "total_tokens": 10
  }
}
```

## 批次輸入

當你想在一次請求中取得多個向量時，請傳送字串陣列：

```bash cURL theme={null}
curl https://api.cometapi.com/v1/embeddings \
  -H "Authorization: Bearer $COMETAPI_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "your-embedding-model-id",
    "input": [
      "Create an API key",
      "Change the base URL",
      "Retry after a rate limit"
    ]
  }'
```

## 範例模型記錄

<Info>
  此範例模型目錄回應展示了 `/api/models` 的封裝格式，以及一筆 OpenAI 相容嵌入模型記錄的結構。部分嵌入記錄會使用空的 `model_type`；請依據 ID 與端點支援來選擇嵌入模型，而不要只依賴該欄位。
</Info>

```bash cURL theme={null}
curl https://api.cometapi.com/api/models
```

```json theme={null}
{
  "success": true,
  "page": 1,
  "page_size": 20,
  "total": 302,
  "data": [
    {
      "created": 1757904564,
      "id": "your-embedding-model-id",
      "code": "your-embedding-model-id",
      "provider": "ExampleProvider",
      "provider_code": "example",
      "name": "Example embedding model",
      "model_type": "embedding",
      "features": [
        "text-embedding"
      ],
      "endpoints": [
        "openai"
      ],
      "pricing": {
        "currency": "USD / M Tokens",
        "input": 0.1,
        "output": null,
        "per_request": null,
        "per_second": null
      }
    }
  ]
}
```

## 常見錯誤

<AccordionGroup>
  <Accordion title="Input too long">
    在進行嵌入前，先將長文件切分成多個區塊。
  </Accordion>

  <Accordion title="Wrong model type">
    從模型目錄中選擇支援嵌入的模型。
  </Accordion>

  <Accordion title="Vector dimensions mismatch">
    對同一個向量索引，請保持使用相同的模型與維度。
  </Accordion>

  <Accordion title="Missing API key">
    傳送 `Authorization: Bearer $COMETAPI_KEY`。
  </Accordion>
</AccordionGroup>

## 錯誤碼與重試策略

<AccordionGroup>
  <Accordion title="400">
    在修正輸入、model ID 或 dimensions 設定之前，請勿重試。
  </Accordion>

  <Accordion title="401">
    在 API key 已提供且有效之前，請勿重試。
  </Accordion>

  <Accordion title="404">
    重試前請檢查 base URL、路徑與 model ID。
  </Accordion>

  <Accordion title="429">
    以指數退避方式重試，並降低批次大小或並行數。
  </Accordion>

  <Accordion title="500 or 503">
    對於暫時性的供應商或服務錯誤，請以退避方式重試。
  </Accordion>
</AccordionGroup>

<Tip>
  實作模式請參閱[錯誤碼與重試策略](/zh-Hant/guides/error-codes-and-retry-strategy)與[速率限制與並行處理](/zh-Hant/guides/rate-limits-and-concurrency)。
</Tip>

## 定價與模型目錄

<CardGroup cols={3}>
  <Card title="Models page" icon="list" href="/overview/models">
    了解 CometAPI 如何在文件中公開 model ID。
  </Card>

  <Card title="Model directory" icon="puzzle-piece" href="https://www.cometapi.com/models/">
    瀏覽可用模型及其能力。
  </Card>

  <Card title="Pricing" icon="tag" href="https://www.cometapi.com/pricing/">
    呼叫模型前先查看定價。
  </Card>
</CardGroup>
