Skip to content

Quickstart

Get from zero to a streaming chat response in a few minutes.

1. Requirements

  • JDK 8 or later (java -version).
  • Maven 3.6+ or Gradle 6+.
  • A Model Studio API key — create one in the Model Studio console.

2. Install

<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. Configure the API key

The client resolves credentials from a config chain: system property -Ddashscope.api.key=sk-..., environment variable DASHSCOPE_API_KEY, then the SDK config file. The simplest setup:

export DASHSCOPE_API_KEY="sk-..."

You can also pass the key explicitly: DashScopeClient.builder().apiKey("sk-...").build(). See the Configuration guide for the full chain (base URL, region, workspace, timeouts, proxies).

4. First call (sync)

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

The client is AutoCloseable: try-with-resources releases the shared connection pool. Create one client and reuse it — every capability hangs off it as a typed resource.

5. Streaming

createStreaming returns a ResponseStream<ChatCompletionChunk> — iterable and AutoCloseable. The SDK asks the server for incremental frames by default, so each chunk's delta is a content increment:

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. Async

DashScopeAsyncClient mirrors the sync resource tree: unary calls return CompletableFuture, streaming calls return RxJava Flowable. Work runs on a daemon executor owned by the client:

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

try (DashScopeAsyncClient client = DashScopeAsyncClient.builder().build()) {
  // Unary: compose on the future.
  CompletableFuture<ChatCompletion> future = client.chat().completions().create(params);
  future.thenAccept(resp -> System.out.println(resp.outputText())).join();

  // Streaming: chunks surface as a 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());
    }
  });
}
Full runnable example: ChatCompletionsCreate.java (auto-synced)
// 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();
    }
  }
}
Full runnable example: ChatCompletionsCreateAsync.java (auto-synced)
// 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();
    }
  }
}

Next steps

  • Features — the full capability map.
  • The Guides section — chat & tool calls, multimodal, embeddings, audio, images/video, files & fine-tuning, AgentStudio, tokenization, configuration, errors, local mock debugging.
  • The API Reference section — auto-generated Javadoc for every public type.
  • The Migration section — moving 2.x code to 3.0.
  • Runnable examples live in the repository's examples/ folder, organized in four layers (atomic capabilities → advanced engineering → agent recipes → real-world scenarios) and verified by an offline dry-run suite.