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

# Embeddings 向量检索

> 生成文本向量，正确匹配输入并实现小规模检索。

Embeddings 把文本转换为向量，适用于语义检索、聚类等场景。[生成向量接口](/zh/api-reference/embeddings)只返回向量，不会自动建立索引或保存文档。模型列表中的模型不一定支持向量接口，请先确认部署中的可用模型。

## Python：批量向量与小规模检索

按 [Python SDK](/zh/guides/python)设置 `API_BASE_URL`（包含 `/v1`）、`API_KEY`、向量模型的 `API_MODEL`。保存为 `embeddings.py`，执行 `python embeddings.py`。示例将一个查询与两段候选文本一起发送，按响应 `index` 恢复对应关系，归一化后计算余弦相似度，再输出排序后的原文。

这只是内存中的小规模演示，适用于允许查询和文档使用相同编码方式的模型。需要 query/document 前缀或任务类型的模型，应按照模型要求分别编码；不要直接套用本例。真实排名由模型决定，不承诺某段文本一定排第一。

```python theme={null}
import json
import math
import os
from openai import OpenAI, APIConnectionError, APIStatusError

query = "How can I reset my password?"
documents = [
    "Invoices are available in the billing dashboard.",
    "Use the password reset link on the sign-in page.",
]
inputs = [query, *documents]

with OpenAI(base_url=os.environ["API_BASE_URL"].rstrip("/"),
            api_key=os.environ["API_KEY"], timeout=60.0, max_retries=0) as client:
    try:
        result = client.embeddings.create(
            model=os.environ["API_MODEL"], input=inputs, encoding_format="float",
        )
        vectors = {}
        dimensions = None
        if not isinstance(result.data, list) or len(result.data) != len(inputs):
            raise ValueError("Expected one vector per input.")
        for item in result.data:
            index = getattr(item, "index", None)
            vector = getattr(item, "embedding", None)
            if type(index) is not int or not 0 <= index < len(inputs) or index in vectors:
                raise ValueError("Invalid or duplicate input index.")
            if not isinstance(vector, list) or not vector:
                raise ValueError("Expected a nonempty float vector.")
            if any(type(value) not in (int, float) or not math.isfinite(value) for value in vector):
                raise ValueError("Invalid vector value.")
            if dimensions is not None and len(vector) != dimensions:
                raise ValueError("Inconsistent vector dimensions.")
            dimensions = len(vector)
            norm = math.hypot(*vector)
            if not math.isfinite(norm) or norm == 0:
                raise ValueError("Cannot normalize this vector.")
            vectors[index] = [value / norm for value in vector]
        matches = []
        for index, document in enumerate(documents):
            score = math.fsum(a * b for a, b in zip(vectors[0], vectors[index + 1]))
            matches.append({"index": index, "score": score, "text": document})
        matches.sort(key=lambda item: item["score"], reverse=True)
        print(json.dumps(matches, ensure_ascii=False, allow_nan=False))
    except APIStatusError as error:
        raise SystemExit(f"Request failed (HTTP {error.status_code}). Check model access and request limits.")
    except APIConnectionError:
        raise SystemExit("Connection failed. Check the API address and network.")
    except (ValueError, TypeError, OverflowError):
        raise SystemExit("Invalid embedding response; check indices, dimensions, and numeric values.")
```

## 输入、编码和维度

* 本指南使用单个字符串或字符串数组。上游 OpenAI 还接受 token ID 数组，但网关的文本提取与部分渠道转换只处理字符串，不能把 token 数组视为跨渠道通用输入。
* 示例显式传 `encoding_format: float`，并校验非空、有限数值、非零向量、统一维度和完整且不重复的索引。`data` 的数组位置不能代替 `index`。
* `dimensions` 只在模型和渠道支持时设置；不要随意截断向量。Base64 返回也是能力相关选项，例如当前 Jina 适配器会去掉 `encoding_format`，因此必须检查实际返回类型。
* 文本长度、单批条数和总 token 限制由部署与模型决定。不要把字符数当 token 数；先切分长文档，再按限制分批。两个接口都是同步 JSON，不提供本页所述请求的 SSE 输出。

## 从演示到检索应用

文档向量通常离线生成并保存，查询时只编码查询。记录文档 ID、分块 ID、模型版本、维度和预处理方式；查询与文档必须处于兼容的向量空间。相同维度不代表不同模型的向量可以混用，更换模型或编码方式通常需要重新建索引。确认模型是否已归一化及索引使用的距离度量，本例自行归一化来计算余弦。

由应用或向量数据库完成候选召回，再把候选文本交给 [Rerank](/zh/guides/rerank)精排。召回与精排前均应限制到当前用户可访问的文档，不能依赖模型过滤权限；Rerank 看不到没有传入的文档。真实向量数据库接入不包含在此演示中。

## 故障处理

400 时核对输入类型、长度、维度和编码选项；401/403 检查密钥与模型访问；429 按[错误处理](/zh/guides/errors)退避。HTTP 200 但少向量、重复索引或维度不一致时，拒绝写入索引，记录请求标识后排查。示例关闭自动重试，不打印密钥或完整错误响应。

字段含义参考 [OpenAI Embeddings API](https://developers.openai.com/api/reference/resources/embeddings/methods/create)；跨渠道行为以本项目适配器及实际部署为准。

下一步：用 [RAG 知识库问答](/zh/guides/rag)将召回、可选重排与带来源回答串成完整流程。

[Read in English](/en/guides/embeddings)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.