Skip to content
LangChain4j 文档版本 1.22.0 源快照 0cf33980 更新于 2026-10-14

Google Cloud Vertex AI 排序(Ranking)API

简介

Google Cloud Vertex AI 排序 API 是一个强大的工具,它通过提升检索文档与给定查询的相关性来改进搜索结果。与传统搜索方法不同,它借助先进的机器学习 算法理解查询与文档的语义上下文,从而给出更精准、更相关的结果。通过分析查询与每篇文档之间的语义关系,该 API 能依据计算出的相关性分数对候选 文档重新排序,确保最相关的结果出现在搜索结果页的顶部。

Maven 依赖

xml
<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j-vertex-ai</artifactId>
    <version>1.22.0-beta32</version>
</dependency>

用法

要配置该模型,你需要指定:

  • Google Cloud 项目 ID,
  • 项目编号,
  • 位置(如 us-central1、europe-west1),
  • 以及你想使用的模型。

注:你可以在 Google Cloud 控制台中找到项目编号,或运行 gcloud projects describe your-project-id 获取。

借助 score(text, query) 和 score(segment, query) 方法,你可以对一个字符串或 TextSegment 相对于某个查询进行打分。

也可以用 scoreAll(segments, query) 方法对多个字符串或 TextSegment 相对于该查询打分:

java
VertexAiScoringModel scoringModel = VertexAiScoringModel.builder()
    .projectId(System.getenv("GCP_PROJECT_ID"))
    .projectNumber(System.getenv("GCP_PROJECT_NUM"))
    .projectLocation(System.getenv("GCP_LOCATION"))
    .model("semantic-ranker-512")
    .build();

Response<List<Double>> score = scoringModel.scoreAll(Stream.of(
        "The sky appears blue due to a phenomenon called Rayleigh scattering. " +
            "Sunlight is comprised of all the colors of the rainbow. Blue light has shorter " +
            "wavelengths than other colors, and is thus scattered more easily.",

        "A canvas stretched across the day,\n" +
            "Where sunlight learns to dance and play.\n" +
            "Blue, a hue of scattered light,\n" +
            "A gentle whisper, soft and bright."
        ).map(TextSegment::from).collect(Collectors.toList()),
    "Why is the sky blue?");

// [0.8199999928474426, 0.4300000071525574]

如果你传入的 TextSegment 带有特定的 title 键,Ranker 模型能在计算中考虑这一元数据。 要指定自定义的 title 键,你可以使用 titleMetadataKey() builder 方法。`

你可以将评分模型与 AiServices 及其 contentAgregator() 方法一起使用, 后者接收一个可指定评分模型的 ContentAggregator 类:

java
VertexAiScoringModel scoringModel = VertexAiScoringModel.builder()
    .projectId(System.getenv("GCP_PROJECT_ID"))
    .projectNumber(System.getenv("GCP_PROJECT_NUM"))
    .projectLocation(System.getenv("GCP_LOCATION"))
    .model("semantic-ranker-512")
    .build();

ContentAggregator contentAggregator = ReRankingContentAggregator.builder()
    .scoringModel(scoringModel)
    ... 
    .build();

RetrievalAugmentor retrievalAugmentor = DefaultRetrievalAugmentor.builder()
    ...
    .contentAggregator(contentAggregator)
    .build();

return AiServices.builder(Assistant.class)
    .chatModel(...)
    .retrievalAugmentor(retrievalAugmentor)
    .build();

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。