Make your first API call to Qwen

Updated at:

Alibaba Cloud Model Studio supports API calls to models through OpenAI-compatible interfaces and the DashScope SDK.

Note

  • If you are familiar with model API calls, you can go directly to the API reference document Text generation.
  • If you are not familiar with programming, you can use Chatbox to interact with Qwen models through a graphical interface.
  • API calls are independent of the operating system version. They work as long as your network can connect to the service.

This topic uses Qwen as an example to guide you through calling model APIs. You will learn:

  • How to get an API key
  • How to set up your local development environment
  • How to call the Qwen API

Account setup

  1. Create an account: If you do not have an Alibaba Cloud account, first create one.

    If you encounter problems, see Register an Alibaba Cloud account.

  2. Activate Alibaba Cloud Model Studio: Use your Alibaba Cloud account to go to the Alibaba Cloud Model Studio platform. After you read and agree to the agreement, Alibaba Cloud Model Studio is automatically activated. If no service agreement dialog appears, the service has already been activated.

    If the message "You have not completed identity verification" appears when you activate the service, complete identity verification first.

  3. Get an API key: Go to the API Key page and click Create API Key. You can then call models with the API key.

    You do not need to select a model when you create an API key. Specify the model to call through the model parameter in the request body, for example, model="qwen-plus". For supported models, see Model list. To limit the models that the API key can call, select the Custom permission when you create the key and turn on the Model access scope switch. After the switch is turned on, the API key can call only the selected models.

  4. Get the workspace ID: When you use models in the China (Beijing), Singapore, Japan (Tokyo), Germany (Frankfurt), or China (Hong Kong) region, you must enter the workspace ID (WorkspaceId) in the Base URL. You can view it on the Workspace Management page.

Set your API key as an environment variable

We recommend that you configure the API key as an environment variable to avoid hardcoding the API key in your code and reduce the risk of leakage.

Steps

Linux

Add a permanent environment variable

If you want the API key environment variable to take effect in all new sessions of the current user, you can add a permanent environment variable.

  1. Run the following command to append the environment variable setting to the ~/.bashrc file.
# 用您的阿里云百炼API Key代替YOUR_DASHSCOPE_API_KEY
echo "export DASHSCOPE_API_KEY='YOUR_DASHSCOPE_API_KEY'" >> ~/.bashrc

Alternatively, you can manually edit the ~/.bashrc file.

Manual modification

Run the following command to open the ~/.bashrc file.

nano ~/.bashrc

Add the following content to the configuration file.

# 用您的阿里云百炼API Key代替YOUR_DASHSCOPE_API_KEY
export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"

In the nano editor, press Ctrl+X, then Y, and then Enter to save and close the file.

  1. Run the following command to make the changes take effect.
source ~/.bashrc
  1. Reopen a terminal window and run the following command to check whether the environment variable takes effect.
echo $DASHSCOPE_API_KEY

Add a temporary environment variable

If you want to use the environment variable only in the current session, you can add a temporary environment variable.

  1. Run the following command.
# 用您的阿里云百炼API Key代替YOUR_DASHSCOPE_API_KEY
export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"
  1. Run the following command to verify that the environment variable takes effect.
echo $DASHSCOPE_API_KEY

macOS

Add a permanent environment variable

If you want the API key environment variable to take effect in all new sessions of the current user, you can add a permanent environment variable.

  1. Run the following command in the terminal to check the default shell type.
echo $SHELL
  1. Proceed based on the default shell type.

    Zsh

    1. Run the following command to append the environment variable setting to the ~/.zshrc file.
    # 用您的阿里云百炼API Key代替YOUR_DASHSCOPE_API_KEY
    echo "export DASHSCOPE_API_KEY='YOUR_DASHSCOPE_API_KEY'" >> ~/.zshrc
    

    Alternatively, you can manually edit the ~/.zshrc file.

    Manual modification

    Run the following command to open the shell configuration file.

    nano ~/.zshrc
    

    Add the following content to the configuration file.

    # 用您的阿里云百炼API Key代替YOUR_DASHSCOPE_API_KEY
    export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"
    

    In the nano editor, press Ctrl+X, then Y, and then Enter to save and close the file.

    1. Run the following command to make the changes take effect.
    source ~/.zshrc
    
    1. Reopen a terminal window and run the following command to check whether the environment variable takes effect.
    echo $DASHSCOPE_API_KEY
    

    Bash

    1. Run the following command to append the environment variable setting to the ~/.bash_profile file.
    # 用您的阿里云百炼API Key代替YOUR_DASHSCOPE_API_KEY
    echo "export DASHSCOPE_API_KEY='YOUR_DASHSCOPE_API_KEY'" >> ~/.bash_profile
    

    Alternatively, you can manually edit the ~/.bash_profile file.

    Manual modification

    Run the following command to open the shell configuration file.

    nano ~/.bash_profile
    

    Add the following content to the configuration file.

    # 用您的阿里云百炼API Key代替YOUR_DASHSCOPE_API_KEY
    export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"
    

    In the nano editor, press Ctrl+X, then Y, and then Enter to save and close the file.

    1. Run the following command to make the changes take effect.
    source ~/.bash_profile
    
    1. Reopen a terminal window and run the following command to check whether the environment variable takes effect.
    echo $DASHSCOPE_API_KEY
    

Add a temporary environment variable

If you want to use the environment variable only in the current session, you can add a temporary environment variable.

The following commands apply to Zsh and Bash.

  1. Run the following command.
# 用您的阿里云百炼API Key代替YOUR_DASHSCOPE_API_KEY
export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"
  1. Run the following command to verify that the environment variable takes effect.
echo $DASHSCOPE_API_KEY

Windows

In Windows, you can configure environment variables through System Properties, CMD, or PowerShell.

System Properties

Note

  • Environment variables configured in this way take effect permanently.
  • Modifying system environment variables requires administrator permissions.
  • After you configure an environment variable, it does not immediately affect command-line windows, IDEs, or other applications that are already running. You must restart these applications or open a new command line for the environment variable to take effect.
  1. On the Windows desktop, press Win+Q, search for Edit the system environment variables in the search box, and click to open the System Properties window.

  2. In the System Properties window, click Environment Variables, and then in the System variables section, click New. For Variable name, enter DASHSCOPE_API_KEY, and for Variable value, enter your DashScope API key.

  3. Click OK in all three windows to close the System Properties configuration page and complete the environment variable configuration.

  4. Open a Command Prompt window or a Windows PowerShell window and run the following command to check whether the environment variable takes effect.

    • CMD query command:
echo %DASHSCOPE_API_KEY%
Microsoft Windows [版本 10.0.19045.5371]
(c) Microsoft Corporation。保留所有权利。
C:\Windows\system32>echo %DASHSCOPE_API_KEY%
sk-ee166797fe40xxx
C:\Windows\system32>
  • Windows PowerShell query command:
echo $env:DASHSCOPE_API_KEY
Windows PowerShell
版权所有 (C) Microsoft Corporation。保留所有权利。
尝试新的跨平台 PowerShell https://aka.ms/pscore6
PS C:\Windows\system32> echo $env:DASHSCOPE_API_KEY
sk-ee166797fe40xxx
PS C:\Windows\system32>

CMD

Add a permanent environment variable

If you want the API key environment variable to take effect in all new sessions of the current user, follow these steps.

  1. Run the following command in CMD.
# 用您的阿里云百炼API Key代替YOUR_DASHSCOPE_API_KEY
setx DASHSCOPE_API_KEY "YOUR_DASHSCOPE_API_KEY"
  1. Open a new CMD window.
  2. Run the following command in the new CMD window to check whether the environment variable takes effect.
echo %DASHSCOPE_API_KEY%

Add a temporary environment variable

If you want to use the environment variable only in the current session, run the following command in CMD.

REM 用您的阿里云百炼API Key代替YOUR_DASHSCOPE_API_KEY
set DASHSCOPE_API_KEY=YOUR_DASHSCOPE_API_KEY

You can run the following command in the current session to check whether the environment variable takes effect.

echo %DASHSCOPE_API_KEY%

PowerShell

Add a permanent environment variable

If you want the API key environment variable to take effect in all new sessions of the current user, follow these steps.

  1. Run the following command in PowerShell.
# 用您的阿里云百炼API Key代替YOUR_DASHSCOPE_API_KEY
[Environment]::SetEnvironmentVariable("DASHSCOPE_API_KEY", "YOUR_DASHSCOPE_API_KEY", [EnvironmentVariableTarget]::User)
  1. Open a new PowerShell window.
  2. Run the following command in the new PowerShell window to check whether the environment variable takes effect.
echo $env:DASHSCOPE_API_KEY

Add a temporary environment variable

If you want to use the environment variable only in the current session, run the following command in PowerShell.

# 用您的阿里云百炼API Key代替YOUR_DASHSCOPE_API_KEY
$env:DASHSCOPE_API_KEY = "YOUR_DASHSCOPE_API_KEY"

You can run the following command in the current session to check whether the environment variable takes effect.

echo $env:DASHSCOPE_API_KEY

Choose a development language

Select a language or tool that you are familiar with to call model APIs.

Python

Step 1: Set up the Python environment

Check your Python version

Your Python must be 3.9 or later. For installation, see Install Python.

You can enter the following command in the terminal to check whether Python and pip are installed in your current computing environment:

python -V
pip --version

For example, on Windows Command Prompt:

C:\Users\Administrator>python -V
Python 3.13.2

C:\Users\Administrator>pip --version
pip 24.3.1 from C:\Users\Administrator\AppData\Local\Programs\Python\Python313\Lib\site-packages\pip (python 3.13)

FAQ

Q: The python -V and pip --version commands return the following errors:

  • 'python' 不是内部或外部命令,也不是可运行的程序或批处理文件。
  • 'pip' 不是内部或外部命令,也不是可运行的程序或批处理文件。
  • -bash: python: command not found
  • -bash: pip: command not found

The solutions are as follows:

Windows

  1. Confirm that you have installed Python in your computing environment by following Install Python, and added python.exe to the PATH environment variable.

    When installing Python 3.13.2, select Add python.exe to PATH at the bottom of the installation wizard to add Python to the system environment variables, and then click Install Now to complete the installation.

  2. If Python is installed and the environment variable is added but the error persists, close the current terminal, open a new terminal window, and try again.

Linux and macOS

  1. Confirm that Python is installed in your computing environment by following Install Python.

  2. If the error persists after Python is installed, run the which python pip command to check whether python and pip exist in the system.

    • If the following result is returned, close the current terminal, open a new terminal window, and try again.
/usr/bin/python
/usr/bin/pip
  • If the following result is returned, run which python3 pip3 again.
/usr/bin/which: no python in (/root/.local/bin:/root/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin)
/usr/bin/which: no pip in (/root/.local/bin:/root/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin)

If the following result is returned, use python3 -V and pip3 --version to check the versions.

/usr/bin/python3
/usr/bin/pip3

Set up a virtual environment (optional)

If you have completed the Python installation, you can create a virtual environment to install the OpenAI Python SDK or the DashScope Python SDK. This helps you avoid dependency conflicts with other projects.

  1. Create a virtual environment

    You can run the following command to create a virtual environment named .venv:

# 如果运行失败,您可以将python替换成python3再运行
python -m venv .venv
  1. Activate the virtual environment

    If you use Windows, run the following command to activate the virtual environment:

.venv\Scripts\activate

If you use macOS or Linux, run the following command to activate the virtual environment:

source .venv/bin/activate

Install the OpenAI Python SDK or the DashScope Python SDK

You can call models on the Alibaba Cloud Model Studio platform through the OpenAI Python SDK or the DashScope Python SDK.

Install the OpenAI Python SDK

Run the following command to install or upgrade the OpenAI Python SDK:

# 如果运行失败,您可以将pip替换成pip3再运行
pip install -U openai

When the message Successfully installed ... openai-x.x.x appears in the terminal, the OpenAI Python SDK has been installed.

Install the DashScope Python SDK

Run the following command to install or upgrade the DashScope Python SDK:

# 如果运行失败,您可以将pip替换成pip3再运行
pip install -U dashscope

When the message Successfully installed ... dashscope-x.x.x appears in the terminal, the DashScope Python SDK has been installed.

Step 2: Call the model API

OpenAI Python SDK

If you have installed Python and the OpenAI Python SDK, you can follow these steps to send your API request.

ImportantThe import os in the sample code is used to read environment variables. Do not omit it. If you use a .env file to manage the API key, import both os and dotenv:

import os
from dotenv import load_dotenv

load_dotenv()
api_key = os.getenv("DASHSCOPE_API_KEY")

Missing import os causes a NameError. Do not mistake it for a failure to load the .env file.

  1. Create a file and name it hello_qwen.py.
  2. Copy the following code into hello_qwen.py and save it.
import os
from openai import OpenAI

try:
    client = OpenAI(
        # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为: api_key="sk-xxx",
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # 以下为华北2(北京)地域的URL,各地域的URL不同。调用时请将{WorkspaceId}替换为真实的业务空间ID。
        base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
    )

    completion = client.chat.completions.create(
        model="qwen3.8-max",  # 模型列表: https://help.aliyun.com/model-studio/getting-started/models
        messages=[
            {'role': 'system', 'content': 'You are a helpful assistant.'},
            {'role': 'user', 'content': '你是谁?'}
        ]
    )
    print(completion.choices[0].message.content)
except Exception as e:
    print(f"错误信息:{e}")
    print("请参考文档:https://help.aliyun.com/model-studio/developer-reference/error-code")
  1. Run python hello_qwen.py or python3 hello_qwen.py from the command line.

    If No such file or directory is displayed, specify the specific file path before the file name.

    After the run, you will see the following output:

我是阿里云开发的一款超大规模语言模型,我叫千问。

DashScope Python SDK

If you have installed Python and the DashScope Python SDK, you can follow these steps to send your API request.

  1. Create a file and name it hello_qwen.py.
  2. Copy the following code into hello_qwen.py and save it.
import os
import dashscope
from dashscope.v2 import DashScopeError

# 以下为华北2(北京)地域的配置,各地域的region取值不同。调用时请将{WorkspaceId}替换为真实的业务空间ID。
client = dashscope.Client(
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key = "sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)
messages = [
    {'role': 'system', 'content': [{'text': 'You are a helpful assistant.'}]},
    {'role': 'user', 'content': [{'text': '你是谁?'}]}
]
try:
    response = client.multimodal.chat.create(
        model="qwen3.8-max",   # 模型列表:https://help.aliyun.com/model-studio/getting-started/models
        messages=messages,
    )
    print(response.output_text)
except DashScopeError as e:
    print(f"HTTP返回码:{e.status_code}")
    print(f"错误码:{e.code}")
    print(f"错误信息:{e.message}")
    print("请参考文档:https://help.aliyun.com/model-studio/developer-reference/error-code")
  1. Run python hello_qwen.py or python3 hello_qwen.py from the command line.

    NoteThe run command in this example must be executed in the directory where the Python file is located. To run it from any location, specify the specific file path before the file name.

    After the run, you will see the following output:

我是来自阿里云的大规模语言模型,我叫千问。

Node.js

Step 1: Set up the Node.js environment

Check the Node.js installation status

You can enter the following command in the terminal to check whether Node.js and npm are installed in your current computing environment:

node -v
npm -v

For example, on Windows Command Prompt:

C:\Users\Administrator>node -v
v22.14.0

C:\Users\Administrator>npm -v
10.9.2

This prints your current Node.js version. If Node.js is not installed in your environment, go to the Node.js official website to download it.

Install the model calling SDK

You can run the following command in the terminal:

npm install --save openai
# 或者
yarn add openai

NoteIf the installation fails, you can complete the installation by configuring a registry mirror, for example:

npm config set registry https://registry.npmmirror.com/

After you configure the registry mirror, rerun the SDK installation command.

When the message added xx package in xxs appears in the terminal, the OpenAI SDK has been installed. You can run npm list openai to check the version details.

Step 2: Call the model API

  1. Create a hello_qwen.mjs file.
  2. Copy the following code into the file.
import OpenAI from "openai";

try {
    const openai = new OpenAI(
        {
            // 若没有配置环境变量,请用阿里云百炼API Key将下行替换为: apiKey: "sk-xxx",
            apiKey: process.env.DASHSCOPE_API_KEY,
            // 以下为华北2(北京)地域的URL,各地域的URL不同。调用时请将{WorkspaceId}替换为真实的业务空间ID。
            baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
        }
    );
    const completion = await openai.chat.completions.create({
        model: "qwen3.8-max",  //模型列表: https://help.aliyun.com/model-studio/getting-started/models
        messages: [
            { role: "system", content: "You are a helpful assistant." },
            { role: "user", content: "你是谁?" }
        ],
    });
    console.log(completion.choices[0].message.content);
} catch (error) {
    console.log(`错误信息:${error}`);
    console.log("请参考文档:https://help.aliyun.com/model-studio/developer-reference/error-code");
}
  1. Run the following command from the command line to send the API request:
node hello_qwen.mjs

Note

  • The run command in this example must be executed in the directory where the hello_qwen.mjs file is located. To run it from any location, specify the specific file path before the file name.
  • Make sure the SDK is installed in the directory where the hello_qwen.mjs file is located. If the SDK and the file are not in the same directory, the error Cannot find package 'openai' imported from xxx occurs.

After the run succeeds, you will see the following output:

PS D:\node_project> node hello_qwen.mjs
(node:25072) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
我是来自阿里云的语言模型,我叫通义千问。
PS D:\node_project>

Java

Step 1: Set up the Java environment

Check your Java version

You can run the following command in the terminal:

java -version
# (可选)如果使用maven管理和构建java项目,还需确保maven已正确安装到您的开发环境中
mvn --version

For example, on Windows Command Prompt:

C:\Users\Administrator>java --version
java 23.0.2 2025-01-21
Java(TM) SE Runtime Environment (build 23.0.2+7-58)
Java HotSpot(TM) 64-Bit Server VM (build 23.0.2+7-58, mixed mode, sharing)

C:\Users\Administrator>mvn --version
Apache Maven 3.9.9 (8e8579a9e76f7d015ee5ec7bfcdc97d260186937)
Maven home: C:\Program Files\apache-maven-3.9.9
Java version: 23.0.2

To use the DashScope Java SDK, your Java must be Java 8 or later. You can check the Java version in the first line of the output. For example, the output openjdk version "16.0.1" 2021-04-20 indicates that the current Java version is Java 16. If Java is not installed in your current computing environment, or the version is earlier than Java 8, go to Java downloads to download and install it.

Install the model calling SDK

If Java is installed in your environment, install the DashScope Java SDK. For the SDK version, see DashScope Java SDK. Run the following command to add the Java SDK dependency, and replace the-latest-version with the latest version number.

XML

  1. Open the pom.xml file of your Maven project.
  2. Add the following dependency information to the <dependencies> tag.
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>dashscope-sdk-java</artifactId>
    <!-- 请将 'the-latest-version' 替换为最新版本号:https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
    <version>the-latest-version</version>
</dependency>
  1. Save the pom.xml file.
  2. Use a Maven command such as mvn compile or mvn clean install to update the project dependencies. Maven automatically downloads and adds the DashScope Java SDK to your project.

For example, in the IntelliJ IDEA environment on Windows:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema ...
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>dashscope-sdk-java</artifactId>
            <!-- 请将 'the-latest-version' 替换为最新版本号:https://mvnrepository.com/artifact/com.alibaba... -->
            <version>2.18.2</version>
        </dependency>
    </dependencies>
</project>
~\Desktop\test_project
mvn compile
[INFO] Scanning for projects...
[INFO]
[INFO] ----------------------< org.example:test_project >----------------------
[INFO] Building test_project 1.0-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ jar]---------------------------------
[INFO]
[INFO] --- resources:3.3.1:resources (default-resources) @ test_project ---
[INFO] skip non existing resourceDirectory C:\Users\Administrator\Desktop\test_project\src\main\resources
[INFO]
[INFO] --- compiler:3.13.0:compile (default-compile) @ test_project ---
[INFO] Nothing to compile - all classes are up to date.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.627 s
[INFO] Finished at: 2025-02-17T13:15:30+08:00
[INFO] ------------------------------------------------------------------------

Gradle

  1. Open the build.gradle file of your Gradle project.
  2. Add the following dependency information to the dependencies block.
dependencies {
    // 请将 'the-latest-version' 替换为最新版本号:https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
    implementation group: 'com.alibaba', name: 'dashscope-sdk-java', version: 'the-latest-version'
}
  1. Save the build.gradle file.
  2. In the command line, switch to your project root directory and run the following Gradle command to update the project dependencies. Gradle automatically downloads and adds the DashScope Java SDK to your project.
./gradlew build --refresh-dependencies

For example, in the IntelliJ IDEA environment on Windows:

Complete build.gradle file example:

group = 'org.example'
version = '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.apache.groovy:groovy:4.0.14'
    testImplementation platform('org.junit:junit-bom:5.10.0')
    testImplementation 'org.junit.jupiter:junit-jupiter'
    implementation group: 'com.alibaba', name: 'dashscope-sdk-java', version: '2.18.2'
}

test {
    useJUnitPlatform()
}

After you run the build command, the terminal output is as follows:

~/Desktop/test_project
./gradlew build --refresh-dependencies

Welcome to Gradle 8.10!

Here are the highlights of this release:
  - Support for Java 23
  - Faster configuration cache
  - Better configuration cache reports

For more details see https://docs.gradle.org/8.10/release-notes.html

BUILD SUCCESSFUL in 7m 51s
2 actionable tasks: 2 executed

Step 2: Call the model API

You can run the following code to call the model API.

import java.util.Arrays;
import java.lang.System;
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 java.util.Collections;
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.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;

public class Main {
    static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";}
    public static MultiModalConversationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalMessage systemMsg = MultiModalMessage.builder()
                .role(Role.SYSTEM.getValue())
                .content(Arrays.asList(Collections.singletonMap("text", "You are a helpful assistant.")))
                .build();
        MultiModalMessage userMsg = MultiModalMessage.builder()
                .role(Role.USER.getValue())
                .content(Arrays.asList(Collections.singletonMap("text", "你是谁?")))
                .build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // 模型列表:https://help.aliyun.com/model-studio/getting-started/models
                .model("qwen3.8-max")
                .messages(Arrays.asList(systemMsg, userMsg))
                .build();
        return conv.call(param);
    }
    public static void main(String[] args) {
        try {
            MultiModalConversationResult result = callWithMessage();
            System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
        } catch (ApiException | NoApiKeyException | InputRequiredException | UploadFileException e) {
            System.err.println("错误信息:"+e.getMessage());
            System.out.println("请参考文档:https://help.aliyun.com/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

After the run, you will see the following output:

我是阿里云开发的一款超大规模语言模型,我叫千问。

curl

You can call models on the Alibaba Cloud Model Studio platform over OpenAI-compatible HTTP or DashScope HTTP. For the model list, see Model list.

NoteIf the environment variable is not configured, use your Alibaba Cloud Model Studio API key to replace: -H "Authorization: Bearer $DASHSCOPE_API_KEY" \ with: -H "Authorization: Bearer sk-xxx" .

OpenAI-compatible HTTP

You can run the following command to send the API request:

Windows

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.8-max\",
    \"messages\": [
        {
            \"role\": \"system\",
            \"content\": \"You are a helpful assistant.\"
        },
        {
            \"role\": \"user\",
            \"content\": \"你是谁?\"
        }
    ]
}"

Linux/macOS

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.8-max",
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "你是谁?"
        }
    ]
}'

After you send the API request, you will receive the following response:

{
    "choices": [
        {
            "message": {
                "role": "assistant",
                "content": "我是来自阿里云的大规模语言模型,我叫千问。"
            },
            "finish_reason": "stop",
            "index": 0,
            "logprobs": null
        }
    ],
    "object": "chat.completion",
    "usage": {
        "prompt_tokens": 22,
        "completion_tokens": 16,
        "total_tokens": 38
    },
    "created": 1728353155,
    "system_fingerprint": null,
    "model": "qwen3.8-max",
    "id": "chatcmpl-39799876-eda8-9527-9e14-2214d641cf9a"
}

DashScope-HTTP

You can run the following command to send the API request:

Windows

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.8-max\",
  \"input\": {
    \"messages\": [
      {
        \"role\": \"system\",
        \"content\": [{\"text\": \"You are a helpful assistant.\"}]
      },
      {
        \"role\": \"user\",
        \"content\": [{\"text\": \"你是谁?\"}]
      }
    ]
  },
  \"parameters\": {
    \"result_format\": \"message\"
  }
}"

Linux/macOS

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.8-max",
    "input":{
        "messages":[
            {
                "role": "system",
                "content": [{"text": "You are a helpful assistant."}]
            },
            {
                "role": "user",
                "content": [{"text": "你是谁?"}]
            }
        ]
    },
    "parameters": {
        "result_format":"message"
    }
}'

After you send the API request, you will receive the following response:

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": "我是来自阿里云的大规模语言模型,我叫千问。"
                }
            }
        ]
    },
    "usage": {
        "total_tokens": 38,
        "output_tokens": 16,
        "input_tokens": 22
    },
    "request_id": "87f776d7-3c82-9d39-b238-d1ad38c9b6a9"
}

Other languages

Call the model API
package main

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

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}
type RequestBody struct {
	Model    string    `json:"model"`
	Messages []Message `json:"messages"`
}

func main() {
	// 创建 HTTP 客户端
	client := &http.Client{}
	// 构建请求体
	requestBody := RequestBody{
		// 模型列表:https://help.aliyun.com/model-studio/getting-started/models
		Model: "qwen3.8-max",
		Messages: []Message{
			{
				Role:    "system",
				Content: "You are a helpful assistant.",
			},
			{
				Role:    "user",
				Content: "你是谁?",
			},
		},
	}
	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		log.Fatal(err)
	}
	// 创建 POST 请求
	// 以下为华北2(北京)地域的URL,各地域的URL不同。调用时请将{WorkspaceId}替换为真实的业务空间ID。
	req, err := http.NewRequest("POST", "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions", bytes.NewBuffer(jsonData))
	if err != nil {
		log.Fatal(err)
	}
	// 设置请求头
	// 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:apiKey := "sk-xxx"
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")
	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	// 读取响应体
	bodyText, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	// 打印响应内容
	fmt.Printf("%s\n", bodyText)
}
<?php
// 设置请求的URL
// 以下为华北2(北京)地域的URL,各地域的URL不同。调用时请将{WorkspaceId}替换为真实的业务空间ID。
$url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions';
// 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:$apiKey = "sk-xxx";
$apiKey = getenv('DASHSCOPE_API_KEY');
// 设置请求头
$headers = [
    'Authorization: Bearer '.$apiKey,
    'Content-Type: application/json'
];
// 设置请求体
$data = [
    // 模型列表:https://help.aliyun.com/model-studio/getting-started/models
    "model" => "qwen3.8-max",
    "messages" => [
        [
            "role" => "system",
            "content" => "You are a helpful assistant."
        ],
        [
            "role" => "user",
            "content" => "你是谁?"
        ]
    ]
];
// 初始化cURL会话
$ch = curl_init();
// 设置cURL选项
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);
// 执行cURL会话
$response = curl_exec($ch);
// 检查是否有错误发生
if (curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
}
// 关闭cURL资源
curl_close($ch);
// 输出响应结果
echo $response;
?>
using System.Net.Http.Headers;
using System.Text;

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

    static async Task Main(string[] args)
    {
        // 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:string? apiKey = "sk-xxx";
        string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");

        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("API Key 未设置。请确保环境变量 'DASHSCOPE_API_KEY' 已设置。");
            return;
        }
        // 以下为华北2(北京)地域的URL,各地域的URL不同。调用时请将{WorkspaceId}替换为真实的业务空间ID。
        string url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions";
        // 模型列表:https://help.aliyun.com/model-studio/getting-started/models
        string jsonContent = @"{
            ""model"": ""qwen3.8-max"",
            ""messages"": [
                {
                    ""role"": ""system"",
                    ""content"": ""You are a helpful assistant.""
                },
                {
                    ""role"": ""user"",
                    ""content"": ""你是谁?""
                }
            ]
        }";

        // 发送请求并获取响应
        string result = await SendPostRequestAsync(url, jsonContent, apiKey);

        // 输出结果
        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"))
        {
            // 设置请求头
            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
            {
                return $"请求失败: {response.StatusCode}";
            }
        }
    }
}

API reference

FAQ

How do I purchase tokens after the free quota is used up?

A: You can visit the Expenses and Costs center. As long as your account has no overdue payments, you can call Qwen models.

Calls to Qwen models are billed automatically, and bills are generated on a per-minute basis (each bill represents the charges incurred within one minute). To view consumption details, go to Bill details.

What should I do if the Model.AccessDenied error occurs after I call the model API?

A: This error occurs because you are using an API key of a sub-workspace, which cannot access the applications or models of the root account workspace. To use a sub-workspace API key, the root account administrator must grant model authorization to the corresponding sub-workspace (for example, for the qwen3.8-max model used in this topic). For detailed steps, see Configure model calling permissions.

How do I integrate Chatbox, Cherry Studio, Cline, or Dify?

A: Refer to the following steps based on your use case:

The most frequently used tools are used as examples here. The methods for integrating other model tools are similar.

Chatbox

See Chatbox.

Cherry Studio

  1. Click the settings button in the lower-left corner. In the Model Service section, find Alibaba Cloud Model Studio. In API Key, enter your API key. For information about how to obtain an API key, see Get and configure an API key. In API endpoint, enter https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/ (replace WorkspaceId with your workspace ID). Click Add.

  2. In Model ID, enter the Qwen model you want to use. This topic uses qwen3.8-max as an example (for more available models, see the Qwen models in Model list). Model Name and Group name are generated automatically.

  3. Select the added model at the top of the interface. Some models support web search. Turn on the web search button next to the input box. Enter "What's the weather like in Hangzhou?" to test:

    The web search button is the globe icon in the toolbar below the input box. After you turn it on, the model successfully returns real-time weather information for Hangzhou and the weather forecast for the coming days, verifying that the web search feature works properly.

Cline

See Cline.

Next steps

View more models

The sample code uses the qwen3.8-max model as an example. Alibaba Cloud Model Studio also supports other Qwen models and third-party models such as DeepSeek and Llama. For supported models and the corresponding API reference documents, see Model list.

Learn advanced usage

The sample code only implements simple Q&A. To learn more about the Qwen API, such as streaming output, structured output, and Function Calling, see Overview.

Experience models online

If you want to interact with models through a dialog box like the Qwen official website, visit the Experience Center.

The Qwen official website integrates the Qwen API with tools such as web search and webpage parsing, so the results differ slightly from those of direct Qwen API calls.

Image generation models support single-turn conversations only and do not support multi-turn conversation editing. Each image generation is an independent operation, and you cannot reference the previous generation result in the same conversation context. To modify an image based on the original one, save the image to your computer, click the plus sign (+) button in the conversation window to upload it again, and then enter a new editing instruction.

Fine-tune models without code

Generally, fine-tuning large models requires an AI knowledge background and engineering capabilities. Alibaba Cloud Model Studio provides a no-code fine-tuning feature. You only need to provide a dataset. For details, see Fine-tune models in the console.

Call custom-trained models

If you have deployed a custom-trained model on Model Studio, use the model code generated on the Dedicated Deployment page as the model parameter when you make API calls, instead of the model ID. Otherwise, the error Model not exist occurs. For details, see the "Post-deployment calls" section in Introduction to model deployment.