O Alibaba Cloud Model Studio suporta chamadas de API para modelos por meio de interfaces compatíveis com OpenAI e do DashScope SDK.
Para chamar a API do Qwen:
Obtenha uma chave de API
Configure seu ambiente de desenvolvimento local
Chame a API do Qwen
Configuração da conta
-
Crie uma conta: Se você ainda não possui uma conta Alibaba Cloud, crie uma.
Se encontrar problemas, consulte Registrar uma conta Alibaba Cloud .
-
Ative o Model Studio: Use sua conta Alibaba Cloud para acessar o Alibaba Cloud Model Studio. Leia e aceite os Termos de Serviço para ativar o service. Se nenhuma caixa de diálogo dos Termos de Serviço aparecer, o service já está ativado.
Obtenha uma chave de API: Acesse a página API Key e clique em Create API key. Em seguida, use a chave de API para chamar os modelos.
Obtenha o ID do seu workspace: Ao chamar modelos na região China (Beijing), Singapore, Japan (Tokyo), Germany (Frankfurt) ou China (Hong Kong), inclua o ID do workspace (WorkspaceId) na Base URL. Encontre-o na página Workspace Management.
Defina sua chave de API como variável de ambiente
Armazene sua chave de API em uma variável de ambiente para evitar codificar credenciais diretamente no código e reduzir riscos de segurança.
Escolha uma linguagem de desenvolvimento
Selecione uma linguagem ou ferramenta para chamar as APIs de modelo.
Python
Etapa 1: Configure o Python
Verifique sua versão do Python
Configure um ambiente virtual (opcional)
Instale o OpenAI Python SDK ou DashScope Python SDK
Etapa 2: Chame a API
OpenAI Python SDK
Com o Python e o OpenAI Python SDK instalados, envie sua primeira solicitação de API.
Crie um arquivo chamado
hello_qwen.py.-
Copie este código para
hello_qwen.pye salve-o.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 URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region. base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1", ) completion = client.chat.completions.create( model="qwen-plus", 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://www.alibabacloud.com/help/model-studio/developer-reference/error-code") -
Execute
python hello_qwen.pyoupython3 hello_qwen.pyna linha de comando.Se você vir
No such file or directory, especifique o caminho completo para o arquivo.A saída é:
I am a large-scale language model developed by Alibaba Cloud. My name is Qwen.
DashScope Python SDK
Com o Python e o DashScope Python SDK instalados, envie sua primeira solicitação de API.
Crie um arquivo chamado
hello_qwen.py.-
Copie este código para
hello_qwen.pye salve-o.import os from dashscope import Generation import dashscope # The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region. dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1' messages = [ {'role': 'system', 'content': 'You are a helpful assistant.'}, {'role': 'user', 'content': 'Who are you?'} ] response = Generation.call( # Singapore, US (Virginia), and China (Beijing) API keys are not interchangeable. Get your API key: https://www.alibabacloud.com/help/model-studio/get-api-key # If the environment variable is not configured, replace with: api_key = "sk-xxx" api_key=os.getenv("DASHSCOPE_API_KEY"), model="qwen-plus", 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://www.alibabacloud.com/help/model-studio/developer-reference/error-code") -
Execute
python hello_qwen.pyoupython3 hello_qwen.pyna linha de comando.NotaExecute o comando deste exemplo a partir do diretório que contém o arquivo Python. Para executá-lo de outro local, especifique o caminho completo.
A saída é:
I am a large-scale language model from Alibaba Cloud. My name is Qwen.
Node.js
Etapa 1: Configure seu ambiente Node.js
Verifique sua instalação do Node.js
Instale o SDK de chamada de modelo
Etapa 2: Chame a API do modelo
Crie um arquivo chamado
hello_qwen.mjs.-
Copie este código para o arquivo.
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 URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region. baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1" } ); const completion = await openai.chat.completions.create({ model: "qwen-plus", 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://www.alibabacloud.com/help/model-studio/developer-reference/error-code"); } -
Execute este comando para enviar uma solicitação de API.
node hello_qwen.mjsNotaExecute este comando a partir do diretório que contém
hello_qwen.mjs. Para executá-lo de qualquer local, especifique o caminho completo para o arquivo.Certifique-se de que o SDK esteja instalado no mesmo diretório que
hello_qwen.mjs. Se estiverem em diretórios diferentes, você veráCannot find package 'openai' imported from xxx.
Após a execução bem-sucedida, a saída é:
I am a language model from Alibaba Cloud. My name is Qwen.
Java
Etapa 1: Configure seu ambiente Java
Verifique sua versão do Java
Instale o SDK de chamada de modelo
Etapa 2: Chame a API
Execute este código para chamar a API do modelo.
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 URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.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()
// Singapore, US (Virginia), and China (Beijing) API keys are not interchangeable. Get your API key: https://www.alibabacloud.com/help/model-studio/get-api-key
// If the environment variable is not configured, replace with: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Model list: 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(result.getOutput().getChoices().get(0).getMessage().getContent());
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("Error message: "+e.getMessage());
System.out.println("See: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
A saída é:
I am a large-scale language model developed by Alibaba Cloud. My name is Qwen.
curl
Chame modelos no Model Studio usando endpoints HTTP compatíveis com OpenAI ou DashScope. Para modelos suportados, consulte Lista de modelos.
Se DASHSCOPE_API_KEY não estiver definido, substitua -H "Authorization: Bearer $DASHSCOPE_API_KEY" por -H "Authorization: Bearer sk-xxx".
HTTP compatível com OpenAI
A URL neste exemplo usa a região Singapore, substitua {WorkspaceId} pelo ID real do seu workspace. As URLs variam por região. Se você usar a região China (Beijing), substitua a URL por https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions.
Envie a solicitação de API:
Após enviar a solicitação de API, você recebe esta resposta:
{
"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
A URL neste exemplo usa a região Singapore, substitua {WorkspaceId} pelo ID real do seu workspace. As URLs variam por região.
Se você usar a região US (Virginia), substitua a URL por
https://dashscope-us.aliyuncs.com/api/v1/services/aigc/text-generation/generation.Se você usar a região China (Beijing), substitua a URL por
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation. Substitua {WorkspaceId} pelo ID do seu workspace.
Envie a solicitação de API:
Após enviar a solicitação de API, você recebe esta resposta:
{
"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"
}
Outras linguagens
Chame a API do modelo
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://www.alibabacloud.com/help/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 URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
req, err := http.NewRequest("POST", "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions", bytes.NewBuffer(jsonData))
if err != nil {
log.Fatal(err)
}
// Set request headers
// Singapore, US (Virginia), and China (Beijing) API keys are not interchangeable. Get your API key: https://www.alibabacloud.com/help/model-studio/get-api-key
// 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 URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
$url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions';
// Singapore, US (Virginia), and China (Beijing) API keys are not interchangeable. Get your API key: https://www.alibabacloud.com/help/model-studio/get-api-key
// 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" => "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)
{
// Singapore, US (Virginia), and China (Beijing) API keys are not interchangeable. Get your API key: https://www.alibabacloud.com/help/model-studio/get-api-key
// If the environment variable is not configured, replace with: string? apiKey = "sk-xxx"
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 URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
string url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions";
// Model list: 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?""
}
]
}";
// 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}";
}
}
}
}Referência da API
Para parâmetros de entrada e saída, consulte Referência da API do Qwen.
Para outros modelos, consulte Lista de modelos.
Perguntas frequentes
Como corrijo o erro Model.AccessDenied após chamar a API do modelo?
R: Este erro ocorre porque você está usando uma chave de API de um sub-workspace. Um sub-workspace não pode acessar aplicativos ou modelos no workspace padrão. Para usar uma chave de API de sub-workspace, o administrador da conta raiz deve conceder autorização de modelo para o sub-workspace correspondente (por exemplo, este tópico usa o modelo Qwen-Plus). Para etapas detalhadas, consulte Configurar permissões de chamada de modelo.
Próximas etapas
Explore mais modelos | O código de exemplo usa |
Aprenda recursos avançados | O código de exemplo cobre apenas perguntas e respostas básicas. Para saber mais sobre a API do Qwen, como saída em streaming, saída estruturada e chamada de função, consulte a Visão geral do modelo de geração de texto. |
Experimente modelos no navegador | Se quiser interagir com modelos por meio de uma caixa de diálogo, como no Qwen Chat, acesse o Playground . |











