> ## 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.

# Rerank 文档重排

> 重排候选文档，正确关联索引、原文与相关性分数。

Rerank 将一个查询与已召回的候选文本重新排序，常用于 RAG 的精排阶段。它返回相关性分数和原始文档索引，不生成向量、不搜索整个知识库，也不直接生成回答。

[POST /v1/rerank](/zh/api-reference/rerank)是网关接入端点，不是 OpenAI 官方 API。先确认渠道支持 Rerank，并使用独立的重排模型；不能把 Embeddings 或对话模型自动当成重排模型。

## Python：重排候选文本

按 [Python SDK](/zh/guides/python)配置 `API_BASE_URL`（包含 `/v1`）、`API_KEY` 和重排模型的 `API_MODEL`。保存为 `rerank.py`，执行 `python rerank.py`。示例复用 SDK 的通用 HTTP `client.post`，没有依赖不存在的 `client.rerank` 方法，也无需额外安装供应商 SDK。

本例显式请求 `top_n: 2` 和 `return_documents: false`，校验结果索引与分数，按分数降序排列，并用 `index` 找回原始文本。即使渠道仍返回 `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.",
    "You can change the interface language in settings.",
]
top_n = 2

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:
        # Generic HTTP helper: /rerank is a gateway extension, not an OpenAI API method.
        result = client.post("/rerank", cast_to=dict, body={
            "model": os.environ["API_MODEL"], "query": query, "documents": documents,
            "top_n": top_n, "return_documents": False,
        })
        if not isinstance(result, dict) or not isinstance(result.get("results"), list):
            raise ValueError("Expected a results array.")
        seen = set()
        matches = []
        for item in result["results"]:
            if not isinstance(item, dict):
                raise ValueError("Expected a result object.")
            index = item.get("index")
            score = item.get("relevance_score")
            if type(index) is not int or not 0 <= index < len(documents) or index in seen:
                raise ValueError("Invalid or duplicate document index.")
            if type(score) not in (int, float) or not math.isfinite(score):
                raise ValueError("Invalid relevance score.")
            seen.add(index)
            # Preserve application-owned text and IDs using the original input index.
            matches.append({"index": index, "score": score, "text": documents[index]})
        matches.sort(key=lambda item: item["score"], reverse=True)
        print(json.dumps(matches[:top_n], ensure_ascii=False, allow_nan=False))
    except APIStatusError as error:
        raise SystemExit(f"Request failed (HTTP {error.status_code}). Check rerank model access and parameters.")
    except APIConnectionError:
        raise SystemExit("Connection failed. Check the API address and network.")
    except (ValueError, TypeError, OverflowError):
        raise SystemExit("Invalid rerank response; check result indices and numeric scores.")
```

## 索引、分数和返回条数

`results[].index` 是本次 `documents` 数组的零基位置，不是排名，也不是数据库文档 ID。若先进行过滤、分块或截取候选集，需保留这份最终数组与业务 ID 的对应关系。禁止通过分数数组位置去取原文。

分数越高通常表示在本次查询中越相关，但不是统一校准的概率，也不是不同模型之间可直接比较的数值。本例只要求分数为有限数，不强制限定在 0–1；阈值应根据所选模型和业务样本评估。返回空 `results` 时输出空列表，不伪造候选。若模型无相关结果但仍给出排序，应用仍需按业务阈值决定是否拒答。

显式设置 `top_n` 为正整数且不大于候选数量。部分渠道可能忽略返回数量，本例会在本地截取前两项，但这不会减少上游已处理的文档。`top_n` 是返回数量，不是从知识库召回多少条。

## 渠道差异

| 参数 | 当前实现中的差异 |
| - | - |
| `return_documents` | Cohere 适配器固定请求 `true`；Ali 在省略时默认 `true`；因此省略或设置 `false` 都不能作为通用的不回传原文保证 |
| `top_n` | Cohere 省略或传非正数时转为 1，其他渠道可能使用不同默认值；示例显式传 2 |
| `documents` | DTO 可接收对象，但字段与支持情况由渠道决定；字符串数组是本文的可迁移基线 |
| `max_chunk_per_doc` / `overlap_tokens` | 网关字段采用这两个拼写，但并非所有适配器转发；不要照搬供应商的复数字段名或承诺统一长文分块 |

请求中的 query 和 documents 均会发送到配置的网关及上游；`return_documents: false` 不表示“不上传原文”。需要结构化文档时，可在应用中序列化为稳定的文本，并保留独立业务 ID。先控制候选数量和文档长度，再调重排参数，不要把整库一次性发送。

## 与 Embeddings 配合

流程为：[Embeddings](/zh/guides/embeddings)建向量索引 → 应用召回候选 → Rerank 精排 → 将选中的原文交给对话模型。只使用 Rerank 也可以重排来自关键词搜索的候选。

错误时先检查模型能力、非空 query/documents、长度和可选参数。HTTP 200 仍需检查 `results` 结构、索引越界/重复和非法分数。本例遇到格式问题失败退出，且不自动重试。

评分解释参考 [Cohere Rerank 最佳实践](https://docs.cohere.com/docs/reranking-best-practices)；该供应商的请求限制不能视为所有渠道的统一限制。

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

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


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