Tous les produits
Search
Centre de documentation

Alibaba Cloud Model Studio:Overview

Dernière mise à jour :Sep 07, 2026

Un modèle de génération de texte produit du contenu à partir d'invites en langage naturel pour des applications telles que les chatbots, la création de contenu, la synthèse de documents et la génération de code.

L'entrée peut varier d'un simple mot-clé à des invites complexes et contextuelles en plusieurs étapes. Voici quelques cas d'utilisation courants :

  • Création de contenu : Générez des articles d'actualité, des descriptions de produits et des scripts pour vidéos courtes.
  • Service client : Développez des chatbots automatisés disponibles 24h/24 et 7j/7 pour répondre aux questions fréquentes.
  • Traduction de texte : Traduisez du texte entre plusieurs langues.
  • Synthèse : Résumez des articles longs, des rapports et des e-mails.
  • Rédaction de documents juridiques : Élaborez des modèles de contrats et des avis juridiques.

Concepts clés

L'entrée d'un modèle de génération de texte est une invite, composée d'un ou plusieurs objets message contenant chacun un rôle et un contenu :

  • Message système : Définit la personnalité du modèle, les lignes directrices comportementales ou les instructions spécifiques à la tâche. La valeur par défaut est « You are a helpful assistant. » (Vous êtes un assistant utile).
  • Message utilisateur : La question, l'instruction ou l'entrée fournie par l'utilisateur au modèle.
  • Message assistant : La réponse du modèle. Dans le cadre d'une conversation multi-tours, transmettez les messages historiques de l'assistant pour maintenir le contexte.

Pour appeler le modèle, construisez un tableau de ces objets message nommé messages. Une requête typique comprend un message system qui définit les lignes directrices comportementales et un message user contenant l'entrée de l'utilisateur.

Le message system est facultatif mais recommandé. Définir le rôle du modèle et ses contraintes comportementales permet d'obtenir des résultats plus cohérents et prévisibles.

[
    {"role": "system", "content": "You are a helpful assistant who provides precise, efficient, and insightful responses, ready to assist users with various tasks and questions."},
    {"role": "user", "content": "Who are you?"}
]

La réponse contient la réplique du modèle dans un message assistant.

{
    "role": "assistant",
    "content": "Hello! I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you with tasks like answering questions, creating text, logical reasoning, and coding. I understand and generate multiple languages, and can handle multi-turn conversations and complex instructions. If there is anything you need help with, just let me know!"
}

Démarrage rapide

Prérequis : Obtenir une clé API et Configurer la clé API comme variable d'environnement. Si vous utilisez un SDK, installez également le SDK OpenAI ou DashScope. Le paramètre {WorkspaceId} dans les URL de base de l'exemple correspond à votre ID d'espace de travail. Pour savoir comment l'obtenir, consultez Régions et domaines d'accès.

API Chat Completions compatible avec OpenAI

Python

import os
from openai import OpenAI

try:
    client = OpenAI(
        # API keys vary by region. To obtain an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
        # If you haven't set the environment variable, replace the following line with your Alibaba Cloud Model Studio API key: api_key="sk-xxx",
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # Endpoint for the Asia Pacific SE 1 (Singapore) region. Replace {WorkspaceId} with your Workspace ID. URLs vary by region.
        base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
    )

    completion = client.chat.completions.create(
        model="qwen3.8-max",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": "Who are you?"},
        ],
    )
    print(completion.choices[0].message.content)
    # To view the full response, uncomment the following line.
    # print(completion.model_dump_json())
except Exception as e:
    print(f"Error message: {e}")
    print("For more information, see the documentation: https://www.alibabacloud.com/help/en/model-studio/error-code")

Réponse

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!

Java

// We recommend using OpenAI Java SDK v3.5.0 or later.
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) {
        try {
            OpenAIClient client = OpenAIOkHttpClient.builder()
                    // API keys vary by region. To obtain an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
                    // If you haven't set the environment variable, replace the following line with your Alibaba Cloud Model Studio API key: .apiKey("sk-xxx")
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    // Endpoint for the Asia Pacific SE 1 (Singapore) region. Replace {WorkspaceId} with your Workspace ID. URLs vary by region.
                    .baseUrl("https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1")
                    .build();

            // Create ChatCompletion parameters.
            ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
                    .model("qwen3.8-max")
                    .addSystemMessage("You are a helpful assistant.")
                    .addUserMessage("Who are you?")
                    .build();

            // Send the request and receive the response.
            ChatCompletion chatCompletion = client.chat().completions().create(params);
            String content = chatCompletion.choices().get(0).message().content().orElse("No valid content returned");
            System.out.println(content);

        } catch (Exception e) {
            System.err.println("Error message: " + e.getMessage());
            System.out.println("For more information, see the documentation: https://www.alibabacloud.com/help/en/model-studio/error-code");
        }
    }
}

Réponse

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!

Node.js

// This code requires Node.js v18+ and must be run in an ES Module environment.
import OpenAI from "openai";

const openai = new OpenAI(
    {
        // API keys vary by region. To obtain an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
        // If you haven't set the environment variable, replace the following line with your Alibaba Cloud Model Studio API key: apiKey: "sk-xxx",
        apiKey: process.env.DASHSCOPE_API_KEY,
        // Endpoint for the Asia Pacific SE 1 (Singapore) region. Replace {WorkspaceId} with your Workspace ID. URLs vary by region.
        baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"

    }
);
const completion = await openai.chat.completions.create({
    model: "qwen3.8-max",
    messages: [
        { role: "system", content: "You are a helpful assistant." },
        { role: "user", content: "Who are you?" }
    ],
});
console.log(completion.choices[0].message.content);
// To view the full response, uncomment the following line.
// console.log(JSON.stringify(completion, null, 4));

Réponse

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!

Go

// We recommend using OpenAI Go SDK v2.4.0 or later.
package main

import (
	"context"
	// To view the full response, uncomment the import below and the related code at the end.
	// "encoding/json"
	"fmt"
	"os"

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

func main() {
	// If you haven't set the environment variable, replace the following line with your Alibaba Cloud Model Studio API key: apiKey := "sk-xxx"
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	client := openai.NewClient(
		option.WithAPIKey(apiKey),
		// API keys vary by region. To obtain an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
		// Endpoint for the Asia Pacific SE 1 (Singapore) region. Replace {WorkspaceId} with your 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.ChatCompletionMessageParamUnion{
				openai.SystemMessage("You are a helpful assistant."),
				openai.UserMessage("Who are you?"),
			},
			Model: "qwen3.8-max",
		},
	)

	if err != nil {
		fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
		// For more information, see the documentation: https://www.alibabacloud.com/help/en/model-studio/error-code
		os.Exit(1)
	}

	if len(chatCompletion.Choices) > 0 {
		fmt.Println(chatCompletion.Choices[0].Message.Content)
	}
	// To view the full response, uncomment the following lines.
	// jsonData, _ := json.MarshalIndent(chatCompletion, "", "  ")
	// fmt.Println(string(jsonData))

}

Réponse

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!

C# (HTTP)

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

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

    static async Task Main(string[] args)
    {
        // If you haven't set the environment variable, replace the following line with your Alibaba Cloud Model Studio API key: string? apiKey = "sk-xxx";
        string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
        // Endpoint for the Asia Pacific SE 1 (Singapore) region. Replace {WorkspaceId} with your Workspace ID. URLs vary by region.
        string url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions";
        string jsonContent = @"{
            ""model"": ""qwen3.8-max"",
            ""messages"": [
                {
                    ""role"": ""system"",
                    ""content"": ""You are a helpful assistant.""
                },
                {
                    ""role"": ""user"",
                    ""content"": ""Who are you?""
                }
            ]
        }";

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

        // To view the full response, uncomment the following line.
        // Console.WriteLine(result);

        // Parse the JSON to extract and print the content.
        using JsonDocument doc = JsonDocument.Parse(result);
        JsonElement root = doc.RootElement;

        if (root.TryGetProperty("choices", out JsonElement choices) &&
            choices.GetArrayLength() > 0)
        {
            JsonElement firstChoice = choices[0];
            if (firstChoice.TryGetProperty("message", out JsonElement message) &&
                message.TryGetProperty("content", out JsonElement content))
            {
                Console.WriteLine(content.GetString());
            }
        }
    }

    private static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
    {
        using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
        {
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = await httpClient.PostAsync(url, content);
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }
            else
            {
                // For more information, see the documentation: https://www.alibabacloud.com/help/en/model-studio/error-code
                return $"Request failed: {response.StatusCode}";
            }
        }
    }
}

Réponse

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!

PHP (HTTP)

<?php
// Set the request URL.
// Endpoint for the Asia Pacific SE 1 (Singapore) region. Replace {WorkspaceId} with your Workspace ID. URLs vary by region.
$url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions';
// API keys vary by region. To obtain an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
// If you haven't set the environment variable, replace the following line with your Alibaba Cloud Model Studio API key: $apiKey = "sk-xxx";
$apiKey = getenv('DASHSCOPE_API_KEY');
// Set the request headers.
$headers = [
    'Authorization: Bearer '.$apiKey,
    'Content-Type: application/json'
];
// Set the request body.
$data = [
    "model" => "qwen3.8-max",
    "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.
// For more information, see the documentation: https://www.alibabacloud.com/help/en/model-studio/error-code
if (curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
}
// Close the cURL resource.
curl_close($ch);
// Parse and output the response content.
$dataObject = json_decode($response);
$content = $dataObject->choices[0]->message->content;
echo $content;
// To view the full response, uncomment the following line.
//echo $response;
?>

Réponse

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!

curl

Les paramètres base_url et la clé API sont spécifiques à chaque région. Consultez la rubrique OpenAI compatible - Chat pour obtenir les URL des endpoints et la rubrique Obtenir une clé API pour récupérer votre clé.

# Modify the endpoint URL for your region.
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": "qwen3.8-max",
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "Who are you?"
        }
    ]
}'

Réponse

{
    "choices": [
        {
            "message": {
                "role": "assistant",
                "content": "I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!"
            },
            "finish_reason": "stop",
            "index": 0,
            "logprobs": null
        }
    ],
    "object": "chat.completion",
    "usage": {
        "prompt_tokens": 26,
        "completion_tokens": 66,
        "total_tokens": 92
    },
    "created": 1726127645,
    "system_fingerprint": null,
    "model": "qwen3.8-max",
    "id": "chatcmpl-81951b98-28b8-9659-ab07-xxxxxx"
}

OpenAI-Compatible Responses API

L'API Responses succède à l'API Chat Completions. Pour les instructions d'utilisation, les exemples de code et les guides de migration, consultez la rubrique OpenAI-Compatible Responses.

Python

import os
from openai import OpenAI

try:
    client = OpenAI(
        # API Keys vary by region. Get your API Key at: https://www.alibabacloud.com/help/en/model-studio/get-api-key
        # If you do not set the environment variable, provide your API Key directly: api_key="sk-xxx",
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # The base URL varies by region. Update it to match your service region.
        base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
    )

    response = client.responses.create(
        model="qwen3.8-max",
        input="Briefly introduce what you can do."
    )

    print(response)
except Exception as e:
    print(f"An error occurred: {e}")
    print("For details, see the error code documentation: https://www.alibabacloud.com/help/en/model-studio/error-code")

Réponse

Champs clés de la réponse :

  • id : ID de la réponse.

  • output : Liste contenant les objets reasoning et message.

    Le champ reasoning n'apparaît que lorsque thinking est activé (activé par défaut pour la série Qwen3,6).

  • usage : Utilisation des tokens.

Exemple de contenu du message. Pour la réponse complète, consultez la section curl.

Hello! I'm an AI assistant with knowledge current as of 2026. Here's a brief overview of what I can do:

*   **Content Creation:** Write emails, articles, stories, scripts, and more.
*   **Coding & Tech:** Generate, debug, and explain code across various programming languages.
*   **Analysis & Summarization:** Process documents, interpret data, and extract key insights.
*   **Problem Solving:** Assist with math, logic, reasoning, and strategic planning.
*   **Learning & Translation:** Explain complex topics simply or translate between multiple languages.

Feel free to ask me anything or give me a task to get started!

Node.js

// Node.js v18+ is required. This code must be run in an ES Module environment.
import OpenAI from "openai";

const openai = new OpenAI({
    // API Keys vary by region. Get your API Key at: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    // If you do not set the environment variable, provide your API Key directly: apiKey: "sk-xxx",
    apiKey: process.env.DASHSCOPE_API_KEY,
    // The base URL varies by region. Update it to match your service region.
    baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
});

async function main() {
    try {
        const response = await openai.responses.create({
            model: "qwen3.8-max",
            input: "Briefly introduce what you can do."
        });

        // Get the model response
        console.log(response);
    } catch (error) {
        console.error("An error occurred:", error);
    }
}

main();

Réponse

Champs clés de la réponse :

  • id : ID de la réponse.

  • output : Liste contenant les objets reasoning et message.

    Le champ reasoning n'apparaît que lorsque thinking est activé (activé par défaut pour la série Qwen3,6).

  • usage : Utilisation des tokens.

Exemple de contenu du message. Pour la réponse complète, consultez la section curl.

Hello! I'm an AI assistant with knowledge current as of 2026. Here's a brief overview of what I can do:

*   **Content Creation:** Write emails, articles, stories, scripts, and more.
*   **Coding & Tech:** Generate, debug, and explain code across various programming languages.
*   **Analysis & Summarization:** Process documents, interpret data, and extract key insights.
*   **Problem Solving:** Assist with math, logic, reasoning, and strategic planning.
*   **Learning & Translation:** Explain complex topics simply or translate between multiple languages.

Feel free to ask me anything or give me a task to get started!

curl

# The endpoint URL varies by region. Update it to match your service region.
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen3.8-max",
    "input": "Briefly introduce what you can do.",
    "enable_thinking": true
}'

Réponse

{
    "created_at": 1772249518,
    "id": "7ad48c6b-3cc4-904f-9284-5f419c6c5xxx",
    "model": "qwen3.8-max",
    "object": "response",
    "output": [
        {
            "id": "msg_94805179-2801-45da-ac1c-a87e8ea20xxx",
            "summary": [
                {
                    "text": "The user is asking for a brief introduction of my capabilities. I will start by recalling the features listed in the system message, ensuring I cover the main points concisely.\n\nFirst, I should mention the enhanced language foundation and architectural efficiency. Next, the upgraded logical reasoning and mathematical capabilities. Visual analysis, including charts and formulas, is a key point. Autonomous agent planning and code generation are also important. Other features include human alignment optimization for better interaction, long-context handling up to 256K tokens, and multilingual support with OCR.\n\nSince the user asked for a \"brief\" overview, I need to be concise. I will group some points together and summarize each capability in a sentence or two, avoiding technical jargon where possible. I'll check the examples in the system message for a suitable structure.\n\nTo make it practical, I'll highlight how these features apply to real tasks, such as handling long documents, solving math problems, analyzing images, and writing code.\n\nI will structure the response as a list of key capabilities with short explanations, starting with a greeting and ending with an offer to help with specific tasks.\n\nMy introduction will identify me as the requested model, qwen3.7-max.\n\nI will not mention the knowledge cutoff unless it's relevant. Since the current date is 2026 and my knowledge is current as of 2026, this is not an issue.\n\nMy draft will be a concise, friendly, and inviting response that highlights each capability.\n",
                    "type": "summary_text"
                }
            ],
            "type": "reasoning"
        },
        {
            "content": [
                {
                    "annotations": [],
                    "text": "I'm **Qwen3.6-plus**, a large language model designed to assist with a wide range of tasks. Here's what I can do:  \n\n- **Understand & Generate Text**: Handle complex instructions, creative writing, and multi-step tasks with improved accuracy.  \n- **Solve Problems**: Tackle advanced math, logic puzzles, and scientific reasoning with step-by-step clarity.  \n- **Analyze Visuals**: Interpret charts, diagrams, formulas, and even extract text from images (OCR).  \n- **Plan & Execute**: Break down goals into actionable steps, run code, or interact with tools autonomously.  \n- **Code & Debug**: Write, explain, or fix code in multiple programming languages.  \n- **Long-Context Mastery**: Process documents, books, or videos up to **256K tokens** without losing key details.  \n- **Multilingual Support**: Communicate fluently in **100+ languages**, including low-resource ones.  \n\nNeed help with something specific? Just ask!",
                    "type": "output_text"
                }
            ],
            "id": "msg_35be06c6-ca4d-4f2b-9677-7897e488dxxx",
            "role": "assistant",
            "status": "completed",
            "type": "message"
        }
    ],
    "parallel_tool_calls": false,
    "status": "completed",
    "tool_choice": "auto",
    "tools": [],
    "usage": {
        "input_tokens": 54,
        "input_tokens_details": {
            "cached_tokens": 0
        },
        "output_tokens": 662,
        "output_tokens_details": {
            "reasoning_tokens": 447
        },
        "total_tokens": 716,
        "x_details": [
            {
                "input_tokens": 54,
                "output_tokens": 662,
                "output_tokens_details": {
                    "reasoning_tokens": 447
                },
                "total_tokens": 716,
                "x_billing_type": "response_api"
            }
        ]
    }
}

DashScope

ImportantLes modèles qwen3,7-max, qwen3,7-max-2026-05-20 et qwen3.6-max-preview prennent uniquement en charge l'API texte. Les modèles qwen3.8-max et qwen3.7-max-2026-06-08 prennent en charge l'API multimodale. Les séries Qwen3.6 et Qwen3.5 nécessitent l'API DashScope multimodale. L'exécution des exemples suivants avec ces modèles renvoie une erreur url error. Pour effectuer un appel correct à l'API multimodale, consultez la section Traitement des données image et vidéo.

Python

import json
import os
from dashscope import Generation
import dashscope

# The following URL is for the Singapore region. Replace {WorkspaceId} with your Workspace ID. URLs vary by 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."},
    {"role": "user", "content": "Who are you?"},
]
response = Generation.call(
    # API keys vary by region. To get an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
    # If you have not set the environment variable, replace the following line with your Model Studio API key: api_key = "sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # qwen3.7-max, qwen3.7-max-2026-05-20, and qwen3.6-max-preview only support the text API. qwen3.8-max and qwen3.7-max-2026-06-08 support the multimodal API. Qwen3.6 and Qwen3.5 series require the multimodal API. Directly replacing the model will cause an error.
    model="qwen-plus",
    messages=messages,
    result_format="message",
)

if response.status_code == 200:
    print(response.output.choices[0].message.content)
    # To view the full response, uncomment the following line.
    # print(json.dumps(response, default=lambda o: o.__dict__, indent=4))
else:
    print(f"HTTP status code: {response.status_code}")
    print(f"Error code: {response.code}")
    print(f"Error message: {response.message}")
    print("For more information, see: https://www.alibabacloud.com/help/en/model-studio/error-code")

Réponse

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!

Java

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.protocol.Protocol;
import com.alibaba.dashscope.utils.JsonUtils;

public class Main {
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        // The following URL is for the Singapore region. Replace {WorkspaceId} with your Workspace ID. URLs vary by region.
        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()
                // API keys vary by region. To get an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
                // If you have not set the environment variable, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // qwen3.7-max, qwen3.7-max-2026-05-20, and qwen3.6-max-preview only support the text API. qwen3.8-max and qwen3.7-max-2026-06-08 support the multimodal API. Qwen3.6 and Qwen3.5 series require the multimodal API. Directly replacing the model will cause an error.
                .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(result.getOutput().getChoices().get(0).getMessage().getContent());
            // To view the full response, uncomment the following line.
            // System.out.println(JsonUtils.toJson(result));
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.err.println("Error message: "+e.getMessage());
            System.out.println("For more information, see: https://www.alibabacloud.com/help/en/model-studio/error-code");
        }
    }
}

Réponse

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!

Node.js (HTTP)

// Requires Node.js v18+
// If you have not set the environment variable, replace the following line with your Model Studio API key: const apiKey = "sk-xxx";
const apiKey = process.env.DASHSCOPE_API_KEY;

const data = {
    // qwen3.7-max, qwen3.7-max-2026-05-20, and qwen3.6-max-preview only support the text API. qwen3.8-max and qwen3.7-max-2026-06-08 support the multimodal API. Qwen3.6 and Qwen3.5 series require the multimodal API. Directly replacing the model will cause an error.
    model: "qwen-plus",
    input: {
        messages: [
            {
                role: "system",
                content: "You are a helpful assistant."
            },
            {
                role: "user",
                content: "Who are you?"
            }
        ]
    },
    parameters: {
        result_format: "message"
    }
};

async function callApi() {
    try {
            // The following URL is for the Singapore region. Replace {WorkspaceId} with your Workspace ID. URLs vary by region.
            const response = await 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)
        });

        const result = await response.json();
        console.log(result.output.choices[0].message.content);
        // To view the full response, uncomment the following line.
        // console.log(JSON.stringify(result));
    } catch (error) {
        // For more information, see: https://www.alibabacloud.com/help/en/model-studio/error-code
        console.error('Request failed:', error.message);
    }
}

callApi();

Réponse

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!

Go (HTTP)

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
)

func main() {
	requestBody := map[string]interface{}{
		// qwen3.7-max, qwen3.7-max-2026-05-20, and qwen3.6-max-preview only support the text API. qwen3.8-max and qwen3.7-max-2026-06-08 support the multimodal API. Qwen3.6 and Qwen3.5 series require the multimodal API. Directly replacing the model will cause an error.
		"model": "qwen-plus",
		"input": map[string]interface{}{
			"messages": []map[string]string{
				{
					"role":    "system",
					"content": "You are a helpful assistant.",
				},
				{
					"role":    "user",
					"content": "Who are you?",
				},
			},
		},
		"parameters": map[string]string{
			"result_format": "message",
		},
	}

	// Serialize to JSON.
	jsonData, _ := json.Marshal(requestBody)

	// Create an HTTP client and request.
	client := &http.Client{}
	// The following URL is for the Singapore region. Replace {WorkspaceId} with your Workspace ID. URLs vary by region.
	req, _ := http.NewRequest("POST", "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation", bytes.NewBuffer(jsonData))

	// Set request headers.
	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, _ := io.ReadAll(resp.Body)

	// Parse the JSON and print the content.
	var result map[string]interface{}
	json.Unmarshal(bodyText, &result)
	content := result["output"].(map[string]interface{})["choices"].([]interface{})[0].(map[string]interface{})["message"].(map[string]interface{})["content"].(string)
	fmt.Println(content)

	// To view the full response, uncomment the following line.
	// fmt.Printf("%s\n", bodyText)
}

Réponse

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!

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)
    {
        // API keys vary by region. To get an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
        // If you have not set the environment variable, replace the following line with your Model Studio API key: string? apiKey = "sk-xxx";
        string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
        // Set the request URL and content.
        // The following URL is for the Singapore region. Replace {WorkspaceId} with your Workspace ID. URLs vary by region.
        string url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
        // qwen3.7-max, qwen3.7-max-2026-05-20, and qwen3.6-max-preview only support the text API. qwen3.8-max and qwen3.7-max-2026-06-08 support the multimodal API. Qwen3.6 and Qwen3.5 series require the multimodal API. Directly replacing the model will cause an error.
        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);
        var jsonResult = System.Text.Json.JsonDocument.Parse(result);
        var content = jsonResult.RootElement.GetProperty("output").GetProperty("choices")[0].GetProperty("message").GetProperty("content").GetString();
        Console.WriteLine(content);
        // To view the full response, uncomment the following line.
        // 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);

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

Réponse

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": "I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!"
                }
            }
        ]
    },
    "usage": {
        "total_tokens": 92,
        "output_tokens": 66,
        "input_tokens": 26
    },
    "request_id": "09dceb20-ae2e-999b-85f9-xxxxxx"
}

PHP (HTTP)

<?php
// The following URL is for the Singapore region. Replace {WorkspaceId} with your Workspace ID. URLs vary by region.
$url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// To get an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
$apiKey = getenv('DASHSCOPE_API_KEY');

$data = [
    // qwen3.7-max, qwen3.7-max-2026-05-20, and qwen3.6-max-preview only support the text API. qwen3.8-max and qwen3.7-max-2026-06-08 support the multimodal API. Qwen3.6 and Qwen3.5 series require the multimodal API. Directly replacing the model will cause an error.
    "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_HTTPHEADER, [
    "Authorization: Bearer $apiKey",
    "Content-Type: application/json"
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($httpCode == 200) {
    $jsonResult = json_decode($response, true);
    $content = $jsonResult['output']['choices'][0]['message']['content'];
    echo $content;
    // To view the full response, uncomment the following line.
    // echo "Model response: " . $response;
} else {
    echo "Request failed: " . $httpCode . " - " . $response;
}

curl_close($ch);
?>

Réponse

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!

curl

L'URL de base et la clé API varient selon la région. Pour plus de détails, consultez les rubriques DashScope et Obtenir une clé API.

# The following URL is for the Singapore region. Replace {WorkspaceId} with your Workspace ID. URLs vary by 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": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "user",
                "content": "Who are you?"
            }
        ]
    },
    "parameters": {
        "result_format": "message"
    }
}'

Réponse

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": "I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!"
                }
            }
        ]
    },
    "usage": {
        "total_tokens": 92,
        "output_tokens": 66,
        "input_tokens": 26
    },
    "request_id": "09dceb20-ae2e-999b-85f9-xxxxxx"
}

Traitement des données d'image et vidéo

Les modèles multimodaux traitent les données non textuelles (images, vidéos) pour des tâches telles que la réponse aux questions visuelles et la détection d'événements. Ils diffèrent des modèles textuels sur deux points :

  • Construction du message utilisateur : Les messages utilisateur multimodaux incluent du texte et des données non textuelles, telles que des images et de l'audio.
  • Interfaces du SDK DashScope : Utilisez l'interface MultiModalConversation pour le SDK Python DashScope, et la classe MultiModalConversation pour le SDK Java DashScope.

Pour connaître les limitations relatives aux fichiers image et vidéo, consultez la rubrique Compréhension des images et des vidéos .

Complétions de chat compatibles avec OpenAI

Python

from openai import OpenAI
import os

client = OpenAI(
    # API keys vary by region. To get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    # If the environment variable is not set, provide your Model Studio API key directly, for example: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The endpoint URL varies by region. Modify it for your region.
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
)
messages = [
    {
        "role": "user",
        "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"
                    },
                },
            {"type": "text", "text": "What products are shown in the image?"},
        ],
    }
]
completion = client.chat.completions.create(
    model="qwen3.6-plus",
    messages=messages,
)
print(completion.choices[0].message.content)
from openai import OpenAI
import os

client = OpenAI(
    # API keys vary by region. To get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    # If the environment variable is not set, provide your Model Studio API key directly, for example: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # This is the endpoint for the Singapore region. Replace {WorkspaceId} with your WorkspaceId. Endpoints vary by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)
messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image_url",
                "image_url": {
                    "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"
                },
            },
            {"type": "text", "text": "What products are shown in the image?"},
        ],
    }
]
completion = client.chat.completions.create(
    model="qwen3.6-plus",
    messages=messages,
)
print(completion.choices[0].message.content)

Node.js

import OpenAI from "openai";

const openai = new OpenAI(
    {
        // API keys vary by region. To get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
        // If the environment variable is not set, provide your Model Studio API key directly, for example: apiKey: "sk-xxx",
        apiKey: process.env.DASHSCOPE_API_KEY,
        // The endpoint URL varies by region. Modify it for your region.
        baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
    }
);

let messages = [
    {
        role: "user",
        content: [
            { type: "image_url", image_url: { "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png" } },
            { type: "text", text: "What products are shown in the image?" },
        ]
    }]
async function main() {
    let response = await openai.chat.completions.create({
        model: "qwen3.6-plus",
        messages: messages
    });
    console.log(response.choices[0].message.content);
}

main()
import OpenAI from "openai";

const openai = new OpenAI(
    {
        // API keys vary by region. To get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
        // If the environment variable is not set, provide your Model Studio API key directly, for example: apiKey: "sk-xxx",
        apiKey: process.env.DASHSCOPE_API_KEY,
        // This is the endpoint for the Singapore region. Replace {WorkspaceId} with your WorkspaceId. Endpoints vary by region.
        baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
    }
);

let messages = [
    {
        role: "user",
        content: [
            { type: "image_url", image_url: { "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png" } },
            { type: "text", text: "What products are shown in the image?" },
        ]
    }]
async function main() {
    let response = await openai.chat.completions.create({
        model: "qwen3.6-plus",
        messages: messages
    });
    console.log(response.choices[0].message.content);
}

main()

curl

L'URL de base et la clé API sont spécifiques à la région. Consultez la rubrique Chat compatible avec OpenAI pour obtenir les URL des endpoints, ainsi que la rubrique Obtenir une clé API pour récupérer votre clé.

# The endpoint URL varies by region. Modify it for your region.
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
  "model": "qwen3.6-plus",
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "image_url",
          "image_url": {
            "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"
          }
        },
        {
          "type": "text",
          "text": "What products are shown in the image?"
        }
      ]
    }
  ]
}'
# This is the endpoint for the Singapore region. Replace {WorkspaceId} with your WorkspaceId. Endpoints vary by region.
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": "qwen3.6-plus",
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "image_url",
          "image_url": {
            "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"
          }
        },
        {
          "type": "text",
          "text": "What products are shown in the image?"
        }
      ]
    }
  ]
}'

DashScope

Python

import os
import dashscope
from dashscope import MultiModalConversation

# This is the endpoint for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. Endpoints vary by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"

messages = [
    {
        "role": "user",
        "content": [
            {
                "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"
            },
            {"text": "What products are shown in the image?"},
        ],
    }
]
response = MultiModalConversation.call(
    # API keys vary by region. To get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    # If the environment variable is not set, provide your Model Studio API key directly, for example: api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model='qwen3.6-plus',   # You can replace this with another multimodal model and modify the messages accordingly.
    messages=messages)
print(response.output.choices[0].message.content[0]['text'])
import os
from dashscope import MultiModalConversation
import dashscope
# This is the endpoint for the Singapore region. Replace {WorkspaceId} with your WorkspaceId. Endpoints vary by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

messages = [
    {
        "role": "user",
        "content": [
            {
                "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"
            },
            {"text": "What products are shown in the image?"},
        ],
    }
]
response = MultiModalConversation.call(
    # API keys vary by region. To get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    # If the environment variable is not set, provide your Model Studio API key directly, for example: api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model='qwen3.6-plus',  # You can replace this with another multimodal model and modify the messages accordingly.
    messages=messages
)

print(response.output.choices[0].message.content[0]['text'])

Java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

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 {
    // This is the endpoint for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. Endpoints vary by region.
    static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";}

    private static final String modelName = "qwen3.6-plus";  // You can replace this with another multimodal model and modify the messages accordingly.

    public static void MultiRoundConversationCall() throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(Collections.singletonMap("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"),
                        Collections.singletonMap("text", "What products are shown in the image?"))).build();
        List<MultiModalMessage> messages = new ArrayList<>();
        messages.add(userMessage);
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // API keys vary by region. To get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
                // If the environment variable is not set, provide your Model Studio API key directly, for example: .apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model(modelName)
                .messages(messages)
                .build();
        MultiModalConversationResult result = conv.call(param);
        System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
    }

    public static void main(String[] args) {
        try {
            MultiRoundConversationCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

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 {
        // This is the endpoint for the Singapore region. Replace {WorkspaceId} with your WorkspaceId. Endpoints vary by region.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    private static final String modelName = "qwen3.6-plus";  // You can replace this with another multimodal model and modify the messages accordingly.

    public static void MultiRoundConversationCall() throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(Collections.singletonMap("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"),
                        Collections.singletonMap("text", "What products are shown in the image?"))).build();
        List<MultiModalMessage> messages = new ArrayList<>();
        messages.add(userMessage);
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // API keys vary by region. To get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
                // If the environment variable is not set, provide your Model Studio API key directly, for example: .apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model(modelName)
                .messages(messages)
                .build();
        MultiModalConversationResult result = conv.call(param);
        System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
    }

    public static void main(String[] args) {
        try {
            MultiRoundConversationCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}

curl

L'URL de base et la clé API varient selon la région. Pour plus de détails, consultez les rubriques DashScope et Obtenir une clé API.

# The endpoint URL varies by region. Modify it for your region.
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
    "model": "qwen3.6-plus",
    "input":{
        "messages":[
            {
                "role": "user",
                "content": [
                    {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"},
                    {"text": "What products are shown in the image?"}
                ]
            }
        ]
    }
}'
# This is the endpoint for the Singapore region. Replace {WorkspaceId} with your WorkspaceId. Endpoints vary by region.
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": "qwen3.6-plus",
    "input":{
        "messages":[
            {
                "role": "user",
                "content": [
                    {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"},
                    {"text": "What products are shown in the image?"}
                ]
            }
        ]
    }
}'

Appels asynchrones

Les appels asynchrones améliorent le débit pour les charges de travail à forte concurrence.

OpenAI-compatible chat completions API

import os
import asyncio
from openai import AsyncOpenAI
import platform

# Create an asynchronous client instance.
client = AsyncOpenAI(
    # API keys vary by region. To get an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
    # If you have not set the environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # This is the URL for the Singapore region. Replace {WorkspaceId} with your workspace ID.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)

# Define an asynchronous task.
async def task(question):
    print(f"Sending question: {question}")
    response = await client.chat.completions.create(
        messages=[
            {"role": "user", "content": question}
        ],
        model="qwen-plus",  # For a list of models, see https://www.alibabacloud.com/help/en/model-studio/getting-started/models
    )
    print(f"Model response: {response.choices[0].message.content}")

# Main asynchronous function.
async def main():
    questions = ["Who are you?", "What can you do?", "What's the weather like?"]
    tasks = [task(q) for q in questions]
    await asyncio.gather(*tasks)

if __name__ == '__main__':
    # Set the event loop policy.
    if platform.system() == 'Windows':
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    # Run the main coroutine.
    asyncio.run(main(), debug=False)
import com.openai.client.OpenAIClientAsync;
import com.openai.client.okhttp.OpenAIOkHttpClientAsync;
import com.openai.models.chat.completions.ChatCompletionCreateParams;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;

public class Main {
    public static void main(String[] args) {
        // Create an OpenAI client to connect to the DashScope-compatible endpoint.
        OpenAIClientAsync client = OpenAIOkHttpClientAsync.builder()
                // API keys vary by region. To get an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
                // If you have not set the environment variable, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // This is the URL for the Singapore region. Replace {WorkspaceId} with your workspace ID.
                .baseUrl("https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1")
                .build();

        // Define a list of questions.
        List<String> questions = Arrays.asList("Who are you?", "What can you do?", "What's the weather like?");

        // Create a list of asynchronous tasks.
        CompletableFuture<?>[] futures = questions.stream()
                .map(question -> CompletableFuture.supplyAsync(() -> {
                    System.out.println("Sending question: " + question);
                    // Create ChatCompletion parameters.
                    ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
                            .model("qwen-plus")  // Specify the model.
                            .addSystemMessage("You are a helpful assistant.")
                            .addUserMessage(question)
                            .build();

                    // Send an asynchronous request and handle the response.
                    return client.chat().completions().create(params)
                        .thenAccept(chatCompletion -> {
                            String content = chatCompletion.choices().get(0).message().content().orElse("No content in response");
                            System.out.println("Model response: " + content);
                        })
                        .exceptionally(e -> {
                            System.err.println("Error: " + e.getMessage());
                            System.out.println("See the documentation: https://www.alibabacloud.com/help/en/model-studio/error-code");
                            return null;
                        });
                }).thenCompose(future -> future))
                .toArray(CompletableFuture[]::new);

        // Wait for all asynchronous operations to complete.
        CompletableFuture.allOf(futures).join();
    }
}

DashScope

La génération de texte asynchrone avec le SDK DashScope n'est prise en charge qu'en Python.

# This requires DashScope Python SDK v1.19.0 or later.
import asyncio
import platform
from dashscope.aigc.generation import AioGeneration
import os
import dashscope
# This is the URL for the Singapore region. Replace {WorkspaceId} with your workspace ID.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

# Define an asynchronous task.
async def task(question):
    print(f"Sending question: {question}")
    response = await AioGeneration.call(
        # If you have not set the environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx",
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        model="qwen-plus",  # For a list of models, see https://www.alibabacloud.com/help/en/model-studio/models
        messages=[{"role": "system", "content": "You are a helpful assistant."},
                  {"role": "user", "content": question}],
        result_format="message",
    )
    print(f"Model response: {response.output.choices[0].message.content}")

# Main asynchronous function.
async def main():
    questions = ["Who are you?", "What can you do?", "What's the weather like?"]
    tasks = [task(q) for q in questions]
    await asyncio.gather(*tasks)

if __name__ == '__main__':
    # Set the event loop policy.
    if platform.system() == 'Windows':
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    # Run the main coroutine.
    asyncio.run(main(), debug=False)
Exemple de réponse

Étant donné que les appels sont asynchrones, l'ordre des réponses peut différer de cet exemple.

Sending question: Who are you?
Sending question: What can you do?
Sending question: What's the weather like?
Model response: Hello! I'm Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, programming, share opinions, play games, and more. If you have any questions or need help, feel free to ask!
Model response: Hello! I am currently unable to access real-time weather information. You can tell me your city or region, and I will do my best to provide you with general weather advice or information. Alternatively, you can use a weather app to check the real-time weather conditions.
Model response: I have many skills, for example:

1. Answering questions: Whether it's academic questions, general knowledge, or professional topics, I can try to help you find answers.
2. Creating text: I can write various types of text, such as stories, official documents, emails, and scripts.
3. Logical reasoning: I can help you solve logical reasoning problems, such as math problems and riddles.
4. Programming: I can provide programming assistance, including code writing, debugging, and optimization.
5. Multilingual support: I support multiple languages, including but not limited to Chinese, English, French, and Spanish.
6. Expressing opinions: I can offer you some perspectives and suggestions to help you make decisions.
7. Playing games: We can play text-based games together, such as riddles or idiom solitaire.

If you have any specific needs or questions, feel free to let me know, and I will do my best to help you!

Utilisation en production

Création d'un contexte de haute qualité

L'injection de grandes quantités de données brutes dans un modèle augmente les coûts et peut dégrader les performances en raison des limitations de la fenêtre de contexte. L'ingénierie du contexte, qui consiste à charger dynamiquement des connaissances précises, améliore la qualité et l'efficacité de la génération. Les techniques clés incluent :

  • prompt engineering : Concevez et optimisez les invites textuelles pour guider le modèle vers la sortie souhaitée. Pour plus d'informations, consultez le Guide des invites pour la génération de texte.
  • Retrieval-Augmented Generation (RAG) : Permet au modèle de répondre aux questions à partir d'une base de connaissances externe, telle que la documentation produit ou les manuels techniques.
  • tool calling : Récupère des informations en temps réel (météo, trafic) ou effectue des actions (appels API, envoi d'e-mails) pour le compte du modèle.
  • memory : Fournit une mémoire à long et à court terme afin que le modèle puisse se rappeler le contexte lors de conversations multi-tours.

Contrôle de la diversité des réponses

Les paramètres temperature et top_p contrôlent la diversité du texte généré. Des valeurs plus élevées augmentent la diversité ; des valeurs plus faibles augmentent le déterminisme. Pour isoler l'effet de chaque paramètre, ajustez-en un seul à la fois.

  • temperature : Plage : [0, 2). Ajuste principalement l'aléatoire.
  • top_p : Plage : [0, 1]. Filtre les réponses en fonction d'un seuil de probabilité.

Les exemples suivants montrent comment les paramètres affectent la sortie. Invite d'entrée : « Écrivez une nouvelle de trois phrases dont les personnages principaux sont un chat et un rayon de soleil. »

  • Diversité élevée (Exemple : temperature=0,9) : Idéal pour l'écriture créative, le brainstorming ou la rédaction marketing.

    Sunlight slanted across the windowsill, and the orange cat crept toward the bright patch as its fur turned the color of melted honey.
    It reached out and tapped the light, then sank into it as if stepping into a warm pool, and the sunlight flowed up its back in a quiet tide.
    The afternoon grew heavy—curled in drifting gold, the cat heard time melt softly inside its purr.
    
  • Déterminisme élevé (Exemple : temperature=0,1) : Idéal pour les questions factuelles, la génération de code ou les textes juridiques.

    In the afternoon, an old cat curled on the windowsill and dozed while counting the spots of light.
    Sunlight hopped across its mottled back, like turning the pages of an old photo album.
    Dust rose and fell, as if time whispered: you were once young, and I was once fierce.
    

Fonctionnement

temperature :

  • Une température plus élevée aplatit la distribution de probabilité des tokens, rendant les tokens moins probables plus fréquents et augmentant l'aléatoire de la sortie.
  • Une température plus faible accentue la distribution, rendant les tokens à haute probabilité encore plus probables et réduisant l'aléatoire de la sortie.

top_p :

L'échantillonnage top_p (nucleus) sélectionne parmi le plus petit ensemble de tokens dont la probabilité cumulée atteint ou dépasse le seuil top_p. Les tokens sont triés par probabilité et accumulés jusqu'à ce que le seuil soit atteint, puis le token suivant est échantillonné aléatoirement dans cet ensemble réduit.

  • Un top_p plus élevé élargit le pool de sélection des tokens, produisant un texte plus diversifié.
  • Un top_p plus faible réduit le pool, produisant un texte plus ciblé et déterministe.

Exemples de paramètres pour des scénarios courants

# Recommended parameter settings for common scenarios
SCENARIO_CONFIGS = {
    # Creative writing
    "creative_writing": {
        "temperature": 0.9,
        "top_p": 0.95
    },
    # Code generation
    "code_generation": {
        "temperature": 0.2,
        "top_p": 0.8
    },
    # Factual Q&A
    "factual_qa": {
        "temperature": 0.1,
        "top_p": 0.7
    },
    # Translation
    "translation": {
        "temperature": 0.3,
        "top_p": 0.8
    }
}

# OpenAI example
# completion = client.chat.completions.create(
#     model="qwen-plus",
#     messages=[{"role": "user", "content": "Write a poem about the moon"}],
#     **SCENARIO_CONFIGS["creative_writing"]
# )
# DashScope example
# response = Generation.call(
#     # If you have not set an environment variable, replace the following line with your Alibaba Cloud Model Studio API key: api_key = "sk-xxx",
#     api_key=os.getenv("DASHSCOPE_API_KEY"),
#     model="qwen-plus",
#     messages=[{"role": "user", "content": "Write a Python function that determines whether the input n is a prime number. Output code only."}],
#     result_format="message",
#     **SCENARIO_CONFIGS["code_generation"]
# )

Autres fonctionnalités

Pour des scénarios plus complexes, les fonctionnalités suivantes sont disponibles :

  • conversation multi-tours : Pour une interaction continue, telle que les questions de suivi ou la collecte d'informations.
  • sortie en streaming : Renvoie les tokens progressivement au fur et à mesure de leur génération, évitant les délais d'expiration pour les chatbots et la génération de code en temps réel.
  • réflexion approfondie : Produit des réponses de meilleure qualité et plus structurées pour le raisonnement complexe ou l'analyse stratégique.
  • sortie structurée : Contraint les réponses à un format JSON cohérent pour une utilisation programmatique et l'analyse des données.
  • complétion par préfixe : Poursuit la génération à partir d'un texte existant, utile pour la complétion de code ou l'écriture de longs documents.

Référence API

Pour tous les paramètres, consultez la référence de l'API compatible OpenAI et la référence de l'API DashScope.

FAQ

Q : Pourquoi le nombre de tokens d'entrée est-il supérieur au nombre de tokens du texte que j'ai envoyé ?

R : Lors du traitement d'une conversation, le système utilise un modèle de chat (Chat Template) pour envelopper le texte d'entrée brut, en ajoutant des marqueurs de contrôle tels que les identifiants de rôle et les délimiteurs de message. Ces marqueurs générés par le système sont également comptés comme des tokens.

Par exemple, lorsque vous envoyez le message {"role": "user", "content": "Hi"} à qwen3.8-max, le texte « Hi » correspond à seulement 1 token après tokenisation. Cependant, lors du traitement système, le texte d'entrée complet réel est formaté comme suit : <|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n<think>. Après tokenisation, ce texte complet porte le nombre total de tokens d'entrée à 11.

Q : Pourquoi l'API Qianwen ne peut-elle pas analyser les liens de pages web ?

R : L'API Qianwen ne peut pas accéder directement au contenu des pages web. Utilisez plutôt le function calling, ou un outil de scraping web comme Beautiful Soup de Python pour extraire le contenu et le transmettre au modèle.

Q : Différences de réponse :Qianwen (Web)vs. API Qianwen

R : Qianwen (Web) ajoute des fonctionnalités par-dessus l'API Qianwen, notamment l'analyse de pages web, la recherche web, la création d'images et la génération de présentations PowerPoint. Ces fonctionnalités ne sont pas incluses dans l'API de base, mais vous pouvez construire des fonctionnalités similaires en utilisant , le function calling.

Q : Génération de fichiers Word, Excel, PDF ou PPT

R : Non. Les modèles de génération de texte ne produisent que du texte brut. Convertissez la sortie au format souhaité en utilisant votre propre code ou des bibliothèques tierces .