> ## 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 模型

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

**代表性模型：** `Qwen/Qwen3-Embedding-4B`、`Qwen/Qwen3-Embedding-0.6B`、`BAAI/bge-m3`。完整列表与定价请参见 [模型广场](https://console.siflow.cn/maas-api/model_plaza)。

***

### 1. 使用场景

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

***

### 2. 如何使用

Embeddings API 支持单个字符串或字符串列表输入，并会为每个输入返回一个向量。常见流程是：先为文档生成向量并存储起来；在用户发起查询时，再对查询文本做嵌入，并与已有向量进行比较（例如使用余弦相似度）。

* 对文档和查询使用**同一个模型**进行嵌入，使它们的向量位于同一空间。
* 在嵌入大量文本时，将多个输入放入一次请求中批量处理，以减少往返次数。
* 最大输入长度（上下文窗口）与定价显示在 [模型广场](https://console.siflow.cn/maas-api/model_plaza) → 模型详情中。

***

### 3. 关键参数

* **参数**：`model`（embedding 模型名称）与 `input`（字符串或字符串列表）。部分模型还接受诸如 `float` 的 `encoding_format`。
* **输入长度**：如果某个输入超过模型的最大长度，请先将长文本拆分为较小的片段再进行嵌入。

***

### 4. 计费与配额

* **公式**：总费用 = 输入 token 数 × 输入单价。Embedding 请求仅按输入 token 计费（不产生生成的输出）。
* 各模型定价：[模型广场](https://console.siflow.cn/maas-api/model_plaza) → 模型详情页面。
* **建议**：文档通常只需嵌入一次并缓存结果，避免每次请求都重复计算；同时可优先采用批量处理，以提升调用效率。

***

### 5. 示例

#### 5.1 嵌入文本（Python）

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

api_key = os.getenv("API_KEY") or "<YOUR 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")
```

#### 5.2 嵌入文本（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"
    ]
  }'
```

#### 5.3 语义相似度

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

api_key = os.getenv("API_KEY") or "<YOUR 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}")
```

***

* 对文档和查询使用同一个 embedding 模型，使向量之间可比较。
* 最大输入长度（上下文窗口）、定价以及支持的语言因模型而异；请参见 [模型广场](https://console.siflow.cn/maas-api/model_plaza) → 模型详情。
