The Qwen API now lives on QwenCloud, Alibaba’s developer platform for Qwen models. It speaks the OpenAI format, so the normal openai Python package works with only a new base URL and key.
This matters more today because Qwen4-35B-A3B went live on the API on 4 December 2026 at just $0.06 per million input tokens. Here is the full setup, from key to streaming, thinking, tools and costs.
- Where: sign up at qwencloud.com, pick a region (Singapore for the free quota), and create a pay-as-you-go API key.
- Code:
pip install openai, then setbase_urltohttps://ap-southeast-1.maas.qwencloudapi.com/compatible-mode/v1. - Models:
qwen4-max($1.50 / $4.50 per 1M),qwen4-35b-a3b($0.06 / $0.36),qwen3.8-flash($0.15 / $0.47). - Thinking: on by default for
qwen4-max. Turn it off withextra_body={"enable_thinking": False}. - Free: about 1M tokens per model for 90 days, Singapore region only, after you add payment details.
What the Qwen API Is (QwenCloud vs Model Studio)
The Qwen API lets your code call Alibaba’s Qwen models over HTTP. You send messages, and the model sends back text, tool calls or reasoning. It is the same family of models you can try for free in the Qwen Chat app, but billed per token and ready for your own apps.
The naming has changed a few times, which confuses people. Here is how it fits together today.
- QwenCloud: Alibaba’s Qwen-branded developer platform. Its changelog marks general availability on 31 March 2026, and Alibaba held a global launch event in Singapore in May 2026. Docs live at docs.qwencloud.com and the API hosts end in
maas.qwencloudapi.com. - Alibaba Cloud Model Studio: the older Alibaba Cloud console route (formerly also called DashScope or Bailian). It still lists the same models, and its pricing page shows the same
qwen4-maxprice of $1.50 / $4.50 in Singapore. - DashScope: the name that survives in the API. The key variable in every official example is still
DASHSCOPE_API_KEY, and there is a native DashScope SDK as well.
Note: This guide uses QwenCloud because its docs are the most current and every example uses its endpoints. If you already have an Alibaba Cloud Model Studio key, keep using the base URL that Model Studio gave you, since keys only work with their own endpoint.
When the Qwen API is a good pick
- Low cost at scale: Qwen4-35B-A3B and Qwen3.8-Flash cost a fraction of US frontier models.
- Long context: the current models accept up to 1M tokens.
- Drop-in migration: if your app already uses the OpenAI SDK, you change three lines.
- Multimodal input: Qwen4 models accept images and video as well as text.
Current Qwen Model IDs, Including Qwen4
QwenCloud hosts dozens of models, including third-party ones like DeepSeek, Kimi and GLM. For most text apps you only need the five below. Prices are the Singapore (International) list prices per 1M tokens, checked on 4 December 2026.
| Model ID | Best for | Input / Output (per 1M) | Context | Thinking |
|---|---|---|---|---|
qwen4-max |
Hard reasoning, coding agents | $1.50 / $4.50 | 1M | Hybrid, on by default |
qwen4-35b-a3b |
Cheap multimodal work, high volume | $0.06 / $0.36 | 1M | Hybrid |
qwen3.8-flash |
Fast, low-cost chat and tools | $0.15 / $0.47 | 1M | Hybrid, on by default |
qwen3.7-plus |
Balanced quality and cost | $0.40 / $1.60 (up to 256K input) | Tiered above 256K | Hybrid, on by default |
qwen3.8-max |
Previous flagship | $2.00 / $6.00 | 1M | Hybrid, on by default |
Qwen4-35B-A3B is the newest one. QwenCloud’s changelog lists it on 4 December 2026 as an open-source mixture-of-experts model with 35B total parameters and about 3B active per step. It takes text, images and video, and outputs text. My Qwen4-35B-A3B guide covers its benchmarks and how to run the open weights locally.
Tip: The old ID qwen4-max-preview was retired on 25 November 2026. It still answers, but requests are routed to qwen4-max and billed at the full rate. Update your config to qwen4-max.
No qwen4-plus or qwen4-flash ID was listed in the QwenCloud changelog on 4 December. Use qwen3.7-plus and qwen3.8-flash until those arrive.
How to Get a Qwen API Key
You need a QwenCloud account with payment details. Adding a card is also what unlocks the free quota. The whole process takes a few minutes.
- Sign up. Go to qwencloud.com and create an account. The console lives at home.qwencloud.com.
- Add payment details. Complete your payment information. The Free Tier page asks for this before it grants the free quota.
- Choose the region first. Use the region selector in the top-right corner of the console. Pick Singapore if you want the free quota. Keys only work in the region where you create them.
- Create the key. Open API Keys, click Create API key, add a description, then click Generate Key.
- Copy it now. The full key is shown only once. After that, the list shows a masked version.
- Save it as an environment variable. On macOS or Linux run
export DASHSCOPE_API_KEY="your-key". On Windows PowerShell runsetx DASHSCOPE_API_KEY "your-key"and open a new terminal. - Install the SDK. Run
pip install -U openai. The examples use the standard OpenAI Python SDK interface, and version 3.63.0 was the latest on PyPI on 4 December 2026.
The official QwenCloud quickstart shows exactly this pattern: the standard OpenAI client, your key from the environment, and the Singapore base URL.

qwen4-max (checked 4 Dec 2026).Keep the key secret. Never paste the key into your code or a public repo. Anyone with it can run up charges on your account. If a key leaks, delete it in the API Keys page and make a new one.
Pay-as-you-go keys are different from Token Plan keys. Token Plan is a subscription with its own sk-sp- keys and its own endpoint. This tutorial uses pay-as-you-go, which needs no subscription.
Regions: International vs China Endpoints
QwenCloud runs in six regions. Each one has its own endpoint, keys, workspaces and model list. A key made in Singapore will fail against the Frankfurt or Beijing URL.
| Region | Region ID | Where inference runs | Free quota |
|---|---|---|---|
| Singapore | ap-southeast-1 |
International: nodes outside the Chinese mainland | Yes |
| China North 2 (Beijing) | cn-beijing |
The Chinese mainland | No |
| Germany (Frankfurt) | eu-central-1 |
Global or EU only (per workspace) | No |
| China (Hong Kong) | cn-hongkong |
Global or Hong Kong only | No |
| Japan (Tokyo) | ap-northeast-1 |
Global or Japan only | No |
| US (Virginia) | us-east-1 |
Global or US only | No |
The host is always {region}.maas.qwencloudapi.com. Add /compatible-mode/v1 for OpenAI-style calls, or /apps/anthropic for Anthropic-style clients.

Which region should you pick?
- Testing or hobby use: Singapore. It is the only region with the free quota.
- Users in mainland China: Beijing (
cn-beijing). Prices there are a little lower, for example $1.413 / $4.24 forqwen4-max. - EU data rules: Frankfurt with an EU-only workspace. The scope is fixed when you create the workspace.
- US apps: Virginia with a US-only workspace if data must stay in the US.
Be careful with “Global” scope. It can run inference on any node, including the Chinese mainland. If that matters for your data, choose a scope with a fixed geographic boundary.
Your First Qwen API Call in Python
This is the smallest working script. It uses the standard OpenAI client and only changes the key and base URL. Thinking is switched off here so the reply comes back fast.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://ap-southeast-1.maas.qwencloudapi.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen4-35b-a3b",
messages=[
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what an API key is in two sentences."},
],
extra_body={"enable_thinking": False},
)
print(completion.choices[0].message.content)
print(completion.usage)
The usage object tells you the input and output tokens for that call. Log it from day one, because it is the only way to match your code to your bill.
The same call with curl
With raw HTTP there is no extra_body. Put enable_thinking at the top level of the JSON body, next to model.
curl https://ap-southeast-1.maas.qwencloudapi.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen4-max",
"messages": [{"role": "user", "content": "Give me 3 names for a coffee shop."}],
"enable_thinking": false
}'
QwenCloud also supports the OpenAI Responses API (client.responses.create) on the same base URL. Chat Completions is the safer default because more Qwen parameters, such as thinking_budget, work there.
Streaming Responses
Streaming sends tokens as they are made, so users see text right away. QwenCloud’s docs also recommend it for long jobs, because long non-streaming calls can time out. Some open-source models only work in streaming mode.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://ap-southeast-1.maas.qwencloudapi.com/compatible-mode/v1",
)
stream = client.chat.completions.create(
model="qwen3.8-flash",
messages=[{"role": "user", "content": "Write a 5-line poem about rain."}],
extra_body={"enable_thinking": False},
stream=True,
stream_options={"include_usage": True},
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
if chunk.usage:
print("\n\nTokens:", chunk.usage.total_tokens)
The if chunk.choices check matters. The final chunk can carry only usage data and an empty choices list, which would crash a naive loop.
Thinking Mode: Turn It On, Off or Down
Most current Qwen models are hybrid: they can reason step by step before answering, or skip it. For qwen4-max and the Qwen3.8 models, thinking is on by default. The reasoning comes back in a separate reasoning_content field.
Stream the thinking and the answer separately
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://ap-southeast-1.maas.qwencloudapi.com/compatible-mode/v1",
)
stream = client.chat.completions.create(
model="qwen4-max",
messages=[{"role": "user", "content": "If 3x + 7 = 22, what is x?"}],
extra_body={"enable_thinking": True, "reasoning_effort": "low"},
max_completion_tokens=8192,
stream=True,
)
for chunk in stream:
if not chunk.choices:
continue
delta = chunk.choices[0].delta
thinking = getattr(delta, "reasoning_content", None)
if thinking:
print(thinking, end="", flush=True) # phase 1: reasoning
if delta.content:
print(delta.content, end="", flush=True) # phase 2: answer
The thinking controls
| Parameter | What it does | Notes for qwen4-max |
|---|---|---|
enable_thinking |
Turns reasoning on or off per request | Default on. Send False for fast, cheap replies. |
reasoning_effort |
Sets depth by level | Default high. minimal/low map to low, medium/high to high, xhigh/max to xhigh, none disables thinking. |
thinking_budget |
Caps thinking tokens | Default 131,072, max 262,144. Must be a positive integer. Chat Completions only. |
max_completion_tokens |
Caps thinking plus answer | Recommended. Not limited to 32,768. |
preserve_thinking |
Keeps earlier reasoning in multi-turn chats | On by default for qwen4-max. Pass old reasoning back in reasoning_content, never inside content. |
Warning: Do not send reasoning_effort and thinking_budget in the same request on qwen4-max or Qwen3.8 models. The API returns an error. Pick one.
Two more rules from the docs catch people out. With thinking on, the old max_tokens parameter only accepts 1 to 32,768, so use max_completion_tokens instead.
And thinking tokens are billed as output, so a long chain of thought can cost more than the answer itself. My reasoning effort and API cost guide shows how this works across providers.
Other Qwen3.8 models use a different default. For qwen3.8-max and qwen3.8-flash, the default effort is xhigh, and the levels are low, medium and xhigh.
Function Calling (Tools)
Function calling lets the model ask your code to run a tool, such as a weather lookup or a database query. QwenCloud says all its general text models support it, including qwen4-max and qwen4-35b-a3b. The format is the normal OpenAI tools array.
import json
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://ap-southeast-1.maas.qwencloudapi.com/compatible-mode/v1",
)
tools = [{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get today's weather for a city.",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name, e.g. Singapore"}
},
"required": ["location"],
},
},
}]
def get_current_weather(location):
# Replace with a real weather API call
return f"{location} is sunny today, 31 C."
messages = [{"role": "user", "content": "What's the weather in Singapore?"}]
first = client.chat.completions.create(
model="qwen4-max", messages=messages, tools=tools,
extra_body={"enable_thinking": False},
)
msg = first.choices[0].message
messages.append(msg)
if msg.tool_calls:
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
result = get_current_weather(**args)
messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
final = client.chat.completions.create(
model="qwen4-max", messages=messages, tools=tools,
extra_body={"enable_thinking": False},
)
print(final.choices[0].message.content)
else:
print(msg.content)
Tool rules worth knowing
- Every tool call needs a reply: an assistant message with
tool_callsmust be followed by atoolmessage for eachtool_call_id, or you get a 400 error. - tool_choice: the error docs say it accepts
"none"or"auto". Do not try to force a specific function. - With thinking on: send the assistant’s
reasoning_contentback along with tool results. The docs say leaving it out lowers accuracy. - Loops: the API rejects a history where the same tool call with the same arguments repeats over several rounds. Add a stop rule in your loop.
Qwen API Pricing With a Worked Example
You pay per million tokens, with separate prices for input and output. The table shows Singapore list prices and Beijing prices from QwenCloud’s model price pages on 4 December 2026. The console may show limited-time discounts on top.
| Model | Singapore input | Singapore output | Beijing input / output | Cache hit (Singapore) |
|---|---|---|---|---|
qwen4-max |
$1.50 | $4.50 | $1.413 / $4.24 | $0.075 |
qwen4-35b-a3b |
$0.06 | $0.36 | $0.057 / $0.339 | $0.003 |
qwen3.8-flash |
$0.15 | $0.47 | $0.113 / $0.382 | Discounted |
qwen3.7-plus (up to 256K input) |
$0.40 | $1.60 | $0.276 / $1.101 | Discounted |
qwen3.8-max |
$2.00 | $6.00 | $1.65 / $4.951 | Discounted |
For qwen4-max and qwen4-35b-a3b, the price is the same with thinking on or off. Thinking still costs more in practice because the reasoning tokens count as output.
qwen3.7-plus uses tiered pricing. If a single request has more than 256K input tokens, every token in that request is billed at the higher tier ($1.20 / $4.80).
Worked example: a support chatbot
Say your bot handles 10,000 requests a day. Each one sends 1,500 input tokens and gets 500 output tokens back, with thinking off. Over 30 days that is 450M input and 150M output tokens.
| Model | Input cost | Output cost | Monthly total |
|---|---|---|---|
qwen4-35b-a3b |
450 x $0.06 = $27 | 150 x $0.36 = $54 | $81 |
qwen3.8-flash |
450 x $0.15 = $67.50 | 150 x $0.47 = $70.50 | $138 |
qwen4-max |
450 x $1.50 = $675 | 150 x $4.50 = $675 | $1,350 |
Now a single hard question on qwen4-max with thinking on: 2,000 input tokens and 6,000 output tokens (most of it reasoning). That costs $0.003 + $0.027 = $0.03. Cheap once, but it adds up fast in an agent loop.
qwen4-35b-a3b or qwen3.8-flash with thinking off, and only move hard tasks to qwen4-max. To compare these numbers with other providers, see my AI API pricing comparison.Free Quota Rules
New QwenCloud accounts get a free token allowance for each model, typically 1,000,000 tokens. At about 2,000 tokens per request, that is roughly 500 test calls per model. The fine print matters, so here it is in one list.
- Singapore only: the quota only covers calls with a Singapore key sent to the Singapore endpoint. Other regions bill from the first token.
- 90 days: it starts on your account activation date. For models released later, such as
qwen4-35b-a3b, it starts on the model’s release date. - Per model: each model ID has its own quota. A dated snapshot and the undated alias count as separate models.
- Input and output together: both are taken from one shared total.
- Not covered: batch calls, built-in tool fees such as web search, fine-tuning and deployment.
- Payment details first: the quota appears after you complete your payment information.
To avoid surprise charges, go to the Free Tier page and turn on Free quota only for a model. Calls then stop with a 403 error when the quota runs out, instead of quietly switching to paid billing.
Limits You Should Know
Limits depend on the model, the region and your monthly spend. These are the figures QwenCloud lists for the new Qwen4 models.
| Limit | qwen4-35b-a3b | qwen4-max |
|---|---|---|
| Context window | 1,000,000 tokens | 1,000,000 tokens |
| Max input | 991K (no thinking), 983K (thinking) | Input and output share the 1M window |
| Max output | 128K (no thinking), 256K (thinking) | 131,072 (no thinking), 262,144 (thinking plus answer) |
| Rate limit | 5,000,000 TPM, 30,000 RPM | Tier based on monthly spend |
max_tokens with thinking on |
1 to 32,768 | 1 to 32,768 |
| Batch API | Beijing only (half price) | Beijing (half price) |
QwenCloud says your monthly spend sets your TPM tier. If you hit 429 errors often, check the Rate limits page in the console. My LLM API rate limits guide explains how tiers work across providers.
Troubleshooting: Common Qwen API Errors
These messages come straight from QwenCloud’s error reference. The fix column covers the usual cause for each.
| Error | Likely cause | Fix |
|---|---|---|
| 401 InvalidApiKey: “Invalid API-key provided.” | Key and base URL are from different regions, a Token Plan key on a pay-as-you-go URL, or a typo | Use a key made in the same region as the base URL. Check for stray spaces. |
| 404 model_not_found: “The model xxx does not exist or you do not have access to it.” | Model not offered in that region, or a wrong ID like qwen-4-max |
Use the exact ID and check the region’s model list. |
| 400 InvalidParameter: “Range of max_tokens should be [1, 32768]” | Large max_tokens with thinking on |
Use max_completion_tokens instead. |
| 400: “Json mode response is not supported when enable_thinking is true” | JSON mode with thinking on | Set enable_thinking to false for JSON-mode calls. |
| 400: “This model only support stream mode” | Non-streaming call to a streaming-only model | Add stream=True. |
| 400: “‘messages’ must contain the word ‘json’…” | response_format of type json_object without the word json in the prompt |
Mention JSON in the system or user message. |
| 400 Arrearage: “Access denied, make sure your account is in good standing.” | Unpaid balance or no payment method | Top up or fix billing in the console. |
| 403 AllocationQuota.FreeTierOnly | Free quota used up while “Free quota only” is on | Turn off the switch on the Free Tier page to allow paid calls. |
| 429 Throttling: “Requests throttling triggered.” | Too many requests or tokens per minute | Retry with exponential backoff and spread requests out. |
| 429 Throttling.BurstRate | Traffic ramped up too quickly | Increase load gradually. |
| 400 DataInspectionFailed | Input or output flagged by content checks | Rephrase the prompt or remove the flagged content. |
| Timeout on long prompts | Thinking plus non-streaming on a long input | Turn on streaming, turn off thinking, or raise the client timeout. |
If a reply stops mid-sentence, the model probably used up its output limit on thinking. Raise max_completion_tokens or lower reasoning_effort.
A simple retry wrapper
import time
from openai import OpenAI, RateLimitError, APIConnectionError
def ask_with_retry(client: OpenAI, **kwargs):
for attempt in range(5):
try:
return client.chat.completions.create(**kwargs)
except (RateLimitError, APIConnectionError):
wait = 2 ** attempt
print(f"Retrying in {wait}s...")
time.sleep(wait)
raise RuntimeError("Qwen API still failing after 5 tries")
For a broader look at handling errors in OpenAI-style SDKs, my OpenAI API Python tutorial covers the exception classes in more depth. The same classes apply here because you use the same client.
FAQ
Is the Qwen API free?
New QwenCloud accounts get about 1M free tokens per model for 90 days, but only in the Singapore region and only after adding payment details. After that, you pay per token.
Is QwenCloud the same as Alibaba Cloud Model Studio?
Both are Alibaba platforms that sell the same Qwen models. QwenCloud is the newer Qwen-branded developer platform, while Model Studio is the Alibaba Cloud console route. Keys from one do not work on the other’s endpoint.
What is the base URL for the Qwen API?
For Singapore it is https://ap-southeast-1.maas.qwencloudapi.com/compatible-mode/v1. For other regions, swap ap-southeast-1 for the region ID, such as cn-beijing or us-east-1.
Which Qwen model should I start with?
Start with qwen4-35b-a3b or qwen3.8-flash for low cost and speed. Move to qwen4-max only for hard reasoning or coding tasks.
How do I turn off thinking in the Qwen API?
Pass extra_body={"enable_thinking": False} in the OpenAI Python SDK. In raw HTTP, put "enable_thinking": false at the top level of the JSON body.
Can I use the Qwen API with the OpenAI SDK?
Yes. QwenCloud supports both Chat Completions and the Responses API in OpenAI format. You only change the API key and base URL.
Is Qwen4-35B-A3B available on the API?
Yes. It was added on 4 December 2026 with the model ID qwen4-35b-a3b, priced at $0.06 input and $0.36 output per 1M tokens in Singapore.
Sources
- QwenCloud docs: Build with QwenCloud (quickstart)
- QwenCloud docs: Regions, deployment scopes, and endpoints
- QwenCloud docs: Model prices
- QwenCloud docs: qwen4-35b-a3b model page
- QwenCloud docs: Model releases changelog
- QwenCloud docs: Thinking
- QwenCloud docs: Function calling
- QwenCloud API reference: OpenAI-compatible Chat
- QwenCloud docs: Get an API key
- QwenCloud docs: Free quota
- QwenCloud docs: Error messages
- Alibaba Cloud Model Studio: Model inference pricing
- Alibaba Cloud blog: Alibaba Cloud launches Qwen Cloud for global markets
- PyPI: openai Python package



