Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/pre-commit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ jobs:
fail-fast: true
env:
OS: ubuntu-latest
PYTHON: '3.8'
PYTHON: '3.12'
steps:
- uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: '3.8'
python-version: '3.12'
- name: Update setuptools and wheel
run: |
pip install setuptools==68.2.2 wheel==0.41.2
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/unit_test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
strategy:
matrix:
os: [ ubuntu-latest ]
python-version: [ '3.8' ]
python-version: [ '3.9', '3.10', '3.11', '3.12', '3.13' ]


steps:
Expand Down
84 changes: 83 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ else:

## API Key Authentication

The SDK uses API key for authentication. Please refer to [official documentation for alibabacloud china](https://www.alibabacloud.com/help/en/model-studio/) and [official documentation for alibabacloud international](https://www.alibabacloud.com/help/en/model-studio/) regarding how to obtain your api-key.
The SDK uses API key for authentication. To obtain an API Key, see [How to get an API Key](https://help.aliyun.com/en/model-studio/get-api-key). Please refer to [official documentation for alibabacloud china](https://www.alibabacloud.com/help/en/model-studio/) and [official documentation for alibabacloud international](https://www.alibabacloud.com/help/en/model-studio/) regarding how to obtain your api-key.

### Using the API Key

Expand Down Expand Up @@ -89,12 +89,94 @@ save_api_key(api_key='YOUR-DASHSCOPE-API-KEY',

```

## Region and Endpoint Configuration

By default the SDK sends requests to the China (Beijing) public endpoint `dashscope.aliyuncs.com`. If your Model Studio (Bailian) workspace lives in another region, switch the endpoint before making calls.

### Using `set_region`

`dashscope.set_region(region, workspace_id)` points the HTTP, WebSocket and OpenAI-compatible base URLs at the given region in a single call. `workspace_id` is required and is used as the endpoint subdomain.

```python
import dashscope

# Switch to the Singapore region for workspace "ws-xxx123"
dashscope.set_region(region="ap-southeast-1", workspace_id="ws-xxx123")

# All subsequent calls use:
# https://ws-xxx123.ap-southeast-1.maas.aliyuncs.com/api/v1
print(dashscope.base_http_api_url)
```

Supported regions:

| Region | Location |
|--------|----------|
| `cn-beijing` | China (Beijing) |
| `cn-hongkong` | China (Hong Kong) |
| `ap-southeast-1` | Singapore |
| `ap-northeast-1` | Japan (Tokyo) |
| `eu-central-1` | Germany (Frankfurt) |
| `us-east-1` | US (Virginia) |

> **API keys are region-specific.** Each region issues its own API keys (`sk-` prefix) in its Model Studio console, and keys cannot be mixed across regions — using a key from another region fails with `401`. Switch `api_key` together with the region.

Region-specific notes:

- WebSocket endpoints (`wss://.../api-ws/v1/inference`) are only served in `cn-beijing` and `ap-southeast-1`. `set_region` still sets `base_websocket_api_url` for every region, but WebSocket-based realtime APIs (realtime speech recognition/synthesis, multimodal dialog, etc.) are not available in the other regions.
- `eu-central-1` / `ap-northeast-1`: the deployment scope (Global, or EU / Japan) is chosen when the workspace is created in the console, not per API call.
- `us-east-1`: model names with the `-us` suffix (e.g. `qwen-plus-us`) restrict inference to the US; names without the suffix default to global inference.
- Batch inference, model fine-tuning and application development are currently only available in `cn-beijing` and `ap-southeast-1`.

> `set_region` updates process-wide globals, so it is not concurrency-safe when a single process talks to multiple regions at the same time. Call it once at startup, or re-call it before each switch.

### Using environment variables

You can also select the region without code:

```shell
export DASHSCOPE_API_REGION='ap-southeast-1' # default: cn-beijing
export DASHSCOPE_WORKSPACE_ID='ws-xxx123' # used to resolve the endpoint subdomain
```

When a MaaS region is set via `DASHSCOPE_API_REGION`, the SDK builds the regional endpoints and substitutes `DASHSCOPE_WORKSPACE_ID` into them. You can also override each base URL directly:

| Environment variable | Overrides |
|----------------------|-----------|
| `DASHSCOPE_HTTP_BASE_URL` | HTTP endpoint (`dashscope.base_http_api_url`) |
| `DASHSCOPE_WEBSOCKET_BASE_URL` | WebSocket endpoint (`dashscope.base_websocket_api_url`) |
| `DASHSCOPE_COMPATIBLE_BASE_URL` | OpenAI-compatible endpoint (`dashscope.base_compatible_api_url`) |

`set_region` always builds workspace-exclusive endpoints. Some regions also offer shared domains without a workspace subdomain — `dashscope.aliyuncs.com` (Beijing), `dashscope-intl.aliyuncs.com` (Singapore) and `dashscope-us.aliyuncs.com` (US Virginia); use the override variables above to point at them.

### OpenAI-compatible chat completions

The SDK exposes an OpenAI-compatible chat completions entry that talks to `dashscope.base_compatible_api_url` (request path `chat/completions`) — no extra `openai` package required. It follows the region configured above.

```python
import dashscope
from dashscope.aigc.chat_completion import Completions

dashscope.set_region(region="cn-hongkong", workspace_id="ws-hk-789")

response = Completions.create(
model="qwen-max",
messages=[{"role": "user", "content": "Hello"}],
api_key="YOUR-DASHSCOPE-API-KEY",
stream=False, # set True to get a generator of ChatCompletionChunk
)
print(response)
```

A complete runnable example is available in [`samples/set_region_example.py`](samples/set_region_example.py).

## AI Assistant: DashScope SDK Expert

The SDK ships with an interactive AI assistant, **DashScope SDK Expert**, built on the bundled Agentic CLI (`dashscope/acli`) framework. For DashScope SDK/CLI users it is the recommended way to get development consultation and AI coding help — answering SDK/API questions, generating runnable examples, showing CLI usage, and diagnosing errors, right in your terminal.

- Run `dashscope` with no arguments to start the assistant. On first run it offers to install the SDK Expert knowledge pack (per-domain quick-reference skills: text, multimodal, speech, retrieval, fine-tuning, agent, cli), so guidance comes from the SDK's public interfaces — parameters, outputs, error codes — without reading the source
- Ask it instead of reading docs — e.g. `dashscope "how do I stream Generation output"` or `dashscope "CLI command to cancel a fine-tuning job"`. Type `/help` inside the assistant to list available commands (`/setup`, `/skill`, `/stats`, ...); classic SDK subcommands still work, and unrecognized commands are routed to the assistant
- Full walkthrough: [DashScope SDK Expert guide](https://help.aliyun.com/en/model-studio/dashscope-sdk-expert)

## Supported Models

Expand Down
84 changes: 83 additions & 1 deletion README_zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ else:

## API Key 鉴权

SDK 使用 API Key 进行鉴权。获取 API Key 的方法请参考[阿里云百炼官方文档(国内站)](https://help.aliyun.com/zh/model-studio/)和[阿里云百炼官方文档(国际站)](https://www.alibabacloud.com/help/en/model-studio/)。
SDK 使用 API Key 进行鉴权。获取 API Key 请参见[如何获取 API Key](https://help.aliyun.com/zh/model-studio/get-api-key),或参考[阿里云百炼官方文档(国内站)](https://help.aliyun.com/zh/model-studio/)和[阿里云百炼官方文档(国际站)](https://www.alibabacloud.com/help/en/model-studio/)。

### 使用 API Key

Expand Down Expand Up @@ -88,12 +88,94 @@ save_api_key(api_key='YOUR-DASHSCOPE-API-KEY',

```

## 区域与端点配置

默认情况下,SDK 将请求发往华北2(北京)公共端点 `dashscope.aliyuncs.com`。如果你的百炼(Model Studio)业务空间位于其他区域,请在调用前先切换端点。

### 使用 `set_region`

`dashscope.set_region(region, workspace_id)` 会一次性把 HTTP、WebSocket 和 OpenAI-compatible 三个 base URL 指向指定区域。`workspace_id` 为必填项,会作为端点的子域名。

```python
import dashscope

# 切换到新加坡区域,业务空间为 "ws-xxx123"
dashscope.set_region(region="ap-southeast-1", workspace_id="ws-xxx123")

# 之后所有调用都会使用:
# https://ws-xxx123.ap-southeast-1.maas.aliyuncs.com/api/v1
print(dashscope.base_http_api_url)
```

支持的区域:

| 区域 | 地理位置 |
|--------|----------|
| `cn-beijing` | 华北2(北京) |
| `cn-hongkong` | 中国(香港) |
| `ap-southeast-1` | 新加坡 |
| `ap-northeast-1` | 日本(东京) |
| `eu-central-1` | 德国(法兰克福) |
| `us-east-1` | 美国(弗吉尼亚) |

> **各地域 API Key 相互独立。**每个地域的 API Key(`sk-` 前缀)需在对应地域的百炼控制台创建,不可跨地域混用——使用其他地域的 Key 会返回 `401`。切换地域时请同步更换 `api_key`。

地域特殊说明:

- WebSocket 端点(`wss://.../api-ws/v1/inference`)目前仅 `cn-beijing` 与 `ap-southeast-1` 提供。`set_region` 对所有地域都会设置 `base_websocket_api_url`,但实时语音识别/合成、多模态对话等基于 WebSocket 的实时 API 在其他地域不可用。
- `eu-central-1` / `ap-northeast-1`:部署范围(全球,或欧盟 / 日本)在控制台创建业务空间时选择,不在 API 调用层配置。
- `us-east-1`:模型名带 `-us` 后缀(如 `qwen-plus-us`)限定美国境内推理;不带后缀默认全球推理。
- 批量推理、模型调优、应用开发等高级功能目前仅 `cn-beijing` 与 `ap-southeast-1` 支持。

> `set_region` 修改的是进程级全局变量,因此在单进程同时访问多个区域时并非并发安全。建议在启动时调用一次,或在每次切换前重新调用。

### 使用环境变量

也可以不写代码,直接通过环境变量选择区域:

```shell
export DASHSCOPE_API_REGION='ap-southeast-1' # 默认:cn-beijing
export DASHSCOPE_WORKSPACE_ID='ws-xxx123' # 用于解析端点子域名
```

当通过 `DASHSCOPE_API_REGION` 设置了 MaaS 区域时,SDK 会构造对应的区域端点,并把 `DASHSCOPE_WORKSPACE_ID` 代入其中。你也可以直接覆盖每一个 base URL:

| 环境变量 | 覆盖的对象 |
|----------------------|-----------|
| `DASHSCOPE_HTTP_BASE_URL` | HTTP 端点(`dashscope.base_http_api_url`) |
| `DASHSCOPE_WEBSOCKET_BASE_URL` | WebSocket 端点(`dashscope.base_websocket_api_url`) |
| `DASHSCOPE_COMPATIBLE_BASE_URL` | OpenAI-compatible 端点(`dashscope.base_compatible_api_url`) |

`set_region` 构造的始终是业务空间专属域名。部分地域还提供不含 workspace 子域名的共享域名——北京 `dashscope.aliyuncs.com`、新加坡 `dashscope-intl.aliyuncs.com`、美国 `dashscope-us.aliyuncs.com`,如需使用可通过上面的环境变量直接覆盖。

### OpenAI-compatible 对话补全

SDK 提供了 OpenAI-compatible 的对话补全入口,它会请求 `dashscope.base_compatible_api_url`(请求路径 `chat/completions`)——无需额外安装 `openai` 库,并自动跟随上面配置的区域。

```python
import dashscope
from dashscope.aigc.chat_completion import Completions

dashscope.set_region(region="cn-hongkong", workspace_id="ws-hk-789")

response = Completions.create(
model="qwen-max",
messages=[{"role": "user", "content": "你好"}],
api_key="YOUR-DASHSCOPE-API-KEY",
stream=False, # 设为 True 则返回 ChatCompletionChunk 生成器
)
print(response)
```

完整可运行示例见 [`samples/set_region_example.py`](samples/set_region_example.py)。

## AI 助手:DashScope SDK Expert

SDK 内置了交互式 AI 助手 **DashScope SDK Expert**,基于随包提供的 Agentic CLI(`dashscope/acli`)框架构建。对于 DashScope SDK/CLI 用户,它是获取开发咨询和 AI 编码帮助的推荐方式——直接在终端中解答 SDK/API 问题、生成可运行示例、展示 CLI 用法、诊断错误。

- 直接运行 `dashscope`(不带参数)即可启动助手。首次运行时会提示安装 SDK Expert 知识包(按领域划分的速查技能:文本、多模态、语音、检索、微调、Agent、CLI),使助手的指导来自 SDK 的公开接口——参数、输出、错误码——而无需阅读源码
- 直接提问代替翻文档——如 `dashscope "如何流式输出 Generation 结果"` 或 `dashscope "取消微调任务的 CLI 命令"`。在助手内输入 `/help` 可列出可用命令(`/setup`、`/skill`、`/stats` 等);经典 SDK 子命令依然可用,无法识别的命令会自动转给助手处理
- 完整使用指南:[DashScope SDK Expert 文档](https://help.aliyun.com/zh/model-studio/dashscope-sdk-expert)

## 支持的模型

Expand Down
44 changes: 44 additions & 0 deletions dashscope/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from dashscope.api_entities.http_request import close_shared_sync_session
from dashscope.common.api_key import save_api_key
from dashscope.common.env import (
MAAS_REGIONS,
api_key,
api_key_file_path,
base_compatible_api_url,
Expand Down Expand Up @@ -81,6 +82,48 @@
list_tokenizers,
)


# cn-beijing defaults to the legacy dashscope.aliyuncs.com endpoints;
# its MaaS URLs are only reachable via an explicit set_region() call.
_MAAS_REGIONS = {*MAAS_REGIONS, "cn-beijing"}


def set_region(region: str, workspace_id: str = None):
"""Switch to a specific MaaS region.

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.

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 or workspace_id is
empty.
"""
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")

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"


__all__ = [
"__version__",
"base_compatible_api_url",
Expand Down Expand Up @@ -141,6 +184,7 @@
"MessageFile",
"AssistantFile",
"VideoSynthesis",
"set_region",
]

logging.getLogger(__name__).addHandler(NullHandler())
1 change: 1 addition & 0 deletions dashscope/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ base_websocket_api_url: str
def save_api_key(api_key: str, file_path: Optional[str] = ...) -> None: ...
def close_shared_aio_session() -> None: ...
def close_shared_sync_session() -> None: ...
def set_region(region: str, workspace_id: Optional[str] = ...) -> None: ...

# ---------------------------------------------------------------------------
# Response types
Expand Down
2 changes: 1 addition & 1 deletion dashscope/acli/agents/subagents.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
Subagents are a subset of capabilities that function as autonomous workers
you delegate tasks to (vs. tool capabilities that the main agent calls).
Currently: local.subagent (built-in) + extension capabilities that act as
remote agents (e.g., Coze workflows).
remote agents (e.g., a hosted workflow engine).

The /subagents command provides:
- list: show all discovered subagents with status
Expand Down
6 changes: 6 additions & 0 deletions dashscope/acli/cli/examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,12 @@ def _copy_example_flat(src: Path, dst: Path, *, force: bool) -> bool:
)

console.print(f"[green]✓ Example copied to: {acli_dir}[/green]")
if src.name == "dashscope-sdk-expert":
from dashscope.acli.cli.handlers_key import _GUIDE_DOC, _doc_locale

console.print(
f"[dim]Guide: {_GUIDE_DOC.format(_doc_locale())}[/dim]",
)
if backup_dir is not None:
console.print(
f"[dim]Overwritten files backed up to: {backup_dir} "
Expand Down
Loading
Loading