You can use API operations to call models in Alibaba Cloud Model Studio. Model Studio supports multiple methods, including OpenAI-compatible interfaces and DashScope SDK.
If you already know how to call a model, you can go to Qwen directly.
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 Alibaba Cloud Model Studio Console. Follow the on-screen instructions to activate model services.
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: Configure Python environment
Check Python version
Configure virtual environment (optional)
Install SDK
Step 2: Call the API
OpenAI Python SDK
After installing Python and OpenAI Python SDK, you can use the following sample code to make your API request. Create a Python file hello_qwen.py
, copy the following sample into hello_qwen.py
, and save the file.
import os
from openai import OpenAI
try:
client = OpenAI(
# Replace the next line with your API Key if you did not configure the environment variable: 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", # For a list of models, see 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.")
After the file is saved, run python hello_qwen.py
or python3 hello_qwen.py
. Sample response:
I am a large language model created by Alibaba Cloud. I'm called Qwen.
DashScope Python SDK
After installing Python and DashScope Python SDK, you can use the following sample code to make your API request. Create a Python file hello_qwen.py
, copy the following sample into hello_qwen.py
, and save the file.
import os
import dashscope
from dashscope import Generation
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(
# Replace the next line with your Bailian API Key if the environment variable is not set: 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/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 .")
After the file is saved, run python hello_qwen.py
or python3 hello_qwen.py
. Sample response:
I am a large language model created by Alibaba Cloud. I'm called Qwen.
Node.js
Step 1: Configure Node.js environment
Check Node.js
Install SDK
Step 2: Call the model
Create a new file hello_qwen.mjs
and copy the following sample code into it.
import OpenAI from "openai";
try {
const openai = new OpenAI({
// If you did not set the environment variable, 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", // For a list of models, see: 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.error(`Error message: ${error}`);
}
Run the following command in the command line to send the API request:
node hello_qwen.mjs
Sample response:
I am Qwen, a large language model developed by Alibaba Cloud.
Java
Step 1: Configure Java environment
Check Java version
Install SDK
Step 2: Call the model
To call the model, execute the following code.
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 you did not set the environment variable, replace the following line with your API Key: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// For a list of models, see: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
.model("qwen-plus")
.messages(Arrays.asList(systemMsg, userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.build();
return gen.call(param);
}
public static void main(String[] args) {
try {
GenerationResult result = callWithMessage();
System.out.println(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 Qwen, a large language model developed by Alibaba Cloud.
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" \ (sk-xxx is your API key).
OpenAI-compatible HTTP
Run the following command to send an API request:
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-plus",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Who are you?"
}
]
}'
Sample response:
{
"choices": [
{
"message": {
"role": "assistant",
"content": "I am a large language model developed by Alibaba Cloud, known as 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
Run the following command to send an API request:
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-plus",
"input":{
"messages":[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Who are you?"
}
]
},
"parameters": {
"result_format":"message"
}
}'
Sample response:
{
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": "I am a large language model developed by Alibaba Cloud, known as Qwen."
}
}
]
},
"usage": {
"total_tokens": 38,
"output_tokens": 16,
"input_tokens": 22
},
"request_id": "87f776d7-3c82-9d39-b238-d1ad38c9b6a9"
}
Other languages
Call the model
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() {
// Initialize HTTP client
client := &http.Client{}
// Construct request body
requestBody := RequestBody{
// For a list of models, see: 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)
}
// Configure request headers
// If you did not set the environment variable, use your API key instead: apiKey := "sk-xxx"
apiKey := os.Getenv("DASHSCOPE_API_KEY")
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Execute the request
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// Read and output the response body
bodyText, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", bodyText)
}
<?php
$url = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
// If you did not set the environment variable is not set, use your API Key instead: $apiKey = "sk-xxx";
$apiKey = getenv('DASHSCOPE_API_KEY');
// Define request headers
$headers = [
'Authorization: Bearer '.$apiKey,
'Content-Type: application/json'
];
// Construct request body
$data = [
// For a list of models, see: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
"model" => "qwen-plus",
"messages" => [
[
"role" => "system",
"content" => "You are a helpful assistant."
],
[
"role" => "user",
"content" => "Who are you?"
]
]
];
// Initialize and configure cURL session
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute the cURL session and capture the response
$response = curl_exec($ch);
// Handle errors, if any
if (curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
}
// Close the cURL session
curl_close($ch);
// Display 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 you did not set the environment variable, use your API Key instead: string? apiKey = "sk-xxx";
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("API Key not set. Please ensure the 'DASHSCOPE_API_KEY' environment variable is configured.");
return;
}
string url = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions";
// For a list of models, see: 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 display the result
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"))
{
// Configure request headers
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Execute the request and process the response
HttpResponseMessage response = await httpClient.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return $"Request failed: {response.StatusCode}";
}
}
}
}
What to do next
For information about all supported models in Model Studio, see List of models.
To create a model application by using the web interface, see Zero-Code Build Private Knowledge Q&A Application.
To create an agent by using the API, see Assistant API.
To interact with models by using a dialog box, go to Playground.