Alibaba Cloud Model Studio supports API calls to models through OpenAI-compatible interfaces and the DashScope SDK.
-
If you are familiar with model API calls, go directly to the Qwen API reference.
-
If you are not familiar with programming, try Chatbox to interact with Qwen models through a graphical interface.
To call the Qwen API:
-
Get an API key
-
Set up your local development environment
-
Call the Qwen API
Account setup
-
Create an account: If you do not have an Alibaba Cloud account, create one.
If you encounter issues, see Register an Alibaba Cloud account.
-
Activate Model Studio: Use your Alibaba Cloud account to go to Alibaba Cloud Model Studio. Read and accept the Terms of Service to activate the service. If no Terms of Service dialog appears, the service is already activated.
If you see the message “You have not completed identity verification” when activating the service, complete identity verification first.
-
Get an API key: Go to the API Key page and click Create API key. Then use the API key to call models.
-
Get your workspace ID: When calling models in the China (Beijing), Singapore, or Germany (Frankfurt) region, you need to include the workspace ID (WorkspaceId) in the Base URL. You can find it on the Workspace Management page.
Set your API key as an environment variable
Store your API key in an environment variable to avoid hardcoding credentials and reduce security risks.
Choose a development language
Select a language or tool to call model APIs.
Python
Step 1: Set up Python
Check your Python version
Set up a virtual environment (optional)
Install the OpenAI Python SDK or DashScope Python SDK
Step 2: Call the API
OpenAI Python SDK
With Python and the OpenAI Python SDK installed, send your first API request.
-
Create a file named
hello_qwen.py. -
Copy this code into
hello_qwen.pyand save it.import os from openai import OpenAI try: client = OpenAI( # If the environment variable is not configured, replace with: api_key="sk-xxx" api_key=os.getenv("DASHSCOPE_API_KEY"), # The following base URL is for the China (Beijing) region. URLs vary by region. Replace {WorkspaceId} with your workspace ID. base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1", ) completion = client.chat.completions.create( model="qwen-plus", # Model list: https://help.aliyun.com/model-studio/getting-started/models messages=[ {'role': 'system', 'content': 'You are a helpful assistant.'}, {'role': 'user', 'content': 'Who are you?'} ] ) print(completion.choices[0].message.content) except Exception as e: print(f"Error message: {e}") print("See: https://help.aliyun.com/model-studio/developer-reference/error-code") -
Run
python hello_qwen.pyorpython3 hello_qwen.pyfrom the command line.If you see
No such file or directory, specify the full path to the file.The output is:
I am a large-scale language model developed by Alibaba Cloud. My name is Qwen.
DashScope Python SDK
With Python and the DashScope Python SDK installed, send your first API request.
-
Create a file named
hello_qwen.py. -
Copy this code into
hello_qwen.pyand save it.import os from dashscope import Generation import dashscope # The following base URL is for the China (Beijing) region. URLs vary by region. Replace {WorkspaceId} with your workspace ID. dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1' messages = [ {'role': 'system', 'content': 'You are a helpful assistant.'}, {'role': 'user', 'content': 'Who are you?'} ] response = Generation.call( # If the environment variable is not configured, replace with: api_key = "sk-xxx" api_key=os.getenv("DASHSCOPE_API_KEY"), model="qwen-plus", # Model list: https://help.aliyun.com/model-studio/getting-started/models messages=messages, result_format="message" ) if response.status_code == 200: print(response.output.choices[0].message.content) else: print(f"HTTP status code: {response.status_code}") print(f"Error code: {response.code}") print(f"Error message: {response.message}") print("See: https://help.aliyun.com/model-studio/developer-reference/error-code") -
Run
python hello_qwen.pyorpython3 hello_qwen.pyfrom the command line.NoteThe command in this example must be executed from the directory containing the Python file. To run it from elsewhere, specify the full path.
The output is:
I am a large-scale language model from Alibaba Cloud. My name is Qwen.
Node.js
Step 1: Set up your Node.js environment
Check your Node.js installation
Install the model calling SDK
Step 2: Call the model API
-
Create a file named
hello_qwen.mjs. -
Copy this code into the file.
import OpenAI from "openai"; try { const openai = new OpenAI( { // If the environment variable is not configured, replace with: apiKey: "sk-xxx" apiKey: process.env.DASHSCOPE_API_KEY, // The following base URL is for the China (Beijing) region. URLs vary by region. Replace {WorkspaceId} with your workspace ID. baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1" } ); const completion = await openai.chat.completions.create({ model: "qwen-plus", // Model list: https://help.aliyun.com/model-studio/getting-started/models messages: [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: "Who are you?" } ], }); console.log(completion.choices[0].message.content); } catch (error) { console.log(`Error message: ${error}`); console.log("See: https://help.aliyun.com/model-studio/developer-reference/error-code"); } -
Run this command to send an API request.
node hello_qwen.mjsNote-
Run this command from the directory containing
hello_qwen.mjs. To run it from any location, specify the full path to the file. -
Ensure the SDK is installed in the same directory as
hello_qwen.mjs. If they are in different directories, you will seeCannot find package 'openai' imported from xxx.
After successful execution, the output is:
I am a language model from Alibaba Cloud. My name is Qwen.
-
Java
Step 1: Set up your Java environment
Check your Java version
Install the model calling SDK
Step 2: Call the API
Run this code to call the model API.
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;
public class Main {
public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
// The following base URL is for the China (Beijing) region. URLs vary by region. Replace {WorkspaceId} with your workspace ID.
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1");
Message systemMsg = Message.builder()
.role(Role.SYSTEM.getValue())
.content("You are a helpful assistant.")
.build();
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("Who are you?")
.build();
GenerationParam param = GenerationParam.builder()
// If the environment variable is not configured, replace with: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Model list: https://help.aliyun.com/model-studio/getting-started/models
.model("qwen-plus")
.messages(Arrays.asList(systemMsg, userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.build();
return gen.call(param);
}
public static void main(String[] args) {
try {
GenerationResult result = callWithMessage();
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("Error message: "+e.getMessage());
System.out.println("See: https://help.aliyun.com/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
The output is:
I am a large-scale language model developed by Alibaba Cloud. My name is Qwen.
curl
Call models on Model Studio using OpenAI-compatible or DashScope HTTP endpoints. For supported models, see Model list.
If DASHSCOPE_API_KEY is not set, replace -H "Authorization: Bearer $DASHSCOPE_API_KEY" with -H "Authorization: Bearer sk-xxx".
OpenAI-compatible HTTP
Send the API request:
After sending the API request, you receive this response:
{
"choices": [
{
"message": {
"role": "assistant",
"content": "I am a large-scale language model from Alibaba Cloud. My name is Qwen."
},
"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": "qwen-plus",
"id": "chatcmpl-39799876-eda8-9527-9e14-2214d641cf9a"
}
DashScope HTTP
Send the API request:
After sending the API request, you receive this response:
{
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": "I am a large-scale language model from Alibaba Cloud. My name is Qwen."
}
}
]
},
"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() {
// Create an HTTP client
client := &http.Client{}
// Build the request body
requestBody := RequestBody{
// Model list: https://help.aliyun.com/model-studio/getting-started/models
Model: "qwen-plus",
Messages: []Message{
{
Role: "system",
Content: "You are a helpful assistant.",
},
{
Role: "user",
Content: "Who are you?",
},
},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
log.Fatal(err)
}
// The following base URL is for the China (Beijing) region. URLs vary by region. Replace {WorkspaceId} with your workspace 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)
}
// If the environment variable is not configured, replace with: apiKey := "sk-xxx"
apiKey := os.Getenv("DASHSCOPE_API_KEY")
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send the request
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// Read the response body
bodyText, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
// Print the response
fmt.Printf("%s\n", bodyText)
}
<?php
// The following base URL is for the China (Beijing) region. URLs vary by region. Replace {WorkspaceId} with your workspace ID.
$url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions';
// If the environment variable is not configured, replace with: $apiKey = "sk-xxx"
$apiKey = getenv('DASHSCOPE_API_KEY');
// Set request headers
$headers = [
'Authorization: Bearer '.$apiKey,
'Content-Type: application/json'
];
// Set request body
$data = [
// Model list: https://help.aliyun.com/model-studio/getting-started/models
"model" => "qwen-plus",
"messages" => [
[
"role" => "system",
"content" => "You are a helpful assistant."
],
[
"role" => "user",
"content" => "Who are you?"
]
]
];
// Initialize a cURL session
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute the cURL session
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
}
// Close the cURL resource
curl_close($ch);
// Output the response
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)
{
// If the environment variable is not configured, replace with: string? apiKey = "sk-xxx"
// Singapore and China (Beijing) API keys differ. Get your API key: https://help.aliyun.com/model-studio/get-api-key
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("API Key not set. Make sure the 'DASHSCOPE_API_KEY' environment variable is set.");
return;
}
// The following base URL is for the China (Beijing) region. URLs vary by region. Replace {WorkspaceId} with your workspace ID.
string url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions";
// Model list: https://help.aliyun.com/model-studio/getting-started/models
string jsonContent = @"{
""model"": ""qwen-plus"",
""messages"": [
{
""role"": ""system"",
""content"": ""You are a helpful assistant.""
},
{
""role"": ""user"",
""content"": ""Who are you?""
}
]
}";
// Send the request and get the response
string result = await SendPostRequestAsync(url, jsonContent, apiKey);
// Output the result
Console.WriteLine(result);
}
private static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
{
using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
{
// Set request headers
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Send the request and get the response
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// Handle the response
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return $"Request failed: {response.StatusCode}";
}
}
}
}API reference
-
For the input and output parameters, see Qwen API reference.
-
For other models, see Model list.
FAQ
How do I buy tokens after my Free quota runs out?
A: Go to Expenses and Costs. Ensure there are no overdue payments before calling Qwen models.
Calls to Qwen models are billed automatically. Bills are generated by the minute, with each entry detailing the charges for that minute. View usage details in Bill details.
How do I fix the Model.AccessDenied error after calling the model API?
A: This error occurs because you are using an API key from a sub-workspace. A sub-workspace cannot access applications or models in the root account workspace. To use a sub-workspace API key, the root account administrator must grant model authorization for the corresponding sub-workspace (for example, this topic uses the Qwen-Plus model). For detailed steps, see Configure model calling permissions.
How do I integrate with Chatbox, Cherry Studio, Cline, or Dify?
A: Follow the steps below based on your use case.
We use the most commonly used tools as examples. Steps for other tools are similar.
Chatbox
See Chatbox.
Cherry Studio
-
Click the Settings button in the lower-left corner. In the Model Service section, find Alibaba Cloud Model Studio. Enter your API key in API key. To obtain your API key, see Get an API Key. Enter
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/in API endpoint (replace {WorkspaceId} with your workspace ID). Click Add.
-
In Model ID, enter the Qwen model you want to use. For example, use qwen-max-latest. For more models, see the Qwen models in the Model list. Model Name and Group name are generated automatically.

-
Select the added model at the top of the interface. Some models support web search. Turn on the web search toggle next to the input box. Test it by entering “What’s the weather like in Hangzhou?”:

Cline
See Cline.
Dify
See Dify.
Next steps
|
Explore more models |
The example code uses |
|
Learn advanced features |
The example code covers basic Q&A only. To learn more about the Qwen API, such as streaming output, structured output, and function calling, see the Text generation model overview. |
|
Try models in the browser |
If you want to interact with models through a dialog box, like on the Qwen official website, go to the Playground (China (Beijing) or Singapore). The Qwen official website integrates the Qwen API with tools such as web search and webpage parsing. Results may differ slightly from direct API calls. |
|
Fine-tune models without code |
Fine-tuning usually requires AI expertise. Model Studio provides no-code fine-tuning—you only need to provide a dataset. For details, see Model tuning in the console. |

















