Dengan menggunakan Qwen-Plus sebagai contoh, topik ini menjelaskan cara memanggil model melalui API di sub-ruang kerja (ruang kerja non-default).
Skenario
-
Mengontrol model yang dapat dipanggil oleh pengguna tertentu: Kunci API untuk ruang kerja default dapat memanggil semua model, sehingga memberikan izin yang berlebihan. Untuk mengontrol model yang dapat dipanggil oleh pengguna RAM, tambahkan pengguna tersebut ke sub-ruang kerja, berikan izin hanya untuk model yang diperlukan, dan minta mereka menggunakan kunci API dari ruang kerja tersebut.
-
Mengalokasikan biaya pemanggilan model: Penggunaan ruang kerja default untuk beberapa layanan atau skenario menyulitkan pembedaan biaya pemanggilan model masing-masing. Buat sub-ruang kerja terpisah untuk setiap layanan atau skenario guna menghasilkan tagihan terpisah dan menyederhanakan alokasi biaya.
Prasyarat
-
Dapatkan kunci API untuk sub-ruang kerja: Untuk memanggil API model besar, buat kunci API di sub-ruang kerja dan tetapkan sebagai variabel lingkungan bernama
DASHSCOPE_API_KEY. -
Tetapkan izin pemanggilan model (wajib untuk model standar): Untuk memanggil standard model, seperti
qwen-plus, dengan kunci API dari sub-ruang kerja, Anda harus terlebih dahulu menetapkan izin pemanggilan model untuk sub-ruang kerja tersebut. -
Pilih bahasa pengembangan: Pilih bahasa dan SDK yang Anda kuasai untuk memanggil API model besar.
Memanggil model
OpenAI
Singapore
SDK base_url: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
HTTP endpoint: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions
China (Beijing)
SDK base_url: https://dashscope.aliyuncs.com/compatible-mode/v1
HTTP endpoint: POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
Contoh ini menunjukkan cara memanggil model standar qwen-plus di sub-ruang kerja menggunakan metode kompatibel OpenAI. Berbeda dengan pemanggilan di ruang kerja default, Anda harus menggunakan kunci API dari sub-ruang kerja.
Python (SDK)
import os
from openai import OpenAI
client = OpenAI(
# Jika variabel lingkungan belum ditetapkan, ganti baris berikut dengan Kunci API Studio Model Anda: api_key="sk-xxx"
# Kunci API untuk wilayah Singapura dan Beijing berbeda. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# base_url ini untuk wilayah Singapura. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. Untuk model di wilayah Beijing, gunakan: 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(
# Contoh ini menggunakan qwen-plus. Anda dapat menggantinya dengan nama model lain sesuai kebutuhan. Untuk daftar model, lihat: 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?"},
],
# Parameter enable_thinking mengontrol proses berpikir untuk model Qwen3 (default True untuk versi open source, False untuk versi komersial).
# Saat menggunakan model Qwen3 open source tanpa mengaktifkan keluaran streaming, hapus komentar baris berikut untuk menghindari error.
# extra_body={"enable_thinking": False},
)
print(completion.model_dump_json())
Java (SDK)
// Contoh ini menggunakan 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()
// Kunci API untuk wilayah Singapura dan Beijing berbeda. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// base_url ini untuk wilayah Singapura. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. Untuk model di wilayah Beijing, gunakan: 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();
}
}
}
Node.js (SDK)
import OpenAI from "openai";
const openai = new OpenAI(
{
// Jika variabel lingkungan belum ditetapkan, ganti baris berikut dengan Kunci API Studio Model Anda: apiKey: "sk-xxx",
// Kunci API untuk wilayah Singapura dan Beijing berbeda. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/model-studio/get-api-key
apiKey: process.env.DASHSCOPE_API_KEY,
// baseURL ini untuk wilayah Singapura. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. Untuk model di wilayah Beijing, gunakan: 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", // Contoh ini menggunakan qwen-plus. Anda dapat menggantinya dengan nama model lain sesuai kebutuhan. Untuk daftar model, lihat: 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();
Go (SDK)
package main
import (
"context"
"os"
"github.com/openai/openai-go"
"github.com/openai/openai-go/option"
)
func main() {
client := openai.NewClient(
// Kunci API untuk wilayah Singapura dan Beijing berbeda. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/model-studio/get-api-key
option.WithAPIKey(os.Getenv("DASHSCOPE_API_KEY")), // defaults to os.LookupEnv("OPENAI_API_KEY")
// URL dasar ini untuk wilayah Singapura. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. Untuk model di wilayah Beijing, gunakan: 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)
}
C# (HTTP)
using System.Net.Http.Headers;
using System.Text;
class Program
{
private static readonly HttpClient httpClient = new HttpClient();
static async Task Main(string[] args)
{
// Jika variabel lingkungan belum ditetapkan, ganti baris berikut dengan Kunci API Studio Model Anda: string? apiKey = "sk-xxx";
// Kunci API untuk wilayah Singapura dan Beijing berbeda. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. Untuk mendapatkan kunci API, lihat 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;
}
// URL ini untuk wilayah Singapura. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. Untuk model di wilayah Beijing, gunakan: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
string url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions";
// Contoh ini menggunakan qwen-plus. Anda dapat menggantinya dengan nama model lain sesuai kebutuhan. Untuk daftar model, lihat: 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}";
}
}
}
}
PHP (HTTP)
<?php
// URL ini untuk wilayah Singapura. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. Untuk model di wilayah Beijing, gunakan: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
$url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions';
// Jika variabel lingkungan belum ditetapkan, ganti baris berikut dengan Kunci API Studio Model Anda: $apiKey = "sk-xxx";
// Kunci API untuk wilayah Singapura dan Beijing berbeda. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/model-studio/get-api-key
$apiKey = getenv('DASHSCOPE_API_KEY');
$headers = [
'Authorization: Bearer '.$apiKey,
'Content-Type: application/json'
];
$data = [
// Contoh ini menggunakan qwen-plus. Anda dapat menggantinya dengan nama model lain sesuai kebutuhan. Untuk daftar model, lihat: 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;
?>
curl (HTTP)
Kunci API untuk wilayah Singapura dan Beijing berbeda. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/model-studio/get-api-key. Jika Anda menggunakan model di wilayah Beijing, ganti URL dengan: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
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
Singapore region
HTTP endpoint:
-
Model bahasa besar Qwen:
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation -
Model Qwen-VL/OCR:
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
base_url untuk panggilan SDK adalah:
Python
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
Java
-
Metode 1:
import com.alibaba.dashscope.protocol.Protocol; Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"); -
Metode 2:
import com.alibaba.dashscope.utils.Constants; Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
China (Beijing)
HTTP endpoint:
-
Model bahasa besar Qwen:
POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation -
Model Qwen-VL/Audio:
POST https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
Anda tidak perlu mengonfigurasi base_url untuk panggilan SDK.
Contoh ini menunjukkan cara memanggil model qwen-plus di sub-ruang kerja menggunakan DashScope. Perbedaan utama dibandingkan penggunaan ruang kerja default adalah bahwa Anda harus menggunakan kunci API untuk sub-ruang kerja.
Python (SDK)
import os
import dashscope
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# Baris sebelumnya menetapkan base_url untuk wilayah Singapura. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. Jika Anda menggunakan model di wilayah China (Beijing), ganti base_url dengan: 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(
# Jika variabel lingkungan belum ditetapkan, ganti baris berikut dengan Kunci API Studio Model Anda: api_key="sk-xxx"
# Kunci API untuk wilayah Singapura dan China (Beijing) berbeda. Untuk mendapatkan kunci API, lihat: https://www.alibabacloud.com/help/model-studio/get-api-key
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen-plus", # Contoh ini menggunakan qwen-plus. Anda dapat menggantinya dengan nama model lain sesuai kebutuhan. Untuk daftar model, lihat: https://www.alibabacloud.com/help/model-studio/getting-started/models
messages=messages,
result_format='message'
)
print(response)
Java (SDK)
// Disarankan menggunakan DashScope SDK v2.12.0 atau lebih baru.
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");
// Baris sebelumnya menetapkan base_url untuk wilayah Singapura. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. Jika Anda menggunakan model di wilayah China (Beijing), ganti base_url dengan: 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()
// Jika variabel lingkungan belum ditetapkan, ganti baris berikut dengan Kunci API Studio Model Anda: .apiKey("sk-xxx")
// Kunci API untuk wilayah Singapura dan China (Beijing) berbeda. Untuk mendapatkan kunci API, lihat: https://www.alibabacloud.com/help/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Contoh ini menggunakan qwen-plus. Anda dapat menggantinya dengan nama model lain sesuai kebutuhan. Untuk daftar model, lihat: 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) {
// Gunakan framework logging untuk mencatat exception.
System.err.println("An error occurred while calling the generation service: " + e.getMessage());
}
System.exit(0);
}
}
PHP (HTTP)
<?php
// URL berikut untuk wilayah Singapura. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. Jika Anda menggunakan model di wilayah China (Beijing), ganti URL dengan: 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";
// Kunci API untuk wilayah Singapura dan China (Beijing) berbeda. Untuk mendapatkan kunci API, lihat: https://www.alibabacloud.com/help/model-studio/get-api-key
$apiKey = getenv('DASHSCOPE_API_KEY');
$data = [
// Contoh ini menggunakan qwen-plus. Anda dapat menggantinya dengan nama model lain sesuai kebutuhan. Untuk daftar model, lihat: 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);
?>
Node.js (HTTP)
DashScope tidak menyediakan SDK Node.js. Untuk melakukan pemanggilan menggunakan OpenAI Node.js SDK, lihat bagian OpenAI-compatible.
import fetch from 'node-fetch';
// Kunci API untuk wilayah Singapura dan China (Beijing) berbeda. Untuk mendapatkan kunci API, lihat: https://www.alibabacloud.com/help/model-studio/get-api-key
const apiKey = process.env.DASHSCOPE_API_KEY;
const data = {
model: "qwen-plus", // Contoh ini menggunakan qwen-plus. Anda dapat menggantinya dengan nama model lain sesuai kebutuhan. Untuk daftar model, lihat: 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"
}
};
// URL berikut untuk wilayah Singapura. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. Jika Anda menggunakan model di wilayah China (Beijing), ganti URL dengan: 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);
});
C# (HTTP)
using System.Net.Http.Headers;
using System.Text;
class Program
{
private static readonly HttpClient httpClient = new HttpClient();
static async Task Main(string[] args)
{
// Jika variabel lingkungan belum ditetapkan, ganti baris berikut dengan Kunci API Studio Model Anda: string? apiKey = "sk-xxx";
// Kunci API untuk wilayah Singapura dan China (Beijing) berbeda. Untuk mendapatkan kunci API, lihat: 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;
}
// Tetapkan URL permintaan dan konten.
// URL berikut untuk wilayah Singapura. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. Jika Anda menggunakan model di wilayah China (Beijing), ganti URL dengan: 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";
// Contoh ini menggunakan qwen-plus. Anda dapat menggantinya dengan nama model lain sesuai kebutuhan. Untuk daftar model, lihat: 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""
}
}";
// Kirim permintaan dan dapatkan respons.
string result = await SendPostRequestAsync(url, jsonContent, apiKey);
// Cetak hasilnya.
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"))
{
// Tetapkan header permintaan.
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Kirim permintaan dan dapatkan respons.
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// Proses respons.
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return $"Request failed: {response.StatusCode}";
}
}
}
}
Go (HTTP)
DashScope tidak menyediakan SDK Go. Untuk melakukan pemanggilan menggunakan OpenAI Go SDK, lihat bagian OpenAI-compatible.
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() {
// Buat klien HTTP.
client := &http.Client{}
// Bangun badan permintaan.
requestBody := RequestBody{
// Contoh ini menggunakan qwen-plus. Anda dapat menggantinya dengan nama model lain sesuai kebutuhan. Untuk daftar model, lihat: 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)
}
// Buat permintaan POST.
// URL berikut untuk wilayah Singapura. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. Jika Anda menggunakan model di wilayah China (Beijing), ganti URL dengan: 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)
}
// Tetapkan header permintaan.
// Jika variabel lingkungan belum ditetapkan, ganti baris berikut dengan Kunci API Studio Model Anda: apiKey := "sk-xxx"
// Kunci API untuk wilayah Singapura dan China (Beijing) berbeda. Untuk mendapatkan kunci API, lihat: 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")
// Kirim permintaan.
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// Baca badan respons.
bodyText, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
// Cetak konten respons.
fmt.Printf("%s\n", bodyText)
}
curl (HTTP)
Kunci API untuk wilayah Singapura dan China (Beijing) berbeda. Dapatkan kunci API.
URL berikut untuk wilayah Singapura. Ganti WorkspaceId dengan ID ruang kerja aktual Anda. Jika Anda menggunakan model di wilayah China (Beijing), ganti URL dengan: https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
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"
}
}'
Kode error
Jika pemanggilan model mengembalikan error, lihat Pesan Error.
Langkah selanjutnya
|
Jelajahi lebih banyak model |
Kode contoh menggunakan model |
|
Penggunaan lanjutan |
Kode contoh menunjukkan skenario tanya jawab dasar. Ikhtisar generasi teks mencakup fitur lanjutan API Qwen, termasuk keluaran streaming, output terstruktur, dan pemanggilan fungsi. |