Skip to content

DashScope Python SDK

v2.1.1 Python 3.9+ Apache-2.0

The dashscope SDK is the official Python client for Alibaba Cloud Model Studio (Bailian): chat completions, multimodal understanding, embeddings, reranking, image and video generation, speech synthesis & recognition, realtime voice, fine-tuning, agentic RL, managed agents and applications.

The dashscope SDK is a typed, resource-style client — dashscope.Client() — modeled on the ergonomics of the OpenAI SDK: one client holds a shared connection pool, every capability hangs off it as a typed resource, responses are typed objects, and failures raise exceptions by default.

Migrating existing 1.x code? See Migrating from 1.x.

Features

  • Typed resources


    client.chat, client.images, client.audio, … — every capability hangs off one client as a typed resource.

  • Sync & async


    AsyncClient mirrors the sync surface, so await is a drop-in switch.

  • Three protocols


    native, openai and anthropic wire protocols on the same client.

  • Text-like streaming


    Iterate .text_stream / .reasoning_stream like plain text.

  • Typed errors & diagnosis


    Exceptions carry code and request_id; opt-in self-diagnosis plus an offline dev mock.

  • A real CLI


    Script every resource from a shell, or run bare dashscope to open the SDK Expert AI assistant (AgenticX).

The full list: Features.

Requirements

  • Python 3.9+ (the optional interactive assistant requires 3.10+).
  • A Model Studio API key — create one in the Model Studio console, then export it:
export DASHSCOPE_API_KEY="sk-..."

Installation

pip install -U dashscope

The base install covers SDK API calls, the dashscope CLI, Agentic RL fine-tuning and the local tokenizer. Optional extras configure the interactive AI assistant, e.g. pip install "dashscope[expert]" (see SDK Expert).

Examples

Create it

import dashscope

client = dashscope.Client()  # reads DASHSCOPE_API_KEY

Run it

resp = client.chat.completions.create(
    model="qwen-plus",
    messages=[{"role": "user", "content": "Tell me a joke"}],
)
print(resp.output_text)
print(resp.usage.total_tokens)

Or the one-liner: dashscope.chat("qwen-plus", "Tell me a joke").

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

Stream it

Pass stream=True to get a ChatStream. The stream is single-pass — pick one of the two consumption styles; you cannot iterate the deltas first and call get_final_message() afterwards:

stream = client.chat.completions.create(
    model="qwen-plus",
    messages=[{"role": "user", "content": "Write a haiku about the sea"}],
    stream=True,
)
for text in stream.text_stream:
    print(text, end="", flush=True)
stream = client.chat.completions.create(
    model="qwen-plus",
    messages=[{"role": "user", "content": "Write a haiku about the sea"}],
    stream=True,
)
final = stream.get_final_message()  # consumes the whole stream
print(final.output_text)

The connection closes automatically when the stream is exhausted; call stream.close() to release it early.

Talk to it (realtime voice)

client.audio.live runs full-duplex voice sessions over WebSocket — see the Qwen Live guide for a complete walkthrough.

Command line (CLI)

Installing the SDK also installs the dashscope command. The CLI covers the main SDK resources, so most capabilities can be scripted straight from a shell:

dashscope version                 # print the SDK version
dashscope auth login              # save an API key
dashscope chat create --model qwen-plus --prompt "Hello!"
dashscope -o json ft list         # machine-readable output for scripting

It covers chat, multimodal, embeddings, images/videos, audio, files, fine-tuning, agentic RL and more, with global options for protocol, region and output format. Running dashscope with no arguments starts the optional interactive AI assistant (pip install "dashscope[expert]"). The frozen 1.x command tree remains available as dashscope1. See Command Line Interface.

AI assistant (SDK Expert)

Bare dashscope (or dashscope expert) opens DashScope SDK Expert, an AgenticX-powered assistant that answers SDK questions, generates runnable examples and diagnoses errors right in your terminal. It needs Python 3.10+ and the optional extra:

pip install -U "dashscope[expert]"
dashscope                                       # interactive assistant
dashscope expert "how do I stream chat output?" # ask once and exit

See SDK Expert (AgenticX) for launch modes, the first-run expert profile and troubleshooting.

Protocols

The same call can speak three wire protocols:

client = dashscope.Client(protocol="openai")  # or "native", "anthropic"

See Protocols.

Errors and diagnosis

Failures raise typed DashScopeError subclasses carrying code, request_id and the response body; opt-in local diagnosis adds structured fix guidance on error.diagnosis. See Errors and Devkit.

Legacy 1.x

The complete 1.x surface still works from its historical import paths (from dashscope import Generation), implemented by frozen facades. See Legacy 1.x.

Dependencies

The base install pulls in requests, aiohttp, httpx + httpx-sse, websocket-client, pydantic (v2), tenacity, tiktoken, and typer + rich for the CLI. Optional assistant extras are listed under Installation.

License

This project is licensed under the Apache License 2.0.