Este tópico explica como invocar um modelo via API em um sub-workspace (workspace não padrão), usando o Qwen-Plus como exemplo.
Cenários
- Controlar quais modelos usuários específicos podem chamar: A chave de API do workspace padrão acessa todos os modelos, o que concede permissões excessivas. Para controlar quais modelos um usuário RAM pode chamar, adicione-o a um sub-workspace, conceda permissões apenas para os modelos necessários e use a chave de API desse workspace.
- Alocar custos de chamadas de modelo: Usar o workspace padrão para múltiplos serviços ou cenários dificulta a distinção dos custos de chamada de cada um. Crie um sub-workspace separado para cada serviço ou cenário para gerar faturas separadas e simplificar a alocação de custos.
Pré-requisitos
-
Obtenha a chave de API do sub-workspace: Para chamar APIs de modelos grandes, crie uma chave de API no sub-workspace e defina-a como variável de ambiente chamada
DASHSCOPE_API_KEY. -
Configure as permissões de chamada de modelo (obrigatório para modelos padrão): Para chamar um modelo padrão, como
qwen-plus, com a chave de API de um sub-workspace, você deve primeiro definir as permissões de chamada de modelo para esse sub-workspace.Nota: Modelos que você ajusta finamente e implanta no Alibaba Cloud Model Studio não exigem permissões de chamada de modelo . No entanto, você só pode chamar esses modelos com a chave de API do workspace onde residem.
- Selecione uma linguagem de desenvolvimento: Escolha uma linguagem e um SDK conhecidos para chamar as APIs de modelos grandes.
Chamada do modelo
OpenAI
- Beijing
- Singapore
SDK
base_url: https://dashscope.aliyuncs.com/compatible-mode/v1HTTP endpoint: POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completionsSDK
base_url: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1HTTP endpoint: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions- Singapore
- China (Beijing)
SDK
base_url: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1HTTP endpoint: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completionsSDK
base_url: https://dashscope.aliyuncs.com/compatible-mode/v1HTTP endpoint: POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completionsqwen-plus em um sub-workspace usando o método compatível com OpenAI. Diferentemente das chamadas no workspace padrão, você deve usar a chave de API do sub-workspace.
Para chamar um modelo ajustado finamente no Alibaba Cloud Model Studio: Você só pode chamar o modelo via DashScope . O método compatível com OpenAI não é suportado.
Python (SDK)
Copy
import os
from openai import OpenAI
client = OpenAI(
# If the environment variable is not set, replace the following line with your Model Studio API key: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
# 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?"},
]
)
print(completion.model_dump_json())
- Python (SDK)
- Java (SDK)
- Node.js (SDK)
- Go (SDK)
- C# (HTTP)
- PHP (HTTP)
- curl (HTTP)
Copy
import os
from openai import OpenAI
client = OpenAI(
# If the environment variable is not set, replace the following line with your Model Studio API key: api_key="sk-xxx"
# The API keys for the Singapore and Beijing regions are different. Replace WorkspaceId with your actual workspace ID. To get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# This base_url is for the Singapore region. Replace WorkspaceId with your actual workspace ID. For models in the Beijing region, use: https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
# This example uses qwen-plus. You can replace it with another model name as needed. For a list of models, see: https://www.alibabacloud.com/help/model-studio/getting-started/models
model="qwen-plus",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Who are you?"},
],
# The enable_thinking parameter controls the thinking process for Qwen3 models (default is True for the open source version, False for the commercial version).
# When using an open source Qwen3 model without enabling streaming output, uncomment the following line to avoid errors.
# extra_body={"enable_thinking": False},
)
print(completion.model_dump_json())
Copy
// This example uses OpenAI SDK v2.6.0.
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
public class Main {
public static void main(String[] args) {
OpenAIClient client = OpenAIOkHttpClient.builder()
// The API keys for the Singapore and Beijing regions are different. Replace WorkspaceId with your actual workspace ID. To get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// This base_url is for the Singapore region. Replace WorkspaceId with your actual workspace ID. For models in the Beijing region, use: https://dashscope.aliyuncs.com/compatible-mode/v1
.baseUrl("https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1")
.build();
ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
.addUserMessage("Who are you")
.model("qwen-plus")
.build();
try {
ChatCompletion chatCompletion = client.chat().completions().create(params);
System.out.println(chatCompletion);
} catch (Exception e) {
System.err.println("Error occurred: " + e.getMessage());
e.printStackTrace();
}
}
}
Copy
import OpenAI from "openai";
const openai = new OpenAI(
{
// If the environment variable is not set, replace the following line with your Model Studio API key: apiKey: "sk-xxx",
// The API keys for the Singapore and Beijing regions are different. Replace WorkspaceId with your actual workspace ID. To get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
apiKey: process.env.DASHSCOPE_API_KEY,
// This baseURL is for the Singapore region. Replace WorkspaceId with your actual workspace ID. For models in the Beijing region, use: https://dashscope.aliyuncs.com/compatible-mode/v1
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.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 replace it with another model name as needed. For a list of models, see: https://www.alibabacloud.com/help/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();
Copy
package main
import (
"context"
"os"
"github.com/openai/openai-go"
"github.com/openai/openai-go/option"
)
func main() {
client := openai.NewClient(
// The API keys for the Singapore and Beijing regions are different. Replace WorkspaceId with your actual workspace ID. To get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
option.WithAPIKey(os.Getenv("DASHSCOPE_API_KEY")), // defaults to os.LookupEnv("OPENAI_API_KEY")
// This base URL is for the Singapore region. Replace WorkspaceId with your actual workspace ID. For models in the Beijing region, use: https://dashscope.aliyuncs.com/compatible-mode/v1/
option.WithBaseURL("https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/"),
)
chatCompletion, err := client.Chat.Completions.New(
context.TODO(), openai.ChatCompletionNewParams{
Messages: openai.F(
[]openai.ChatCompletionMessageParamUnion{
openai.UserMessage("Who are you"),
},
),
Model: openai.F("qwen-plus"),
},
)
if err != nil {
panic(err.Error())
}
println(chatCompletion.Choices[0].Message.Content)
}
Copy
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 set, replace the following line with your Model Studio API key: string? apiKey = "sk-xxx";
// The API keys for the Singapore and Beijing regions are different. Replace WorkspaceId with your actual workspace ID. To get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("API key is not set. Ensure the 'DASHSCOPE_API_KEY' environment variable is set.");
return;
}
// This URL is for the Singapore region. Replace WorkspaceId with your actual workspace ID. For models in the Beijing region, use: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
string url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions";
// This example uses qwen-plus. You can replace it with another model name as needed. For a list of models, see: https://www.alibabacloud.com/help/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?""
}
]
}";
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 $"Request failed: {response.StatusCode}";
}
}
}
}
Copy
<?php
// This URL is for the Singapore region. Replace WorkspaceId with your actual workspace ID. For models in the Beijing region, use: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
$url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions';
// If the environment variable is not set, replace the following line with your Model Studio API key: $apiKey = "sk-xxx";
// The API keys for the Singapore and Beijing regions are different. Replace WorkspaceId with your actual workspace ID. To get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
$apiKey = getenv('DASHSCOPE_API_KEY');
$headers = [
'Authorization: Bearer '.$apiKey,
'Content-Type: application/json'
];
$data = [
// This example uses qwen-plus. You can replace it with another model name as needed. For a list of models, see: https://www.alibabacloud.com/help/model-studio/getting-started/models
"model" => "qwen-plus",
"messages" => [
[
"role" => "system",
"content" => "You are a helpful assistant."
],
[
"role" => "user",
"content" => "Who are you?"
]
]
];
$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_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
}
curl_close($ch);
echo $response;
?>
As chaves de API das regiões de Singapura e Pequim são diferentes. Substitua WorkspaceId pelo ID real do seu workspace. Para obter uma chave de API, consulte https://www.alibabacloud.com/help/model-studio/get-api-key. Se você usar um modelo na região de Pequim, substitua a URL por: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
Copy
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.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?"
}
]
}'
DashScope
- China (Beijing)
- Singapore region
HTTP endpoint:
- Modelos de linguagem grande Qwen:
POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation - Modelos Qwen-VL/Audio:
POST https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
base_url para chamadas via SDK.HTTP endpoint:
- Modelos de linguagem grande Qwen:
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation - Modelos Qwen-VL/OCR:
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
base_url para chamadas via SDK é:- Python
- Java
Copy
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
- Método 1:
Copy
import com.alibaba.dashscope.protocol.Protocol;
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
- Método 2:
Copy
import com.alibaba.dashscope.utils.Constants;
Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
- Singapore region
- China (Beijing)
HTTP endpoint:
- Modelos de linguagem grande Qwen:
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation - Modelos Qwen-VL/OCR:
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
base_url para chamadas via SDK é:- Python
- Java
Copy
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
- Método 1:
Copy
import com.alibaba.dashscope.protocol.Protocol;
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
- Método 2:
Copy
import com.alibaba.dashscope.utils.Constants;
Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
HTTP endpoint:
- Modelos de linguagem grande Qwen:
POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation - Modelos Qwen-VL/Audio:
POST https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
base_url para chamadas via SDK.qwen-plus em um sub-workspace usando DashScope. A principal diferença em relação ao uso do workspace padrão é que você deve usar a chave de API do sub-workspace.
- Python (SDK)
- Java (SDK)
- PHP (HTTP)
- Node.js (HTTP)
- C# (HTTP)
- Go (HTTP)
- curl (HTTP)
Copy
import os
import dashscope
messages = [
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': 'Who are you?'}
]
response = dashscope.Generation.call(
# If the environment variable is not set, replace the following line with your Model Studio API key: api_key="sk-xxx"
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen-plus", # This example uses qwen-plus. You can replace it with another model name as needed. For a list of models, see: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
messages=messages,
result_format='message'
)
print(response)
Copy
// DashScope SDK v2.12.0 or later is recommended.
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;
public class Main {
public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
Generation gen = new Generation();
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 set, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// This example uses qwen-plus. You can replace it with another model name as needed. 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(JsonUtils.toJson(result));
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
// Use a logging framework to record the exception.
System.err.println("An error occurred while calling the generation service: " + e.getMessage());
}
System.exit(0);
}
}
Copy
<?php
$url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
$apiKey = getenv('DASHSCOPE_API_KEY');
$data = [
// This example uses qwen-plus. You can replace it with another model name as needed. For a list of 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);
?>
O DashScope não fornece um SDK para Node.js. Para fazer chamadas usando o SDK OpenAI para Node.js, consulte a seção Compatível com OpenAI.
Copy
import fetch from 'node-fetch';
const apiKey = process.env.DASHSCOPE_API_KEY;
const data = {
model: "qwen-plus", // This example uses qwen-plus. You can replace it with another model name as needed. For a list of models, see: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
input: {
messages: [
{
role: "system",
content: "You are a helpful assistant."
},
{
role: "user",
content: "Who are you?"
}
]
},
parameters: {
result_format: "message"
}
};
fetch('https://dashscope.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);
});
Copy
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 set, replace the following line with your Model Studio API key: string? apiKey = "sk-xxx";
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("API key not set. Ensure the 'DASHSCOPE_API_KEY' environment variable is set.");
return;
}
// Set the request URL and content.
string url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// This example uses qwen-plus. You can replace it with another model name as needed. For a list of 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 the request and get the response.
string result = await SendPostRequestAsync(url, jsonContent, apiKey);
// Print 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 the 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);
// Process the response.
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return $"Request failed: {response.StatusCode}";
}
}
}
}
O DashScope não fornece um SDK para Go. Para fazer chamadas usando o SDK OpenAI para Go, consulte a seção Compatível com OpenAI.
Copy
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type Input struct {
Messages []Message `json:"messages"`
}
type Parameters struct {
ResultFormat string `json:"result_format"`
}
type RequestBody struct {
Model string `json:"model"`
Input Input `json:"input"`
Parameters Parameters `json:"parameters"`
}
func main() {
// Create an HTTP client.
client := &http.Client{}
// Build the request body.
requestBody := RequestBody{
// This example uses qwen-plus. You can replace it with another model name as needed. For a list of models, see: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
Model: "qwen-plus",
Input: Input{
Messages: []Message{
{
Role: "system",
Content: "You are a helpful assistant.",
},
{
Role: "user",
Content: "Who are you?",
},
},
},
Parameters: Parameters{
ResultFormat: "message",
},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
log.Fatal(err)
}
// Create a POST request.
req, err := http.NewRequest("POST", "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation", bytes.NewBuffer(jsonData))
if err != nil {
log.Fatal(err)
}
// Set the request headers.
// If the environment variable is not set, replace the following line with your Model Studio 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 response content.
fmt.Printf("%s\n", bodyText)
}
Copy
curl --location "https://dashscope.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"
}
}'
- Python (SDK)
- Java (SDK)
- PHP (HTTP)
- Node.js (HTTP)
- C# (HTTP)
- Go (HTTP)
- curl (HTTP)
Copy
import os
import dashscope
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# The preceding line sets the base_url for the Singapore region. Replace WorkspaceId with your actual workspace ID. If you use a model in the China (Beijing) region, replace the base_url with: https://dashscope.aliyuncs.com/api/v1
messages = [
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': 'Who are you?'}
]
response = dashscope.Generation.call(
# If the environment variable is not set, replace the following line with your Model Studio API key: api_key="sk-xxx"
# The API keys for the Singapore and China (Beijing) regions are different. To get an API key, see: https://www.alibabacloud.com/help/model-studio/get-api-key
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen-plus", # This example uses qwen-plus. You can replace it with another model name as needed. For a list of models, see: https://www.alibabacloud.com/help/model-studio/getting-started/models
messages=messages,
result_format='message'
)
print(response)
Copy
// DashScope SDK v2.12.0 or later is recommended.
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://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
// The preceding line sets the base_url for the Singapore region. Replace WorkspaceId with your actual workspace ID. If you use a model in the China (Beijing) region, replace the base_url with: https://dashscope.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 set, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
// The API keys for the Singapore and China (Beijing) regions are different. To get an API key, see: https://www.alibabacloud.com/help/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// This example uses qwen-plus. You can replace it with another model name as needed. For a list of models, see: https://www.alibabacloud.com/help/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 a logging framework to record the exception.
System.err.println("An error occurred while calling the generation service: " + e.getMessage());
}
System.exit(0);
}
}
Copy
<?php
// The following URL is for the Singapore region. Replace WorkspaceId with your actual workspace ID. If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
$url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// The API keys for the Singapore and China (Beijing) regions are different. To get an API key, see: https://www.alibabacloud.com/help/model-studio/get-api-key
$apiKey = getenv('DASHSCOPE_API_KEY');
$data = [
// This example uses qwen-plus. You can replace it with another model name as needed. For a list of models, see: https://www.alibabacloud.com/help/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);
?>
O DashScope não fornece um SDK para Node.js. Para fazer chamadas usando o SDK OpenAI para Node.js, consulte a seção Compatível com OpenAI.
Copy
import fetch from 'node-fetch';
// The API keys for the Singapore and China (Beijing) regions are different. To get an API key, see: https://www.alibabacloud.com/help/model-studio/get-api-key
const apiKey = process.env.DASHSCOPE_API_KEY;
const data = {
model: "qwen-plus", // This example uses qwen-plus. You can replace it with another model name as needed. For a list of models, see: https://www.alibabacloud.com/help/model-studio/getting-started/models
input: {
messages: [
{
role: "system",
content: "You are a helpful assistant."
},
{
role: "user",
content: "Who are you?"
}
]
},
parameters: {
result_format: "message"
}
};
// The following URL is for the Singapore region. Replace WorkspaceId with your actual workspace ID. If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
fetch('https://{WorkspaceId}.ap-southeast-1.maas.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);
});
Copy
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 set, replace the following line with your Model Studio API key: string? apiKey = "sk-xxx";
// The API keys for the Singapore and China (Beijing) regions are different. To get an API key, see: https://www.alibabacloud.com/help/model-studio/get-api-key
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("API key not set. Ensure the 'DASHSCOPE_API_KEY' environment variable is set.");
return;
}
// Set the request URL and content.
// The following URL is for the Singapore region. Replace WorkspaceId with your actual workspace ID. If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
string url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// This example uses qwen-plus. You can replace it with another model name as needed. For a list of models, see: https://www.alibabacloud.com/help/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 the request and get the response.
string result = await SendPostRequestAsync(url, jsonContent, apiKey);
// Print 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 the 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);
// Process the response.
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return $"Request failed: {response.StatusCode}";
}
}
}
}
O DashScope não fornece um SDK para Go. Para fazer chamadas usando o SDK OpenAI para Go, consulte a seção Compatível com OpenAI.
Copy
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type Input struct {
Messages []Message `json:"messages"`
}
type Parameters struct {
ResultFormat string `json:"result_format"`
}
type RequestBody struct {
Model string `json:"model"`
Input Input `json:"input"`
Parameters Parameters `json:"parameters"`
}
func main() {
// Create an HTTP client.
client := &http.Client{}
// Build the request body.
requestBody := RequestBody{
// This example uses qwen-plus. You can replace it with another model name as needed. For a list of models, see: https://www.alibabacloud.com/help/model-studio/getting-started/models
Model: "qwen-plus",
Input: Input{
Messages: []Message{
{
Role: "system",
Content: "You are a helpful assistant.",
},
{
Role: "user",
Content: "Who are you?",
},
},
},
Parameters: Parameters{
ResultFormat: "message",
},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
log.Fatal(err)
}
// Create a POST request.
// The following URL is for the Singapore region. Replace WorkspaceId with your actual workspace ID. If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
req, err := http.NewRequest("POST", "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation", bytes.NewBuffer(jsonData))
if err != nil {
log.Fatal(err)
}
// Set the request headers.
// If the environment variable is not set, replace the following line with your Model Studio API key: apiKey := "sk-xxx"
// The API keys for the Singapore and China (Beijing) regions are different. To get an API key, see: https://www.alibabacloud.com/help/model-studio/get-api-key
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 content.
fmt.Printf("%s\n", bodyText)
}
As chaves de API das regiões de Singapura e China (Pequim) são diferentes. Obtenha uma chave de API .
A URL abaixo refere-se à região de Singapura. Substitua WorkspaceId pelo ID real do seu workspace. Se você usar um modelo na região da China (Pequim), substitua a URL por: https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
Copy
curl --location "https://{WorkspaceId}.ap-southeast-1.maas.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"
}
}'
Códigos de erro
Se uma chamada de modelo retornar um erro, consulte Mensagens de erro.Próximos passos
Explore mais modelos | O código de exemplo usa o modelo |
Uso avançado | O código de exemplo demonstra um cenário básico de perguntas e respostas. A Visão geral da geração de texto aborda recursos avançados da API Qwen, incluindo saída em streaming, saída estruturada e chamada de função. |