Draft

Switch an Existing OpenAI Client to Qwen4-Max Without Rewriting It

  • Not yet verified
  • Versions not pinned
  • 15 min read

Task

What you will complete

Point an existing OpenAI Chat Completions, OpenAI Responses, or Anthropic Messages client at qwen4-max on Beijing Model Studio by changing only the key, base URL, and model, with 免费额度用完即停 / Free Quota Only turned on, then confirm one request with a local check.

Success criteria

  • status_triage.py (or the matching Responses or Anthropic script) sends one request to qwen4-max after changing only the key, base URL, and model.
  • The local check accepts only a first word of low, medium, or high and exits 0.
  • {WorkspaceId} has been replaced in the base URL, and 免费额度用完即停 is on for qwen4-max.

What this is not

Not a rewrite of the app into a different protocol, not a quality bake-off against OpenAI, and not a multi-step tool loop. Skip this swap if the app cannot set a custom base_url, if you need qwen4-max-preview or a Token Plan host, or if the workload is batch inference, fine-tuning, or deploying your own copy of the model.

Prerequisites

  • An existing client that already speaks OpenAI Chat Completions, OpenAI Responses, or Anthropic Messages, and that can set a custom base_url.
  • A China-site (aliyun.com) Beijing Model Studio key and workspace ID, with 免费额度用完即停 turned on for qwen4-max.
  • Python and the official openai or anthropic package matching the protocol the app already uses.

Environment

DASHSCOPE_API_KEY
Beijing Model Studio API key
DASHSCOPE_BASE_URL
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1 for Chat Completions or Responses (replace WorkspaceId)
DASHSCOPE_ANTHROPIC_BASE_URL
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/apps/anthropic for Anthropic Messages (no trailing /v1)
QWEN_MODEL
qwen4-max (default in the example code)

Most Qwen “OpenAI-compatible” writeups start from a blank script. This one assumes you already have a client that talks to OpenAI, or to another host that already speaks Chat Completions, the Responses API, or Anthropic Messages. The job is narrower: point that client at qwen4-max on Alibaba Cloud Model Studio in China (Beijing), leave the request code you already have in place, and confirm one call still returns a shape your app can parse.

You change three settings: the key, the host, and the model name. Compatibility of the request shape does not mean every parameter you already send will keep its old behavior. Some OpenAI and Anthropic parameters are ignored, rejected, or given a different meaning once the host changes. This page names those mismatches, shows a before-and-after config for a small existing-style client, and stops at a local contract check. Nobody at this site has sent the swapped request to a Beijing key yet.

What to change Chat Completions or Responses Anthropic Messages
API key A regular China-site Beijing Model Studio key, not a Token Plan key if you want the new-user free grant The same Beijing key, sent as x-api-key or Authorization: Bearer
SDK base_url https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1 https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/apps/anthropic
Model qwen4-max qwen4-max

Hosts, limits, and parameter rules in the sections that follow were taken from official Model Studio documentation opened on 2026-11-17 (Asia/Shanghai). Planned commands are marked as not run. This page has no captured transcript, latency, or token count.

This page has no migrated request on record

The scripts next to this tutorial are in examples/. python3 -m py_compile accepted them. No process on this site has called OpenAI or Model Studio with those files.

Response fields and error codes in the sections below are quoted from official pages and labeled as such. Once a live Beijing run exists, this section should shrink to the date, the SDK version, and the contract-check output from that run.

Which protocol is the app already speaking?

Do not change protocol on the first swap. Identify the path the client already uses, then point that same path at Beijing.

  • If the code calls client.chat.completions.create, or posts to /v1/chat/completions and reads choices[0].message.content, it is on OpenAI Chat Completions. Keep that method. Model Studio documents Chat Completions compatibility for qwen4-max.
  • If it calls client.responses.create, or posts to /v1/responses and reads output_text (or the output array), it is on the OpenAI Responses API. Keep that method. The qwen4-max card lists Responses as supported. The SDK base_url is the same compatible-mode/v1 host as Chat Completions; only the path after it changes.
  • If it uses the Anthropic SDK (client.messages.create) or posts to /v1/messages with x-api-key, it is on Anthropic Messages. Keep that SDK. The Beijing host is different: it ends at /apps/anthropic, not at /compatible-mode/v1.

A client that hard-codes https://api.openai.com/v1 with no base_url hook is not a three-value edit away from Qwen. You will need a place to inject the Model Studio host before any of the configs below will stick. Assistants, Batch, image-generation edits, and other OpenAI surfaces are outside this page. The official qwen4-max card lists Chat Completions, Responses, Anthropic Messages, and DashScope. It also marks batch inference as unsupported.

What three values have to change, and which host should they point at?

For an OpenAI-compatible SDK, official compatibility docs say you migrate existing code by changing the API key, the base URL, and the model name. The same three-value instruction appears on the Anthropic Messages page, with a different base URL.

Use the workspace-specific Beijing host. Official pages recommend migrating China (Beijing) traffic from https://dashscope.aliyuncs.com to https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com, and they still describe the older DashScope host as usable. Copy {WorkspaceId} from 业务空间详情 in the console.

Protocol SDK base_url (Beijing, recommended) HTTP path you should see
Chat Completions https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1 POST .../compatible-mode/v1/chat/completions
Responses The same compatible-mode/v1 host POST .../compatible-mode/v1/responses
Anthropic Messages https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/apps/anthropic POST .../apps/anthropic/v1/messages

The Responses docs also warn that the older path /api/v2/apps/protocols/compatible-mode/v1/responses is no longer maintained. If a migrated Responses client still targets that path, change the path before you debug the key.

Keys are bound to the region that created them. The Chinese compatibility page says a Beijing key sent to a Virginia endpoint returns HTTP 401, message Incorrect API key provided, code invalid_api_key. That code means the key and the host do not share a region. It does not, by itself, mean the key was revoked.

A typo to avoid, re-checked on 2026-11-17. The English compatibility overview (Call Qwen models via OpenAI API, page stamped Last Updated Nov 16, 2026) still lists Beijing’s SDK BASE_URL as https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1. That is the Singapore region code. The same English page’s “Important” note correctly tells Beijing users to move to https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com. The Chinese compatibility page lists cn-beijing in the table itself. If you follow the English table and send a Beijing key to ap-southeast-1, the documented result is the 401 above.

The preview ID qwen4-max-preview belongs on a Token Plan key and host, and only for a short preview window. A regular Model Studio key should send the production ID qwen4-max.

What should be true in the Beijing console before you fire the first swapped request?

Stay on the China site and in Beijing. Sign up at aliyun.com, complete 实名认证 (real-name verification), and open the Model Studio console with the primary account or a RAM user that has AliyunBailianFullAccess. Official free-quota docs say the new-user grant is issued only in 华北2 / China (Beijing), only after real-name verification, and only on a regular API key. Token Plan and Coding Plan keys do not consume that grant.

On the qwen4-max model page, read on 2026-11-17, the China-site Beijing card lists a 1,000,000-token free allowance, with input and output sharing one pool, at a list price of CNY 10 per million input tokens and CNY 30 per million output tokens (output is thinking plus the answer). Official quota rules give the allowance a 90-day life. The clock starts at the later of three dates: when Model Studio was activated, when the model was listed, or when an application was approved. qwen4-max appeared on the official listing page on 2026-11-16. Ninety days from that date lands on 2027-02-14. An account that already existed on 2026-11-16 might have its clock pinned to the listing date rather than to a later activation. On 2026-11-17 that still leaves most of the window ahead, but only the console’s remaining balance and expiry date settle the question for a given account.

Before the first call, turn on 免费额度用完即停 for qwen4-max on the Beijing free quota page. In the English UI, the toggle is named Free Quota Only. Official pages say it is off by default. If it stays off, exhausting the grant does not stop the API; later calls are billed at the list price automatically. If you turn it on, a request past the grant is refused instead: the free-quota page documents HTTP 403 with error code AllocationQuota.FreeTierOnly, and says no further charge is taken. Treat that refusal as the protection you turned on, not as a reason to add credit.

Issue a regular key from the Beijing API Key settings screen, and take the workspace ID from the workspace details view. Nothing in that sequence requires a purchased pack, a foreign legal entity, or travel outside mainland China.

What does the before-and-after client look like?

examples/status_triage.py is a stand-in for a small app you already have. It sends one operations status line and expects a single word back: low, medium, or high. A local check accepts only those three words. The request body and the check do not change. Only the wiring does.

The “before” values look like any ordinary OpenAI client:

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])  # default host
completion = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[...],
)

The “after” values, for a China-site Beijing key, are:

client = OpenAI(
    api_key=os.environ["DASHSCOPE_API_KEY"],
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen4-max",
    messages=[...],
    reasoning_effort="none",
    max_completion_tokens=16,
)

Replace {WorkspaceId} before you call. The script also refuses to start if that placeholder is still in the URL.

qwen4-max documents thinking as on by default (enable_thinking true, reasoning_effort high, thinking_budget 131,072). A one-word label does not need that budget, and thinking tokens come out of the same million-token grant. The example therefore sends reasoning_effort="none", which the model card lists as the way to turn thinking off, and caps the completion with max_completion_tokens=16. Those choices are documented, not measured. If a live call rejects reasoning_effort="none", keep the error; do not invent a fallback from this page.

The planned command, which has not been run:

export DASHSCOPE_API_KEY='your-beijing-key'
export DASHSCOPE_BASE_URL='https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1'
python3 examples/status_triage.py

A later verified revision should paste the printed label, response.model, finish_reason, and token counts. Until then, there is nothing to quote.

If the existing app is already on Responses or Anthropic Messages, do not rewrite it into Chat Completions just to follow the script above. examples/responses_swap.py and examples/anthropic_swap.py show only the constructor change for those two protocols. A Responses client should read output_text. An Anthropic client must keep sending max_tokens, which the Messages docs mark as required, and its SDK base_url must stop at /apps/anthropic with no trailing /v1.

You can make this edit in an ordinary Python environment, or in a coding agent such as Codex or Grok Bot that can change the three values and run the script. The steps on this page do not require a Cursor account or a Claude Code account.

Which of your current parameters will not survive the swap?

Compatibility here means the request shape, not identical behavior. Walk the parameters your client already sends and adjust the ones below before the first call, especially if you care about staying inside the free grant.

Chat Completions

  • tool_choice="required" is not a reliable carry-over. The Chat Completions parameter reference says Qwen models currently do not support required: without thinking, a tool call is not guaranteed; with thinking, required is not supported. Forcing a named function with {"type": "function", "function": {"name": "..."}} is also documented as unsupported in thinking mode. auto and none remain the safe values for a first swap. This page does not walk through a tool-calling job; if you need that, use the separate Qwen4-Max tool-calling tutorial in this cluster.
  • n must stay at 1 when tools are present. The same reference says: if you pass tools, set n to 1.
  • enable_thinking and thinking_budget are not standard OpenAI fields. In the official Python SDK they belong in extra_body (for example extra_body={"enable_thinking": False}). If you post JSON with curl or another HTTP client, put those two fields in the same object as model and messages; there is no extra_body wrapper on the wire. Passing them only as top-level keyword arguments to the Python SDK is a usual way to have them dropped without an error.
  • Do not set reasoning_effort and thinking_budget on the same qwen4-max request. The Chat Completions reference says that combination is unsupported. thinking_budget must be a positive integer; it cannot be 0. If you set only thinking_budget, the docs map 1–4096 to low, 4097–131072 to high, and 131073–262144 to xhigh. If you set neither, the documented default is reasoning_effort=high and thinking_budget=131072.
  • reasoning_effort values are mapped, not passed through unchanged. For qwen4-max, the model card and the Chat Completions reference map minimal and low to low; medium and high to high; xhigh and max to xhigh; and none to thinking off. If your OpenAI app sends medium or minimal, the effective Qwen effort will not be a distinct middle or “tiny” tier.
  • max_tokens is deprecated. New requests should use max_completion_tokens. For qwen4-max specifically, an API compatibility upgrade dated 2026-11-02 says max_tokens is now equivalent to max_completion_tokens: it caps thinking and the answer together. On older Qwen models the same field sometimes capped only the answer. A budget that used to leave room for a hidden chain of thought may now truncate the whole output, with finish_reason length.

Responses API

  • Unlisted OpenAI parameters are ignored. The create-response reference states the rule directly: only parameters listed in that document are processed; any other OpenAI parameter is ignored. A flag that used to change behavior on OpenAI can become a no-op here without raising an error.
  • background is not supported. The same page says the API is synchronous only.
  • Long inputs can be truncated without an error. To leave room for built-in tools and reasoning, the documented maximum input is about 80% of the model’s context window. Anything past that is cut automatically. The request does not fail, so a migrated client can look “successful” while the model never saw the end of the prompt.
  • previous_response_id is only as durable as its documented lifetime. Official examples say the previous response id is valid for 7 days, and that you must pass the top-level response id, not an id from the output array.
  • reasoning.effort is the Responses-side control. A guide example notes that it takes priority over enable_thinking, and that thinking_budget is not the way to cap thinking length on that API.

Anthropic Messages

  • temperature is allowed in [0, 2), which is wider than Anthropic’s documented [0.0, 1.0]. A value that was legal on Anthropic remains legal here; a value you might later raise toward 2 needs a check against that half-open range.
  • There is no /v1/models endpoint. Clients that probe model discovery get HTTP 404. Official FAQ text says to add the model name by hand and to keep the SDK base_url at /apps/anthropic. A base URL that already ends in /v1 can produce a doubled /v1/v1/models path, which also 404s.
  • max_tokens is required. An OpenAI-style client that omitted it will not port to this protocol unchanged.
  • output_config.effort is a Model Studio extension. It is not in Anthropic’s public SDK types and has to be passed through in the request body. thinking.budget_tokens is documented as on the way out; new integrations are told to use output_config.effort instead.

Which errors after the swap are usually wiring, not a bad model?

These codes are from official error and quota pages. They have not been reproduced here.

  • HTTP 401, invalid_api_key, message Incorrect API key provided. The key, the region, and the host do not match. A Beijing key does not authenticate on a Singapore or Virginia base_url. Following the English overview’s Beijing typo (ap-southeast-1) is enough to land here. A Token Plan key is also the wrong credential for this free-quota path: official quota docs say those dedicated keys do not draw from the new-user grant, and the preview model uses a different host.
  • HTTP 404 on the model, or model_not_found. Check the ID. qwen4-max is the production ID for a regular key. qwen4-max-preview does not belong on this host.
  • HTTP 404 on /v1/models from an Anthropic-compatible client. That probe is expected to fail. The Messages compatibility endpoint only serves /v1/messages. Fix the base URL if you see /v1/v1/, and set qwen4-max explicitly.
  • HTTP 403, AllocationQuota.FreeTierOnly. 免费额度用完即停 is on, and the free grant is exhausted or expired. This is the stop you asked for. It is not a reason to top up. If you still have console balance and this is the first call, check that you enabled the switch on qwen4-max itself and that you are not using a Token Plan key, which does not draw from this grant.
  • HTTP 429 for rate or allocation limits. The compatibility overview also lists 429 when a quota is exceeded or the account is in arrears. Treat 429 as a limit or billing signal, and read the body; do not assume it is the same event as AllocationQuota.FreeTierOnly.
  • A Responses call that returns 200 but a thinner answer than the prompt should have produced. If the input was large, suspect the documented 80% silent truncation, or a parameter the Responses reference does not list and therefore ignores.
  • finish_reason: length on a short visible answer. Thinking and the answer share max_completion_tokens on qwen4-max. Raise the cap, or send reasoning_effort="none" for a smoke test.
  • The local check in status_triage.py exits with local check failed. The HTTP call may have succeeded. The model did not return one of low, medium, or high as the first word. Keep the raw content. That is useful evidence for a later verified revision; it is not, by itself, proof that the wiring is wrong.

When is changing those three values the wrong move?

Skip this swap if the app cannot set a custom base_url. Without that hook, you are editing the HTTP stack, not migrating a client.

Skip it if you need qwen4-max-preview or a Token Plan host. Those credentials and URLs are not the Beijing free-quota path described here.

Skip it if the workload is batch inference, fine-tuning, or deployment of your own copy of the model. The qwen4-max card lists all three as unsupported, and the free grant would not cover them anyway.

Skip it if you are already on the international site and expected a Singapore free allowance. That is a different account, a different region, and a different set of English quota pages. A reader working in mainland China should keep the account on aliyun.com and the key in Beijing, rather than mixing the two sites.

Skip it if the first thing you need is a quality bake-off against OpenAI, or a multi-step tool loop. This page only confirms that one request still speaks the protocol. A comparison of Beijing free grants, and a tool-calling walkthrough on qwen4-max, are separate tutorials in this cluster.

And skip it as a “rewrite later” promise to yourself if the client already depends on an OpenAI-only parameter that Model Studio documents as ignored or unsupported — background on Responses, tool_choice="required" on Qwen Chat Completions, or Anthropic model discovery. Fix those dependencies first, or the three-value swap will look finished while the app’s real path is not.

What a verified revision still has to show

Verification needs a China-site Beijing key, 免费额度用完即停 enabled for qwen4-max, {WorkspaceId} replaced in the base URL, and one run of status_triage.py (or the matching Responses or Anthropic script) whose local check passes. The revision should record the SDK version, the printed response.model, finish_reason, and token usage, and any error that appeared before a successful call. Until that run is on file, every command and every response field here remains a documentation claim, not a measured result.

Sources

Each link below was opened on 2026-11-17, Asia/Shanghai:

  • qwen4-max model page and the English model card: model ID, support for OpenAI Chat Completions, Responses, Anthropic Messages, and DashScope, default thinking settings, reasoning_effort mappings, Beijing list price CNY 10 / 30, the 1,000,000-token free allowance, and no batch or fine-tuning.
  • OpenAI Chat接口兼容 and the English compatibility overview: the three-value migration, workspace and legacy hosts, region-bound keys, the 401 region-mismatch example, and the English Beijing ap-southeast-1 typo, still present on this date.
  • OpenAI兼容-Chat: tool_choice limits on Qwen, n with tools, enable_thinking / thinking_budget via extra_body, the reasoning_effort and thinking_budget conflict on qwen4-max, and max_tokens versus max_completion_tokens.
  • API 兼容性升级 (2026-11-02): from qwen4-max onward, max_tokens caps thinking plus the answer.
  • 创建响应 and OpenAI Responses接口兼容: ignored unlisted parameters, no background, 80% silent input truncation, previous_response_id lifetime, the retired Responses path, and output_text.
  • Anthropic兼容-Messages: the /apps/anthropic host, required max_tokens, temperature range [0, 2), no /v1/models, and output_config.effort.
  • 新人免费额度: Beijing-only grant on the China site, 90-day clock, per-model pools, 实名认证, 用完即停 off by default, HTTP 403 / AllocationQuota.FreeTierOnly, and Token Plan keys not drawing from the grant.
  • Base URL总览: legacy DashScope hosts for OpenAI-compatible and Anthropic-compatible calls.

Third-party pages were opened for search context, not as a source of limits:


Title tag: Switch an Existing OpenAI Client to Qwen4-Max

Meta description: Point an existing OpenAI or Anthropic client at qwen4-max on Beijing Model Studio by changing the key, base URL, and model, then confirm one request. Official compatibility notes; not yet verified on a live key.

Slug: switch-openai-client-to-qwen4-max

Evidence it actually ran

This is the shape of the stamp. It has not been earned, and the example date that follows is a placeholder, not a run: Ran on YYYY-MM-DD (Asia/Shanghai) with the pinned versions.

Command output
None recorded. A verified revision will quote the output from the run, not a sample written in advance.
Tests, CI, or Inspector
Not run for this draft.
Repository or config
No link recorded.

Failure modes

Anticipated only. None of these has been checked against a run of this tutorial.

  • Unchecked

    HTTP 401 invalid_api_key, Incorrect API key provided

    The key, the region, and the host do not match. A Beijing key does not authenticate on a Singapore or Virginia base_url. Following the English overview's Beijing typo (ap-southeast-1) is enough to land here. A Token Plan key is also the wrong credential for this free-quota path.

  • Unchecked

    HTTP 404 on the model, or model_not_found

    Check the ID. qwen4-max is the production ID for a regular key. qwen4-max-preview does not belong on this host.

  • Unchecked

    HTTP 404 on /v1/models from an Anthropic-compatible client

    That probe is expected to fail. The Messages compatibility endpoint only serves /v1/messages. Fix the base URL if you see /v1/v1/, and set qwen4-max explicitly.

  • Unchecked

    HTTP 403 AllocationQuota.FreeTierOnly

    免费额度用完即停 is on, and the free grant is exhausted or expired. This is the stop you asked for. It is not a reason to top up.

  • Unchecked

    HTTP 429 for rate or allocation limits

    The compatibility overview also lists 429 when a quota is exceeded or the account is in arrears. Treat 429 as a limit or billing signal, and read the body; do not assume it is the same event as AllocationQuota.FreeTierOnly.

  • Unchecked

    A Responses call returns 200 but a thinner answer than the prompt should have produced

    If the input was large, suspect the documented 80% silent truncation, or a parameter the Responses reference does not list and therefore ignores.

  • Unchecked

    finish_reason: length on a short visible answer

    Thinking and the answer share max_completion_tokens on qwen4-max. Raise the cap, or send reasoning_effort="none" for a smoke test.

  • Unchecked

    The local check in status_triage.py exits with local check failed

    The HTTP call may have succeeded. The model did not return one of low, medium, or high as the first word. Keep the raw content. That is useful evidence for a later verified revision; it is not, by itself, proof that the wiring is wrong.

Other tutorials in Migrate.