跳转至内容

异步客户端

DashScopeAsyncClient 完整镜像同步资源树 —— 相同的访问器、相同的参数 builder —— 但一元调用 返回 CompletableFuture<T>,流式调用返回 RxJava Flowable<T>(与 2.x 对齐)。底层异步服务在 executor 上委托同步实现,因此行为(重试、错误、配置链)完全一致。

改编自可运行的 ChatCompletionsCreateAsync。

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

import com.alibaba.dashscope.DashScopeAsyncClient;
import com.alibaba.dashscope.examples.ExampleSupport;
import com.alibaba.dashscope.types.completions.ChatCompletion;
import com.alibaba.dashscope.types.completions.ChatCompletionChunk;
import com.alibaba.dashscope.types.completions.ChatCompletionCreateParams;
import com.alibaba.dashscope.types.completions.Delta;
import com.alibaba.dashscope.types.messages.Message;
import io.reactivex.Flowable;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * Async chat completions: {@link DashScopeAsyncClient} mirrors the sync resource tree, returning
 * {@link CompletableFuture} for unary calls and RxJava {@link Flowable} for streaming (2.x parity).
 *
 * <p>Work runs on a daemon executor owned by the client; try-with-resources shuts it down. Compare
 * with the sync {@link ChatCompletionsCreate}.
 */
public final class ChatCompletionsCreateAsync {

  public static void main(String[] args) throws Exception {
    String model = System.getenv().getOrDefault("DASHSCOPE_MODEL", "qwen3.7-plus");
    List<Message> messages =
        Arrays.asList(Message.system("You are a helpful assistant."), Message.user("请用一句话介绍杭州"));
    ChatCompletionCreateParams params =
        ChatCompletionCreateParams.builder().model(model).messages(messages).build();

    try (DashScopeAsyncClient client = ExampleSupport.asyncClient()) {
      // Non-streaming: the call returns immediately; compose on the future.
      System.out.println("----- async non-streaming request -----");
      CompletableFuture<ChatCompletion> future = client.chat().completions().create(params);
      CompletableFuture<String> answer =
          future.thenApply(
              resp -> {
                System.out.println(resp.outputText());
                System.out.println(
                    "usage: "
                        + resp.getUsage().getTotalTokens()
                        + " tokens, request_id: "
                        + resp.getRequestId());
                return resp.outputText();
              });
      answer.join();

      // Streaming: chunks surface as a Flowable; blockingForEach consumes them on this thread.
      System.out.println("----- async streaming request -----");
      Flowable<ChatCompletionChunk> stream = client.chat().completions().createStreaming(params);
      stream.blockingForEach(
          chunk -> {
            Delta delta = chunk.delta();
            if (delta != null && delta.getContent() != null) {
              System.out.print(delta.getContent());
              System.out.flush();
            }
          });
      System.out.println();
    }
  }
}

一元调用:CompletableFuture

import com.alibaba.dashscope.DashScopeAsyncClient;
import com.alibaba.dashscope.types.completions.ChatCompletion;
import java.util.concurrent.CompletableFuture;

try (DashScopeAsyncClient client = DashScopeAsyncClient.builder().build()) {
  // 调用立即返回;在 future 上组合后续逻辑。
  CompletableFuture<ChatCompletion> future = client.chat().completions().create(params);
  CompletableFuture<String> answer = future.thenApply(resp -> {
    System.out.println(resp.outputText());
    System.out.println("usage: " + resp.getUsage().getTotalTokens()
        + " tokens, request_id: " + resp.getRequestId());
    return resp.outputText();
  });
  answer.join();
}

失败会以同步客户端抛出的同一套类型化 DashScopeException 族异常完成 future —— 处理时解包 CompletionException.getCause()。

流式:Flowable

import com.alibaba.dashscope.types.completions.ChatCompletionChunk;
import com.alibaba.dashscope.types.completions.Delta;
import io.reactivex.Flowable;

Flowable<ChatCompletionChunk> stream = client.chat().completions().createStreaming(params);
// blockingForEach 在当前线程消费 chunk;响应式管线可用 subscribe(...)。
stream.blockingForEach(chunk -> {
  Delta delta = chunk.delta();
  if (delta != null && delta.getContent() != null) {
    System.out.print(delta.getContent());
    System.out.flush();
  }
});

生命周期与 executor

  • 工作运行在客户端自有的 daemon executor 上;try-with-resources(close())会将其关闭。 创建一个客户端并共享 —— 不要每次调用都新建客户端。
  • 用 DashScopeAsyncClient.builder().executor(...) 注入自己的 executor 以控制线程;注入后 生命周期由你负责(SDK 不会将其关闭)。httpClient(...) 同理。见配置。

同步 vs 异步一览

DashScopeClient DashScopeAsyncClient
一元 ChatCompletion create(params) CompletableFuture<ChatCompletion> create(params)
流式 ResponseStream<ChatCompletionChunk>(for-each、try-with-resources) Flowable<ChatCompletionChunk>(blockingForEach / subscribe)
逐请求选项 (params, RequestOptions) 重载 相同
关闭 try-with-resources try-with-resources(同时关闭自有 executor)