全部产品
Search
文档中心

Alibaba Cloud Model Studio:Ikhtisar

更新时间:Dec 12, 2025

Model generasi teks menghasilkan teks yang logis dan koheren berdasarkan prompt input.

Input untuk model generasi teks dapat berupa kata kunci sederhana, ringkasan satu kalimat, atau instruksi dan konteks yang lebih kompleks. Model ini mempelajari pola bahasa dengan menganalisis data dalam jumlah besar dan memiliki berbagai aplikasi:

  • Pembuatan konten: Menghasilkan laporan berita, deskripsi produk, dan skrip video pendek.

  • Layanan pelanggan: Menjalankan chatbot untuk memberikan dukungan 24/7 dan menjawab pertanyaan umum.

  • Terjemahan teks: Melakukan terjemahan lintas bahasa yang cepat dan akurat.

  • Generasi ringkasan: Mengekstraksi poin-poin utama dari artikel panjang, laporan, dan email.

  • Penyusunan dokumen hukum: Menghasilkan kerangka dasar untuk templat kontrak dan opini hukum.

Pemilihan model

Wilayah layanan

Alibaba Cloud Model Studio menyediakan layanan model di wilayah Singapura dan Tiongkok (Beijing). Memanggil layanan dari wilayah terdekat dapat mengurangi latensi jaringan.

Model tujuan umum

Qwen-Max, Qwen-Plus, dan Qwen-Flash semuanya telah ditingkatkan ke seri Qwen3 dan kompatibel dengan metode pemanggilan OpenAI. Model-model ini cocok untuk berbagai skenario, seperti layanan pelanggan cerdas, pembuatan teks, penyempurnaan konten, dan ringkasan.

  • Qwen-Plus: Menyeimbangkan performa, kecepatan, dan biaya. Ini adalah pilihan yang direkomendasikan untuk sebagian besar skenario.

  • Qwen-Max: Model dengan performa terbaik dalam seri Qwen. Cocok untuk menangani tugas kompleks multi-langkah.

  • Qwen-Flash: Model tercepat dan paling hemat biaya dalam seri Qwen. Cocok untuk menjalankan pekerjaan sederhana.

Model khusus skenario

Untuk kebutuhan bisnis tertentu, Model Studio menawarkan berbagai model khusus dan teroptimalkan. Model-model ini mencakup domain seperti kemampuan kode, konteks panjang, terjemahan, penambangan data, pengenalan niat, asumsi peran, dan penelitian mendalam.

Model multimodal

  • Qwen-VL (Teks + Citra → Teks): Menyediakan kemampuan pemahaman citra. Mendukung tugas seperti Pengenalan karakter optik (OCR), penalaran visual, dan pemahaman teks-citra.

  • Qwen-Omni (Omni-modal → Teks + Audio): Mendukung berbagai input data, termasuk video, audio, citra, dan teks. Menghasilkan output teks dan ucapan untuk menangani tugas lintas-modal yang kompleks.

  • Speech recognition model (Audio → Teks): Mengenali dan mentranskripsikan konten ucapan dalam audio. Mendukung bahasa seperti Tionghoa (termasuk Kanton dan dialek lainnya), Inggris, Jepang, dan Korea.

Model pihak ketiga

Model Studio menyediakan model bahasa besar (LLM) pihak ketiga terkenal, termasuk DeepSeek dan Kimi. Untuk daftar lengkap model, lihat Generasi teks - Model pihak ketiga.

Konsep inti

Input untuk model generasi teks adalah prompt, yang terdiri dari satu atau beberapa objek message. Setiap message terdiri dari role dan content:

  • System message: Menetapkan peran yang harus dimainkan model atau instruksi yang harus diikuti. Jika tidak ditentukan, nilai default-nya adalah "You are a helpful assistant."

  • User message: Pertanyaan atau instruksi dari pengguna kepada model.

  • Assistant message: Konten respons dari model.

Saat Anda memanggil model, Anda dapat membuat array messages dengan objek-objek message ini. Permintaan tipikal terdiri dari message system yang menetapkan kode etik dan message user yang memberikan instruksi pengguna.

system bersifat opsional. Anda dapat menggunakan message ini untuk menetapkan peran dan kode etik model guna mencapai output yang lebih stabil dan konsisten.
[
    {"role": "system", "content": "You are a helpful assistant. You need to provide accurate, efficient, and insightful responses, and be ready to help users with various tasks and questions."},
    {"role": "user", "content": "Who are you?"}
]

Objek respons output berisi message assistant dari model.

{
    "role": "assistant",
    "content": "Hello! I am Qwen, an extra-large language model developed by the Tongyi Lab of Alibaba Group. I can help you answer questions, create text, perform logical reasoning, and write code. I can understand and generate multiple languages, and I support multi-turn conversations and complex task processing. If you need any help, just let me know!"
}

Memulai

Prasyarat: Anda telah membuat Kunci API dan mengekspor Kunci API sebagai Variabel lingkungan. Untuk menggunakan SDK, Anda harus menginstal SDK OpenAI atau DashScope.

Jalankan kode berikut untuk memulai percakapan dengan model qwen-plus. Untuk hasil generasi berkualitas lebih tinggi, lihat Pemikiran mendalam.

Kompatibel dengan OpenAI

Python

import os
from openai import OpenAI

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

    completion = client.chat.completions.create(
        # Untuk daftar model, lihat https://www.alibabacloud.com/help/en/model-studio/models
        model="qwen-plus",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": "Who are you?"},
        ],
    )
    print(completion.choices[0].message.content)
    # Untuk melihat respons lengkap, hapus komentar pada baris berikut.
    # print(completion.model_dump_json())
except Exception as e:
    print(f"Error message: {e}")
    print("Untuk informasi lebih lanjut, lihat https://www.alibabacloud.com/help/en/model-studio/error-code")

Respons

I am Qwen, an extra-large language model developed by the Tongyi Lab of Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, and write code. I can also express opinions and play games. If you have any questions or need help, feel free to ask me!

Java

// Kami merekomendasikan menggunakan OpenAI Java SDK v3.5.0 atau yang lebih baru.
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) {
        try {
            OpenAIClient client = OpenAIOkHttpClient.builder()
                    // Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: .apiKey("sk-xxx")
                    // Kunci API untuk wilayah Singapura dan Beijing berbeda. Untuk mendapatkan Kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    // Berikut ini adalah URL untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti URL dengan https://dashscope.aliyuncs.com/compatible-mode/v1
                    .baseUrl("https://dashscope-intl.aliyuncs.com/compatible-mode/v1")
                    .build();

            // Buat parameter ChatCompletion.
            ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
                    .model("qwen-plus")  // Tentukan model.
                    .addSystemMessage("You are a helpful assistant.")
                    .addUserMessage("Who are you?")
                    .build();

            // Kirim permintaan dan dapatkan respons.
            ChatCompletion chatCompletion = client.chat().completions().create(params);
            String content = chatCompletion.choices().get(0).message().content().orElse("No valid content returned");
            System.out.println(content);
            
        } catch (Exception e) {
            System.err.println("Error message: " + e.getMessage());
            System.out.println("Untuk informasi lebih lanjut, lihat https://www.alibabacloud.com/help/en/model-studio/error-code");
        }
    }
}

Respons

I am Qwen, an extra-large language model developed by the Tongyi Lab of Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, and write code. I can also express opinions and play games. If you have any questions or need help, feel free to ask me!

Node.js

// Memerlukan Node.js v18+ dan harus dijalankan di lingkungan ES Module.
import OpenAI from "openai";

const openai = new OpenAI(
    {
        // Kunci API untuk wilayah Singapura dan Beijing berbeda. Untuk mendapatkan Kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
        // Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: apiKey: "sk-xxx",
        apiKey: process.env.DASHSCOPE_API_KEY,
        // Berikut ini adalah URL untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti URL dengan https://dashscope.aliyuncs.com/compatible-mode/v1
        baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
        
    }
);
const completion = await openai.chat.completions.create({
    model: "qwen-plus",  // Untuk daftar model, lihat https://www.alibabacloud.com/help/en/model-studio/models
    messages: [
        { role: "system", content: "You are a helpful assistant." },
        { role: "user", content: "Who are you?" }
    ],
});
console.log(completion.choices[0].message.content);
// Untuk melihat respons lengkap, hapus komentar pada baris berikut.
// console.log(JSON.stringify(completion, null, 4));

Respons

I am Qwen, an extra-large language model developed by the Tongyi Lab of Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, and write code. I can also express opinions and play games. If you have any questions or need help, feel free to ask me!

Go

// Diperlukan OpenAI Go SDK v2.4.0 atau yang lebih baru.
package main

import (
	"context"
	// Untuk melihat respons lengkap, hapus komentar pada baris berikut dan baris di akhir blok kode.
	// "encoding/json"
	"fmt"
	"os"

	"github.com/openai/openai-go/v2"
	"github.com/openai/openai-go/v2/option"
)

func main() {
	// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: apiKey := "sk-xxx"
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	client := openai.NewClient(
		option.WithAPIKey(apiKey),
		// Kunci API untuk wilayah Singapura dan Beijing berbeda. Untuk mendapatkan Kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
		// Berikut ini adalah URL untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti 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.ChatCompletionMessageParamUnion{
				openai.SystemMessage("You are a helpful assistant."),
				openai.UserMessage("Who are you?"),
			},
			Model: "qwen-plus",
		},
	)

	if err != nil {
		fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
		// Untuk informasi lebih lanjut tentang pesan error, lihat https://www.alibabacloud.com/help/en/model-studio/error-code
		os.Exit(1)
	}

	if len(chatCompletion.Choices) > 0 {
		fmt.Println(chatCompletion.Choices[0].Message.Content)
	}
	// Untuk melihat respons lengkap, hapus komentar pada baris berikut.
	// jsonData, _ := json.MarshalIndent(chatCompletion, "", "  ")
	// fmt.Println(string(jsonData))

}

Respons

I am Qwen, an extra-large language model developed by the Tongyi Lab of Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, and write code. I can also express opinions and play games. If you have any questions or need help, feel free to ask me!

C# (HTTP)

using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

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 Model Studio Anda: string? apiKey = "sk-xxx";
        string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
        // Berikut ini adalah base_url untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti base_url dengan https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
        string url = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions";
        // Untuk daftar model, lihat https://www.alibabacloud.com/help/en/model-studio/getting-started/models
        string jsonContent = @"{
            ""model"": ""qwen-plus"",
            ""messages"": [
                {
                    ""role"": ""system"",
                    ""content"": ""You are a helpful assistant.""
                },
                {
                    ""role"": ""user"", 
                    ""content"": ""Who are you?""
                }
            ]
        }";

        // Kirim permintaan dan dapatkan respons.
        string result = await SendPostRequestAsync(url, jsonContent, apiKey);
        
        // Untuk melihat respons lengkap, hapus komentar pada baris berikut.
        // Console.WriteLine(result);

        // Uraikan JSON dan keluarkan hanya bagian kontennya.
        using JsonDocument doc = JsonDocument.Parse(result);
        JsonElement root = doc.RootElement;
        
        if (root.TryGetProperty("choices", out JsonElement choices) && 
            choices.GetArrayLength() > 0)
        {
            JsonElement firstChoice = choices[0];
            if (firstChoice.TryGetProperty("message", out JsonElement message) &&
                message.TryGetProperty("content", out JsonElement content))
            {
                Console.WriteLine(content.GetString());
            }
        }
    }

    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
            {   
                // Untuk informasi lebih lanjut tentang pesan error, lihat https://www.alibabacloud.com/help/en/model-studio/error-code
                return $"Request failed: {response.StatusCode}";
            }
        }
    }
}

Respons

I am Qwen, an extra-large language model developed by the Tongyi Lab of Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, and write code. I can also express opinions and play games. If you have any questions or need help, feel free to ask me!

PHP (HTTP)

<?php
// Tetapkan URL permintaan.
// Berikut ini 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';
// Kunci API untuk wilayah Singapura dan Beijing berbeda. Untuk mendapatkan Kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: $apiKey = "sk-xxx";
$apiKey = getenv('DASHSCOPE_API_KEY');
// Tetapkan header permintaan.
$headers = [
    'Authorization: Bearer '.$apiKey,
    'Content-Type: application/json'
];
// Tetapkan isi permintaan.
$data = [
    "model" => "qwen-plus",
    "messages" => [
        [
            "role" => "system",
            "content" => "You are a helpful assistant."
        ],
        [
            "role" => "user",
            "content" => "Who are you?"
        ]
    ]
];
// Inisialisasi sesi cURL.
$ch = curl_init();
// Tetapkan 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.
// Untuk informasi lebih lanjut tentang pesan error, lihat https://www.alibabacloud.com/help/en/model-studio/error-code
if (curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
}
// Tutup resource cURL.
curl_close($ch);
// Keluarkan respons.
$dataObject = json_decode($response);
$content = $dataObject->choices[0]->message->content;
echo $content;
// Untuk melihat respons lengkap, hapus komentar pada baris berikut.
//echo $response;
?>

Respons

I am Qwen, an extra-large language model developed by the Tongyi Lab of Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, and write code. I can also express opinions and play games. If you have any questions or need help, feel free to ask me!

curl

base_url pada contoh berikut adalah untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti base_url dengan https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions.

Kunci API untuk wilayah Singapura dan Beijing berbeda. Untuk informasi lebih lanjut, lihat Dapatkan dan konfigurasikan Kunci API.

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?"
        }
    ]
}'

Respons

{
    "choices": [
        {
            "message": {
                "role": "assistant",
                "content": "I am Qwen, an extra-large language model developed by the Tongyi Lab of Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, and write code. I can also express opinions and play games. If you have any questions or need help, feel free to ask me!"
            },
            "finish_reason": "stop",
            "index": 0,
            "logprobs": null
        }
    ],
    "object": "chat.completion",
    "usage": {
        "prompt_tokens": 26,
        "completion_tokens": 66,
        "total_tokens": 92
    },
    "created": 1726127645,
    "system_fingerprint": null,
    "model": "qwen-plus",
    "id": "chatcmpl-81951b98-28b8-9659-ab07-xxxxxx"
}

DashScope

Python

import json
import os
from dashscope import Generation
import dashscope

# Berikut ini adalah URL untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti URL dengan https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = "https://dashscope-intl.aliyuncs.com/api/v1"

messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Who are you?"},
]
response = Generation.call(
    # Kunci API untuk wilayah Singapura dan Beijing berbeda. Untuk mendapatkan Kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
    # Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: 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)
    # Untuk melihat respons lengkap, hapus komentar pada baris berikut.
    # print(json.dumps(response, default=lambda o: o.__dict__, indent=4))
else:
    print(f"HTTP status code: {response.status_code}")
    print(f"Error code: {response.code}")
    print(f"Error message: {response.message}")
    print("Untuk informasi lebih lanjut, lihat https://www.alibabacloud.com/help/en/model-studio/error-code")

Respons

I am Qwen, an extra-large language model developed by the Tongyi Lab of Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, and write code. I can also express opinions and play games. If you have any questions or need help, feel free to ask me!

Java

// Kami merekomendasikan menggunakan DashScope Java SDK v2.20.6 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.protocol.Protocol;
import com.alibaba.dashscope.utils.JsonUtils;

public class Main {
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        // Berikut ini adalah URL untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti URL dengan https://dashscope.aliyuncs.com/api/v1
        Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("You are a helpful assistant.")
                .build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content("Who are you?")
                .build();
        GenerationParam param = GenerationParam.builder()
                // Kunci API untuk wilayah Singapura dan Beijing berbeda. Untuk mendapatkan Kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
                // Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: .apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .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());
            // Untuk melihat respons lengkap, hapus komentar pada baris berikut.
            // System.out.println(JsonUtils.toJson(result));
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.err.println("Error message: "+e.getMessage());
            System.out.println("Untuk informasi lebih lanjut, lihat https://www.alibabacloud.com/help/en/model-studio/error-code");
        }
    }
}

Respons

I am Qwen, an extra-large language model developed by the Tongyi Lab of Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, and write code. I can also express opinions and play games. If you have any questions or need help, feel free to ask me!

Node.js (HTTP)

// Memerlukan Node.js v18+.
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: const apiKey = "sk-xxx";
const apiKey = process.env.DASHSCOPE_API_KEY;

const data = {
    model: "qwen-plus",
    input: {
        messages: [
            {
                role: "system",
                content: "You are a helpful assistant."
            },
            {
                role: "user",
                content: "Who are you?"
            }
        ]
    },
    parameters: {
        result_format: "message"
    }
};

async function callApi() {
    try {
        // Berikut ini 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
        const response = await fetch('https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });

        const result = await response.json();
        console.log(result.output.choices[0].message.content);
        // Untuk melihat respons lengkap, hapus komentar pada baris berikut.
        // console.log(JSON.stringify(result));
    } catch (error) {
        // Untuk informasi lebih lanjut tentang pesan error, lihat https://www.alibabacloud.com/help/en/model-studio/error-code
        console.error('Call failed:', error.message);
    }
}

callApi();

Respons

I am Qwen, an extra-large language model developed by the Tongyi Lab of Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, and write code. I can also express opinions and play games. If you have any questions or need help, feel free to ask me!

Go (HTTP)

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
)

func main() {
	requestBody := map[string]interface{}{
		"model": "qwen-plus",
		"input": map[string]interface{}{
			"messages": []map[string]string{
				{
					"role":    "system",
					"content": "You are a helpful assistant.",
				},
				{
					"role":    "user",
					"content": "Who are you?",
				},
			},
		},
		"parameters": map[string]string{
			"result_format": "message",
		},
	}

	// Serialisasi ke JSON.
	jsonData, _ := json.Marshal(requestBody)

	// Buat klien HTTP dan permintaan.
	client := &http.Client{}
	// Berikut ini 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, _ := http.NewRequest("POST", "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation", bytes.NewBuffer(jsonData))

	// Tetapkan header permintaan.
	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, _ := io.ReadAll(resp.Body)

	// Uraikan JSON dan keluarkan kontennya.
	var result map[string]interface{}
	json.Unmarshal(bodyText, &result)
	content := result["output"].(map[string]interface{})["choices"].([]interface{})[0].(map[string]interface{})["message"].(map[string]interface{})["content"].(string)
	fmt.Println(content)

	// Untuk melihat respons lengkap, hapus komentar pada baris berikut.
	// fmt.Printf("%s\n", bodyText)
}

Respons

I am Qwen, an extra-large language model developed by the Tongyi Lab of Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, and write code. I can also express opinions and play games. If you have any questions or need help, feel free to ask me!

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)
    {
        // Kunci API untuk wilayah Singapura dan Beijing berbeda. Untuk mendapatkan Kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
        // Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: string? apiKey = "sk-xxx";
        string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
        // Tetapkan URL dan konten permintaan.
        // Berikut ini 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";
        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);
        var jsonResult = System.Text.Json.JsonDocument.Parse(result);
        var content = jsonResult.RootElement.GetProperty("output").GetProperty("choices")[0].GetProperty("message").GetProperty("content").GetString();
        Console.WriteLine(content);
        // Untuk melihat respons lengkap, hapus komentar pada baris berikut.
        // 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);

            // Tangani respons.
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }
            else
            {
                return $"Request failed: {response.StatusCode}";
            }
        }
    }
}

Respons

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": "I am Qwen, an extra-large language model developed by the Tongyi Lab of Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, and write code. I can also express opinions and play games. If you have any questions or need help, feel free to ask me!"
                }
            }
        ]
    },
    "usage": {
        "total_tokens": 92,
        "output_tokens": 66,
        "input_tokens": 26
    },
    "request_id": "09dceb20-ae2e-999b-85f9-xxxxxx"
}

PHP (HTTP)

<?php
// Berikut ini 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/en/model-studio/get-api-key
$apiKey = getenv('DASHSCOPE_API_KEY');

$data = [
    "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_HTTPHEADER, [
    "Authorization: Bearer $apiKey",
    "Content-Type: application/json"
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($httpCode == 200) {
    $jsonResult = json_decode($response, true);
    $content = $jsonResult['output']['choices'][0]['message']['content'];
    echo $content;
    // Untuk melihat respons lengkap, hapus komentar pada baris berikut.
    // echo "Model response: " . $response;
} else {
    echo "Request error: " . $httpCode . " - " . $response;
}

curl_close($ch);
?>

Respons

I am Qwen, an extra-large language model developed by the Tongyi Lab of Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, and write code. I can also express opinions and play games. If you have any questions or need help, feel free to ask me!

curl

base_url pada contoh berikut adalah untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti base_url dengan: https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation

Kunci API untuk wilayah Singapura dan Beijing berbeda. Untuk informasi lebih lanjut, lihat Dapatkan dan konfigurasikan Kunci API.

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"
    }
}'

Respons

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": "I am Qwen, an extra-large language model developed by the Tongyi Lab of Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, and write code. I can also express opinions and play games. If you have any questions or need help, feel free to ask me!"
                }
            }
        ]
    },
    "usage": {
        "total_tokens": 92,
        "output_tokens": 66,
        "input_tokens": 26
    },
    "request_id": "09dceb20-ae2e-999b-85f9-xxxxxx"
}

Pemrosesan citra dan video

Model multimodal mendukung pemrosesan data non-teks, seperti citra dan video, untuk tugas-tugas seperti visual question answering dan deteksi event. Pemanggilan model-model ini berbeda dari pemanggilan model teks biasa dalam hal-hal berikut:

  • Struktur pesan pengguna: Pesan pengguna untuk model multimodal tidak hanya berisi teks, tetapi juga informasi multimodal, seperti citra dan audio.

  • Antarmuka SDK DashScope: Saat menggunakan SDK Python DashScope, panggil antarmuka MultiModalConversation. Saat menggunakan SDK Java DashScope, panggil kelas MultiModalConversation.

Untuk batasan file citra dan video, lihat visual understanding.

Kompatibel dengan OpenAI

Python

from openai import OpenAI
import os

client = OpenAI(
    # Kunci API untuk wilayah Singapura dan Beijing berbeda. Untuk mendapatkan kunci API, kunjungi: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
    # Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # base_url berikut digunakan 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"
)
messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image_url",
                "image_url": {
                    "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"
                },
            },
            {"type": "text", "text": "What products are shown in the image?"},
        ],
    }
]
completion = client.chat.completions.create(
    model="qwen3-vl-plus",  # Ganti ini dengan model multi-modal lain dan sesuaikan messages sesuai kebutuhan.
    messages=messages,
)
print(completion.choices[0].message.content)

Node.js

import OpenAI from "openai";

const openai = new OpenAI(
    {
        // Kunci API untuk wilayah Singapura dan Beijing berbeda. Untuk mendapatkan kunci API, kunjungi: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
        // Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan Kunci API Model Studio Anda: apiKey: "sk-xxx",
        apiKey: process.env.DASHSCOPE_API_KEY,
        // baseURL berikut digunakan untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti baseURL dengan: https://dashscope.aliyuncs.com/compatible-mode/v1
        baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
    }
);

let messages = [
    {
        role: "user",
        content: [
            { type: "image_url", image_url: { "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png" } },
            { type: "text", text: "What products are shown in the image?" },
        ]
    }]
async function main() {
    let response = await openai.chat.completions.create({
        model: "qwen3-vl-plus",   // Ganti ini dengan model multi-modal lain dan sesuaikan messages sesuai kebutuhan.
        messages: messages
    });
    console.log(response.choices[0].message.content);
}

main()

curl

base_url pada contoh berikut digunakan untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti base_url dengan: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions.

Kunci API untuk wilayah Singapura dan Beijing berbeda. Untuk informasi selengkapnya, lihat Dapatkan dan konfigurasikan kunci API.

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": "qwen3-vl-plus",
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "image_url",
          "image_url": {
            "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"
          }
        },
        {
          "type": "text",
          "text": "What products are shown in the image?"
        }
      ]
    }
  ]
}'

DashScope

Python

import os
from dashscope import MultiModalConversation
import dashscope
# base_url berikut digunakan untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti base_url dengan https://dashscope.aliyuncs.com/api/v1.
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

messages = [
    {
        "role": "user",
        "content": [
            {
                "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"
            },
            {"text": "What products are shown in the image?"},
        ],
    }
]
response = MultiModalConversation.call(
    # Kunci API untuk wilayah Singapura dan Beijing berbeda. Untuk mendapatkan kunci API, kunjungi https://www.alibabacloud.com/help/en/model-studio/get-api-key.
    # Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan api_key="sk-xxx", dan gunakan Kunci API Model Studio Anda.
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model='qwen3-vl-plus',  # Anda dapat mengganti model dengan model multimodal lain dan menyesuaikan messages-nya.
    messages=messages
)

print(response.output.choices[0].message.content[0]['text'])

Java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;

public class Main {
    static {
        // base_url berikut digunakan untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti base_url dengan https://dashscope.aliyuncs.com/api/v1.
        Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
    }

    private static final String modelName = "qwen3-vl-plus";  //  Anda dapat mengganti ini dengan model multimodal lain sesuai kebutuhan dan menyesuaikan messages-nya.

    public static void MultiRoundConversationCall() throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(Collections.singletonMap("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"),
                        Collections.singletonMap("text", "What products are shown in the image?"))).build();
        List<MultiModalMessage> messages = new ArrayList<>();
        messages.add(userMessage);
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // Kunci API untuk wilayah Singapura dan Beijing berbeda. Untuk mendapatkan kunci API, kunjungi: https://www.alibabacloud.com/help/en/model-studio/get-api-key
                // Jika tidak ada variabel lingkungan yang dikonfigurasi, gunakan Kunci API Model Studio Anda untuk mengganti baris berikut dengan: .apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model(modelName)
                .messages(messages)
                .build();
        MultiModalConversationResult result = conv.call(param);
        System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));        // tambahkan hasil ke percakapan
    }

    public static void main(String[] args) {
        try {
            MultiRoundConversationCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}

curl

base_url berikut digunakan untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti base_url dengan: https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation.

Kunci API untuk wilayah Singapura dan Beijing berbeda. Untuk informasi selengkapnya, lihat Dapatkan dan konfigurasikan kunci API.

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
    "model": "qwen3-vl-plus",
    "input":{
        "messages":[
            {
                "role": "user",
                "content": [
                    {"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"},
                    {"text": "What products are shown in the image?"}
                ]
            }
        ]
    }
}'

Pemanggilan asinkron

Pemanggilan asinkron meningkatkan efisiensi penanganan permintaan dalam skenario dengan konkurensi tinggi.

Kompatibel dengan OpenAI

Python

import os
import asyncio
from openai import AsyncOpenAI
import platform

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

# Definisikan daftar tugas asinkron.
async def task(question):
    print(f"Mengirim pertanyaan: {question}")
    response = await client.chat.completions.create(
        messages=[
            {"role": "user", "content": question}
        ],
        model="qwen-plus",  # Untuk daftar model, lihat https://www.alibabacloud.com/help/en/model-studio/getting-started/models
    )
    print(f"Tanggapan model: {response.choices[0].message.content}")

# Fungsi asinkron utama.
async def main():
    questions = ["Who are you?", "What can you do?", "What's the weather like?"]
    tasks = [task(q) for q in questions]
    await asyncio.gather(*tasks)

if __name__ == '__main__':
    # Atur kebijakan event loop.
    if platform.system() == 'Windows':
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    # Jalankan korutin utama.
    asyncio.run(main(), debug=False)
    

Java

import com.openai.client.OpenAIClientAsync;
import com.openai.client.okhttp.OpenAIOkHttpClientAsync;
import com.openai.models.chat.completions.ChatCompletionCreateParams;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;

public class Main {
    public static void main(String[] args) {
        // Buat klien OpenAI dan hubungkan ke API yang kompatibel dengan DashScope.
        OpenAIClientAsync client = OpenAIOkHttpClientAsync.builder()
                // Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan kunci API Model Studio Anda: .apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // URL berikut ini untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti URL dengan https://dashscope.aliyuncs.com/compatible-mode/v1
                .baseUrl("https://dashscope-intl.aliyuncs.com/compatible-mode/v1")
                .build();

        // Definisikan daftar pertanyaan.
        List<String> questions = Arrays.asList("Who are you?", "What can you do?", "What's the weather like?");

        // Buat daftar tugas asinkron.
        CompletableFuture<?>[] futures = questions.stream()
                .map(question -> CompletableFuture.supplyAsync(() -> {
                    System.out.println("Mengirim pertanyaan: " + question);
                    // Buat parameter ChatCompletion.
                    ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
                            .model("qwen-plus")  // Tentukan model.
                            .addSystemMessage("You are a helpful assistant.")
                            .addUserMessage(question)
                            .build();

                    // Kirim permintaan asinkron dan proses respons.
                    return client.chat().completions().create(params)
                        .thenAccept(chatCompletion -> {
                            String content = chatCompletion.choices().get(0).message().content().orElse("No response content");
                            System.out.println("Tanggapan model: " + content);
                        })
                        .exceptionally(e -> {
                            System.err.println("Pesan error: " + e.getMessage());
                            System.out.println("Untuk informasi lebih lanjut, lihat https://www.alibabacloud.com/help/en/model-studio/error-code");
                            return null;
                        });
                }).thenCompose(future -> future))
                .toArray(CompletableFuture[]::new);

        // Tunggu hingga semua operasi asinkron selesai.
        CompletableFuture.allOf(futures).join();
    }
}

DashScope

Generasi teks asinkron dengan SDK DashScope hanya didukung dalam Python.

# Versi SDK Python DashScope harus 1.19.0 atau lebih baru.
import asyncio
import platform
from dashscope.aigc.generation import AioGeneration
import os
import dashscope
# URL berikut ini untuk wilayah Singapura. Untuk menggunakan model di wilayah Beijing, ganti URL dengan: https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

# Definisikan tugas asinkron.
async def task(question):
    print(f"Mengirim pertanyaan: {question}")
    response = await AioGeneration.call(
        # Jika variabel lingkungan belum diatur, ganti baris berikut dengan kunci API Model Studio Anda: api_key="sk-xxx",
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        model="qwen-plus",  # Daftar Model: https://www.alibabacloud.com/help/zh/model-studio/models
        messages=[{"role": "system", "content": "You are a helpful assistant."},
                  {"role": "user", "content": question}],
        result_format="message",
    )
    print(f"Tanggapan model: {response.output.choices[0].message.content}")

# Fungsi asinkron utama.
async def main():
    questions = ["Who are you?", "What can you do?", "How is the weather?"]
    tasks = [task(q) for q in questions]
    await asyncio.gather(*tasks)

if __name__ == '__main__':
    # Atur kebijakan event loop.
    if platform.system() == 'Windows':
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    # Jalankan korutin utama.
    asyncio.run(main(), debug=False)

Respons

Karena panggilan bersifat asinkron, urutan respons mungkin berbeda dari contoh.
Sending question: Who are you?
Sending question: What can you do?
Sending question: What's the weather like?
Model response: Hello! I am Qwen, a large-scale language model developed by the Tongyi Lab at Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and playbooks, perform logical reasoning, write code, express opinions, and play games. If you have any questions or need help, feel free to ask me at any time!
Model response: Hello! I cannot get real-time weather information at the moment. You can tell me your city or region, and I will do my best to provide you with general weather advice or information. Alternatively, you can use a weather application to check the real-time weather conditions.
Model response: I have many skills, such as:

1. **Answering questions**: I can try to help you answer academic questions, common sense questions, or questions about professional knowledge.
2. **Text creation**: I can write various types of text, such as stories, official documents, emails, and playbooks.
3. **Logical reasoning**: I can help you solve logical reasoning problems, such as math problems and riddles.
4. **Programming**: I can provide programming assistance, including code writing, debugging, and optimization.
5. **Multilingual support**: I support multiple languages, including but not limited to Chinese, English, French, and Spanish.
6. **Expressing opinions**: I can provide you with opinions and suggestions to help you make decisions.
7. **Playing games**: We can play text-based games together, such as riddles and word chain games.

If you have any specific needs or questions, feel free to let me know, and I will do my best to help you!

Going live

Build high-quality context

Memasukkan sejumlah besar data mentah langsung ke dalam model meningkatkan biaya dan mengurangi performa karena keterbatasan ukuran konteks. Context engineering meningkatkan kualitas dan efisiensi generasi dengan memuat pengetahuan yang relevan secara dinamis. Teknik utamanya meliputi hal-hal berikut:

  • Prompt engineering: Teknik ini melibatkan perancangan dan pengoptimalan instruksi teks (prompt) untuk memandu model secara lebih tepat, sehingga menghasilkan output yang diinginkan. Untuk informasi selengkapnya, lihat Panduan prompt teks-ke-teks.

  • Retrieval-augmented generation (RAG): Teknik ini digunakan ketika model perlu menjawab pertanyaan berdasarkan basis pengetahuan eksternal, seperti dokumen produk atau manual teknis.

  • Tool calling: Teknik ini memungkinkan model mengambil informasi real-time—seperti pembaruan cuaca atau lalu lintas—atau menjalankan operasi tertentu, seperti memanggil API atau mengirim email.

  • Memory: Fitur ini menciptakan memori jangka panjang dan jangka pendek untuk model, sehingga memungkinkannya memahami riwayat percakapan.

Control response diversity

Parameter temperature dan top_p mengontrol keragaman teks yang dihasilkan. Nilai yang lebih tinggi menghasilkan konten yang lebih beragam, sedangkan nilai yang lebih rendah menghasilkan konten yang lebih deterministik. Untuk mengevaluasi efek parameter ini secara akurat, ubah hanya satu parameter dalam satu waktu.

  • temperature: Rentang [0, 2). Mengatur tingkat keacakan.

  • top_p: Rentang [0, 1]. Menyaring respons berdasarkan ambang batas probabilitas.

Contoh berikut menunjukkan bagaimana pengaturan parameter yang berbeda memengaruhi konten yang dihasilkan. Prompt input adalah: "Tulis cerita pendek tiga kalimat tentang seekor kucing dan seberkas sinar matahari."

  • Keragaman tinggi (contoh temperature=0.9): Gunakan untuk skenario yang membutuhkan kreativitas, imajinasi, dan ekspresi baru, seperti penulisan kreatif, brainstorming, atau copywriting pemasaran.

    Sunlight slanted onto the windowsill. The ginger cat crept toward the glowing tile, its fur instantly turning the color of melted honey.
    It extended a paw to tap the patch of light, sinking in as if stepping into a warm pool, and the sunlight flowed up its back from its paw pads.
    The afternoon suddenly grew heavy. The cat, curled in the flowing gold dust, heard time gently dissolve into its purrs.
  • Determinisme tinggi (contoh temperature=0.1): Gunakan untuk skenario yang membutuhkan konten akurat, ketat, dan dapat diprediksi, seperti tanya jawab faktual, generasi kode, atau teks hukum.

    In the afternoon, an old cat curled on the windowsill, dozing among the sunbeams.
    Sunlight gently danced across its mottled back, like flipping through an old photo album.
    Dust floated up and settled down, as if time whispered: You were once young, and I was once warm.

Cara kerja

temperature:

  • Temperature yang lebih tinggi meratakan distribusi probabilitas token, menurunkan probabilitas token berprobabilitas tinggi dan meningkatkan probabilitas token berprobabilitas rendah. Akibatnya, pilihan model untuk token berikutnya menjadi lebih acak.

  • Temperature yang lebih rendah membuat distribusi probabilitas token menjadi lebih curam, sehingga token berprobabilitas tinggi lebih mungkin dipilih dan model cenderung memilih dari sekumpulan kecil token berprobabilitas tinggi.

top_p:

Pengambilan sampel top_p memilih dari sekumpulan token yang paling mungkin. Metode ini mengurutkan semua token berikutnya yang mungkin berdasarkan probabilitas secara menurun, lalu menjumlahkan probabilitas tersebut mulai dari token paling mungkin hingga mencapai ambang batas top_p yang ditentukan. Misalnya, nilai top_p sebesar 0.8 berarti 80%. Model kemudian memilih token berikutnya secara acak dari kelompok ini.

  • Nilai top_p yang lebih tinggi mempertimbangkan lebih banyak token, sehingga teks yang dihasilkan menjadi lebih beragam.

  • Nilai top_p yang lebih rendah mempertimbangkan lebih sedikit token, sehingga teks yang dihasilkan menjadi lebih fokus dan deterministik.

Konfigurasi parameter contoh untuk berbagai skenario

# Recommended parameter configurations for different scenarios
SCENARIO_CONFIGS = {
    # Creative writing
    "creative_writing": {
        "temperature": 0.9,
        "top_p": 0.95
    },
    # Code generation
    "code_generation": {
        "temperature": 0.2,
        "top_p": 0.8
    },
    # Factual Q&A
    "factual_qa": {
        "temperature": 0.1,
        "top_p": 0.7
    },
    # Translation
    "translation": {
        "temperature": 0.3,
        "top_p": 0.8
    }
}

# OpenAI usage example
# completion = client.chat.completions.create(
#     model="qwen-plus",
#     messages=[{"role": "user", "content": "Write a poem about the moon"}],
#     **SCENARIO_CONFIGS["creative_writing"]
# )
# DashScope usage example
# response = Generation.call(
#     # If the environment variable is not configured, replace the following line with your Model Studio API key: api_key = "sk-xxx",
#     api_key=os.getenv("DASHSCOPE_API_KEY"),
#     model="qwen-plus",
#     messages=[{"role": "user", "content": "Write a Python function to determine if an input n is a prime number. Do not output non-code content"}],
#     result_format="message",
#     **SCENARIO_CONFIGS["code_generation"]
# )

More features

Bagian-bagian sebelumnya menjelaskan metode interaksi dasar. Untuk skenario yang lebih kompleks, pertimbangkan fitur-fitur berikut:

  • Multi-turn conversation: Fitur ini digunakan dalam skenario yang memerlukan komunikasi berkelanjutan, seperti pertanyaan lanjutan dan pengumpulan informasi.

  • Streaming output: Fitur ini digunakan dalam skenario yang memerlukan respons instan, seperti chatbot dan generasi kode real-time. Fitur ini meningkatkan pengalaman pengguna serta membantu mencegah timeout akibat waktu respons yang lama.

  • Deep thinking: Fitur ini digunakan dalam skenario yang memerlukan jawaban berkualitas tinggi, terstruktur, dan mendalam, seperti penalaran kompleks dan analisis kebijakan.

  • Structured output: Fitur ini digunakan ketika Anda memerlukan model memberikan respons dalam format JSON yang stabil, berguna untuk panggilan programatis atau penguraian data.

  • Partial mode: Fitur ini digunakan dalam skenario seperti penyelesaian kode dan penulisan teks panjang, di mana model perlu melanjutkan dari teks yang sudah ada.

Referensi API

Untuk daftar lengkap parameter pemanggilan model, lihat referensi API yang kompatibel dengan OpenAI dan referensi API DashScope.

FAQ

T: Mengapa API Qwen tidak dapat menganalisis tautan web?

J: API Qwen tidak dapat mengakses dan mengurai tautan web secara langsung. Anda dapat menggunakan fitur seperti Function Calling dan , atau alat web scraping seperti Beautiful Soup dari Python untuk membaca informasi dari halaman web.

T: Mengapa respons dari Qwen berbasis web dan API Qwen tidak konsisten?

J: Qwen berbasis web mencakup optimisasi teknis tambahan yang dibangun di atas API Qwen. Hal ini memungkinkan fitur seperti penguraian halaman web, pencarian web, pembuatan grafik, dan pembuatan PPT. Fitur-fitur tersebut bukan kemampuan bawaan dari API model. Anda dapat menggunakan fitur seperti , Function Calling, dan untuk mengoptimalkan hasil model.

T: Apakah model dapat langsung menghasilkan file dalam format Word, Excel, PDF, atau PPT?

J: Tidak. Model generasi teks di Model Studio hanya menghasilkan teks biasa. Untuk membuat file dalam format tersebut, Anda dapat mengonversi teks biasa tersebut menggunakan kode atau pustaka pihak ketiga.