跳转至内容

向量化与重排

检索管线的两块基石:client.embeddings() 把文本变成向量,client.rerank() 按与查询的相关性 对候选文档重排序。改编自可运行的 EmbeddingsCreate 与 RerankCreate。

完整可运行示例:EmbeddingsCreate.java(自动同步)
// Copyright (c) Alibaba, Inc. and its affiliates.
package com.alibaba.dashscope.examples.atomic.embeddings;

import com.alibaba.dashscope.DashScopeClient;
import com.alibaba.dashscope.examples.ExampleSupport;
import com.alibaba.dashscope.types.embeddings.Embedding;
import com.alibaba.dashscope.types.embeddings.EmbeddingCreateParams;
import com.alibaba.dashscope.types.embeddings.EmbeddingResponse;
import java.util.Arrays;
import java.util.List;

/**
 * Text embeddings: one batch create call. Translation of the Python blueprint example
 * 01_atomic_capabilities/embeddings/embeddings.py.
 */
public final class EmbeddingsCreate {

  public static void main(String[] args) throws Exception {
    String model = System.getenv().getOrDefault("DASHSCOPE_MODEL", "text-embedding-v4");
    List<String> texts = Arrays.asList("杭州是浙江省的省会", "上海是中国的直辖市");

    try (DashScopeClient client = ExampleSupport.client()) {
      System.out.println("----- embeddings request -----");
      EmbeddingResponse resp =
          client
              .embeddings()
              .create(
                  EmbeddingCreateParams.builder()
                      .model(model)
                      .texts(texts)
                      .dimension(1024)
                      .build());
      for (Embedding item : resp.getEmbeddings()) {
        System.out.println(
            "index=" + item.getIndex() + ", embedding dim=" + item.getEmbedding().size());
      }
      System.out.println("usage: " + resp.getUsage().getTotalTokens() + " tokens");

      // Batch embedding over a file (one text per line) is available via the async-task facade:
      //   Job job =
      //       client.embeddings().jobs().create(
      //           com.alibaba.dashscope.types.embeddings.BatchEmbeddingCreateParams.builder()
      //               .model(model)
      //               .fileUrl("https://.../texts.txt")
      //               .build());
      //   Job result =
      //       client.embeddings().jobs().wait(job.getTaskId(),
      //           com.alibaba.dashscope.RequestOptions.NONE);
    }
  }
}
完整可运行示例:RerankCreate.java(自动同步)
// Copyright (c) Alibaba, Inc. and its affiliates.
package com.alibaba.dashscope.examples.atomic.rerank;

import com.alibaba.dashscope.DashScopeClient;
import com.alibaba.dashscope.examples.ExampleSupport;
import com.alibaba.dashscope.types.rerank.RerankCreateParams;
import com.alibaba.dashscope.types.rerank.RerankResponse;
import com.alibaba.dashscope.types.rerank.RerankResult;
import java.util.Arrays;

/**
 * Document reranking. Translation of the Python blueprint example
 * 01_atomic_capabilities/rerank/rerank.py.
 */
public final class RerankCreate {

  public static void main(String[] args) throws Exception {
    String model = System.getenv().getOrDefault("DASHSCOPE_MODEL", "gte-rerank-v2");

    try (DashScopeClient client = ExampleSupport.client()) {
      System.out.println("----- rerank request -----");
      RerankResponse resp =
          client
              .rerank()
              .create(
                  RerankCreateParams.builder()
                      .model(model)
                      .query("哈尔滨在哪?")
                      .documents(Arrays.asList("黑龙江离俄罗斯很近", "哈尔滨是中国黑龙江省的省会,位于中国东北"))
                      .topN(5)
                      .returnDocuments(true)
                      .instruct("Retrieval document that can answer users query.")
                      .build());
      for (RerankResult result : resp.getResults()) {
        String document = result.getDocument() == null ? null : result.getDocument().getText();
        System.out.println(
            "index="
                + result.getIndex()
                + ", score="
                + result.getRelevanceScore()
                + ", document="
                + document);
      }
      System.out.println(
          "usage: "
              + resp.getUsage().getTotalTokens()
              + " tokens, request_id: "
              + resp.getRequestId());
    }
  }
}

向量化

一次批量 create 调用取代 2.x 的 TextEmbedding / BatchTextEmbedding:

import com.alibaba.dashscope.types.embeddings.Embedding;
import com.alibaba.dashscope.types.embeddings.EmbeddingCreateParams;
import com.alibaba.dashscope.types.embeddings.EmbeddingResponse;
import java.util.Arrays;
import java.util.List;

List<String> texts = Arrays.asList("杭州是浙江省的省会", "上海是中国的直辖市");

EmbeddingResponse resp = client.embeddings().create(
    EmbeddingCreateParams.builder()
        .model("text-embedding-v4")
        .texts(texts)
        .dimension(1024)
        .build());
for (Embedding item : resp.getEmbeddings()) {
  System.out.println("index=" + item.getIndex()
      + ", embedding dim=" + item.getEmbedding().size());
}
System.out.println("usage: " + resp.getUsage().getTotalTokens() + " tokens");

文件批量向量化

大规模语料可用异步任务 facade 对整个文件向量化(每行一条文本):

Job job = client.embeddings().jobs().create(
    BatchEmbeddingCreateParams.builder()
        .model("text-embedding-v4")
        .fileUrl("https://.../texts.txt")
        .build());
Job result = client.embeddings().jobs().wait(job.getTaskId(), RequestOptions.NONE);

重排

import com.alibaba.dashscope.types.rerank.RerankCreateParams;
import com.alibaba.dashscope.types.rerank.RerankResponse;
import com.alibaba.dashscope.types.rerank.RerankResult;
import java.util.Arrays;

RerankResponse resp = client.rerank().create(
    RerankCreateParams.builder()
        .model("gte-rerank-v2")
        .query("哈尔滨在哪?")
        .documents(Arrays.asList(
            "黑龙江离俄罗斯很近",
            "哈尔滨是中国黑龙江省的省会,位于中国东北"))
        .topN(5)
        .returnDocuments(true)
        .instruct("Retrieval document that can answer users query.")
        .build());
for (RerankResult result : resp.getResults()) {
  String document = result.getDocument() == null ? null : result.getDocument().getText();
  System.out.println("index=" + result.getIndex()
      + ", score=" + result.getRelevanceScore()
      + ", document=" + document);
}
  • topN 限制返回结果数;returnDocuments(true) 回传文档文本。
  • instruct 用于引导排序任务描述(可选)。

组合起来(RAG)

先对语料向量化,按向量相似度召回候选,再用 rerank() 精排短名单,最后交给模型。完整管线: RagExpertSystem (recipe)与 ProductionRagHarness (场景 harness)。