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

# Embeddings

> 生成文本的数值向量表示，用于搜索、聚类和分类。

## 概述

Embedding 是文本的数值向量表示，用于捕捉语义信息。借助它，你可以对文本执行数学运算，例如衡量不同文本之间的“距离”或“相似度”。

它是许多 AI 应用的基础能力，包括语义搜索、聚类、推荐、异常检测和分类。YouRouter 通过一个简单统一的 API 提供主流 embedding 模型。

## 用法

<CodeGroup>
  ```python Python theme={null}
  import os
  from openai import OpenAI

  client = OpenAI(
      api_key=os.environ["YOUROUTER_API_KEY"],
      base_url="https://api.yourouter.ai/v1"
  )

  response = client.embeddings.create(
      input="The quick brown fox jumps over the lazy dog",
      model="text-embedding-ada-002"
  )

  embedding = response.data[0].embedding
  print(f"Embedding dimensions: {len(embedding)}")
  ```

  ```javascript Node.js theme={null}
  import OpenAI from 'openai';

  const openai = new OpenAI({
    apiKey: process.env.YOUROUTER_API_KEY,
    baseURL: 'https://api.yourouter.ai/v1',
  });

  async function main() {
    const response = await openai.embeddings.create({
      input: "Your text string goes here",
      model: "text-embedding-ada-002",
    });
    console.log(response.data[0].embedding);
  }

  main();
  ```

  ```bash cURL theme={null}
  curl https://api.yourouter.ai/v1/embeddings \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $YOUROUTER_API_KEY" \
    -d '{
      "input": "The quick brown fox jumps over the lazy dog",
      "model": "text-embedding-ada-002"
    }'
  ```
</CodeGroup>

### 批量处理

为了提高效率，可以给 `input` 传一个字符串数组，一次生成多个 embedding。

<CodeGroup>
  ```python theme={null}
  response = client.embeddings.create(
      input=[
          "First sentence to embed.",
          "Another sentence for batch processing."
      ],
      model="text-embedding-ada-002"
  )

  for i, data in enumerate(response.data):
      print(f"Embedding for input {i+1}: {len(data.embedding)} dimensions")
  ```
</CodeGroup>

## 参数

<ResponseField name="input" type="string or array" required>
  要做 embedding 的文本。可以是单个字符串，也可以是字符串数组。
</ResponseField>

<ResponseField name="model" type="string" required>
  要使用的 embedding 模型 ID，例如 `text-embedding-ada-002`。
</ResponseField>

<ResponseField name="encoding_format" type="string" default="float">
  返回 embedding 的编码格式，可选 `float` 或 `base64`。`base64` 有助于减少 JSON 体积。
</ResponseField>

<ResponseField name="user" type="string">
  代表终端用户的唯一标识，可用于监控和滥用检测。
</ResponseField>

## 使用场景

### 语义搜索

语义搜索并不依赖关键词精确匹配，而是寻找在语义上与用户查询更相关的内容，即使它们不包含完全相同的词语。实现方式通常是比较查询向量和文档向量之间的相似度。

```python theme={null}
import numpy as np
from scipy.spatial.distance import cosine

documents = [
    "The sky is blue and beautiful.",
    "The sun is the star at the center of the Solar System.",
    "Artificial intelligence will reshape our world."
]

doc_embeddings = [
    client.embeddings.create(input=doc, model="text-embedding-ada-002").data[0].embedding
    for doc in documents
]

query = "What is the future of AI?"
query_embedding = client.embeddings.create(input=query, model="text-embedding-ada-002").data[0].embedding

similarities = [1 - cosine(query_embedding, doc_emb) for doc_emb in doc_embeddings]
most_similar_index = np.argmax(similarities)

print(f"Query: '{query}'")
print(f"Most similar document: '{documents[most_similar_index]}'")
```

### 分类与聚类

Embedding 也是很强的机器学习特征。你可以把它们输入分类器，例如情感分析或主题分类，也可以用聚类算法把相似内容分组。

## 最佳实践

<AccordionGroup>
  <Accordion title="预处理">
    虽然现代 embedding 模型已经很鲁棒，但在某些场景下，适度的文本预处理仍然有帮助，比如移除无关字符或做基础规范化。不过不建议过度 stemming 或 stop-word removal，以免损失语义上下文。
  </Accordion>

  <Accordion title="通过批量提升效率">
    当你需要处理多段文本时，优先传数组进行批量 embedding。这样能显著减少网络往返次数并降低延迟。
  </Accordion>

  <Accordion title="缓存">
    如果应用会频繁对相同文本做 embedding，例如热门查询或常见标题，建议增加缓存层，例如 Redis 或内存缓存。这样可以减少 API 调用、降低成本并提升性能。
  </Accordion>
</AccordionGroup>

## 扩展方案：向量数据库

当 embedding 数量超过几千条时，暴力遍历计算相似度会越来越慢。这时通常需要引入向量数据库。

向量数据库专门用于高效存储和检索海量向量，支持百万甚至十亿级 embedding 搜索。它们通过 HNSW、IVF 等索引算法实现近似最近邻搜索，在速度和准确率之间取得很好的平衡。

常见选择包括：

* **云服务**：Pinecone、Zilliz Cloud
* **开源 / 自托管**：Weaviate、Milvus、Chroma、Qdrant
