全部产品
Search
文档中心

Alibaba Cloud Model Studio:Panggil model di sub-workspace

更新时间:Nov 29, 2025

Topik ini menggunakan Qwen-Plus sebagai contoh untuk menjelaskan cara memanggil model di sub-workspace (workspace non-default) melalui API.

Skenario

  • Kontrol model mana yang dapat dipanggil oleh pengguna tertentu: Kunci API untuk workspace default dapat digunakan untuk memanggil semua model, yang berpotensi memberikan izin berlebihan. Untuk mengontrol model yang dapat dipanggil oleh pengguna Resource Access Management (RAM), Anda dapat menambahkan pengguna tersebut ke sub-workspace, memberikan izin hanya untuk model yang diperlukan, dan mewajibkan pengguna tersebut menggunakan kunci API dari workspace tersebut untuk melakukan panggilan.

  • Pisahkan biaya pemanggilan model: Saat workspace default digunakan untuk beberapa layanan atau skenario, membedakan biaya pemanggilan model untuk masing-masing layanan bisa menjadi sulit. Dengan membuat sub-workspace terpisah untuk setiap layanan atau skenario, Anda dapat menghasilkan tagihan terpisah untuk setiap workspace guna memudahkan pemisahan biaya pemanggilan.

Persiapan

  1. Dapatkan kunci API untuk sub-workspace: Buat kunci API di sub-workspace dan konfigurasikan sebagai variabel lingkungan bernama DASHSCOPE_API_KEY untuk memanggil API model bahasa besar.

  2. Dapatkan izin pemanggilan model (wajib untuk memanggil model standar): Untuk memanggil model standar, seperti qwen-plus, menggunakan kunci API sub-workspace, Anda harus memberikan izin untuk memanggil model ini pada workspace tersebut.

  3. Pilih bahasa pengembangan: Pilih bahasa dan SDK yang Anda kuasai untuk memanggil API model bahasa besar.

Panggil model

Kompatibel dengan OpenAI

Online debugging for OpenAI compatible API
POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions

Wilayah Singapura

base_url untuk panggilan SDK adalah https://dashscope-intl.aliyuncs.com/compatible-mode/v1.

Alamat permintaan HTTP adalah POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions.

Wilayah Beijing

base_url untuk panggilan SDK adalah https://dashscope.aliyuncs.com/compatible-mode/v1.

Alamat permintaan HTTP adalah POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions.

Bagian ini menggunakan input teks sebagai contoh untuk menunjukkan cara memanggil model standar qwen-plus di sub-workspace dengan cara yang kompatibel dengan OpenAI. Satu-satunya perbedaan dibandingkan memanggil model di workspace default adalah Anda harus menggunakan kunci API dari sub-workspace.

Python (SDK)

import os
from openai import OpenAI


client = OpenAI(
    # Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Studio Model Anda: api_key="sk-xxx"
    # Kunci API untuk wilayah Singapura dan Beijing berbeda. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Berikut adalah base_url untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti base_url dengan: https://dashscope.aliyuncs.com/compatible-mode/v1
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",  
)

completion = client.chat.completions.create(
    # Contoh ini menggunakan model 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 kesalahan.
    # extra_body={"enable_thinking": False},
)
print(completion.model_dump_json())

Java (SDK)

// Kode 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. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/model-studio/get-api-key
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // Berikut adalah base_url untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti base_url dengan: https://dashscope.aliyuncs.com/compatible-mode/v1
                .baseUrl("https://dashscope-intl.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 Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Studio Model Anda: apiKey: "sk-xxx",
        // Kunci API untuk wilayah Singapura dan Beijing berbeda. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/model-studio/get-api-key
        apiKey: process.env.DASHSCOPE_API_KEY,
        // Berikut adalah base_url untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti base_url dengan: https://dashscope.aliyuncs.com/compatible-mode/v1
        baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1" 
    }
);

async function main() {
    const completion = await openai.chat.completions.create({
        model: "qwen-plus",  // Contoh ini menggunakan model 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. 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")
		// Berikut adalah base_url untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti base_url dengan: https://dashscope.aliyuncs.com/compatible-mode/v1/
		option.WithBaseURL("https://dashscope-intl.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 Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Studio Model Anda: string? apiKey = "sk-xxx";
        // Kunci API untuk wilayah Singapura dan 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 is not set. Make sure that the 'DASHSCOPE_API_KEY' environment variable is set.");
            return;
        }

        // Setel URL permintaan dan konten.
        // Berikut adalah URL untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti URL dengan: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
        string url = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions";
        // Contoh ini menggunakan model 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?""
                }
            ]
        }";

        // 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"))
        {
            // Setel 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}";
            }
        }
    }
}

PHP (HTTP)

<?php
// Setel URL permintaan.
// Berikut adalah URL untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti URL dengan: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
$url = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Studio Model Anda: $apiKey = "sk-xxx";
// Kunci API untuk wilayah Singapura dan Beijing berbeda. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/model-studio/get-api-key
$apiKey = getenv('DASHSCOPE_API_KEY');
// Setel header permintaan.
$headers = [
    'Authorization: Bearer '.$apiKey,
    'Content-Type: application/json'
];
// Setel isi permintaan.
$data = [
    // Contoh ini menggunakan model 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?"
        ]
    ]
];
// Inisialisasi sesi cURL.
$ch = curl_init();
// Setel opsi cURL.
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);
// Jalankan sesi cURL.
$response = curl_exec($ch);
// Periksa apakah terjadi kesalahan.
if (curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
}
// Tutup resource cURL.
curl_close($ch);
// Cetak respons.
echo $response;
?>

curl (HTTP)

Kunci API untuk wilayah Singapura dan Beijing berbeda. 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://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?"
        }
    ]
}'

DashScope

Wilayah Singapura

Alamat permintaan HTTP adalah:

  • Model bahasa besar Qwen: POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation

  • Model Qwen-VL/OCR: POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

base_url untuk panggilan SDK adalah:

Kode Python

dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

Kode Java

  • Metode 1:

    import com.alibaba.dashscope.protocol.Protocol;
    Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
  • Metode 2:

    import com.alibaba.dashscope.utils.Constants;
    Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";

Wilayah Beijing

Alamat permintaan HTTP adalah:

  • 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.

Bagian ini menggunakan input teks sebagai contoh untuk menunjukkan cara memanggil model standar qwen-plus di sub-workspace menggunakan metode DashScope. Satu-satunya perbedaan dibandingkan memanggil model di workspace default adalah Anda harus menggunakan kunci API dari sub-workspace.

Python (SDK)

import os
import dashscope

dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# Baris sebelumnya menyetel base_url untuk wilayah Singapura. Jika Anda menggunakan model di wilayah 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 Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Studio Model Anda: api_key="sk-xxx"
    # Kunci API untuk wilayah Singapura dan 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 model 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 yang 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://dashscope-intl.aliyuncs.com/api/v1");
        // Baris sebelumnya menyetel base_url untuk wilayah Singapura. Jika Anda menggunakan model di wilayah 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 Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Studio Model Anda: .apiKey("sk-xxx")
                // Kunci API untuk wilayah Singapura dan 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 model 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
// Berikut adalah URL untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti URL dengan: https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
$url = "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// Kunci API untuk wilayah Singapura dan 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 model 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 untuk lingkungan Node.js. Untuk melakukan panggilan dengan OpenAI Node.js SDK, lihat bagian kompatibel dengan OpenAI dalam topik ini.

import fetch from 'node-fetch';
// Kunci API untuk wilayah Singapura dan Beijing berbeda. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/model-studio/get-api-key
$apiKey = getenv('DASHSCOPE_API_KEY');
const apiKey = process.env.DASHSCOPE_API_KEY;

const data = {
    model: "qwen-plus", // Contoh ini menggunakan model 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"
    }
};

fetch('https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
// URL sebelumnya untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti URL dengan: 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);
});

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 Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Studio Model Anda: string? apiKey = "sk-xxx";
        // Kunci API untuk wilayah Singapura dan Beijing berbeda. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/model-studio/get-api-key
$apiKey = getenv('DASHSCOPE_API_KEY');
        string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");

        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("API key is not set. Make sure that the 'DASHSCOPE_API_KEY' environment variable is set.");
            return;
        }

        // Setel URL permintaan dan konten.
        // Berikut adalah URL untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti URL dengan: https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
        string url = "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
        // Contoh ini menggunakan model 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"))
        {
            // Setel 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 panggilan menggunakan OpenAI Go SDK, lihat bagian kompatibel dengan OpenAI dalam topik ini.

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 isi permintaan.
	requestBody := RequestBody{
		// Contoh ini menggunakan model 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.
	// Berikut adalah URL untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti URL dengan: https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
	req, err := http.NewRequest("POST", "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation", bytes.NewBuffer(jsonData))
	if err != nil {
		log.Fatal(err)
	}

	// Setel header permintaan.
	// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Studio Model Anda: apiKey := "sk-xxx"
	// Kunci API untuk wilayah Singapura dan 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 isi respons.
	bodyText, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	// Cetak isi respons.
	fmt.Printf("%s\n", bodyText)
}

curl (HTTP)

Kunci API untuk wilayah Singapura dan Beijing berbeda. Untuk informasi selengkapnya, lihat Dapatkan dan Konfigurasikan Kunci API
Berikut adalah URL untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti URL dengan: https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
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"
    }
}'

Kode kesalahan

Jika pemanggilan model gagal dan mengembalikan pesan kesalahan, lihat Pesan kesalahan untuk menyelesaikan masalah.

Langkah selanjutnya

Lihat model lainnya

Kode contoh menggunakan model qwen-plus sebagai contoh. Studio Model juga mendukung model Qwen lainnya. Untuk informasi tentang model yang didukung dan referensi API-nya, lihat Daftar Model.

Pelajari penggunaan lanjutan

Kode contoh hanya menunjukkan fungsionalitas tanya-jawab dasar. Untuk mempelajari lebih lanjut tentang fitur API Qwen, seperti keluaran streaming, keluaran terstruktur, dan pemanggilan fungsi, lihat Ikhtisar model generasi teks.