RAG Rerank(重排)框架 -- Cohere Rerank

Cohere Rerank(重排) 框架

Cohere Rerank 在商业化 RAG 架构中非常成熟、效果非常稳健,是各大主流 AI 框架(LangChain、LlamaIndex 等)默认首选的重排(Rerank)方案。

Cohere 免费的 Key 有每分钟请求次数(Rate Limit)的限制,适合个人开发、RAG 测试。
免费的 Key ,Rerank 接口的每分钟请求限制(RPM)是 10 次 / 分钟。免费测试版还有全局硬性限制:总调用量限制总共 1,000 次 / 月(每月初重置)。
免费的 Key ,完全够个人写 Demo、本地联调、验证 RAG 检索效果使用。
如果是企业级别的,需要付费。1000 次搜索 的价格通常在 $2.00 ~ $2.50 美元。

Cohere 的API Key,怎么获取?

获取 Cohere 的 API Key 非常简单,只需几步操作:

  • 访问官网并注册账号

打开Cohere Dashboard 注册页面, https://dashboard.cohere.com/welcome/register

可以直接使用 Google 账号、GitHub 账号快捷登录,或者用邮箱进行注册。

  • 进入后台获取 API Key

登录成功后,找到并点击 API Keys 选项,或者直接访问 [dashboard.cohere.com/api-keys](https://dashboard.cohere.com/api-keys)

网站会自动为你生成一个默认的免费试用密钥。

  • 复制并保存

点击该 Key 旁边的复制按钮,保存到你的本地配置文件(如 Spring Boot 的 application.yml.env 文件)中。

maven 引入 Cohere

<dependency>
    <groupId>com.cohere</groupId>
    <artifactId>cohere-java</artifactId>
    <version>1.10.1</version>
</dependency>

Cohere Rerank 服务代码:

import com.cohere.api.Cohere;
import com.cohere.api.resources.v2.requests.V2RerankRequest;
import com.cohere.api.resources.v2.types.V2RerankResponse;

import java.util.List;

public class CohereRerankService {

    private static final String DEFAULT_MODEL = "rerank-v4.0-fast";

    private final Cohere cohere;
    private final String model;

    public CohereRerankService(String apiKey) {
        this(apiKey, DEFAULT_MODEL);
    }

    public CohereRerankService(String apiKey, String model) {
        if (apiKey == null || apiKey.isBlank()) {
            throw new IllegalArgumentException("Cohere API Key不能为空");
        }

        this.cohere = Cohere.builder()
                .token(apiKey)
                .clientName("java-rerank-example")
                .build();

        this.model = model;
    }

    /**
     * 对候选文档重新评分和排序。
     */
    public List<RerankResult> rerank(
            String query,
            List<String> documents,
            int topN) {

        if (query == null || query.isBlank()) {
            throw new IllegalArgumentException("查询内容不能为空");
        }

        if (documents == null || documents.isEmpty()) {
            return List.of();
        }

        int resultSize = Math.min(Math.max(topN, 1), documents.size());

        V2RerankRequest request = V2RerankRequest.builder()
                .model(model)
                .query(query)
                .documents(documents)
                .topN(resultSize)
                .build();

        try {
            V2RerankResponse response = cohere.v2().rerank(request);

            return response.getResults().stream()
                    .map(result -> new RerankResult(
                            result.getIndex(),
                            documents.get(result.getIndex()),
                            result.getRelevanceScore()))
                    .toList();
        } catch (RuntimeException exception) {
            throw new CohereRerankException(
                    "调用 Cohere Rerank API 失败",
                    exception);
        }
    }

    public record RerankResult(
            int originalIndex,
            String document,
            double relevanceScore) {
    }

    public static class CohereRerankException extends RuntimeException {

        public CohereRerankException(String message, Throwable cause) {
            super(message, cause);
        }
    }
}

Cohere Rerank 调用示例

import java.util.List;

public class CohereRerankExample {

    public static void main(String[] args) {
        //需要在本地环境配置变量 COHERE_API_KEY
        String apiKey = System.getenv("COHERE_API_KEY");

        CohereRerankService rerankService =
                new CohereRerankService(apiKey);

        String query = "如何提高知识库检索结果的相关性?";

        List<String> candidateDocuments = List.of(
                "可以使用向量数据库快速召回语义相似的候选文档。",
                "Cohere Rerank 可以对候选文档进行精确评分和重新排序。",
                "Java 是一种面向对象的编程语言。",
                "合理设置分块大小可以减少知识内容混杂。"
        );

        List<CohereRerankService.RerankResult> results =
                rerankService.rerank(
                        query,
                        candidateDocuments,
                        2);

        results.forEach(result -> {
            System.out.println("原始下标:" + result.originalIndex());
            System.out.println("相关性分数:" + result.relevanceScore());
            System.out.println("文档内容:" + result.document());
            System.out.println();
        });
    }
}

posted on 2026-08-13 17:42  乐之者v  阅读(8)  评论(0)    收藏  举报

导航