Request body | Text inputPythonimport os
import dashscope
# The following is the base_url for the Singapore region. When making a call, replace {WorkspaceId} with your actual workspace ID. The URLs for different regions vary.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': 'Who are you?'}
]
response = dashscope.Generation.call(
# If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
# The API keys for the Singapore/US (Virginia) and China (Beijing) regions are different. To obtain an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen-plus", # This example uses qwen-plus. You can replace it with another model name as needed. For a list of models, see https://www.alibabacloud.com/help/en/model-studio/getting-started/models
messages=messages,
result_format='message'
)
print(response)
Java// We recommend that you use DashScope SDK V2.12.0 or later.
import java.util.Arrays;
import java.lang.System;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.protocol.Protocol;
public class Main {
public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
// The following is the base_url for the Singapore region. When making a call, replace {WorkspaceId} with your actual workspace ID. The URLs for different regions vary.
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
Message systemMsg = Message.builder()
.role(Role.SYSTEM.getValue())
.content("You are a helpful assistant.")
.build();
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("Who are you?")
.build();
GenerationParam param = GenerationParam.builder()
// If you have not configured an environment variable, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
// The API keys for the Singapore/US (Virginia) and China (Beijing) regions are different. To obtain an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// This example uses qwen-plus. You can replace it with another model name as needed. For a list of models, see https://www.alibabacloud.com/help/en/model-studio/getting-started/models
.model("qwen-plus")
.messages(Arrays.asList(systemMsg, userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.build();
return gen.call(param);
}
public static void main(String[] args) {
try {
GenerationResult result = callWithMessage();
System.out.println(JsonUtils.toJson(result));
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
// Use a logging framework to record the exception information.
System.err.println("An error occurred while calling the generation service: " + e.getMessage());
}
System.exit(0);
}
}
PHP (HTTP)<?php
$url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// The API keys for the Singapore/US (Virginia) and China (Beijing) regions are different. To obtain an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
$apiKey = getenv('DASHSCOPE_API_KEY');
$data = [
// This example uses qwen-plus. You can replace it with another model name as needed. For a list of models, see https://www.alibabacloud.com/help/en/model-studio/getting-started/models
"model" => "qwen-plus",
"input" => [
"messages" => [
[
"role" => "system",
"content" => "You are a helpful assistant."
],
[
"role" => "user",
"content" => "Who are you?"
]
]
],
"parameters" => [
"result_format" => "message"
]
];
$jsonData = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer $apiKey",
"Content-Type: application/json"
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode == 200) {
echo "Response: " . $response;
} else {
echo "Error: " . $httpCode . " - " . $response;
}
curl_close($ch);
?>
Node.js (HTTP)DashScope does not provide an SDK for the Node.js environment. To make calls using the OpenAI Node.js SDK, see the OpenAI section in this topic. import fetch from 'node-fetch';
// The API keys for the Singapore/US (Virginia) and China (Beijing) regions are different. To obtain an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
const apiKey = process.env.DASHSCOPE_API_KEY;
const data = {
model: "qwen-plus", // This example uses qwen-plus. You can replace it with another model name as needed. For a list of models, see https://www.alibabacloud.com/help/en/model-studio/getting-started/models
input: {
messages: [
{
role: "system",
content: "You are a helpful assistant."
},
{
role: "user",
content: "Who are you?"
}
]
},
parameters: {
result_format: "message"
}
};
fetch('https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
console.log(JSON.stringify(data));
})
.catch(error => {
console.error('Error:', error);
});
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 you have not configured an environment variable, replace the following line with your Model Studio API key: string? apiKey = "sk-xxx";
// The API keys for the Singapore/US (Virginia) and China (Beijing) regions are different. To obtain an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("The API key is not set. Make sure that the 'DASHSCOPE_API_KEY' environment variable is set.");
return;
}
// Set the request URL and content.
string url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// This example uses qwen-plus. You can replace it with another model name as needed. For a list of models, see https://www.alibabacloud.com/help/en/model-studio/getting-started/models
string jsonContent = @"{
""model"": ""qwen-plus"",
""input"": {
""messages"": [
{
""role"": ""system"",
""content"": ""You are a helpful assistant.""
},
{
""role"": ""user"",
""content"": ""Who are you?""
}
]
},
""parameters"": {
""result_format"": ""message""
}
}";
// 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 the 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}";
}
}
}
}
Go (HTTP)DashScope does not provide an SDK for Go. To make calls using the OpenAI Go SDK, see the OpenAI-Go section in this topic. package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type Input struct {
Messages []Message `json:"messages"`
}
type Parameters struct {
ResultFormat string `json:"result_format"`
}
type RequestBody struct {
Model string `json:"model"`
Input Input `json:"input"`
Parameters Parameters `json:"parameters"`
}
func main() {
// Create an HTTP client.
client := &http.Client{}
// Build the request body.
requestBody := RequestBody{
// This example uses qwen-plus. You can replace it with another model name as needed. For a list of models, see https://www.alibabacloud.com/help/en/model-studio/getting-started/models
Model: "qwen-plus",
Input: Input{
Messages: []Message{
{
Role: "system",
Content: "You are a helpful assistant.",
},
{
Role: "user",
Content: "Who are you?",
},
},
},
Parameters: Parameters{
ResultFormat: "message",
},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
log.Fatal(err)
}
// Create a POST request.
req, err := http.NewRequest("POST", "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation", bytes.NewBuffer(jsonData))
if err != nil {
log.Fatal(err)
}
// Set the request headers.
// If you have not configured an environment variable, replace the following line with your Model Studio API key: apiKey := "sk-xxx"
// The API keys for the Singapore/US (Virginia) and China (Beijing) regions are different. To obtain an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
apiKey := os.Getenv("DASHSCOPE_API_KEY")
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send the request.
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// Read the response body.
bodyText, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
// Print the response content.
fmt.Printf("%s\n", bodyText)
}
curlReplace {WorkspaceId} with your actual workspace ID. The API keys for the Singapore, US (Virginia), and China (Beijing) regions are different. For more information, see Obtain an API key curl --location "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "qwen-plus",
"input":{
"messages":[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Who are you?"
}
]
},
"parameters": {
"result_format": "message"
}
}'
Streaming outputFor more information, see Streaming output. Text generation modelsPythonimport os
import dashscope
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{'role':'system','content':'you are a helpful assistant'},
{'role': 'user','content': 'Who are you?'}
]
responses = dashscope.Generation.call(
# If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
# The API keys for the Singapore/US (Virginia) and China (Beijing) regions are different. To obtain an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key=os.getenv('DASHSCOPE_API_KEY'),
# This example uses qwen-plus. You can replace it with another model name as needed. For a list of models, see https://www.alibabacloud.com/help/en/model-studio/getting-started/models
model="qwen-plus",
messages=messages,
result_format='message',
stream=True,
incremental_output=True
)
for response in responses:
print(response)
Javaimport java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import io.reactivex.Flowable;
import java.lang.System;
import com.alibaba.dashscope.protocol.Protocol;
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
private static void handleGenerationResult(GenerationResult message) {
System.out.println(JsonUtils.toJson(message));
}
public static void streamCallWithMessage(Generation gen, Message userMsg)
throws NoApiKeyException, ApiException, InputRequiredException {
GenerationParam param = buildGenerationParam(userMsg);
Flowable<GenerationResult> result = gen.streamCall(param);
result.blockingForEach(message -> handleGenerationResult(message));
}
private static GenerationParam buildGenerationParam(Message userMsg) {
return GenerationParam.builder()
// If you have not configured an environment variable, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
// The API keys for the Singapore/US (Virginia) and China (Beijing) regions are different. To obtain an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// This example uses qwen-plus. You can replace it with another model name as needed. For a list of models, see https://www.alibabacloud.com/help/en/model-studio/getting-started/models
.model("qwen-plus")
.messages(Arrays.asList(userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.incrementalOutput(true)
.build();
}
public static void main(String[] args) {
try {
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
Message userMsg = Message.builder().role(Role.USER.getValue()).content("Who are you?").build();
streamCallWithMessage(gen, userMsg);
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
logger.error("An exception occurred: {}", e.getMessage());
}
System.exit(0);
}
}
curlcurl --location "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--header "X-DashScope-SSE: enable" \
--data '{
"model": "qwen-plus",
"input":{
"messages":[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Who are you?"
}
]
},
"parameters": {
"result_format": "message",
"incremental_output":true
}
}'
Multimodal modelsPythonimport os
from dashscope import MultiModalConversation
import dashscope
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": [
{"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
{"text": "What is depicted in the image?"}
]
}
]
responses = MultiModalConversation.call(
# The API keys for the Singapore/US (Virginia) and China (Beijing) regions are different. To obtain an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
# If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
model='qwen3-vl-plus', # You can replace this with another multimodal model and modify the messages accordingly.
messages=messages,
stream=True,
incremental_output=True)
full_content = ""
print("Streaming output content:")
for response in responses:
if response["output"]["choices"][0]["message"].content:
print(response.output.choices[0].message.content[0]['text'])
full_content += response.output.choices[0].message.content[0]['text']
print(f"Full content: {full_content}")
Javaimport java.util.Arrays;
import java.util.Collections;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import io.reactivex.Flowable;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
public static void streamCall()
throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
// must create mutable map.
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(Collections.singletonMap("image", "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"),
Collections.singletonMap("text", "What is depicted in the image?"))).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// The API keys for the Singapore/US (Virginia) and China (Beijing) regions are different. To obtain an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
// If you have not configured an environment variable, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3-vl-plus") // You can replace this with another multimodal model and modify the messages accordingly.
.messages(Arrays.asList(userMessage))
.incrementalOutput(true)
.build();
Flowable<MultiModalConversationResult> result = conv.streamCall(param);
result.blockingForEach(item -> {
try {
var content = item.getOutput().getChoices().get(0).getMessage().getContent();
// Check if content exists and is not empty.
if (content != null && !content.isEmpty()) {
System.out.println(content.get(0).get("text"));
}
} catch (Exception e){
System.exit(0);
}
});
}
public static void main(String[] args) {
try {
streamCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
curlcurl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-H 'X-DashScope-SSE: enable' \
-d '{
"model": "qwen3-vl-plus",
"input":{
"messages":[
{
"role": "user",
"content": [
{"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
{"text": "What is depicted in the image?"}
]
}
]
},
"parameters": {
"incremental_output": true
}
}'
Image inputFor more information about how to use large language models (LLMs) to analyze images, see Image and video understanding. Pythonimport os
import dashscope
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": [
{"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
{"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"},
{"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/rabbit.png"},
{"text": "What are these?"}
]
}
]
response = dashscope.MultiModalConversation.call(
# The API keys for the Singapore, Virginia, and Beijing regions are different. To get an API key, visit https://www.alibabacloud.com/help/zh/model-studio/get-api-key
api_key=os.getenv('DASHSCOPE_API_KEY'),
# This example uses qwen-vl-max. You can replace it with another model name as needed. For a list of models, visit https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
model='qwen-vl-max',
messages=messages
)
print(response)
Java// Copyright (c) Alibaba, Inc. and its affiliates.
import java.util.Arrays;
import java.util.Collections;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
public static void simpleMultiModalConversationCall()
throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
Collections.singletonMap("image", "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"),
Collections.singletonMap("image", "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"),
Collections.singletonMap("image", "https://dashscope.oss-cn-beijing.aliyuncs.com/images/rabbit.png"),
Collections.singletonMap("text", "What are these?"))).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// If you have not configured the environment variable, replace the next line with .apiKey("sk-xxx") and use your Model Studio API key.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// This example uses qwen-vl-plus. You can replace it with another model name as needed. For a list of models, visit https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
.model("qwen-vl-plus")
.message(userMessage)
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
simpleMultiModalConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
curlReplace {WorkspaceId} with your actual workspace ID. The API keys for the Singapore, US (Virginia), and China (Beijing) regions are different. To obtain an API key, see Get an API key curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"model": "qwen-vl-plus",
"input":{
"messages":[
{
"role": "user",
"content": [
{"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
{"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"},
{"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/rabbit.png"},
{"text": "What are these?"}
]
}
]
}
}'
Video inputThe following examples show how to input video frames. For more information about other methods, such as inputting a video file, see Visual understanding. Pythonimport os
# The DashScope SDK version must be 1.20.10 or later.
import dashscope
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [{"role": "user",
"content": [
# If you use a model from the Qwen2.5-VL series and input a list of images, you can set the fps parameter. This parameter specifies that the images are extracted from the original video every 1/fps seconds.
{"video":["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"],
"fps":2},
{"text": "Describe the events in this video"}]}]
response = dashscope.MultiModalConversation.call(
# If you have not configured the environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
# API keys are different for the Singapore/Virginia and Beijing regions. To obtain an API key, see https://www.alibabacloud.com/help/zh/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
model='qwen-vl-max', # This example uses qwen-vl-max. Replace it with another model name as needed. For a list of models, see https://www.alibabacloud.com/help/zh/model-studio/models
messages=messages
)
print(response["output"]["choices"][0]["message"].content[0]["text"])
Java// The DashScope SDK version must be 2.18.3 or later.
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
private static final String MODEL_NAME = "qwen-vl-max"; // This example uses qwen-vl-max. Replace it with another model name as needed. For a list of models, see https://www.alibabacloud.com/help/zh/model-studio/models
public static void videoImageListSample() throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage systemMessage = MultiModalMessage.builder()
.role(Role.SYSTEM.getValue())
.content(Arrays.asList(Collections.singletonMap("text", "You are a helpful assistant.")))
.build();
// If you use a model from the Qwen2.5-VL series and input a list of images, you can set the fps parameter. This parameter specifies that the images are extracted from the original video every 1/fps seconds.
Map<String, Object> params = Map.of(
"video", Arrays.asList("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"),
"fps",2);
MultiModalMessage userMessage = MultiModalMessage.builder()
.role(Role.USER.getValue())
.content(Arrays.asList(
params,
Collections.singletonMap("text", "Describe the events in this video")))
.build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// If you have not configured the environment variable, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
// API keys are different for the Singapore/Virginia and Beijing regions. To obtain an API key, see https://www.alibabacloud.com/help/zh/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model(MODEL_NAME)
.messages(Arrays.asList(systemMessage, userMessage)).build();
MultiModalConversationResult result = conv.call(param);
System.out.print(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
}
public static void main(String[] args) {
try {
videoImageListSample();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
curlReplace {WorkspaceId} with your actual workspace ID. The API keys are different for the Singapore, US (Virginia), and China (Beijing) regions. For more information, see Get an API key curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen-vl-max",
"input": {
"messages": [
{
"role": "user",
"content": [
{
"video": [
"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"
],
"fps":2
},
{
"text": "Describe the events in this video"
}
]
}
]
}
}'
Tool callingFor the complete code of the function calling flow, see Overview. Pythonimport os
import dashscope
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
tools = [
{
"type": "function",
"function": {
"name": "get_current_time",
"description": "Useful for getting the current time.",
"parameters": {}
}
},
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Useful for getting the weather in a specific city.",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city or district, such as Beijing, Hangzhou, or Yuhang District."
}
}
},
"required": [
"location"
]
}
}
]
messages = [{"role": "user", "content": "What is the weather like in Hangzhou?"}]
response = dashscope.Generation.call(
# If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
# The API keys for the Singapore, Virginia, and Beijing regions are different. To get an API key, visit: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key=os.getenv('DASHSCOPE_API_KEY'),
# This example uses qwen-plus. You can replace it with another model as needed. For a list of models, visit: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
model='qwen-plus',
messages=messages,
tools=tools,
result_format='message'
)
print(response)
Javaimport java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.alibaba.dashscope.aigc.conversation.ConversationParam.ResultFormat;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.tools.FunctionDefinition;
import com.alibaba.dashscope.tools.ToolFunction;
import com.alibaba.dashscope.utils.JsonUtils;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.victools.jsonschema.generator.Option;
import com.github.victools.jsonschema.generator.OptionPreset;
import com.github.victools.jsonschema.generator.SchemaGenerator;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfig;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder;
import com.github.victools.jsonschema.generator.SchemaVersion;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import com.alibaba.dashscope.protocol.Protocol;
public class Main {
public class GetWeatherTool {
private String location;
public GetWeatherTool(String location) {
this.location = location;
}
public String call() {
return location + " is sunny today.";
}
}
public class GetTimeTool {
public GetTimeTool() {
}
public String call() {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String currentTime = "Current time: " + now.format(formatter) + ".";
return currentTime;
}
}
public static void SelectTool()
throws NoApiKeyException, ApiException, InputRequiredException {
SchemaGeneratorConfigBuilder configBuilder =
new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2020_12, OptionPreset.PLAIN_JSON);
SchemaGeneratorConfig config = configBuilder.with(Option.EXTRA_OPEN_API_FORMAT_VALUES)
.without(Option.FLATTENED_ENUMS_FROM_TOSTRING).build();
SchemaGenerator generator = new SchemaGenerator(config);
ObjectNode jsonSchema_weather = generator.generateSchema(GetWeatherTool.class);
ObjectNode jsonSchema_time = generator.generateSchema(GetTimeTool.class);
FunctionDefinition fdWeather = FunctionDefinition.builder().name("get_current_weather").description("Gets the weather for a specified area")
.parameters(JsonUtils.parseString(jsonSchema_weather.toString()).getAsJsonObject()).build();
FunctionDefinition fdTime = FunctionDefinition.builder().name("get_current_time").description("Gets the current time")
.parameters(JsonUtils.parseString(jsonSchema_time.toString()).getAsJsonObject()).build();
Message systemMsg = Message.builder().role(Role.SYSTEM.getValue())
.content("You are a helpful assistant. When asked a question, use tools wherever possible.")
.build();
Message userMsg = Message.builder().role(Role.USER.getValue()).content("Weather in Hangzhou").build();
List<Message> messages = new ArrayList<>();
messages.addAll(Arrays.asList(systemMsg, userMsg));
GenerationParam param = GenerationParam.builder()
// The API keys for the Singapore, Virginia, and Beijing regions are different. To get an API key, visit: https://www.alibabacloud.com/help/en/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// This example uses qwen-plus. You can replace it with another model as needed. For a list of models, visit: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
.model("qwen-plus")
.messages(messages)
.resultFormat(ResultFormat.MESSAGE)
.tools(Arrays.asList(
ToolFunction.builder().function(fdWeather).build(),
ToolFunction.builder().function(fdTime).build()))
.build();
// The following is the base URL for the Singapore region. When making a call, replace {WorkspaceId} with your actual workspace ID. The URL varies by region.
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
GenerationResult result = gen.call(param);
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
SelectTool();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.println(String.format("Exception %s", e.getMessage()));
}
System.exit(0);
}
}
curlReplace {WorkspaceId} with your actual workspace ID. The API keys for the Singapore, US (Virginia), and China (Beijing) regions are different. For more information, see Get an API key The following URL is for the Singapore region. curl --location "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "qwen-plus",
"input": {
"messages": [{
"role": "user",
"content": "What is the weather like in Hangzhou?"
}]
},
"parameters": {
"result_format": "message",
"tools": [{
"type": "function",
"function": {
"name": "get_current_time",
"description": "Useful for getting the current time.",
"parameters": {}
}
},{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Useful for getting the weather in a specific city.",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city or district, such as Beijing, Hangzhou, or Yuhang District."
}
}
},
"required": ["location"]
}
}]
}
}'
Asynchronous invocation# Your Dashscope Python SDK must be version 1.19.0 or later.
import asyncio
import platform
import os
import dashscope
from dashscope.aigc.generation import AioGeneration
# The following base_url is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. The URL varies by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
async def main():
response = await AioGeneration.call(
# If you do not configure an environment variable, replace the next line with api_key="sk-xxx", where sk-xxx is your Model Studio API key.
# The API keys for the Singapore, Virginia, and Beijing regions are different. To get an API key, see https://www.alibabacloud.com/help/zh/model-studio/get-api-key
api_key=os.getenv('DASHSCOPE_API_KEY'),
# This example uses the qwen-plus model. You can change the model name as needed. For a list of models, see https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
model="qwen-plus",
messages=[{"role": "user", "content": "Who are you?"}],
result_format="message",
)
print(response)
if platform.system() == "Windows":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())
Document understandingPythonimport os
import dashscope
# Currently, the qwen-long-latest model can be called only in the China (Beijing) region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{'role': 'system', 'content': 'you are a helpful assistant'},
# Replace '{FILE_ID}' with the file-id used in your actual conversation scenario.
{'role':'system','content':f'fileid://{FILE_ID}'},
{'role': 'user', 'content': 'What is this article about?'}]
response = dashscope.Generation.call(
# If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen-long-latest",
messages=messages,
result_format='message'
)
print(response)
Javaimport os
import dashscope
# Currently, the qwen-long-latest model can be called only in the China (Beijing) region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{'role': 'system', 'content': 'you are a helpful assistant'},
# Replace '{FILE_ID}' with the file-id used in your actual conversation scenario.
{'role':'system','content':f'fileid://{FILE_ID}'},
{'role': 'user', 'content': 'What is this article about?'}]
response = dashscope.Generation.call(
# If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen-long-latest",
messages=messages,
result_format='message'
)
print(response)
curlCurrently, only the China (Beijing) region supports calling the document understanding model. Replace {FILE_ID} with the file ID that is used in your actual conversation scenario. curl --location "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "qwen-long-latest",
"input":{
"messages":[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "system",
"content": "fileid://{FILE_ID}"
},
{
"role": "user",
"content": "What is this article about?"
}
]
},
"parameters": {
"result_format": "message"
}
}'
|
model string (Required) The name of the model to use. Supported models include Qwen large language models (commercial and open source editions), Qwen-VL, Qwen-Coder, math models, DeepSeek, Kimi, GLM, and MiniMax. For specific model names and billing details, see Select a model. |
messages array (Required) The context to pass to the large language model (LLM), arranged in conversational order. When you call over HTTP, place messages in the input object. Message types System Message object (Optional) A system message that is used to set the role, tone, task objectives, or constraints for the LLM. It is usually placed first in the messages array. We do not recommend that you set a system message for QwQ models. A system message does not take effect for QVQ models. Properties content string (Required) The content of the message. role string (Required) The role for the system message. The value is fixed to system. User Message object (Required) A user message that is used to pass questions, instructions, or context to the model. Properties content string or array (Required) The content of the message. If the input is only text, this parameter is a string. If the input includes multimodal data, such as images, or if explicit caching is enabled, this parameter is an array. Properties text string (Required) The input text. image string (Optional) The image file for image understanding. You can pass an image in one of the following three ways: Public URL: A publicly accessible image link. Base64 encoding of the image, in the format data:image/<format>;base64,<data>. Local file: The absolute path of a local file.
Applicable models: Qwen-VL, QVQ Example: {"image":"https://xxxx.jpeg"} video array or string (Optional) The video to pass when you use a Qwen-VL model or a QVQ model. If you pass an image list, the type is array. If you pass a video file, the type is string.
To pass a local file, see Local file (Qwen-VL) or Local file (QVQ). Examples: Image list: {"video":["https://xx1.jpg",...,"https://xxn.jpg"]} Video file: {"video":"https://xxx.mp4"}
fps float (Optional) The number of frames to extract per second. The value must be in the range of [0.1, 10]. The default value is 2.0. Description The `fps` parameter has two functions: When a video file is the input, this parameter controls the frame extraction frequency. One frame is extracted every fps1 seconds. This applies to Qwen-VL models and QVQ models. It informs the model of the time interval between adjacent frames, which helps the model better understand the video's temporal dynamics. This applies to both video file and image list inputs. This feature is suitable for scenarios such as event time localization or summarizing content by segment. This is supported by Qwen3.7, Qwen3.6, Qwen3.5, Qwen3-VL, Qwen2.5-VL, and QVQ models.
A larger fps value is suitable for high-speed motion scenarios, such as sports events and action movies. A smaller fps value is suitable for long videos or scenarios with relatively static content. Examples Passing an image list: {"video":["https://xx1.jpg",...,"https://xxn.jpg"],"fps":2} Passing a video file: {"video": "https://xx1.mp4","fps":2}
max_frames integer (Optional) The maximum number of frames that can be extracted from a video. If the number of frames calculated based on fps exceeds max_frames, the system automatically adjusts to extract frames uniformly within the max_frames limit. This ensures that the total number of frames does not exceed the limit. Value range qwen3.7 series, qwen3.6 series, qwen3.5 series: The maximum and default value is 8000. qwen3-vl-plus series, qwen3-vl-flash series, qwen3-vl-235b-a22b-thinking, qwen3-vl-235b-a22b-instruct: The maximum and default value is 2000.
qwen-vl-max, qwen-vl-max-0813, qwen-vl-plus, qwen-vl-plus-0815: The maximum and default value is 512.
Sample value {"type": "video_url","video_url": {"url":"https://xxxx.mp4"},"max_frame": 2000}
When you call with an OpenAI-compatible API, you cannot customize the max_frames parameter. The API automatically uses the default value for each model. min_pixels integer (Optional) Sets the minimum pixel threshold for the input image or video frames. If the total pixels of an input image or video frame are less than min_pixels, the image or frame is enlarged until its total pixels are higher than min_pixels. Examples 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) Sets the maximum pixel threshold for the input image or video frames. If the total pixels of an input image or video are within the [min_pixels, max_pixels] range, the model recognizes the original image. If the total pixels of the input image are greater than max_pixels, the image is scaled down until the total pixels are below max_pixels. Value range Image input: The value of max_pixels depends on whether the <a baseurl="t3230323_v1_0_0.xdita" data-node="4759789" data-root="85177" data-tag="xref" href="t2614691.xdita#0edad44583knr" id="758d486a79gkv">vl_high_resolution_images</a> parameter is enabled. Video file or image list input: qwen3.7 series, qwen3.6 series, qwen3.5 series, qwen3-vl-plus series, qwen3-vl-flash series, qwen3-vl-235b-a22b-thinking, qwen3-vl-235b-a22b-instruct: The default value is 655360, and the maximum value is 2048000.
Other Qwen3-VL open source models, qwen-vl-max, qwen-vl-max-0813, qwen-vl-plus, qwen-vl-plus-0815: The default value is 655360, and the maximum value is 786432. Other qwen-vl-plus models, other qwen-vl-max models, Qwen2.5-VL open source series, and QVQ series models: The default value is 501760, and the maximum value is 602112.
Examples 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 pixels of all frames that are extracted from a video (pixels of a single frame × total number of frames). If the total pixels of the video exceed this limit, the system scales down the video frames but still ensures that the pixel value of a single frame is within the [min_pixels, max_pixels] range. This applies to Qwen-VL and QVQ models. For long videos with many extracted frames, you can appropriately lower this value to reduce token consumption and processing time, but this may result in the loss of image details. Value range qwen3.7 series, qwen3.6 series, qwen3.5 series: The default and maximum value is 819200000. This value corresponds to 800000 image tokens (1 image token per 32×32 pixels). qwen3-vl-plus series, qwen3-vl-flash series, qwen3-vl-235b-a22b-thinking, qwen3-vl-235b-a22b-instruct: The default and maximum value is 134217728. This value corresponds to 131072 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: The default and minimum value is 67108864. This value 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: The default and minimum value is 51380224. This value corresponds to 65536 image tokens (1 image token per 28×28 pixels).
Examples 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) This is supported only by models that support explicit caching. It is used to enable explicit caching. Properties type string (Required) The value must be ephemeral. role string (Required) The role for a user message. The value must be user. Assistant Message object (Optional) The model's reply to the user message. Properties content string (Optional) The content of the message. This is optional only if the tool_calls parameter is specified in the assistant message. role string (Required) The value must be assistant. partial boolean (Optional) Specifies whether to enable partial mode. For more information and a list of supported models, see Partial mode. tool_calls array (Optional) The tool and input parameter information that is returned after you initiate a function call. It contains one or more objects. This is obtained from the tool_calls field of the previous model response. Properties id string The ID of the tool response. type string The tool type. Currently, only function is supported. function object The tool and input parameter information. Properties name string The tool name. arguments string The input parameter information, in JSON string format. index integer The index of the current tool information in the tool_calls array. Tool Message object (Optional) The output information of the tool. Properties content string (Required) The output content of the tool function. It must be in string format. role string (Required) The value must be tool. tool_call_id string (Optional) The ID that is returned after you initiate a function call. You can retrieve it using response.output.choices[0].message.tool_calls[$index]["id"]. It is used to mark the tool that corresponds to the tool message. |
temperature float (Optional) The sampling temperature, which controls the diversity of the text that is generated by the model. A higher temperature results in more diverse text, and a lower temperature results in more deterministic text. Value range: [0, 2) When you call over HTTP, place temperature in the parameters object. We do not recommend that you 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 that is generated by the model. A higher `top_p` value results in more diverse text, and a lower `top_p` value results in more deterministic text. Value range: (0, 1.0]. In the Java SDK, this parameter is topP. When you call over HTTP, place top_p in the parameters object. We do not recommend that you modify the default `top_p` value for QVQ models. |
top_k integer (Optional) The size of the candidate set for sampling during generation. For example, if you set this parameter to 50, only the 50 tokens with the highest scores in a single generation are used to form the candidate set for random sampling. A larger value increases randomness, and a smaller value increases determinism. A value of `None` or a value greater than 100 indicates that the `top_k` strategy is not enabled and only the `top_p` strategy takes effect. The value must be greater than or equal to 0. Default top_k values QVQ series: 10 QwQ series: 40 models before the rest of the qwen-vl-plus series, : 1 All other models: 20 GLM series (provided by Alibaba Cloud): 20 DeepSeek, Kimi, and MiniMax series do not support the `top_k` parameter. In the Java SDK, this parameter is topK. When you call over HTTP, place top_k in the parameters object. We do not recommend that you modify the default `top_k` value for QVQ models. |
enable_thinking boolean (Optional) Specifies whether to enable thinking mode for a hybrid thinking model. This applies to Qwen3.7, Qwen3.6, Qwen3.5, Qwen3, and Qwen3-VL models, along with the DeepSeek-V4-Pro/V4-Flash series, DeepSeek-V3.2/V3.2-exp/V3.1 series, Kimi-K2.6/K2.5 series, and GLM series. The DeepSeek-V4 series has thinking mode enabled by default. You can adjust the inference effort with the reasoning_effort parameter. Valid values: For the default values for different models, see Supported models. In the Java SDK, this parameter is `enableThinking`. When you call over HTTP, place enable_thinking in the parameters object. |
preserve_thinking boolean (Optional) The default value is 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.
When you call over HTTP, place preserve_thinking in the parameters object. The Java SDK is not supported. |
thinking_budget integer (Optional) The maximum length of the thinking process. This applies to the commercial and open source editions of Qwen3.7, Qwen3.6, Qwen3.5, Qwen3-VL, and Qwen3 models. For more information, see Limit thinking length. The default value is the maximum chain-of-thought length for the model. For more information, see Select a model. In the Java SDK, this parameter is `thinkingBudget`. When you call over HTTP, place thinking_budget in the parameters object. The default value is the maximum chain-of-thought length for the model. |
reasoning_effort string (Optional) The default value is high. Controls the inference effort of DeepSeek-V4 and GLM series models. The valid values are high (high-effort inference) and max (maximum-effort 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. When you call over HTTP, place reasoning_effort in the parameters object. |
tool_stream boolean (Optional) The default value is false. This parameter only affects the streaming output behavior of complex tool parameters and is effective only in streaming calls. Simple tool parameters, where all parameter types are strings, can be streamed as long as streaming calls are enabled. tool_stream has no effect on them. Complex tools are tools where some parameter types in the tool definition are arrays or objects. Currently, only the Qwen and GLM series support this. Qwen series support list: Qwen series usage reference: Complex tools are tools where some parameter types in the tool definition are arrays or objects. GLM series support list: glm-4.6, glm-4.7, glm-5, and glm-5.1. GLM series usage reference: When you call over HTTP, place tool_stream in the parameters object. |
enable_code_interpreter boolean (Optional) The default value is false. Specifies whether to enable the code interpreter feature. For more information, see Code interpreter. Valid values: The Java SDK is not supported. When you call over HTTP, place enable_code_interpreter in the parameters object. |
clear_thinking boolean (Optional) The default value is `false`. Controls whether to use the reasoning_content (thinking process) from previous turns as context input for the model in a multi-turn conversation. This is supported only by the GLM series models glm-5.2, glm-5.1, glm-5, and glm-4.7. true: Enables the feature. This ignores the reasoning_content from previous turns and uses only visible text, tool calls, and results as context input. This can reduce context length and cost.
false (default): Disables the feature. This 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 its original order in the messages. Missing, trimming, rewriting, or reordering degrades performance or prevents the feature from taking effect.
|
repetition_penalty float (Optional) The penalty for repeating consecutive sequences during model generation. A higher `repetition_penalty` value can reduce repetition in the model's output. A value of 1.0 indicates no penalty. The value must be greater than 0. In the Java SDK, this parameter is repetitionPenalty. When you call over HTTP, place repetition_penalty in the parameters object. When you use the qwen-vl-plus_2025-01-25 model for text extraction, we recommend that you set `repetition_penalty` to 1.0. We do not recommend that you 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. The Java SDK does not support setting this parameter. When you call over HTTP, place presence_penalty in the parameters object. |
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.
In the Java SDK, this parameter is vlHighResolutionImages (requires V2.20.8 or later). When you call over HTTP, place vl_high_resolution_images in the parameters object. |
vl_enable_image_hw_output boolean (Optional) The default value is false. Specifies whether to return the dimensions of the scaled image. The model scales the input image. If you set this parameter to `True`, it returns the height and width of the scaled image. If streaming output is enabled, this information is returned in the last chunk. This is supported by Qwen-VL models. In the Java SDK, this parameter is vlEnableImageHwOutput. The minimum required Java SDK version is 2.20.8. When you call over HTTP, place vl_enable_image_hw_output in the parameters object. |
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. In the Java SDK, this parameter is maxTokens. For Qwen-VL models, it is maxLength in the Java SDK, but versions later than 2.18.4 also support setting it as `maxTokens`. When you call over HTTP, place max_tokens in the parameters object. |
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. The Java SDK does not currently support this parameter. When you call over HTTP, place max_completion_tokens in the parameters object. |
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]. When you call over HTTP, place seed in the parameters object. |
stream boolean (Optional) The default value is false. Specifies whether to stream the reply. The valid values are: false: The model generates all content and then returns the result at once. true: The model generates and outputs content on the fly. This means that the model immediately outputs a chunk of content as soon as it is generated.
This parameter is supported only by the Python SDK. To implement streaming output with the Java SDK, call the streamCall interface. To implement streaming output over HTTP, specify X-DashScope-SSE as enable in the header. Qwen3 commercial edition (thinking mode), Qwen3 open source edition, QwQ, and QVQ support only streaming output. |
incremental_output boolean (Optional) The default is false. For Qwen3-Max, Qwen3-VL, Qwen3 open source edition, QwQ, and QVQ models, the default is true. Specifies whether to enable incremental output in streaming output mode. We recommend that you set this parameter to true. Value: false: Each output contains the entire sequence that is generated so far. The last output is the complete generated result. I
I like
I like apple
I like apple.
true (recommended): The output is incremental. Subsequent output does not include previously output content. You must read these chunks one by one in real time to obtain the complete result. I
like
apple
.
In the Java SDK, this parameter is incrementalOutput. When you call over HTTP, place incremental_output in the parameters object. QwQ models and Qwen3 models in thinking mode support only setting this parameter to true. Because the default value for Qwen3 commercial edition models is false, you must manually set it to true in thinking mode. Qwen3 open source edition models do not support setting this parameter to false. |
response_format object (Optional) The default value is {"type": "text"}. The format of the returned content. The valid values are: For more information, see Structured output. For a list of supported models, see Supported models. 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. In the Java SDK, this parameter is `responseFormat`. When you call over HTTP, place response_format in the parameters object. Properties type string (Required) The format of the returned content. The valid values are: |
result_format string (Optional) The default is text. For Qwen3-Max, Qwen3-VL, QwQ models, Qwen3 open source models (except qwen3-next-80b-a3b-instruct), the default is `message`. The format of the returned data. We recommend that you set this parameter to message to facilitate multi-turn conversations. The platform will later unify the default value to message. In the Java SDK, this parameter is resultFormat. When you call over HTTP, place result_format in the parameters object. If the model is Qwen-VL, QVQ, setting the value to text has no effect. Qwen3-Max, Qwen3-VL, and Qwen3 models in thinking mode can only be set to message. Because the default value for Qwen3 commercial edition models is text, you need to set it to message. If you use the Java SDK to call a Qwen3 open source model and pass text, the response is still returned in message format. |
logprobs boolean (Optional) The default value is false. Specifies whether to return the log probabilities of the output tokens. The valid values are: true
Back false
You cannot return.
The following models are supported: Snapshot models of the qwen-plus series (excluding stable edition models) Snapshot models of the qwen-turbo series (excluding stable edition models) qwen3-vl-plus series (including stable edition models) qwen3-vl-flash series (including stable edition models) Qwen3 open source models
When you call over HTTP, place logprobs in the parameters object. |
top_logprobs integer (Optional) The default value is 0. Specifies the number of most likely candidate tokens to return at each generation step. Value range: [0, 5] This parameter takes effect only if logprobs is true. In the Java SDK, this parameter is topLogprobs. When you call over HTTP, place top_logprobs in the parameters object. |
n integer (Optional) The default value is 1. The number of responses to generate. The value range is 1-4. For scenarios that require multiple responses to be generated, such as creative writing or ad copy, you can set a larger `n` value. Currently, only Qwen3 (non-thinking mode) models are supported. The value is fixed at 1 if the `tools` parameter is passed. Setting a larger `n` value does not increase input token consumption but does increase output token consumption. When you call over HTTP, place n in the parameters object. |
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]. When you call over HTTP, place stop in the parameters object. |
tools array (Optional) An array that contains one or more tool objects for the model to call during function calling. For more information, see Function Calling. When you use tools, you must set result_format to message. When you initiate function calling or submit tool execution results, you must set the tools parameter. Properties type string (Required) The tool type. Currently, only function is supported. function object (Required) Properties name string (Required) The name of the tool function. It must consist of letters and numbers, and can contain underscores and hyphens. The maximum length is 64 characters. description string (Required) A description of the tool function, which helps the model to choose when and how to call the tool function. parameters object (Optional) The default value is {}. A description of the tool's parameters, which needs to be a valid JSON Schema. For a description of JSON Schema, see this link. If the parameters parameter is empty, it means 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. When you call over HTTP, place tools in the parameters object. This is temporarily not supported for qwen-vl series models. |
tool_choice string or object (Optional) The default value is auto. The tool selection strategy. You can set this parameter to force a tool call method for a specific type of problem, such as always using a certain tool or disabling all tools. auto
The LLM chooses the tool strategy autonomously. none
If you want to temporarily disable tool calls in a specific request, you can set the tool_choice parameter to none. {"type": "function", "function": {"name": "the_function_to_call"}}
If you want to force a call to a specific tool, 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. Models in thinking mode do not support forcing a call to a specific tool.
In the Java SDK, this parameter is toolChoice. When you call over HTTP, place tool_choice in the parameters object. |
parallel_tool_calls boolean (Optional) The default value is false. Specifies whether to enable parallel tool calls. Valid values: true: Enabled
false: Disabled.
For more information about parallel tool calls, see Parallel tool calls. In the Java SDK, this parameter is parallelToolCalls. When you call over HTTP, place parallel_tool_calls in the parameters object. |