Skip to content

Embeddings and Rerank

Two building blocks for retrieval pipelines: client.embeddings() turns text into vectors, client.rerank() reorders candidate documents by relevance to a query. Adapted from the runnable EmbeddingsCreate and RerankCreate.

Full runnable example: EmbeddingsCreate.java (auto-synced)
// 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);
    }
  }
}
Full runnable example: RerankCreate.java (auto-synced)
// 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());
    }
  }
}

Embeddings

One batch create call replaces 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(
    "Hangzhou is the capital of Zhejiang",
    "Shanghai is a municipality of China");

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");

Batch embedding over a file

For large corpora, an async-task facade embeds a file (one text per line):

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);

Rerank

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("Where is Harbin?")
        .documents(Arrays.asList(
            "Heilongjiang borders Russia",
            "Harbin is the capital of Heilongjiang, in northeast China"))
        .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 caps how many results come back; returnDocuments(true) echoes the document text.
  • instruct steers the ranking task description (optional).

Putting it together (RAG)

Embed the corpus, retrieve candidates by vector similarity, then rerank the shortlist with rerank() before handing it to the model. Complete pipelines: RagExpertSystem (recipe) and ProductionRagHarness (scenario harness).