Skip to content

Client & Configuration

The client entry points: Client (sync) and AsyncClient (async), plus configuration and module-level helpers.

Async scope

AsyncClient mirrors the sync surface except the duplex audio WebSocket sessions, which remain sync-only.

Clients

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
def __init__(
    self,
    *,
    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[httpx.Client] = None,
    raise_on_error: bool = True,
    protocol_options: Optional[Dict[str, Any]] = None,
    user_agent_suffix: Optional[str] = None,
) -> None:
    self._config = resolve_config(
        api_key=api_key,
        base_url=base_url,
        workspace=workspace,
        region=region,
        protocol=protocol,
        timeout=timeout,
        max_retries=max_retries,
        strict_validation=strict_validation,
        config_path=config_path,
    )
    self._raise_on_error = raise_on_error
    self._protocol_options = protocol_options
    self._user_agent_suffix = user_agent_suffix
    self._protocol = get_protocol(
        self._config.protocol,
        protocol_options=protocol_options,
    )
    self._transport = SyncTransport(
        base_url=self._config.base_url,
        api_key=self._config.api_key,
        workspace=self._config.workspace,
        user_agent=default_user_agent(user_agent_suffix),
        timeout=self._config.timeout,
        max_retries=self._config.max_retries,
        http_client=http_client,
        limits=None
        if http_client is not None
        else _http_limits(self._config),
    )
    self.chat = Chat(self)
    self.multimodal = Multimodal(self)
    self.embeddings = Embeddings(self)
    self.rerank = Rerank(self)
    self.decision = Decision(self)
    self.tokenization = Tokenization(self)
    self.files = Files(self)
    self.models = Models(self)
    self.images = Images(self)
    self.videos = Videos(self)
    self._audio = None
    self.fine_tunes = FineTunes(self)
    self.deployments = Deployments(self)
    self.rl = Rl(self)
    self.apps = Apps(self)
    self.tingwu = TingWu(self)
    self._agentstudio = None

chat instance-attribute

chat = Chat(self)

multimodal instance-attribute

multimodal = Multimodal(self)

embeddings instance-attribute

embeddings = Embeddings(self)

rerank instance-attribute

rerank = Rerank(self)

decision instance-attribute

decision = Decision(self)

tokenization instance-attribute

tokenization = Tokenization(self)

files instance-attribute

files = Files(self)

models instance-attribute

models = Models(self)

images instance-attribute

images = Images(self)

videos instance-attribute

videos = Videos(self)

fine_tunes instance-attribute

fine_tunes = FineTunes(self)

deployments instance-attribute

deployments = Deployments(self)

rl instance-attribute

rl = Rl(self)

apps instance-attribute

apps = Apps(self)

tingwu instance-attribute

tingwu = TingWu(self)

audio property

audio: 'Audio'

Audio capabilities (lazily mounted).

reinforcement_learning property

reinforcement_learning: 'Rl'

Long-form alias for client.rl.

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.

config property

config: Config

protocol property

protocol: ChatProtocol

transport property

transport: SyncTransport

raise_on_error property

raise_on_error: bool

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
def with_options(
    self,
    *,
    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.
    """
    config = self._config
    # ``user_agent_suffix`` deliberately does not participate in the
    # pool-sharing decision. The User-Agent is re-applied per request
    # from the transport's own defaults (see ``_request_headers``),
    # so a derived client sharing this one's httpx pool still sends
    # its own agent on the wire. Adding it here would split pools for
    # no behavioural gain.
    share_pool = (
        api_key is None
        and base_url is None
        and workspace is None
        and region is None
        and timeout is None
    )
    return type(self)(
        api_key=config.api_key if api_key is None else api_key,
        base_url=(
            config.configured_base_url if base_url is None else base_url
        ),
        workspace=(config.workspace if workspace is None else workspace),
        region=config.region if region is None else region,
        protocol=config.protocol if protocol is None else protocol,
        timeout=config.timeout if timeout is None else timeout,
        max_retries=(
            config.max_retries if max_retries is None else max_retries
        ),
        strict_validation=(
            config.strict_validation
            if strict_validation is None
            else strict_validation
        ),
        http_client=(self._transport.http_client if share_pool else None),
        raise_on_error=(
            self._raise_on_error
            if raise_on_error is None
            else raise_on_error
        ),
        protocol_options=self._protocol_options,
        user_agent_suffix=(
            self._user_agent_suffix
            if user_agent_suffix is None
            else user_agent_suffix
        ),
    )

close

close() -> None
Source code in dashscope/client.py
281
282
283
284
285
def close(self) -> None:
    self._transport.close()
    if self._agentstudio is not None:
        self._agentstudio.close()
        self._agentstudio = None

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
def ws_connection(
    self,
    *,
    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``.
    """
    config = self._config
    return WsConnection(
        url=url,
        api_key=config.api_key,
        workspace=config.workspace,
        region=config.region,
        # Websocket sessions bypass this client's HTTP transport, so the
        # agent (and its surface suffix) is carried across explicitly.
        headers=with_client_user_agent(self, headers),
        connector=connector,
        timeout=config.timeout if timeout is None else timeout,
        module=module,
        task_queue_size=task_queue_size,
        ping_interval=ping_interval,
    )

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
def __init__(
    self,
    *,
    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[httpx.AsyncClient] = None,
    raise_on_error: bool = True,
    protocol_options: Optional[Dict[str, Any]] = None,
    user_agent_suffix: Optional[str] = None,
) -> None:
    self._config = resolve_config(
        api_key=api_key,
        base_url=base_url,
        workspace=workspace,
        region=region,
        protocol=protocol,
        timeout=timeout,
        max_retries=max_retries,
        strict_validation=strict_validation,
        config_path=config_path,
    )
    self._raise_on_error = raise_on_error
    self._protocol_options = protocol_options
    self._user_agent_suffix = user_agent_suffix
    self._protocol = get_protocol(
        self._config.protocol,
        protocol_options=protocol_options,
    )
    self._transport = AsyncTransport(
        base_url=self._config.base_url,
        api_key=self._config.api_key,
        workspace=self._config.workspace,
        user_agent=default_user_agent(user_agent_suffix),
        timeout=self._config.timeout,
        max_retries=self._config.max_retries,
        http_client=http_client,
        limits=None
        if http_client is not None
        else _http_limits(self._config),
    )
    self.chat = AsyncChat(self)
    self.multimodal = AsyncMultimodal(self)
    self.embeddings = AsyncEmbeddings(self)
    self.rerank = AsyncRerank(self)
    self.decision = AsyncDecision(self)
    self.tokenization = AsyncTokenization(self)
    self.files = AsyncFiles(self)
    self.models = AsyncModels(self)
    self.images = AsyncImages(self)
    self.videos = AsyncVideos(self)
    self._audio = None
    self.fine_tunes = AsyncFineTunes(self)
    self.deployments = AsyncDeployments(self)
    self.rl = AsyncRl(self)
    self.apps = AsyncApps(self)
    self.tingwu = AsyncTingWu(self)
    self._agentstudio = None

chat instance-attribute

chat = AsyncChat(self)

multimodal instance-attribute

multimodal = AsyncMultimodal(self)

embeddings instance-attribute

embeddings = AsyncEmbeddings(self)

rerank instance-attribute

rerank = AsyncRerank(self)

decision instance-attribute

decision = AsyncDecision(self)

tokenization instance-attribute

tokenization = AsyncTokenization(self)

files instance-attribute

files = AsyncFiles(self)

models instance-attribute

models = AsyncModels(self)

images instance-attribute

images = AsyncImages(self)

videos instance-attribute

videos = AsyncVideos(self)

fine_tunes instance-attribute

fine_tunes = AsyncFineTunes(self)

deployments instance-attribute

deployments = AsyncDeployments(self)

rl instance-attribute

rl = AsyncRl(self)

apps instance-attribute

apps = AsyncApps(self)

tingwu instance-attribute

tingwu = AsyncTingWu(self)

audio property

audio: 'AsyncAudio'

Audio capabilities (lazily mounted).

reinforcement_learning property

reinforcement_learning: 'AsyncRl'

Long-form alias for client.rl.

agentstudio property

agentstudio

Lazily mounted AgentStudio sub-SDK (design doc M3 3.8).

See :attr:Client.agentstudio; errors use the dashscope exception family natively.

config property

config: Config

protocol property

protocol: ChatProtocol

transport property

transport: AsyncTransport

raise_on_error property

raise_on_error: bool

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
def with_options(
    self,
    *,
    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.
    """
    config = self._config
    # See Client.with_options: the User-Agent is applied per request,
    # so the suffix must not force a separate pool.
    share_pool = (
        api_key is None
        and base_url is None
        and workspace is None
        and region is None
        and timeout is None
    )
    return type(self)(
        api_key=config.api_key if api_key is None else api_key,
        base_url=(
            config.configured_base_url if base_url is None else base_url
        ),
        workspace=(config.workspace if workspace is None else workspace),
        region=config.region if region is None else region,
        protocol=config.protocol if protocol is None else protocol,
        timeout=config.timeout if timeout is None else timeout,
        max_retries=(
            config.max_retries if max_retries is None else max_retries
        ),
        strict_validation=(
            config.strict_validation
            if strict_validation is None
            else strict_validation
        ),
        http_client=(self._transport.http_client if share_pool else None),
        raise_on_error=(
            self._raise_on_error
            if raise_on_error is None
            else raise_on_error
        ),
        protocol_options=self._protocol_options,
        user_agent_suffix=(
            self._user_agent_suffix
            if user_agent_suffix is None
            else user_agent_suffix
        ),
    )

aclose async

aclose() -> None
Source code in dashscope/client.py
535
536
537
538
539
async def aclose(self) -> None:
    await self._transport.aclose()
    if self._agentstudio is not None:
        await self._agentstudio.aclose()
        self._agentstudio = None

Configuration

strict_validation and raise_on_error interact with the per-call raw=True escape hatch — see Types — raw responses & parsing.

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,
)

api_key instance-attribute

api_key: Optional[str]

base_url instance-attribute

base_url: str

workspace instance-attribute

workspace: Optional[str]

protocol instance-attribute

protocol: str

timeout instance-attribute

timeout: float

max_retries instance-attribute

max_retries: int

protocol_base_url instance-attribute

protocol_base_url: str

configured_base_url class-attribute instance-attribute

configured_base_url: Optional[str] = None

region class-attribute instance-attribute

region: str = DEFAULT_REGION

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
def __init__(self) -> None:
    self._explicit: Dict[str, Any] = {}
    self._lock = threading.Lock()

api_key property writable

api_key: Optional[str]

base_url property writable

base_url: str

websocket_base_url property writable

websocket_base_url: Optional[str]

workspace property writable

workspace: Optional[str]

region property writable

region: str

protocol property writable

protocol: str

timeout property writable

timeout: float

max_retries property writable

max_retries: int

http_max_connections property writable

http_max_connections: int

http_max_keepalive_connections property writable

http_max_keepalive_connections: int

http_keepalive_expiry property writable

http_keepalive_expiry: float

strict_validation property writable

strict_validation: bool

log_level property writable

log_level: Optional[str]

get_explicit

get_explicit(name: str) -> Any

Explicitly assigned value, or None if unset.

Source code in dashscope/_config.py
365
366
367
368
def get_explicit(self, name: str) -> Any:
    """Explicitly assigned value, or None if unset."""
    with self._lock:
        return self._explicit.get(name)

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
def clear(self) -> 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.
    """
    with self._lock:
        had_log_level = "log_level" in self._explicit
        self._explicit.clear()
    if had_log_level:
        # pylint: disable=import-outside-toplevel
        from dashscope._logging import reset_log_level

        reset_log_level()

Top-level helpers

set_region is a legacy 1.x helper

dashscope.set_region() only updates the historical module-level endpoint variables (base_http_api_url etc.) used by dashscope.legacy_1x; it does not affect Client / AsyncClient configuration resolution. For the current client use Client(region=..., workspace=...) or 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
def 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.
    """
    client = _select_client(acquire=True)
    try:
        return client.chat.completions.create(
            model=model,
            messages=[prompt],
            **kwargs,
        )
    finally:
        _release_client(client)

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
def set_region(region: str, workspace_id: str = 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.

    Args:
        region (str): The MaaS region, e.g. "ap-southeast-1",
            "us-east-1", "cn-hongkong", "cn-beijing", "eu-central-1",
            "ap-northeast-1".
        workspace_id (str): The workspace ID, used as the subdomain
            of the MaaS endpoint.

    Raises:
        ValueError: If region is not supported, workspace_id is
            empty, or workspace_id is not a valid hostname label.
    """
    if region not in _MAAS_REGIONS:
        raise ValueError(
            f"Unsupported region '{region}'. "
            f"Supported regions: {sorted(_MAAS_REGIONS)}",
        )

    if not workspace_id:
        raise ValueError("workspace_id is required")

    validate_workspace_id(workspace_id)

    global base_http_api_url, base_compatible_api_url
    global base_websocket_api_url

    host = f"{workspace_id}.{region}.maas.aliyuncs.com"
    base_http_api_url = f"https://{host}/api/v1"
    base_compatible_api_url = f"https://{host}/compatible-mode/v1"
    base_websocket_api_url = f"wss://{host}/api-ws/v1/inference"

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
def 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.
    """
    target = (
        _DEFAULT_API_KEY_FILE_PATH
        if api_key_file_path is None
        else api_key_file_path
    )
    path = Path(target).expanduser()
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(api_key, encoding="utf-8")

WebSocket transport

Low-level WebSocket primitives exported from the package root, used by the realtime audio sessions and available for custom inference tasks:

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
def __init__(
    self,
    *,
    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,
) -> None:
    if timeout is not None and timeout <= 0:
        raise ValueError("timeout must be positive")
    if task_queue_size <= 0:
        raise ValueError("task_queue_size must be positive")
    if ping_interval is not None and ping_interval <= 0:
        raise ValueError("ping_interval must be positive")
    self._url = (
        url
        or settings.websocket_base_url
        or workspace_ws_url(workspace, WS_INFERENCE_PATH, region)
    )
    self._timeout = timeout
    self._task_queue_size = task_queue_size
    self._ping_interval = ping_interval
    self._heartbeat_stop = threading.Event()
    self._tasks: Dict[str, WsTask] = {}
    self._lock = threading.Lock()
    self._send_lock = threading.Lock()
    self._closed = False
    self._binary_uplink_owner: Optional[WsTask] = None
    self._binary_downlink_owner: Optional[WsTask] = None
    self._ws = _connect(
        self._url,
        _assemble_headers(api_key, workspace, headers, module),
        connector,
        timeout,
    )
    # Reads happen only on the reader thread and per-task timeouts
    # are enforced on the demux queues, so the socket itself must
    # block forever -- a socket read timeout would kill the reader
    # during any quiet period longer than the timeout.
    try:
        settimeout = getattr(self._ws, "settimeout", None)
        if callable(settimeout):
            settimeout(None)
        self._reader = threading.Thread(
            target=self._reader_main,
            name="dashscope-ws-reader",
            daemon=True,
        )
        self._reader.start()
        ping = getattr(self._ws, "ping", None)
        if self._ping_interval is not None and callable(ping):
            self._heartbeat = threading.Thread(
                target=self._heartbeat_main,
                name="dashscope-ws-heartbeat",
                daemon=True,
            )
            self._heartbeat.start()
    except BaseException:
        self.close()
        raise

closed property

closed: bool

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
def open_task(self, *, timeout: Optional[float] = None) -> WsTask:
    if timeout is not None and timeout <= 0:
        raise ValueError("timeout must be positive")
    with self._lock:
        if self._closed:
            raise WsStateError(detail="connection is closed")
        task = WsTask(
            self,
            uuid.uuid4().hex,
            self._timeout if timeout is None else timeout,
            self._task_queue_size,
        )
        self._tasks[task.task_id] = task
        return task

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
def close(self) -> None:
    self._fail(
        APIConnectionError("websocket connection closed"),
        operation=None,
    )
    # Initialization may fail before the reader is created or started.
    reader = getattr(self, "_reader", None)
    if (
        reader is not None
        and reader.is_alive()
        and threading.current_thread() is not reader
    ):
        reader.join(timeout=2)
    heartbeat = getattr(self, "_heartbeat", None)
    if (
        heartbeat is not None
        and heartbeat.is_alive()
        and threading.current_thread() is not heartbeat
    ):
        heartbeat.join(timeout=2)

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
def __init__(
    self,
    connection: "WsConnection",
    task_id: str,
    timeout: Optional[float],
    queue_size: int,
) -> None:
    self._conn = connection
    self._task_id = task_id
    self._timeout = timeout
    self._queue: "queue.Queue[_QueueItem]" = queue.Queue(
        maxsize=queue_size,
    )
    self._request_id = task_id
    self._lock = threading.Lock()
    self._run_sent = False
    self._started = False
    self._input_finished = False
    self._cancel_sent = False
    self._finished = False
    self._closed = False
    # Reader-side routing uses the connection lock, not the send lock.
    self._routing_active = False
    self._routing_finished = False
    # Retain IDs even when events are still waiting for the consumer.
    self._routing_request_id = task_id
    self._error: Optional[BaseException] = None

task_id property

task_id: str

request_id property

request_id: str

finished property

finished: bool

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
def run_task(
    self,
    *,
    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."""
    payload: Dict[str, Any] = {
        "task_group": task_group,
        "task": task,
        "function": function,
        "model": model,
        "input": input if input is not None else {},
    }
    if parameters is not None:
        payload["parameters"] = parameters
    if resources is not None:
        payload["resources"] = resources
    frame = self._frame("run-task", payload)
    frame["header"]["streaming"] = streaming
    with self._lock:
        if self._closed or self._run_sent:
            raise WsStateError(detail="task already started or closed")
        self._run_sent = True
        self._conn._send(frame, task=self)
    try:
        event = self.recv_event()
        if event["header"].get("event") != EVENT_STARTED:
            raise WsEventError(
                detail="expected task-started, got "
                f"{event['header'].get('event')!r}",
                request_id=self.request_id,
            )
        self._started = True
        return event
    except BaseException:
        self.close()
        raise
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
def claim_binary_downlink(self) -> 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).
    """
    self._conn._claim_binary_downlink(self)

send_binary

send_binary(data: bytes) -> None
Source code in dashscope/transport/ws_connection.py
217
218
219
220
221
222
223
def send_binary(self, data: bytes) -> None:
    if not isinstance(data, (bytes, bytearray, memoryview)):
        raise TypeError("audio data must be bytes")
    with self._lock:
        self._check_input()
        self._conn._claim_binary_uplink(self)
        self._conn._send(bytes(data), opcode=2, task=self)

continue_task

continue_task(input: Dict[str, Any]) -> None
Source code in dashscope/transport/ws_connection.py
225
226
227
228
229
230
231
def continue_task(self, input: Dict[str, Any]) -> None:
    with self._lock:
        self._check_input()
        self._conn._send(
            self._frame("continue-task", {"input": input}),
            task=self,
        )

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
def finish_task(self, input: Optional[Dict[str, Any]] = None) -> None:
    """End input, or cancel synthesis while output is still arriving."""
    with self._lock:
        if self._closed or not self._started:
            raise WsStateError(detail="task is not active")
        if self._finished:
            return
        cancel = input is not None and input.get("directive") == "cancel"
        if self._cancel_sent or (self._input_finished and not cancel):
            return
        self._conn._send(
            self._frame("finish-task", {"input": input or {}}),
            task=self,
        )
        self._input_finished = True
        self._cancel_sent = cancel

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
def recv_event(self) -> Dict[str, Any]:
    """Read the next control event; use recv for binary output."""
    while True:
        frame = self.recv()
        if frame is None:
            raise WsStateError(detail="task is finished")
        if isinstance(frame, dict):
            return frame

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
def recv(self) -> Union[Dict[str, Any], bytes, None]:
    """Read queued frames before surfacing a persistent close/error."""
    if self._finished:
        return None
    try:
        kind, payload = self._queue.get(timeout=self._timeout)
    except queue.Empty:
        error = APITimeoutError(
            detail="timed out waiting for a websocket event",
            request_id=self._routing_request_id,
        )
        _log_error("receive", error, self._routing_request_id)
        raise error from None
    if kind == _ERROR:
        # Requeue the terminal marker so subsequent readers also fail.
        self._queue.put((kind, payload))
        raise payload
    if isinstance(payload, (bytes, bytearray)):
        return bytes(payload)
    return self._process_event(payload)

close

close() -> None

Detach and wake receivers; the shared socket stays open.

Source code in dashscope/transport/ws_connection.py
280
281
282
def close(self) -> None:
    """Detach and wake receivers; the shared socket stays open."""
    self._conn._detach(self)