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

# 嵌入模型（Embedding）

> 了解算秩 Embedding 模型如何将文本转换为语义向量，并用于语义搜索、RAG 检索、聚类、重排序和批量嵌入。

嵌入（Embedding）模型会将文本转换为能够表达语义信息的稠密向量，使语义相近的文本在向量空间中更接近。它们常用于语义搜索、检索、重排序、聚类，以及 RAG（检索增强生成，Retrieval-Augmented Generation）等场景，并通过兼容 OpenAI 的 Embeddings API 提供服务。

代表模型包括：

* `Qwen/Qwen3-Embedding-4B`
* `BAAI/bge-m3`

完整模型列表和价格，请以 [模型广场](https://console.siflow.cn/model-inference/models) 为准。

## 核心能力

* **语义搜索**：按语义而不是精确关键词来匹配查询和文档。
* **面向 RAG 的检索**：先对知识库内容做嵌入并存储向量，再检索最相关的片段，为 LLM 回答提供上下文。
* **聚类与去重**：将相似项分组，或检测近似重复的内容。
* **推荐与重排序**：根据与查询或用户画像的相似度对候选项打分。

## 使用方式

Embeddings API 支持单个字符串或字符串列表输入，并会为每个输入返回一个向量。

常见流程：

1. 为文档生成向量并存储。
2. 在用户发起查询时，对查询文本做嵌入。
3. 将查询向量与已有向量进行比较，例如使用余弦相似度。

## 关键参数

* `model`：Embedding 模型名称。
* `input`：字符串或字符串列表。
* `encoding_format`：部分模型接受，例如 `float` 的 `encoding_format`。

## 注意事项

* 对文档和查询使用同一个 Embedding 模型进行嵌入，使它们的向量位于同一空间，使向量之间可比较。
* 如果某个输入超过模型的最大长度，请先将长文本拆分为较小的片段再进行嵌入。最大输入长度（上下文窗口）与定价显示在 [模型广场](https://console.siflow.cn/model-inference/models) 的模型详情中。
* 在嵌入大量文本时，将多个输入放入一次请求中批量处理，以减少往返次数。

## 计费

* **公式**：总费用 = 输入 token 数 × 输入单价。

  Embedding 模型请求仅按输入 token 计费，不产生生成的输出。
* **价格**：各模型价格请在 [模型广场](https://console.siflow.cn/model-inference/models) 的模型详情页查看。
* **建议**：

  * 文档通常只需嵌入一次并缓存结果，避免每次请求都重复计算。
  * 可优先采用批量处理，以提升调用效率。

## 调用示例

示例使用环境变量读取 API Key，避免将密钥写入代码。

```bash theme={null}
export API_KEY="YOUR_API_KEY"
```

### 嵌入文本（Python）

```python theme={null}
import os
import requests

api_key = os.environ["API_KEY"]
api_url = "https://api.siflow.cn/model-api/embeddings"

response = requests.post(
    api_url,
    headers={
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    },
    json={
        "model": "Qwen/Qwen3-Embedding-4B",
        "input": [
            "Machine learning is a subset of artificial intelligence",
            "Deep learning uses neural networks with multiple layers",
            "Natural language processing enables computers to understand text",
        ],
    },
)

data = response.json()
for i, item in enumerate(data["data"]):
    print(f"Embedding {i}: {len(item['embedding'])} dimensions")
```

### 嵌入文本（curl）

```bash theme={null}
curl -X POST https://api.siflow.cn/model-api/embeddings \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $API_KEY" \
  -d '{
    "model": "Qwen/Qwen3-Embedding-4B",
    "input": [
      "Machine learning is a subset of artificial intelligence",
      "Deep learning uses neural networks with multiple layers"
    ]
  }'
```

### 语义相似度

```python theme={null}
import os
import requests
import numpy as np

api_key = os.environ["API_KEY"]
api_url = "https://api.siflow.cn/model-api/embeddings"


def embed(texts):
    resp = requests.post(
        api_url,
        headers={
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
        },
        json={"model": "BAAI/bge-m3", "input": texts},
    )
    return [np.array(item["embedding"]) for item in resp.json()["data"]]


def cosine(a, b):
    return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))


query, *docs = embed([
    "How do I reset my password?",
    "Steps to recover a forgotten account password.",
    "Our refund policy for annual plans.",
])

for i, doc in enumerate(docs):
    print(f"doc {i}: {cosine(query, doc):.3f}")
```
