The Qwen models on Model Studio support OpenAI compatible interfaces. You can migrate your existing OpenAI code to Model Studio by changing only the API key, base URL, and model name.
Compatibility information
BASE_URL
The BASE_URL is the network endpoint for accessing the model service. When you use the OpenAI compatible interface with Model Studio, configure the BASE_URL as follows.
When you call via the OpenAI SDK or other OpenAI compatible SDKs, use the following BASE_URL:
Singapore: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
Virginia: https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/compatible-mode/v1
Beijing: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
Hong Kong (China): https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1
Japan (Tokyo): https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/compatible-mode/v1
When you call via HTTP, use the following full endpoint:
Singapore: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions
Virginia: POST https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions
Beijing: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions
Hong Kong (China): POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1/chat/completions
Japan (Tokyo): POST https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions
ImportantModel Studio has introduced workspace-specific domain names for the Beijing, Singapore, and Hong Kong (China) regions that provide better performance and higher stability. Migrate to the new domain names:
- Beijing region: Migrate from
https://dashscope.aliyuncs.comtohttps://{WorkspaceId}.cn-beijing.maas.aliyuncs.com - Singapore region: Migrate from
https://dashscope-intl.aliyuncs.comtohttps://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com - Hong Kong (China) region: Migrate from
https://cn-hongkong.dashscope.aliyuncs.comtohttps://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com
Replace {WorkspaceId} with your actual workspace ID.
Troubleshoot failed calls: If a call through the OpenAI compatible interface fails with a 404, 401, 403, or connection error, check the following configurations:
Cross-region calls
A Model Studio API key is bound to the region in which it was created. When you call the base URL of a region, you must use an API key that was created in that same region. An API key from another region is rejected with an authentication error.
This rule applies to every region that provides an endpoint, including China (Beijing), US (Virginia), Singapore, and Japan (Tokyo), as well as China (Hong Kong). Create the API key in the console of the region whose endpoint you call.
For example, if you use an API key created in the China (Beijing) region to call the US (Virginia) endpoint, the request returns HTTP 401 with the error message Incorrect API key provided and the error code invalid_api_key. This error indicates that the API key and the endpoint belong to different regions, not that the API key is invalid or lacks permissions.
Supported models
Supported models: Qwen large language models (commercial and open-source editions), Qwen-VL, Qwen-Coder, Qwen-Omni, Qwen-Math, DeepSeek, Kimi, GLM, MiniMax.
Qwen-Audio does not support the OpenAI compatible protocol. Use the DashScope protocol instead.
Call via OpenAI SDK
Prerequisites
- Python is installed on your machine.
- The latest version of the OpenAI SDK is installed.
# If the following command fails, replace pip with pip3
pip install -U openai
- You have activated Model Studio and obtained an API key. For instructions, see Get API key.
- (Recommended) Configure the API key as an environment variable to reduce the risk of key exposure. You can also configure it directly in code, but this increases the risk of exposure.
- Select the model you want to use from the supported models list.
Usage
The following examples show how to use the OpenAI SDK to access Qwen models on Model Studio.
Non-streaming example
from openai import OpenAI
import os
def get_response():
client = OpenAI(
# API keys differ by region. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"), # If the environment variable is unset, replace this line with your Model Studio API key: api_key="sk-xxx"
# Singapore base_url. Replace {WorkspaceId} with your actual workspace ID. URLs differ by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen4-max", # This example uses qwen4-max. You can change the model name as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/getting-started/models
messages=[{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': '你是谁?'}]
)
print(completion.model_dump_json())
if __name__ == '__main__':
get_response()
The following output is returned:
The following historical qwen3.8-max response illustrates the response fields.
{
"id": "chatcmpl-xxx",
"choices": [
{
"finish_reason": "stop",
"index": 0,
"logprobs": null,
"message": {
"content": "我是来自阿里云的超大规模预训练模型,我叫千问。",
"role": "assistant",
"function_call": null,
"tool_calls": null
}
}
],
"created": 1716430652,
"model": "qwen3.8-max",
"object": "chat.completion",
"system_fingerprint": null,
"usage": {
"completion_tokens": 18,
"prompt_tokens": 22,
"total_tokens": 40
}
}
Streaming example
from openai import OpenAI
import os
def get_response():
client = OpenAI(
# API keys differ by region. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
# If the environment variable is unset, replace the next line with your Model Studio API key: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
# Singapore base_url. Replace {WorkspaceId} with your actual workspace ID. URLs differ by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen4-max", # This example uses qwen4-max. You can change the model name as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/getting-started/models
messages=[{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': '你是谁?'}],
stream=True,
# Include token usage in the final streamed chunk using the following setting
stream_options={"include_usage": True}
)
for chunk in completion:
print(chunk.model_dump_json())
if __name__ == '__main__':
get_response()
The following output is returned:
The following historical qwen3.8-max response illustrates the response fields.
{"id":"chatcmpl-xxx","choices":[{"delta":{"content":"","function_call":null,"role":"assistant","tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1719286190,"model":"qwen3.8-max","object":"chat.completion.chunk","system_fingerprint":null,"usage":null}
{"id":"chatcmpl-xxx","choices":[{"delta":{"content":"我是","function_call":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1719286190,"model":"qwen3.8-max","object":"chat.completion.chunk","system_fingerprint":null,"usage":null}
{"id":"chatcmpl-xxx","choices":[{"delta":{"content":"来自","function_call":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1719286190,"model":"qwen3.8-max","object":"chat.completion.chunk","system_fingerprint":null,"usage":null}
{"id":"chatcmpl-xxx","choices":[{"delta":{"content":"阿里","function_call":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1719286190,"model":"qwen3.8-max","object":"chat.completion.chunk","system_fingerprint":null,"usage":null}
{"id":"chatcmpl-xxx","choices":[{"delta":{"content":"云的大规模语言模型","function_call":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1719286190,"model":"qwen3.8-max","object":"chat.completion.chunk","system_fingerprint":null,"usage":null}
{"id":"chatcmpl-xxx","choices":[{"delta":{"content":",我叫千问。","function_call":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1719286190,"model":"qwen3.8-max","object":"chat.completion.chunk","system_fingerprint":null,"usage":null}
{"id":"chatcmpl-xxx","choices":[{"delta":{"content":"","function_call":null,"role":null,"tool_calls":null},"finish_reason":"stop","index":0,"logprobs":null}],"created":1719286190,"model":"qwen3.8-max","object":"chat.completion.chunk","system_fingerprint":null,"usage":null}
{"id":"chatcmpl-xxx","choices":[],"created":1719286190,"model":"qwen3.8-max","object":"chat.completion.chunk","system_fingerprint":null,"usage":{"completion_tokens":16,"prompt_tokens":22,"total_tokens":38}}
Tool calling example
The following example demonstrates tool calling (function call) through the OpenAI compatible interface, using a weather query tool and a time query tool. The example code supports multi-turn tool calling.
from openai import OpenAI
from datetime import datetime
import json
import os
client = OpenAI(
# API keys differ by region. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
# If the environment variable is unset, replace the next line with your Model Studio API key: api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# Singapore base_url. Replace {WorkspaceId} with your actual workspace ID. URLs differ by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
# Define tools; the model uses their name and description to choose a tool
tools = [
# Tool 1: Get the current time
{
"type": "function",
"function": {
"name": "get_current_time",
"description": "当你想知道现在的时间时非常有用。",
# Getting the current time requires no input, so parameters is an empty dictionary
"parameters": {}
}
},
# Tool 2: Get the weather in a specific city
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "当你想查询指定城市的天气时非常有用。",
"parameters": {
"type": "object",
"properties": {
# Weather queries require a location, so the parameter is location
"location": {
"type": "string",
"description": "城市或县区,比如北京市、杭州市、余杭区等。"
}
}
},
"required": [
"location"
]
}
}
]
# Simulated weather tool. Example result: "It is raining in Beijing today."
def get_current_weather(location):
return f"{location}今天是雨天。 "
# Tool for the current time. Example result: "Current time: 2024-04-15 17:15:18."
def get_current_time():
# Get the current date and time
current_datetime = datetime.now()
# Format the current date and time
formatted_time = current_datetime.strftime('%Y-%m-%d %H:%M:%S')
# Return the formatted current time
return f"当前时间:{formatted_time}。"
# Encapsulate the model response function
def get_response(messages):
completion = client.chat.completions.create(
model="qwen4-max", # This example uses qwen4-max. You can change the model name as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/getting-started/models
messages=messages,
tools=tools
)
return completion.model_dump()
def call_with_messages():
print('\n')
messages = [
{
"content": input('请输入:'), # Example questions: "What time is it?" "What time will it be in an hour?" "What is the weather in Beijing?"
"role": "user"
}
]
print("-"*60)
# First model call
i = 1
first_response = get_response(messages)
assistant_output = first_response['choices'][0]['message']
print(f"\n第{i}轮大模型输出信息:{first_response}\n")
if assistant_output['content'] is None:
assistant_output['content'] = ""
messages.append(assistant_output)
# Return the final answer directly if no tool call is needed
if assistant_output['tool_calls'] == None: # If no tool is needed, print the assistant response directly without a second model call
print(f"无需调用工具,我可以直接回复:{assistant_output['content']}")
return
# Call the model over multiple turns until no further tool calls are needed
while assistant_output['tool_calls'] != None:
# Run the weather tool if a weather query is needed
if assistant_output['tool_calls'][0]['function']['name'] == 'get_current_weather':
tool_info = {"name": "get_current_weather", "role":"tool"}
# Extract location parameters
location = json.loads(assistant_output['tool_calls'][0]['function']['arguments'])['location']
tool_info['content'] = get_current_weather(location)
# Run the time tool if a time query is needed
elif assistant_output['tool_calls'][0]['function']['name'] == 'get_current_time':
tool_info = {"name": "get_current_time", "role":"tool"}
tool_info['content'] = get_current_time()
print(f"工具输出信息:{tool_info['content']}\n")
print("-"*60)
messages.append(tool_info)
assistant_output = get_response(messages)['choices'][0]['message']
if assistant_output['content'] is None:
assistant_output['content'] = ""
messages.append(assistant_output)
i += 1
print(f"第{i}轮大模型输出信息:{assistant_output}\n")
print(f"最终答案:{assistant_output['content']}")
if __name__ == '__main__':
call_with_messages()
Request parameters
The request parameters are aligned with the OpenAI interface. The following table describes the currently supported parameters:
Parameter | Type | Default | Description |
|---|---|---|---|
model | string | - | The model to use. For available models, see Supported models. |
messages | array | - | The conversation history between the user and the model. Each array element has the format |
top_p (optional) | float | - | The nucleus sampling probability threshold. For example, a value of 0.8 keeps only the smallest set of tokens whose cumulative probability is at least 0.8. Valid values: (0, 1.0). Higher values increase randomness; lower values increase determinism. |
temperature (optional) | float | - | Controls the randomness and diversity of model responses. Higher values flatten the probability distribution, selecting more low-probability tokens for more diverse output. Lower values sharpen the distribution, favoring high-probability tokens for more deterministic output. Valid values: [0, 2). A value of 0 is not recommended. |
presence_penalty (optional) | float | - | Controls repetition across the entire generated sequence. Higher values reduce repetition. Valid values: [-2.0, 2.0]. Supported only on Qwen commercial models and open-source models qwen1.5 and later. |
n (optional) | integer | 1 | The number of responses to generate. Valid values: |
max_tokens (optional) | integer | - | The maximum number of tokens the model can generate. For example, if the model supports up to 2k output tokens, you can set this to 1k to prevent overly long responses. Different models have different output limits. See the model list for details. |
seed (optional) | integer | - | The random seed for generation, used to control randomness of model output. Supports unsigned 64-bit integers. |
stream (optional) | boolean | False | Controls whether to use streaming output. When streaming is enabled, the interface returns a generator. Iterate over it to get results, where each output is the incremental sequence generated. |
stop (optional) | string or array | None | Controls precise stopping of content generation. Generation stops automatically when the model is about to produce the specified string or token_id. Can be a string or array type. When string type: generation stops when the model is about to produce the specified stop word. When array type: array elements can be token_ids, strings, or arrays of token_ids. Generation stops when the generated token or its token_id matches an element in stop. When stop is array type, you cannot mix token_ids and strings as elements. |
tools (optional) | array | None | The tool library available for the model to call. During a function call flow, the model selects one tool from this library. Each tool has the following structure: The tools parameter cannot be used with stream=True simultaneously. |
stream_options (optional) | object | None | Configures whether to display token usage in streaming output. Only takes effect when stream is True. To count tokens in streaming mode, set |
Response parameters
Parameter | Type | Description | Notes |
|---|---|---|---|
id | string | The system-generated ID for this request. | - |
model | string | The model name used for this request. | - |
system_fingerprint | string | The configuration version used by the model runtime. Currently not supported; returns an empty string. | - |
choices | array | The details of the model-generated content. | - |
choices[i].finish_reason | string | The reason generation stopped. Values: null (still generating), stop (stopped due to a stop condition), length (stopped due to exceeding max length). | - |
choices[i].message | object | The message output by the model. | - |
choices[i].message.role | string | The model role. Fixed value: assistant. | - |
choices[i].message.content | string | The text generated by the model. | - |
choices[i].index | integer | The sequence number of the generated result. Default: 0. | - |
created | integer | The timestamp (in seconds) of the generated result. | - |
usage | object | Metering information indicating the token consumption for this request. | - |
usage.prompt_tokens | integer | The token count of the user input text. | - |
usage.completion_tokens | integer | The token count of the model-generated response. | - |
usage.total_tokens | integer | The sum of usage.prompt_tokens and usage.completion_tokens. | - |
Call via langchain_openai SDK
Prerequisites
- Python is installed on your machine.
- The langchain_openai SDK is installed.
# If the following command fails, replace pip with pip3
pip install -U langchain_openai
- You have activated Model Studio and obtained an API key. For instructions, see Get API key.
- (Recommended) Configure the API key as an environment variable to reduce the risk of key exposure. You can also configure it directly in code, but this increases the risk of exposure.
- Select the model you want to use from the supported models list.
Usage
The following examples show how to use the langchain_openai SDK to access Qwen models on Model Studio.
Non-streaming output
Non-streaming output uses the invoke method:
from langchain_openai import ChatOpenAI
import os
def get_response():
llm = ChatOpenAI(
# API keys differ by region. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"), # If the environment variable is unset, replace this line with your Model Studio API key: api_key="sk-xxx"
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1", # Singapore base_url. Replace {WorkspaceId} with your actual workspace ID. URLs differ by region.
model="qwen4-max" # This example uses qwen4-max. You can change the model name as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/getting-started/models
)
messages = [
{"role":"system","content":"You are a helpful assistant."},
{"role":"user","content":"你是谁?"}
]
response = llm.invoke(messages)
print(response.json())
if __name__ == "__main__":
get_response()
The following output is returned:
{
"content": "我是来自阿里云的大规模语言模型,我叫千问。",
"additional_kwargs": {},
"response_metadata": {
"token_usage": {
"completion_tokens": 16,
"prompt_tokens": 22,
"total_tokens": 38
},
"model_name": "qwen-plus",
"system_fingerprint": "",
"finish_reason": "stop",
"logprobs": null
},
"type": "ai",
"name": null,
"id": "run-xxx",
"example": false,
"tool_calls": [],
"invalid_tool_calls": []
}
Streaming output
Streaming output uses the stream method. You do not need to configure a stream parameter separately.
from langchain_openai import ChatOpenAI
import os
def get_response():
llm = ChatOpenAI(
# API keys differ by region. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"), # If the environment variable is unset, replace this line with your Model Studio API key: api_key="sk-xxx"
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1", # Singapore base_url. Replace {WorkspaceId} with your actual workspace ID. URLs differ by region.
model="qwen4-max", # This example uses qwen4-max. You can change the model name as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/getting-started/models
stream_usage=True
)
messages = [
{"role":"system","content":"You are a helpful assistant."},
{"role":"user","content":"你是谁?"},
]
response = llm.stream(messages)
for chunk in response:
print(chunk.model_dump_json())
if __name__ == "__main__":
get_response()
The following output is returned:
{"content": "", "additional_kwargs": {}, "response_metadata": {}, "type": "AIMessageChunk", "name": null, "id": "run-xxx", "example": false, "tool_calls": [], "invalid_tool_calls": [], "usage_metadata": null, "tool_call_chunks": []}
{"content": "我是", "additional_kwargs": {}, "response_metadata": {}, "type": "AIMessageChunk", "name": null, "id": "run-xxx", "example": false, "tool_calls": [], "invalid_tool_calls": [], "usage_metadata": null, "tool_call_chunks": []}
{"content": "来自", "additional_kwargs": {}, "response_metadata": {}, "type": "AIMessageChunk", "name": null, "id": "run-xxx", "example": false, "tool_calls": [], "invalid_tool_calls": [], "usage_metadata": null, "tool_call_chunks": []}
{"content": "阿里", "additional_kwargs": {}, "response_metadata": {}, "type": "AIMessageChunk", "name": null, "id": "run-xxx", "example": false, "tool_calls": [], "invalid_tool_calls": [], "usage_metadata": null, "tool_call_chunks": []}
{"content": "云", "additional_kwargs": {}, "response_metadata": {}, "type": "AIMessageChunk", "name": null, "id": "run-xxx", "example": false, "tool_calls": [], "invalid_tool_calls": [], "usage_metadata": null, "tool_call_chunks": []}
{"content": "的大规模语言模型", "additional_kwargs": {}, "response_metadata": {}, "type": "AIMessageChunk", "name": null, "id": "run-xxx", "example": false, "tool_calls": [], "invalid_tool_calls": [], "usage_metadata": null, "tool_call_chunks": []}
{"content": ",我叫通", "additional_kwargs": {}, "response_metadata": {}, "type": "AIMessageChunk", "name": null, "id": "run-xxx", "example": false, "tool_calls": [], "invalid_tool_calls": [], "usage_metadata": null, "tool_call_chunks": []}
{"content": "义千问。", "additional_kwargs": {}, "response_metadata": {}, "type": "AIMessageChunk", "name": null, "id": "run-xxx", "example": false, "tool_calls": [], "invalid_tool_calls": [], "usage_metadata": null, "tool_call_chunks": []}
{"content": "", "additional_kwargs": {}, "response_metadata": {"finish_reason": "stop"}, "type": "AIMessageChunk", "name": null, "id": "run-xxx", "example": false, "tool_calls": [], "invalid_tool_calls": [], "usage_metadata": null, "tool_call_chunks": []}
{"content": "", "additional_kwargs": {}, "response_metadata": {}, "type": "AIMessageChunk", "name": null, "id": "run-xxx", "example": false, "tool_calls": [], "invalid_tool_calls": [], "usage_metadata": {"input_tokens": 22, "output_tokens": 16, "total_tokens": 38}, "tool_call_chunks": []}
For parameter configuration details, see Request parameters. Parameters are defined in the ChatOpenAI object.
Call via HTTP
You can call Model Studio through HTTP requests and receive responses in the same structure as OpenAI HTTP responses.
Prerequisites
- You have activated Model Studio and obtained an API key. For instructions, see Get API key.
- (Recommended) Configure the API key as an environment variable to reduce the risk of key exposure. You can also configure it directly in code, but this increases the risk of exposure.
Endpoint
Singapore: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions
Virginia: POST https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions
Beijing: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions
Hong Kong (China): POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1/chat/completions
Request examples
The following examples use cURL commands to call the API.
NoteIf you have not configured your API key as an environment variable, replace $DASHSCOPE_API_KEY with your actual API key.
Non-streaming output
# Singapore URL. Replace {WorkspaceId} with your actual workspace ID. URLs differ by region.
curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"model": "qwen4-max",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "你是谁?"
}
]
}'
The following output is returned:
The following historical qwen3.8-max response illustrates the response fields.
{
"choices": [
{
"message": {
"role": "assistant",
"content": "我是来自阿里云的大规模语言模型,我叫千问。"
},
"finish_reason": "stop",
"index": 0,
"logprobs": null
}
],
"object": "chat.completion",
"usage": {
"prompt_tokens": 11,
"completion_tokens": 16,
"total_tokens": 27
},
"created": 1715252778,
"system_fingerprint": "",
"model": "qwen3.8-max",
"id": "chatcmpl-xxx"
}
Streaming output
To use streaming output, set the stream parameter to true in the request body.
# Singapore URL. Replace {WorkspaceId} with your actual workspace ID. URLs differ by region.
curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"model": "qwen4-max",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "你是谁?"
}
],
"stream":true
}'
The following output is returned:
The following historical qwen3.8-max response illustrates the response fields.
data: {"choices":[{"delta":{"content":"","role":"assistant"},"index":0,"logprobs":null,"finish_reason":null}],"object":"chat.completion.chunk","usage":null,"created":1715931028,"system_fingerprint":null,"model":"qwen3.8-max","id":"chatcmpl-3bb05cf5cd819fbca5f0b8d67a025022"}
data: {"choices":[{"finish_reason":null,"delta":{"content":"我是"},"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1715931028,"system_fingerprint":null,"model":"qwen3.8-max","id":"chatcmpl-3bb05cf5cd819fbca5f0b8d67a025022"}
data: {"choices":[{"delta":{"content":"来自"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1715931028,"system_fingerprint":null,"model":"qwen3.8-max","id":"chatcmpl-3bb05cf5cd819fbca5f0b8d67a025022"}
data: {"choices":[{"delta":{"content":"阿里"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1715931028,"system_fingerprint":null,"model":"qwen3.8-max","id":"chatcmpl-3bb05cf5cd819fbca5f0b8d67a025022"}
data: {"choices":[{"delta":{"content":"云的大规模语言模型"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1715931028,"system_fingerprint":null,"model":"qwen3.8-max","id":"chatcmpl-3bb05cf5cd819fbca5f0b8d67a025022"}
data: {"choices":[{"delta":{"content":",我叫千问。"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1715931028,"system_fingerprint":null,"model":"qwen3.8-max","id":"chatcmpl-3bb05cf5cd819fbca5f0b8d67a025022"}
data: {"choices":[{"delta":{"content":""},"finish_reason":"stop","index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1715931028,"system_fingerprint":null,"model":"qwen3.8-max","id":"chatcmpl-3bb05cf5cd819fbca5f0b8d67a025022"}
data: [DONE]
For parameter details, see Request parameters.
Error response
When a request fails, the response includes code and message fields indicating the cause:
{
"error": {
"message": "Incorrect API key provided. ",
"type": "invalid_request_error",
"param": null,
"code": "invalid_api_key"
}
}
Configure a third-party client
You can call Model Studio models from any third-party client that supports the OpenAI compatible protocol. The following steps use the Zhipu client as an example:
-
In the provider settings of the client, select Custom provider.
-
Base URL: Enter the base URL that the OpenAI SDK uses for your region. For the base URL of each region, see BASE_URL. The base URL ends with
/compatible-mode/v1and does not include/chat/completions. Because base URLs differ by region, use the one for the region of your API key.For example, for the Singapore region, enter
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1. Replace{WorkspaceId}with your workspace ID, which you can find on the workspace details page in the Model Studio console. The legacyhttps://dashscope.aliyuncs.comdomain remains available, but use the workspace-specific domain whenever possible. -
API Key: Enter the Model Studio API key for the region that the base URL points to. You can create and obtain an API key on the API Key management page of the Model Studio console.
-
Model name: Enter the name of a large language model that supports the OpenAI compatible protocol. For the models that you can choose from, see Supported models. For example,
qwen3.7-plus. This model name is an example only and does not indicate that the model provides a free quota. -
Save the configuration and start a conversation to verify that the third-party client can call the model.
A call may return HTTP 400 with error.message set to current user api does not support http call and error.type set to invalid_request_error. This error means that the model you entered does not support HTTP calls through the OpenAI compatible interface. Replace it with a model from Supported models and try again.
Error codes
Error code | Description |
|---|---|
400 - Invalid Request Error | The request is invalid. See the error message for details. |
401 - Incorrect API key provided | The API key is incorrect. |
429 - Rate limit reached for requests | QPS or QPM limit exceeded. |
429 - You exceeded your current quota, please check your plan and billing details | Quota exceeded or account in arrears. |
500 - The server had an error while processing your request | Server error. |
503 - The engine is currently overloaded, please try again later | Server overloaded. Retry later. |