配置¶
每项设置都通过配置链解析:
builder > JVM 系统属性 > 环境变量 > ~/.dashscope/config.toml > 默认值
wsBaseUrl 没有配置文件键;raiseOnError、httpClient 与 executor 仅支持 builder。API key
还会额外回退到 1.x key 文件(DASHSCOPE_API_KEY_FILE_PATH 或 ~/.dashscope/api_key),因此只需
导出 DASHSCOPE_API_KEY,DashScopeClient.builder().build() 即可工作。
客户端选项¶
客户端级选项(DashScopeClient.builder() / DashScopeAsyncClient.builder()):
| Builder 方法 | 环境变量 | 默认值 | 说明 |
|---|---|---|---|
apiKey(...) |
DASHSCOPE_API_KEY |
— | API key(上述配置链) |
baseUrl(...) |
DASHSCOPE_BASE_URL / DASHSCOPE_HTTP_BASE_URL |
区域端点 | HTTP base URL |
wsBaseUrl(...) |
DASHSCOPE_WEBSOCKET_BASE_URL |
区域端点 | WebSocket base URL |
workspace(...) |
DASHSCOPE_WORKSPACE |
— | 工作空间 id(部分 API 必填,如 decision) |
region(...) |
DASHSCOPE_REGION |
cn-beijing |
MaaS 网关区域 |
timeout(...) |
DASHSCOPE_TIMEOUT |
5 分钟 | 单请求超时(Duration) |
maxRetries(...) |
DASHSCOPE_MAX_RETRIES |
2 | 可重试失败的自动重试次数 |
raiseOnError(...) |
— | true |
false 切换为 2.x 风格的 isError() 返回 |
wsPingInterval(...) |
DASHSCOPE_WS_PING_INTERVAL |
0(关闭) | WebSocket 保活 ping;NAT/代理后建议 20–30 s |
httpClient(...) |
— | SDK 自有 | 注入自己的 OkHttpClient(生命周期由你负责) |
executor(...) |
— | SDK 自有 | 注入异步 executor(生命周期由你负责) |
try (DashScopeClient client = DashScopeClient.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.workspace("llm-xxxx")
.timeout(Duration.ofSeconds(60))
.maxRetries(3)
.build()) {
// ...
}
每项设置也有对应的 JVM 系统属性(如 -Ddashscope.api.key=sk-...、
-Ddashscope.base.url=http://127.0.0.1:8000、-Ddashscope.timeout=60),在配置链中位于
builder 与环境变量之间。
配置文件¶
配置文件是扁平的 key = value TOML 子集;时长单位为秒。路径默认
~/.dashscope/config.toml,可用 DASHSCOPE_CONFIG 覆盖:
# ~/.dashscope/config.toml
api_key = "sk-..."
base_url = "https://dashscope.aliyuncs.com"
workspace = "llm-xxxx"
region = "cn-beijing"
timeout = 300 # 秒
max_retries = 2
ws_ping_interval = 0 # 秒,0 = 关闭
逐请求覆盖¶
每个资源方法都有 (params, RequestOptions) 重载。为 null 的字段继承客户端配置。
import com.alibaba.dashscope.RequestOptions;
import java.time.Duration;
RequestOptions options = RequestOptions.builder()
.timeout(Duration.ofSeconds(30))
.maxRetries(0)
.header("X-Custom-Header", "value")
.enableEncryption(true) // 本次调用启用 DashScope 加密 HTTP 通道
.build();
client.chat().completions().create(params, options);
RequestOptions 支持 timeout、maxRetries、apiKey、workspace、额外 headers、
enableEncryption,以及 wsQueueCapacity(有界 WebSocket 事件缓冲)。
加密通道¶
enableEncryption(true) 为该次调用开启 DashScope 加密 HTTP 通道(RSA 信封加密)—— 适合敏感
载荷。端到端示例:
ChatCompletionsCreateEncrypted。
完整可运行示例:ChatCompletionsCreateEncrypted.java(自动同步)
// 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}.
*
* <p>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());
}
}
}
自定义 HTTP client 与 executor¶
注入自己的 OkHttpClient 可控制代理、连接池或拦截器 —— 注入后生命周期由你负责
(SDK close() 时不会将其关闭)。异步客户端的 executor(...) 同理。
OkHttpClient http = new OkHttpClient.Builder()
.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.corp", 8080)))
.build();
try (DashScopeClient client = DashScopeClient.builder().httpClient(http).build()) {
// ...
}
日志与遥测¶
- Wire 日志(仅环境变量):
DASHSCOPE_NETWORK_LOGGING_LEVEL=BASIC、HEADERS或BODY(默认NONE)。凭据请求头始终脱敏。 - 遥测退出:
DASHSCOPE_DISABLE_SDK_HEADERS=1(或true)可去掉x-dashscope-sdk-client/x-dashscope-sdk-session-id跟踪头;User-Agent与调用方自设的 请求头不受影响。
AgentStudio 端点¶
3.0 的 baseUrl 不作用于 AgentStudio。其端点需用 DASHSCOPE_AGENTSTUDIO_URL 单独覆盖。