`(`Iterable` + `AutoCloseable`),默认增量帧。见[对话与流式](guides/chat.md)。 |
+| 类型化错误 | unchecked 的 `DashScopeException` 家族(`AuthenticationException`、`RateLimitException`、`ContentFilterException`、`ApiTimeoutException`……),携带 `code`、HTTP 状态码与 `request_id`。见[错误与诊断](guides/errors.md)。 |
+| 自动重试 | 非流式 HTTP 按请求配置和失败类型重试,不判断操作是否幂等。支持退避和 `Retry-After` / `Retry-After-ms` / `X-Should-Retry`;用 `RequestOptions` 逐请求覆盖。见[错误与诊断](guides/errors.md)。 |
+| 配置链 | builder > 系统属性 > 环境变量 > `~/.dashscope/config.toml` > 默认值;逐请求 `RequestOptions`。见[配置](guides/configuration.md)。 |
+| 加密通道 | 可选 RSA 信封加密(`RequestOptions.enableEncryption(true)`),自动获取并缓存网关公钥。 |
+| AgentStudio | 托管智能体资源(agents、sessions、events、记忆库、凭据库……)与 `legacy_2x` 解耦,独立端点(`DASHSCOPE_AGENTSTUDIO_URL`),SSE 流单次遍历语义。见 [AgentStudio](guides/agentstudio.md)。 |
+| 本地分词器 | `TokenizerFactory.qwen()` 使用已有词表时可离线计数;缺少词表时可能下载。另有远程 `tokenization().count`。见[分词器](guides/tokenization.md)。 |
+| 冻结的 2.x facade | 迁入 `legacy_2x` 的接口已废弃并将在 4.0 移除;AgentStudio 和 `shared` 不受此移除计划影响。见[从 2.x 迁移](migrating.md)。 |
+| 工程质量 | JDK 8+ 字节码、ErrorProne 检查和 CI Mock 干跑。麦克风实时识别与要求 HTTPS 下载结果的批量转写不在干跑范围内,归档的旧版示例也不参与构建。见[示例中心](examples.md)。 |
+
+## 2.x 系列
+
+2.x 代际(发布至 **v2.23.8**,2026 年 11 月)围绕按能力划分的入口类构建 ——
+`new Generation()`、`new MultiModalConversation()`、`new ImageSynthesis()`……——
+搭配受检异常 `ApiException` / `NoApiKeyException` / `InputRequiredException`,以及
+`ResultCallback` / `Flowable` 流式调用。
+
+在 3.x 构件继续使用迁入 `com.alibaba.dashscope.legacy_2x` 的 API,需要更改 import 并重新编译。该层已**冻结**、废弃,并将在 4.0 移除。包名映射见[旧版 2.x](legacy.md),入口对照表见[从 2.x 迁移](migrating.md)。2.x 各版本的变更记录仍可在
+[GitHub Releases](https://github.com/dashscope/dashscope-sdk-java/releases) 查阅。
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/ExampleSupport.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/ExampleSupport.java
new file mode 100644
index 00000000..93d32687
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/ExampleSupport.java
@@ -0,0 +1,42 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples;
+
+import com.alibaba.dashscope.DashScopeAsyncClient;
+import com.alibaba.dashscope.DashScopeClient;
+
+/**
+ * Shared entry helpers for all examples: the API key comes only from the config chain ({@code
+ * -Ddashscope.api.key=} / {@code DASHSCOPE_API_KEY} / config file); when missing, print guidance
+ * and exit non-zero (design §8 requirements).
+ */
+public final class ExampleSupport {
+
+ private ExampleSupport() {}
+
+ public static String requireApiKey() {
+ String key = System.getProperty("dashscope.api.key");
+ if (key == null || key.isEmpty()) {
+ key = System.getenv("DASHSCOPE_API_KEY");
+ }
+ if (key == null || key.isEmpty()) {
+ System.err.println(
+ "error: no API key. Set DASHSCOPE_API_KEY (or -Ddashscope.api.key=sk-...); "
+ + "see https://www.alibabacloud.com/help/en/model-studio/get-api-key");
+ System.exit(1);
+ }
+ return key;
+ }
+
+ /**
+ * Sync client from the config chain (env/sysprops/config file); close it with try-with-resources.
+ */
+ public static DashScopeClient client() {
+ requireApiKey();
+ return DashScopeClient.builder().build();
+ }
+
+ public static DashScopeAsyncClient asyncClient() {
+ requireApiKey();
+ return DashScopeAsyncClient.builder().build();
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/apps/AppsCompletionsCreate.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/apps/AppsCompletionsCreate.java
new file mode 100644
index 00000000..c91033d1
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/apps/AppsCompletionsCreate.java
@@ -0,0 +1,53 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.apps;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.types.apps.AppCompletion;
+import com.alibaba.dashscope.types.apps.AppCompletionCreateParams;
+import com.alibaba.dashscope.types.common.ResponseStream;
+
+/**
+ * Bailian application call: non-streaming and streaming. Translation of the Python blueprint
+ * example 01_atomic_capabilities/applications/apps.py.
+ *
+ * APP_ID: the application ID of a Model Studio app; provide it via the {@code DASHSCOPE_APP_ID}
+ * environment variable.
+ */
+public final class AppsCompletionsCreate {
+
+ public static void main(String[] args) throws Exception {
+ String appId = System.getenv().getOrDefault("DASHSCOPE_APP_ID", "");
+ String prompt = "如何做土豆炖猪脚?";
+
+ try (DashScopeClient client = ExampleSupport.client()) {
+ // Non-streaming
+ System.out.println("----- non-streaming request -----");
+ AppCompletion resp =
+ client
+ .apps()
+ .completions()
+ .create(AppCompletionCreateParams.builder().appId(appId).prompt(prompt).build());
+ System.out.println(resp.getText());
+ System.out.println(
+ "session_id: " + resp.getSessionId() + ", request_id: " + resp.getRequestId());
+
+ // Streaming: each frame carries the completion text as it arrives
+ System.out.println("----- streaming request -----");
+ try (ResponseStream stream =
+ client
+ .apps()
+ .completions()
+ .createStreaming(
+ AppCompletionCreateParams.builder().appId(appId).prompt(prompt).build())) {
+ for (AppCompletion chunk : stream) {
+ if (chunk.getText() != null && !chunk.getText().isEmpty()) {
+ System.out.print(chunk.getText());
+ System.out.flush();
+ }
+ }
+ }
+ System.out.println();
+ }
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/AsrHttpStreamRecognize.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/AsrHttpStreamRecognize.java
new file mode 100644
index 00000000..22363142
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/AsrHttpStreamRecognize.java
@@ -0,0 +1,147 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.audio;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.types.common.ResponseStream;
+import com.alibaba.dashscope.types.common.Usage;
+import com.alibaba.dashscope.types.multimodal.ContentPart;
+import com.alibaba.dashscope.types.multimodal.MultimodalChatChunk;
+import com.alibaba.dashscope.types.multimodal.MultimodalChatCreateParams;
+import com.alibaba.dashscope.types.multimodal.MultimodalChoice;
+import com.alibaba.dashscope.types.multimodal.MultimodalMessage;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * REST ASR: submit complete WAV audio once and receive cumulative transcripts over SSE. The Python
+ * original POSTs {@code /services/aigc/multimodal-generation/generation} through the raw transport;
+ * Java 3.0 has no raw transport API, so the SAME endpoint semantics are expressed as {@code
+ * client.multimodal().chat().createStreaming(...)} with model {@code qwen-audio-3.1-asr-flash}, one
+ * audio content part, and the ASR knobs ({@code format}, {@code sample_rate}) carried in the {@code
+ * parameters} passthrough. A local file is uploaded by the SDK's OSS preprocessing (an {@code
+ * oss://} URL plus the resolve header) instead of Python's base64 data URI; an {@code --url} value
+ * is sent as-is. This is NOT realtime audio input: the service officially returns batched results
+ * only for audio of at least 60 seconds, so the first SSE event of a long file may be slow. Usage:
+ *
+ *
+ * AsrHttpStreamRecognize (--file <speech.wav> | --url <https audio url>) [--model M]
+ *
+ *
+ * Translation of the Python blueprint example 01_atomic_capabilities/audio/asr_http_stream.py.
+ */
+public final class AsrHttpStreamRecognize {
+
+ public static void main(String[] args) throws Exception {
+ Path file = null;
+ String url = null;
+ String model = "qwen-audio-3.1-asr-flash";
+ for (int i = 0; i < args.length; i++) {
+ switch (args[i]) {
+ case "--file":
+ file = Paths.get(value(args, ++i));
+ break;
+ case "--url":
+ url = value(args, ++i);
+ break;
+ case "--model":
+ model = value(args, ++i);
+ break;
+ default:
+ usage();
+ System.exit(2);
+ }
+ }
+ if ((file == null) == (url == null)) {
+ usage();
+ System.exit(2);
+ }
+
+ String audioRef;
+ if (file != null) {
+ // This sample only sends 16 kHz mono 16-bit PCM WAV and never resamples; validate before
+ // the (paid) request. The preprocessor uploads the local path to OSS.
+ AudioCommon.readWav(file, 16000);
+ audioRef = file.toString();
+ } else {
+ if (!url.startsWith("https://")) {
+ System.err.println("error: --url must be a service-reachable HTTPS audio URL");
+ System.exit(2);
+ }
+ audioRef = url;
+ }
+
+ Map asrParameters = new HashMap<>();
+ asrParameters.put("format", "wav");
+ // Integer, not a quoted string: the SDK's typed ASR channel also sends sample_rate as a number.
+ asrParameters.put("sample_rate", 16000);
+ MultimodalChatCreateParams params =
+ MultimodalChatCreateParams.builder()
+ .model(model)
+ .messages(
+ Collections.singletonList(
+ MultimodalMessage.user(Collections.singletonList(ContentPart.audio(audioRef)))))
+ // Same wire body as the Python original: no incremental_output flag; this model
+ // answers with cumulative output.text frames (each may revise an earlier partial).
+ .parameters(asrParameters)
+ .build();
+
+ try (DashScopeClient client = ExampleSupport.client();
+ ResponseStream stream =
+ client.multimodal().chat().createStreaming(params)) {
+ int count = 0;
+ String requestId = null;
+ Usage usage = null;
+ for (MultimodalChatChunk chunk : stream) {
+ if (chunk.getRequestId() != null) {
+ requestId = chunk.getRequestId();
+ }
+ if (chunk.getUsage() != null) {
+ usage = chunk.getUsage();
+ }
+ MultimodalChoice choice = chunk.firstChoice();
+ String text =
+ choice == null || choice.getMessage() == null ? "" : choice.getMessage().text();
+ if (text.isEmpty()) {
+ continue;
+ }
+ count++;
+ System.out.println("[cumulative " + count + "] " + text);
+ }
+ if (count == 0) {
+ throw new IllegalStateException("HTTP stream ended without any output text");
+ }
+ System.err.println(
+ "request_id="
+ + requestId
+ + " text_events="
+ + count
+ + (usage == null
+ ? ""
+ : " usage(input/output/total)="
+ + usage.getInputTokens()
+ + "/"
+ + usage.getOutputTokens()
+ + "/"
+ + usage.getTotalTokens()
+ + usage.getExtra()));
+ }
+ }
+
+ private static String value(String[] args, int i) {
+ if (i >= args.length) {
+ usage();
+ System.exit(2);
+ }
+ return args[i];
+ }
+
+ private static void usage() {
+ System.err.println(
+ "usage: AsrHttpStreamRecognize (--file | --url ) [--model"
+ + " M]");
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/AsrJobsTranscribe.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/AsrJobsTranscribe.java
new file mode 100644
index 00000000..3b9a1f6c
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/AsrJobsTranscribe.java
@@ -0,0 +1,214 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.audio;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.RequestOptions;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.resources.jobs.Job;
+import com.alibaba.dashscope.resources.jobs.JobResult;
+import com.alibaba.dashscope.types.audio.AsrTranscribeParams;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.Response;
+
+/**
+ * HTTP recorded-file ASR: submit HTTPS audio URLs as a batch transcription job, wait for the
+ * terminal state, then print each file's transcript. Default model {@code
+ * qwen-audio-3.1-asr-flash-filetrans} (accepts exactly one URL per task). Upload your own WAV to a
+ * service-reachable HTTPS URL first; local paths are NOT file_urls and this sample never uploads
+ * audio. Submitting is a paid operation: the task_id is printed BEFORE waiting, so an interrupted
+ * run can be resumed with {@code --task-id} (same region/workspace) instead of a new paid
+ * submission. Usage:
+ *
+ *
+ * AsrJobsTranscribe (--url <https audio url> [--url ...] | --task-id <id>) [--model M] [--wait-timeout SEC]
+ *
+ *
+ * Translation of the Python blueprint example 01_atomic_capabilities/audio/asr_file.py.
+ */
+public final class AsrJobsTranscribe {
+
+ /** Same path {@code AsrService.transcribe} submits to (its path constant is SDK-internal). */
+ private static final String TRANSCRIBE_PATH = "/services/audio/asr/transcription";
+
+ public static void main(String[] args) throws Exception {
+ List urls = new ArrayList<>();
+ String taskId = null;
+ String model = AsrTranscribeParams.DEFAULT_MODEL;
+ long waitTimeoutSec = 600;
+ for (int i = 0; i < args.length; i++) {
+ switch (args[i]) {
+ case "--url":
+ urls.add(httpsUrl(value(args, ++i)));
+ break;
+ case "--task-id":
+ taskId = value(args, ++i);
+ break;
+ case "--model":
+ model = value(args, ++i);
+ break;
+ case "--wait-timeout":
+ waitTimeoutSec = Long.parseLong(value(args, ++i));
+ break;
+ default:
+ usage();
+ System.exit(2);
+ }
+ }
+ boolean submit = !urls.isEmpty();
+ boolean resume = taskId != null && !taskId.isEmpty();
+ // Exactly one of submit (--url) / resume (--task-id).
+ if (submit == resume) {
+ usage();
+ System.exit(2);
+ }
+ if (submit && AsrTranscribeParams.DEFAULT_MODEL.equals(model) && urls.size() != 1) {
+ System.err.println("error: qwen-audio-3.1-asr-flash-filetrans requires exactly one --url");
+ System.exit(2);
+ }
+
+ try (DashScopeClient client = ExampleSupport.client()) {
+ Job job;
+ if (submit) {
+ System.err.println("Submitting a paid batch task; input URLs will not be logged.");
+ AsrTranscribeParams params =
+ AsrTranscribeParams.builder().model(model).fileUrls(urls).build();
+ // Not the blocking transcribe() sugar: the task_id must be printed BEFORE the wait so an
+ // interrupted paid batch can be resumed with --task-id.
+ ObjectMapper mapper = new ObjectMapper();
+ ObjectNode body = mapper.createObjectNode();
+ body.put("model", params.getModel());
+ ArrayNode fileUrls = body.putObject("input").putArray("file_urls");
+ params.getFileUrls().forEach(fileUrls::add);
+ Job created =
+ client.audio().asr().jobs().create(TRANSCRIBE_PATH, body, RequestOptions.NONE);
+ if (created.getTaskId() == null) {
+ throw new IllegalStateException(
+ "No task ID returned (request_id="
+ + created.getRequestId()
+ + "); check the service before submitting again");
+ }
+ System.out.println("task_id: " + created.getTaskId());
+ System.err.println(
+ "Resume without a new paid submission: --task-id " + created.getTaskId());
+ job =
+ client
+ .audio()
+ .asr()
+ .jobs()
+ .wait(created.getTaskId(), Duration.ofSeconds(waitTimeoutSec), RequestOptions.NONE);
+ } else {
+ System.out.println("task_id: " + taskId);
+ job =
+ client
+ .audio()
+ .asr()
+ .jobs()
+ .wait(taskId, Duration.ofSeconds(waitTimeoutSec), RequestOptions.NONE);
+ }
+ System.out.println(
+ "Task status: "
+ + job.getTaskStatus()
+ + " request_id="
+ + job.getRequestId()
+ + (job.getUsage() != null ? " usage=" + job.getUsage() : ""));
+ // Even a failed batch may contain usable completed files.
+ int failures = printResults(job);
+ if (!job.isSucceeded() || failures > 0) {
+ System.err.println("Batch unsuccessful; " + failures + " per-file failure(s).");
+ System.exit(1);
+ }
+ }
+ }
+
+ private static int printResults(Job job) throws Exception {
+ List results = job.getResults();
+ if (results.isEmpty()) {
+ throw new IllegalStateException("Task returned no per-file results");
+ }
+ ObjectMapper mapper = new ObjectMapper();
+ // Never reuse the SDK transport for downloads: signed URLs need no API key. OkHttp follows
+ // redirects by default, matching the python.org/requests behavior of the blueprint.
+ OkHttpClient downloader =
+ new OkHttpClient.Builder().connectTimeout(Duration.ofSeconds(30)).build();
+ int failures = 0;
+ int index = 0;
+ for (JobResult result : results) {
+ index++;
+ try {
+ Object status = result.getExtra().get("subtask_status");
+ if (!"SUCCEEDED".equals(status)) {
+ throw new IllegalStateException("subtask did not succeed");
+ }
+ String url = httpsUrl(result.getTranscriptionUrl());
+ try (Response response =
+ downloader.newCall(new Request.Builder().url(url).get().build()).execute()) {
+ if (!response.isSuccessful()) {
+ throw new IllegalStateException("download failed");
+ }
+ System.out.println("File " + index + ": " + url);
+ System.out.println(
+ transcriptText(
+ mapper.readTree(response.body() == null ? "" : response.body().string())));
+ }
+ } catch (Exception e) {
+ failures++;
+ // Exception messages can contain presigned URLs; keep them out of logs.
+ System.err.println("File " + index + ": FAILED (" + e.getClass().getSimpleName() + ")");
+ }
+ }
+ return failures;
+ }
+
+ private static String transcriptText(JsonNode document) {
+ JsonNode transcripts = document == null ? null : document.get("transcripts");
+ if (transcripts == null || !transcripts.isArray()) {
+ throw new IllegalArgumentException("transcription JSON has no transcripts list");
+ }
+ List texts = new ArrayList<>();
+ for (JsonNode transcript : transcripts) {
+ JsonNode text = transcript.get("text");
+ if (text != null && text.isTextual()) {
+ texts.add(text.asText());
+ continue;
+ }
+ StringBuilder joined = new StringBuilder();
+ for (JsonNode sentence : transcript.path("sentences")) {
+ joined.append(sentence.path("text").asText());
+ }
+ texts.add(joined.toString());
+ }
+ return String.join("\n", texts);
+ }
+
+ private static String httpsUrl(String value) {
+ if (value == null || !value.startsWith("https://") || value.contains("#")) {
+ throw new IllegalArgumentException(
+ "Use an HTTPS audio URL without userinfo or fragments, not a local path. "
+ + "Upload your own WAV to a service-reachable URL yourself; this sample never "
+ + "uploads files.");
+ }
+ return value;
+ }
+
+ private static String value(String[] args, int i) {
+ if (i >= args.length) {
+ usage();
+ System.exit(2);
+ }
+ return args[i];
+ }
+
+ private static void usage() {
+ System.err.println(
+ "usage: AsrJobsTranscribe (--url [--url ...] | --task-id )"
+ + " [--model M] [--wait-timeout SEC]");
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/AsrMicrophoneRecognize.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/AsrMicrophoneRecognize.java
new file mode 100644
index 00000000..92bcd5f2
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/AsrMicrophoneRecognize.java
@@ -0,0 +1,153 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.audio;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.resources.audio.RecognitionSession;
+import com.alibaba.dashscope.types.audio.AsrRecognizeParams;
+import com.alibaba.dashscope.types.audio.AsrResult;
+import java.io.ByteArrayOutputStream;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.time.Duration;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import javax.sound.sampled.TargetDataLine;
+
+/**
+ * Capture the system microphone and stream PCM to streaming ASR in the caller thread. Translation
+ * of the Python blueprint example 01_atomic_capabilities/audio/asr_microphone.py.
+ *
+ * Capture uses blocking 100 ms mono 16-bit 16 kHz reads; a receiver thread prints partial
+ * sentences to stderr and final sentences to stdout. {@code --seconds N} bounds the capture window
+ * (default 5); {@code --recording take.wav} additionally saves the captured PCM.
+ *
+ *
+ * mvn -q -f examples/pom.xml exec:java -Dexec.mainClass=com.alibaba.dashscope.examples.atomic.audio.AsrMicrophoneRecognize -Dexec.args="--seconds 10 --recording take.wav"
+ *
+ */
+public final class AsrMicrophoneRecognize {
+
+ public static void main(String[] args) throws Exception {
+ double seconds = 5.0;
+ String model = "qwen-audio-3.1-asr-flash-streaming";
+ Path recording = null;
+ for (int i = 0; i < args.length; i++) {
+ switch (args[i]) {
+ case "--seconds":
+ seconds = Double.parseDouble(args[++i]);
+ break;
+ case "--model":
+ model = args[++i];
+ break;
+ case "--recording":
+ recording = Paths.get(args[++i]);
+ break;
+ default:
+ System.err.println("unknown argument: " + args[i]);
+ usage();
+ }
+ }
+ if (seconds <= 0) {
+ System.err.println("error: --seconds must be positive");
+ System.exit(2);
+ }
+ int sampleRate = 16000;
+ TargetDataLine line = AudioCommon.microphone(sampleRate);
+
+ try (DashScopeClient client = ExampleSupport.client()) {
+ RecognitionSession session =
+ client
+ .audio()
+ .asr()
+ .recognize(
+ AsrRecognizeParams.builder()
+ .model(model)
+ .format("pcm")
+ .sampleRate(sampleRate)
+ .build());
+ ExecutorService receiverPool = Executors.newSingleThreadExecutor();
+ ByteArrayOutputStream captured = new ByteArrayOutputStream();
+ try {
+ session.start();
+ // Receive on a worker thread while the caller thread captures and sends mic frames.
+ Future> receiver =
+ receiverPool.submit(
+ () -> {
+ for (AsrResult result : session.results()) {
+ AsrResult.Sentence sentence = result.getSentence();
+ if (sentence == null || sentence.getText() == null) {
+ continue;
+ }
+ if (Boolean.TRUE.equals(sentence.getSentenceEnd())) {
+ System.out.println(sentence.getText());
+ } else {
+ System.err.println("[partial] " + sentence.getText());
+ }
+ }
+ });
+ System.err.println(
+ "Recording up to " + seconds + "s; Ctrl+C stops capture and drains ASR.");
+ long remaining = Math.round(seconds * sampleRate);
+ while (remaining > 0) {
+ checkReceiver(receiver);
+ int count = (int) Math.min(sampleRate / 10, remaining);
+ byte[] frame = new byte[count * 2];
+ int offset = 0;
+ while (offset < frame.length) {
+ int n = line.read(frame, offset, frame.length - offset);
+ if (n <= 0) {
+ break;
+ }
+ offset += n;
+ }
+ if (offset != frame.length) {
+ throw new RuntimeException("Microphone returned an incomplete PCM frame.");
+ }
+ if (recording != null) {
+ captured.write(frame, 0, frame.length);
+ }
+ session.sendAudioFrame(frame);
+ remaining -= count;
+ }
+ session.stop();
+ receiver.get();
+ } finally {
+ session.close();
+ receiverPool.shutdown();
+ line.stop();
+ line.close();
+ }
+ System.err.println(
+ "request_id="
+ + session.getRequestId()
+ + " first_package_delay_ms="
+ + millis(session.getFirstPackageDelay())
+ + " usage="
+ + session.getUsage());
+ if (recording != null) {
+ AudioCommon.writeWav(recording, captured.toByteArray(), sampleRate);
+ System.err.println("recording saved: " + recording.toAbsolutePath());
+ }
+ }
+ }
+
+ /** Surface a receiver failure as soon as the capture loop notices it exited early. */
+ private static void checkReceiver(Future> receiver) throws Exception {
+ if (receiver.isDone()) {
+ receiver.get();
+ throw new RuntimeException("Capture not finished but the receiver thread exited.");
+ }
+ }
+
+ private static String millis(Duration duration) {
+ return duration == null ? "null" : Long.toString(duration.toMillis());
+ }
+
+ private static void usage() {
+ System.err.println(
+ "usage: AsrMicrophoneRecognize [--seconds 5] [--model m] [--recording ]");
+ System.exit(2);
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/AsrWebsocketRecognize.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/AsrWebsocketRecognize.java
new file mode 100644
index 00000000..0918e966
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/AsrWebsocketRecognize.java
@@ -0,0 +1,94 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.audio;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.resources.audio.AudioPacer;
+import com.alibaba.dashscope.resources.audio.RecognitionSession;
+import com.alibaba.dashscope.types.audio.AsrRecognizeParams;
+import com.alibaba.dashscope.types.audio.AsrResult;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.time.Duration;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+/**
+ * WebSocket duplex ASR (translation of the Python blueprint's {@code asr_websocket.py}): send PCM
+ * from a local WAV while receiving sentences. Default model {@code
+ * qwen-audio-3.1-asr-flash-streaming}; input must be mono 16-bit 16 kHz PCM WAV (no resampling).
+ * Usage:
+ *
+ *
+ * mvn -q -f examples/pom.xml exec:java -Dexec.mainClass=com.alibaba.dashscope.examples.atomic.audio.AsrWebsocketRecognize -Dexec.args="speech.wav"
+ *
+ */
+public final class AsrWebsocketRecognize {
+
+ public static void main(String[] args) throws Exception {
+ if (args.length < 1) {
+ System.err.println("usage: AsrWebsocketRecognize [model]");
+ System.exit(2);
+ }
+ Path wav = Paths.get(args[0]);
+ String model = args.length > 1 ? args[1] : "qwen-audio-3.1-asr-flash-streaming";
+
+ AudioCommon.PcmAudio audio = AudioCommon.readWav(wav, 16000);
+ int chunkBytes = AudioPacer.bytesPer100ms(audio.sampleRate);
+
+ try (DashScopeClient client = ExampleSupport.client()) {
+ RecognitionSession session =
+ client
+ .audio()
+ .asr()
+ .recognize(
+ AsrRecognizeParams.builder()
+ .model(model)
+ .format("pcm")
+ .sampleRate(audio.sampleRate)
+ .build());
+ ExecutorService receiverPool = Executors.newSingleThreadExecutor();
+ try {
+ session.start();
+ // Receive on a worker thread while the caller thread paces uplink frames.
+ Future> receiver =
+ receiverPool.submit(
+ () -> {
+ for (AsrResult result : session.results()) {
+ AsrResult.Sentence sentence = result.getSentence();
+ if (sentence == null || sentence.getText() == null) {
+ continue;
+ }
+ if (Boolean.TRUE.equals(sentence.getSentenceEnd())) {
+ System.out.println(sentence.getText());
+ } else {
+ System.err.println("[partial] " + sentence.getText());
+ }
+ }
+ });
+ long start = System.nanoTime();
+ int index = 0;
+ for (byte[] frame : AudioPacer.pcmChunks(audio.pcm, chunkBytes)) {
+ AudioPacer.pace(start, index++);
+ session.sendAudioFrame(frame);
+ }
+ session.stop();
+ receiver.get();
+ } finally {
+ session.close();
+ receiverPool.shutdown();
+ }
+ // getFirstPackageDelay() stays null when no sentence was ever recognized (silence or
+ // speech-free audio), so it must not be dereferenced unconditionally.
+ Duration firstDelay = session.getFirstPackageDelay();
+ System.err.println(
+ "request_id="
+ + session.getRequestId()
+ + " first_package_delay_ms="
+ + (firstDelay == null ? "null" : firstDelay.toMillis())
+ + " usage="
+ + session.getUsage());
+ }
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/AudioCommon.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/AudioCommon.java
new file mode 100644
index 00000000..5aa4d331
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/AudioCommon.java
@@ -0,0 +1,110 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.audio;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import javax.sound.sampled.AudioFileFormat;
+import javax.sound.sampled.AudioFormat;
+import javax.sound.sampled.AudioInputStream;
+import javax.sound.sampled.AudioSystem;
+import javax.sound.sampled.Clip;
+import javax.sound.sampled.LineUnavailableException;
+import javax.sound.sampled.TargetDataLine;
+
+/**
+ * Local audio helpers for the examples (translation of the Python blueprint's {@code _common.py}):
+ * WAV container read/write, microphone capture and playback. Pure JDK ({@code javax.sound}), no
+ * cloud calls.
+ */
+public final class AudioCommon {
+
+ /** Decoded 16-bit mono PCM plus its sample rate. */
+ public static final class PcmAudio {
+ public final byte[] pcm;
+ public final int sampleRate;
+
+ PcmAudio(byte[] pcm, int sampleRate) {
+ this.pcm = pcm;
+ this.sampleRate = sampleRate;
+ }
+ }
+
+ private AudioCommon() {}
+
+ /**
+ * Read a local WAV as raw PCM. Requires mono, 16-bit PCM at one of {@code allowedRates}; no
+ * resampling is performed (convert with ffmpeg first if needed).
+ */
+ public static PcmAudio readWav(Path path, int... allowedRates) throws Exception {
+ AudioFormat format;
+ byte[] pcm;
+ try (AudioInputStream in = AudioSystem.getAudioInputStream(path.toFile())) {
+ format = in.getFormat();
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ byte[] buf = new byte[8192];
+ int n;
+ while ((n = in.read(buf)) >= 0) {
+ out.write(buf, 0, n);
+ }
+ pcm = out.toByteArray();
+ }
+ if (format.getChannels() != 1
+ || format.getSampleSizeInBits() != 16
+ || format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
+ throw new IllegalArgumentException(
+ "need mono 16-bit PCM WAV; actual: " + format + ". Convert with ffmpeg first.");
+ }
+ int rate = (int) format.getSampleRate();
+ for (int allowed : allowedRates) {
+ if (rate == allowed) {
+ return new PcmAudio(pcm, rate);
+ }
+ }
+ throw new IllegalArgumentException(
+ "need sample rate in " + java.util.Arrays.toString(allowedRates) + "; actual: " + rate);
+ }
+
+ /** Write raw 16-bit mono PCM into a new WAV file; never overwrites an existing file. */
+ public static void writeWav(Path path, byte[] pcm, int sampleRate) throws IOException {
+ if (!path.toString().toLowerCase().endsWith(".wav")) {
+ throw new IllegalArgumentException("PCM output must use the .wav extension");
+ }
+ if (Files.exists(path)) {
+ throw new IllegalArgumentException("output already exists: " + path);
+ }
+ AudioFormat format = new AudioFormat(sampleRate, 16, 1, true, false);
+ try (AudioInputStream in =
+ new AudioInputStream(new ByteArrayInputStream(pcm), format, pcm.length / 2)) {
+ AudioSystem.write(in, AudioFileFormat.Type.WAVE, path.toFile());
+ }
+ }
+
+ /** Play a WAV synchronously; when no audio line exists (CI/headless), print a hint and skip. */
+ public static void play(Path path) {
+ try (AudioInputStream in = AudioSystem.getAudioInputStream(path.toFile())) {
+ Clip clip = AudioSystem.getClip();
+ clip.open(in);
+ clip.start();
+ while (clip.isRunning()) {
+ Thread.sleep(50);
+ }
+ clip.close();
+ } catch (LineUnavailableException | IOException e) {
+ System.err.println("playback unavailable (" + e.getMessage() + "); file kept: " + path);
+ } catch (Exception e) {
+ throw new RuntimeException("playback failed: " + path, e);
+ }
+ }
+
+ /** Open the default microphone at the given rate as 16-bit mono PCM. */
+ public static TargetDataLine microphone(int sampleRate) throws LineUnavailableException {
+ AudioFormat format = new AudioFormat(sampleRate, 16, 1, true, false);
+ TargetDataLine line = AudioSystem.getTargetDataLine(format);
+ line.open(format, sampleRate / 10 * 2);
+ line.start();
+ return line;
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/AudioConnectionReuse.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/AudioConnectionReuse.java
new file mode 100644
index 00000000..21de7ce1
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/AudioConnectionReuse.java
@@ -0,0 +1,270 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.audio;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.resources.audio.AudioPacer;
+import com.alibaba.dashscope.resources.audio.RecognitionSession;
+import com.alibaba.dashscope.resources.audio.SynthesisSession;
+import com.alibaba.dashscope.transport.ws.WsConnection;
+import com.alibaba.dashscope.types.audio.AsrRecognizeParams;
+import com.alibaba.dashscope.types.audio.AsrResult;
+import com.alibaba.dashscope.types.audio.TtsConnectParams;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardOpenOption;
+import java.time.Duration;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+/**
+ * Run five sequential ASR or TTS tasks on one shared WebSocket connection. Translation of the
+ * Python blueprint example 01_atomic_capabilities/audio/connection_reuse.py.
+ *
+ * ASR and TTS run separately (subcommand {@code asr}/{@code tts}), each on its own connection;
+ * no automatic reconnect. Per-round summary lines are printed as JSON with the request id.
+ *
+ *
+ * mvn -q -f examples/pom.xml exec:java -Dexec.mainClass=com.alibaba.dashscope.examples.atomic.audio.AudioConnectionReuse -Dexec.args="asr speech.wav --output-dir reuse-asr"
+ *
+ */
+public final class AudioConnectionReuse {
+ private static final int RUNS = 5;
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ public static void main(String[] args) throws Exception {
+ if (args.length < 1 || (!args[0].equals("asr") && !args[0].equals("tts"))) {
+ usage();
+ }
+ String kind = args[0];
+ String model =
+ "asr".equals(kind) ? "qwen-audio-3.1-asr-flash-streaming" : "qwen-audio-3.1-tts-flash";
+ String voice = "longanhuan_v3.1";
+ String text = "你好,这是连接复用测试。";
+ Path wav = null;
+ Path outputDir = null;
+ for (int i = 1; i < args.length; i++) {
+ switch (args[i]) {
+ case "--model":
+ model = args[++i];
+ break;
+ case "--voice":
+ voice = args[++i];
+ break;
+ case "--text":
+ text = args[++i];
+ break;
+ case "--output-dir":
+ outputDir = Paths.get(args[++i]);
+ break;
+ default:
+ if ("asr".equals(kind) && wav == null && !args[i].startsWith("--")) {
+ wav = Paths.get(args[i]);
+ } else {
+ System.err.println("unknown argument: " + args[i]);
+ usage();
+ }
+ }
+ }
+ if (outputDir == null || ("asr".equals(kind) && wav == null)) {
+ usage();
+ }
+ if ("tts".equals(kind) && text.trim().isEmpty()) {
+ System.err.println("error: --text must not be empty");
+ System.exit(2);
+ }
+ // New output directory; never overwrite an existing one (Python mkdir() parity).
+ Files.createDirectory(outputDir);
+
+ AudioCommon.PcmAudio audio = "asr".equals(kind) ? AudioCommon.readWav(wav, 16000) : null;
+ try (DashScopeClient client = ExampleSupport.client();
+ WsConnection connection = client.wsConnection()) {
+ for (int index = 1; index <= RUNS; index++) {
+ Map result =
+ "asr".equals(kind)
+ ? recognizeOne(client, connection, audio, model, outputDir, index)
+ : synthesizeOne(client, connection, model, voice, text, outputDir, index);
+ result.put("index", index);
+ result.put("connection_open_after_task", true);
+ System.out.println(MAPPER.writeValueAsString(result));
+ }
+ }
+ System.out.println(
+ "Completed " + RUNS + " independent tasks on 1 connection: " + outputDir.toAbsolutePath());
+ }
+
+ private static Map recognizeOne(
+ DashScopeClient client,
+ WsConnection connection,
+ AudioCommon.PcmAudio audio,
+ String model,
+ Path outputDir,
+ int index)
+ throws Exception {
+ RecognitionSession session =
+ client
+ .audio()
+ .asr()
+ .recognize(
+ AsrRecognizeParams.builder().model(model).format("pcm").sampleRate(16000).build(),
+ connection);
+ ExecutorService pool = Executors.newSingleThreadExecutor();
+ StringBuilder transcript = new StringBuilder();
+ try {
+ session.start();
+ System.out.println("ASR " + index + "/" + RUNS + ": task_id=" + session.getTaskId());
+ Future> receiver =
+ pool.submit(
+ () -> {
+ for (AsrResult result : session.results()) {
+ AsrResult.Sentence sentence = result.getSentence();
+ if (sentence == null || sentence.getText() == null) {
+ continue;
+ }
+ if (Boolean.TRUE.equals(sentence.getSentenceEnd())) {
+ synchronized (transcript) {
+ transcript.append(sentence.getText()).append('\n');
+ }
+ } else {
+ System.err.println("[partial] " + sentence.getText());
+ }
+ }
+ });
+ long start = System.nanoTime();
+ int chunkIndex = 0;
+ int chunkBytes = AudioPacer.bytesPer100ms(16000);
+ for (byte[] frame : AudioPacer.pcmChunks(audio.pcm, chunkBytes)) {
+ AudioPacer.pace(start, chunkIndex++);
+ session.sendAudioFrame(frame);
+ }
+ session.stop();
+ receiver.get();
+ Map result =
+ completedTask(
+ session.getTaskId(),
+ session.getRequestId(),
+ session.getLastResponse(),
+ session.getFirstPackageDelay(),
+ session.getUsage());
+ result.put("last_package_delay_ms", millis(session.getLastPackageDelay()));
+ String text;
+ synchronized (transcript) {
+ text = transcript.toString().trim();
+ }
+ if (text.isEmpty()) {
+ throw new RuntimeException("No final transcript; use a WAV containing clear speech");
+ }
+ String name = String.format("asr-%02d.txt", index);
+ Files.write(
+ outputDir.resolve(name),
+ (text + "\n").getBytes(StandardCharsets.UTF_8),
+ StandardOpenOption.CREATE_NEW);
+ result.put("transcript", name);
+ result.put("text", text);
+ return result;
+ } finally {
+ session.close();
+ pool.shutdown();
+ }
+ }
+
+ private static Map synthesizeOne(
+ DashScopeClient client,
+ WsConnection connection,
+ String model,
+ String voice,
+ String text,
+ Path outputDir,
+ int index)
+ throws Exception {
+ String roundText = "第" + index + "次。" + text;
+ SynthesisSession session =
+ client
+ .audio()
+ .tts()
+ .connect(
+ TtsConnectParams.builder()
+ .model(model)
+ .voice(voice)
+ .format("pcm")
+ .sampleRate(24000)
+ .build(),
+ connection);
+ ExecutorService pool = Executors.newSingleThreadExecutor();
+ ByteArrayOutputStream pcm = new ByteArrayOutputStream();
+ try {
+ session.start();
+ System.out.println("TTS " + index + "/" + RUNS + ": task_id=" + session.getTaskId());
+ Future receiver =
+ pool.submit(
+ () -> {
+ long received = 0;
+ for (byte[] chunk : session.audioChunks()) {
+ pcm.write(chunk, 0, chunk.length);
+ received += chunk.length;
+ }
+ return received;
+ });
+ session.sendText(roundText);
+ session.stop();
+ long size = receiver.get();
+ Map result =
+ completedTask(
+ session.getTaskId(),
+ session.getRequestId(),
+ session.getLastResponse(),
+ session.getFirstPackageDelay(),
+ session.getUsage());
+ if (size == 0 || size % 2 != 0) {
+ throw new RuntimeException("Returned PCM audio is empty or incomplete (" + size + " bytes)");
+ }
+ String name = String.format("tts-%02d.wav", index);
+ AudioCommon.writeWav(outputDir.resolve(name), pcm.toByteArray(), 24000);
+ result.put("audio", name);
+ result.put("input_text", roundText);
+ result.put("audio_bytes", size);
+ result.put("audio_seconds", size / 48000.0);
+ return result;
+ } finally {
+ session.close();
+ pool.shutdown();
+ }
+ }
+
+ /** Python completed_task(): the last frame must be this task's task-finished. */
+ private static Map completedTask(
+ String taskId, String requestId, JsonNode lastResponse, Duration firstDelay, Object usage) {
+ JsonNode header = lastResponse == null ? null : lastResponse.path("header");
+ String event = header == null ? null : header.path("event").asText(null);
+ if (!"task-finished".equals(event) || !taskId.equals(header.path("task_id").asText(null))) {
+ throw new RuntimeException("No matching task-finished received; stop reusing the connection");
+ }
+ Map result = new LinkedHashMap<>();
+ result.put("task_id", taskId);
+ result.put("request_id", requestId);
+ result.put("final_event", event);
+ result.put("first_package_delay_ms", millis(firstDelay));
+ result.put("usage", usage);
+ return result;
+ }
+
+ private static String millis(Duration duration) {
+ return duration == null ? "null" : Long.toString(duration.toMillis());
+ }
+
+ private static void usage() {
+ System.err.println(
+ "usage: AudioConnectionReuse asr --output-dir [--model m]\n"
+ + " AudioConnectionReuse tts --output-dir [--model m] [--voice v]"
+ + " [--text t]");
+ System.exit(2);
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/RealtimeOmniDialog.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/RealtimeOmniDialog.java
new file mode 100644
index 00000000..293b3a21
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/RealtimeOmniDialog.java
@@ -0,0 +1,278 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.audio;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.resources.audio.AudioPacer;
+import com.alibaba.dashscope.resources.audio.RealtimeSession;
+import com.alibaba.dashscope.types.audio.RealtimeParams;
+import com.alibaba.dashscope.types.audio.UpdateSessionParams;
+import com.fasterxml.jackson.databind.JsonNode;
+import java.io.ByteArrayOutputStream;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import javax.sound.sampled.TargetDataLine;
+
+/**
+ * One Omni 3.8 spoken turn from a WAV file or the microphone, saved as a 24 kHz WAV reply.
+ * Translation of the Python blueprint example 01_atomic_capabilities/audio/realtime_omni.py.
+ *
+ * Manual end-of-turn (commit + createResponse), no server VAD; default voice {@code
+ * longanlingxin}. WAV input must be mono 16-bit 16 kHz, 0.1–20 s.
+ *
+ *
+ * mvn -q -f examples/pom.xml exec:java -Dexec.mainClass=com.alibaba.dashscope.examples.atomic.audio.RealtimeOmniDialog -Dexec.args="--wav input.wav --output reply.wav"
+ *
+ */
+public final class RealtimeOmniDialog {
+ private static final String MODEL = "qwen3.8-omni-flash-realtime";
+
+ public static void main(String[] args) throws Exception {
+ Path wav = null;
+ Path output = null;
+ boolean microphone = false;
+ boolean noPlay = false;
+ double seconds = 10.0;
+ String voice = "longanlingxin";
+ String instructions = "请用简洁自然的中文回答。";
+ for (int i = 0; i < args.length; i++) {
+ switch (args[i]) {
+ case "--wav":
+ wav = Paths.get(args[++i]);
+ break;
+ case "--microphone":
+ microphone = true;
+ break;
+ case "--seconds":
+ seconds = Double.parseDouble(args[++i]);
+ break;
+ case "--voice":
+ voice = args[++i];
+ break;
+ case "--instructions":
+ instructions = args[++i];
+ break;
+ case "--output":
+ output = Paths.get(args[++i]);
+ break;
+ case "--no-play":
+ noPlay = true;
+ break;
+ default:
+ System.err.println("unknown argument: " + args[i]);
+ usage();
+ }
+ }
+ if (output == null || (wav == null && !microphone) || (wav != null && microphone)) {
+ usage();
+ }
+ if (microphone && (seconds < 0.1 || seconds > 20)) {
+ System.err.println("error: --seconds must be between 0.1 and 20");
+ System.exit(2);
+ }
+ AudioCommon.PcmAudio audio = null;
+ if (wav != null) {
+ audio = AudioCommon.readWav(wav, 16000);
+ double duration = audio.pcm.length / 2.0 / 16000;
+ if (duration < 0.1 || duration > 20) {
+ System.err.println("error: this example accepts single-turn WAV input of 0.1 to 20 seconds");
+ System.exit(2);
+ }
+ }
+
+ ByteArrayOutputStream pcm = new ByteArrayOutputStream();
+ int size;
+ try (DashScopeClient client = ExampleSupport.client()) {
+ RealtimeSession session =
+ client.audio().realtime().connect(RealtimeParams.builder().model(MODEL).build());
+ ExecutorService pool = Executors.newSingleThreadExecutor();
+ try {
+ session.connect();
+ session.updateSession(
+ UpdateSessionParams.builder()
+ .modalities(Arrays.asList("text", "audio"))
+ .voice(voice)
+ .inputAudio(UpdateSessionParams.AudioFormat.of("pcm", 16000))
+ .outputAudio(UpdateSessionParams.AudioFormat.of("pcm", 24000))
+ .enableInputAudioTranscription(false)
+ .enableTurnDetection(false)
+ .parameters(Collections.singletonMap("instructions", instructions))
+ .build());
+ // events() is a single-use stream, so ONE receiver thread consumes it for the whole
+ // session: it releases sessionUpdated once the server acknowledges the session update
+ // (gating the input below) and finishes at response.done.
+ CountDownLatch sessionUpdated = new CountDownLatch(1);
+ Future receiver =
+ pool.submit(
+ () -> {
+ try {
+ return receiveReply(session, pcm, sessionUpdated);
+ } finally {
+ // Also release a failed receiver so the sender notices via checkReceiver.
+ sessionUpdated.countDown();
+ }
+ });
+ if (!sessionUpdated.await(30, TimeUnit.SECONDS)) {
+ throw new RuntimeException("No session.updated event received within 30 seconds");
+ }
+ if (audio != null) {
+ sendWav(session, receiver, audio);
+ } else {
+ sendMicrophone(session, receiver, seconds);
+ }
+ session.commit();
+ session.createResponse();
+ size = receiver.get();
+ } finally {
+ session.close();
+ pool.shutdown();
+ }
+ }
+ if (size == 0 || size % 2 != 0) {
+ throw new RuntimeException("Response audio is empty or incomplete (" + size + " bytes)");
+ }
+ AudioCommon.writeWav(output, pcm.toByteArray(), 24000);
+ System.out.println(
+ "Saved "
+ + output.toAbsolutePath()
+ + " ("
+ + String.format("%.2f", size / 48000.0)
+ + " seconds)");
+ if (!noPlay) {
+ AudioCommon.play(output);
+ }
+ }
+
+ /**
+ * Single-pass consumer of the single-use event stream: audio deltas go to {@code output}, text
+ * deltas print inline, {@code sessionUpdated} counts down at {@code session.updated}, and the
+ * decoded audio byte count is returned at {@code response.done}.
+ */
+ static int receiveReply(
+ RealtimeSession session, ByteArrayOutputStream output, CountDownLatch sessionUpdated) {
+ int size = 0;
+ for (JsonNode event : session.events()) {
+ String kind = event.path("type").asText();
+ switch (kind) {
+ case "response.audio.delta":
+ if (output != null) {
+ byte[] audio = Base64.getDecoder().decode(event.path("delta").asText());
+ output.write(audio, 0, audio.length);
+ size += audio.length;
+ }
+ break;
+ case "response.text.delta":
+ case "response.audio_transcript.delta":
+ System.out.print(event.path("delta").asText());
+ System.out.flush();
+ break;
+ case "response.text.done":
+ case "response.audio_transcript.done":
+ System.out.println();
+ System.out.println(
+ "Full response: " + event.path("text").asText(event.path("transcript").asText("")));
+ break;
+ case "conversation.item.input_audio_transcription.completed":
+ System.out.println();
+ System.out.println("Input transcript: " + event.path("transcript").asText(""));
+ break;
+ case "response.done":
+ JsonNode response = event.path("response");
+ String status = response.path("status").asText(null);
+ if (!"completed".equals(status)) {
+ throw new RuntimeException("Response did not complete normally: " + status);
+ }
+ System.out.println();
+ System.out.println("response_id: " + response.path("id").asText(null));
+ System.out.println("usage: " + response.path("usage"));
+ break;
+ default:
+ break;
+ }
+ if (kind.equals("session.updated")) {
+ sessionUpdated.countDown();
+ } else if (kind.equals("response.done")) {
+ return size;
+ }
+ }
+ throw new RuntimeException("Connection closed without response.done");
+ }
+
+ /** Pace a 16 kHz WAV into the input buffer, one 100 ms chunk at a time. */
+ static void sendWav(RealtimeSession session, Future> receiver, AudioCommon.PcmAudio audio)
+ throws Exception {
+ int chunkBytes = AudioPacer.bytesPer100ms(16000);
+ long start = System.nanoTime();
+ int index = 0;
+ int sent = 0;
+ for (byte[] frame : AudioPacer.pcmChunks(audio.pcm, chunkBytes)) {
+ checkReceiver(receiver);
+ AudioPacer.pace(start, index++);
+ session.appendAudio(frame);
+ sent += frame.length;
+ }
+ if (sent < 3200) {
+ throw new IllegalArgumentException("This turn requires at least 0.1 seconds of audio");
+ }
+ }
+
+ /** Capture the microphone for {@code seconds} and append each 100 ms block. */
+ static void sendMicrophone(RealtimeSession session, Future> receiver, double seconds)
+ throws Exception {
+ TargetDataLine line = AudioCommon.microphone(16000);
+ int sent = 0;
+ try {
+ System.out.println(
+ "Recording for " + seconds + " seconds; press Ctrl+C to end this turn early.");
+ long remaining = Math.round(seconds * 16000);
+ while (remaining > 0) {
+ checkReceiver(receiver);
+ int count = (int) Math.min(1600, remaining);
+ byte[] frame = new byte[count * 2];
+ int offset = 0;
+ while (offset < frame.length) {
+ int n = line.read(frame, offset, frame.length - offset);
+ if (n <= 0) {
+ break;
+ }
+ offset += n;
+ }
+ if (offset != frame.length) {
+ throw new RuntimeException("Microphone returned an incomplete PCM frame");
+ }
+ session.appendAudio(frame);
+ sent += frame.length;
+ remaining -= count;
+ }
+ } finally {
+ line.stop();
+ line.close();
+ }
+ if (sent < 3200) {
+ throw new IllegalArgumentException("This turn requires at least 0.1 seconds of audio");
+ }
+ }
+
+ /** Surface a receiver failure as soon as the send side notices it exited early. */
+ static void checkReceiver(Future> receiver) throws Exception {
+ if (receiver.isDone()) {
+ receiver.get();
+ throw new RuntimeException("Receiver thread exited before input ended");
+ }
+ }
+
+ private static void usage() {
+ System.err.println(
+ "usage: RealtimeOmniDialog (--wav | --microphone [--seconds 10]) --output"
+ + " [--voice v] [--instructions s] [--no-play]");
+ System.exit(2);
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/RealtimeQwenAudioDialog.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/RealtimeQwenAudioDialog.java
new file mode 100644
index 00000000..db9f41ef
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/RealtimeQwenAudioDialog.java
@@ -0,0 +1,155 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.audio;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.resources.audio.RealtimeSession;
+import com.alibaba.dashscope.types.audio.RealtimeParams;
+import com.alibaba.dashscope.types.audio.UpdateSessionParams;
+import java.io.ByteArrayOutputStream;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * One Qwen-Audio realtime spoken turn from a WAV file or the microphone, saved as a 24 kHz WAV
+ * reply. Translation of the Python blueprint example
+ * 01_atomic_capabilities/audio/realtime_qwen_audio.py.
+ *
+ * Fixed model {@code qwen-audio-3.0-realtime-plus}, default voice {@code longanqian}; manual
+ * end-of-turn (commit + createResponse). Unlike the omni example this dialect uses the legacy flat
+ * {@code input_audio_format}/{@code output_audio_format} session fields. WAV input must be mono
+ * 16-bit 16 kHz, 0.1–20 s.
+ *
+ *
+ * mvn -q -f examples/pom.xml exec:java -Dexec.mainClass=com.alibaba.dashscope.examples.atomic.audio.RealtimeQwenAudioDialog -Dexec.args="--wav input.wav --output reply.wav"
+ *
+ */
+public final class RealtimeQwenAudioDialog {
+ private static final String MODEL = "qwen-audio-3.0-realtime-plus";
+
+ public static void main(String[] args) throws Exception {
+ Path wav = null;
+ Path output = null;
+ boolean microphone = false;
+ boolean noPlay = false;
+ double seconds = 10.0;
+ String voice = "longanqian";
+ String instructions = "请用简洁自然的中文回答。";
+ for (int i = 0; i < args.length; i++) {
+ switch (args[i]) {
+ case "--wav":
+ wav = Paths.get(args[++i]);
+ break;
+ case "--microphone":
+ microphone = true;
+ break;
+ case "--seconds":
+ seconds = Double.parseDouble(args[++i]);
+ break;
+ case "--voice":
+ voice = args[++i];
+ break;
+ case "--instructions":
+ instructions = args[++i];
+ break;
+ case "--output":
+ output = Paths.get(args[++i]);
+ break;
+ case "--no-play":
+ noPlay = true;
+ break;
+ default:
+ System.err.println("unknown argument: " + args[i]);
+ usage();
+ }
+ }
+ if (output == null || (wav == null && !microphone) || (wav != null && microphone)) {
+ usage();
+ }
+ if (microphone && (seconds < 0.1 || seconds > 20)) {
+ System.err.println("error: --seconds must be between 0.1 and 20");
+ System.exit(2);
+ }
+ AudioCommon.PcmAudio audio = null;
+ if (wav != null) {
+ audio = AudioCommon.readWav(wav, 16000);
+ double duration = audio.pcm.length / 2.0 / 16000;
+ if (duration < 0.1 || duration > 20) {
+ System.err.println("error: this example accepts single-turn WAV input of 0.1 to 20 seconds");
+ System.exit(2);
+ }
+ }
+
+ ByteArrayOutputStream pcm = new ByteArrayOutputStream();
+ int size;
+ try (DashScopeClient client = ExampleSupport.client()) {
+ RealtimeSession session =
+ client.audio().realtime().connect(RealtimeParams.builder().model(MODEL).build());
+ ExecutorService pool = Executors.newSingleThreadExecutor();
+ try {
+ session.connect();
+ session.updateSession(
+ UpdateSessionParams.builder()
+ .modalities(Arrays.asList("text", "audio"))
+ .voice(voice)
+ .inputAudioFormat("pcm")
+ .outputAudioFormat("pcm")
+ .enableTurnDetection(false)
+ .parameters(Collections.singletonMap("instructions", instructions))
+ .build());
+ // One receiver thread consumes the single-use event stream (see RealtimeOmniDialog).
+ CountDownLatch sessionUpdated = new CountDownLatch(1);
+ Future receiver =
+ pool.submit(
+ () -> {
+ try {
+ return RealtimeOmniDialog.receiveReply(session, pcm, sessionUpdated);
+ } finally {
+ sessionUpdated.countDown();
+ }
+ });
+ if (!sessionUpdated.await(30, TimeUnit.SECONDS)) {
+ throw new RuntimeException("No session.updated event received within 30 seconds");
+ }
+ if (audio != null) {
+ RealtimeOmniDialog.sendWav(session, receiver, audio);
+ } else {
+ RealtimeOmniDialog.sendMicrophone(session, receiver, seconds);
+ }
+ session.commit();
+ session.createResponse();
+ size = receiver.get();
+ } finally {
+ session.close();
+ pool.shutdown();
+ }
+ }
+ if (size == 0 || size % 2 != 0) {
+ throw new RuntimeException("Response audio is empty or incomplete (" + size + " bytes)");
+ }
+ AudioCommon.writeWav(output, pcm.toByteArray(), 24000);
+ System.out.println(
+ "Saved "
+ + output.toAbsolutePath()
+ + " ("
+ + String.format("%.2f", size / 48000.0)
+ + " seconds)");
+ if (!noPlay) {
+ AudioCommon.play(output);
+ }
+ }
+
+ private static void usage() {
+ System.err.println(
+ "usage: RealtimeQwenAudioDialog (--wav | --microphone [--seconds 10]) --output"
+ + " [--voice v] [--instructions s] [--no-play]");
+ System.exit(2);
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/RealtimeTranslation.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/RealtimeTranslation.java
new file mode 100644
index 00000000..a940d5ba
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/RealtimeTranslation.java
@@ -0,0 +1,213 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.audio;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.resources.audio.RealtimeSession;
+import com.alibaba.dashscope.types.audio.RealtimeParams;
+import com.alibaba.dashscope.types.audio.UpdateSessionParams;
+import com.fasterxml.jackson.databind.JsonNode;
+import java.io.ByteArrayOutputStream;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Translate speech with Qwen3.8-LiveTranslate, saving the spoken translation as a 24 kHz WAV.
+ * Translation of the Python blueprint example 01_atomic_capabilities/audio/realtime_translation.py.
+ *
+ * Server-side turn detection stays enabled: no commit/createResponse; {@code endSession()} at
+ * input end, and the receiver drains until {@code session.finished} (not the first {@code
+ * response.done}) so every translation segment is collected. Default target language {@code en}.
+ *
+ *
+ * mvn -q -f examples/pom.xml exec:java -Dexec.mainClass=com.alibaba.dashscope.examples.atomic.audio.RealtimeTranslation -Dexec.args="--wav input.wav --language en --output translation.wav"
+ *
+ */
+public final class RealtimeTranslation {
+ private static final String MODEL = "qwen3.8-livetranslate-flash-realtime";
+
+ public static void main(String[] args) throws Exception {
+ Path wav = null;
+ Path output = null;
+ boolean microphone = false;
+ boolean noPlay = false;
+ double seconds = 10.0;
+ String language = "en";
+ for (int i = 0; i < args.length; i++) {
+ switch (args[i]) {
+ case "--wav":
+ wav = Paths.get(args[++i]);
+ break;
+ case "--microphone":
+ microphone = true;
+ break;
+ case "--seconds":
+ seconds = Double.parseDouble(args[++i]);
+ break;
+ case "--language":
+ language = args[++i];
+ break;
+ case "--output":
+ output = Paths.get(args[++i]);
+ break;
+ case "--no-play":
+ noPlay = true;
+ break;
+ default:
+ System.err.println("unknown argument: " + args[i]);
+ usage();
+ }
+ }
+ if (output == null || (wav == null && !microphone) || (wav != null && microphone)) {
+ usage();
+ }
+ if (language.trim().isEmpty()) {
+ System.err.println("error: --language requires a non-empty target language code");
+ System.exit(2);
+ }
+ if (microphone && (seconds < 0.1 || seconds > 20)) {
+ System.err.println("error: --seconds must be between 0.1 and 20");
+ System.exit(2);
+ }
+ AudioCommon.PcmAudio audio = null;
+ if (wav != null) {
+ audio = AudioCommon.readWav(wav, 16000);
+ double duration = audio.pcm.length / 2.0 / 16000;
+ if (duration < 0.1 || duration > 20) {
+ System.err.println("error: this example accepts WAV input of 0.1 to 20 seconds");
+ System.exit(2);
+ }
+ }
+
+ ByteArrayOutputStream pcm = new ByteArrayOutputStream();
+ int size;
+ try (DashScopeClient client = ExampleSupport.client()) {
+ RealtimeSession session =
+ client.audio().realtime().connect(RealtimeParams.builder().model(MODEL).build());
+ ExecutorService pool = Executors.newSingleThreadExecutor();
+ try {
+ session.connect();
+ session.updateSession(
+ UpdateSessionParams.builder()
+ .modalities(Arrays.asList("text", "audio"))
+ .translation(UpdateSessionParams.Translation.of(language))
+ .build());
+ // events() is a single-use stream, so ONE receiver thread drains it for the whole
+ // session: it releases sessionUpdated once the server acknowledges the session update
+ // (gating the input below) and finishes at session.finished — every translation segment
+ // is collected, not just the first response.done.
+ CountDownLatch sessionUpdated = new CountDownLatch(1);
+ Future receiver =
+ pool.submit(
+ () -> {
+ try {
+ return drainTranslation(session, pcm, sessionUpdated);
+ } finally {
+ sessionUpdated.countDown();
+ }
+ });
+ if (!sessionUpdated.await(30, TimeUnit.SECONDS)) {
+ throw new RuntimeException("No session.updated event received within 30 seconds");
+ }
+ if (audio != null) {
+ RealtimeOmniDialog.sendWav(session, receiver, audio);
+ } else {
+ RealtimeOmniDialog.sendMicrophone(session, receiver, seconds);
+ }
+ session.endSession();
+ size = receiver.get();
+ } finally {
+ session.close();
+ pool.shutdown();
+ }
+ }
+ if (size == 0 || size % 2 != 0) {
+ throw new RuntimeException("Translation audio is empty or incomplete (" + size + " bytes)");
+ }
+ AudioCommon.writeWav(output, pcm.toByteArray(), 24000);
+ System.out.println(
+ "Saved "
+ + output.toAbsolutePath()
+ + " ("
+ + String.format("%.2f", size / 48000.0)
+ + " seconds)");
+ if (!noPlay) {
+ AudioCommon.play(output);
+ }
+ }
+
+ /**
+ * Single-pass consumer of the single-use event stream: translation audio deltas go to {@code
+ * output}, {@code sessionUpdated} counts down at {@code session.updated}, and the decoded audio
+ * byte count is returned at {@code session.finished} (after at least one completed response).
+ * Prints the source transcription and translated text.
+ */
+ private static int drainTranslation(
+ RealtimeSession session, ByteArrayOutputStream output, CountDownLatch sessionUpdated) {
+ int size = 0;
+ int responses = 0;
+ for (JsonNode event : session.events()) {
+ String kind = event.path("type").asText();
+ switch (kind) {
+ case "response.audio.delta":
+ if (output != null) {
+ byte[] audio = Base64.getDecoder().decode(event.path("delta").asText());
+ output.write(audio, 0, audio.length);
+ size += audio.length;
+ }
+ break;
+ case "response.text.delta":
+ case "response.audio_transcript.delta":
+ System.out.print(event.path("delta").asText());
+ System.out.flush();
+ break;
+ case "response.text.done":
+ case "response.audio_transcript.done":
+ System.out.println();
+ System.out.println(
+ "Translation: " + event.path("text").asText(event.path("transcript").asText("")));
+ break;
+ case "conversation.item.input_audio_transcription.completed":
+ System.out.println();
+ System.out.println("Source: " + event.path("transcript").asText(""));
+ break;
+ case "response.done":
+ JsonNode response = event.path("response");
+ String status = response.path("status").asText(null);
+ if (status != null && !"completed".equals(status)) {
+ throw new RuntimeException("Translation did not complete normally: " + status);
+ }
+ responses++;
+ System.out.println();
+ System.out.println("response_id: " + response.path("id").asText(null));
+ System.out.println("usage: " + response.path("usage"));
+ break;
+ default:
+ break;
+ }
+ if (kind.equals("session.updated")) {
+ sessionUpdated.countDown();
+ } else if (kind.equals("session.finished")) {
+ if (responses == 0) {
+ throw new RuntimeException("Session ended without a translation response completion event");
+ }
+ return size;
+ }
+ }
+ throw new RuntimeException("Connection closed without session.finished");
+ }
+
+ private static void usage() {
+ System.err.println(
+ "usage: RealtimeTranslation (--wav | --microphone [--seconds 10]) --output"
+ + " [--language en] [--no-play]");
+ System.exit(2);
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/TingWuJobsCreate.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/TingWuJobsCreate.java
new file mode 100644
index 00000000..5751d9b4
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/TingWuJobsCreate.java
@@ -0,0 +1,91 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.audio;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.RequestOptions;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.resources.jobs.Job;
+import com.alibaba.dashscope.types.tingwu.TingWuJobParams;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * Offline TingWu job: create a task whose free-form input carries the business-defined fields
+ * ({@code fileUrl} — the audio/video file to analyze — and {@code appid} — the TingWu app ID), wait
+ * for the terminal state, and print the result URL. Replace the appid default and pass your own
+ * publicly accessible file URL before running. Only the offline-jobs part of the Python original is
+ * covered here (its realtime websocket session is a separate capability). Usage:
+ *
+ *
+ * TingWuJobsCreate --url <audio/video file url> [--app-id 123456] [--model tingwu-automotive-service-inspection]
+ *
+ *
+ * Translation of the Python blueprint example 01_atomic_capabilities/audio/tingwu.py.
+ */
+public final class TingWuJobsCreate {
+
+ public static void main(String[] args) throws Exception {
+ String url = null;
+ String appId = "123456"; // Placeholder, as in the Python original; use your own TingWu app ID.
+ String model = "tingwu-automotive-service-inspection";
+ for (int i = 0; i < args.length; i++) {
+ switch (args[i]) {
+ case "--url":
+ url = value(args, ++i);
+ break;
+ case "--app-id":
+ appId = value(args, ++i);
+ break;
+ case "--model":
+ model = value(args, ++i);
+ break;
+ default:
+ usage();
+ System.exit(2);
+ }
+ }
+ if (url == null) {
+ usage();
+ System.exit(2);
+ }
+
+ Map input = new LinkedHashMap<>();
+ input.put("fileUrl", url);
+ input.put("appid", appId);
+ try (DashScopeClient client = ExampleSupport.client()) {
+ Job created =
+ client
+ .tingwu()
+ .jobs()
+ .create(TingWuJobParams.builder().model(model).input(input).build());
+ if (created.isError()) {
+ System.err.println("error: " + created.getCode() + " " + created.getMessage());
+ System.exit(1);
+ }
+ System.out.println("task_id: " + created.getTaskId());
+ Job job = client.tingwu().jobs().wait(created.getTaskId(), RequestOptions.NONE);
+ System.out.println(
+ "Task status: " + job.getTaskStatus() + " request_id=" + job.getRequestId());
+ if (job.getResultUrl() != null) {
+ System.out.println("result_url: " + job.getResultUrl());
+ }
+ System.out.println(job.getOutput());
+ if (!job.isSucceeded()) {
+ System.exit(1);
+ }
+ }
+ }
+
+ private static String value(String[] args, int i) {
+ if (i >= args.length) {
+ usage();
+ System.exit(2);
+ }
+ return args[i];
+ }
+
+ private static void usage() {
+ System.err.println(
+ "usage: TingWuJobsCreate --url [--app-id ID] [--model M]");
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/TtsHttpStreamSynthesize.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/TtsHttpStreamSynthesize.java
new file mode 100644
index 00000000..a142cfd4
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/TtsHttpStreamSynthesize.java
@@ -0,0 +1,115 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.audio;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.types.audio.TtsSynthesizeParams;
+import com.alibaba.dashscope.types.common.ResponseStream;
+import java.io.ByteArrayOutputStream;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+/**
+ * HTTP SSE TTS: stream decoded PCM chunks, accumulate them into one WAV at 24000 Hz, save after the
+ * stream completes, then play (unless {@code --no-play}). Default model {@code
+ * qwen-audio-3.1-tts-flash} with voice {@code longanhuan_v3.1}. A real request may incur charges.
+ * The SDK's {@code byte[]} stream skips frames that carry no audio (usage-only tails), so the
+ * finish flag and requestId/usage of the Python original are not observable here; an in-stream
+ * business error still surfaces as an exception. Usage:
+ *
+ * TtsHttpStreamSynthesize <text> <output.wav> [--model M] [--voice V] [--no-play]
+ *
+ *
+ * Translation of the Python blueprint example 01_atomic_capabilities/audio/tts_http_stream.py.
+ */
+public final class TtsHttpStreamSynthesize {
+
+ private static final int SAMPLE_RATE = 24000;
+
+ public static void main(String[] args) throws Exception {
+ if (args.length < 2) {
+ usage();
+ System.exit(2);
+ }
+ String text = args[0];
+ Path output = Paths.get(args[1]);
+ String model = "qwen-audio-3.1-tts-flash";
+ String voice = "longanhuan_v3.1";
+ boolean play = true;
+ for (int i = 2; i < args.length; i++) {
+ switch (args[i]) {
+ case "--model":
+ model = value(args, ++i);
+ break;
+ case "--voice":
+ voice = value(args, ++i);
+ break;
+ case "--no-play":
+ play = false;
+ break;
+ default:
+ usage();
+ System.exit(2);
+ }
+ }
+ if (text.trim().isEmpty()) {
+ System.err.println("error: text must not be empty or blank");
+ System.exit(2);
+ }
+
+ ByteArrayOutputStream pcm = new ByteArrayOutputStream();
+ try (DashScopeClient client = ExampleSupport.client();
+ ResponseStream stream =
+ client.audio().tts().http().stream(
+ TtsSynthesizeParams.builder()
+ .model(model)
+ .voice(voice)
+ .text(text)
+ // Request raw PCM: this example accumulates the chunks and wraps them below.
+ .format("pcm")
+ .sampleRate(SAMPLE_RATE)
+ .build())) {
+ for (byte[] chunk : stream) {
+ pcm.write(chunk, 0, chunk.length);
+ }
+ }
+ byte[] audio = pcm.toByteArray();
+ if (audio.length >= 12
+ && audio[0] == 'R'
+ && audio[1] == 'I'
+ && audio[2] == 'F'
+ && audio[3] == 'F'
+ && audio[8] == 'W'
+ && audio[9] == 'A'
+ && audio[10] == 'V'
+ && audio[11] == 'E') {
+ // The service returned a RIFF/WAVE container instead of raw PCM; refuse to wrap it twice.
+ throw new IllegalStateException("service returned a WAV container, not raw PCM");
+ }
+ if (audio.length == 0 || audio.length % 2 != 0) {
+ throw new IllegalStateException(
+ "returned PCM audio is empty or not an even number of bytes (" + audio.length + ")");
+ }
+ // Never overwrites an existing file (AudioCommon.writeWav enforces this).
+ AudioCommon.writeWav(output, audio, SAMPLE_RATE);
+ System.out.printf(
+ "Saved %s (%d bytes PCM, %.2f seconds)%n",
+ output.toAbsolutePath(), audio.length, audio.length / 2.0 / SAMPLE_RATE);
+ if (play) {
+ AudioCommon.play(output);
+ }
+ }
+
+ private static String value(String[] args, int i) {
+ if (i >= args.length) {
+ usage();
+ System.exit(2);
+ }
+ return args[i];
+ }
+
+ private static void usage() {
+ System.err.println(
+ "usage: TtsHttpStreamSynthesize [--model M] [--voice V] [--no-play]");
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/TtsHttpSynthesize.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/TtsHttpSynthesize.java
new file mode 100644
index 00000000..e9337610
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/TtsHttpSynthesize.java
@@ -0,0 +1,112 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.audio;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.types.audio.TtsSynthesizeParams;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+/**
+ * HTTP one-shot TTS: synthesize the whole text in one call, wrap the returned raw PCM into one WAV,
+ * save it, then play it (unless {@code --no-play}). Default model {@code qwen-audio-3.1-tts-flash}
+ * with voice {@code longanhuan_v3.1} at 24000 Hz. A real request may incur charges. The one-shot
+ * aggregate holds the whole audio in memory; prefer the streaming variant for long text. Usage:
+ *
+ * TtsHttpSynthesize <text> <output.wav> [--model M] [--voice V] [--no-play]
+ *
+ * Translation of the Python blueprint example 01_atomic_capabilities/audio/tts_http.py.
+ */
+public final class TtsHttpSynthesize {
+
+ private static final int SAMPLE_RATE = 24000;
+
+ public static void main(String[] args) throws Exception {
+ if (args.length < 2) {
+ usage();
+ System.exit(2);
+ }
+ String text = args[0];
+ Path output = Paths.get(args[1]);
+ String model = "qwen-audio-3.1-tts-flash";
+ String voice = "longanhuan_v3.1";
+ boolean play = true;
+ for (int i = 2; i < args.length; i++) {
+ switch (args[i]) {
+ case "--model":
+ model = value(args, ++i);
+ break;
+ case "--voice":
+ voice = value(args, ++i);
+ break;
+ case "--no-play":
+ play = false;
+ break;
+ default:
+ usage();
+ System.exit(2);
+ }
+ }
+ if (text.trim().isEmpty()) {
+ System.err.println("error: text must not be empty or blank");
+ System.exit(2);
+ }
+
+ byte[] pcm;
+ try (DashScopeClient client = ExampleSupport.client()) {
+ // The aggregated byte[] result carries no requestId/usage; only the streaming variants
+ // expose per-frame envelopes.
+ pcm =
+ client
+ .audio()
+ .tts()
+ .http()
+ .synthesize(
+ TtsSynthesizeParams.builder()
+ .model(model)
+ .voice(voice)
+ .text(text)
+ // Request raw PCM: this example wraps it into a WAV itself below.
+ .format("pcm")
+ .sampleRate(SAMPLE_RATE)
+ .build());
+ }
+ if (pcm.length >= 12
+ && pcm[0] == 'R'
+ && pcm[1] == 'I'
+ && pcm[2] == 'F'
+ && pcm[3] == 'F'
+ && pcm[8] == 'W'
+ && pcm[9] == 'A'
+ && pcm[10] == 'V'
+ && pcm[11] == 'E') {
+ // The service returned a RIFF/WAVE container instead of raw PCM; refuse to wrap it twice.
+ throw new IllegalStateException("service returned a WAV container, not raw PCM");
+ }
+ if (pcm.length == 0 || pcm.length % 2 != 0) {
+ throw new IllegalStateException(
+ "returned PCM audio is empty or not an even number of bytes (" + pcm.length + ")");
+ }
+ // Never overwrites an existing file (AudioCommon.writeWav enforces this).
+ AudioCommon.writeWav(output, pcm, SAMPLE_RATE);
+ System.out.printf(
+ "Saved %s (%d bytes PCM, %.2f seconds)%n",
+ output.toAbsolutePath(), pcm.length, pcm.length / 2.0 / SAMPLE_RATE);
+ if (play) {
+ AudioCommon.play(output);
+ }
+ }
+
+ private static String value(String[] args, int i) {
+ if (i >= args.length) {
+ usage();
+ System.exit(2);
+ }
+ return args[i];
+ }
+
+ private static void usage() {
+ System.err.println(
+ "usage: TtsHttpSynthesize [--model M] [--voice V] [--no-play]");
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/TtsWebsocketConnect.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/TtsWebsocketConnect.java
new file mode 100644
index 00000000..95639b51
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/TtsWebsocketConnect.java
@@ -0,0 +1,223 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.audio;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.resources.audio.SynthesisSession;
+import com.alibaba.dashscope.types.audio.TtsConnectParams;
+import com.alibaba.dashscope.types.common.ResponseStream;
+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.io.ByteArrayOutputStream;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+/**
+ * WebSocket duplex TTS: send text while receiving audio into one WAV, then play it. Translation of
+ * the Python blueprint example 01_atomic_capabilities/audio/tts_websocket.py.
+ *
+ * Default model {@code qwen-audio-3.1-tts-flash}, voice {@code longanhuan_v3.1}. With {@code
+ * --prompt}, an LLM answer is streamed first ({@code chat.completions.createStreaming}) and every
+ * delta text is fed straight into the synthesizer.
+ *
+ *
+ * mvn -q -f examples/pom.xml exec:java -Dexec.mainClass=com.alibaba.dashscope.examples.atomic.audio.TtsWebsocketConnect -Dexec.args="--text 'Hello, welcome to speech synthesis.' --output hello.wav"
+ *
+ */
+public final class TtsWebsocketConnect {
+ private static final Map DEFAULT_VOICES = new HashMap<>();
+
+ static {
+ DEFAULT_VOICES.put("qwen-audio-3.1-tts-flash", "longanhuan_v3.1");
+ DEFAULT_VOICES.put("qwen-audio-3.0-tts-flash", "longanhuan_v3.6");
+ DEFAULT_VOICES.put("cosyvoice-v3-flash", "longanhuan");
+ DEFAULT_VOICES.put("cosyvoice-v3-plus", "longanhuan");
+ }
+
+ public static void main(String[] args) throws Exception {
+ List texts = new ArrayList<>();
+ String prompt = null;
+ String llmModel = "qwen-plus";
+ String model = "qwen-audio-3.1-tts-flash";
+ String voice = null;
+ String instruction = null;
+ int sampleRate = 24000;
+ Path output = null;
+ boolean noPlay = false;
+ for (int i = 0; i < args.length; i++) {
+ switch (args[i]) {
+ case "--text":
+ texts.add(args[++i]);
+ break;
+ case "--prompt":
+ prompt = args[++i];
+ break;
+ case "--llm-model":
+ llmModel = args[++i];
+ break;
+ case "--model":
+ model = args[++i];
+ break;
+ case "--voice":
+ voice = args[++i];
+ break;
+ case "--instruction":
+ instruction = args[++i];
+ break;
+ case "--sample-rate":
+ sampleRate = Integer.parseInt(args[++i]);
+ break;
+ case "--output":
+ output = Paths.get(args[++i]);
+ break;
+ case "--no-play":
+ noPlay = true;
+ break;
+ default:
+ System.err.println("unknown argument: " + args[i]);
+ usage();
+ }
+ }
+ if (output == null
+ || (texts.isEmpty() && prompt == null)
+ || (prompt != null && !texts.isEmpty())) {
+ usage();
+ }
+ if (prompt != null && prompt.trim().isEmpty()) {
+ System.err.println("error: --prompt requires a non-empty prompt");
+ System.exit(2);
+ }
+ if (prompt == null && texts.stream().noneMatch(t -> !t.trim().isEmpty())) {
+ System.err.println("error: text must not be empty");
+ System.exit(2);
+ }
+ if (voice == null) {
+ voice = DEFAULT_VOICES.getOrDefault(model, "longanhuan_v3.1");
+ }
+
+ try (DashScopeClient client = ExampleSupport.client()) {
+ TtsConnectParams.Builder params =
+ TtsConnectParams.builder().model(model).voice(voice).format("pcm").sampleRate(sampleRate);
+ if (instruction != null) {
+ params.parameters(Collections.singletonMap("instruction", instruction));
+ }
+ SynthesisSession session = client.audio().tts().connect(params.build());
+ ExecutorService receiverPool = Executors.newSingleThreadExecutor();
+ ByteArrayOutputStream pcm = new ByteArrayOutputStream();
+ long size;
+ try {
+ session.start();
+ // Receive audio chunks on a worker thread while the caller thread sends text.
+ Future receiver =
+ receiverPool.submit(
+ () -> {
+ long received = 0;
+ for (byte[] chunk : session.audioChunks()) {
+ pcm.write(chunk, 0, chunk.length);
+ received += chunk.length;
+ }
+ return received;
+ });
+ try {
+ if (prompt != null) {
+ streamPrompt(client, llmModel, prompt, session, receiver);
+ } else {
+ for (String part : texts) {
+ checkReceiver(receiver);
+ if (!part.isEmpty()) {
+ session.sendText(part);
+ }
+ }
+ }
+ session.stop();
+ size = receiver.get();
+ } finally {
+ // Close before joining the pool to unblock a socket reader (Python parity).
+ session.close();
+ }
+ if (size == 0 || size % 2 != 0) {
+ throw new RuntimeException("Returned PCM audio is empty or incomplete (" + size + " bytes)");
+ }
+ System.err.println(
+ "request_id="
+ + session.getRequestId()
+ + " first_package_delay_ms="
+ + millis(session.getFirstPackageDelay())
+ + " usage="
+ + session.getUsage());
+ AudioCommon.writeWav(output, pcm.toByteArray(), sampleRate);
+ } finally {
+ receiverPool.shutdown();
+ }
+ System.out.println(
+ "Saved "
+ + output.toAbsolutePath()
+ + " ("
+ + String.format("%.2f", size / 2.0 / sampleRate)
+ + " seconds)");
+ if (!noPlay) {
+ AudioCommon.play(output);
+ }
+ }
+ }
+
+ /** Stream an LLM answer and feed every delta text into the synthesizer (Python --prompt flow). */
+ private static void streamPrompt(
+ DashScopeClient client,
+ String llmModel,
+ String prompt,
+ SynthesisSession session,
+ Future receiver)
+ throws Exception {
+ try (ResponseStream stream =
+ client
+ .chat()
+ .completions()
+ .createStreaming(
+ ChatCompletionCreateParams.builder()
+ .model(llmModel)
+ .messages(Collections.singletonList(Message.user(prompt)))
+ .incrementalOutput(true)
+ .build())) {
+ for (ChatCompletionChunk chunk : stream) {
+ Delta delta = chunk.delta();
+ String text = delta == null ? null : delta.getContent();
+ if (text != null && !text.isEmpty()) {
+ checkReceiver(receiver);
+ session.sendText(text);
+ }
+ }
+ }
+ }
+
+ /** Surface a receiver failure as soon as the send side notices it exited early. */
+ private static void checkReceiver(Future> receiver) throws Exception {
+ if (receiver.isDone()) {
+ receiver.get();
+ throw new RuntimeException("Synthesis session ended before all text was sent");
+ }
+ }
+
+ private static String millis(Duration duration) {
+ return duration == null ? "null" : Long.toString(duration.toMillis());
+ }
+
+ private static void usage() {
+ System.err.println(
+ "usage: TtsWebsocketConnect (--text [--text ...] | --prompt ) --output "
+ + " [--model m] [--voice v] [--llm-model m] [--instruction s] [--sample-rate 24000]"
+ + " [--no-play]");
+ System.exit(2);
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/VoiceCloneManage.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/VoiceCloneManage.java
new file mode 100644
index 00000000..1a1bca63
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/VoiceCloneManage.java
@@ -0,0 +1,215 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.audio;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.types.audio.Voice;
+import com.alibaba.dashscope.types.audio.VoiceCreateParams;
+import com.alibaba.dashscope.types.audio.VoiceList;
+import com.alibaba.dashscope.types.common.JobStatus;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Voice cloning management (Qwen-Audio / CosyVoice): create a clone from reference audio at a
+ * service-reachable HTTPS URL and wait until it is OK, or get/list/delete existing clones. Default
+ * target model {@code qwen-audio-3.0-tts-flash} (voice-enrollment API); synthesis must use the same
+ * target model. No synthesis, playback, or auto-deletion here: a created voice persists, including
+ * after timeout or interruption, and is never deleted unless {@code delete --yes} is run
+ * explicitly. Usage:
+ *
+ *
+ * VoiceCloneManage create --url <https audio> [--prefix demo] [--model qwen-audio-3.0-tts-flash] [--wait-timeout SEC]
+ * VoiceCloneManage get --voice-id <id>
+ * VoiceCloneManage list [--prefix P] [--page-index N] [--page-size N]
+ * VoiceCloneManage delete --voice-id <id> --yes
+ *
+ *
+ * Translation of the Python blueprint example 01_atomic_capabilities/audio/voice_clone.py.
+ */
+public final class VoiceCloneManage {
+
+ public static void main(String[] args) throws Exception {
+ if (args.length < 1) {
+ usage();
+ System.exit(2);
+ }
+ String command = args[0];
+ Map opts = new HashMap<>();
+ boolean yes = false;
+ for (int i = 1; i < args.length; i++) {
+ if ("--yes".equals(args[i])) {
+ yes = true;
+ } else if (args[i].startsWith("--")) {
+ opts.put(args[i], value(args, ++i));
+ } else {
+ usage();
+ System.exit(2);
+ }
+ }
+
+ try (DashScopeClient client = ExampleSupport.client()) {
+ switch (command) {
+ case "create":
+ create(client, opts);
+ break;
+ case "get":
+ get(client, voiceId(opts));
+ break;
+ case "list":
+ list(client, opts);
+ break;
+ case "delete":
+ if (!yes) {
+ System.err.println("error: delete requires --yes; nothing has been deleted");
+ System.exit(2);
+ }
+ delete(client, voiceId(opts));
+ break;
+ default:
+ usage();
+ System.exit(2);
+ }
+ }
+ }
+
+ private static void create(DashScopeClient client, Map opts) throws Exception {
+ String url = opts.get("--url");
+ if (url == null || !url.startsWith("https://")) {
+ // Upload owned/authorized speaker audio yourself; this sample never uploads local files.
+ // Recommended: 10-20 s WAV (16-bit)/MP3/M4A, >=16 kHz, <=10 MB, at most 60 s, with at
+ // least 5 s of continuous clear speech and no music or other speakers.
+ System.err.println("error: create requires --url ");
+ System.exit(2);
+ }
+ String prefix = opts.getOrDefault("--prefix", "demo");
+ if (!prefix.matches("[a-z0-9]{1,10}")) {
+ System.err.println("error: --prefix must be 1-10 lowercase letters/digits");
+ System.exit(2);
+ }
+ String model = opts.getOrDefault("--model", "qwen-audio-3.0-tts-flash");
+ long waitTimeoutSec = Long.parseLong(opts.getOrDefault("--wait-timeout", "300"));
+ System.err.println(
+ "Use only your own or explicitly authorized speaker audio. Creating a clone may incur"
+ + " charges; it will NOT be automatically deleted.");
+ Voice voice =
+ client
+ .audio()
+ .voices()
+ .create(VoiceCreateParams.builder().targetModel(model).prefix(prefix).url(url).build());
+ if (voice.getVoiceId() == null) {
+ throw new IllegalStateException(
+ "No voice ID returned (request_id="
+ + voice.getRequestId()
+ + "); use list before attempting another create");
+ }
+ System.out.println("voice_id: " + voice.getVoiceId() + " request_id=" + voice.getRequestId());
+ System.err.println("Recover without creating again: get --voice-id " + voice.getVoiceId());
+ waitReady(client, voice.getVoiceId(), waitTimeoutSec);
+ System.out.println(
+ "Ready. Synthesize separately with the same target model ("
+ + model
+ + "); may incur charges.");
+ }
+
+ /** Poll until OK; only DEPLOYING is retryable — never poll UNDEPLOYED or unknown states. */
+ private static void waitReady(DashScopeClient client, String voiceId, long waitTimeoutSec)
+ throws Exception {
+ long deadline = System.nanoTime() + waitTimeoutSec * 1_000_000_000L;
+ String previous = null;
+ while (true) {
+ long remainingMs = (deadline - System.nanoTime()) / 1_000_000L;
+ if (remainingMs <= 0) {
+ throw new IllegalStateException(
+ "Voice is not ready before --wait-timeout; use get to recover");
+ }
+ Voice voice = client.audio().voices().get(voiceId);
+ if (!String.valueOf(voice.getStatus()).equals(previous)) {
+ System.out.println("Voice status: " + voice.getStatus());
+ previous = String.valueOf(voice.getStatus());
+ }
+ if ("OK".equals(voice.getStatus())) {
+ return;
+ }
+ if (!"DEPLOYING".equals(voice.getStatus())) {
+ throw new IllegalStateException(
+ "Voice is unavailable or has unsupported status: " + voice.getStatus());
+ }
+ Thread.sleep(Math.min(2000, remainingMs));
+ }
+ }
+
+ private static void get(DashScopeClient client, String voiceId) {
+ Voice voice = client.audio().voices().get(voiceId);
+ System.out.println(
+ "voice_id: "
+ + voiceId
+ + "; status: "
+ + voice.getStatus()
+ + "; request_id="
+ + voice.getRequestId());
+ if (!"OK".equals(voice.getStatus())) {
+ System.err.println("Voice is not ready; do not synthesize with it yet.");
+ System.exit(1);
+ }
+ }
+
+ private static void list(DashScopeClient client, Map opts) {
+ String prefix = opts.get("--prefix");
+ int pageIndex = Integer.parseInt(opts.getOrDefault("--page-index", "0"));
+ int pageSize = Integer.parseInt(opts.getOrDefault("--page-size", "10"));
+ if (pageIndex < 0 || pageSize <= 0) {
+ System.err.println("error: --page-index must be >= 0 and --page-size must be > 0");
+ System.exit(2);
+ }
+ VoiceList voices = client.audio().voices().list(prefix, pageIndex, pageSize);
+ System.out.println(
+ "Page "
+ + pageIndex
+ + ": "
+ + voices.getVoices().size()
+ + " voice(s)"
+ + " request_id="
+ + voices.getRequestId());
+ for (Map voice : voices.getVoices()) {
+ System.out.println("voice_id: " + voice.get("voice_id") + "; status: " + voice.get("status"));
+ }
+ }
+
+ private static void delete(DashScopeClient client, String voiceId) {
+ JobStatus result = client.audio().voices().delete(voiceId);
+ System.out.println(
+ "Deleted "
+ + voiceId
+ + "; status: "
+ + result.getStatus()
+ + "; request_id: "
+ + result.getRequestId());
+ }
+
+ private static String voiceId(Map opts) {
+ String id = opts.get("--voice-id");
+ if (id == null || id.isEmpty() || id.chars().anyMatch(Character::isWhitespace)) {
+ System.err.println("error: --voice-id must be nonempty and contain no spaces");
+ System.exit(2);
+ }
+ return id;
+ }
+
+ private static String value(String[] args, int i) {
+ if (i >= args.length) {
+ usage();
+ System.exit(2);
+ }
+ return args[i];
+ }
+
+ private static void usage() {
+ System.err.println(
+ "usage: VoiceCloneManage create --url [--prefix demo] [--model M]"
+ + " [--wait-timeout SEC]\n"
+ + " VoiceCloneManage get --voice-id \n"
+ + " VoiceCloneManage list [--prefix P] [--page-index N] [--page-size N]\n"
+ + " VoiceCloneManage delete --voice-id --yes");
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/ChatCompletionsCreate.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/ChatCompletionsCreate.java
new file mode 100644
index 00000000..a1d04612
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/ChatCompletionsCreate.java
@@ -0,0 +1,64 @@
+// 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.
+ *
+ * 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 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 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();
+ }
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/ChatCompletionsCreateAsync.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/ChatCompletionsCreateAsync.java
new file mode 100644
index 00000000..4c33eb90
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/ChatCompletionsCreateAsync.java
@@ -0,0 +1,63 @@
+// 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).
+ *
+ * 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 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 future = client.chat().completions().create(params);
+ CompletableFuture 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 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();
+ }
+ }
+}
\ No newline at end of file
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/ChatCompletionsCreateEncrypted.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/ChatCompletionsCreateEncrypted.java
new file mode 100644
index 00000000..c7fbb26c
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/ChatCompletionsCreateEncrypted.java
@@ -0,0 +1,45 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.chat;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.RequestOptions;
+import com.alibaba.dashscope.examples.ExampleSupport;
+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;
+
+/**
+ * Encrypted chat channel (J7): {@code RequestOptions.enableEncryption(true)} fetches the server's
+ * latest RSA public key ({@code GET /public-keys/latest}), wraps a fresh per-request AES key with
+ * it, AES-GCM-encrypts the sensitive {@code input} part, and decrypts the encrypted {@code output}
+ * transparently. The call shape is identical to {@link ChatCompletionsCreate}.
+ *
+ * Encryption is per-request: the same client can mix plain and encrypted calls.
+ */
+public final class ChatCompletionsCreateEncrypted {
+
+ public static void main(String[] args) throws Exception {
+ String model = System.getenv().getOrDefault("DASHSCOPE_MODEL", "qwen3.7-plus");
+
+ try (DashScopeClient client = ExampleSupport.client()) {
+ System.out.println("----- encrypted request -----");
+ ChatCompletion resp =
+ client
+ .chat()
+ .completions()
+ .create(
+ ChatCompletionCreateParams.builder()
+ .model(model)
+ .messages(
+ Arrays.asList(
+ Message.system("You are a helpful assistant."),
+ Message.user("请用一句话介绍杭州")))
+ .build(),
+ RequestOptions.builder().enableEncryption(true).build());
+ // outputText() is already decrypted by the SDK.
+ System.out.println(resp.outputText());
+ System.out.println("request_id: " + resp.getRequestId());
+ }
+ }
+}
\ No newline at end of file
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/TokenizationCount.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/TokenizationCount.java
new file mode 100644
index 00000000..a84e1261
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/TokenizationCount.java
@@ -0,0 +1,48 @@
+// 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.messages.Message;
+import com.alibaba.dashscope.types.tokenization.TokenCount;
+import com.alibaba.dashscope.types.tokenization.TokenizationCountParams;
+import java.util.Arrays;
+
+/**
+ * Server-side token counting over a plain prompt and over a chat message list. Translation of the
+ * Python blueprint example 01_atomic_capabilities/text_generation/tokenization.py.
+ *
+ *
For the local BPE tokenizer (no network) see {@link TokenizationLocalCount}.
+ */
+public final class TokenizationCount {
+
+ public static void main(String[] args) throws Exception {
+ String model = System.getenv().getOrDefault("DASHSCOPE_MODEL", "qwen3.7-plus");
+
+ try (DashScopeClient client = ExampleSupport.client()) {
+ // Count the tokens of a plain prompt
+ System.out.println("----- count (prompt) -----");
+ TokenCount resp =
+ client
+ .tokenization()
+ .count(TokenizationCountParams.builder().model(model).prompt("请用一句话介绍杭州").build());
+ System.out.println("input_tokens: " + resp.getInputTokens());
+ System.out.println("token_ids: " + resp.getTokenIds());
+
+ // Count the tokens of a chat message list
+ System.out.println("----- count (messages) -----");
+ resp =
+ client
+ .tokenization()
+ .count(
+ TokenizationCountParams.builder()
+ .model(model)
+ .messages(
+ Arrays.asList(
+ Message.system("You are a helpful assistant."),
+ Message.user("请用一句话介绍杭州")))
+ .build());
+ System.out.println("input_tokens: " + resp.getInputTokens());
+ }
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/TokenizationLocalCount.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/TokenizationLocalCount.java
new file mode 100644
index 00000000..4511cb55
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/TokenizationLocalCount.java
@@ -0,0 +1,39 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.chat;
+
+import com.alibaba.dashscope.tokenization.Tokenizer;
+import com.alibaba.dashscope.tokenization.TokenizerFactory;
+import java.util.List;
+
+/**
+ * Local Qwen BPE tokenizer: encode/decode entirely offline, no API key and no network call (the
+ * vocabulary {@code qwen.tiktoken} is resolved from {@code DASHSCOPE_QWEN_VOCAB}, the classpath, a
+ * verified local cache, or a one-time ModelScope download).
+ *
+ *
For server-side counting see {@link TokenizationCount}. Local results are approximate: they
+ * are not guaranteed to match the model's own tokenization exactly.
+ */
+public final class TokenizationLocalCount {
+
+ public static void main(String[] args) {
+ Tokenizer tokenizer = TokenizerFactory.qwen();
+
+ // Ordinary encoding: special tokens in the text are treated as plain text.
+ System.out.println("----- encodeOrdinary -----");
+ String text = "你好,杭州!";
+ List ids = tokenizer.encodeOrdinary(text);
+ System.out.println("text: " + text);
+ System.out.println("token count: " + ids.size());
+ System.out.println("token_ids: " + ids);
+ System.out.println("decoded: " + tokenizer.decode(ids));
+
+ // Special-token-aware encoding: "all" recognizes <|im_start|> / <|im_end|> etc. as single
+ // tokens; "none" forbids them, "none_raise" throws when the input has none.
+ System.out.println("----- encode (special tokens) -----");
+ String chatText = "<|im_start|>user\n你好<|im_end|>";
+ List chatIds = tokenizer.encode(chatText, "all");
+ System.out.println("text: " + chatText.replace("\n", "\\n"));
+ System.out.println("token count: " + chatIds.size());
+ System.out.println("decoded: " + tokenizer.decode(chatIds).replace("\n", "\\n"));
+ }
+}
\ No newline at end of file
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/decision/DecisionCreate.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/decision/DecisionCreate.java
new file mode 100644
index 00000000..9e5d514e
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/decision/DecisionCreate.java
@@ -0,0 +1,94 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.decision;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.types.decision.DecisionAnswer;
+import com.alibaba.dashscope.types.decision.DecisionCreateParams;
+import com.alibaba.dashscope.types.decision.DecisionQuestion;
+import com.alibaba.dashscope.types.decision.DecisionResult;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * Decision model (System One): one {@code decision().create} call answers a set of typed questions
+ * about a business {@code state} in a single forward pass — multi-choice ({@code choice}), yes/no
+ * ({@code noul}) and ordinal scale ({@code score}) — each answer carrying its probability
+ * distribution. The model generates no text, so latency and cost do not grow with output length.
+ * Typical uses: ticket routing, content moderation, agent routing. Translation of the Python
+ * blueprint example 01_atomic_capabilities/decision/decision.py.
+ */
+public final class DecisionCreate {
+
+ public static void main(String[] args) throws Exception {
+ String model = System.getenv().getOrDefault("DASHSCOPE_MODEL", "decision-model-preview");
+
+ // The business state under decision: free text, a dialogue, or a structured object like
+ // this support ticket.
+ Map state = new LinkedHashMap<>();
+ state.put("ticket_id", "T-1001");
+ state.put("content", "订单支付后超过 24 小时仍未到账,用户无法继续使用核心服务。");
+
+ Map questions = new LinkedHashMap<>();
+ // choice: pick one of the criteria options (1-255 options; give the full set and add an
+ // "other" fallback).
+ Map departmentOptions = new LinkedHashMap<>();
+ departmentOptions.put("billing", "支付、退款和账单问题");
+ departmentOptions.put("technical", "产品故障和集成问题");
+ departmentOptions.put("other", "不属于以上两类的问题");
+ questions.put("department", DecisionQuestion.choice("应该由哪个团队处理?", departmentOptions));
+ // noul: yes/no judgement; the answer is P(yes), 0=no, 1=yes.
+ questions.put("escalate", DecisionQuestion.noul("是否需要立即通知值班人员?"));
+ // score: ordinal scale described low to high (2-255 levels; 3-7 clearly distinguishable
+ // levels work best).
+ questions.put(
+ "severity",
+ DecisionQuestion.score(
+ "这个问题有多严重?",
+ Arrays.asList("轻微问题,不影响功能", "部分功能受影响,但存在替代方案", "核心功能不可用,没有替代方案", "造成严重业务或安全影响")));
+
+ try (DashScopeClient client = ExampleSupport.client()) {
+ System.out.println("----- decision request -----");
+ DecisionResult resp =
+ client
+ .decision()
+ .create(
+ DecisionCreateParams.builder()
+ .model(model)
+ .state(state)
+ .questions(questions)
+ .build());
+
+ // getAnswers() keys mirror the request's question ids.
+ DecisionAnswer department = resp.getAnswers().get("department");
+ System.out.println(
+ "department="
+ + department.getChoice()
+ + ", confidence="
+ + department.getConfidence()
+ + ", probabilities="
+ + department.getProbabilities());
+
+ DecisionAnswer escalate = resp.getAnswers().get("escalate");
+ System.out.println("escalate P(yes)=" + escalate.getNoul());
+
+ DecisionAnswer severity = resp.getAnswers().get("severity");
+ // score is the probability-weighted level index and may fall between two levels; legend
+ // maps an index back to its text.
+ System.out.println(
+ "severity="
+ + severity.getScore()
+ + ", confidence="
+ + severity.getConfidence()
+ + ", legend="
+ + severity.getLegend());
+
+ System.out.println(
+ "input_tokens="
+ + resp.getUsage().getInputTokens()
+ + ", latency_ms="
+ + resp.getLatencyMs());
+ }
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/deployments/DeploymentsManage.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/deployments/DeploymentsManage.java
new file mode 100644
index 00000000..4f867cfd
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/deployments/DeploymentsManage.java
@@ -0,0 +1,72 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.deployments;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.types.deployments.Deployment;
+import com.alibaba.dashscope.types.deployments.DeploymentList;
+
+/**
+ * Model deployments: list deployed models and get one; the billed create -> scale -> delete
+ * lifecycle is shown commented out (same convention as {@code FineTunesCreate}).
+ *
+ * The read-only list/get sections run as-is. Uncomment the lifecycle section to deploy a
+ * fine-tuned model (see {@code FineTunesCreate}); capacity is billed while the deployment runs.
+ * This is the model-deployment service {@code client.deployments()}, not the AgentStudio
+ * scheduled-deployment service in {@code recipes.agentstudio.AgentStudioDeploymentsManage}.
+ */
+public final class DeploymentsManage {
+
+ public static void main(String[] args) throws Exception {
+ try (DashScopeClient client = ExampleSupport.client()) {
+ // List deployments (paged)
+ System.out.println("----- list deployments -----");
+ DeploymentList page = client.deployments().list(1, 10);
+ System.out.println("total: " + page.getTotalCount());
+ for (Deployment deployment : page.getDeployments()) {
+ System.out.println(
+ "deployed_model="
+ + deployment.getDeployedModel()
+ + ", status="
+ + deployment.getStatus()
+ + ", capacity="
+ + deployment.getCapacity());
+ }
+
+ // Get one deployment by deployed_model (uses the first entry of the list above)
+ if (!page.getDeployments().isEmpty()) {
+ System.out.println("----- get deployment -----");
+ Deployment deployment =
+ client.deployments().get(page.getDeployments().get(0).getDeployedModel());
+ System.out.println(
+ "deployed_model="
+ + deployment.getDeployedModel()
+ + ", status="
+ + deployment.getStatus()
+ + ", ready_capacity="
+ + deployment.getReadyCapacity());
+ }
+
+ // Full lifecycle: create -> scale -> delete. Uncomment to deploy a fine-tuned model;
+ // capacity is billed until the deployment is deleted.
+ //
+ // System.out.println("----- create deployment -----");
+ // Deployment created =
+ // client.deployments().create(
+ // com.alibaba.dashscope.types.deployments.DeploymentCreateParams.builder()
+ // .model("my-finetuned-model")
+ // .capacity(1)
+ // .build());
+ // System.out.println("created deployed_model=" + created.getDeployedModel());
+ //
+ // System.out.println("----- scale deployment -----");
+ // Deployment scaled = client.deployments().scale(created.getDeployedModel(), 2);
+ // System.out.println("status=" + scaled.getStatus() + ", capacity=" + scaled.getCapacity());
+ //
+ // System.out.println("----- delete deployment -----");
+ // com.alibaba.dashscope.types.common.JobStatus deleted =
+ // client.deployments().delete(created.getDeployedModel());
+ // System.out.println("status=" + deleted.getStatus());
+ }
+ }
+}
\ No newline at end of file
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/embeddings/EmbeddingsCreate.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/embeddings/EmbeddingsCreate.java
new file mode 100644
index 00000000..41b20a47
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/embeddings/EmbeddingsCreate.java
@@ -0,0 +1,51 @@
+// 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 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);
+ }
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/files/FilesManage.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/files/FilesManage.java
new file mode 100644
index 00000000..efb04a21
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/files/FilesManage.java
@@ -0,0 +1,65 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.files;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.types.files.DeletionStatus;
+import com.alibaba.dashscope.types.files.FileList;
+import com.alibaba.dashscope.types.files.FileObject;
+import com.alibaba.dashscope.types.files.FileUploadParams;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+/**
+ * File management: upload -> list -> get -> delete. Translation of the Python blueprint example
+ * 01_atomic_capabilities/files/files.py.
+ *
+ * Creates a small temporary JSONL file locally so the example is self-contained.
+ */
+public final class FilesManage {
+
+ public static void main(String[] args) throws Exception {
+ // Build a small local file to upload
+ Path filePath = Files.createTempFile("dashscope-example", ".jsonl");
+ Files.write(
+ filePath,
+ "{\"prompt\": \"你好\", \"completion\": \"你好!有什么可以帮你?\"}\n".getBytes(StandardCharsets.UTF_8));
+
+ try (DashScopeClient client = ExampleSupport.client()) {
+ // Upload
+ System.out.println("----- upload file -----");
+ FileObject uploaded =
+ client
+ .files()
+ .upload(
+ FileUploadParams.builder()
+ .file(filePath)
+ .purpose(FileUploadParams.PURPOSE_FINE_TUNE)
+ .description("example upload")
+ .build());
+ System.out.println("file_id: " + uploaded.getFileId() + ", name: " + uploaded.getName());
+
+ // List files
+ System.out.println("----- list files -----");
+ FileList files = client.files().list(1, 10);
+ files.getFiles().stream()
+ .limit(5)
+ .forEach(
+ item ->
+ System.out.println("file_id=" + item.getFileId() + ", name=" + item.getName()));
+
+ // Get one file
+ System.out.println("----- get file -----");
+ FileObject item = client.files().get(uploaded.getFileId());
+ System.out.println("file_id=" + item.getFileId() + ", name=" + item.getName());
+
+ // Delete the uploaded file
+ System.out.println("----- delete file -----");
+ DeletionStatus deleted = client.files().delete(uploaded.getFileId());
+ System.out.println("deleted: " + deleted.isDeleted());
+ } finally {
+ Files.deleteIfExists(filePath);
+ }
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/finetunes/FineTunesCreate.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/finetunes/FineTunesCreate.java
new file mode 100644
index 00000000..22a04142
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/finetunes/FineTunesCreate.java
@@ -0,0 +1,77 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.finetunes;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.types.finetunes.FineTune;
+import com.alibaba.dashscope.types.finetunes.FineTuneList;
+
+/**
+ * Fine-tuning: list jobs and get one job; the full create -> wait -> delete lifecycle is shown
+ * commented out. Translation of the Python blueprint example
+ * 01_atomic_capabilities/fine_tuning/fine_tunes.py.
+ *
+ *
The read-only list/get sections run as-is. Uncomment the creation section after uploading a
+ * training file (see {@code FilesManage}) and setting {@code DASHSCOPE_TRAINING_FILE_ID}.
+ */
+public final class FineTunesCreate {
+
+ public static void main(String[] args) throws Exception {
+ try (DashScopeClient client = ExampleSupport.client()) {
+ // List fine-tuning jobs (paged)
+ System.out.println("----- list fine-tunes -----");
+ FineTuneList page = client.fineTunes().list(1, 10);
+ System.out.println("total: " + page.getTotalCount());
+ for (FineTune job : page.getJobs()) {
+ System.out.println(
+ "job_id="
+ + job.getJobId()
+ + ", status="
+ + job.getStatus()
+ + ", model="
+ + job.getFinetunedModel());
+ }
+
+ // Get one job by ID (uses the first job of the list above)
+ if (!page.getJobs().isEmpty()) {
+ System.out.println("----- get fine-tune -----");
+ FineTune job = client.fineTunes().get(page.getJobs().get(0).getJobId());
+ System.out.println(
+ "job_id="
+ + job.getJobId()
+ + ", status="
+ + job.getStatus()
+ + ", finished="
+ + job.isFinished());
+ }
+
+ // Full lifecycle: create -> wait -> delete. Uncomment after setting
+ // DASHSCOPE_TRAINING_FILE_ID to an uploaded file ID.
+ //
+ // String model = System.getenv().getOrDefault("DASHSCOPE_MODEL", "qwen-turbo");
+ // String trainingFileId = System.getenv("DASHSCOPE_TRAINING_FILE_ID");
+ //
+ // System.out.println("----- create fine-tune -----");
+ // FineTune created =
+ // client.fineTunes().create(
+ // com.alibaba.dashscope.types.finetunes.FineTuneCreateParams.builder()
+ // .model(model)
+ // .trainingFileIds(java.util.Collections.singletonList(trainingFileId))
+ // .mode("sft")
+ // .hyperParameters(java.util.Collections.singletonMap("n_epochs", 2))
+ // .finetunedModel("my-finetuned-model")
+ // .build());
+ // System.out.println("created job_id=" + created.getJobId());
+ //
+ // System.out.println("----- wait fine-tune -----");
+ // FineTune finalJob =
+ // client.fineTunes().wait(created.getJobId(),
+ // com.alibaba.dashscope.RequestOptions.NONE);
+ // System.out.println(
+ // "status=" + finalJob.getStatus() + ", succeeded=" + finalJob.isSucceeded());
+ //
+ // System.out.println("----- delete fine-tune -----");
+ // client.fineTunes().delete(created.getJobId());
+ }
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/images/ImagesGenerate.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/images/ImagesGenerate.java
new file mode 100644
index 00000000..29d9db6d
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/images/ImagesGenerate.java
@@ -0,0 +1,80 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.images;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.RequestOptions;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.resources.jobs.Job;
+import com.alibaba.dashscope.types.common.Page;
+import com.alibaba.dashscope.types.images.ImageGenerateParams;
+
+/**
+ * Image generation (wanx series): one-call generate (submit + wait), then the manual async-task
+ * submit/wait/fetch flow, then list tasks. Translation of the Python blueprint example
+ * 01_atomic_capabilities/image_video_synthesis/images.py.
+ */
+public final class ImagesGenerate {
+
+ public static void main(String[] args) throws Exception {
+ String model = System.getenv().getOrDefault("DASHSCOPE_MODEL", "wanx2.1-t2i-turbo");
+ String prompt = "一间有着精致窗户的花店,漂亮的木质门,摆放着花朵";
+
+ try (DashScopeClient client = ExampleSupport.client()) {
+ // One-call generate: submits the task and waits for the result
+ System.out.println("----- generate (submit + wait) -----");
+ Job job =
+ client
+ .images()
+ .generate(
+ ImageGenerateParams.builder()
+ .model(model)
+ .prompt(prompt)
+ .n(1)
+ .size("1024*1024")
+ .build());
+ if (job.isSucceeded()) {
+ for (String url : job.getImageUrls()) {
+ System.out.println("image url: " + url);
+ }
+ } else {
+ System.out.println("job failed: " + job.getOutput());
+ }
+
+ // Manual async-task flow: submit first, then wait/fetch by task_id
+ System.out.println("----- jobs.create + wait + fetch -----");
+ Job pending =
+ client
+ .images()
+ .jobs()
+ .create(
+ ImageGenerateParams.builder()
+ .model(model)
+ .prompt(prompt)
+ .n(1)
+ .size("1024*1024")
+ .build());
+ if (pending.getOutput() == null) {
+ throw new IllegalStateException("pending.getOutput() is null");
+ }
+ String taskId = pending.getTaskId();
+ System.out.println("submitted task_id: " + taskId);
+
+ Job finished = client.images().jobs().wait(taskId, RequestOptions.NONE);
+ System.out.println("wait finished, succeeded: " + finished.isSucceeded());
+
+ Job snapshot = client.images().jobs().fetch(taskId, RequestOptions.NONE);
+ System.out.println("fetch output: " + snapshot.getOutput());
+
+ // List historical tasks
+ System.out.println("----- jobs.list -----");
+ Page result = client.images().jobs().list(null, RequestOptions.NONE);
+ System.out.println("total tasks: " + result.getTotalCount());
+ result.getItems().stream()
+ .limit(3)
+ .forEach(
+ task ->
+ System.out.println(
+ "task_id=" + task.getTaskId() + ", status=" + task.getTaskStatus()));
+ }
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/models/ModelsList.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/models/ModelsList.java
new file mode 100644
index 00000000..ae954c69
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/models/ModelsList.java
@@ -0,0 +1,41 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.models;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.RequestOptions;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.types.models.Model;
+import com.alibaba.dashscope.types.models.ModelList;
+
+/**
+ * Model catalog: paged list, provider-filtered list, and get-by-name. Translation of the Python
+ * blueprint example 01_atomic_capabilities/models/models.py.
+ */
+public final class ModelsList {
+
+ public static void main(String[] args) throws Exception {
+ String model = System.getenv().getOrDefault("DASHSCOPE_MODEL", "qwen3.8-max");
+
+ try (DashScopeClient client = ExampleSupport.client()) {
+ // List models (paged)
+ System.out.println("----- list models -----");
+ ModelList page = client.models().list(1, 10);
+ System.out.println("total: " + page.getTotalCount() + ", page " + page.getPageNo());
+ for (Model item : page.getModels()) {
+ System.out.println("model: " + item.getModel());
+ }
+
+ // List only Model Studio (Bailian) models
+ System.out.println("----- list models (provider=Bailian) -----");
+ page = client.models().list(1, 10, "Bailian", RequestOptions.NONE);
+ page.getModels().stream()
+ .limit(5)
+ .forEach(item -> System.out.println("model: " + item.getModel()));
+
+ // Get one model by name
+ System.out.println("----- get model -----");
+ Model item = client.models().get(model);
+ System.out.println("model: " + item.getModel());
+ }
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/multimodal/MultimodalChatCreate.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/multimodal/MultimodalChatCreate.java
new file mode 100644
index 00000000..8e9a3116
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/multimodal/MultimodalChatCreate.java
@@ -0,0 +1,72 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.multimodal;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.types.common.ResponseStream;
+import com.alibaba.dashscope.types.multimodal.ContentPart;
+import com.alibaba.dashscope.types.multimodal.MultimodalChatChunk;
+import com.alibaba.dashscope.types.multimodal.MultimodalChatCompletion;
+import com.alibaba.dashscope.types.multimodal.MultimodalChatCreateParams;
+import com.alibaba.dashscope.types.multimodal.MultimodalChoice;
+import com.alibaba.dashscope.types.multimodal.MultimodalMessage;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Multimodal chat (qwen-vl image understanding): non-streaming and streaming. Translation of the
+ * Python blueprint example 01_atomic_capabilities/multimodal_vision/multimodal_chat.py.
+ */
+public final class MultimodalChatCreate {
+
+ public static void main(String[] args) throws Exception {
+ String model = System.getenv().getOrDefault("DASHSCOPE_MODEL", "qwen3-vl-plus");
+ // Replace with your own image URL (must be publicly accessible)
+ String imageUrl =
+ "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/"
+ + "zh-CN/20241022/emyrja/dog_and_girl.jpeg";
+ List messages =
+ Collections.singletonList(
+ MultimodalMessage.user(
+ Arrays.asList(ContentPart.image(imageUrl), ContentPart.text("图中描绘的是什么景象?"))));
+
+ try (DashScopeClient client = ExampleSupport.client()) {
+ // Non-streaming
+ System.out.println("----- non-streaming request -----");
+ MultimodalChatCompletion resp =
+ client
+ .multimodal()
+ .chat()
+ .create(MultimodalChatCreateParams.builder().model(model).messages(messages).build());
+ System.out.println(resp.outputText());
+ System.out.println(
+ "usage: "
+ + resp.getUsage().getTotalTokens()
+ + " tokens, request_id: "
+ + resp.getRequestId());
+
+ // Streaming
+ System.out.println("----- streaming request -----");
+ try (ResponseStream stream =
+ client
+ .multimodal()
+ .chat()
+ .createStreaming(
+ MultimodalChatCreateParams.builder().model(model).messages(messages).build())) {
+ for (MultimodalChatChunk chunk : stream) {
+ MultimodalChoice choice = chunk.firstChoice();
+ if (choice == null || choice.getMessage() == null) {
+ continue;
+ }
+ String text = choice.getMessage().text();
+ if (!text.isEmpty()) {
+ System.out.print(text);
+ System.out.flush();
+ }
+ }
+ }
+ System.out.println();
+ }
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/rerank/RerankCreate.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/rerank/RerankCreate.java
new file mode 100644
index 00000000..6efd682d
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/rerank/RerankCreate.java
@@ -0,0 +1,51 @@
+// 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());
+ }
+ }
+}
diff --git a/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/videos/VideosGenerate.java b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/videos/VideosGenerate.java
new file mode 100644
index 00000000..2c30a02a
--- /dev/null
+++ b/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/videos/VideosGenerate.java
@@ -0,0 +1,69 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.atomic.videos;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.RequestOptions;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.resources.jobs.Job;
+import com.alibaba.dashscope.types.common.Page;
+import com.alibaba.dashscope.types.videos.VideoGenerateParams;
+
+/**
+ * Video generation (wan series): one-call generate (submit + wait), then the manual async-task
+ * submit/wait/fetch flow, then list tasks. Translation of the Python blueprint example
+ * 01_atomic_capabilities/image_video_synthesis/videos.py.
+ *
+ * Note: video-generation tasks take a while; please be patient.
+ */
+public final class VideosGenerate {
+
+ public static void main(String[] args) throws Exception {
+ String model = System.getenv().getOrDefault("DASHSCOPE_MODEL", "wan2.7-t2v");
+ String prompt = "一只小猫在月光下奔跑";
+
+ try (DashScopeClient client = ExampleSupport.client()) {
+ // One-call generate: submits the task and waits for the result
+ System.out.println("----- generate (submit + wait) -----");
+ Job job =
+ client
+ .videos()
+ .generate(VideoGenerateParams.builder().model(model).prompt(prompt).build());
+ if (job.isSucceeded()) {
+ System.out.println("video url: " + job.getVideoUrl());
+ } else {
+ System.out.println("job failed: " + job.getOutput());
+ }
+
+ // Manual async-task flow: submit first, then wait/fetch by task_id
+ System.out.println("----- jobs.create + wait + fetch -----");
+ Job pending =
+ client
+ .videos()
+ .jobs()
+ .create(VideoGenerateParams.builder().model(model).prompt(prompt).build());
+ if (pending.getOutput() == null) {
+ throw new IllegalStateException("pending.getOutput() is null");
+ }
+ String taskId = pending.getTaskId();
+ System.out.println("submitted task_id: " + taskId);
+
+ Job finished = client.videos().jobs().wait(taskId, RequestOptions.NONE);
+ System.out.println("wait finished, succeeded: " + finished.isSucceeded());
+ System.out.println("video url: " + finished.getVideoUrl());
+
+ Job snapshot = client.videos().jobs().fetch(taskId, RequestOptions.NONE);
+ System.out.println("fetch output: " + snapshot.getOutput());
+
+ // List historical tasks
+ System.out.println("----- jobs.list -----");
+ Page result = client.videos().jobs().list(null, RequestOptions.NONE);
+ System.out.println("total tasks: " + result.getTotalCount());
+ result.getItems().stream()
+ .limit(3)
+ .forEach(
+ task ->
+ System.out.println(
+ "task_id=" + task.getTaskId() + ", status=" + task.getTaskStatus()));
+ }
+ }
+}
diff --git a/examples/02_advanced_engineering/com/alibaba/dashscope/examples/engineering/cache/ClientSideCache.java b/examples/02_advanced_engineering/com/alibaba/dashscope/examples/engineering/cache/ClientSideCache.java
new file mode 100644
index 00000000..361b896a
--- /dev/null
+++ b/examples/02_advanced_engineering/com/alibaba/dashscope/examples/engineering/cache/ClientSideCache.java
@@ -0,0 +1,186 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.engineering.cache;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.types.completions.ChatCompletionCreateParams;
+import com.alibaba.dashscope.types.embeddings.EmbeddingCreateParams;
+import com.alibaba.dashscope.types.messages.Message;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.AbstractMap;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Client-side semantic cache: cut token spend by answering repeat / near-repeat questions from
+ * local memory. The query is embedded with {@code client.embeddings()} and compared (cosine
+ * similarity) against the questions already cached; at or above a similarity threshold the stored
+ * answer is returned with no model call at all, below it the query is sent to {@code client.chat()}
+ * and the result is cached. Embedding vectors themselves are memoized by content hash (SHA-256 of
+ * the text), so an exact repeat never re-pays the embedding call either.
+ *
+ * Translation of the Python blueprint example 02_advanced_engineering/client_side_cache.py.
+ *
+ *
The store here is a plain in-memory list; swap in Redis or a vector database for production.
+ * Requires DASHSCOPE_API_KEY because cache misses call the real embeddings + chat endpoints.
+ */
+public final class ClientSideCache {
+
+ private static final String EMBED_MODEL = envOr("DASHSCOPE_EMBED_MODEL", "text-embedding-v4");
+ private static final String CHAT_MODEL = envOr("DASHSCOPE_MODEL", "qwen3.7-plus");
+
+ /**
+ * Cosine similarity at or above which two questions are treated as the same and the cached answer
+ * is reused. Tune to your precision/recall trade-off: higher means fewer false hits, lower means
+ * more savings.
+ */
+ private static final double THRESHOLD = 0.90;
+
+ private ClientSideCache() {}
+
+ private static String envOr(String name, String fallback) {
+ String value = System.getenv(name);
+ return value == null || value.isEmpty() ? fallback : value;
+ }
+
+ /** Cosine similarity of two equal-length float vectors. */
+ static double cosine(List a, List b) {
+ double dot = 0.0;
+ double normA = 0.0;
+ double normB = 0.0;
+ for (int i = 0; i < a.size(); i++) {
+ double x = a.get(i);
+ double y = b.get(i);
+ dot += x * y;
+ normA += x * x;
+ normB += y * y;
+ }
+ if (normA == 0.0 || normB == 0.0) {
+ return 0.0;
+ }
+ return dot / (Math.sqrt(normA) * Math.sqrt(normB));
+ }
+
+ /** Content-hash key for the embedding memo: SHA-256 hex of the exact text. */
+ private static String contentKey(String text) {
+ MessageDigest digest;
+ try {
+ digest = MessageDigest.getInstance("SHA-256");
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException("SHA-256 not available", e);
+ }
+ byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));
+ StringBuilder out = new StringBuilder(hash.length * 2);
+ for (byte b : hash) {
+ out.append(Character.forDigit((b >> 4) & 0xF, 16)).append(Character.forDigit(b & 0xF, 16));
+ }
+ return out.toString();
+ }
+
+ /** One cached question: its embedding plus the answer the model gave. */
+ private static final class CacheEntry {
+ final List embedding;
+ final String question;
+ final String answer;
+
+ CacheEntry(List embedding, String question, String answer) {
+ this.embedding = embedding;
+ this.question = question;
+ this.answer = answer;
+ }
+ }
+
+ /** In-memory semantic cache backed by DashScope embeddings. */
+ static final class SemanticCache {
+ private final DashScopeClient client;
+ private final double threshold;
+ private final List entries = new ArrayList<>();
+ private final Map> embeddingMemo = new HashMap<>();
+ int hits;
+ int misses;
+
+ SemanticCache(DashScopeClient client, double threshold) {
+ this.client = client;
+ this.threshold = threshold;
+ }
+
+ private List embed(String text) {
+ return embeddingMemo.computeIfAbsent(
+ contentKey(text),
+ key ->
+ client
+ .embeddings()
+ .create(EmbeddingCreateParams.builder().model(EMBED_MODEL).text(text).build())
+ .getEmbeddings()
+ .get(0)
+ .getEmbedding());
+ }
+
+ private String chat(String question) {
+ return client
+ .chat()
+ .completions()
+ .create(
+ ChatCompletionCreateParams.builder()
+ .model(CHAT_MODEL)
+ .messages(Collections.singletonList(Message.user(question)))
+ .build())
+ .outputText();
+ }
+
+ /** Return the answer for {@code question}; {@code true} when served from cache. */
+ Map.Entry ask(String question) {
+ List queryVector = embed(question);
+ double bestSimilarity = -1.0;
+ String bestAnswer = null;
+ for (CacheEntry entry : entries) {
+ double similarity = cosine(queryVector, entry.embedding);
+ if (similarity > bestSimilarity) {
+ bestSimilarity = similarity;
+ bestAnswer = entry.answer;
+ }
+ }
+ if (bestAnswer != null && bestSimilarity >= threshold) {
+ hits++;
+ return new AbstractMap.SimpleImmutableEntry<>(bestAnswer, true);
+ }
+ // Miss: pay for one real completion, then remember it.
+ String answer = chat(question);
+ entries.add(new CacheEntry(queryVector, question, answer));
+ misses++;
+ return new AbstractMap.SimpleImmutableEntry<>(answer, false);
+ }
+ }
+
+ /** Ask a few questions and show which ones hit the cache. */
+ public static void main(String[] args) {
+ try (DashScopeClient client = ExampleSupport.client()) {
+ SemanticCache cache = new SemanticCache(client, THRESHOLD);
+ String[] questions = {
+ "用一句话介绍杭州",
+ "用一句话介绍杭州", // exact repeat -> guaranteed cache hit
+ "请简单介绍一下杭州这座城市", // near-duplicate -> likely hit
+ "用一句话介绍北京", // different meaning -> cache miss
+ };
+ for (String question : questions) {
+ Map.Entry result = cache.ask(question);
+ String tag = result.getValue() ? "CACHE HIT " : "CACHE MISS";
+ System.out.println("[" + tag + "] Q: " + question);
+ System.out.println(" A: " + result.getKey());
+ }
+ System.out.println(
+ "----- hits="
+ + cache.hits
+ + ", misses="
+ + cache.misses
+ + ", real chat calls="
+ + cache.misses
+ + " -----");
+ }
+ }
+}
diff --git a/examples/02_advanced_engineering/com/alibaba/dashscope/examples/engineering/resilience/CircuitBreakerRetry.java b/examples/02_advanced_engineering/com/alibaba/dashscope/examples/engineering/resilience/CircuitBreakerRetry.java
new file mode 100644
index 00000000..edd35508
--- /dev/null
+++ b/examples/02_advanced_engineering/com/alibaba/dashscope/examples/engineering/resilience/CircuitBreakerRetry.java
@@ -0,0 +1,298 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.engineering.resilience;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.errors.ApiConnectionException;
+import com.alibaba.dashscope.errors.DashScopeException;
+import com.alibaba.dashscope.types.completions.ChatCompletion;
+import com.alibaba.dashscope.types.completions.ChatCompletionCreateParams;
+import com.alibaba.dashscope.types.messages.Message;
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpServer;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Function;
+
+/**
+ * High availability: cross-region failover guarded by a hand-rolled circuit breaker, layered on top
+ * of the SDK's built-in retry ({@code ClientOptions.maxRetries} / {@code RequestOptions.maxRetries}
+ * already absorb transient 429/5xx within a region — the breaker exists to fail
+ * across regions when a whole region keeps erroring).
+ *
+ * Translation of the Python blueprint example 02_advanced_engineering/circuit_breaker_retry.py.
+ *
+ *
The demo runs fully offline and deterministically: per-region JDK {@link HttpServer} instances
+ * play the gateways (the primary region 503s, the secondary 200s). Drop the {@code baseUrl}
+ * override to hit the real gateways — note that API keys are region-specific.
+ */
+public final class CircuitBreakerRetry {
+
+ /** Fail over across these regions, in order. */
+ private static final List REGIONS = Arrays.asList("cn-beijing", "ap-southeast-1");
+
+ private enum BreakerState {
+ CLOSED,
+ OPEN,
+ HALF_OPEN;
+
+ @Override
+ public String toString() {
+ return name().toLowerCase();
+ }
+ }
+
+ /** Minimal per-region circuit breaker (CLOSED/OPEN/HALF_OPEN). */
+ static final class CircuitBreaker {
+ private final int failureThreshold;
+ private final double resetTimeoutSeconds;
+ private BreakerState state = BreakerState.CLOSED;
+ private int failureCount;
+ private long openedAtNanos;
+
+ CircuitBreaker(int failureThreshold, double resetTimeoutSeconds) {
+ this.failureThreshold = failureThreshold;
+ this.resetTimeoutSeconds = resetTimeoutSeconds;
+ }
+
+ /** Whether a request may be attempted right now. */
+ synchronized boolean allow() {
+ if (state == BreakerState.OPEN) {
+ long elapsedNanos = System.nanoTime() - openedAtNanos;
+ if (elapsedNanos >= (long) (resetTimeoutSeconds * 1_000_000_000L)) {
+ state = BreakerState.HALF_OPEN;
+ return true;
+ }
+ return false;
+ }
+ return true;
+ }
+
+ synchronized void recordSuccess() {
+ failureCount = 0;
+ state = BreakerState.CLOSED;
+ }
+
+ synchronized void recordFailure() {
+ failureCount++;
+ if (state == BreakerState.HALF_OPEN || failureCount >= failureThreshold) {
+ state = BreakerState.OPEN;
+ openedAtNanos = System.nanoTime();
+ }
+ }
+
+ synchronized BreakerState state() {
+ return state;
+ }
+ }
+
+ /** Connection errors and 5xx / 429 are worth failing over on. */
+ private static boolean isRetryable(DashScopeException exc) {
+ if (exc instanceof ApiConnectionException) {
+ return true;
+ }
+ Integer status = exc.getStatusCode();
+ return status != null && (status >= 500 || status == 429);
+ }
+
+ /** One answered call: which region served it plus the completion itself. */
+ static final class ChatOutcome {
+ final String region;
+ final ChatCompletion completion;
+
+ ChatOutcome(String region, ChatCompletion completion) {
+ this.region = region;
+ this.completion = completion;
+ }
+ }
+
+ /** Try each region in order, guarded by a circuit breaker. */
+ static final class MultiRegionClient implements AutoCloseable {
+ private final List regions;
+ private final Function clientFactory;
+ // Written only in the constructor and held in a final field, so safely published as-is.
+ private final Map breakers = new LinkedHashMap<>();
+ // chat() may be called from a request pool (CircuitBreaker's own methods are synchronized for
+ // exactly that reason), so this lazily filled cache must be thread-safe too: a racing
+ // computeIfAbsent on a plain map can drop an entry, and that client would then never be closed
+ // because close() only sees what the map still holds. This makes concurrent creation safe, not
+ // concurrent creation-and-close: close() must still run after all chat() calls have returned.
+ private final Map clients = new ConcurrentHashMap<>();
+
+ MultiRegionClient(
+ List regions,
+ Function clientFactory,
+ int failureThreshold,
+ double resetTimeoutSeconds) {
+ this.regions = new ArrayList<>(regions);
+ this.clientFactory = clientFactory;
+ for (String region : regions) {
+ breakers.put(region, new CircuitBreaker(failureThreshold, resetTimeoutSeconds));
+ }
+ }
+
+ private DashScopeClient client(String region) {
+ return clients.computeIfAbsent(region, clientFactory);
+ }
+
+ /** Return the outcome from the first healthy region. */
+ ChatOutcome chat(String prompt, String model) {
+ DashScopeException lastError = null;
+ List openCircuits = new ArrayList<>();
+ for (String region : regions) {
+ CircuitBreaker breaker = breakers.get(region);
+ if (!breaker.allow()) {
+ openCircuits.add(region);
+ System.out.println(" [" + region + "] circuit OPEN -> skip");
+ continue;
+ }
+ try {
+ ChatCompletion completion =
+ client(region)
+ .chat()
+ .completions()
+ .create(
+ ChatCompletionCreateParams.builder()
+ .model(model)
+ .messages(Collections.singletonList(Message.user(prompt)))
+ .build());
+ breaker.recordSuccess();
+ System.out.println(" [" + region + "] OK (circuit " + breaker.state() + ")");
+ return new ChatOutcome(region, completion);
+ } catch (DashScopeException exc) {
+ lastError = exc;
+ boolean retryable = isRetryable(exc);
+ if (retryable) {
+ breaker.recordFailure();
+ }
+ System.out.println(
+ " ["
+ + region
+ + "] "
+ + exc.getClass().getSimpleName()
+ + " status="
+ + exc.getStatusCode()
+ + " retryable="
+ + retryable
+ + " -> circuit "
+ + breaker.state());
+ if (!retryable) {
+ throw exc; // a 4xx is a real bug; do not mask it
+ }
+ }
+ }
+ if (lastError == null) {
+ // Every region was skipped by an open circuit, so no call was attempted and there is no
+ // underlying failure to report; name the open circuits instead of printing "...: null".
+ throw new ApiConnectionException(
+ "all regions unavailable, circuits open: " + openCircuits, null);
+ }
+ throw new ApiConnectionException(
+ "all regions failed: "
+ + lastError
+ + (openCircuits.isEmpty() ? "" : " (skipped, circuits open: " + openCircuits + ")"),
+ lastError);
+ }
+
+ @Override
+ public void close() {
+ clients.values().forEach(DashScopeClient::close);
+ }
+ }
+
+ // ---- offline gateways: one canned HTTP server per region ---- //
+
+ private static void respond(HttpExchange exchange, int status, String json) throws IOException {
+ byte[] body = json.getBytes(StandardCharsets.UTF_8);
+ exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
+ exchange.sendResponseHeaders(status, body.length);
+ try (OutputStream out = exchange.getResponseBody()) {
+ out.write(body);
+ }
+ exchange.close();
+ }
+
+ /**
+ * Offline gateway: the primary region 503s, every other 200s. The handler closes over {@code
+ * region} instead of sniffing the request host, so it stays correct when a workspace changes the
+ * gateway.
+ */
+ private static HttpServer startGateway(String region, boolean primary) throws IOException {
+ HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ server.createContext(
+ "/",
+ exchange -> {
+ if (primary) {
+ respond(
+ exchange,
+ 503,
+ "{\"code\":\"ServiceUnavailable\",\"message\":\"mocked regional outage\"}");
+ return;
+ }
+ respond(
+ exchange,
+ 200,
+ "{\"output\":{\"choices\":[{\"finish_reason\":\"stop\",\"message\":"
+ + "{\"role\":\"assistant\",\"content\":\"来自 "
+ + region
+ + " 的应答\"}}]},"
+ + "\"usage\":{\"total_tokens\":10},"
+ + "\"request_id\":\"mock-"
+ + region
+ + "\"}");
+ });
+ server.start();
+ return server;
+ }
+
+ /** Drive three calls to show the breaker opening and failing over. */
+ public static void main(String[] args) throws Exception {
+ List servers = new ArrayList<>();
+ Map gatewayUrls = new LinkedHashMap<>();
+ for (String region : REGIONS) {
+ // Offline demo: injected mock gateway + dummy creds. Real regional use needs a
+ // region-specific workspace AND API key.
+ HttpServer server = startGateway(region, region.equals(REGIONS.get(0)));
+ servers.add(server);
+ gatewayUrls.put(region, "http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1");
+ }
+ try {
+ MultiRegionClient mc =
+ new MultiRegionClient(
+ REGIONS,
+ region ->
+ DashScopeClient.builder()
+ .apiKey("sk-mock")
+ .region(region)
+ .baseUrl(gatewayUrls.get(region))
+ .maxRetries(0) // keep the demo instant; SDK retry is a separate layer
+ .build(),
+ 2,
+ 30.0);
+ try {
+ // Three calls show the breaker progressing CLOSED -> OPEN: the first two probe the dead
+ // primary and fail over; the third sees the primary OPEN and goes straight to the
+ // healthy region.
+ for (int i = 1; i <= 3; i++) {
+ System.out.println("----- call " + i + " -----");
+ ChatOutcome outcome = mc.chat("你好", "qwen3.7-plus");
+ System.out.println(" served by: " + outcome.region);
+ System.out.println(" answer : " + outcome.completion.outputText());
+ System.out.println(" request_id: " + outcome.completion.getRequestId());
+ }
+ } finally {
+ mc.close();
+ }
+ } finally {
+ servers.forEach(server -> server.stop(0));
+ }
+ }
+}
diff --git a/examples/02_advanced_engineering/com/alibaba/dashscope/examples/engineering/testing/LocalMockDebugging.java b/examples/02_advanced_engineering/com/alibaba/dashscope/examples/engineering/testing/LocalMockDebugging.java
new file mode 100644
index 00000000..5ac67c5d
--- /dev/null
+++ b/examples/02_advanced_engineering/com/alibaba/dashscope/examples/engineering/testing/LocalMockDebugging.java
@@ -0,0 +1,140 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.engineering.testing;
+
+import com.alibaba.dashscope.ClientOptions;
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.errors.DashScopeException;
+import com.alibaba.dashscope.types.completions.ChatCompletion;
+import com.alibaba.dashscope.types.completions.ChatCompletionCreateParams;
+import com.alibaba.dashscope.types.messages.Message;
+import com.sun.net.httpserver.HttpServer;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.Collections;
+
+/**
+ * Local mock debugging: develop against a canned gateway with zero network calls (beyond loopback)
+ * and zero token cost. A JDK {@link HttpServer} serves canned chat envelopes in-process; pointing
+ * the client at it via {@code builder.baseUrl(...)} (equivalently {@code -Ddashscope.base.url=...})
+ * exercises both the success path and the error paths (bad parameter, rate limit, content filter)
+ * deterministically — before spending a single real token.
+ *
+ * Translation of the Python blueprint example 02_advanced_engineering/local_mock_debugging.py.
+ *
+ *
Drop the {@code baseUrl} override and the exact same calling code runs against the real
+ * gateway.
+ */
+public final class LocalMockDebugging {
+
+ private LocalMockDebugging() {}
+
+ /** The native chat-completion envelope the real gateway returns. */
+ private static String chatEnvelope(String text, String requestId) {
+ return "{\"output\":{\"choices\":[{\"finish_reason\":\"stop\",\"message\":"
+ + "{\"role\":\"assistant\",\"content\":\""
+ + text
+ + "\"}}]},"
+ + "\"usage\":{\"input_tokens\":8,\"output_tokens\":4,\"total_tokens\":12},"
+ + "\"request_id\":\""
+ + requestId
+ + "\"}";
+ }
+
+ /**
+ * Route by request body so one server serves many scenarios: send a message containing {@code
+ * trigger-error} to exercise the error path; anything else returns a normal completion.
+ */
+ private static HttpServer startMockGateway() throws IOException {
+ HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ server.createContext(
+ "/",
+ exchange -> {
+ String body = new String(readAll(exchange.getRequestBody()), StandardCharsets.UTF_8);
+ byte[] payload;
+ int status;
+ if (body.contains("trigger-error")) {
+ status = 400;
+ payload =
+ "{\"code\":\"InvalidParameter\",\"message\":\"mocked bad request\"}"
+ .getBytes(StandardCharsets.UTF_8);
+ } else {
+ status = 200;
+ payload =
+ chatEnvelope("你好,这是本地 Mock 返回。", "mock-req-1").getBytes(StandardCharsets.UTF_8);
+ }
+ exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
+ exchange.sendResponseHeaders(status, payload.length);
+ try (OutputStream out = exchange.getResponseBody()) {
+ out.write(payload);
+ }
+ exchange.close();
+ });
+ server.start();
+ return server;
+ }
+
+ /** A client whose whole exchange is served in-process; the key is never validated. */
+ private static DashScopeClient mockClient(String baseUrl) {
+ return DashScopeClient.builder().apiKey("sk-mock").baseUrl(baseUrl).build();
+ }
+
+ private static ChatCompletion chat(DashScopeClient client, String content) {
+ return client
+ .chat()
+ .completions()
+ .create(
+ ChatCompletionCreateParams.builder()
+ .model("qwen3.7-plus")
+ .messages(Collections.singletonList(Message.user(content)))
+ .build());
+ }
+
+ public static void main(String[] args) throws Exception {
+ HttpServer server = startMockGateway();
+ try {
+ String baseUrl = "http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1";
+ try (DashScopeClient client = mockClient(baseUrl)) {
+ System.out.println("----- mocked success -----");
+ ChatCompletion resp = chat(client, "你好");
+ System.out.println("output_text : " + resp.outputText());
+ System.out.println("request_id : " + resp.getRequestId());
+ System.out.println("total_tokens: " + resp.getUsage().getTotalTokens());
+
+ // Error path 1: the SDK raises a typed exception by default.
+ System.out.println("----- mocked error (raiseOnError=true) -----");
+ try {
+ chat(client, "trigger-error");
+ } catch (DashScopeException exc) {
+ System.out.println("caught : " + exc.getClass().getSimpleName());
+ System.out.println("code : " + exc.getCode());
+ System.out.println("status_code : " + exc.getStatusCode());
+ System.out.println("message : " + exc.getMessage());
+ }
+
+ // Error path 2: opt out of raising to inspect the error inline. The derived client
+ // shares the parent's connection pool and must not outlive it.
+ System.out.println("----- mocked error (raiseOnError=false) -----");
+ DashScopeClient lenient =
+ client.withOptions(ClientOptions.builder().raiseOnError(false).build());
+ ChatCompletion err = chat(lenient, "trigger-error");
+ System.out.println("is_error : " + err.isError());
+ System.out.println("code : " + err.getCode());
+ System.out.println("message : " + err.getMessage());
+ }
+ } finally {
+ server.stop(0);
+ }
+ }
+
+ private static byte[] readAll(java.io.InputStream in) throws IOException {
+ java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
+ byte[] buf = new byte[8192];
+ int n;
+ while ((n = in.read(buf)) >= 0) {
+ out.write(buf, 0, n);
+ }
+ return out.toByteArray();
+ }
+}
diff --git a/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/AgentStudioDeploymentsManage.java b/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/AgentStudioDeploymentsManage.java
new file mode 100644
index 00000000..d70826f1
--- /dev/null
+++ b/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/AgentStudioDeploymentsManage.java
@@ -0,0 +1,85 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.recipes.agentstudio;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.applications.agentstudio.AgentStudioClient;
+import com.alibaba.dashscope.applications.agentstudio.message.ClientEvents;
+import com.alibaba.dashscope.applications.agentstudio.model.Deployment;
+import com.alibaba.dashscope.applications.agentstudio.model.DeploymentRun;
+import com.alibaba.dashscope.applications.agentstudio.param.DeploymentAgentParam;
+import com.alibaba.dashscope.applications.agentstudio.param.DeploymentCreateParam;
+import com.alibaba.dashscope.applications.agentstudio.param.DeploymentRunListParam;
+import com.alibaba.dashscope.applications.agentstudio.param.DeploymentScheduleParam;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import java.util.Collections;
+
+/**
+ * Agent recipe: create and run a Managed Agent deployment.
+ *
+ *
A deployment wraps an agent with a cron schedule and a bootstrap event list, so the agent runs
+ * unattended (here: weekday mornings, Asia/Shanghai). The flow: create deployment -> trigger one
+ * manual run -> list recent runs.
+ *
+ *
AgentStudio is shared by the 2.x and 3.0 SDK generations: {@code client.agentStudio()} lazily
+ * mounts a single shared {@link AgentStudioClient} (workspace and region forward from the client
+ * config), so one {@code DashScopeClient} covers both the 3.0 resources and AgentStudio.
+ *
+ *
Translation of the Python blueprint example 03_agent_recipes/agentstudio_deployments.py.
+ *
+ *
Requires DASHSCOPE_API_KEY; DASHSCOPE_WORKSPACE selects the AgentStudio workspace (defaults to
+ * trial); DASHSCOPE_AGENT_ID must name an existing agent (see {@code AgentStudioQuickStart}).
+ */
+public final class AgentStudioDeploymentsManage {
+
+ /** Placeholder, as in the Python blueprint: point DASHSCOPE_AGENT_ID at a real agent. */
+ private static final String AGENT_ID = envOr("DASHSCOPE_AGENT_ID", "agent_xxx");
+
+ private AgentStudioDeploymentsManage() {}
+
+ private static String envOr(String name, String fallback) {
+ String value = System.getenv(name);
+ return value == null || value.isEmpty() ? fallback : value;
+ }
+
+ /** Create the deployment, fire one manual run, then list recent runs. */
+ public static void main(String[] args) {
+ try (DashScopeClient client =
+ DashScopeClient.builder()
+ .apiKey(ExampleSupport.requireApiKey())
+ .workspace(envOr("DASHSCOPE_WORKSPACE", "trial"))
+ .build()) {
+ AgentStudioClient studio = client.agentStudio();
+
+ Deployment deployment =
+ studio
+ .deployments()
+ .create(
+ DeploymentCreateParam.builder()
+ .name("daily-summary")
+ .description("Generate a daily summary")
+ .agent(DeploymentAgentParam.builder().id(AGENT_ID).build())
+ .schedule(
+ DeploymentScheduleParam.builder()
+ .type(DeploymentScheduleParam.TYPE_CRON)
+ .expression("0 9 * * 1-5")
+ .timezone("Asia/Shanghai")
+ .build())
+ .initialEvents(
+ Collections.singletonList(
+ ClientEvents.userMessage("Summarize yesterday's orders")))
+ .metadata(Collections.singletonMap("biz", "summary"))
+ .build());
+ System.out.println("deployment: " + deployment.getId() + " " + deployment.getStatus());
+
+ DeploymentRun run = studio.deployments().run(deployment.getId());
+ System.out.println("run: " + run.getId() + " " + run.getStatus());
+
+ for (DeploymentRun item :
+ studio
+ .deployments()
+ .listRuns(deployment.getId(), DeploymentRunListParam.builder().limit(20).build())) {
+ System.out.println(item.getId() + " " + item.getTriggerSource() + " " + item.getStatus());
+ }
+ }
+ }
+}
diff --git a/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/AgentStudioDynamicWorkflows.java b/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/AgentStudioDynamicWorkflows.java
new file mode 100644
index 00000000..9c5d44e3
--- /dev/null
+++ b/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/AgentStudioDynamicWorkflows.java
@@ -0,0 +1,125 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.recipes.agentstudio;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.applications.agentstudio.AgentStudioClient;
+import com.alibaba.dashscope.applications.agentstudio.model.Agent;
+import com.alibaba.dashscope.applications.agentstudio.model.Configs.MultiAgentConfig;
+import com.alibaba.dashscope.applications.agentstudio.model.Configs.ReuseWorkflowsConfig;
+import com.alibaba.dashscope.applications.agentstudio.model.Configs.WorkflowConfig;
+import com.alibaba.dashscope.applications.agentstudio.model.Configs.WorkflowInlineAgentsConfig;
+import com.alibaba.dashscope.applications.agentstudio.model.Configs.WorkflowPermissionType;
+import com.alibaba.dashscope.applications.agentstudio.model.Configs.WorkflowResourceReference;
+import com.alibaba.dashscope.applications.agentstudio.model.DynamicWorkflow;
+import com.alibaba.dashscope.applications.agentstudio.param.AgentCreateParam;
+import com.alibaba.dashscope.applications.agentstudio.param.DynamicWorkflowCreateParam;
+import com.alibaba.dashscope.applications.agentstudio.param.DynamicWorkflowListParam;
+import com.alibaba.dashscope.applications.agentstudio.param.DynamicWorkflowUpdateParam;
+import com.alibaba.dashscope.applications.agentstudio.param.DynamicWorkflowVersionListParam;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.google.gson.JsonObject;
+import java.util.Collections;
+
+/**
+ * Create, update, inspect, bind and archive a published Dynamic Workflow.
+ *
+ *
Requires DASHSCOPE_API_KEY and a workspace configured through DASHSCOPE_WORKSPACE or the
+ * client config. DASHSCOPE_AGENTSTUDIO_URL optionally overrides the service endpoint. Agent
+ * Workflow tools initiate execution; this example manages definitions and fixed-version bindings.
+ */
+public final class AgentStudioDynamicWorkflows {
+ /** Manage a definition and bind version 1 to an Agent, then archive both demo resources. */
+ public static void main(String[] args) {
+ try (DashScopeClient client = ExampleSupport.client()) {
+ AgentStudioClient studio = client.agentStudio();
+ JsonObject schema = new JsonObject();
+ schema.addProperty("type", "object");
+ DynamicWorkflow workflow =
+ studio
+ .dynamicWorkflows()
+ .create(
+ DynamicWorkflowCreateParam.builder()
+ .name("echo-workflow")
+ .description("Echo the supplied value")
+ .script(
+ "export const meta={name:'echo-workflow'}; return {value:args.value};")
+ .inputSchema(schema)
+ .build());
+ Agent agent = null;
+ try {
+ studio
+ .dynamicWorkflows()
+ .update(
+ workflow.getId(),
+ DynamicWorkflowUpdateParam.builder()
+ .description("Updated description; script and schema stay unchanged")
+ .build());
+ studio
+ .dynamicWorkflows()
+ .update(
+ workflow.getId(),
+ DynamicWorkflowUpdateParam.builder()
+ .clearDescription(true)
+ .clearInputSchema(true)
+ .build());
+ System.out.println(
+ "latest: " + studio.dynamicWorkflows().retrieve(workflow.getId()).getVersion());
+ DynamicWorkflow fixed = studio.dynamicWorkflows().retrieveVersion(workflow.getId(), 1);
+ System.out.println("fixed: " + fixed.getId() + " version=" + fixed.getVersion());
+ for (DynamicWorkflow item :
+ studio
+ .dynamicWorkflows()
+ .list(
+ DynamicWorkflowListParam.builder().limit(10).includeArchived(false).build())) {
+ System.out.println("workflow: " + item.getId() + " version=" + item.getVersion());
+ }
+ for (DynamicWorkflow item :
+ studio
+ .dynamicWorkflows()
+ .listVersions(
+ workflow.getId(),
+ DynamicWorkflowVersionListParam.builder().limit(10).build())) {
+ System.out.println("published version: " + item.getVersion());
+ }
+
+ WorkflowInlineAgentsConfig inline = new WorkflowInlineAgentsConfig();
+ inline.setType(WorkflowPermissionType.ENABLED);
+ WorkflowConfig creation = new WorkflowConfig();
+ creation.setType(WorkflowPermissionType.ENABLED);
+ creation.setInlineAgents(inline);
+ WorkflowResourceReference binding = new WorkflowResourceReference();
+ binding.setId(workflow.getId());
+ binding.setVersion(1);
+ ReuseWorkflowsConfig reuse = new ReuseWorkflowsConfig();
+ reuse.setType(WorkflowPermissionType.ENABLED);
+ reuse.setWorkflows(Collections.singletonList(binding));
+ MultiAgentConfig multiagent = new MultiAgentConfig();
+ multiagent.setType("coordinator");
+ multiagent.setAgents(Collections.emptyList());
+ multiagent.setWorkflows(creation);
+ multiagent.setReuseWorkflows(reuse);
+ agent =
+ studio
+ .agents()
+ .create(
+ AgentCreateParam.builder()
+ .name("workflow-coordinator")
+ .model("qwen-plus")
+ .multiagent(multiagent)
+ .build());
+ System.out.println("agent: " + agent.getId() + " version=" + agent.getVersion());
+ } finally {
+ try {
+ if (agent != null) {
+ studio.agents().archive(agent.getId());
+ }
+ } finally {
+ DynamicWorkflow archived = studio.dynamicWorkflows().archive(workflow.getId());
+ System.out.println("archived: " + archived.getId() + " " + archived.getArchived());
+ }
+ }
+ }
+ }
+
+ private AgentStudioDynamicWorkflows() {}
+}
diff --git a/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/AgentStudioMemoryStores.java b/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/AgentStudioMemoryStores.java
new file mode 100644
index 00000000..58c5ed11
--- /dev/null
+++ b/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/AgentStudioMemoryStores.java
@@ -0,0 +1,140 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.recipes.agentstudio;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.applications.agentstudio.AgentStudioClient;
+import com.alibaba.dashscope.applications.agentstudio.model.AgentStudioDeletionStatus;
+import com.alibaba.dashscope.applications.agentstudio.model.Memory;
+import com.alibaba.dashscope.applications.agentstudio.model.MemoryStore;
+import com.alibaba.dashscope.applications.agentstudio.model.MemoryVersion;
+import com.alibaba.dashscope.applications.agentstudio.pagination.CursorPage;
+import com.alibaba.dashscope.applications.agentstudio.param.MemoryCreateParam;
+import com.alibaba.dashscope.applications.agentstudio.param.MemoryListParam;
+import com.alibaba.dashscope.applications.agentstudio.param.MemoryStoreCreateParam;
+import com.alibaba.dashscope.applications.agentstudio.param.MemoryStoreListParam;
+import com.alibaba.dashscope.applications.agentstudio.param.MemoryUpdateParam;
+import com.alibaba.dashscope.applications.agentstudio.param.MemoryVersionListParam;
+import com.alibaba.dashscope.examples.ExampleSupport;
+
+/**
+ * Agent recipe: AgentStudio memory stores end-to-end. Flow: create store -> seed memory -> list
+ * with content (view=full, auto-pagination) -> update with optimistic lock -> list versions ->
+ * redact a version -> list stores -> delete store.
+ *
+ *
3.0 port of {@code legacy_2x/AgentStudioMemoryStores.java}: same flow under {@code
+ * com.alibaba.dashscope.applications.agentstudio}, mounted via {@code client.agentStudio()}, plus
+ * the {@code redact()} audit step. Unlike the frozen legacy copy, this file is a compiled example
+ * source and runs in the offline dry-run suite.
+ *
+ *
Requires DASHSCOPE_API_KEY; DASHSCOPE_WORKSPACE selects the AgentStudio workspace (defaults to
+ * trial).
+ */
+public final class AgentStudioMemoryStores {
+
+ private AgentStudioMemoryStores() {}
+
+ private static String envOr(String name, String fallback) {
+ String value = System.getenv(name);
+ return value == null || value.isEmpty() ? fallback : value;
+ }
+
+ /** Run the full memory-store flow. */
+ public static void main(String[] args) {
+ try (DashScopeClient client =
+ DashScopeClient.builder()
+ .apiKey(ExampleSupport.requireApiKey())
+ .workspace(envOr("DASHSCOPE_WORKSPACE", "trial"))
+ .build()) {
+ AgentStudioClient studio = client.agentStudio();
+
+ // 1. Create a store; description is read by the agent - write it for the model.
+ System.out.println("==> creating memory store");
+ MemoryStore store =
+ studio
+ .memoryStores()
+ .create(
+ MemoryStoreCreateParam.builder()
+ .name("demo-preferences")
+ .description("Per-user preferences and project context.")
+ .build());
+ System.out.println(" store_id=" + store.getId());
+
+ // 2. Seed reference material before any session runs.
+ System.out.println("==> seeding memory");
+ Memory memory =
+ studio
+ .memoryStores()
+ .memories()
+ .create(
+ store.getId(),
+ MemoryCreateParam.builder()
+ .path("/formatting_standards.md")
+ .content("All reports use GAAP formatting.")
+ .build());
+ System.out.printf(
+ " memory_id=%s path=%s size=%d%n",
+ memory.getId(), memory.getPath(), memory.getContentSizeBytes());
+
+ // 3. Read back with content (view=full; the default basic is metadata only). Print prefixes
+ // before iterating: the loop auto-paginates and prefixes are per page.
+ System.out.println("==> listing memories (view=full)");
+ CursorPage page =
+ studio
+ .memoryStores()
+ .memories()
+ .list(store.getId(), MemoryListParam.builder().view("full").build());
+ System.out.println(" prefixes=" + page.getPrefixes());
+ for (Memory item : page) {
+ System.out.printf(" %s -> %s%n", item.getPath(), item.getContent());
+ }
+
+ // 4. Update with the optimistic lock (contentSha256 from step 2).
+ System.out.println("==> updating memory");
+ Memory updated =
+ studio
+ .memoryStores()
+ .memories()
+ .update(
+ store.getId(),
+ memory.getId(),
+ MemoryUpdateParam.builder()
+ .content("All reports use GAAP formatting. ISO-8601 dates.")
+ .contentSha256(memory.getContentSha256())
+ .build());
+ System.out.println(" updated_sha=" + updated.getContentSha256());
+
+ // 5. Audit history: every mutation produced a memver_ snapshot (newest first).
+ System.out.println("==> listing memory versions");
+ String firstVersionId = null;
+ for (MemoryVersion version :
+ studio
+ .memoryStores()
+ .memoryVersions()
+ .list(store.getId(), MemoryVersionListParam.builder().build())) {
+ System.out.printf(" version=%s operation=%s%n", version.getId(), version.getOperation());
+ if (firstVersionId == null) {
+ firstVersionId = version.getId();
+ }
+ }
+
+ // 6. Redact one snapshot: path/content/sha/size are cleared, the audit trail stays.
+ if (firstVersionId != null) {
+ System.out.println("==> redacting version " + firstVersionId);
+ MemoryVersion redacted =
+ studio.memoryStores().memoryVersions().redact(store.getId(), firstVersionId);
+ System.out.printf(
+ " redacted_at=%s content=%s%n", redacted.getRedactedAt(), redacted.getContent());
+ }
+
+ // 7. List stores and clean up.
+ System.out.println("==> listing stores");
+ for (MemoryStore item :
+ studio.memoryStores().list(MemoryStoreListParam.builder().limit(20).build())) {
+ System.out.printf(" store=%s name=%s%n", item.getId(), item.getName());
+ }
+ AgentStudioDeletionStatus deleted = studio.memoryStores().delete(store.getId());
+ System.out.println(" deleted=" + deleted.isDeleted());
+ System.out.println("done.");
+ }
+ }
+}
diff --git a/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/AgentStudioQuickStart.java b/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/AgentStudioQuickStart.java
new file mode 100644
index 00000000..2214e5fd
--- /dev/null
+++ b/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/AgentStudioQuickStart.java
@@ -0,0 +1,129 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.recipes.agentstudio;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.applications.agentstudio.AgentStudioClient;
+import com.alibaba.dashscope.applications.agentstudio.message.ClientEvents;
+import com.alibaba.dashscope.applications.agentstudio.model.Agent;
+import com.alibaba.dashscope.applications.agentstudio.model.Configs;
+import com.alibaba.dashscope.applications.agentstudio.model.Environment;
+import com.alibaba.dashscope.applications.agentstudio.model.Session;
+import com.alibaba.dashscope.applications.agentstudio.param.AgentCreateParam;
+import com.alibaba.dashscope.applications.agentstudio.param.EnvironmentCreateParam;
+import com.alibaba.dashscope.applications.agentstudio.param.SessionCreateParam;
+import com.alibaba.dashscope.applications.agentstudio.resource.AgentStudioEventStream;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Agent recipe: AgentStudio end-to-end quickstart. Flow: create environment -> create agent ->
+ * create session -> send message -> stream events -> archive session.
+ *
+ * AgentStudio is shared by the 2.x and 3.0 SDK generations: {@code client.agentStudio()} lazily
+ * mounts a single shared {@link AgentStudioClient} (workspace and region forward from the client
+ * config; the 3.0 {@code baseUrl} does not apply to it), so one {@code DashScopeClient} covers both
+ * the 3.0 resources and AgentStudio.
+ *
+ *
The Python example's opt-in {@code memory_stores_demo} flow (create store -> write memory ->
+ * list -> update -> list versions -> delete) is already covered by the Java sample {@code
+ * legacy_2x/AgentStudioMemoryStores.java}, so it is not duplicated here.
+ *
+ *
Translation of the Python blueprint example 03_agent_recipes/agentstudio.py.
+ *
+ *
Requires DASHSCOPE_API_KEY; DASHSCOPE_WORKSPACE selects the AgentStudio workspace (defaults to
+ * trial).
+ */
+public final class AgentStudioQuickStart {
+
+ private AgentStudioQuickStart() {}
+
+ private static String envOr(String name, String fallback) {
+ String value = System.getenv(name);
+ return value == null || value.isEmpty() ? fallback : value;
+ }
+
+ /** The builtin_toolkit entry from the Python example: everything off except bash. */
+ private static Configs.ToolConfig bashOnlyToolkit() {
+ Configs.ToolConfig toolkit = new Configs.ToolConfig();
+ toolkit.setType("builtin_toolkit");
+ Configs.ToolConfig.DefaultConfig defaultConfig = new Configs.ToolConfig.DefaultConfig();
+ defaultConfig.setEnabled(false);
+ toolkit.setDefaultConfig(defaultConfig);
+ Configs.ToolConfig.PerToolConfig bash = new Configs.ToolConfig.PerToolConfig();
+ bash.setName("bash");
+ bash.setEnabled(true);
+ toolkit.setConfigs(Collections.singletonList(bash));
+ return toolkit;
+ }
+
+ /** Run the full quickstart flow. */
+ public static void main(String[] args) {
+ try (DashScopeClient client =
+ DashScopeClient.builder()
+ .apiKey(ExampleSupport.requireApiKey())
+ .workspace(envOr("DASHSCOPE_WORKSPACE", "trial"))
+ .build()) {
+ AgentStudioClient studio = client.agentStudio();
+
+ System.out.println("==> creating environment");
+ Map config = new HashMap<>();
+ config.put("type", "cloud");
+ config.put("networking", Collections.singletonMap("type", "unrestricted"));
+ Environment env =
+ studio
+ .environments()
+ .create(
+ EnvironmentCreateParam.builder().name("quickstart-env").config(config).build());
+ System.out.println(" environment_id=" + env.getId());
+
+ System.out.println("==> creating agent");
+ Agent agent =
+ studio
+ .agents()
+ .create(
+ AgentCreateParam.builder()
+ .name("quickstart-agent")
+ .systemPrompt("You are a friendly demo agent. Reply briefly.")
+ .model("qwen3.8-max")
+ .tools(Collections.singletonList(bashOnlyToolkit()))
+ .build());
+ System.out.println(" agent_id=" + agent.getId());
+
+ System.out.println("==> creating session");
+ Session session =
+ studio
+ .sessions()
+ .create(
+ SessionCreateParam.builder()
+ .agent(agent.getId())
+ .environmentId(env.getId())
+ .title("quickstart")
+ .build());
+ System.out.println(" session_id=" + session.getId());
+
+ System.out.println("==> sending user message");
+ studio
+ .sessions()
+ .events()
+ .send(
+ session.getId(),
+ Collections.singletonList(
+ ClientEvents.userMessage("Hello! Tell me one fun fact about Hangzhou.")));
+
+ System.out.println("==> streaming events");
+ try (AgentStudioEventStream stream = studio.sessions().events().stream(session.getId())) {
+ for (String text : stream.textStream()) {
+ System.out.print(text);
+ System.out.flush();
+ }
+ System.out.println();
+ }
+
+ System.out.println("==> archiving session");
+ studio.sessions().archive(session.getId());
+ System.out.println("done.");
+ }
+ }
+}
diff --git a/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/SandboxAgentChat.java b/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/SandboxAgentChat.java
new file mode 100644
index 00000000..47bb8bda
--- /dev/null
+++ b/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/SandboxAgentChat.java
@@ -0,0 +1,52 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.recipes.agentstudio;
+
+import com.alibaba.dashscope.applications.agentstudio.sandbox.BailianSandboxClient;
+import com.alibaba.dashscope.applications.agentstudio.sandbox.agent.AgentHandle;
+import com.alibaba.dashscope.applications.agentstudio.sandbox.agent.AgentsClient;
+import com.alibaba.dashscope.applications.agentstudio.sandbox.agent.LaunchRequest;
+import com.alibaba.dashscope.applications.agentstudio.sandbox.agent.ModelConfig;
+import com.alibaba.dashscope.applications.agentstudio.sandbox.agent.TurnResult;
+import com.alibaba.dashscope.applications.agentstudio.sandbox.template.OfficialImage;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import java.time.Duration;
+
+/**
+ * 一键启动托管Agent、发送问题并释放实例,保留模板供复用;可传OPENCLAW。 平台使用DASHSCOPE_BASE_URL和DASHSCOPE_API_KEY;对话模型使用独立的
+ * DASHSCOPE_MODEL_BASE_URL和DASHSCOPE_MODEL_API_KEY。
+ */
+public final class SandboxAgentChat {
+ private SandboxAgentChat() {}
+
+ public static void main(String[] args) {
+ OfficialImage image =
+ args.length == 0 ? OfficialImage.DEEPSEEK_HARNESS : OfficialImage.valueOf(args[0]);
+ // 模型配置独立于平台认证;省略时沿用镜像配置,不复用平台Key或URL。
+ ModelConfig model =
+ ModelConfig.builder()
+ .baseUrl(System.getenv("DASHSCOPE_MODEL_BASE_URL"))
+ .modelId(System.getenv("DASHSCOPE_MODEL"))
+ .apiKey(System.getenv("DASHSCOPE_MODEL_API_KEY"))
+ .build();
+ try (BailianSandboxClient client =
+ BailianSandboxClient.builder()
+ .baseUrl(System.getProperty("dashscope.base.url", System.getenv("DASHSCOPE_BASE_URL")))
+ .apiKey(ExampleSupport.requireApiKey())
+ .build()) {
+ AgentsClient.LaunchOperation launch =
+ client.agents().launchAsync(LaunchRequest.image(image).modelConfig(model).build());
+ try {
+ AgentHandle agent = launch.await(Duration.ofMinutes(8));
+ TurnResult reply =
+ agent.defaultSession().submit("只计算7乘8并返回结果。").awaitResult(Duration.ofMinutes(3));
+ if (!"SUCCEEDED".equals(reply.status())) {
+ throw new IllegalStateException("对话未成功:" + reply.status());
+ }
+ System.out.println(reply.text());
+ } finally {
+ // 释放实例,保留个人模板供后续实例复用。
+ client.agents().release(launch.instanceId()).await(Duration.ofMinutes(3));
+ }
+ }
+ }
+}
diff --git a/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/SandboxCreate.java b/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/SandboxCreate.java
new file mode 100644
index 00000000..07faf985
--- /dev/null
+++ b/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/SandboxCreate.java
@@ -0,0 +1,54 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.recipes.agentstudio;
+
+import com.alibaba.dashscope.applications.agentstudio.sandbox.BailianSandboxClient;
+import com.alibaba.dashscope.applications.agentstudio.sandbox.SandboxCreateRequest;
+import com.alibaba.dashscope.applications.agentstudio.sandbox.SandboxHandle;
+import com.alibaba.dashscope.applications.agentstudio.sandbox.template.OfficialImage;
+import com.alibaba.dashscope.applications.agentstudio.sandbox.template.TemplateCreateRequest;
+import com.alibaba.dashscope.applications.agentstudio.sandbox.template.TemplateInfo;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import java.time.Duration;
+import java.util.UUID;
+
+/** 创建普通模板与实例,退出时依次释放本次创建的实例和模板。 */
+public final class SandboxCreate {
+ private SandboxCreate() {}
+
+ public static void main(String[] args) {
+ try (BailianSandboxClient client =
+ BailianSandboxClient.builder()
+ .baseUrl(System.getProperty("dashscope.base.url", System.getenv("DASHSCOPE_BASE_URL")))
+ .apiKey(ExampleSupport.requireApiKey())
+ .build()) {
+ TemplateInfo template =
+ client
+ .templates()
+ .create(
+ TemplateCreateRequest.builder()
+ .image(OfficialImage.CODE_INTERPRETER)
+ .name("sandbox-example-" + UUID.randomUUID())
+ .cpuCount(1)
+ .memoryMB(2048)
+ .build());
+ try {
+ client.templates().awaitReady(template.id(), template.buildId(), Duration.ofMinutes(5));
+ SandboxHandle sandbox =
+ client
+ .sandboxes()
+ .create(
+ SandboxCreateRequest.builder()
+ .templateId(template.id())
+ .timeout(Duration.ofMinutes(10))
+ .build());
+ try {
+ System.out.println("sandboxId=" + sandbox.id() + " state=" + sandbox.get().state());
+ } finally {
+ sandbox.release();
+ }
+ } finally {
+ client.templates().delete(template.id());
+ }
+ }
+ }
+}
diff --git a/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/SandboxWebUiOpen.java b/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/SandboxWebUiOpen.java
new file mode 100644
index 00000000..2d3479e7
--- /dev/null
+++ b/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/SandboxWebUiOpen.java
@@ -0,0 +1,49 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.recipes.agentstudio;
+
+import com.alibaba.dashscope.applications.agentstudio.sandbox.BailianSandboxClient;
+import com.alibaba.dashscope.applications.agentstudio.sandbox.SandboxWebUi;
+import com.alibaba.dashscope.applications.agentstudio.sandbox.template.OfficialImage;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import java.io.InputStream;
+
+/** 打开原生Web UI;默认DSH,可传OPENCLAW,按回车关闭预览。 平台填写DASHSCOPE_BASE_URL/API_KEY;模型凭据独立,留空仍可启动,实际对话需有可用模型。 */
+public final class SandboxWebUiOpen {
+ private SandboxWebUiOpen() {}
+
+ public static void main(String[] args) throws Exception {
+ OfficialImage image =
+ args.length == 0 ? OfficialImage.DEEPSEEK_HARNESS : OfficialImage.valueOf(args[0]);
+ String sandboxId = System.getenv("DASHSCOPE_SANDBOX_ID");
+ boolean reuse = sandboxId != null && !sandboxId.trim().isEmpty();
+ // sandboxId复用已有实例;仅templateId时新建实例;均未填时创建模板和实例。
+ SandboxWebUi.Options options =
+ new SandboxWebUi.Options(
+ sandboxId,
+ System.getenv("DASHSCOPE_SANDBOX_TEMPLATE_ID"),
+ null,
+ reuse ? null : System.getenv("DASHSCOPE_MODEL_BASE_URL"),
+ reuse ? null : System.getenv("DASHSCOPE_MODEL"),
+ reuse ? null : System.getenv("DASHSCOPE_MODEL_API_KEY"),
+ null);
+ try (BailianSandboxClient client =
+ BailianSandboxClient.builder()
+ .baseUrl(System.getProperty("dashscope.base.url", System.getenv("DASHSCOPE_BASE_URL")))
+ .apiKey(ExampleSupport.requireApiKey())
+ .build()) {
+ SandboxWebUi preview = client.sandboxes().openWebUi(image, options);
+ System.out.println("在本机浏览器打开 " + preview.previewUrl());
+ System.out.println("按回车关闭预览;复用的实例和模板保留。");
+ waitForExit(preview, System.in);
+ }
+ }
+
+ /** 等待输入并关闭预览;只清理本次创建的资源,不关闭调用方输入流。 */
+ public static void waitForExit(AutoCloseable preview, InputStream input) throws Exception {
+ try {
+ input.read();
+ } finally {
+ preview.close();
+ }
+ }
+}
diff --git a/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/chat/ToolCallLoop.java b/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/chat/ToolCallLoop.java
new file mode 100644
index 00000000..66c6b277
--- /dev/null
+++ b/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/chat/ToolCallLoop.java
@@ -0,0 +1,172 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.recipes.chat;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.types.completions.ChatCompletion;
+import com.alibaba.dashscope.types.completions.ChatCompletionCreateParams;
+import com.alibaba.dashscope.types.completions.ChatCompletionMessage;
+import com.alibaba.dashscope.types.messages.Message;
+import com.alibaba.dashscope.types.messages.ToolCall;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+
+/**
+ * Agent recipe: a managed multi-turn tool-call loop — the classic agent state machine. Send the
+ * conversation plus a tool schema; whenever the model asks to call a tool ({@code
+ * message.tool_calls}), execute it locally, append the result as a {@code role="tool"} message, and
+ * call the model again — until it returns a plain answer with no further tool calls. A {@code
+ * MAX_TURNS} guard stops a misbehaving model from looping forever.
+ *
+ * Translation of the Python blueprint example 03_agent_recipes/tool_call_loop.py.
+ *
+ *
Requires DASHSCOPE_API_KEY (it calls the real chat endpoint).
+ */
+public final class ToolCallLoop {
+
+ private static final String MODEL = envOr("DASHSCOPE_MODEL", "qwen3.7-plus");
+ private static final int MAX_TURNS = 5;
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private ToolCallLoop() {}
+
+ private static String envOr(String name, String fallback) {
+ String value = System.getenv(name);
+ return value == null || value.isEmpty() ? fallback : value;
+ }
+
+ /** One OpenAI-shaped function tool schema with a single string parameter. */
+ private static Map functionTool(
+ String name, String description, String paramName, String paramDescription) {
+ Map property = new LinkedHashMap<>();
+ property.put("type", "string");
+ property.put("description", paramDescription);
+ Map parameters = new LinkedHashMap<>();
+ parameters.put("type", "object");
+ parameters.put("properties", Collections.singletonMap(paramName, property));
+ parameters.put("required", Collections.singletonList(paramName));
+ Map function = new LinkedHashMap<>();
+ function.put("name", name);
+ function.put("description", description);
+ function.put("parameters", parameters);
+ Map tool = new LinkedHashMap<>();
+ tool.put("type", "function");
+ tool.put("function", function);
+ return tool;
+ }
+
+ /**
+ * Tool schemas the model may choose to call (OpenAI function shape, which the native gateway also
+ * accepts).
+ */
+ private static final List> TOOLS =
+ Arrays.asList(
+ functionTool("get_weather", "查询某个城市当前的天气", "city", "城市名,例如 杭州"),
+ functionTool("get_population", "查询某个城市的常住人口(万人)", "city", "城市名"));
+
+ // ---- local tool implementations (stand-ins for real services) ---- //
+
+ private static String getWeather(String city) {
+ Map table = new LinkedHashMap<>();
+ table.put("杭州", "晴,26℃");
+ table.put("北京", "多云,21℃");
+ return table.getOrDefault(city, "未知");
+ }
+
+ private static int getPopulation(String city) {
+ Map table = new LinkedHashMap<>();
+ table.put("杭州", 1237);
+ table.put("北京", 2184);
+ return table.getOrDefault(city, 0);
+ }
+
+ private static final Map, Object>> TOOL_IMPL =
+ new LinkedHashMap<>();
+
+ static {
+ TOOL_IMPL.put("get_weather", args -> getWeather((String) args.get("city")));
+ TOOL_IMPL.put("get_population", args -> getPopulation((String) args.get("city")));
+ }
+
+ /** Execute one tool call, always returning a JSON string result. */
+ private static String runTool(String name, String argumentsJson) {
+ Map args;
+ try {
+ args =
+ MAPPER.readValue(
+ argumentsJson == null || argumentsJson.isEmpty() ? "{}" : argumentsJson,
+ new TypeReference>() {});
+ } catch (JsonProcessingException e) {
+ return "{\"error\":\"invalid JSON arguments\"}";
+ }
+ Function, Object> impl = TOOL_IMPL.get(name);
+ if (impl == null) {
+ return toJson(Collections.singletonMap("error", "unknown tool: " + name));
+ }
+ try {
+ return toJson(Collections.singletonMap("result", impl.apply(args)));
+ } catch (RuntimeException e) {
+ return toJson(Collections.singletonMap("error", "bad arguments: " + e.getMessage()));
+ }
+ }
+
+ private static String toJson(Object value) {
+ try {
+ return MAPPER.writeValueAsString(value);
+ } catch (JsonProcessingException e) {
+ throw new IllegalStateException("failed to serialize tool result", e);
+ }
+ }
+
+ /** Drive the tool-call state machine until a final answer. */
+ static String agentLoop(DashScopeClient client, String userInput) {
+ List messages = new ArrayList<>();
+ messages.add(Message.system("你是一个助手,可以调用工具获取实时信息。"));
+ messages.add(Message.user(userInput));
+ for (int turn = 0; turn < MAX_TURNS; turn++) {
+ ChatCompletion resp =
+ client
+ .chat()
+ .completions()
+ .create(
+ ChatCompletionCreateParams.builder()
+ .model(MODEL)
+ .messages(messages)
+ .tools(TOOLS)
+ .build());
+ ChatCompletionMessage message = resp.getChoices().get(0).getMessage();
+ if (message.getToolCalls() == null || message.getToolCalls().isEmpty()) {
+ System.out.println("[turn " + turn + "] final: " + message.getContent());
+ return message.getContent();
+ }
+
+ // Echo the assistant tool-call turn back verbatim ...
+ messages.add(Message.assistant(message.getContent(), message.getToolCalls()));
+ // ... then run each tool and append its result.
+ for (ToolCall call : message.getToolCalls()) {
+ String name = call.getFunction().getName();
+ String arguments = call.getFunction().getArguments();
+ String result = runTool(name, arguments);
+ System.out.println("[turn " + turn + "] " + name + "(" + arguments + ") -> " + result);
+ messages.add(Message.tool(result, name, call.getId()));
+ }
+ }
+ System.out.println("reached MAX_TURNS=" + MAX_TURNS + " without a final answer");
+ return null;
+ }
+
+ /** Run the agent loop against the real chat endpoint. */
+ public static void main(String[] args) {
+ try (DashScopeClient client = ExampleSupport.client()) {
+ agentLoop(client, "杭州现在天气怎么样?顺便说下它有多少人口。");
+ }
+ }
+}
diff --git a/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/rag/RagExpertSystem.java b/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/rag/RagExpertSystem.java
new file mode 100644
index 00000000..a35c56b6
--- /dev/null
+++ b/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/rag/RagExpertSystem.java
@@ -0,0 +1,176 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.recipes.rag;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.types.completions.ChatCompletion;
+import com.alibaba.dashscope.types.completions.ChatCompletionCreateParams;
+import com.alibaba.dashscope.types.embeddings.Embedding;
+import com.alibaba.dashscope.types.embeddings.EmbeddingCreateParams;
+import com.alibaba.dashscope.types.embeddings.EmbeddingResponse;
+import com.alibaba.dashscope.types.messages.Message;
+import com.alibaba.dashscope.types.rerank.RerankCreateParams;
+import com.alibaba.dashscope.types.rerank.RerankResponse;
+import com.alibaba.dashscope.types.rerank.RerankResult;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+/**
+ * Agent recipe: a standard RAG loop with Bailian retrieval (embeddings + rerank).
+ * Retrieval-augmented generation grounds the model in your own documents so answers cite sources
+ * instead of hallucinating. The loop:
+ *
+ *
+ * embed a small corpus once ({@code client.embeddings()});
+ * embed the query and take a cosine top-k;
+ * re-score those candidates with {@code client.rerank()} (a cross-encoder) for precision;
+ * stuff the top passages into an "answer only from context" prompt, call {@code
+ * client.chat()}, and print the answer with citations.
+ *
+ *
+ * Translation of the Python blueprint example 03_agent_recipes/rag_expert_system.py.
+ *
+ *
Requires DASHSCOPE_API_KEY.
+ */
+public final class RagExpertSystem {
+
+ private static final String EMBED_MODEL = envOr("DASHSCOPE_EMBED_MODEL", "text-embedding-v4");
+ private static final String RERANK_MODEL = envOr("DASHSCOPE_RERANK_MODEL", "gte-rerank-v2");
+ private static final String CHAT_MODEL = envOr("DASHSCOPE_MODEL", "qwen3.7-plus");
+ private static final int TOP_K = 3;
+
+ /** A tiny stand-in corpus; in production load chunks from files or a DB. */
+ private static final List CORPUS =
+ Arrays.asList(
+ "DashScope 是阿里云百炼提供的模型服务 SDK,支持文本生成、向量、重排等能力。",
+ "百炼平台提供 qwen 系列大模型,可通过 API Key 调用。",
+ "文本向量(embedding)把句子映射为定长浮点向量,用于语义检索。",
+ "重排(rerank)用交叉编码器对候选文档按与查询的相关性重新打分。",
+ "杭州是浙江省的省会,位于中国东南沿海。");
+
+ private RagExpertSystem() {}
+
+ private static String envOr(String name, String fallback) {
+ String value = System.getenv(name);
+ return value == null || value.isEmpty() ? fallback : value;
+ }
+
+ /** Cosine similarity of two equal-length float vectors. */
+ private static double cosine(List a, List b) {
+ double dot = 0.0;
+ double normA = 0.0;
+ double normB = 0.0;
+ for (int i = 0; i < a.size(); i++) {
+ double x = a.get(i);
+ double y = b.get(i);
+ dot += x * y;
+ normA += x * x;
+ normB += y * y;
+ }
+ if (normA == 0.0 || normB == 0.0) {
+ return 0.0;
+ }
+ return dot / (Math.sqrt(normA) * Math.sqrt(normB));
+ }
+
+ /** Embed a list of texts, returned in input order. */
+ private static List> embedTexts(DashScopeClient client, List texts) {
+ EmbeddingResponse resp =
+ client
+ .embeddings()
+ .create(EmbeddingCreateParams.builder().model(EMBED_MODEL).texts(texts).build());
+ List ordered = new ArrayList<>(resp.getEmbeddings());
+ ordered.sort(Comparator.comparingInt(Embedding::getIndex));
+ List> vectors = new ArrayList<>(ordered.size());
+ for (Embedding item : ordered) {
+ vectors.add(item.getEmbedding());
+ }
+ return vectors;
+ }
+
+ /** Indices of the top_k corpus vectors closest to the query. */
+ private static List retrieve(
+ List queryVector, List> corpusVectors, int topK) {
+ List scores = new ArrayList<>();
+ List order = new ArrayList<>();
+ for (int i = 0; i < corpusVectors.size(); i++) {
+ scores.add(cosine(queryVector, corpusVectors.get(i)));
+ order.add(i);
+ }
+ order.sort((a, b) -> Double.compare(scores.get(b), scores.get(a)));
+ return order.subList(0, Math.min(topK, order.size()));
+ }
+
+ /** Re-score candidates; return passage text ordered by relevance. */
+ private static List rerank(
+ DashScopeClient client, String query, List candidates) {
+ RerankResponse resp =
+ client
+ .rerank()
+ .create(
+ RerankCreateParams.builder()
+ .model(RERANK_MODEL)
+ .query(query)
+ .documents(candidates)
+ .topN(candidates.size())
+ .returnDocuments(true)
+ .build());
+ List passages = new ArrayList<>();
+ for (RerankResult result : resp.getResults()) {
+ if (result.getDocument() != null) {
+ passages.add(result.getDocument().getText());
+ }
+ }
+ return passages;
+ }
+
+ /** Run the full retrieve -> rerank -> generate loop. */
+ static String ragAnswer(DashScopeClient client, String query) {
+ List> corpusVectors = embedTexts(client, CORPUS);
+ List queryVector = embedTexts(client, Collections.singletonList(query)).get(0);
+
+ List candidateIdx = retrieve(queryVector, corpusVectors, TOP_K);
+ List candidates = new ArrayList<>();
+ System.out.println("retrieved (cosine top-k):");
+ for (int idx : candidateIdx) {
+ candidates.add(CORPUS.get(idx));
+ System.out.println(" - [" + idx + "] " + CORPUS.get(idx));
+ }
+
+ List passages = rerank(client, query, candidates);
+ System.out.println("after rerank:");
+ for (String passage : passages) {
+ System.out.println(" - " + passage);
+ }
+
+ StringBuilder context = new StringBuilder();
+ for (int n = 0; n < passages.size(); n++) {
+ context.append('[').append(n).append("] ").append(passages.get(n)).append('\n');
+ }
+ String prompt = "仅根据下面的资料回答问题,并标注引用的编号;若资料不足,则回答:资料不足。\n" + "资料:\n" + context + "\n问题:" + query;
+ ChatCompletion resp =
+ client
+ .chat()
+ .completions()
+ .create(
+ ChatCompletionCreateParams.builder()
+ .model(CHAT_MODEL)
+ .messages(Collections.singletonList(Message.user(prompt)))
+ .build());
+ System.out.println("chat request_id: " + resp.getRequestId());
+ return resp.outputText();
+ }
+
+ /** Run the retrieve -> rerank -> generate demo. */
+ public static void main(String[] args) {
+ try (DashScopeClient client = ExampleSupport.client()) {
+ String question = "什么是重排(rerank)?它有什么作用?";
+ String answer = ragAnswer(client, question);
+ System.out.println("----- answer -----");
+ System.out.println(answer);
+ }
+ }
+}
diff --git a/examples/04_real_world_scenarios/com/alibaba/dashscope/examples/scenarios/customerservice/CustomerServiceAssistant.java b/examples/04_real_world_scenarios/com/alibaba/dashscope/examples/scenarios/customerservice/CustomerServiceAssistant.java
new file mode 100644
index 00000000..7c3d07a2
--- /dev/null
+++ b/examples/04_real_world_scenarios/com/alibaba/dashscope/examples/scenarios/customerservice/CustomerServiceAssistant.java
@@ -0,0 +1,425 @@
+// Copyright (c) Alibaba, Inc. and its affiliates.
+package com.alibaba.dashscope.examples.scenarios.customerservice;
+
+import com.alibaba.dashscope.DashScopeClient;
+import com.alibaba.dashscope.examples.ExampleSupport;
+import com.alibaba.dashscope.types.completions.ChatCompletion;
+import com.alibaba.dashscope.types.completions.ChatCompletionCreateParams;
+import com.alibaba.dashscope.types.completions.ChatCompletionMessage;
+import com.alibaba.dashscope.types.messages.Message;
+import com.alibaba.dashscope.types.messages.ToolCall;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+
+/**
+ * Real-world scenario: an online customer-service assistant with guardrails, tool access and
+ * multi-turn memory.
+ *
+ * This is a complete, production-shaped case rather than a one-line model call. It stitches
+ * together the patterns a real support bot needs:
+ *
+ *
+ * Guardrailed persona — the system prompt scopes the bot to order / logistics / refund
+ * topics, forbids inventing order data, and tells it when to escalate to a human.
+ * Business tools — the model reads real order state through {@code query_order} /
+ * {@code track_shipment} / {@code check_refund_eligible} and can open a support ticket via
+ * {@code create_ticket} (all backed here by a small in-memory "database"; swap in your own
+ * service calls).
+ * Sliding-window memory — {@link ConversationMemory} pins the system prompt, keeps
+ * only the most recent turns under a budget, and never splits an assistant tool-call turn
+ * from its tool results, so a long chat cannot blow the context window or corrupt the wire
+ * format.
+ * Managed tool-call loop — the classic agent state machine with a {@code MAX_TURNS}
+ * guard and defensive JSON handling.
+ *
+ *
+ * The demo runs a three-turn conversation where turn 2 ("can I refund it ?") only makes
+ * sense if the bot remembers the order id from turn 1, which is exactly what the memory layer buys
+ * you.
+ *
+ *
Translation of the Python blueprint example
+ * 04_real_world_scenarios/customer_service_assistant.py.
+ *
+ *
Requires DASHSCOPE_API_KEY (it calls the real chat endpoint).
+ */
+public final class CustomerServiceAssistant {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private static final String MODEL = envOr("DASHSCOPE_MODEL", "qwen3.7-plus");
+
+ /** Hard stop so a misbehaving model cannot loop on tools forever. */
+ private static final int MAX_TURNS = 6;
+
+ /**
+ * Number of post-system messages kept in context; older turns are dropped oldest-first. Tune
+ * against your model's context window.
+ */
+ private static final int MAX_HISTORY_TURNS = 20;
+
+ private static final String SYSTEM_PROMPT =
+ "你是「示例商城」的在线客服助手。请严格遵守以下规则:\n"
+ + "1. 只回答与订单、物流、退款、售后相关的问题;对无关问题礼貌说明"
+ + "无法处理并引导用户回到售后话题。\n"
+ + "2. 涉及具体订单时,必须调用工具查询真实数据后再回答,"
+ + "禁止编造订单状态、物流或退款结论。\n"
+ + "3. 当无法解决问题、或用户明确要求人工时,调用 create_ticket "
+ + "创建工单,并把工单号告诉用户。\n"
+ + "4. 回答简洁、友好,使用中文。";
+
+ /** Refund window in days after shipping, per store policy. */
+ private static final int REFUND_WINDOW_DAYS = 7;
+
+ /** One row of the stand-in order database. */
+ private static final class OrderInfo {
+ final String item;
+ final double amount;
+ final String status;
+ final int shippedDays;
+ final String carrier;
+ final String trackingNo;
+ final String latestEvent;
+ final boolean signed;
+
+ OrderInfo(
+ String item,
+ double amount,
+ String status,
+ int shippedDays,
+ String carrier,
+ String trackingNo,
+ String latestEvent,
+ boolean signed) {
+ this.item = item;
+ this.amount = amount;
+ this.status = status;
+ this.shippedDays = shippedDays;
+ this.carrier = carrier;
+ this.trackingNo = trackingNo;
+ this.latestEvent = latestEvent;
+ this.signed = signed;
+ }
+ }
+
+ /** A tiny stand-in order database (replace with your real backend). */
+ private static final Map ORDERS = new LinkedHashMap<>();
+
+ static {
+ ORDERS.put(
+ "SO2024001",
+ new OrderInfo(
+ "无线蓝牙耳机", 299.0, "已发货", 2, "示例A速运", "EX1234567890", "【杭州市】快件已到达杭州转运中心", false));
+ ORDERS.put(
+ "SO2024002",
+ new OrderInfo("机械键盘", 459.0, "已签收", 12, "示例B物流", "EX9988776655", "【北京市】已签收,签收人:本人", true));
+ }
+
+ private CustomerServiceAssistant() {}
+
+ private static String envOr(String name, String fallback) {
+ String value = System.getenv(name);
+ return value == null || value.isEmpty() ? fallback : value;
+ }
+
+ // ---------------- business tools (backed by the in-memory "database") ----------------
+
+ /** Return the core state of one order. */
+ private static Map queryOrder(String orderId) {
+ OrderInfo order = ORDERS.get(orderId);
+ Map result = new LinkedHashMap<>();
+ if (order == null) {
+ result.put("found", false);
+ result.put("message", "未找到订单 " + orderId);
+ return result;
+ }
+ result.put("found", true);
+ result.put("order_id", orderId);
+ result.put("item", order.item);
+ result.put("amount", order.amount);
+ result.put("status", order.status);
+ return result;
+ }
+
+ /** Return carrier / tracking / latest logistics event. */
+ private static Map trackShipment(String orderId) {
+ OrderInfo order = ORDERS.get(orderId);
+ Map result = new LinkedHashMap<>();
+ if (order == null) {
+ result.put("found", false);
+ result.put("message", "未找到订单 " + orderId);
+ return result;
+ }
+ result.put("found", true);
+ result.put("order_id", orderId);
+ result.put("carrier", order.carrier);
+ result.put("tracking_no", order.trackingNo);
+ result.put("latest_event", order.latestEvent);
+ return result;
+ }
+
+ /** Decide refund eligibility from the store's 7-day policy. */
+ private static Map checkRefundEligible(String orderId) {
+ OrderInfo order = ORDERS.get(orderId);
+ Map result = new LinkedHashMap<>();
+ if (order == null) {
+ result.put("found", false);
+ result.put("eligible", false);
+ result.put("reason", "未找到订单 " + orderId);
+ return result;
+ }
+ if (order.shippedDays <= REFUND_WINDOW_DAYS && !order.signed) {
+ result.put("found", true);
+ result.put("eligible", true);
+ result.put("reason", "发货未超过 7 天且未签收,可申请退款");
+ return result;
+ }
+ String reason;
+ if (order.signed) {
+ reason = "订单已签收,需走退货流程,建议转人工处理";
+ } else {
+ reason = "发货已超过 " + REFUND_WINDOW_DAYS + " 天,暂不支持自助退款";
+ }
+ result.put("found", true);
+ result.put("eligible", false);
+ result.put("reason", reason);
+ return result;
+ }
+
+ /** Open a human-support ticket; returns the ticket id. */
+ private static Map createTicket(String orderId, String reason) {
+ String ticketId =
+ String.format("TK%05d", ((orderId + reason).hashCode() & 0x7fffffff) % 100000);
+ Map result = new LinkedHashMap<>();
+ result.put("created", true);
+ result.put("ticket_id", ticketId);
+ result.put("order_id", orderId);
+ result.put("reason", reason);
+ return result;
+ }
+
+ // ---------------- tool registry ----------------
+
+ /**
+ * Build one OpenAI function-schema tool entry. Each {@code param} is a {@code {name,
+ * description}} pair; all parameters are required strings.
+ */
+ private static Map functionTool(
+ String name, String description, String[]... params) {
+ Map properties = new LinkedHashMap<>();
+ List required = new ArrayList<>();
+ for (String[] param : params) {
+ Map schema = new LinkedHashMap<>();
+ schema.put("type", "string");
+ schema.put("description", param[1]);
+ properties.put(param[0], schema);
+ required.add(param[0]);
+ }
+ Map parameters = new LinkedHashMap<>();
+ parameters.put("type", "object");
+ parameters.put("properties", properties);
+ parameters.put("required", required);
+ Map function = new LinkedHashMap<>();
+ function.put("name", name);
+ function.put("description", description);
+ function.put("parameters", parameters);
+ Map tool = new LinkedHashMap<>();
+ tool.put("type", "function");
+ tool.put("function", function);
+ return tool;
+ }
+
+ /**
+ * Tool schemas the model may call (OpenAI function shape, accepted by the native gateway too).
+ */
+ private static final List> TOOLS =
+ Arrays.asList(
+ functionTool(
+ "query_order", "查询订单的商品、金额与当前状态", new String[] {"order_id", "订单号,例如 SO2024001"}),
+ functionTool("track_shipment", "查询订单的承运商、运单号与最新物流轨迹", new String[] {"order_id", "订单号"}),
+ functionTool(
+ "check_refund_eligible", "按商城退款政策判断订单是否可退款并给出原因", new String[] {"order_id", "订单号"}),
+ functionTool(
+ "create_ticket",
+ "创建人工客服工单,用于无法自助解决或用户要求转人工",
+ new String[] {"order_id", "相关订单号"},
+ new String[] {"reason", "转人工的原因,简述用户诉求"}));
+
+ /** Tool implementations, dispatched by name from parsed JSON arguments. */
+ private static final Map, Map