客户端与配置¶
客户端入口:Client(同步)与 AsyncClient(异步),以及配置和模块级辅助函数。
异步范围
AsyncClient 镜像同步接口,但双工语音 WebSocket 会话
除外——它们仅支持同步。
客户端¶
Client
¶
Client(
*,
api_key: Optional[str] = None,
base_url: Optional[str] = None,
workspace: Optional[str] = None,
region: Optional[str] = None,
protocol: Optional[str] = None,
timeout: Optional[float] = None,
max_retries: Optional[int] = None,
strict_validation: Optional[bool] = None,
config_path: Union[str, Path, None] = None,
http_client: Optional[Client] = None,
raise_on_error: bool = True,
protocol_options: Optional[Dict[str, Any]] = None,
user_agent_suffix: Optional[str] = None
)
Synchronous dashscope 2.0 client.
Usage::
import dashscope
client = dashscope.Client(api_key="sk-xxx")
resp = client.chat.completions.create(
model="qwen-plus",
messages=[{"role": "user", "content": "Hello"}],
)
Source code in dashscope/client.py
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 | |
agentstudio
property
¶
agentstudio
Lazily mounted AgentStudio sub-SDK (design doc M3 3.8).
AgentStudio raises dashscope.errors natively. It ships its
own transport rather than riding this client's, so its requests
keep the unmarked module tag (agentstudio) instead of the v2
2 marker -- the backend already reports on that tag, and
changing it would split the server-side statistics.
user_agent_suffix
property
¶
user_agent_suffix: Optional[str]
The surface tag appended to this client's User-Agent, if any.
with_options
¶
with_options(
*,
api_key: Optional[str] = None,
base_url: Optional[str] = None,
workspace: Optional[str] = None,
region: Optional[str] = None,
protocol: Optional[str] = None,
timeout: Optional[float] = None,
max_retries: Optional[int] = None,
strict_validation: Optional[bool] = None,
raise_on_error: Optional[bool] = None,
user_agent_suffix: Optional[str] = None
) -> "Client"
Derive a client with the given options overridden.
Unmentioned options are inherited. When connection-level options
(api_key/base_url/workspace/region/timeout)
are left unchanged the derived client shares this one's
connection pool and must not outlive it; otherwise it builds its
own pool.
Source code in dashscope/client.py
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | |
close
¶
close() -> None
Source code in dashscope/client.py
281 282 283 284 285 | |
ws_connection
¶
ws_connection(
*,
url: Optional[str] = None,
headers: Optional[Mapping[str, str]] = None,
connector: Optional[Connector] = None,
timeout: Optional[float] = None,
module: Optional[str] = None,
task_queue_size: int = 1024,
ping_interval: Optional[float] = 30.0
) -> WsConnection
Open a shared duplex websocket carrying multiple tasks.
Credentials, region and timeout come from this client's config.
Pass the connection as connection= to the realtime audio
sessions (audio.asr.recognize / audio.tts.connect /
tingwu.realtime) to run tasks concurrently or back-to-back
on one socket, saving the handshake per task -- the 1.x
Java-side connection-reuse pattern for latency-sensitive audio
traffic. The caller owns the connection and closes it via
WsConnection.close.
Source code in dashscope/client.py
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 | |
AsyncClient
¶
AsyncClient(
*,
api_key: Optional[str] = None,
base_url: Optional[str] = None,
workspace: Optional[str] = None,
region: Optional[str] = None,
protocol: Optional[str] = None,
timeout: Optional[float] = None,
max_retries: Optional[int] = None,
strict_validation: Optional[bool] = None,
config_path: Union[str, Path, None] = None,
http_client: Optional[AsyncClient] = None,
raise_on_error: bool = True,
protocol_options: Optional[Dict[str, Any]] = None,
user_agent_suffix: Optional[str] = None
)
Asynchronous dashscope 2.0 client.
Usage::
import dashscope
client = dashscope.AsyncClient(api_key="sk-xxx")
resp = await client.chat.completions.create(
model="qwen-plus",
messages=[{"role": "user", "content": "Hello"}],
)
Source code in dashscope/client.py
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 | |
agentstudio
property
¶
agentstudio
Lazily mounted AgentStudio sub-SDK (design doc M3 3.8).
See :attr:Client.agentstudio; errors use the dashscope
exception family natively.
user_agent_suffix
property
¶
user_agent_suffix: Optional[str]
The surface tag appended to this client's User-Agent, if any.
with_options
¶
with_options(
*,
api_key: Optional[str] = None,
base_url: Optional[str] = None,
workspace: Optional[str] = None,
region: Optional[str] = None,
protocol: Optional[str] = None,
timeout: Optional[float] = None,
max_retries: Optional[int] = None,
strict_validation: Optional[bool] = None,
raise_on_error: Optional[bool] = None,
user_agent_suffix: Optional[str] = None
) -> "AsyncClient"
Derive a client with the given options overridden.
Unmentioned options are inherited. When connection-level options
(api_key/base_url/workspace/region/timeout)
are left unchanged the derived client shares this one's
connection pool and must not outlive it; otherwise it builds its
own pool.
Source code in dashscope/client.py
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 | |
aclose
async
¶
aclose() -> None
Source code in dashscope/client.py
535 536 537 538 539 | |
配置¶
strict_validation、raise_on_error 与单次调用的 raw=True
相互配合——见类型——原始响应与解析。
Config
dataclass
¶
Config(
api_key: Optional[str],
base_url: str,
workspace: Optional[str],
protocol: str,
timeout: float,
max_retries: int,
protocol_base_url: str,
configured_base_url: Optional[str] = None,
region: str = DEFAULT_REGION,
http_max_connections: int = DEFAULT_HTTP_MAX_CONNECTIONS,
http_max_keepalive_connections: int = DEFAULT_HTTP_MAX_KEEPALIVE_CONNECTIONS,
http_keepalive_expiry: float = DEFAULT_HTTP_KEEPALIVE_EXPIRY,
strict_validation: bool = DEFAULT_STRICT_VALIDATION,
)
http_max_connections
class-attribute
instance-attribute
¶
http_max_connections: int = DEFAULT_HTTP_MAX_CONNECTIONS
http_max_keepalive_connections
class-attribute
instance-attribute
¶
http_max_keepalive_connections: int = (
DEFAULT_HTTP_MAX_KEEPALIVE_CONNECTIONS
)
http_keepalive_expiry
class-attribute
instance-attribute
¶
http_keepalive_expiry: float = DEFAULT_HTTP_KEEPALIVE_EXPIRY
strict_validation
class-attribute
instance-attribute
¶
strict_validation: bool = DEFAULT_STRICT_VALIDATION
Settings
¶
Settings()
Global mutable settings facade (design doc M3 3.11).
Single runtime entry point: values assigned here override environment
variables and config.toml for every Client created afterwards.
Unset properties fall back lazily to the environment (read at access
time, not import time).
Source code in dashscope/_config.py
361 362 363 | |
get_explicit
¶
get_explicit(name: str) -> Any
Explicitly assigned value, or None if unset.
Source code in dashscope/_config.py
365 366 367 368 | |
clear
¶
clear() -> None
Forget every explicit assignment (back to env / defaults).
If log_level had been assigned, the logger level is reset to
the DASHSCOPE_LOG env level (or WARNING) so it does not leak.
Source code in dashscope/_config.py
370 371 372 373 374 375 376 377 378 379 380 381 382 383 | |
模块级辅助函数¶
set_region 是 1.x 历史接口
dashscope.set_region() 只修改历史模块级端点变量
(base_http_api_url 等),供 dashscope.legacy_1x 使用,
不影响 Client / AsyncClient 的配置解析。
当前客户端请使用 Client(region=..., workspace=...) 或
dashscope.settings.region。
chat
¶
chat(
model: str, prompt: str, **kwargs: Any
) -> ChatCompletion
One-call chat entry: dashscope.chat("qwen-plus", "Tell me a joke").
Extra keyword arguments are forwarded to
client.chat.completions.create. Global settings and environment
changes are re-resolved before each call; an in-flight call keeps its
previous client alive until that call finishes.
Source code in dashscope/_quickstart.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | |
set_region
¶
set_region(
region: str, workspace_id: Optional[str] = None
) -> None
Switch to a specific MaaS region (legacy 1.x helper).
Updates base_http_api_url, base_compatible_api_url and
base_websocket_api_url to point to the MaaS endpoint for the
given region and workspace. These module-level variables are
only read by dashscope.legacy_1x; this call does not affect
Client / AsyncClient configuration resolution. For the
current client use Client(region=..., workspace=...) or
dashscope.settings.region instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
region
|
str
|
The MaaS region, e.g. "ap-southeast-1", "us-east-1", "cn-hongkong", "cn-beijing", "eu-central-1", "ap-northeast-1". |
required |
workspace_id
|
str
|
The workspace ID, used as the subdomain of the MaaS endpoint. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If region is not supported, workspace_id is empty, or workspace_id is not a valid hostname label. |
Source code in dashscope/__init__.py
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | |
save_api_key
¶
save_api_key(
api_key: str, api_key_file_path: Optional[str] = None
) -> None
Store an api key in the key file _api_key_from_file reads back.
Without an explicit path this writes ~/.dashscope/api_key, the same
fixed location the 1.x dashscope.save_api_key uses, so a key stored
through either stack is picked up by both. As in 1.x,
DASHSCOPE_API_KEY_FILE_PATH redirects only the read, not the write.
Source code in dashscope/_config.py
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 | |
WebSocket 传输¶
从包根导出的底层 WebSocket 原语,供实时语音会话使用, 也可用于自定义推理任务:
WsConnection
¶
WsConnection(
*,
url: Optional[str] = None,
api_key: Optional[str] = None,
workspace: Optional[str] = None,
region: Optional[str] = None,
headers: Optional[Mapping[str, str]] = None,
connector: Optional[Connector] = None,
timeout: Optional[float] = None,
module: Optional[str] = None,
task_queue_size: int = 1024,
ping_interval: Optional[float] = 30.0
)
One physical duplex websocket shared by multiple tasks.
Construction performs the handshake once; every open_task then
runs an independent task on the same socket. close() shuts the
socket down and fails every task still attached.
Source code in dashscope/transport/ws_connection.py
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 | |
open_task
¶
open_task(*, timeout: Optional[float] = None) -> WsTask
Source code in dashscope/transport/ws_connection.py
364 365 366 367 368 369 370 371 372 373 374 375 376 377 | |
close
¶
close() -> None
Source code in dashscope/transport/ws_connection.py
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 | |
WsTask
¶
WsTask(
connection: "WsConnection",
task_id: str,
timeout: Optional[float],
queue_size: int,
)
Bases: _EventProcessor
One task on a shared connection; same interface as WsSession.
close() only detaches the task from the connection -- the
shared socket stays open for the remaining tasks.
Source code in dashscope/transport/ws_connection.py
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | |
run_task
¶
run_task(
*,
task_group: str,
task: str,
function: str,
model: str,
parameters: Optional[Dict[str, Any]] = None,
input: Optional[Dict[str, Any]] = None,
resources: Optional[List[Dict[str, Any]]] = None,
streaming: str = "duplex"
) -> Dict[str, Any]
Send run-task and wait for task-started before allowing input.
Source code in dashscope/transport/ws_connection.py
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 | |
claim_binary_downlink
¶
claim_binary_downlink() -> None
Route binary output frames to this task.
Binary frames carry no task id, so when more than one task is active the downlink owner must be claimed explicitly (with a single active task it is assigned implicitly).
Source code in dashscope/transport/ws_connection.py
208 209 210 211 212 213 214 215 | |
send_binary
¶
send_binary(data: bytes) -> None
Source code in dashscope/transport/ws_connection.py
217 218 219 220 221 222 223 | |
continue_task
¶
continue_task(input: Dict[str, Any]) -> None
Source code in dashscope/transport/ws_connection.py
225 226 227 228 229 230 231 | |
finish_task
¶
finish_task(input: Optional[Dict[str, Any]] = None) -> None
End input, or cancel synthesis while output is still arriving.
Source code in dashscope/transport/ws_connection.py
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 | |
recv_event
¶
recv_event() -> Dict[str, Any]
Read the next control event; use recv for binary output.
Source code in dashscope/transport/ws_connection.py
250 251 252 253 254 255 256 257 | |
recv
¶
recv() -> Union[Dict[str, Any], bytes, None]
Read queued frames before surfacing a persistent close/error.
Source code in dashscope/transport/ws_connection.py
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | |
close
¶
close() -> None
Detach and wake receivers; the shared socket stays open.
Source code in dashscope/transport/ws_connection.py
280 281 282 | |