Draft

Call Qwen4-Max Through the OpenAI-Compatible API and Finish a Tool-Calling Task

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

Task

What you will complete

Call qwen4-max from the OpenAI SDK on Alibaba Cloud Model Studio in Beijing by changing only api_key, base_url, and model, stay on that model's official free quota with 免费额度用完即停 / Free Quota Only turned on, then finish a tool-calling job: a checked dependency report for an npm project.

Success criteria

  • quickstart.py prints an answer and a usage object from qwen4-max, with no code change beyond api_key, base_url and model.
  • stream.py prints the answer as it arrives and ends with a usage line.
  • dependency_report.py exits 0: the model read package.json through the tools, wrote out/dependency-report.md, and the script's own model-free check found every declared package in it.

What this is not

Not a launch roundup, a benchmark comparison, or a guide to Token Plan or qwen4-max-preview. You do not need a new SDK, a Token Plan, or a foreign legal entity for this path.

Prerequisites

  • A China-site (aliyun.com) Alibaba Cloud account with real-name verification (实名认证) completed, and Model Studio activated by signing in to the console.
  • A Beijing / 华北2 Model Studio API key, created in the same region as the endpoint you will call, and the workspace ID from the console's workspace details page.
  • 免费额度用完即停 (Free Quota Only) turned on for qwen4-max on the Beijing free-quota page, before any call.
  • Python 3.9 or newer and the openai package. Node.js only if you want the optional Node snippet.
  • Any npm project with a package.json to audit. This site's own repository works.

Environment

DASHSCOPE_API_KEY
Beijing Model Studio API key from the same region as QWEN_BASE_URL
QWEN_BASE_URL
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1 (the older https://dashscope.aliyuncs.com/compatible-mode/v1 is still documented as working)
QWEN_MODEL
qwen4-max (default in the example code)

If you already call chat completions with the official OpenAI SDK, you can point that same client at Qwen4-Max. You do not need a new SDK, a Token Plan, or a foreign legal entity. This walkthrough uses Alibaba Cloud Model Studio in China (Beijing), stays on the official free quota, and finishes with a tool-calling job that audits a package.json and then checks the report without the model.

Here is the path, in short:

  • Use the model ID qwen4-max. Do not send qwen4-max-preview to a regular Model Studio key.
  • Sign up on the Alibaba Cloud China site (aliyun.com), complete real-name verification, and create the key in China (Beijing). That is the path that works from mainland China.
  • After Model Studio is activated, qwen4-max has a 1,000,000-token free quota on the China site in Beijing, valid for 90 days. Input and output tokens share that pool, and the quota is not shared with other models. Turn on 免费额度用完即停 (the English docs call this Free Quota Only). It is off by default. If you leave it off and the quota runs out, later calls flip to pay-as-you-go on their own.
  • Point the SDK at https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1. The older https://dashscope.aliyuncs.com/compatible-mode/v1 is still documented as working.
  • Change only api_key, base_url, and model. Then run the package.json audit.

Prices, limits, and response shapes below come from official Model Studio documentation read on 2026-11-17 (Asia/Shanghai). Nobody at Actually Ran has run this code against qwen4-max yet. There is no captured terminal output on this page, and nothing below is a measured result.

This page is not yet verified

The example scripts live next to this tutorial in examples/qwen4-max-openai-compatible/. They have been syntax-checked with python -m py_compile and node --check. That is all.

Where the docs describe the shape of a response, the page says so and labels it as documented, not observed. When a real run exists, this note will be replaced with the date, package versions, and the output from that run.

Should you use qwen4-max or qwen4-max-preview?

Model Studio lists two IDs. They are not interchangeable. This tutorial uses qwen4-max.

qwen4-max-preview qwen4-max
Listed 2026-11-11 2026-11-16
Access Token Plan only. Pay-as-you-go and the regular free-quota key are not supported. Regular Model Studio API key (the key you create in the Beijing console)
Key and base URL Token Plan’s dedicated key and base URL (https://token-plan.cn-beijing.maas.aliyuncs.com or https://token-plan.ap-southeast-1.maas.aliyuncs.com) A normal Model Studio key and the region’s compatible-mode/v1 base URL
Lifetime Preview runs 2026-11-11 10:00 to 2026-11-25 24:00 (UTC+8), then the model is retired Production model. The preview page itself recommends switching to it.
Context 1M tokens 1M tokens
Output budget 393,216 tokens, shared by thinking and the answer 262,144 tokens for thinking plus the answer; 131,072 maximum output with thinking off
Reasoning effort (Chat Completions) low, medium, xhigh (default xhigh) low, high, xhigh (default high)

If you only hold a Token Plan subscription, follow the preview model’s own quick-start page. This tutorial’s base URL and key rules do not apply there.

The qwen4-max model page lists the same capability set in both cases: text, image, and video input; text output; thinking on by default; function calling with parallel tool calls; structured output; web search; explicit and implicit caching; and compatibility with OpenAI Chat Completions, OpenAI Responses, Anthropic Messages, and DashScope. Batch inference and fine-tuning are listed as not supported for qwen4-max.

How do you stay on the Beijing free quota?

Start on the China site, in Beijing. Do not treat a top-up or a pay-as-you-go plan as a prerequisite.

  1. Create or sign in to an Alibaba Cloud account on aliyun.com. Complete real-name verification (实名认证). The free-quota docs say the quota is not issued until that is done.
  2. Sign in to the Model Studio console (百炼) with the primary account, or with a RAM user that has AliyunBailianFullAccess. The docs say the service is activated automatically on that first login. You do not buy a package to get the new-user quota.
  3. Stay in China (Beijing) / 华北2. On the China site, the pricing and free-quota pages both say the free quota is offered only in this region. The quota may take up to two hours to show up; models that have one are marked with a blue quota bar.
  4. Open the Beijing free quota page. Find qwen4-max and turn on 免费额度用完即停. You can also flip it on the model’s own page, or use the page’s batch control. The switch is off by default. Leave it off, and when the free tokens run out the next call is billed at the list price. Turn it on, and the service stops instead. The official English name for the same switch is Free Quota Only.
  5. Create an API key on the Beijing API Key page. Copy the full key immediately; the docs say a new key is shown in full only once. Create the key in the same region you will call. A Beijing key sent to a Singapore or Virginia endpoint returns HTTP 401 with Incorrect API key provided and code invalid_api_key, even though the key itself is valid.
  6. Copy your workspace ID from the console’s workspace details page (业务空间详情). You need it for the recommended base URL.

The free quota, as documented on 2026-11-17:

  • 1,000,000 tokens for qwen4-max in Beijing on the China site.
  • Valid for 90 days, counted from Model Studio activation, the model’s release, or application approval, whichever is later.
  • Input and output tokens deduct from the same pool. The console shows one remaining total, not separate input and output balances.
  • Each model has its own quota. Exhausting qwen4-max does not spend, or unlock, another model’s tokens, and the platform will not switch models for you.
  • The quota covers real-time inference only. It does not cover batch calls, fine-tuning, or deployment. Those do not apply to qwen4-max anyway: the model page lists batch inference and fine-tuning as unsupported.
  • An Alibaba Cloud primary account and its RAM users share one quota for the same model. Re-registering under the same real-name identity does not grant a second new-user quota.

A note on the international site. The English pricing and free-quota pages are the mirror image of the China site: they offer a 1,000,000-token free quota in Singapore (International scope) and say other regions have none. QwenCloud’s own docs also describe a Singapore pay-as-you-go free allowance and a host of the form https://ap-southeast-1.maas.qwencloudapi.com/compatible-mode/v1, with no workspace ID. This tutorial does not use that path, and this site has not verified whether a China-site Beijing key works on the QwenCloud host. If you already have an international-site account, follow those English pages for Singapore. If you are working from mainland China, stay on aliyun.com and Beijing.

Which base URL should a Beijing key use?

Official Model Studio docs currently show two working forms for Beijing OpenAI-compatible calls:

Form Base URL What the docs say
Recommended workspace domain https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1 Introduced for better performance and stability. This is the form the compatibility and Chat Completions pages tell you to migrate to.
Legacy domain https://dashscope.aliyuncs.com/compatible-mode/v1 “The existing domain remains fully functional.” The get-API-key page still gives this URL for third-party tools.

The base URL ends at /compatible-mode/v1. Do not append /chat/completions when you use the OpenAI SDK; the SDK adds that path. Replace {WorkspaceId} with the ID from the workspace details page. There is no separate “free quota endpoint.” The same Beijing URL is used whether you are still inside the free allowance or, later, paying list price.

One documentation typo to ignore: as of 2026-11-17, the English OpenAI compatibility overview still prints ap-southeast-1 under the Beijing heading. Its own migration note, the Chinese compatibility page, and the English Chat Completions page all use cn-beijing for Beijing. This tutorial uses cn-beijing.

Set the three variables the example code reads:

export DASHSCOPE_API_KEY="sk-..."   # created in Beijing, same region as the URL below
export QWEN_BASE_URL="https://<WorkspaceId>.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
export QWEN_MODEL="qwen4-max"

If you want to try the legacy host first, set QWEN_BASE_URL to https://dashscope.aliyuncs.com/compatible-mode/v1 instead. Keep the Beijing key either way.

What is the smallest OpenAI SDK change that works?

Install the OpenAI SDK. The examples folder leaves the package unpinned on purpose; a verified version of this page will pin the exact version it ran.

cd examples/qwen4-max-openai-compatible
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt

quickstart.py is a normal OpenAI SDK call. The only Model Studio-specific values are the key, the base URL, and the model ID.

import os

from openai import OpenAI

client = OpenAI(
    api_key=os.environ["DASHSCOPE_API_KEY"],  # key created in the SAME region as base_url
    base_url=os.environ["QWEN_BASE_URL"],  # e.g. https://<WorkspaceId>.cn-beijing.maas.aliyuncs.com/compatible-mode/v1
)

completion = client.chat.completions.create(
    model=os.environ.get("QWEN_MODEL", "qwen4-max"),
    messages=[
        {"role": "system", "content": "You are a concise assistant for software engineers."},
        {"role": "user", "content": "In one sentence, what does an OpenAI-compatible endpoint mean?"},
    ],
)

print(completion.choices[0].message.content)
print(completion.usage)

Planned command. Not run for this draft.

python quickstart.py

Documented response shape, not observed output. Model Studio’s compatibility page documents an OpenAI-style chat.completion object: choices[0].message with role assistant and content, finish_reason of stop or length, and usage with prompt_tokens, completion_tokens, and total_tokens. The page’s own sample response is from an older model, so this tutorial does not reproduce it.

Thinking is on by default for qwen4-max. Per the deep-thinking docs, the thinking text comes back in a separate reasoning_content field and the answer stays in content, so code that reads message.content keeps working.

The same call from the official Node SDK, in quickstart.mjs:

import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.DASHSCOPE_API_KEY,
  baseURL: process.env.QWEN_BASE_URL,
});

const completion = await client.chat.completions.create({
  model: process.env.QWEN_MODEL ?? "qwen4-max",
  messages: [
    { role: "system", content: "You are a concise assistant for software engineers." },
    { role: "user", content: "In one sentence, what does an OpenAI-compatible endpoint mean?" },
  ],
});

console.log(completion.choices[0].message.content);
console.log(completion.usage);

How do you stream the answer and still get token usage?

stream.py sets stream=True and stream_options={"include_usage": True}. The compatibility docs say the token usage then arrives on a final chunk whose choices list is empty, so the loop checks for that before touching choices[0]. Thinking tokens arrive in delta.reasoning_content before the answer in delta.content.

stream = client.chat.completions.create(
    model=os.environ.get("QWEN_MODEL", "qwen4-max"),
    messages=[{"role": "user", "content": "Explain HTTP 429 to a junior developer in three bullet points."}],
    stream=True,
    stream_options={"include_usage": True},
)

shown_answer_header = False
for chunk in stream:
    if chunk.usage is not None:  # the final chunk carries usage and an empty choices list
        print(f"\n\n[usage] {chunk.usage}")
        continue
    if not chunk.choices:
        continue
    delta = chunk.choices[0].delta
    reasoning = getattr(delta, "reasoning_content", None)
    if reasoning:
        print(reasoning, end="", flush=True)
    if delta.content:
        if not shown_answer_header:
            print("\n\n--- answer ---\n")
            shown_answer_header = True
        print(delta.content, end="", flush=True)

The full file, with the client setup, is examples/qwen4-max-openai-compatible/stream.py.

Planned command. Not run for this draft.

python stream.py

Can tool calling finish a real job, not just a weather demo?

Official function-calling samples usually ask the model for the weather in one city. That shows the message shape. It does not tell you whether the model will inspect a real project and leave a file you can check.

This task is narrower, and it is checkable. The model gets three local tools and nothing else. It has to inspect an npm project and save a Markdown report. Then the script checks the report without the model: every name under dependencies and devDependencies in package.json has to appear in it. Exit code 0 means the check passed. A fluent final message is not enough.

The tools:

  • list_dir(path) returns the names in a directory inside the project root, skipping node_modules/ and .git/.
  • read_text_file(path) returns one UTF-8 file inside the project root, capped at 200 KB.
  • write_report(markdown) writes out/dependency-report.md next to the script.

Paths from the model are resolved and refused if they leave the project root. Tool errors go back to the model as text instead of crashing the loop.

The complete dependency_report.py is below. This is the script to save and run, not output from a qwen4-max run. Nobody at Actually Ran has executed it against the model yet. The same file also lives at examples/qwen4-max-openai-compatible/dependency_report.py.

"""Real task: have Qwen4-Max audit an npm project's package.json through tool calls.

The model can only reach the project through three local tools:
  list_dir(path)            -> names inside the project root
  read_text_file(path)      -> text of one file inside the project root (size-capped)
  write_report(markdown)    -> writes ./out/dependency-report.md

After the model finishes, this script checks the report itself, without the model:
every dependency and devDependency name in package.json must appear in the report.
Exit code 0 means the check passed; 1 means it did not.

Usage:
  export DASHSCOPE_API_KEY=...        # Beijing key from the same region as QWEN_BASE_URL
  export QWEN_BASE_URL=https://<WorkspaceId>.cn-beijing.maas.aliyuncs.com/compatible-mode/v1
  # legacy form still documented: https://dashscope.aliyuncs.com/compatible-mode/v1
  python dependency_report.py /path/to/an/npm/project

Turn on Free Quota Only / 免费额度用完即停 before you run this.
Not run yet by Actually Ran. Written from Alibaba Cloud Model Studio docs.
"""
from __future__ import annotations

import json
import os
import sys
from pathlib import Path

from openai import OpenAI

MODEL = os.environ.get("QWEN_MODEL", "qwen4-max")
MAX_TURNS = 8
MAX_FILE_BYTES = 200_000
OUT_DIR = Path(__file__).resolve().parent / "out"
REPORT_PATH = OUT_DIR / "dependency-report.md"

TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "list_dir",
            "description": "List files and folders in a directory inside the project. Use '.' for the project root.",
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {"type": "string", "description": "Directory path relative to the project root."}
                },
                "required": ["path"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "read_text_file",
            "description": "Read a UTF-8 text file inside the project, such as package.json.",
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {"type": "string", "description": "File path relative to the project root."}
                },
                "required": ["path"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "write_report",
            "description": "Save the finished dependency report as Markdown. Call this exactly once, at the end.",
            "parameters": {
                "type": "object",
                "properties": {
                    "markdown": {"type": "string", "description": "The complete report in Markdown."}
                },
                "required": ["markdown"],
            },
        },
    },
]

SYSTEM_PROMPT = (
    "You audit npm projects. Use the tools to inspect the project; never guess file contents. "
    "Write a Markdown report with these sections: "
    "1) Scripts: a table of every npm script and its command. "
    "2) Dependencies: a table of every dependency and devDependency with its version range and kind. "
    "3) Ranges: list each package whose range starts with ^ or ~ and say what that allows. "
    "4) Runtime: the Node engine requirement, or 'not declared'. "
    "Name every package exactly as written in package.json. Then call write_report once and stop."
)


def resolve_inside(root: Path, relative: str) -> Path:
    """Resolve a model-supplied path and refuse anything outside the project root."""
    candidate = (root / relative).resolve()
    if candidate != root and root not in candidate.parents:
        raise ValueError(f"path escapes the project root: {relative}")
    return candidate


def run_tool(root: Path, name: str, args: dict) -> str:
    try:
        if name == "list_dir":
            target = resolve_inside(root, args.get("path", "."))
            entries = sorted(p.name + ("/" if p.is_dir() else "") for p in target.iterdir())
            skipped = {"node_modules/", ".git/"}
            return json.dumps([e for e in entries if e not in skipped])
        if name == "read_text_file":
            target = resolve_inside(root, args["path"])
            data = target.read_bytes()[:MAX_FILE_BYTES]
            return data.decode("utf-8", errors="replace")
        if name == "write_report":
            OUT_DIR.mkdir(parents=True, exist_ok=True)
            REPORT_PATH.write_text(args["markdown"], encoding="utf-8")
            return f"saved {REPORT_PATH.name} ({len(args['markdown'])} characters)"
        return f"error: unknown tool {name}"
    except Exception as exc:  # tool errors go back to the model as text, not as a crash
        return f"error: {type(exc).__name__}: {exc}"


def assistant_message_to_dict(message) -> dict:
    """Keep only the fields the next request needs, including reasoning_content if thinking was on."""
    entry: dict = {"role": "assistant", "content": message.content or ""}
    reasoning = getattr(message, "reasoning_content", None)
    if reasoning:
        entry["reasoning_content"] = reasoning
    if message.tool_calls:
        entry["tool_calls"] = [
            {
                "id": call.id,
                "type": "function",
                "function": {"name": call.function.name, "arguments": call.function.arguments},
            }
            for call in message.tool_calls
        ]
    return entry


def check_report(root: Path) -> list[str]:
    """Model-free check: every declared package name must appear in the saved report."""
    if not REPORT_PATH.exists():
        return ["report file was not written"]
    package = json.loads((root / "package.json").read_text(encoding="utf-8"))
    names = list(package.get("dependencies", {})) + list(package.get("devDependencies", {}))
    report = REPORT_PATH.read_text(encoding="utf-8")
    return [f"missing from report: {name}" for name in names if name not in report]


def main() -> int:
    root = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
    if not (root / "package.json").is_file():
        print(f"No package.json in {root}", file=sys.stderr)
        return 2
    if REPORT_PATH.exists():
        REPORT_PATH.unlink()  # never let an old report pass the check

    client = OpenAI(api_key=os.environ["DASHSCOPE_API_KEY"], base_url=os.environ["QWEN_BASE_URL"])
    messages: list[dict] = [
        {"role": "system", "content": SYSTEM_PROMPT},
        {"role": "user", "content": "Audit the npm project at the project root and save the report."},
    ]
    total_prompt = total_completion = 0

    for turn in range(1, MAX_TURNS + 1):
        completion = client.chat.completions.create(
            model=MODEL,
            messages=messages,
            tools=TOOLS,
            # Model Studio's own function-calling examples for qwen4-max turn thinking off.
            # Remove this line to keep thinking on; reasoning_content is then sent back each turn.
            extra_body={"enable_thinking": False},
        )
        if completion.usage:
            total_prompt += completion.usage.prompt_tokens
            total_completion += completion.usage.completion_tokens
        message = completion.choices[0].message
        messages.append(assistant_message_to_dict(message))

        if not message.tool_calls:
            print(f"[turn {turn}] model finished: {(message.content or '').strip()[:300]}")
            break

        # parallel_tool_calls defaults to true, so handle every call in the list, in order.
        for call in message.tool_calls:
            try:
                args = json.loads(call.function.arguments or "{}")
            except json.JSONDecodeError:
                args = {}
                result = f"error: arguments were not valid JSON: {call.function.arguments!r}"
            else:
                result = run_tool(root, call.function.name, args)
            print(f"[turn {turn}] tool {call.function.name}({json.dumps(args)[:120]}) -> {result[:80]!r}")
            messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
    else:
        print(f"Stopped after {MAX_TURNS} turns without a final answer.", file=sys.stderr)

    print(f"[usage] prompt_tokens={total_prompt} completion_tokens={total_completion}")
    problems = check_report(root)
    if problems:
        print("CHECK FAILED:\n  " + "\n  ".join(problems), file=sys.stderr)
        return 1
    print(f"CHECK PASSED: {REPORT_PATH}")
    return 0


if __name__ == "__main__":
    sys.exit(main())

Why each of those lines is there, from the docs:

  • enable_thinking is not an OpenAI parameter, so the Python SDK sends it through extra_body. Model Studio’s function-calling examples for qwen4-max set it to False. This page does the same for the audit loop. It does not walk through thinking controls in depth.
  • Tool results go back as {"role": "tool", "tool_call_id": ..., "content": ...}. The tool_call_id matches each result to its call.
  • parallel_tool_calls defaults to true, so one response can hold several tool calls. The loop handles all of them, not only the first.
  • If you keep thinking on, preserve_thinking is on by default for qwen4-max, and the model’s earlier reasoning_content must go back in the assistant message rather than being merged into content. assistant_message_to_dict() in the example keeps that field when it is present.
  • tool_choice="required" is documented as unsupported for Qwen models: in non-thinking mode it does not guarantee a tool call, and in thinking mode it is not supported. The script asks for write_report in the system prompt and verifies the file afterwards instead of forcing the call.

The script caps the loop at eight model turns and deletes any old report before it starts, so a stale file cannot pass the check.

Planned command. Not run for this draft. Point it at any npm project. From this site’s repository root:

python examples/qwen4-max-openai-compatible/dependency_report.py .

What the script prints, by construction, not observed output. One [turn N] tool ... line per tool call, a [turn N] model finished: ... line, a [usage] line with the summed prompt_tokens and completion_tokens, then either CHECK PASSED with the report path and exit code 0, or CHECK FAILED with the missing package names and exit code 1. Which tools the model calls, in what order, and how many turns it takes are unknown until it runs.

What actually changes when you leave OpenAI’s own endpoint?

  • Same SDK, three values. api_key, base_url, and model change. Message format, tools, tool_calls, stream, and stream_options keep their OpenAI shapes.
  • Non-standard parameters go in extra_body. enable_thinking is the one used here. In Node, the docs pass it as a top-level field of the request object.
  • The output budget includes thinking. The preview model’s page says that from qwen4-max-preview on, max_tokens is equivalent to max_completion_tokens and limits thinking plus the answer together. The qwen4-max page lists max_completion_tokens defaults of 262,144 with thinking and 131,072 without. If you carry over a small max_tokens from an OpenAI model, leave room for thinking or turn thinking off.
  • Reasoning effort. On Chat Completions, qwen4-max accepts reasoning_effort of low, high, or xhigh (default high). The docs map OpenAI-style values: minimal to low, medium to high, max to xhigh. Do not set reasoning_effort and thinking_budget together. A later tutorial in this cluster covers thinking controls in more depth.
  • Default sampling differs from OpenAI’s. Documented defaults: temperature 1.0 with thinking and 0.7 without; top_p 0.95 and 0.8; presence_penalty 0.0 with thinking and 1.5 without. Set them explicitly if your prompts depend on them.
  • tool_choice. auto is the default, and forcing one named function is supported. "required" is not supported for Qwen models.
  • Other APIs. The qwen4-max page also lists the OpenAI Responses API and Anthropic Messages as supported. This tutorial only covers Chat Completions.

What does a call cost after the free tokens are gone?

As long as the Beijing free quota still has tokens and 免费额度用完即停 is on, a successful call should not produce a bill. The numbers below are the list prices that apply after that quota expires or is exhausted, and only if the stop switch is off. They are from Model Studio’s pricing pages, read 2026-11-17. qwen4-max has a single tier for requests up to 1M input tokens, and the output price covers thinking plus the answer.

Region and price page Input per 1M tokens Output per 1M tokens Cache read per 1M tokens
China (Beijing), Chinese price page CNY 10 CNY 30 CNY 0.5
Singapore, international price page USD 1.5 USD 4.5 USD 0.075

On the China site, Singapore is also listed, in yuan: CNY 10.938 input and CNY 32.813 output, with no free quota in that region. Beijing cache writes are listed at CNY 12.5 per 1M tokens for a 5-minute TTL and CNY 20 for a 1-hour TTL. This tutorial does not use the cache.

The formula, using the usage numbers the API returns:

cost = prompt_tokens / 1,000,000 × input_price
     + completion_tokens / 1,000,000 × output_price

A tool loop resends the whole conversation every turn, so prompt_tokens adds up across turns. That is why dependency_report.py sums usage over all turns and prints the totals. As arithmetic only, not a measurement: a run that totals 20,000 prompt tokens and 2,000 completion tokens in Beijing would cost 20,000 / 1,000,000 × 10 + 2,000 / 1,000,000 × 30 = CNY 0.26, before any remaining free quota or cache discount.

Context caching bills cache hits at a discount and cache writes at a premium, and you cannot combine the cache discount with batch pricing. qwen4-max does not support batch inference anyway.

What usually breaks?

The error codes below are from Model Studio’s error-code page. They have not been reproduced here.

  • 401 invalid_api_key. The key, region, and base URL do not match. A key from one region does not work on another region’s endpoint. A Token Plan key also does not work on the regular Model Studio endpoint, and the reverse. If you followed the typo on the English compatibility overview and sent a Beijing key to an ap-southeast-1 host, this is the error to expect.
  • 404 ModelNotFound / model_not_found. Check the model ID spelling and that the model is offered in the region you are calling. qwen4-max-preview is not available on the regular (non-Token-Plan) endpoints.
  • 403 AccessDenied, or Arrearage. Access or service activation is missing, or the account has an overdue balance.
  • 429 Throttling.RateQuota or Throttling.AllocationQuota / insufficient_quota. Rate limit reached, or the free quota is used up. If 免费额度用完即停 is on, this is the intended stop, not a prompt to top up. The qwen4-max page lists a starting limit of 5,000,000 tokens per minute in Beijing and Singapore.
  • 400 InvalidParameter. Read the message. A common cause after migration is a parameter the model does not accept, such as tool_choice="required".
  • HTTP 400 current user api does not support http call. The model you named does not support the OpenAI-compatible HTTP interface. That is not expected for qwen4-max, so check for a typo in the model ID.
  • Answer truncated with finish_reason: length. Raise max_tokens or max_completion_tokens, or turn thinking off for the call.
  • The script says CHECK FAILED. The model skipped a package or never called write_report. Read the turn log, tighten the system prompt, and run again. Keep the failing log; it belongs in the evidence section too.

Files in this tutorial

All in examples/qwen4-max-openai-compatible/ in the site repository:

  • requirements.txt — the openai package, unpinned until a verified run pins it.
  • quickstart.py — the minimal call.
  • quickstart.mjs — the same call with the Node SDK.
  • stream.py — streaming with thinking and usage.
  • dependency_report.py — the tool-calling task and its model-free check.

What it takes to verify this page

A run needs a Beijing Model Studio key, a workspace ID, and 免费额度用完即停 turned on for qwen4-max. For a developer in mainland China, a China-site (aliyun.com) account after real-name verification is the straightforward route. Verification means running the three Python scripts, keeping their full terminal output, recording the openai package version, Python version, and run time with a timezone, and committing the generated report. Until those exist, there is no evidence section on this page.

Sources

All read on 2026-11-17 (Asia/Shanghai). Benchmark figures from the launch post are not repeated here because this site has not measured them.


Title tag: Call Qwen4-Max Through the OpenAI-Compatible API and Tool Calling

Meta description: Point the OpenAI SDK at Alibaba Model Studio in Beijing, call qwen4-max on the free quota with stop-when-exhausted on, then audit a package.json through local tools. Written from official docs; not yet run.

Slug: qwen4-max-openai-compatible-tool-calling

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

    401 invalid_api_key because the key, region, and base URL do not match

    A key from one region does not work on another region's endpoint. A Token Plan key also does not work on the regular Model Studio endpoint, and the reverse. If you followed the typo on the English compatibility overview and sent a Beijing key to an ap-southeast-1 host, this is the error to expect.

  • Unchecked

    404 ModelNotFound or model_not_found

    Check the model ID spelling and that the model is offered in the region you are calling. qwen4-max-preview is not available on the regular (non-Token-Plan) endpoints.

  • Unchecked

    403 AccessDenied, or Arrearage

    Access or service activation is missing, or the account has an overdue balance.

  • Unchecked

    429 Throttling.RateQuota or Throttling.AllocationQuota / insufficient_quota

    Rate limit reached, or the free quota is used up. If 免费额度用完即停 is on, this is the intended stop, not a prompt to top up.

  • Unchecked

    400 InvalidParameter after a migration

    A common cause is a parameter the model does not accept, such as tool_choice="required".

  • Unchecked

    HTTP 400 current user api does not support http call

    The model you named does not support the OpenAI-compatible HTTP interface. That is not expected for qwen4-max, so check for a typo in the model ID.

  • Unchecked

    Answer truncated with finish_reason: length

    For qwen4-max the output budget is shared by thinking and the final answer. Raise max_tokens or max_completion_tokens, or turn thinking off for the call.

  • Unchecked

    The script says CHECK FAILED

    The model skipped a package or never called write_report. A fluent final message is not enough; the script's model-free check has to find every declared package in the report.

Other tutorials in Integrate.