> ## 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-Hans/overview/models) 或 [model directory](https://www.cometapi.com/models/) 中选择支持嵌入的 model ID。下面的示例调用的是与 OpenAI 兼容的嵌入 API。

<Note>
  这些示例使用占位符 `your-embedding-model-id`。在运行请求之前，请将其替换为 [Models page](/zh-Hans/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-Hans/guides/error-codes-and-retry-strategy)和[速率限制与并发](/zh-Hans/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>
