This topic describes how to call a model in a sub-workspace (non-default workspace) through the API, using Qwen-Plus as an example.
Scenarios
Control model permissions: Users in the default workspace can access all models (which may be excessive). To control model access, add users to a sub-workspace and specify which models they can call.
Track model costs: When multiple teams share the default workspace, it's difficult to track model costs. By creating separate sub-workspaces, each workspace can generate independent bills, making cost allocation easier.
Before you begin
Prepare a sub-workspace: Learn how to create a sub-workspace. Skip this step if you already have one. How to view all your workspaces
If you see the following message at the top of the Model Studio console, you need to activate Model Studio (and get the free quota). If this message is not displayed, the service is already active.

Obtain API key: Create an API key in this sub-workspace.
Model authorization: Authorize the sub-workspace to call a model in the list (such as Qwen-Plus) using the sub-workspace's API key.
Call the model
OpenAI
This section calls Qwen-Plus in the OpenAI compatible method. The model has been authorized in advance. The only difference between calling models in a sub-workspace versus the default workspace is that you must use an API key created in that sub-workspace.
Public cloud
base_url for SDK: https://dashscope-intl.aliyuncs.com/compatible-mode/v1
HTTP endpoint: POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions
Before running the samples:
Set the API key you prepared as an environment variable.
Select a programming language you are familiar with and prepare the local development environment.
To use the OpenAI SDK, you must also install the OpenAI SDK.
Python
import os
from openai import OpenAI
client = OpenAI(
# If environment variables are not configured, replace the following line with: api_key="sk-xxx" using the sub-workspace's API key
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", # This example uses qwen-plus. You can change the model name as needed (model authorization is required). For supported 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.model_dump_json())Node.js
import OpenAI from "openai";
const openai = new OpenAI(
{
// If environment variables are not configured, replace the following line with: apiKey: "sk-xxx" using the sub-workspace's API key
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
}
);
async function main() {
const completion = await openai.chat.completions.create({
model: "qwen-plus", // This example uses qwen-plus. You can change the model name as needed (model authorization is required). For supported 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(JSON.stringify(completion))
}
main();HTTP
curl
If you haven't set environment variables, replace $DASHSCOPE_API_KEY with: the API key from your sub-workspace sk-xxx.
This example uses qwen-plus. You can use other models that are authorized.
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?"
}
]
}'PHP
<?php
// Set the request URL
$url = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
// If environment variables are not configured, replace the following line with: $apiKey = "sk-xxx" using the API key of your sub-workspace
$apiKey = getenv('DASHSCOPE_API_KEY');
// Configure request headers
$headers = [
'Authorization: Bearer '.$apiKey,
'Content-Type: application/json'
];
// Set request body
$data = [
// This example uses qwen-plus. You can change the model name as needed (model authorization is required). For supported 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 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 cURL session
$response = curl_exec($ch);
// Check whether an error occurs
if (curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
}
// Close cURL resource
curl_close($ch);
// Output the result
echo $response;
?>C#
using System.Net.Http.Headers;
using System.Text;
class Program
{
private static readonly HttpClient httpClient = new HttpClient();
static async Task Main(string[] args)
{
// If environment variables are not configured, replace the following line with: string? apiKey = "sk-xxx" using the API key of your sub-workspace
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;
}
// Set request URL and content
string url = "https://dashscope.aliyuncs-intl.com/compatible-mode/v1/chat/completions";
// This example uses qwen-plus. You can change the model name as needed (model authorization is required). For supported 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 request and obtain response
string result = await SendPostRequestAsync(url, jsonContent, apiKey);
// Output 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"))
{
// Configure request headers
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Send request and obtain response
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// Process response
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return $"Request failed: {response.StatusCode}";
}
}
}
}Go
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 request body
requestBody := RequestBody{
// This example uses qwen-plus. You can change the model name as needed (model authorization is required). For supported 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 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 environment variables are not configured, replace the following line with: apiKey := "sk-xxx" using the sub-workspace's API key
apiKey := os.Getenv("DASHSCOPE_API_KEY")
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send request
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// Read 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)
}Java
OpenAI does not provide a Java SDK. You can use the DashScope section of this topic instead.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import com.google.gson.Gson;
public class Main {
static class Message {
String role;
String content;
public Message(String role, String content) {
this.role = role;
this.content = content;
}
}
static class RequestBody {
String model;
Message[] messages;
public RequestBody(String model, Message[] messages) {
this.model = model;
this.messages = messages;
}
}
public static void main(String[] args) {
try {
// Create request body
RequestBody requestBody = new RequestBody(
// This example uses qwen-plus. You can change the model name as needed (model authorization is required). For supported models, see: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
"qwen-plus",
new Message[] {
new Message("system", "You are a helpful assistant."),
new Message("user", "Who are you?")
}
);
// Convert request body to JSON
Gson gson = new Gson();
String jsonInputString = gson.toJson(requestBody);
// Create a URL object
URL url = new URL("https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// Set request method to POST
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json; utf-8");
httpURLConnection.setRequestProperty("Accept", "application/json");
// If environment variables are not configured, replace the following line with: String apiKey = "sk-xxx" using the sub-workspace's API key
String apiKey = System.getenv("DASHSCOPE_API_KEY");
String auth = "Bearer " + apiKey;
httpURLConnection.setRequestProperty("Authorization", auth);
// Enable input and output streams
httpURLConnection.setDoOutput(true);
// Write request body
try (OutputStream os = httpURLConnection.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// Obtain response code
int responseCode = httpURLConnection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// Read response body
try (BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println("Response Body: " + response);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.exit(0);
}
}
}DashScope
This section calls Qwen-Plus in the DashScope method. The model has been authorized in advance. The only difference between calling models in a sub-workspace versus the default workspace is that you must use an API key created in that sub-workspace.
Public cloud
HTTP endpoint:
For Qwen LMs:
POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generationFor Qwen VL:
POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generationbase_url for SDK:
Python code:
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'Java code:
Method 1:
import com.alibaba.dashscope.protocol.Protocol; Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");Method 2:
import com.alibaba.dashscope.utils.Constants; Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
Before running the samples:
Set the API key you prepared as an environment variable.
Select a programming language you are familiar with and prepare the local development environment.
To use the DashScope SDK, you must install the DashScope SDK.
Python
import os
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 = dashscope.Generation.call(
# If environment variables are not configured, replace the following line with: api_key="sk-xxx" using the sub-workspace's API key
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen-plus", # This example uses qwen-plus. You can change the model name as needed (model authorization is required). For supported models, see: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
messages=messages,
result_format='message'
)
print(response)Java
// Recommended dashscope SDK version >= 2.12.0
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.utils.JsonUtils;
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 environment variables are not configured, replace the following line with: .apiKey("sk-xxx") using the API key of your sub-workspace
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// This example uses qwen-plus. You can change the model name as needed (model authorization is required). For supported 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(JsonUtils.toJson(result));
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
// Use logging framework to record exceptions
System.err.println("An error occurred while calling the generation service: " + e.getMessage());
}
System.exit(0);
}
}HTTP
curl
If you haven't set environment variables, replace $DASHSCOPE_API_KEY with: the API key from your sub-workspace sk-xxx.
This example uses qwen-plus. You can use other models that are authorized.
curl --location "https://dashscope-intl.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"
}
}'PHP
<?php
$url = "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// If environment variables are not configured, replace the following line with: $apiKey = "sk-xxx" using the API key of your sub-workspace
$apiKey = getenv('DASHSCOPE_API_KEY');
$data = [
// This example uses qwen-plus. You can change the model name as needed (model authorization is required). For supported models, see: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
"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_RETURNTRANSFER, true);
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) {
echo "Response: " . $response;
} else {
echo "Error: " . $httpCode . " - " . $response;
}
curl_close($ch);
?>Node.js
DashScope does not provide an SDK for Node.js environment. To use the OpenAI Node.js SDK, see the OpenAI section of this topic.
import fetch from 'node-fetch';
// If environment variables are not configured, replace the following line with: apiKey = "sk-xxx" using the API key of your sub-workspace
const apiKey = process.env.DASHSCOPE_API_KEY;
const data = {
// This example uses qwen-plus. You can change the model name as needed (model authorization is required). For supported models, see: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
model: "qwen-plus",
input: {
messages: [
{
role: "system",
content: "You are a helpful assistant."
},
{
role: "user",
content: "Who are you?"
}
]
},
parameters: {
result_format: "message"
}
};
fetch('https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
console.log(JSON.stringify(data));
})
.catch(error => {
console.error('Error:', error);
});C#
using System.Net.Http.Headers;
using System.Text;
class Program
{
private static readonly HttpClient httpClient = new HttpClient();
static async Task Main(string[] args)
{
// If environment variables are not configured, replace the following line with: string? apiKey = "sk-xxx" using the API key of your sub-workspace
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;
}
// Set request URL and content
string url = "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// This example uses qwen-plus. You can change the model name as needed (model authorization is required). For supported models, see: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
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 request and obtain response
string result = await SendPostRequestAsync(url, jsonContent, apiKey);
// Output 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"))
{
// Configure request headers
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Send request and obtain response
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// Process response
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return $"Request failed: {response.StatusCode}";
}
}
}
}Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import com.google.gson.Gson;
public class Main {
static class Message {
String role;
String content;
public Message(String role, String content) {
this.role = role;
this.content = content;
}
}
static class Input {
Message[] messages;
public Input(Message[] messages) {
this.messages = messages;
}
}
static class Parameters {
String result_format;
public Parameters(String result_format) {
this.result_format = result_format;
}
}
static class RequestBody {
String model;
Input input;
Parameters parameters;
public RequestBody(String model, Input input, Parameters parameters) {
this.model = model;
this.input = input;
this.parameters = parameters;
}
}
public static void main(String[] args) {
try {
// Create request body
RequestBody requestBody = new RequestBody(
// This example uses qwen-plus. You can change the model name as needed (model authorization is required). For supported models, see: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
"qwen-plus",
new Input(new Message[] {
new Message("system", "You are a helpful assistant."),
new Message("user", "Who are you?")
}),
new Parameters("message")
);
// Convert request body to JSON
Gson gson = new Gson();
String jsonInputString = gson.toJson(requestBody);
// Create a URL object
URL url = new URL("https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// Set request method to POST
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json; utf-8");
httpURLConnection.setRequestProperty("Accept", "application/json");
// If environment variables are not configured, replace the following line with: String apiKey = "sk-xxx" using the sub-workspace's API key
String apiKey = System.getenv("DASHSCOPE_API_KEY");
String auth = "Bearer " + apiKey;
httpURLConnection.setRequestProperty("Authorization", auth);
// Enable input and output streams
httpURLConnection.setDoOutput(true);
// Write request body
try (OutputStream os = httpURLConnection.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// Read response body
try (BufferedReader br = new BufferedReader(new InputStreamReader( StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.exit(0);
}
}
}Error codes
HTTP status code | Code | Message | Description |
400 | InvalidParameter | Model not exist. | The model name you provided is incorrect. |
401 | InvalidApiKey | Invalid API-key provided. Incorrect API key provided. | The API key you provided is incorrect. |
invalid_api_key | |||
403 | Model.AccessDenied | Model access denied. | You are not authorized to call the model. Using the API key of a sub-workspace requires authorization, see Before you begin: Model authorization. |
404 | ModelNotFound | Model can not be found. The model xx does not exist or you do not have access to it. | The model name you provided is incorrect. |
model_not_found | |||
- | NoPermission | You are not authorized to do this operation. Action: sfm:CreateSession;Resource: acs:sfm::xxx:* (1-1). | Use your Alibaba Cloud account to grant the |
- | - | openai.OpenAIError: The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable. | You did not provide an API key. Set your API key as an environment variable or write the API key as plaintext in the code (not recommended). |
- | - | AuthenticationError: No api key provided. You can set by dashscope.api_key = your_api_key in code, or you can set it via environment variable DASHSCOPE_API_KEY= your_api_key. |
FAQ
How to view all my workspaces?
You can view and switch between authorized workspaces in the lower-left corner of the Model Studio console.
How to check whether model authorization is required for the current sub-workspace?
Switch to the sub-workspace and go to the Models page. If Playground for your desired model is disabled and displays the following message, you need to request model authorization from the Alibaba Cloud account owner. If no such message is displayed, you can already use this model.

What to do next
More models | The sample code uses Qwen-Plus as an example. Model Studio also supports other Qwen models. For information about supported models and their API reference, see Models and pricing. |
Advanced features | The sample code only shows basic functionality. To learn more about Qwen API features, see Streaming, JSON mode, Function calling, and other topics under Overview of text generation models. |