Skip to content

Quickstart

The dashscope API centers on a typed Client (and its async twin AsyncClient) with resource namespaces such as client.chat, client.images and client.audio. This page gets you from install to your first chat completion.

Requirements

Python 3.9 or newer is required.

Installation

python -m pip install -U dashscope

Configure your API key

The recommended way is the DASHSCOPE_API_KEY environment variable — never hard-code keys in source files:

export DASHSCOPE_API_KEY="<your-api-key>"

Alternatively, persist the key once with dashscope.save_api_key("sk-xxx") (writes ~/.dashscope/api_key), or assign it at runtime through dashscope.settings.api_key.

Configuration is resolved in this order, first match wins:

  1. Explicit Client(...) arguments
  2. Process-level dashscope.settings
  3. Environment variables (DASHSCOPE_API_KEY, DASHSCOPE_BASE_URL, ...)
  4. config.toml
  5. The API key file

CI and containers

Inject DASHSCOPE_API_KEY as a secret environment variable in CI; save_api_key is meant for interactive local machines only.

First call (sync)

One-call chat

For scripts and notebooks, dashscope.chat manages a client for you:

import dashscope

resp = dashscope.chat("qwen-plus", "Tell me a joke")
print(resp.output_text)

Extra keyword arguments are forwarded to client.chat.completions.create.

Use the Client

import dashscope

client = dashscope.Client()  # reads DASHSCOPE_API_KEY
resp = client.chat.completions.create(
    model="qwen-plus",
    messages=[{"role": "user", "content": "Hello!"}],
)
print(resp.output_text)

Client owns an HTTP connection pool; close it when done, or use it as a context manager:

with dashscope.Client() as client:
    resp = client.chat.completions.create(
        model="qwen-plus",
        messages=[{"role": "user", "content": "Hello!"}],
    )

Streaming

Pass stream=True and iterate over the chunks:

with dashscope.Client() as client:
    stream = client.chat.completions.create(
        model="qwen-plus",
        messages=[{"role": "user", "content": "Write a haiku about the sea."}],
        stream=True,
    )
    for chunk in stream:
        if chunk.choices:
            print(chunk.choices[0].delta.content or "", end="", flush=True)

Async

import asyncio
import dashscope


async def main():
    async with dashscope.AsyncClient() as client:
        resp = await client.chat.completions.create(
            model="qwen-plus",
            messages=[{"role": "user", "content": "Hello!"}],
        )
        print(resp.output_text)


asyncio.run(main())
Full runnable example: chat.py (auto-synced)
# -*- coding: utf-8 -*-
# Copyright (c) Alibaba, Inc. and its affiliates.
"""dashscope 2.0 chat example: non-streaming and streaming
completions."""

import os

import dashscope

# Authentication: the client reads the API key from the
# DASHSCOPE_API_KEY environment variable by default; you can also
# pass it explicitly via dashscope.Client(api_key="sk-xxx").
# The model can be overridden via the DASHSCOPE_MODEL environment
# variable.
MODEL = os.environ.get("DASHSCOPE_MODEL", "qwen3.7-plus")

MESSAGES = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "请用一句话介绍杭州"},
]


if __name__ == "__main__":
    # One-call quickstart, backed by a shared singleton client
    print("----- quickstart request -----")
    completion = dashscope.chat(MODEL, "请用一句话介绍杭州")
    print(completion.output_text)

    client = dashscope.Client()

    # Non-streaming
    print("----- non-streaming request -----")
    resp = client.chat.completions.create(  # type: ignore[call-overload]
        model=MODEL,
        messages=MESSAGES,
    )
    print(resp.output_text)
    print(
        f"usage: {resp.usage.total_tokens} tokens, "
        f"request_id: {resp.request_id}",
    )

    # Streaming: text_stream yields the content deltas as they arrive
    print("----- streaming request -----")
    stream = client.chat.completions.create(  # type: ignore[call-overload]
        model=MODEL,
        messages=MESSAGES,
        stream=True,
    )
    for text in stream.text_stream:
        print(text, end="", flush=True)
    print()
    # Call stream.get_final_message() instead of consuming text_stream
    # to get the fully merged ChatCompletion (including usage) of a
    # streaming response.


# --- Production springboard (Best Practices & Patterns) -------
# Minimal runnable atomic call above; to productionize it, see:
#   Offline mock debugging: 02_advanced_engineering/local_mock_debugging.py
#   Backoff + breaker DR: 02_advanced_engineering/circuit_breaker_retry.py
#   Streaming retry: 04_real_world_scenarios/production_ready_rag_harness.py
#   (the SDK does not auto-retry streams; the harness ships its
#   own retry_with_backoff)
# -------------------------------------------------------------

Error handling

Failed calls (connection failures, HTTP errors and server-side business errors) raise subclasses of DashScopeError carrying code, status_code, request_id and the response body:

from dashscope import Client, DashScopeError

try:
    with Client() as client:
        client.chat.completions.create(
            model="qwen-plus",
            messages=[{"role": "user", "content": "Hi"}],
        )
except DashScopeError as exc:
    print(exc.code, exc.status_code, exc.request_id, exc.message)

Two boundaries

  • Local configuration and argument validation may raise ValueError (e.g. an invalid region or an empty file_id); those are not DashScopeErrors.
  • Streaming has two phases: a failure to establish the stream raises DashScopeError as above; once the stream is established, low-level transport errors during iteration (e.g. httpx.ReadTimeout) propagate unchanged. The SDK does not reconnect automatically — catch and handle them in the caller.

See Errors for the full hierarchy (rate limits, authentication, timeouts, WebSocket errors, ...).

Next steps

  • Examples — run a sample offline, explore SDK capabilities, or follow a complete application.
  • Chat and streaming, async client, and configuration — go beyond the first request.

  • Client & Configuration — Client / AsyncClient constructor options, Config / Settings, region switching.

  • Chat — chat completions, streaming and response models.
  • Audio — TTS, ASR, realtime and Qwen Live sessions; see the Qwen Live guide for a full walkthrough.
  • Resources — embeddings, rerank, images, videos, files, models, fine-tunes, deployments, apps and more.
  • Types — shared message / response / pagination models.