跳转至内容

快速上手

几分钟内从零跑通一个流式对话响应。

1. 环境要求

  • JDK 8 及以上(java -version)。
  • Maven 3.6+ 或 Gradle 6+。
  • 百炼 API Key —— 在百炼控制台创建。

2. 安装

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>dashscope-sdk-java</artifactId>
    <version>3.0.0</version>
</dependency>
implementation 'com.alibaba:dashscope-sdk-java:3.0.0'
implementation("com.alibaba:dashscope-sdk-java:3.0.0")

3. 配置 API Key

客户端按配置链解析凭据:系统属性 -Ddashscope.api.key=sk-... → 环境变量 DASHSCOPE_API_KEY → SDK 配置文件。最简单的做法:

export DASHSCOPE_API_KEY="sk-..."

也可以显式传入:DashScopeClient.builder().apiKey("sk-...").build()。 完整配置链(base URL、region、workspace、超时、代理)见「配置」指南。

4. 第一次调用(同步)

import com.alibaba.dashscope.DashScopeClient;
import com.alibaba.dashscope.types.completions.ChatCompletion;
import com.alibaba.dashscope.types.completions.ChatCompletionCreateParams;
import com.alibaba.dashscope.types.messages.Message;
import java.util.Arrays;
import java.util.List;

public class QuickStart {
  public static void main(String[] args) {
    List<Message> messages = Arrays.asList(
        Message.system("You are a helpful assistant."),
        Message.user("请用一句话介绍杭州"));

    try (DashScopeClient client = DashScopeClient.builder().build()) {
      ChatCompletion resp = client.chat().completions().create(
          ChatCompletionCreateParams.builder()
              .model("qwen-plus")
              .messages(messages)
              .build());
      System.out.println(resp.outputText());
      System.out.println("usage: " + resp.getUsage().getTotalTokens()
          + " tokens, request_id: " + resp.getRequestId());
    }
  }
}

客户端实现了 AutoCloseable:try-with-resources 会释放共享连接池。请创建一个客户端并复用 —— 所有能力都以类型化资源的形式挂载其上。

5. 流式

createStreaming 返回 ResponseStream<ChatCompletionChunk> —— 可遍历且 AutoCloseable。 SDK 默认向服务端请求增量帧,因此每个 chunk 的 delta 就是内容增量:

import com.alibaba.dashscope.types.common.ResponseStream;
import com.alibaba.dashscope.types.completions.ChatCompletionChunk;
import com.alibaba.dashscope.types.completions.Delta;

try (ResponseStream<ChatCompletionChunk> stream =
    client.chat().completions().createStreaming(
        ChatCompletionCreateParams.builder()
            .model("qwen-plus")
            .messages(messages)
            .build())) {
  for (ChatCompletionChunk chunk : stream) {
    Delta delta = chunk.delta();
    if (delta != null && delta.getContent() != null) {
      System.out.print(delta.getContent());
      System.out.flush();
    }
  }
}

6. 异步

DashScopeAsyncClient 完整镜像同步资源树:一元调用返回 CompletableFuture,流式调用返回 RxJava Flowable。任务运行在客户端持有的守护线程池上:

import com.alibaba.dashscope.DashScopeAsyncClient;
import io.reactivex.Flowable;
import java.util.concurrent.CompletableFuture;

try (DashScopeAsyncClient client = DashScopeAsyncClient.builder().build()) {
  // 一元调用:在 future 上组合。
  CompletableFuture<ChatCompletion> future = client.chat().completions().create(params);
  future.thenAccept(resp -> System.out.println(resp.outputText())).join();

  // 流式:chunk 以 Flowable 形式到达。
  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());
    }
  });
}
完整可运行示例:ChatCompletionsCreate.java(自动同步)
// Copyright (c) Alibaba, Inc. and its affiliates.
package com.alibaba.dashscope.examples.atomic.chat;

import com.alibaba.dashscope.DashScopeClient;
import com.alibaba.dashscope.examples.ExampleSupport;
import com.alibaba.dashscope.types.common.ResponseStream;
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 java.util.Arrays;
import java.util.List;

/**
 * Chat completions: non-streaming and streaming. Translation of the Python blueprint example
 * 01_atomic_capabilities/text_generation/chat.py.
 *
 * <p>The Python module-level one-call quickstart {@code dashscope.chat(model, prompt)} has no Java
 * 3.0 equivalent; the try-with-resources {@link DashScopeClient} below is the entry point.
 */
public final class ChatCompletionsCreate {

  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("请用一句话介绍杭州"));

    try (DashScopeClient client = ExampleSupport.client()) {
      // Non-streaming
      System.out.println("----- non-streaming request -----");
      ChatCompletion resp =
          client
              .chat()
              .completions()
              .create(ChatCompletionCreateParams.builder().model(model).messages(messages).build());
      System.out.println(resp.outputText());
      System.out.println(
          "usage: "
              + resp.getUsage().getTotalTokens()
              + " tokens, request_id: "
              + resp.getRequestId());

      // Streaming: each chunk's delta carries a content increment (the SDK asks the server for
      // incremental frames by default when streaming).
      System.out.println("----- streaming request -----");
      try (ResponseStream<ChatCompletionChunk> stream =
          client
              .chat()
              .completions()
              .createStreaming(
                  ChatCompletionCreateParams.builder().model(model).messages(messages).build())) {
        for (ChatCompletionChunk chunk : stream) {
          Delta delta = chunk.delta();
          if (delta != null && delta.getContent() != null) {
            System.out.print(delta.getContent());
            System.out.flush();
          }
        }
      }
      System.out.println();
    }
  }
}
完整可运行示例: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();
    }
  }
}

下一步

  • 特性 —— 能力全景。
  • 「指南」分区 —— 对话与工具调用、多模态、向量化、语音、图像/视频、文件与微调、AgentStudio、 分词器、配置、错误、本地 Mock 调试。
  • 「API 参考」分区 —— 为每个公共类型自动生成的 Javadoc。
  • 「迁移」分区 —— 2.x 代码迁移到 3.0。
  • 可运行示例位于仓库 examples/ 目录,按四层组织(原子能力 → 高级工程 → 智能体配方 → 真实场景),并由离线 dry-run 套件验证。