You can use APIs to call models in Model Studio, including OpenAI-compatible interfaces and DashScope SDK.
This topic uses Qwen as an example to guide you through your first API call. You will learn how to:
Obtain an API key.
Set up the development environment.
Make an API call to Qwen
Manage account
Register an account: If you do not have an Alibaba Cloud account, you must first register for one.
Activate Model Studio: Go to the Model Studio console, activate the service to obtain the free quota.
Obtain an API key: In the upper right corner of the console, select API-KEY. On the page that appears, create an API key.
Set API key as environment variable
We recommend that you set the API key as an environment variable to avoid explicitly specifying it in the code, thus reducing the risk of leaks.
Select development language
Choose the programming language or tool with which you are most comfortable.
Python
Step 1: Prepare Python environment
Check Python version
Configure virtual environment (optional)
Install OpenAI Python SDK or DashScope Python SDK
Step 2: Call the API
OpenAI Python SDK
After installing Python and OpenAI Python SDK, take the following steps to send your API request.
Create a new file named
hello_qwen.py
.Copy the following code into
hello_qwen.py
and save it.import os from openai import OpenAI try: client = OpenAI( # If the environment variable is not configured, replace the following line with your API key: api_key="sk-xxx", api_key=os.getenv("DASHSCOPE_API_KEY"), base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1", ) completion = client.chat.completions.create( model="qwen-plus", # Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models messages=[ {'role': 'system', 'content': 'You are a helpful assistant.'}, {'role': 'user', 'content': 'Who are you?'} ] ) print(completion.choices[0].message.content) except Exception as e: print(f"Error message: {e}") print("For more information, see: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code")
Run
python hello_qwen.py
orpython3 hello_qwen.py
.NoteThe command used in this example needs to be executed in the directory where the Python file is located. If you want to execute it from any location, specify the specific file path before the file name.
Sample response:
I am a large language model created by Alibaba Cloud. I am called Qwen.
DashScope Python SDK
After installing Python and DashScope Python SDK, take the following steps to send your API request.
Create a new file named
hello_qwen.py
.Copy the following code into
hello_qwen.py
and save it.import os from dashscope import Generation import dashscope dashscope.base_http_api_url = 'https://dashscope-intl.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 the following line with your API key: api_key = "sk-xxx", api_key=os.getenv("DASHSCOPE_API_KEY"), model="qwen-plus", # Model list: https://www.alibabacloud.com/help/en/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 return 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/developer-reference/error-code")
Run
python hello_qwen.py
orpython3 hello_qwen.py
.NoteThe command used in this example needs to be executed in the directory where the Python file is located. If you want to execute it from any location, specify the specific file path before the file name.
Sample response:
I am a large language model created by Alibaba Cloud. I am called Qwen.
Node.js
Step 1: Prepare Node.js environment
Check Node.js installation status
Install the SDK
Step 2: Call the API
Create a
hello_qwen.mjs
file.Copy the following code into the file.
import OpenAI from "openai"; try { const openai = new OpenAI( { // If the environment variable is not configured, replace the following line with your API key: apiKey: "sk-xxx", apiKey: process.env.DASHSCOPE_API_KEY, baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1" } ); const completion = await openai.chat.completions.create({ model: "qwen-plus", // Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models messages: [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: "Who are you?" } ], }); console.log(completion.choices[0].message.content); } catch (error) { console.log(`Error message: ${error}`); console.log("For more information, see: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code"); }
Run the following command to send the API request:
node hello_qwen.mjs
NoteThe command used in this example needs to be executed in the directory where
hello_qwen.mjs
resides. If you want to execute it from any location, specify the specific file path before the file name.Ensure that the SDK is installed in the directory where
hello_qwen.mjs
resides. If the SDK is not in the same directory as the file, an errorCannot find package 'openai' imported from xxx
will occur.
Sample response:
I am a language model created by Alibaba Cloud. I am called Qwen.
Java
Step 1: Prepare Java environment
Check Java version
Install the SDK
Step 2: Call the API
You can run the following code to call the 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 {
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.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 the following line with your API key: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
.model("qwen-plus")
.messages(Arrays.asList(systemMsg, userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.build();
return gen.call(param);
}
public static void main(String[] args) {
try {
GenerationResult result = callWithMessage();
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
} 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/developer-reference/error-code");
}
System.exit(0);
}
}
Sample response:
I am a large language model created by Alibaba Cloud. I am called Qwen.
cURL
You call models in Model Studio by using OpenAI-compatible HTTP or DashScope HTTP protocols. For a list of supported models, see List of models.
If you did not set the environment variable, replace -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
with -H "Authorization: Bearer sk-xxx" \
.
OpenAI-compatible HTTP
To send an API request, run the following command:
Sample response:
{
"choices": [
{
"message": {
"role": "assistant",
"content": "I am a large language model created by Alibaba Cloud. I am called 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
To send an API request, run the following command:
Sample response:
{
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": "I am a large language model created by Alibaba Cloud. I am called Qwen."
}
}
]
},
"usage": {
"total_tokens": 38,
"output_tokens": 16,
"input_tokens": 22
},
"request_id": "87f776d7-3c82-9d39-b238-d1ad38c9b6a9"
}
Other languages
Call the 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{}
// Construct the request body
requestBody := RequestBody{
// Model list: https://www.alibabacloud.com/help/en/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)
}
// Create a POST request
req, err := http.NewRequest("POST", "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions", bytes.NewBuffer(jsonData))
if err != nil {
log.Fatal(err)
}
// Set request headers
// If the environment variable is not configured, replace the following line with your API key: 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 content of the response
fmt.Printf("%s\n", bodyText)
}
<?php
// Set the request URL
$url = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
// If the environment variable is not configured, replace the following line with your API key: $apiKey = "sk-xxx";
$apiKey = getenv('DASHSCOPE_API_KEY');
// Set request headers
$headers = [
'Authorization: Bearer '.$apiKey,
'Content-Type: application/json'
];
// Set the request body
$data = [
"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 whether an error occurs
if (curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
}
// Close the cURL resource
curl_close($ch);
// Output the response result
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;
}
string url = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions";
// 模型列表:https://www.alibabacloud.com/help/en/model-studio/getting-started/models
string jsonContent = @"{
""model"": ""qwen-plus"",
""messages"": [
{
""role"": ""system"",
""content"": ""You are a helpful assistant.""
},
{
""role"": ""user"",
""content"": ""你是谁?""
}
]
}";
// 发送请求并获取响应
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}";
}
}
}
}
using System.Net.Http.Headers;
using System.Text;
class Program
{
private static readonly HttpClient httpClient = new HttpClient();
static async Task Main(string[] args)
{
// If the environment variable is not configured, replace the following line with your API key: string? apiKey = "sk-xxx";
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("API Key is not set. Please ensure the environment variable 'DASHSCOPE_API_KEY' is set.");
return;
}
string url = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions";
// Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
string jsonContent = @"{
""model"": ""qwen-plus"",
""messages"": [
{
""role"": ""system"",
""content"": ""You are a helpful assistant.""
},
{
""role"": ""user"",
""content"": ""Who are you?""
}
]
}";
// Send the request and obtain 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 obtain the response
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// Process the response
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return $"Request failed: {response.StatusCode}";
}
}
}
}
FAQ
Q: My free quota has run out. How to purchase tokens for the Qwen models?
A: You can go to Expenses and Costs. So long as your account has no overdue payments, you can call the Qwen models.
Charges for using the Qwen models will appear on your bill one hour after the request.
What to do next
More models: The sample code use the qwen-plus model. Model Studio supports other commercial and open source Qwen models. For supported models and their API references, see List of models.
Advanced usage: The sample code covers only a basic Q&A pair. To explore more Qwen API features, such as Streaming output, Structured output (JSON mode), Tool calling (Function calling), and more, go to the Text Generation directory.
Create application on the console: Build a private Q&A assistant without coding.
Create applications through code: Assistant API.
Interact directly with the model: For direct interaction through a dialog box similar to Qwen Chat, go to Playground.