All Products
Search
Document Center

Alibaba Cloud Model Studio:Ikhtisar

Last Updated:Mar 21, 2026

Model generasi teks menghasilkan teks yang jelas dan koheren berdasarkan sebuah prompt.

Model generasi teks menerima berbagai jenis input, mulai dari kata kunci sederhana dan deskripsi singkat hingga instruksi kompleks dan informasi kontekstual. Model-model ini dilatih pada dataset besar untuk mempelajari pola bahasa serta mendukung berbagai aplikasi, seperti:

  • Pembuatan konten: Menghasilkan artikel berita, deskripsi produk, dan naskah video pendek.

  • Layanan pelanggan: Memberdayakan chatbot untuk menyediakan dukungan 24/7 dan menjawab pertanyaan umum.

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

  • Generasi ringkasan: Menyaring informasi penting dari dokumen panjang, laporan, dan email.

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

Pemilihan model

Wilayah layanan

Alibaba Cloud Model Studio menyediakan layanan model di wilayah Singapura, AS (Virginia), Tiongkok (Beijing), Tiongkok (Hong Kong), dan Jerman (Frankfurt). Setiap wilayah memerlukan Kunci API terpisah. Menggunakan wilayah terdekat mengurangi latensi jaringan. Untuk informasi lebih lanjut, lihat Pilih wilayah dan mode penyebaran.

Model tujuan umum

Model generasi teks Qwen kompatibel dengan format API OpenAI dan cocok untuk berbagai skenario, seperti layanan pelanggan cerdas, pembuatan konten, penyempurnaan teks, dan ringkasan.

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

    Seri terbaru Qwen-3.5-Plus unggul dalam berbagai tugas, termasuk pemahaman bahasa, penalaran logis, Code Generation, Agent Tasks, Pemahaman Gambar, pemahaman video, dan interaksi Graphical User Interface (GUI). Model ini mendukung Tool Calling bawaan, dan kemampuan teksnya setara dengan Qwen-Max. Model ini sangat direkomendasikan.
  • Qwen-Max: Model dengan performa tertinggi dalam seri Qwen-3, ideal untuk tugas kompleks multi-langkah.

  • Qwen-Flash: Model tercepat dan paling hemat biaya dalam seri Qwen, ideal untuk tugas sederhana.

  • Seri Open Source Qwen-3.5: qwen3.5-397b-a17b, qwen3.5-122b-a10b, qwen3.5-27b, dan qwen3.5-35b-a3b.

Model khusus skenario

Untuk kebutuhan bisnis spesifik, Alibaba Cloud Model Studio menawarkan model khusus dan teroptimalkan untuk domain seperti kode, Long Context, terjemahan, penambangan data, Intent Recognition, role-playing, dan deep search.

Model multimodal

  • Qwen-Plus (Teks + Gambar/Video → Teks): Seri Qwen-3.5-Plus menerima input visual dan teks, memberikan performa luar biasa dalam tugas seperti pemahaman bahasa, penalaran logis, Code Generation, Agent Tasks, Pemahaman Gambar, pemahaman video, dan interaksi Graphical User Interface (GUI). Kemampuan penalaran visualnya merupakan lompatan signifikan dibandingkan seri Qwen-VL.

  • Qwen-Omni (Omni-modal → Teks + Audio): Menerima berbagai input data, termasuk video, audio, gambar, dan teks, serta menghasilkan output teks dan suara untuk tugas lintas-modalitas kompleks.

  • Speech Recognition Models (Audio → Teks): Model-model ini mengenali dan mentranskripsikan ucapan dari audio. Bahasa yang didukung meliputi Tionghoa (termasuk berbagai dialek seperti Kanton), Inggris, Jepang, dan Korea.

Model pihak ketiga

Alibaba Cloud Model Studio juga menawarkan Large Language Model (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 sebuah prompt, yang terdiri dari satu atau beberapa objek Message. Setiap Message terdiri dari Role dan Content:

  • System Message: Mendefinisikan peran model dan instruksi yang harus diikuti. Jika tidak ditentukan, nilai default-nya adalah "You are a helpful assistant".

  • User Message: Pertanyaan atau instruksi yang diberikan oleh pengguna.

  • Assistant Message: Balasan dari model.

Untuk memanggil model, berikan array messages yang terdiri dari objek-objek Message tersebut. Permintaan tipikal terdiri dari pesan system yang mendefinisikan kode etik dan pesan user dengan instruksinya.

Pesan system bersifat opsional, tetapi kami merekomendasikan untuk mendefinisikan peran dan kode etik model agar menghasilkan output yang lebih stabil dan konsisten.
[
    {"role": "system", "content": "You are a helpful assistant who provides accurate, efficient, and insightful responses. You are ready to help users with any task or question."},
    {"role": "user", "content": "Who are you?"}
]

Objek respons berisi pesan assistant dengan balasan dari model.

{
    "role": "assistant",
    "content": "Hello! I am Qwen, a large-scale 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 conversation and complex task processing. If you need any help, just let me know!"
}

Mulai cepat

Prasyarat: Dapatkan Kunci API, atur Kunci API sebagai Variabel lingkungan, dan instal SDK OpenAI atau DashScope.

OpenAI compatible - Responses API

Responses API merupakan ekstensi dari Chat Completions API. Untuk catatan penggunaan, contoh kode, dan panduan migrasi, lihat OpenAI compatible - Responses.

Python

import os
from openai import OpenAI

try:
    client = OpenAI(
        # Kunci API bersifat spesifik per wilayah. Dapatkan Kunci API Anda: https://www.alibabacloud.com/help/model-studio/get-api-key
        # Atau, atur Kunci API Anda secara langsung: api_key="sk-xxx",
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # Ubah URL dasar sesuai wilayah Anda.
        base_url="https://dashscope-intl.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1",
    )

    response = client.responses.create(
        model="qwen3.5-plus", 
        input="Briefly introduce what you can do?"
    )

    print(response)
except Exception as e:
    print(f"An error occurred: {e}")
    print("Untuk detailnya, lihat dokumentasi kode kesalahan: https://www.alibabacloud.com/help/model-studio/error-code")

Respons

Objek Respons berisi bidang-bidang berikut:

  • id: Pengidentifikasi unik untuk respons.

  • output: Daftar output yang berisi reasoning (proses berpikir model) dan message (respons model).

    Bidang reasoning hanya dikembalikan saat deep thinking diaktifkan. Misalnya, fitur ini diaktifkan secara default untuk seri Qwen-3.5.
  • usage: Statistik penggunaan Token.

Berikut adalah contoh isi respons. Untuk respons lengkap, lihat bagian curl.

Hello! I'm an AI assistant with knowledge current up to 2026. Here's a brief overview of what I can do:

*   Content Creation: Write emails, articles, stories, scripts, and more.
*   Coding & Tech: Generate, debug, and explain code across various programming languages.
*   Analysis & Summarization: Process documents, interpret data, and extract key insights.
*   Problem Solving: Assist with math, logic, reasoning, and strategic planning.
*   Learning & Translation: Explain complex topics simply or translate between multiple languages.

Feel free to ask me anything or give me a task to get started!

Node.js

// Memerlukan Node.js v18 atau lebih baru. Jalankan di lingkungan ES Module.
import OpenAI from "openai";

const openai = new OpenAI({
    // Kunci API bersifat spesifik per wilayah. Dapatkan Kunci API Anda: https://www.alibabacloud.com/help/model-studio/get-api-key
    // Atau, atur Kunci API Anda secara langsung: apiKey: "sk-xxx",
    apiKey: process.env.DASHSCOPE_API_KEY,
    // Ubah URL dasar sesuai wilayah Anda.
    baseURL: "https://dashscope-intl.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1"
});

async function main() {
    try {
        const response = await openai.responses.create({
            model: "qwen3.5-plus",
            input: "Briefly introduce what you can do?"
        });

        // Dapatkan respons model
        console.log(response);
    } catch (error) {
        console.error("An error occurred:", error);
    }
}

main();

Respons

Objek Respons berisi bidang-bidang berikut:

  • id: Pengidentifikasi unik untuk respons.

  • output: Daftar output yang berisi reasoning (proses berpikir model) dan message (respons model).

    Bidang reasoning hanya dikembalikan saat deep thinking diaktifkan. Misalnya, fitur ini diaktifkan secara default untuk seri Qwen-3.5.
  • usage: Statistik penggunaan Token.

Berikut adalah contoh isi respons. Untuk respons lengkap, lihat bagian curl.

Hello! I'm an AI assistant with knowledge current up to 2026. Here's a brief overview of what I can do:

*   Content Creation: Write emails, articles, stories, scripts, and more.
*   Coding & Tech: Generate, debug, and explain code across various programming languages.
*   Analysis & Summarization: Process documents, interpret data, and extract key insights.
*   Problem Solving: Assist with math, logic, reasoning, and strategic planning.
*   Learning & Translation: Explain complex topics simply or translate between multiple languages.

Feel free to ask me anything or give me a task to get started!

Curl

# Ubah URL dasar sesuai wilayah Anda.
curl -X POST https://dashscope-intl.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen3.5-plus",
    "input": "Briefly introduce what you can do?",
    "enable_thinking": true
}'

Respons

{
    "created_at": 1772249518,
    "id": "7ad48c6b-3cc4-904f-9284-5f419c6c5xxx",
    "model": "qwen3.5-plus",
    "object": "response",
    "output": [
        {
            "id": "msg_94805179-2801-45da-ac1c-a87e8ea20xxx",
            "summary": [
                {
                    "text": "Okay, the user is asking me to briefly introduce what I can do. Let me start by recalling the capabilities listed in the system message. I need to make sure I cover the main points without getting too detailed.\n\nFirst, I should mention my enhanced language foundation and architecture efficiency. Then, the upgraded logical reasoning and mathematical capabilities. Visual analysis is another key point, including charts and formulas. Autonomous agent planning and code generation are important too. Human alignment optimization for better interaction, long-context handling up to 256K, and multilingual support with OCR.\n\nWait, the user said \"briefly,\" so I need to keep it concise. Maybe group some points together. Let me check the examples given in the system message. They have sections like Enhanced Language Foundation, Advanced Logical Reasoning, etc. But since it's a brief intro, I should summarize each capability in a sentence or two.\n\nAlso, the user might be looking for practical applications. Maybe highlight how these features help in real tasks. For example, handling long documents, solving math problems, analyzing images, writing code, etc.\n\nI should avoid technical jargon where possible. Make it clear and straightforward. Let me structure it as a list of key capabilities with short explanations. Start with a greeting, then list the main points, and end with an offer to help with specific tasks.\n\nWait, the system message says \"You are Qwen3.5,\" so I need to introduce myself as such. But the user just asked what I can do, so maybe start with \"I'm Qwen3.5...\" and then list the capabilities.\n\nCheck if all the upgraded features from Qwen3 to Qwen3.5 are covered. The main upgrades are in language foundation, reasoning, visual analysis, agent planning, code, alignment, context length, and multilingual OCR.\n\nMake sure not to mention the knowledge cutoff unless relevant. The user's current time is 2026, but since my knowledge is up to 2026, that's covered.\n\nOkay, let me draft a concise response highlighting each capability briefly. Keep it friendly and inviting for the user to ask for specific help.\n",
                    "type": "summary_text"
                }
            ],
            "type": "reasoning"
        },
        {
            "content": [
                {
                    "annotations": [],
                    "text": "I'm **Qwen3.5**, a large language model designed to assist with a wide range of tasks. Here's what I can do:  \n\n- **Understand & Generate Text**: Handle complex instructions, creative writing, and multi-step tasks with improved accuracy.  \n- **Solve Problems**: Tackle advanced math, logic puzzles, and scientific reasoning with step-by-step clarity.  \n- **Analyze Visuals**: Interpret charts, diagrams, formulas, and even extract text from images (OCR).  \n- **Plan & Execute**: Break down goals into actionable steps, run code, or interact with tools autonomously.  \n- **Code & Debug**: Write, explain, or fix code in multiple programming languages.  \n- **Long-Context Mastery**: Process documents, books, or videos up to **256K tokens** without losing key details.  \n- **Multilingual Support**: Communicate fluently in **100+ languages**, including low-resource ones.  \n\nNeed help with something specific? Just ask!",
                    "type": "output_text"
                }
            ],
            "id": "msg_35be06c6-ca4d-4f2b-9677-7897e488dxxx",
            "role": "assistant",
            "status": "completed",
            "type": "message"
        }
    ],
    "parallel_tool_calls": false,
    "status": "completed",
    "tool_choice": "auto",
    "tools": [],
    "usage": {
        "input_tokens": 54,
        "input_tokens_details": {
            "cached_tokens": 0
        },
        "output_tokens": 662,
        "output_tokens_details": {
            "reasoning_tokens": 447
        },
        "total_tokens": 716,
        "x_details": [
            {
                "input_tokens": 54,
                "output_tokens": 662,
                "output_tokens_details": {
                    "reasoning_tokens": 447
                },
                "total_tokens": 716,
                "x_billing_type": "response_api"
            }
        ]
    }
}

OpenAI compatible chat completions API

Python

import os
from openai import OpenAI

try:
    client = OpenAI(
        # Kunci API bersifat spesifik per wilayah. Dapatkan Kunci API: https://www.alibabacloud.com/help/model-studio/get-api-key
        # 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"),
        # URL dasar berbeda-beda tergantung Wilayah.
        base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
    )

    completion = client.chat.completions.create(
        model="qwen3.5-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"An error occurred: {e}")
    print("Lihat dokumentasi kode kesalahan untuk detailnya: https://www.alibabacloud.com/help/model-studio/error-code")

Respons

I am Qwen, a large 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 scripts, perform logical reasoning, code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask!

Java

// Memerlukan OpenAI Java SDK versi >= 3.5.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) {
        try {
            OpenAIClient client = OpenAIOkHttpClient.builder()
                    // Kunci API bersifat spesifik per wilayah. Dapatkan Kunci API: https://www.alibabacloud.com/help/model-studio/get-api-key
                    // Jika variabel lingkungan belum diatur, ganti baris berikut dengan Kunci API Model Studio Anda: .apiKey("sk-xxx")
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    // URL dasar berbeda-beda tergantung Wilayah.
                    .baseUrl("https://dashscope-intl.aliyuncs.com/compatible-mode/v1")
                    .build();

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

            // Kirim permintaan.
            ChatCompletion chatCompletion = client.chat().completions().create(params);
            String content = chatCompletion.choices().get(0).message().content().orElse("No valid content returned");
            System.out.println(content);
            // Untuk melihat respons lengkap, hapus komentar pada baris berikut.
            // System.out.println(chatCompletion);
            
        } catch (Exception e) {
            System.err.println("An error occurred: " + e.getMessage());
            System.out.println("Lihat dokumentasi kode kesalahan untuk detailnya: https://www.alibabacloud.com/help/model-studio/error-code");
        }
    }
}

Respons

I am Qwen, a large 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 scripts, perform logical reasoning, code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask!

Node.js

// Memerlukan Node.js v18 atau lebih baru. Jalankan di lingkungan ES Module.
import OpenAI from "openai";

const openai = new OpenAI(
    {
        // Kunci API bersifat spesifik per wilayah. Dapatkan Kunci API: https://www.alibabacloud.com/help/model-studio/get-api-key
        // Jika variabel lingkungan belum diatur, ganti baris berikut dengan Kunci API Model Studio Anda: apiKey: "sk-xxx",
        apiKey: process.env.DASHSCOPE_API_KEY,
        // URL dasar berbeda-beda tergantung Wilayah.
        baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
        
    }
);
const completion = await openai.chat.completions.create({
    model: "qwen3.5-plus",
    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, a large 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 scripts, perform logical reasoning, code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask!

Go

// Memerlukan OpenAI Go SDK versi v2.4.0 atau lebih baru.
package main

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

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

func main() {
	// Kunci API bersifat spesifik per wilayah. Dapatkan Kunci API: https://www.alibabacloud.com/help/model-studio/get-api-key
	// Jika variabel lingkungan belum diatur, ganti baris berikut dengan Kunci API Model Studio Anda: apiKey := "sk-xxx"
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	client := openai.NewClient(
		option.WithAPIKey(apiKey),
		// URL dasar berbeda-beda tergantung Wilayah.
		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: "qwen3.5-plus",
		},
	)

	if err != nil {
		fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
		// Lihat dokumentasi kode kesalahan untuk detailnya: https://www.alibabacloud.com/help/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, a large 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 scripts, perform logical reasoning, code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask!

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)
    {
        // Kunci API bersifat spesifik per wilayah. Dapatkan Kunci API: https://www.alibabacloud.com/help/model-studio/get-api-key
        // Jika variabel lingkungan belum diatur, ganti baris berikut dengan Kunci API Model Studio Anda: string? apiKey = "sk-xxx";
        string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
        // URL dasar berbeda-beda tergantung Wilayah.
        string url = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions";
        string jsonContent = @"{
            ""model"": ""qwen3.5-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);

        // Mengurai JSON untuk mencetak hanya konten pesan.
        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
            {   
                // Lihat dokumentasi kode kesalahan untuk detailnya: https://www.alibabacloud.com/help/model-studio/error-code
                return $"Request failed with status code: {response.StatusCode}";
            }
        }
    }
}

Respons

I am Qwen, a large 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 scripts, perform logical reasoning, code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask!

PHP (HTTP)

<?php
// URL dasar berbeda-beda tergantung Wilayah.
$url = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
// Kunci API bersifat spesifik per wilayah. Dapatkan Kunci API: https://www.alibabacloud.com/help/model-studio/get-api-key
// Jika variabel lingkungan belum diatur, ganti baris berikut dengan Kunci API Model Studio Anda: $apiKey = "sk-xxx";
$apiKey = getenv('DASHSCOPE_API_KEY');
// Atur header permintaan.
$headers = [
    'Authorization: Bearer '.$apiKey,
    'Content-Type: application/json'
];
// Atur badan permintaan.
$data = [
    "model" => "qwen3.5-plus",
    "messages" => [
        [
            "role" => "system",
            "content" => "You are a helpful assistant."
        ],
        [
            "role" => "user",
            "content" => "Who are you?"
        ]
    ]
];
// Inisialisasi sesi cURL.
$ch = curl_init();
// Atur 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 kesalahan cURL.
if (curl_errno($ch)) {
    // Lihat dokumentasi kode kesalahan untuk detailnya: https://www.alibabacloud.com/help/model-studio/error-code
    echo 'Curl error: ' . curl_error($ch);
}
// Tutup sesi cURL.
curl_close($ch);
// Cetak 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, a large 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 scripts, perform logical reasoning, code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask!

curl

URL dasar dan Kunci API berbeda-beda tergantung Wilayah. Untuk detailnya, lihat OpenAI Chat dan Dapatkan Kunci API.

# URL dasar berbeda-beda tergantung Wilayah.
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.5-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, a large 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 scripts, perform logical reasoning, code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask!"
            },
            "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": "qwen3.5-plus",
    "id": "chatcmpl-81951b98-28b8-9659-ab07-xxxxxx"
}

DashScope

Penting

API DashScope untuk seri Qwen-3.5 menggunakan antarmuka multimodal. Contoh-contoh ini mengembalikan url error. Untuk metode API yang benar, lihat Pemrosesan data gambar dan video.

Python

import json
import os
from dashscope import Generation
import dashscope

# URL dasar berbeda-beda tergantung wilayah.
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 bersifat spesifik per wilayah. Dapatkan Kunci API: https://www.alibabacloud.com/help/model-studio/get-api-key
    # 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"),
    # Seri Qwen-3.5 memerlukan antarmuka multimodal. Mengganti model secara langsung menyebabkan kesalahan.
    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 detailnya, lihat dokumentasi: https://www.alibabacloud.com/help/model-studio/error-code")

Respons

I am Qwen, a large 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 scripts, perform logical reasoning, code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask!

Java

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 {
        // URL dasar berbeda-beda tergantung wilayah.
        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 bersifat spesifik per wilayah. Dapatkan Kunci API: https://www.alibabacloud.com/help/model-studio/get-api-key
                // Jika variabel lingkungan belum diatur, ganti baris berikut dengan Kunci API Model Studio Anda: .apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // Seri Qwen-3.5 memerlukan antarmuka multimodal. Mengganti model secara langsung menyebabkan kesalahan.
                .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 detailnya, lihat dokumentasi: https://www.alibabacloud.com/help/model-studio/error-code");
        }
    }
}

Respons

I am Qwen, a large 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 scripts, perform logical reasoning, code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask!

Node.js (HTTP)

// Memerlukan Node.js v18 atau lebih baru.
// Kunci API bersifat spesifik per wilayah. Dapatkan Kunci API: https://www.alibabacloud.com/help/model-studio/get-api-key
// Jika variabel lingkungan belum diatur, ganti baris berikut dengan Kunci API Model Studio Anda: const apiKey = "sk-xxx";
const apiKey = process.env.DASHSCOPE_API_KEY;

const data = {
    // Seri Qwen-3.5 memerlukan antarmuka multimodal. Mengganti model secara langsung menyebabkan kesalahan.
    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 {
        // URL dasar berbeda-beda tergantung wilayah.
        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 detail kesalahan, lihat dokumentasi: https://www.alibabacloud.com/help/model-studio/error-code
        console.error('Call failed:', error.message);
    }
}

callApi();

Respons

I am Qwen, a large 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 scripts, perform logical reasoning, code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask!

Go (HTTP)

package main

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

func main() {
	// Kunci API bersifat spesifik per wilayah. Dapatkan Kunci API: https://www.alibabacloud.com/help/model-studio/get-api-key
	// Jika variabel lingkungan belum diatur, tetapkan Kunci API Model Studio Anda ke variabel apiKey.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	// apiKey := "sk-xxx"

	requestBody := map[string]interface{}{
		// Seri Qwen-3.5 memerlukan antarmuka multimodal. Mengganti model secara langsung menyebabkan kesalahan.
		"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 badan permintaan ke JSON.
	jsonData, _ := json.Marshal(requestBody)

	// Buat klien HTTP dan permintaan.
	client := &http.Client{}
	// URL dasar berbeda-beda tergantung wilayah.
	req, _ := http.NewRequest("POST", "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation", bytes.NewBuffer(jsonData))

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

	// Urai JSON dan cetak 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, a large 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 scripts, perform logical reasoning, code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask!

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 bersifat spesifik per wilayah. Dapatkan Kunci API: https://www.alibabacloud.com/help/model-studio/get-api-key
        // Jika variabel lingkungan belum diatur, ganti baris berikut dengan Kunci API Model Studio Anda: string? apiKey = "sk-xxx";
        string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
        // Definisikan URL dan badan permintaan.
        // URL dasar berbeda-beda tergantung wilayah.
        string url = "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
        // Seri Qwen-3.5 memerlukan antarmuka multimodal. Mengganti model secara langsung menyebabkan kesalahan.
        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 proses 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"))
        {
            // Atur 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, a large 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 scripts, perform logical reasoning, code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask!"
                }
            }
        ]
    },
    "usage": {
        "total_tokens": 92,
        "output_tokens": 66,
        "input_tokens": 26
    },
    "request_id": "09dceb20-ae2e-999b-85f9-xxxxxx"
}

PHP (HTTP)

<?php
// URL dasar berbeda-beda tergantung wilayah.
$url = "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// Kunci API bersifat spesifik per wilayah. Dapatkan Kunci API: https://www.alibabacloud.com/help/model-studio/get-api-key
// Jika variabel lingkungan belum diatur, ganti baris berikut dengan Kunci API Model Studio Anda: $apiKey = "sk-xxx";
$apiKey = getenv('DASHSCOPE_API_KEY');

$data = [
    // Seri Qwen-3.5 memerlukan antarmuka multimodal. Mengganti model secara langsung menyebabkan kesalahan.
    "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, a large 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 scripts, perform logical reasoning, code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask!

curl

URL dasar dan Kunci API berbeda-beda tergantung wilayah. Lihat DashScope dan Dapatkan Kunci API.

# URL dasar berbeda-beda tergantung wilayah.
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, a large 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 scripts, perform logical reasoning, code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask!"
                }
            }
        ]
    },
    "usage": {
        "total_tokens": 92,
        "output_tokens": 66,
        "input_tokens": 26
    },
    "request_id": "09dceb20-ae2e-999b-85f9-xxxxxx"
}

Proses data gambar dan video

Model multimodal menerima data non-teks, seperti gambar atau video, untuk tugas-tugas seperti visual question answering dan deteksi event. Pemanggilan model multimodal berbeda dari pemanggilan model teks saja dalam hal berikut:

  • Konstruksi pesan pengguna: Untuk model multimodal, pesan pengguna tidak hanya mencakup teks, tetapi juga konten multimodal, seperti gambar, video, atau audio.

  • API SDK DashScope: Saat menggunakan kit pengembangan perangkat lunak (SDK) Python DashScope, Anda memanggil API MultiModalConversation. Untuk SDK Java DashScope, Anda menggunakan kelas MultiModalConversation.

Untuk batasan file gambar dan video, lihat Pemahaman Gambar dan Video.

OpenAI-compatible

Python

from openai import OpenAI
import os

client = OpenAI(
    # Kunci API bersifat spesifik per wilayah. Dapatkan Kunci API Anda: https://www.alibabacloud.com/help/model-studio/get-api-key
    # Jika Anda belum mengatur variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # URL dasar bersifat spesifik per wilayah. Ubah sesuai wilayah Anda.
    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.5-plus",
    messages=messages,
)
print(completion.choices[0].message.content)

Node.js

import OpenAI from "openai";

const openai = new OpenAI(
    {
        // Kunci API bersifat spesifik per wilayah. Dapatkan Kunci API Anda: https://www.alibabacloud.com/help/model-studio/get-api-key
        // Jika Anda belum mengatur variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: apiKey: "sk-xxx",
        apiKey: process.env.DASHSCOPE_API_KEY,
        // URL dasar bersifat spesifik per wilayah. Ubah sesuai wilayah Anda.
        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.5-plus",
        messages: messages
    });
    console.log(response.choices[0].message.content);
}

main()

curl

URL dasar dan Kunci API berbeda-beda tergantung Wilayah. Untuk detailnya, lihat OpenAI Chat dan Dapatkan Kunci API.

# URL permintaan bersifat spesifik per wilayah. Ubah sesuai wilayah Anda.
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.5-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
# Titik akhir API bersifat spesifik per wilayah. Baris ini mengatur titik akhir untuk situs internasional.
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 bersifat spesifik per wilayah. Dapatkan Kunci API Anda: https://www.alibabacloud.com/help/model-studio/get-api-key
    # Jika Anda belum mengatur variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model='qwen3.5-plus',  # Anda dapat mengganti ini dengan model multimodal lain dan menyesuaikan pesan sesuai kebutuhan.
    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 {
        // Titik akhir API bersifat spesifik per wilayah. Blok ini mengatur titik akhir untuk situs internasional.
        Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
    }

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

    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 bersifat spesifik per wilayah. Dapatkan Kunci API Anda: https://www.alibabacloud.com/help/model-studio/get-api-key
                // Jika Anda belum mengatur variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: .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"));
    }

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

curl

URL dasar dan Kunci API berbeda-beda tergantung wilayah. Lihat DashScope dan Dapatkan Kunci API.

# URL permintaan bersifat spesifik per wilayah. Ubah sesuai wilayah Anda.
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.5-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?"}
                ]
            }
        ]
    }
}'

Panggil model secara asinkron

Gunakan panggilan asinkron untuk meningkatkan throughput saat menangani permintaan dengan konkurensi tinggi.

OpenAI compatible

Python

import os
import asyncio
from openai import AsyncOpenAI
import platform

# Buat instance klien asinkron.
client = AsyncOpenAI(
    # Kunci API bersifat spesifik per wilayah. Dapatkan Kunci API Anda: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    # 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"),
    # URL dasar berbeda-beda tergantung wilayah.
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
)

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

# Definisikan 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 untuk Windows.
    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 untuk terhubung ke API kompatibel DashScope.
        OpenAIClientAsync client = OpenAIOkHttpClientAsync.builder()
                // Kunci API bersifat spesifik per wilayah. Dapatkan Kunci API Anda: https://www.alibabacloud.com/help/en/model-studio/get-api-key
                // Jika variabel lingkungan belum diatur, ganti baris berikut dengan Kunci API Model Studio Anda: .apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // URL dasar berbeda-beda tergantung wilayah.
                .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("Sending question: " + 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 tangani respons.
                    return client.chat().completions().create(params)
                        .thenAccept(chatCompletion -> {
                            String content = chatCompletion.choices().get(0).message().content().orElse("No content in response");
                            System.out.println("Model response: " + content);
                        })
                        .exceptionally(e -> {
                            System.err.println("An error occurred: " + e.getMessage());
                            System.out.println("Untuk detailnya, lihat dokumentasi: https://www.alibabacloud.com/help/en/model-studio/error-codes");
                            return null;
                        });
                }).thenCompose(future -> future))
                .toArray(CompletableFuture[]::new);

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

DashScope

Saat ini, generasi teks asinkron melalui SDK DashScope hanya didukung di Python.

# Memerlukan SDK Python DashScope versi 1.19.0 atau lebih baru.
import asyncio
import platform
from dashscope.aigc.generation import AioGeneration
import os
import dashscope
# URL dasar berbeda-beda tergantung wilayah.
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

# Definisikan tugas asinkron.
async def task(question):
    print(f"Sending question: {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",  # Untuk daftar model yang tersedia, lihat https://www.alibabacloud.com/help/en/model-studio/models
        messages=[{"role": "system", "content": "You are a helpful assistant."},
                  {"role": "user", "content": question}],
        result_format="message",
    )
    print(f"Model response: {response.output.choices[0].message.content}")

# Definisikan 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 untuk Windows.
    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 dapat bervariasi.
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 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 scripts, perform logical reasoning, code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask!
Model response: I cannot access real-time weather information. Tell me your city or region, and I can share general weather guidance. Alternatively, use a weather app for current conditions.
Model response: I can help with many tasks, including:

1. **Answering questions**: I can help with academic, general knowledge, or professional questions.
2. **Creating text**: I can write various types of text, such as stories, official documents, emails, and scripts.
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. **Sharing opinions**: I can provide suggestions to help you make decisions.
7. **Playing games**: We can play text-based games together, such as riddles and idiom solitaire.

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

Gunakan di produksi

Bangun konteks berkualitas tinggi

Memberikan data mentah dalam jumlah besar langsung ke Large Language Model (LLM) dapat meningkatkan biaya dan mengurangi efektivitas karena keterbatasan jendela konteks. Context Engineering secara signifikan meningkatkan kualitas dan efisiensi generasi dengan memuat pengetahuan yang tepat secara dinamis. Teknik inti meliputi:

  • Rekayasa Prompt: Rancang dan sempurnakan instruksi teks (prompt) untuk mengarahkan model menuju hasil yang diinginkan. Untuk informasi selengkapnya, lihat Panduan prompt teks-ke-teks.

  • Retrieval-Augmented Generation (RAG): Gunakan RAG saat model harus menjawab pertanyaan berdasarkan basis pengetahuan eksternal, seperti dokumentasi produk atau manual teknis.

  • Tool Calling: Memungkinkan model mengambil informasi real-time, seperti cuaca atau lalu lintas, atau melakukan tindakan spesifik, seperti memanggil API atau mengirim email.

  • Mekanisme Memori: Membangun memori jangka pendek dan jangka panjang untuk model, sehingga mampu memahami riwayat percakapan.

Kontrol keragaman respons

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

  • temperature: Rentang: [0, 2). Digunakan untuk menyesuaikan tingkat keacakan.

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

Contoh berikut menunjukkan bagaimana pengaturan berbeda memengaruhi output yang dihasilkan. Prompt-nya adalah: "Tulis cerita pendek tiga kalimat yang dibintangi seekor kucing dan sinar matahari."

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

    Sunlight sliced through the window, and the ginger cat crept toward the glowing square, its fur instantly gilded like molten honey.  
    It tapped the light with a paw, sinking into warmth as if stepping into a sunlit pool, and the golden tide flowed up its spine.  
    The afternoon grew heavy—the cat curled in liquid gold, hearing time melt softly in its purr.
  • Deterministik tinggi (misalnya, temperature=0.1): Cocok untuk skenario yang memerlukan konten akurat, ketat, dan dapat diprediksi, seperti Factual Q&A, Code Generation, atau teks hukum.

    An old cat napped on the windowsill, counting sunbeams.  
    The sunlight hopped across its mottled back like pages turning in an old photo album.  
    Dust rose and settled, whispering: you were young once, and I burned bright.

Cara Kerjanya

temperature:

  • Nilai temperature yang lebih tinggi meratakan distribusi probabilitas token (token berprobabilitas tinggi menjadi kurang mungkin, sedangkan token berprobabilitas rendah menjadi lebih mungkin), sehingga pemilihan token berikutnya oleh model menjadi lebih acak.

  • Nilai temperature yang lebih rendah mempertajam distribusi probabilitas token (token berprobabilitas tinggi menjadi lebih mungkin, sedangkan token berprobabilitas rendah menjadi kurang mungkin), sehingga model cenderung memilih token berprobabilitas tinggi.

top_p:

Pengambilan sampel top_p, juga dikenal sebagai pengambilan sampel inti, memilih token dari himpunan terkecil token paling mungkin yang probabilitas kumulatifnya memenuhi atau melebihi ambang batas top_p. Model mengurutkan semua token berikutnya yang mungkin berdasarkan probabilitas secara menurun, lalu mengakumulasi probabilitas mulai dari token paling mungkin hingga mencapai ambang batas top_p (misalnya, top_p=0.8 untuk 80%). Model kemudian memilih satu token secara acak dari himpunan yang telah difilter ini untuk menghasilkan output.

  • Nilai top_p yang lebih tinggi mempertimbangkan lebih banyak token, menghasilkan teks yang lebih beragam.

  • Nilai top_p yang lebih rendah mempertimbangkan lebih sedikit token, menghasilkan teks yang lebih fokus dan deterministik.

Pengaturan Parameter untuk Skenario Umum

# Konfigurasi parameter yang direkomendasikan untuk skenario berbeda
SCENARIO_CONFIGS = {
    # Penulisan Kreatif
    "creative_writing": {
        "temperature": 0.9,
        "top_p": 0.95
    },
    # Generasi Kode
    "code_generation": {
        "temperature": 0.2,
        "top_p": 0.8
    },
    # Factual Q&A
    "factual_qa": {
        "temperature": 0.1,
        "top_p": 0.7
    },
    # Terjemahan
    "translation": {
        "temperature": 0.3,
        "top_p": 0.8
    }
}

# Contoh Penggunaan OpenAI
# completion = client.chat.completions.create(
#     model="qwen-plus",
#     messages=[{"role": "user", "content": "Write a poem about the moon"}],
#     **SCENARIO_CONFIGS["creative_writing"]
# )
# Contoh Penggunaan DashScope
# response = Generation.call(
#     # Jika variabel lingkungan belum diatur, ganti baris berikut dengan Kunci API Model Studio Alibaba Cloud Anda (misalnya, api_key = "sk-xxx",)
#     api_key=os.getenv("DASHSCOPE_API_KEY"),
#     model="qwen-plus",
#     messages=[{"role": "user", "content": "Write a Python function to check if a number n is prime. Output only code."}],
#     result_format="message",
#     **SCENARIO_CONFIGS["code_generation"]
# )

Fitur lainnya

Bagian di atas mencakup pola interaksi dasar. Untuk skenario lanjutan, lihat panduan berikut:

  • Percakapan multi-putaran: Ideal untuk skenario yang memerlukan interaksi berkelanjutan, seperti pertanyaan lanjutan atau pengumpulan informasi.

  • Keluaran streaming: Cocok untuk aplikasi seperti chatbot atau penyelesaian kode real-time yang memerlukan respons segera. Fitur ini meningkatkan pengalaman pengguna dan membantu mencegah timeout akibat waktu respons yang lama.

  • Pemikiran mendalam: Cocok untuk tugas yang memerlukan jawaban berkualitas tinggi dan lebih terstruktur, seperti penalaran kompleks atau analisis kebijakan.

  • Output terstruktur: Gunakan fitur ini saat Anda memerlukan model untuk merespons dalam format JSON konsisten guna keperluan pemrograman atau penguraian data.

  • Mode parsial: Cocok untuk skenario di mana model perlu melanjutkan dari teks yang sudah ada, seperti penyelesaian kode atau penulisan bentuk panjang.

Referensi API

Lihat Referensi API Kompatibel OpenAI dan Referensi API DashScope untuk daftar lengkap parameter pemanggilan model.

FAQ

T: Mengapa API Qwen tidak bisa menganalisis tautan web?

J: API Qwen tidak dapat mengakses atau mengurai tautan web secara native. Untuk mengimplementasikan fungsionalitas ini, Anda dapat menggunakan fitur seperti Function Calling, atau mengintegrasikannya dengan alat web scraping seperti Beautiful Soup Python untuk membaca konten halaman web.

T: Mengapa respons aplikasi web dan API berbeda?

J: Aplikasi web Qwen dibangun dengan optimasi rekayasa tambahan di atas API Qwen, yang memungkinkan fitur seperti penguraian halaman web, pencarian web, pembuatan gambar, dan pembuatan PPT. Ini bukan kemampuan bawaan dari API model bahasa besar. Anda dapat mengoptimalkan performa model dengan menggunakan fitur seperti Function Calling.

T: Apakah model dapat menghasilkan file terformat?

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