All Products
Search
Document Center

Alibaba Cloud Model Studio:OpenAI compatible - Chat

Last Updated:Jul 15, 2026

You can call models using the OpenAI compatible Chat API. This document describes the input and output parameters and provides call examples.

Singapore

SDK call configuration for base_url: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1

HTTP request: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions

US (Virginia)

SDK call configuration for base_url: https://dashscope-us.aliyuncs.com/compatible-mode/v1

HTTP request: POST https://dashscope-us.aliyuncs.com/compatible-mode/v1/chat/completions

China (Beijing)

SDK call configuration for base_url: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1

HTTP request: POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions

Hong Kong (China)

SDK call configuration for base_url: https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1

HTTP request: POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1/chat/completions

Germany (Frankfurt)

SDK call configuration for base_url: <u>https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/compatible-mode/v1</u>

Request URL: POST https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions

Japan (Tokyo)

SDK call configuration for base_url: https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/compatible-mode/v1

HTTP request: POST https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions

Replace {WorkspaceId} with your actual workspace ID.

Obtain an API key and set it as an environment variable. If you use an OpenAI SDK, you must also install the SDK.

Important

Alibaba Cloud Model Studio has released workspace-specific domains for the China (Beijing), Singapore, and China (Hong Kong) regions. The new dedicated domains deliver superior performance and higher stability for inference requests. We recommend migrating to the new domains:

  • China (Beijing): from https://dashscope.aliyuncs.com to https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com

  • Singapore: from https://dashscope-intl.aliyuncs.com to https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com

  • China (Hong Kong): from https://cn-hongkong.dashscope.aliyuncs.com to https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com

{WorkspaceId} is your workspace ID, which can be found on the Workspace Details page in the Alibaba Cloud Model Studio console. The existing domain remains fully functional.

Request body

POST /chat/completions

OpenAI-compatible API online debugging

POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions

Text input

Python

import os
from openai import OpenAI


client = OpenAI(
    # If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
    # API keys vary by region. Get API Key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",  
)

completion = client.chat.completions.create(
    # This example uses qwen-plus. You can replace it with another model name as needed. Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
    model="qwen-plus",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Who are you?"},
    ],
    # extra_body={"enable_thinking": False},
)
print(completion.model_dump_json())

Java

// This code uses OpenAI SDK version 2.6.0
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;

public class Main {
    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.builder()
                // API keys vary by region. Get API Key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
                .baseUrl("https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1") 
                .build();

        ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
                .addUserMessage("Who are you?")
                .model("qwen-plus")
                .build();

        try {
            ChatCompletion chatCompletion = client.chat().completions().create(params);
            System.out.println(chatCompletion);
        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Node.js

import OpenAI from "openai";

const openai = new OpenAI(
    {
        // If the environment variable is not configured, replace the following line with your Model Studio API key: apiKey: "sk-xxx",
        // API keys vary by region. Get API Key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
        apiKey: process.env.DASHSCOPE_API_KEY,
        // Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
        baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1" 
    }
);

async function main() {
    const completion = await openai.chat.completions.create({
        model: "qwen-plus",  // This example uses qwen-plus. You can replace it with another model name as needed. Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
        messages: [
            { role: "system", content: "You are a helpful assistant." },
            { role: "user", content: "Who are you?" }
        ],
    });
    console.log(JSON.stringify(completion))
}

main();

Go

package main

import (
	"context"
	"os"

	"github.com/openai/openai-go"
	"github.com/openai/openai-go/option"
)

func main() {
	client := openai.NewClient(
	        // API keys vary by region. Get API Key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
		option.WithAPIKey(os.Getenv("DASHSCOPE_API_KEY")), // defaults to os.LookupEnv("OPENAI_API_KEY")
		// Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
		option.WithBaseURL("https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/"), 
	)
	chatCompletion, err := client.Chat.Completions.New(
		context.TODO(), openai.ChatCompletionNewParams{
			Messages: openai.F(
				[]openai.ChatCompletionMessageParamUnion{
					openai.UserMessage("Who are you?"),
				},
			),
			Model: openai.F("qwen-plus"),
		},
	)

	if err != nil {
		panic(err.Error())
	}

	println(chatCompletion.Choices[0].Message.Content)
}

C# (HTTP)

using System.Net.Http.Headers;
using System.Text;

class Program
{
    private static readonly HttpClient httpClient = new HttpClient();

    static async Task Main(string[] args)
    {
        // If the environment variable is not configured, replace the following line with your Model Studio API key: string? apiKey = "sk-xxx";
        // API keys vary by region. Get API Key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
        string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");

        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("API Key not set. Make sure the 'DASHSCOPE_API_KEY' environment variable is set.");
            return;
        }

        // Set the request URL and content
        // Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
        string url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions";
        // This example uses qwen-plus. You can replace it with another model name as needed. Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
        string jsonContent = @"{
            ""model"": ""qwen-plus"",
            ""messages"": [
                {
                    ""role"": ""system"",
                    ""content"": ""You are a helpful assistant.""
                },
                {
                    ""role"": ""user"", 
                    ""content"": ""Who are you?""
                }
            ]
        }";

        // Send the request and get the response
        string result = await SendPostRequestAsync(url, jsonContent, apiKey);

        // Print the result
        Console.WriteLine(result);
    }

    private static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
    {
        using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
        {
            // Set request headers
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // Send the request and get the response
            HttpResponseMessage response = await httpClient.PostAsync(url, content);

            // Process the response
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }
            else
            {
                return $"Request failed: {response.StatusCode}";
            }
        }
    }
}

PHP (HTTP)

<?php
// Set the request URL
// Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
$url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions';
// If the environment variable is not configured, replace the following line with your Model Studio API key: $apiKey = "sk-xxx";
// API keys vary by region. Get API Key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
$apiKey = getenv('DASHSCOPE_API_KEY');
// Set request headers
$headers = [
    'Authorization: Bearer '.$apiKey,
    'Content-Type: application/json'
];
// Set the request body
$data = [
    // This example uses qwen-plus. You can replace it with another model name as needed. Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
    "model" => "qwen-plus",
    "messages" => [
        [
            "role" => "system",
            "content" => "You are a helpful assistant."
        ],
        [
            "role" => "user",
            "content" => "Who are you?"
        ]
    ]
];
// Initialize a cURL session
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute the cURL session
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
}
// Close the cURL resource
curl_close($ch);
// Print the response
echo $response;
?>

curl

Replace {WorkspaceId} with your workspace ID. The URLs vary by region. You can obtain an API key at https://www.alibabacloud.com/help/en/model-studio/get-api-key.
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen-plus",
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user", 
            "content": "Who are you?"
        }
    ]
}'

Streaming output

For more information about usage, see Streaming output.

Python

import os
from openai import OpenAI

client = OpenAI(
    # If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
    # API keys vary by region. Get API Key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen-plus",  # This example uses qwen-plus. You can replace it with another model name as needed. Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
    messages=[{'role': 'system', 'content': 'You are a helpful assistant.'},
                {'role': 'user', 'content': 'Who are you?'}],
    stream=True,
    stream_options={"include_usage": True}
    )
for chunk in completion:
    print(chunk.model_dump_json())

Node.js

import OpenAI from "openai";

const openai = new OpenAI(
    {
        // API keys vary by region. Get API Key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
        apiKey: process.env.DASHSCOPE_API_KEY,
        baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
    }
);

async function main() {
    const completion = await openai.chat.completions.create({
        model: "qwen-plus", // This example uses qwen-plus. You can replace it with another model name as needed. Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
        messages: [
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": "Who are you?"}
        ],
        stream: true,
    });
    for await (const chunk of completion) {
        console.log(JSON.stringify(chunk));
    }
}

main();

curl

Replace {WorkspaceId} with your workspace ID. The URLs vary by region. You can obtain an API key at https://www.alibabacloud.com/help/en/model-studio/get-api-key.
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": "qwen-plus",
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user", 
            "content": "Who are you?"
        }
    ],
    "stream":true
}'

Image input

For more information about how large language models analyze images, see Image and video understanding.

Python

import os
from openai import OpenAI

client = OpenAI(
    # If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
    # API keys vary by region. Get API Key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen-vl-plus",  # This example uses qwen-vl-plus. You can replace it with another model name as needed. Model list: https://www.alibabacloud.com/help/en/model-studio/models
    messages=[{"role": "user","content": [
            {"type": "image_url",
             "image_url": {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"}},
            {"type": "text", "text": "What is this?"},
            ]}]
    )
print(completion.model_dump_json())

Node.js

import OpenAI from "openai";

const openai = new OpenAI(
    {
        // API keys vary by region. Get API Key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
        apiKey: process.env.DASHSCOPE_API_KEY,
        baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
    }
);

async function main() {
    const response = await openai.chat.completions.create({
        model: "qwen-vl-max", // This example uses qwen-vl-max. You can replace it with another model name as needed. Model list: https://www.alibabacloud.com/help/en/model-studio/models
        messages: [{role: "user",content: [
            { type: "image_url",image_url: {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"}},
            { type: "text", text: "What is this?" },
        ]}]
    });
    console.log(JSON.stringify(response));
}

main();

curl

Replace {WorkspaceId} with your workspace ID. The URLs vary by region. You can obtain an API key at https://www.alibabacloud.com/help/en/model-studio/get-api-key.
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
  "model": "qwen-vl-plus",
  "messages": [{
      "role": "user",
      "content": [
       {"type": "image_url","image_url": {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"}},
       {"type": "text","text": "What is this?"}
       ]}]
}'

Video input

The following example shows how to pass a list of images. For more information about usage, such as passing video files, see Visual understanding.

Python

import os
from openai import OpenAI

client = OpenAI(
    # If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
    # API keys vary by region. Get API Key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",  
)
completion = client.chat.completions.create(
    # This example uses qwen-vl-max. You can replace it with another model name as needed. Model list: https://www.alibabacloud.com/help/en/model-studio/models
    model="qwen-vl-max",
    messages=[{
        "role": "user",
        "content": [
            {
                "type": "video",
                "video": [
                    "https://img.alicdn.com/imgextra/i3/O1CN01K3SgGo1eqmlUgeE9b_!!6000000003923-0-tps-3840-2160.jpg",
                    "https://img.alicdn.com/imgextra/i4/O1CN01BjZvwg1Y23CF5qIRB_!!6000000003000-0-tps-3840-2160.jpg",
                    "https://img.alicdn.com/imgextra/i4/O1CN01Ib0clU27vTgBdbVLQ_!!6000000007859-0-tps-3840-2160.jpg",
                    "https://img.alicdn.com/imgextra/i1/O1CN01aygPLW1s3EXCdSN4X_!!6000000005710-0-tps-3840-2160.jpg"]
            },
            {
                "type": "text",
                "text": "Describe the specific process in this video"
            }]}]
)
print(completion.model_dump_json())

Node.js

// Make sure you have specified "type": "module" in package.json
import OpenAI from "openai"; 

const openai = new OpenAI({
    // If the environment variable is not configured, replace the following line with your Model Studio API key: apiKey: "sk-xxx",
    // API keys vary by region. Get API Key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    apiKey: process.env.DASHSCOPE_API_KEY, 
    baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"    
});

async function main() {
    const response = await openai.chat.completions.create({
        // This example uses qwen-vl-max. You can replace it with another model name as needed. Model list: https://www.alibabacloud.com/help/en/model-studio/models 
        model: "qwen-vl-max",
        messages: [{
            role: "user",
            content: [
                {
                    type: "video",
                    video: [
                        "https://img.alicdn.com/imgextra/i3/O1CN01K3SgGo1eqmlUgeE9b_!!6000000003923-0-tps-3840-2160.jpg",
                        "https://img.alicdn.com/imgextra/i4/O1CN01BjZvwg1Y23CF5qIRB_!!6000000003000-0-tps-3840-2160.jpg",
                        "https://img.alicdn.com/imgextra/i4/O1CN01Ib0clU27vTgBdbVLQ_!!6000000007859-0-tps-3840-2160.jpg",
                        "https://img.alicdn.com/imgextra/i1/O1CN01aygPLW1s3EXCdSN4X_!!6000000005710-0-tps-3840-2160.jpg"
                    ]
                },
                {
                    type: "text",
                    text: "Describe the specific process in this video"
                }
        ]}]
    });
    console.log(JSON.stringify(response));
}

main();

curl

Replace {WorkspaceId} with your workspace ID. The URLs vary by region. For more information, see Get API Key.
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
    "model": "qwen-vl-max",
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "video",
                    "video": [
                        "https://img.alicdn.com/imgextra/i3/O1CN01K3SgGo1eqmlUgeE9b_!!6000000003923-0-tps-3840-2160.jpg",
                        "https://img.alicdn.com/imgextra/i4/O1CN01BjZvwg1Y23CF5qIRB_!!6000000003000-0-tps-3840-2160.jpg",
                        "https://img.alicdn.com/imgextra/i4/O1CN01Ib0clU27vTgBdbVLQ_!!6000000007859-0-tps-3840-2160.jpg",
                        "https://img.alicdn.com/imgextra/i1/O1CN01aygPLW1s3EXCdSN4X_!!6000000005710-0-tps-3840-2160.jpg"
                    ]
                },
                {
                    "type": "text",
                    "text": "Describe the specific process in this video"
                }
            ]
        }
    ]
}'

Tool calling

For the complete Function Calling process code, see Function Calling.

Python

import os
from openai import OpenAI

client = OpenAI(
    # If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
    # API keys vary by region. Get API Key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",  
)

tools = [
    # Tool 1: Get the current time
    {
        "type": "function",
        "function": {
            "name": "get_current_time",
            "description": "Useful when you want to know the current time.",
            "parameters": {}  # Because getting the current time requires no input parameters, parameters is an empty dictionary
        }
    },  
    # Tool 2: Get the weather for a specified city
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "Useful when you want to query the weather of a specified city.",
            "parameters": {  
                "type": "object",
                "properties": {
                    # A location must be provided to query the weather, so the parameter is set to location
                    "location": {
                        "type": "string",
                        "description": "A city or district, such as Beijing, Hangzhou, or Yuhang District."
                    }
                },
                "required": ["location"]
            }
        }
    }
]
messages = [{"role": "user", "content": "What's the weather like in Hangzhou?"}]
completion = client.chat.completions.create(
    model="qwen-plus",  # This example uses qwen-plus. You can replace it with another model name as needed. Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
    messages=messages,
    tools=tools
)

print(completion.model_dump_json())

Node.js

import OpenAI from "openai";

const openai = new OpenAI(
    {
        // If the environment variable is not configured, replace the following line with your Model Studio API key: apiKey: "sk-xxx",
        // API keys vary by region. Get API Key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
        apiKey: process.env.DASHSCOPE_API_KEY,
        baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
    }
);

const messages = [{"role": "user", "content": "What's the weather like in Hangzhou?"}];
const tools = [
// Tool 1: Get the current time
{
    "type": "function",
    "function": {
        "name": "get_current_time",
        "description": "Useful when you want to know the current time.",
        // Because getting the current time requires no input parameters, parameters is empty
        "parameters": {}  
    }
},  
// Tool 2: Get the weather for a specified city
{
    "type": "function",
    "function": {
        "name": "get_current_weather",
        "description": "Useful when you want to query the weather of a specified city.",
        "parameters": {  
            "type": "object",
            "properties": {
                // A location must be provided to query the weather, so the parameter is set to location
                "location": {
                    "type": "string",
                    "description": "A city or district, such as Beijing, Hangzhou, or Yuhang District."
                }
            },
            "required": ["location"]
        }
    }
}
];

async function main() {
    const response = await openai.chat.completions.create({
        model: "qwen-plus", // This example uses qwen-plus. You can replace it with another model name as needed. Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
        messages: messages,
        tools: tools,
    });
    console.log(JSON.stringify(response));
}

main();

curl

Replace {WorkspaceId} with your workspace ID. The URLs vary by region. For more information, see Get API Key.
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen-plus",
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user", 
            "content": "What is the weather like in Hangzhou?"
        }
    ],
    "tools": [
    {
        "type": "function",
        "function": {
            "name": "get_current_time",
            "description": "Useful when you want to know the current time.",
            "parameters": {}
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "Useful when you want to query the weather of a specified city.",
            "parameters": {
                "type": "object",
                "properties": {
                    "location":{
                        "type": "string",
                        "description": "A city or district, such as Beijing, Hangzhou, or Yuhang District."
                    }
                },
                "required": ["location"]
            }
        }
    }
  ]
}'

Asynchronous invocation

import os
import asyncio
from openai import AsyncOpenAI
import platform

client = AsyncOpenAI(
    # If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
    # If you use a model in the China (Beijing) region, you need to use the API KEY for the China (Beijing) region. Get the link: https://modelstudio.console.alibabacloud.com/?tab=model#/api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

async def main():
    response = await client.chat.completions.create(
        messages=[{"role": "user", "content": "Who are you?"}],
        model="qwen-plus",  # This example uses qwen-plus. You can replace it with another model name as needed. Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
    )
    print(response.model_dump_json())

if platform.system() == "Windows":
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())

model string (Required)

The model name.

Supported models: Qwen Large Language Model (commercial and open source versions), Qwen-VL, Qwen-Coder, Qwen-Omni, Qwen-Math, DeepSeek, Kimi, GLM, and MiniMax.

For specific model names and billing details, see the Model Studio console.

messages array (Required)

The context passed to the large language model, arranged in conversational order.

Message type

System Message object (Optional)

A system message that defines the role, tone, task, or constraints for the large language model. It is usually the first element in the messages array.

Do not set a system message for QwQ models. System messages have no effect on QVQ models.

Properties

content string (Required)

The system instruction. It specifies the model's role, behavior, response style, and task constraints.

role string (Required)

The role for the system message. The value is fixed to system.

User Message object (Required)

The user message. It passes questions, instructions, or context to the model.

Properties

content string or array (Required)

The message content. The type is string if the input is text only. The type is array if the input contains multimodal data such as images, or if explicit caching is enabled.

Properties for multimodal models or when explicit caching is enabled

type string (Required)

Valid values:

  • text

    Set to text for text input.

  • image_url

    Set to image_url for image input.

  • input_audio

    Set to input_audio for audio input.

  • video

    Set to video for video input as a list of images.

  • video_url

    Set to video_url for video file input.

    Only some Qwen-VL models support video file input. For more information, see Video understanding (Qwen-VL). QVQ and Qwen-Omni models support direct video file input.

text string

The input text. This parameter is required when type is text.

image_url object

The input image information. This parameter is required when type is image_url.

Properties

url string(Required)

The URL or Base64-encoded Data URL of the image. To pass a local file, see Image and video understanding.

input_audio object

The input audio information. This parameter is required when type is input_audio.

Properties

data string(Required)

The URL or Base64-encoded Data URL of the audio. To pass a local file, see Input a Base64-encoded local file.

format string(Required)

The format of the input audio, such as mp3 or wav.

video array

The input video information, provided as a list of images. This parameter is required when type is video. For more information about its usage, see Video understanding (Qwen-VL), Video understanding (QVQ), or Video understanding (Qwen-Omni).

Example value:

[
    "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
    "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
    "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
    "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"
]

video_url object

The input video file information. This parameter is required when type is video_url.

Qwen-VL can only understand the visual information of video files, while Qwen-Omni can understand both visual and audio information.

Properties

url string(Required)

The public URL or Base64-encoded Data URL of the video file. To input a local video file, see Input a Base64-encoded local file.

fps float (Optional)

The number of frames to extract per second. Valid values: [0.1, 10]. Default value: 2.0.

The valid range for MiniMax/MiniMax-M3 is [0.2, 5], and the default value is 1.

Feature description

The fps parameter has two functions:

  • When you input a video file, it controls the frame extraction frequency. One frame is extracted every seconds.

    This applies to Qwen-VL, QVQ models.
  • It informs the model of the time interval between adjacent frames to help it better understand the video's progression over time. This applies to both video file and image list inputs. This feature is suitable for scenarios such as event time localization or segmented content summarization.

    Supported by Qwen3.7, Qwen3.6, Qwen3.5, Qwen3-VL, Qwen2.5-VL, Qwen3.5-Omni, and QVQ models.

A larger fps value is suitable for high-speed motion scenarios, such as sports events or action movies. A smaller fps value is suitable for long videos or scenes with static content.

Example values

  • Input for an image list: {"video":["https://xx1.jpg",...,"https://xxn.jpg"],"fps":2}

  • Video file input: {"video": "https://xx1.mp4", "fps":2}

min_pixels integer (Optional)

Sets the minimum pixel threshold for input images or video frames. If an input's pixel count is less than min_pixels, it is enlarged until its total pixel count is greater than min_pixels. This parameter applies to Qwen-VL and QVQ models.

Value range

  • Image input:

    • Qwen3.7, Qwen3.6, Qwen3.5, Qwen3-VL: Default and minimum value: 65536

    • Qwen3.5-Omni: Default and minimum value: 24576

    • qwen-vl-max, qwen-vl-max-0813, qwen-vl-plus, qwen-vl-plus-0815: Default and minimum value: 4096

    • Other qwen-vl-plus models, other qwen-vl-max models, Qwen2.5-VL open source series, and QVQ series models: Default and minimum value: 3136

  • Video file or image list input:

    • Qwen3.7, Qwen3.6, Qwen3.5, Qwen3.5-Omni, Qwen3-VL (including commercial and open source versions), qwen-vl-max, qwen-vl-max-0813, qwen-vl-plus, qwen-vl-plus-0815: Default value: 65536. Minimum value: 4096

    • Other qwen-vl-plus models, other qwen-vl-max models, Qwen2.5-VL open source series, and QVQ series models: Default value: 50176. Minimum value: 3136

Example values

  • Image input: {"type": "image_url","image_url": {"url":"https://xxxx.jpg"},"min_pixels": 65536}

  • Video file input: {"type": "video_url","video_url": {"url":"https://xxxx.mp4"},"min_pixels": 65536}

  • Image list input: {"type": "video","video": ["https://xx1.jpg",...,"https://xxn.jpg"],"min_pixels": 65536}

max_pixels integer (Optional)

Specifies the maximum pixel threshold for input images or video frames. If the pixel count of an input image or video is within the [min_pixels, max_pixels] range, the model processes the original image. If the pixel count is greater than max_pixels, the image is scaled down until its pixel count is less than or equal to max_pixels. This parameter applies to Qwen-VL and QVQ models.

Value range

  • Image input:

    The value of max_pixels depends on whether the <a baseurl="t3230321_v1_0_0.xdita" data-node="4759789" data-root="85177" data-tag="xref" href="t2614691.xdita#0edad44583knr" id="bfbaba10a77e0">vl_high_resolution_images</a> parameter is enabled.

    • When vl_high_resolution_images is False:

      • Qwen3.7, Qwen3.6, Qwen3.5, Qwen3-VL: Default value: 2621440. Maximum value: 16777216

      • Qwen3.5-Omni: Default value: 1310720. Maximum value: 16777216

      • qwen-vl-max, qwen-vl-max-0813, qwen-vl-plus, qwen-vl-plus-0815: Default value: 1310720. Maximum value: 16777216

      • Other qwen-vl-plus models, other qwen-vl-max models, Qwen2.5-VL open source series, and QVQ series models: Default value: 1003520. Maximum value: 12845056

    • When vl_high_resolution_images is True:

      • Qwen3.7, Qwen3.6, Qwen3.5-Omni, Qwen3.5, Qwen3-VL, qwen-vl-max, qwen-vl-max-0813, qwen-vl-plus, qwen-vl-plus-0815: max_pixels is invalid. The maximum pixel count for input images is fixed at 16777216.

      • Other qwen-vl-plus models, other qwen-vl-max models, Qwen2.5-VL open source series, and QVQ series models: max_pixels is invalid. The maximum pixel count for input images is fixed at 12845056.

  • Video file or image list input:

    • Qwen3.7 series, Qwen3.6 series, Qwen3.5 series, Qwen3.5-Omni, Qwen3-VL closed-source series, qwen3-vl-235b-a22b-thinking, qwen3-vl-235b-a22b-instruct: Default value: 655360. Maximum value: 2048000

    • Other Qwen3-VL open source models, qwen-vl-max, qwen-vl-max-0813, qwen-vl-plus, qwen-vl-plus-0815: Default value: 655360. Maximum value: 786432

    • Other qwen-vl-plus models, other qwen-vl-max models, Qwen2.5-VL open source series, and QVQ series models: Default value: 501760. Maximum value: 602112

Example values

  • Image input: {"type": "image_url","image_url": {"url":"https://xxxx.jpg"},"max_pixels": 8388608}

  • Video file input: {"type": "video_url","video_url": {"url":"https://xxxx.mp4"},"max_pixels": 655360}

  • Image list input: {"type": "video","video": ["https://xx1.jpg",...,"https://xxn.jpg"],"max_pixels": 655360}

total_pixels integer (Optional)

Limits the total pixel count of all frames extracted from a video, which is calculated as (pixels per frame × total frames). If the total pixel count of the video exceeds this limit, the system scales down the video frames. The system ensures that the pixel count of a single frame remains within the [min_pixels, max_pixels] range. This parameter applies to Qwen-VL and QVQ models.

For long videos with many extracted frames, you can reduce this value to decrease token consumption and processing time, but this may result in a loss of image detail.

Value range

  • Qwen3.7 series, Qwen3.6 series, Qwen3.5 series: Default and maximum value: 819200000. This corresponds to 800000 image tokens (1 image token per 32×32 pixels).

  • Qwen3-VL closed-source series, qwen3-vl-235b-a22b-thinking, qwen3-vl-235b-a22b-instruct: Default and maximum value: 134217728. This corresponds to 131072 image tokens (1 image token per 32×32 pixels).

  • Qwen3.5-Omni: Default and minimum value: 184549376. This corresponds to 180224 image tokens (1 image token per 32×32 pixels).

  • Other Qwen3-VL open source models, qwen-vl-max, qwen-vl-max-0813, qwen-vl-plus, qwen-vl-plus-0815: Default and minimum value: 67108864. This corresponds to 65536 image tokens (1 image token per 32×32 pixels).

  • Other qwen-vl-plus models, other qwen-vl-max models, Qwen2.5-VL open source series, and QVQ series models: Default and minimum value: 51380224. This corresponds to 65536 image tokens (1 image token per 28×28 pixels).

Example values

  • Video file input: {"type": "video_url","video_url": {"url":"https://xxxx.mp4"},"total_pixels": 134217728}

  • Image list input: {"type": "video","video": ["https://xx1.jpg",...,"https://xxn.jpg"],"total_pixels": 134217728}

cache_control object (Optional)

Enables explicit caching. For more information, see Explicit caching.

Properties

type string(Required)

Only ephemeral is supported.

role string (Required)

The role for the user message. The value is fixed to user.

Assistant Message object (Optional)

The model's reply. It is typically passed back to the model as context in a multi-turn conversation.

Properties

content string (Optional)

The text content of the model's reply. When tool_calls is included, content can be empty. Otherwise, content is required.

role string (Required)

The role for the assistant message. The value is fixed to assistant.

partial boolean (Optional) Default value: false

Specifies whether to enable partial mode.

Valid values:

  • true: Enable.

  • false: Disable.

For a list of supported models, see partial mode.

tool_calls array (Optional)

The information about the tool and its input parameters that the model decides to call. It contains one or more objects and is obtained from the tool_calls field of the previous model response.

Properties

id string (Required)

The ID of the tool call.

type string(Required)

The tool type. Currently, only function is supported.

function object(Required)

Tools and input parameters

Properties

name string(Required)

The tool name.

arguments string(Required)

The input parameter information, as a JSON formatted string.

index integer(Required)

The index of this tool call in the tool_calls array.

Tool Message object (Optional)

The result of the tool call.

Properties

content string (Required)

The output content of the tool function. It must be a string. If the tool returns structured data, such as JSON, it must be serialized into a string.

role string (Required)

The value is fixed to tool.

tool_call_id string (Required)

The ID of the tool call that this message is a response to. You can obtain it from `completion.choices[0].message.tool_calls[$index].id`. This ID is used to associate the tool message with the corresponding tool call.

stream boolean (Optional) Default value: false

Specifies whether to reply in streaming output mode. For more information, see Streaming output.

Valid values:

  • false: The model returns the complete content after generation is finished.

  • true: The model outputs content as it is generated. A data chunk is returned each time a part of the content is generated. You must read these chunks to assemble the complete reply.

We recommend that you set this to true to improve the user experience and reduce the risk of timeouts.

Note

If a non-streaming call is not completed within 300 seconds, the service interrupts the request and returns the generated content instead of an error. We recommend that you use streaming calls for scenarios that require long outputs. For more information, see the timeout description in Overview of text generation models.

stream_options object (Optional)

Configuration items for streaming output. This parameter takes effect only when stream is set to true.

Properties

include_usage boolean (Optional) Default value: false

Specifies whether to include token consumption information in the last data chunk of the response.

Valid values:

  • true: Include.

  • false: Do not include.

For streaming output, token consumption information can only appear in the last data chunk of the response.

modalities array (Optional) Default value: ["text"]

The modality of the output data. This parameter applies only to Qwen-Omni models. For more information, see Non-real-time (Qwen-Omni).

Valid values:

  • ["text","audio"]: Output text and audio.

  • ["text"]: Output text only.

audio object (Optional)

The voice and format of the output audio. This parameter applies only to Qwen-Omni models and requires the modalities parameter to be set to ["text","audio"]. For more information, see Non-real-time (Qwen-Omni).

Properties

voice string (Required)

The voice of the output audio. For more information, see Non-real-time (Qwen-Omni).

format string (Required)

The format of the output audio. Only wav is supported.

temperature float (Optional)

The sampling temperature, which controls the diversity of the text generated by the model.

A higher temperature results in more diverse text, while a lower temperature results in more deterministic text.

Value range: [0, 2)

Both temperature and top_p can control the diversity of the generated text. We recommend that you set only one of them. For more information, see Overview.

Do not modify the default temperature value for QVQ models.

top_p float (Optional)

The probability threshold for nucleus sampling, which controls the diversity of the text generated by the model.

A higher top_p results in more diverse text. A lower top_p results in more deterministic text.

Value range: (0, 1.0]

Both temperature and top_p can control the diversity of the generated text. We recommend that you set only one of them. For more information, see Overview.

Do not modify the default top_p value for QVQ models.

top_k integer (Optional)

Specifies the number of candidate tokens to sample from during generation. A larger value results in more random output, while a smaller value results in more deterministic output. If set to null or a value greater than 100, the top_k strategy is disabled, and only the top_p strategy takes effect. The value must be an integer greater than or equal to 0.

Default top_k values

QVQ series: 10;

QwQ series: 40;

models before the qwen-vl-plus series, and qwen2.5-omni-7b: 1;

Qwen3-Omni-Flash series: 50;

All other models: 20.

GLM series (supplied by Alibaba Cloud): 20;

The DeepSeek, Kimi, and MiniMax series do not support the top_k parameter.

This parameter is not a standard OpenAI parameter. When you call using the Python SDK, place it in the extra_body object. Configuration: extra_body={"top_k":xxx}.
Do not modify the default top_k value for QVQ models.

repetition_penalty float (Optional)

The repetition penalty for consecutive sequences during model generation. Increasing repetition_penalty can reduce repetition in the model's output. A value of 1.0 means no penalty. There is no strict value range, as long as it is greater than 0.

This parameter is not a standard OpenAI parameter. When you call using the Python SDK, place it in the extra_body object. Configuration: extra_body={"repetition_penalty":xxx}.
When you use the qwen-vl-plus_2025-01-25 model for text extraction, set repetition_penalty to 1.0.
Do not modify the default repetition_penalty value for QVQ models.

presence_penalty float (Optional)

Controls the content repetition when the model generates text.

Value range: [-2.0, 2.0]. Positive values reduce repetition, while negative values increase it.

In scenarios that require diversity, fun, or creativity, such as creative writing or brainstorming, you can increase this value. In scenarios that emphasize consistency and term accuracy, such as technical documents or formal texts, you can decrease this value.

Default presence_penalty values

Qwen3.7 (non-thinking mode), Qwen3.6 (non-thinking mode), Qwen3.5-Omni, Qwen3.5 (non-thinking mode), qwen3-max-preview (thinking mode), Qwen3 (non-thinking mode), Qwen3-Instruct series/1.7b/4b (thinking mode), QVQ series, qwen-max, qwen2.5-vl series, qwen-vl-max series, qwen-vl-plus, Qwen3-VL (non-thinking): 1.5;

qwen3-8b/14b/32b/30b-a3b/235b-a22b (thinking mode), qwen-plus/qwen-plus-latest/2025-04-28 (thinking mode), qwen-turbo/qwen-turbo/2025-04-28 (thinking mode): 0.5;

All others are 0.0.

DeepSeek series (supplied by Alibaba Cloud): deepseek-r1, deepseek-r1-0528, deepseek-r1-distill-qwen distilled version: 1;

Kimi series (supplied by Alibaba Cloud): kimi-k2.7-code, kimi-k2.6, kimi-k2.5: 0.0;

Kimi series (supplied by Moonshot AI): 0.0;

MiniMax series (supplied by Alibaba Cloud): MiniMax-M2.5, MiniMax-M2.1: 0.0;

Other DeepSeek, Kimi, GLM, and MiniMax models have no default value.

How it works

If the parameter value is positive, the model applies a penalty to tokens that already exist in the text. The penalty is not related to the number of times the token appears. This reduces the likelihood of these tokens reappearing, thus reducing content repetition and increasing word diversity.

Example

Prompt: Translate this sentence into Chinese: "This movie is good. The plot is good, the acting is good, the music is good, and overall, the whole movie is just good. It is really good, in fact. The plot is so good, and the acting is so good, and the music is so good."

Parameter value 2.0: This movie is great. The plot is fantastic, the acting is superb, and the music is also very beautiful. Overall, the entire film is just incredible. It is actually truly outstanding. The storyline is very exciting, the performances are excellent, and the soundtrack is so moving.

Parameter value 0.0: This movie is good. The plot is good, the acting is good, and the music is good. Overall, the whole movie is very good. In fact, it is really great. The plot is very good, the acting is also very excellent, and the music is equally outstanding.

Parameter value -2.0: This movie is good. The plot is good, the acting is good, and the music is good. Overall, the whole movie is good. In fact, it is really good. The plot is very good, the acting is very good, and the music is very good.

When you use the qwen-vl-plus model for text extraction, set presence_penalty to 1.5.
Do not modify the default presence_penalty value for QVQ models.

response_format object (Optional) Default value: {"type": "text"}

The format of the response. Valid values:

  • {"type": "text"}: Outputs a text reply.

  • {"type": "json_object"}: Outputs a standard JSON formatted string.

For more information, see Structured output.
If you specify {"type": "json_object"}, you must explicitly instruct the model to output JSON in the prompt, such as "Please output in JSON format". Otherwise, an error occurs.
For supported models, see Structured output.

Properties

type string (Required)

The format of the returned content. Valid values:

  • text: Outputs a text reply.

  • json_object: Outputs a standard JSON formatted string.

max_tokens integer (Optional, to be deprecated)

This parameter will be deprecated. For new integrations, use max_completion_tokens.

The maximum length of the model's answer, which excludes chain-of-thought content. That is: Model answer = Model output – Chain-of-thought (if any).

The default and maximum values are both the model's maximum output length.

If the model's answer exceeds this value, generation stops early, and the returned finish_reason is length.

For GLM-5.2 and later GLM series models, max_tokens behaves the same as max_completion_tokens — it limits the total output length including the chain-of-thought, not just the final response. We recommend using the max_completion_tokens parameter directly with GLM-5.2 series models for more semantically explicit control.

max_completion_tokens integer (Optional)

The maximum length of the model's output, including the chain-of-thought and the model's answer. If the model's output exceeds this value, generation stops early, and the returned finish_reason is length.

The default and maximum values are both the model's maximum output length.

Difference from max_tokens: max_completion_tokens limits the complete model output (chain-of-thought + answer), while max_tokens only limits the answer part. For thinking models, we recommend that you use max_completion_tokens.

The following models are supported:

  • Qwen Max: Qwen3.7-Max and later models

  • Qwen Plus: Qwen3.5-Plus and later models

  • Qwen Flash: Qwen3.5-Flash and later models

  • Kimi: kimi-k2.5 and later models

  • GLM: glm-5 and later models

  • MiniMax: MiniMax-M2.5 and later models

  • DeepSeek: deepseek-v3, deepseek-r1, deepseek-r1-0528, deepseek-v3.1, deepseek-v3.2, deepseek-v3.2-exp, deepseek-v4-pro, deepseek-v4-flash, and later models

The models listed above do not include models supplied directly by third parties.
There may be a difference of up to 10 tokens between the actual output token count and the specified max_completion_tokens value.

vl_high_resolution_images boolean (Optional) Default value: false

Specifies whether to increase the pixel limit for input images to the pixel count that corresponds to 16384 tokens. For more information, see Processing high-resolution images.

  • vl_high_resolution_images: true uses a fixed resolution strategy and ignores the max_pixels setting. If the resolution is exceeded, the total pixel count of the image is scaled down to stay within this limit.

    Click to view the pixel limits for each model

    When vl_high_resolution_images is True, the pixel limits vary by model:

    • For the Qwen3.7 series, Qwen3.6 series, Qwen3.5 series, Qwen3-VL series, qwen-vl-max, qwen-vl-max-0813, qwen-vl-plus, qwen-vl-plus-0815, and models, the value is 16777216. (Each Token corresponds to 32*32 pixels. The total value is calculated as 16384*32*32.)

    • QVQ series, other Qwen2.5-VL series models: 12845056 (1 token corresponds to 28*28 pixels, which is 16384*28*28)

  • vl_high_resolution_images is false, the pixel limit is determined by max_pixels. If the input image's pixel count exceeds max_pixels, the image is scaled down to within the max_pixels limit. The default pixel limit for each model is the default value of max_pixels.

This parameter is not a standard OpenAI parameter. When you call using the Python SDK, place it in the extra_body object. Configuration: extra_body={"vl_high_resolution_images":xxx}.

n integer (Optional) Default value: 1

The number of responses to generate. The value range is 1-4. This is suitable for scenarios that require multiple candidate responses, such as creative writing or ad copy.

Only supported by Qwen3 (non-thinking mode) models.
If the tools parameter is passed, set n to 1.
Increasing n increases the output token consumption but not the input token consumption.

enable_thinking boolean (Optional)

When you use a mixed-thinking model, which supports both thinking and non-thinking modes, this parameter specifies whether to enable thinking mode. This applies to Qwen3.7, Qwen3.6, Qwen3.5, Qwen3, Qwen3-Omni-Flash, and Qwen3-VL models, along with the DeepSeek-V4-Pro/V4-Flash series, DeepSeek-V3.2/V3.2-exp/V3.1 series, Kimi-K2.7-code (thinking model only), Kimi-K2.6/K2.5 series, and GLM series. The DeepSeek-V4 series enables thinking by default. You can adjust the inference intensity with the reasoning_effort parameter.

Valid values:

  • true: Enable

    When enabled, the thinking content is returned in the reasoning_content field.
  • false: Disable

Default values for different models: Supported models

This parameter is not a standard OpenAI parameter. When you call using the Python SDK, place it in the extra_body object. Configuration: extra_body={"enable_thinking": xxx}.
If you call over HTTP directly (for example, with curl) instead of using the OpenAI SDK, do not use extra_body. Simply place enable_thinking at the top level of the request body (body), alongside parameters such as model and messages, for example "enable_thinking": true.
The MiniMax and MiniMax-M3 models from Xiyu Technology do not use this parameter. Instead, use the thinking parameter.

thinking object (Optional) Default value: {"type":"adaptive"}

Controls the thinking mode of MiniMax/MiniMax-M3 supplied by MiniMax.

thinking.type valid values:

  • adaptive: Automatic (default). The model decides whether to think.

  • disabled: Disables thinking and replies directly.

This parameter is not a standard OpenAI parameter. When you call using the Python SDK, place it in the extra_body object. Configuration: extra_body={"thinking": {"type": "adaptive"}}.

preserve_thinking boolean (Optional) Default value: false

Specifies whether to append the reasoning_content from assistant messages in the conversation history to the model input. This is suitable for scenarios where the model needs to refer to the historical thinking process.

Currently supported by qwen3.7-max, qwen3.7-max-2026-05-20 and subsequent snapshots, qwen3.6-max-preview, qwen3.7-plus, qwen3.7-plus-2026-05-26, qwen3.6-plus, qwen3.6-plus-2026-04-02, qwen3.6-flash, qwen3.6-flash-2026-04-16, kimi-k2.6 (deployed on Alibaba Cloud Model Studio), kimi-k2.7-code (deployed on Alibaba Cloud Model Studio, enabled by default), kimi/kimi-k2.7-code-highspeed (supplied by Moonshot AI, enabled by default), and kimi/kimi-k2.7-code (supplied by Moonshot AI, enabled by default).

  • If the historical messages do not contain reasoning_content, enabling this parameter does not cause an error.

  • When enabled, the reasoning_content from the historical conversation is included in the input token count and is billed.

This parameter is not a standard OpenAI parameter. When you call using the Python SDK, place it in the extra_body object. Configuration: extra_body={"preserve_thinking": True}.

thinking_budget integer (Optional)

The maximum number of tokens for the thinking process. This applies to the commercial and open source versions of Qwen3.7, Qwen3.6, Qwen3.5, Qwen3-VL, and Qwen3 models. For more information, see Limit thinking length.

The default value is the model's maximum chain-of-thought length. For more information, see the model list.

This parameter is not a standard OpenAI parameter. When you call using the Python SDK, place it in the extra_body object. Configuration: extra_body={"thinking_budget": xxx}.

reasoning_effort string (Optional) Default value: high

Controls the inference intensity of DeepSeek-V4 and GLM series models.

Valid values:

  • high: High-intensity inference

  • max: Maximum-intensity inference

low and medium are mapped to high, and xhigh is mapped to max.

This applies to glm-5.2, glm-5.1, glm-5, deepseek-v4-pro, and deepseek-v4-flash.

This parameter is not a standard OpenAI parameter. When you call using the Python SDK, place it in the extra_body object. Configuration: extra_body={"reasoning_effort": "high"}.

tool_stream boolean (Optional) Default value: false

Takes effect only when stream=true. This parameter is currently supported only by Qwen and GLM series.

Qwen series support list:

  • qwen-max series: text modality of the qwen3.7-max series

  • qwen-plus series: text modality of the qwen3.7-plus and qwen3.6-plus series, and omni-modality of the qwen3.5-plus series

  • qwen-flash series: omni-modality of the qwen3.6-flash and qwen3.5-flash series

Qwen series usage reference:

`tool_stream` only affects complex tool parameters. For normal tool parameters, streaming output is enabled as long as stream=true. Complex tools are tools where some parameter types in the tool definition are `array` or `object`.

  • tool_stream=false: Complex tool parameters are output at once. This is the default behavior, and complex formats are more accurate.

  • tool_stream=true: Complex tool parameters are output in a stream, which avoids timeout risks for complex formats.

GLM series support list: glm-4.6, glm-4.7, glm-5, and glm-5.1.

GLM series usage reference:

  • tool_stream=false: Tool parameters are output at once. This is the default behavior, and complex formats are more accurate.

  • tool_stream=true: Tool parameters are output in a stream, which avoids timeout risks for complex formats.

This parameter is not a standard OpenAI parameter. When you call using the Python SDK, place it in the extra_body object. Configuration: extra_body={"tool_stream": true}.

enable_code_interpreter boolean (Optional) Default value: false

Specifies whether to enable the code interpreter feature. For more information, see Code interpreter.

Valid values:

  • true: Enable

  • false: Disable

This parameter is not a standard OpenAI parameter. When you call using the Python SDK, place it in the extra_body object. Configuration: extra_body={"enable_code_interpreter": xxx}.

seed integer (Optional)

A random number seed. This parameter is used to ensure reproducible results with the same input and parameters. If you pass the same seed value in a call and other parameters remain unchanged, the model returns the same result as much as possible.

Value range: [0,2<sup>31</sup>−1].

logprobs boolean (Optional) Default value: false

Specifies whether to return the log probabilities of the output tokens. Valid values:

  • true

    Return

  • false

    Do not return

Content generated during the thinking phase (reasoning_content) does not return log probabilities.

Supported models

  • Snapshot models of the qwen-plus series (excluding stable version models)

  • Snapshot models of the qwen-turbo series (excluding stable version models)

  • qwen3-vl-plus series models (including stable version models)

  • qwen3-vl-flash series models (including stable version models)

  • Qwen3 open source models

top_logprobs integer (Optional) Default value: 0

Specifies the number of most likely candidate tokens to return at each generation step.

Value range: [0, 5]

This parameter takes effect only when logprobs is true.

stop string or array (Optional)

Used to specify stop words. When a string or token_id specified in stop appears in the generated text, generation stops immediately.

You can pass sensitive words to control the model's output.

When stop is an array, you cannot input both token_id and strings as elements. For example, you cannot specify ["Hello",104307].

tools array (Optional)

An array that contains one or more tool objects for the model to call in Function Calling. For more information, see Function Calling.

If `tools` is set and the model determines that a tool needs to be called, the response returns tool information in `tool_calls`.

Properties

type string (Required)

The tool type. Currently, only function is supported.

function object (Required)

Properties

name string (Required)

The tool name. Only letters, numbers, underscores (_), and hyphens (-) are allowed. The maximum length is 64 tokens.

description string (Required)

The tool description, which helps the model determine when and how to call the tool.

parameters object (Optional) Default value: {}

The parameter description for the tool, which must be a valid JSON Schema. For a description of JSON Schema, see the link. If the parameters parameter is empty, the tool has no input parameters, such as a time query tool.

To improve the accuracy of tool calls, we recommend that you pass parameters.

tool_choice string or object (Optional) Default value: auto

The tool selection strategy. To force a specific tool calling method for a certain type of problem, such as always using a specific tool or disabling all tools, you can set this parameter.

Valid values:

  • auto

    The large language model chooses the tool strategy.

  • none

    If you do not want to call a tool, you can set the tool_choice parameter to none.

  • {"type": "function", "function": {"name": "the_function_to_call"}}

    If you want to force a specific tool to be called, you can set the tool_choice parameter to {"type": "function", "function": {"name": "the_function_to_call"}}, where the_function_to_call is the name of the specified tool function.

    Thinking mode models do not support forcing a specific tool to be called.

parallel_tool_calls boolean (Optional) Default value: false

Specifies whether to enable parallel tool calling. For more information, see Parallel tool calling.

Valid values:

  • true: Enable

  • false: Disable

enable_search boolean (Optional) Default value: false

Specifies whether to enable web search. For more information, see Web search.

Valid values:

  • true: Enable.

    If web search is not performed after enabling, you can optimize the prompt or set the forced_search parameter in search_options to enable forced search.
  • false: Disable.

Enabling the web search feature may increase token consumption.
This parameter is not a standard OpenAI parameter. When you call using the Python SDK, place it in the extra_body object. Configuration: extra_body={"enable_search": True}.

search_options object (Optional)

The strategy for web search. For more information, see Web search.

Properties

forced_search boolean(Optional) Default value: false

Specifies whether to force web search. This parameter takes effect only when enable_search is set to true.

Valid values:

  • true: Force enable.

  • false: Do not force enable. The model decides whether to perform a web search.

search_strategy string(Optional) Default value: turbo

The search strategy. This parameter takes effect only when enable_search is set to true.

Valid values:

  • turbo (Default): Balances response speed and search effectiveness. This strategy is suitable for most scenarios.

  • max: Adopts a more comprehensive search strategy. This strategy can call multi-source search engines to obtain more detailed search results, but the response time may be longer.

  • agent: Can call the web search tool and the large language model multiple times to achieve multi-turn information retrieval and content integration.

    This strategy is applicable only to qwen3.5-plus, qwen3.5-plus-2026-02-15, qwen3.5-flash, qwen3.5-flash-2026-02-23, qwen3-max, qwen3-max-2026-01-23, qwen3-max-2025-09-23, qwen3.5-omni-plus, qwen3.5-omni-plus-2026-03-15, qwen3.5-omni-flash, and qwen3.5-omni-flash-2026-03-15.
  • agent_max: Supports web scraping based on the agent strategy. For more information, see Web scraping.

    This strategy is applicable only to the thinking mode of qwen3-max and qwen3-max-2026-01-23.

enable_search_extension boolean(Optional) Default value: false

Specifies whether to enable vertical search. This parameter takes effect only when enable_search is set to true.

Valid values:

  • true: Enable.

  • false: Disable.

This parameter is not a standard OpenAI parameter. When you call using the Python SDK, place it in the extra_body object. Configuration: extra_body={"search_options": xxx}.

clear_thinking boolean (Optional) Default value: false

Controls whether the reasoning_content (thinking process) from previous turns in a multi-turn conversation is used as context input for the model. This parameter is supported only by the GLM series models glm-5.2, glm-5.1, glm-5, and glm-4.7.

This parameter is not a standard OpenAI parameter. When you call using the Python SDK, place it in the extra_body object. Configuration: extra_body={"skill": [...]}.
  • true: Ignores the reasoning_content from previous turns and uses only visible text, tool calls, results, and other non-inference content as context input. This can reduce the context length and cost.

  • false (Default): Retains the reasoning_content from previous turns and provides it to the model along with the context. If you want to enable Preserved Thinking, you must pass the historical reasoning_content completely, unmodified, and in the original order within messages. Missing, trimming, rewriting, or reordering degrades performance or causes it to fail.

Chat response object (non-streaming output)

{
    "choices": [
        {
            "message": {
                "role": "assistant",
                "content": "I am a large-scale language model developed by Alibaba Cloud. My name is Qwen."
            },
            "finish_reason": "stop",
            "index": 0,
            "logprobs": null
        }
    ],
    "object": "chat.completion",
    "usage": {
        "prompt_tokens": 3019,
        "completion_tokens": 104,
        "total_tokens": 3123,
        "prompt_tokens_details": {
            "cached_tokens": 2048
        }
    },
    "created": 1735120033,
    "system_fingerprint": null,
    "model": "qwen-plus",
    "id": "chatcmpl-6ada9ed2-7f33-9de2-8bb0-78bd4035025a"
}

id string

The unique identifier for this call.

choices array

An array of content generated by the model.

Properties

finish_reason string

The reason why the model stopped generating.

Consider the following three scenarios:

  • stop: The model stopped generating because it triggered the stop parameter in the input or stopped naturally.

  • length: The model stopped generating because the generation length is too long.

  • tool_calls: The model stopped generating because a tool needs to be called.

index integer

The index of this object in the choices array.

logprobs object

The token probability information of the model's output.

Properties

content array

An array that contains each token and its log probability.

Properties

token string

The text of the current token.

bytes array

A list of the raw UTF-8 bytes of the current token. This is used to accurately restore the output content, such as emojis or Chinese characters.

logprob float

The log probability of the current token. A return value of null indicates an extremely low probability.

top_logprobs array

The most likely candidate tokens at the current token position. The number of tokens is consistent with the top_logprobs request parameter. Each element contains:

Properties

token string

The text of the candidate token.

bytes array

A list of the raw UTF-8 bytes of the current token. This is used to accurately restore the output content, such as emojis or Chinese characters.

logprob float

The log probability of this candidate token. A null value indicates an extremely low probability.

message object

The message that is output by the model.

Properties

content string

The content of the model's reply.

reasoning_content string

The chain-of-thought content of the model.

refusal string

This parameter is currently fixed to null.

role string

The role of the message. The value is fixed to assistant.

audio object

This parameter is currently fixed to null.

function_call (to be deprecated)object

This value is fixed to null. For more information, see the tool_calls parameter.

tool_calls array

The information about the tool and its input parameters that the model decides to call.

Properties

id string

The unique identifier for this tool call.

type string

The tool type. Currently, only function is supported.

function object

Tool details

Properties

name string

The tool name.

arguments string

The input parameter information, as a JSON formatted string.

Because the large language model's response is random, the output parameter information may not conform to the function signature. You must validate the parameters before you call the function.

index integer

The index of this tool call in the tool_calls array.

created integer

The Unix timestamp, in seconds, when the request was created.

model string

The model that is used for this request.

object string

The value is always chat.completion.

service_tier string

This parameter is currently fixed to null.

system_fingerprint string

This parameter is currently fixed to null.

usage object

The token consumption information for this request.

Properties

completion_tokens integer

The number of tokens in the model's output.

prompt_tokens integer

The number of input tokens. For more information, see Additional notes.

total_tokens integer

The total number of tokens consumed. This is the sum of prompt_tokens and completion_tokens.

completion_tokens_details object

A fine-grained classification of output tokens.

Properties

audio_tokens integer

This parameter is currently fixed to null.

reasoning_tokens integer

This parameter is currently fixed to null.

text_tokens integer

The number of tokens in the output text.

prompt_tokens_details object

A fine-grained classification of input tokens.

Properties

audio_tokens integer

This parameter is currently fixed to null.

cached_tokens integer

The number of tokens that hit the cache. For more information about Context Cache, see Context cache.

text_tokens integer

The number of input text tokens.

image_tokens integer

The number of input image tokens.

video_tokens integer

The number of tokens for the input video file or image list.

cache_creation object

The explicit cache creation information.

Properties

ephemeral_5m_input_tokens integer

The number of tokens that are used to create the explicit cache.

cache_creation_input_tokens integer

The number of tokens that are used to create the explicit cache.

cache_type string

When you use explicit cache, the parameter value is ephemeral. Otherwise, this parameter does not exist.

Chat response chunk object (streaming output)

{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[{"delta":{"content":"","function_call":null,"refusal":null,"role":"assistant","tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1735113344,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[{"delta":{"content":"I am","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1735113344,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[{"delta":{"content":" a large-scale","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1735113344,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[{"delta":{"content":" language","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1735113344,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[{"delta":{"content":" model from Alibaba","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1735113344,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[{"delta":{"content":" Cloud. My name","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1735113344,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[{"delta":{"content":" is Qwen","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1735113344,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[{"delta":{"content":".","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1735113344,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[{"delta":{"content":"","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":"stop","index":0,"logprobs":null}],"created":1735113344,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[],"created":1735113344,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":{"completion_tokens":17,"prompt_tokens":22,"total_tokens":39,"completion_tokens_details":null,"prompt_tokens_details":{"audio_tokens":null,"cached_tokens":0}}}

id string

The unique identifier for this call. Each chunk object has the same ID.

choices array

An array of content generated by the model, which can contain one or more objects. If the include_usage parameter is set to true, choices is an empty array in the last chunk.

Properties

delta object

The incremental object of the request.

Properties

content string

The incremental message content.

reasoning_content string

The incremental chain-of-thought content.

function_call object

This value defaults to null. For more information, see the tool_calls parameter.

audio object

The reply that is generated when you use the Qwen-Omni model.

Properties

data string

The incremental Base64-encoded audio data.

expires_at integer

The timestamp when the request was created.

refusal object

This parameter is currently fixed to null.

role string

The role of the incremental message object. It has a value only in the first chunk.

tool_calls array

The information about the tool and its input parameters that the model decides to call.

Properties

index integer

The index of this tool call in the tool_calls array.

id string

The unique identifier for this tool call.

function object

The information about the called tool.

Properties

arguments string

The incremental input parameters. The arguments from all chunks are concatenated to form the complete set of input parameters.

Because the large language model's response is random, the output parameter information may not conform to the function signature. You must validate the parameters before you call the function.

name string

The tool name. It has a value only in the first chunk.

type string

The tool type. Currently, only function is supported.

finish_reason string

The reason why the model stopped generating. The value can be one of the following:

  • stop: The model stopped generating because it triggered the stop parameter in the input or stopped naturally.

  • The value is null until the generation is complete.

  • length: The model stopped generating because the generation length is too long.

  • tool_calls: The model stopped generating because a tool needs to be called.

index integer

The index of the current response in the choices array. When the input parameter n is greater than 1, you can use this parameter to concatenate the complete content that corresponds to different responses.

logprobs object

The probability information of the current object.

Properties

content array

An array of tokens with log probability information.

Properties

token string

The current token.

bytes array

A list of the raw UTF-8 bytes of the current token. This is helpful when you process emojis and Chinese characters.

logprob float

The log probability of the current token. A null value indicates an extremely low probability.

top_logprobs array

The most likely tokens at the current token position and their log probabilities. The number of elements is consistent with the top_logprobs input parameter.

Properties

token string

The current token.

bytes array

A list of the raw UTF-8 bytes of the current token. This is helpful when you process emojis and Chinese characters.

logprob float

The log probability of the current token. A null value indicates an extremely low probability.

created integer

The timestamp when this request was created. Each chunk has the same timestamp.

model string

The model that is used for this request.

object string

The value is always chat.completion.chunk.

service_tier string

This parameter is currently fixed to null.

system_fingerprintstring

This parameter is currently fixed to null.

usage object

The tokens consumed by this request. It is displayed only in the last chunk when include_usage is set to true.

Properties

completion_tokens integer

The number of tokens in the model's output.

prompt_tokens integer

The number of input tokens.

total_tokens integer

The total number of tokens, which is the sum of prompt_tokens and completion_tokens.

completion_tokens_details object

Detailed information about the output tokens.

Properties

audio_tokens integer

The number of output audio tokens.

reasoning_tokens integer

The number of tokens in the thinking process.

text_tokens integer

The number of output text tokens.

prompt_tokens_details object

A fine-grained classification of input tokens.

Properties

audio_tokens integer

The number of input audio tokens.

The number of audio tokens in a video file is returned in this parameter.

text_tokens integer

The number of input text tokens.

video_tokens integer

The number of tokens for the input video, which can be an image list or a video file.

image_tokens integer

The number of input image tokens.

cached_tokens integer

The number of tokens that hit the cache. For more information about Context Cache, see Context cache.

cache_creation object

The explicit cache creation information.

Properties

ephemeral_5m_input_tokens integer

The number of tokens that are used to create the explicit cache.

cache_creation_input_tokens integer

The number of tokens that are used to create the explicit cache.

cache_type string

The cache type. The value is fixed to ephemeral.

Error codes

If the model call fails and an error message is returned, see Error codes to resolve the issue.