TL;DR
This guide shows how to call Qwen4-Max through CometAPI using the OpenAI Python SDK. You will send a first text request, then reuse the client for multimodal input, streaming, tool calls, and structured JSON output.
Key Takeaways
- A CometAPI key authenticates requests to the CometAPI endpoint. Keep the key in an environment variable.
- Thinking and the final answer share an output budget. Choose the budget for the task before sending a long request.
- For an image or video, send the prompt and the media together in one user message.
- When Qwen4-Max requests a tool, your application runs the function and returns its result to the model.
What Is the Qwen4-Max API?
Qwen4-Max is Alibabaโs multimodal reasoning model. Alibaba released Qwen4-Max to developers on November 16, 2026. A support application can use one conversation to read a screenshot, look up an order, and draft a reply from the result.
Which Qwen4-Max API Limits Affect a Request?
Use the modelโs context and output limits to decide how much conversation history to send and how much space to reserve for the answer.
| Setting | Qwen4-Max | How to use it |
|---|---|---|
| Context window | 1,000,000 tokens | Reserve space for the reply when sending long histories. |
| Maximum input | 991,808 tokens with thinking off; 983,616 with thinking on | Trim older messages or select the relevant pages first. |
| Maximum output | 131,072 tokens with thinking off; 262,144 with thinking on | With thinking enabled, reasoning and visible text share the completion allowance. |
| Media | Text, images, or video in; text out | Send a screenshot alongside the question you want answered. |
Choose a reasoning setting
Qwen4-Max uses high reasoning effort by default. For a short transformation, such as translating a label, you can disable thinking. For a task with an explicit reasoning allowance, set thinking_budget instead. Choose either reasoning_effort or thinking_budget in a given request.
In thinking mode, reasoning and the final answer share the same output budget. If the limit is too small, the final answer may be truncated.
For a translation request, pass {"enable_thinking": False} in extra_body. The Chat Completions parameter reference lists the accepted effort values and budget ranges.
How Do You Use Qwen4-Max API with CometAPI?
Step 1. Create a key and set it in your terminal
Sign in to CometAPI, open the API key console, and generate a key. Use the same terminal for the setup and the Python examples below.
On macOS or Linux, replace the placeholder with your CometAPI key.
export COMETAPI_API_KEY="your_api_key"
On Windows, set the variable for your current PowerShell session.
$env:COMETAPI_API_KEY="your_api_key"
Step 2. Install the SDK and choose the endpoint
Install the OpenAI Python SDK in your active Python environment.
python -m pip install -U openai
Configure the base URL once in the reusable client below. The curl example includes the complete HTTP request URL.
Step 3. Build a reusable client and check the response
Save this as qwen_client.py. The helper returns text only after the API reports a completed answer, so a truncated response cannot silently enter your application.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["COMETAPI_API_KEY"],
base_url="https://api.cometapi.com/v1",
)
MODEL = "qwen4-max"
def answer_text(response):
if not response.choices:
raise ValueError("No completion was returned")
choice = response.choices[0]
if choice.finish_reason != "stop":
raise ValueError(f"Incomplete answer: {choice.finish_reason}")
text = choice.message.content
if not text or not text.strip():
raise ValueError("The answer was empty")
return text.strip()
Step 4. Send and validate your first request
Python example
Save this as first_request.py beside qwen_client.py and run python first_request.py. The expected output is ORD-4821. The check catches extra commentary as well as an incorrect identifier.
from qwen_client import MODEL, answer_text, client
reply = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content":
"Return only the order ID from this note: Order ORD-4821 arrived today."}],
max_completion_tokens=128,
extra_body={"enable_thinking": False},
)
order_id = answer_text(reply)
if order_id != "ORD-4821":
raise ValueError(f"Unexpected order ID: {order_id!r}")
print(order_id)
HTTP example with curl
Run this command in Bash to inspect the raw JSON response. Read choices[0].message.content for the order ID and choices[0].finish_reason for the completion status.
curl --fail-with-body -sS https://api.cometapi.com/v1/chat/completions \
-H "Authorization: Bearer $COMETAPI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen4-max",
"messages": [{"role": "user", "content": "Return only the order ID from this note: Order ORD-4821 arrived today."}],
"enable_thinking": false,
"max_completion_tokens": 128
}'
Which API Calling Patterns Can You Use with Qwen4-Max?
Reuse the client and model setting from qwen_client.py for each example below. Save each example beside that file and include this import at the top:
from qwen_client import MODEL, client
Read a screenshot or video
Send a screenshot with a question to extract visible text or inspect an interface. You can use the same request structure for other images.
Paste a publicly accessible image URL when prompted. The request sends the image and your question together.
image_url = input("Image URL: ").strip()
response = client.chat.completions.create(
model=MODEL,
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "Describe the image and identify any visible text."},
{"type": "image_url", "image_url": {"url": image_url}},
],
}],
)
print(response.choices[0].message.content)
To compare screenshots, append a second image_url item to the list. For a video, replace the image item with {"type": "video_url", "video_url": {"url": video_url}} and ask a question about the clip. The answer arrives as text.
Stream a reply as it arrives
Use streaming to display a reply incrementally in your interface.
Print answer text as it arrives. Chunks that only carry reasoning or status information produce no visible text.
stream = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": "Suggest three ways to test a search box."}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
print()
In production, also handle stream errors and record the final completion status. A chunk without visible content is not necessarily an error.
Return a tool result to the conversation
The application must execute the requested function itself. It should then append the assistant tool-call message and the corresponding tool result to the conversation history before requesting the model's final response.
Look up an order in a local sample dictionary, then let the model turn the result into a customer-facing answer.
import json
orders = {"12345": "shipped"}
messages = [{"role": "user", "content": "Where is order 12345?"}]
tools = [{
"type": "function",
"function": {
"name": "get_order_status",
"description": "Look up an order by its order ID.",
"parameters": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"],
},
},
}]
settings = {"model": MODEL, "extra_body": {"enable_thinking": False}}
reply = client.chat.completions.create(messages=messages, tools=tools, **settings)
message = reply.choices[0].message
if message.tool_calls:
messages.append(message)
for call in message.tool_calls:
args = json.loads(call.function.arguments)
status = orders.get(args["order_id"], "unknown")
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps({"status": status}),
})
reply = client.chat.completions.create(messages=messages, **settings)
print(reply.choices[0].message.content)
Request a JSON object
Classify a support ticket and read the returned category as a Python value.
reply = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content":
'Return a JSON object with a "category" field. Ticket: My payment failed twice.'}],
response_format={"type": "json_object"},
extra_body={"enable_thinking": False},
)
import json
print(json.loads(reply.choices[0].message.content)["category"])
How Much Does Qwen4-Max API Cost?
CometAPI currently lists Qwen4-Max at $1.20 per million input tokens and $3.60 per million output tokens. These are CometAPI prices and may differ from Alibaba Cloud Model Studio pricing. For 100,000 input tokens and 10,000 billed output tokens, the input costs $0.12 and the output costs $0.036, for a total of $0.156. Count billed thinking tokens in the output total.
This estimate excludes retries, external tool charges, and other application-level expenses.
Conclusion
Before sending production traffic, run one representative request end to end. For a chat UI, check how long the first visible words take to arrive. For a tool workflow, confirm that a missing record produces a useful answer. Record the billed tokens for the successful run so you have a baseline when the prompt or model changes.
FAQ
Why did my Qwen4-Max answer end mid-sentence?
Inspect response.choices[0].finish_reason. A value of length indicates that the completion reached a token limit. Check how much of the output allowance the request used, then increase max_completion_tokens or ask for a shorter answer.
Why does my Qwen4-Max script fail before it sends a request?
A KeyError naming COMETAPI_API_KEY means Python could not find the environment variable. Set it in the terminal that launches the script. If you run the example from an IDE, add the variable to its run configuration and restart the process.
How can I test my order lookup without a live orders database?
Run the tool example twice, once with order 12345 and once with an ID absent from the dictionary. Inspect the tool message in each conversation. The two lookups should return shipped and unknown respectively, and the final answers should reflect those values.

