All Products
Search
Document Center

Alibaba Cloud Model Studio:Ikhtisar

Last Updated:Aug 26, 2026

Model generasi teks menghasilkan teks dari prompt bahasa alami untuk aplikasi seperti chatbot, pembuatan konten, ringkasan dokumen, dan penulisan kode.

Input dapat berupa satu kata kunci hingga prompt kompleks multi-langkah dengan konteks. Kasus penggunaan umum meliputi:

  • Pembuatan konten: Hasilkan artikel berita, deskripsi produk, dan skrip video format pendek.
  • Layanan pelanggan: Bangun chatbot otomatis 24/7 untuk menjawab pertanyaan yang sering diajukan.
  • Terjemahan teks: Terjemahkan teks antar berbagai bahasa.
  • Ringkasan: Ringkas artikel panjang, laporan, dan email.
  • Penyusunan dokumen hukum: Susun templat kontrak dan opini hukum.

Konsep utama

Input ke model generasi teks adalah prompt, yang terdiri dari satu atau beberapa objek message masing-masing berisi role dan content:

  • Pesan sistem: Menetapkan persona model, panduan perilaku, atau instruksi spesifik tugas. Nilai default-nya adalah "You are a helpful assistant."
  • Pesan pengguna: Pertanyaan, instruksi, atau input pengguna ke model.
  • Pesan asisten: Tanggapan model. Dalam percakapan multi-putaran, sertakan pesan asisten historis untuk mempertahankan konteks.

Untuk memanggil model, buat array objek message tersebut dengan nama messages. Permintaan tipikal terdiri dari pesan system yang menetapkan panduan perilaku dan pesan user berisi input pengguna.

Pesan system bersifat opsional tetapi direkomendasikan. Mendefinisikan peran dan batasan perilaku model menghasilkan output yang lebih konsisten dan dapat diprediksi.

[
    {"role": "system", "content": "You are a helpful assistant who provides precise, efficient, and insightful responses, ready to assist users with various tasks and questions."},
    {"role": "user", "content": "Who are you?"}
]

Tanggapan berisi balasan model dalam pesan assistant.

{
    "role": "assistant",
    "content": "Hello! I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you with tasks like answering questions, creating text, logical reasoning, and coding. I understand and generate multiple languages, and can handle multi-turn conversations and complex instructions. If there is anything you need help with, just let me know!"
}

Mulai cepat

Prasyarat: Dapatkan Kunci API dan Konfigurasikan kunci API sebagai variabel lingkungan. Jika menggunakan SDK, juga instal OpenAI atau SDK DashScope. {WorkspaceId} pada URL dasar contoh adalah ID ruang kerja Anda. Untuk cara mendapatkannya, lihat Wilayah dan domain akses.

API Chat Completions Kompatibel OpenAI

Python

import os
from openai import OpenAI

try:
    client = OpenAI(
        # Kunci API bervariasi berdasarkan wilayah. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
        # Jika Anda belum mengatur variabel lingkungan, ganti baris berikut dengan Kunci API Alibaba Cloud Model Studio Anda: api_key="sk-xxx",
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # Titik akhir untuk wilayah Asia Pasifik SE 1 (Singapura). Ganti {WorkspaceId} dengan ID Ruang Kerja Anda. URL bervariasi berdasarkan wilayah.
        base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
    )

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

Tanggapan

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!

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()
                    // Kunci API bervariasi berdasarkan wilayah. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
                    // Jika Anda belum mengatur variabel lingkungan, ganti baris berikut dengan Kunci API Alibaba Cloud Model Studio Anda: .apiKey("sk-xxx")
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    // Titik akhir untuk wilayah Asia Pasifik SE 1 (Singapura). Ganti {WorkspaceId} dengan ID Ruang Kerja Anda. URL bervariasi berdasarkan wilayah.
                    .baseUrl("https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1")
                    .build();

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

            // Kirim permintaan dan terima tanggapan.
            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 dokumentasi: https://www.alibabacloud.com/help/en/model-studio/error-code");
        }
    }
}

Tanggapan

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!

Node.js

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

const openai = new OpenAI(
    {
        // Kunci API bervariasi berdasarkan wilayah. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
        // Jika Anda belum mengatur variabel lingkungan, ganti baris berikut dengan Kunci API Alibaba Cloud Model Studio Anda: apiKey: "sk-xxx",
        apiKey: process.env.DASHSCOPE_API_KEY,
        // Titik akhir untuk wilayah Asia Pasifik SE 1 (Singapura). Ganti {WorkspaceId} dengan ID Ruang Kerja Anda. URL bervariasi berdasarkan wilayah.
        baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"

    }
);
const completion = await openai.chat.completions.create({
    model: "qwen3.8-max",
    messages: [
        { role: "system", content: "You are a helpful assistant." },
        { role: "user", content: "Who are you?" }
    ],
});
console.log(completion.choices[0].message.content);
// Untuk melihat tanggapan lengkap, hapus komentar baris berikut.
// console.log(JSON.stringify(completion, null, 4));

Tanggapan

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!

Go

// Kami merekomendasikan menggunakan OpenAI Go SDK v2.4.0 atau yang lebih baru.
package main

import (
	"context"
	// Untuk melihat tanggapan lengkap, hapus komentar impor di bawah dan kode terkait di bagian akhir.
	// "encoding/json"
	"fmt"
	"os"

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

func main() {
	// Jika Anda belum mengatur variabel lingkungan, ganti baris berikut dengan Kunci API Alibaba Cloud Model Studio Anda: apiKey := "sk-xxx"
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	client := openai.NewClient(
		option.WithAPIKey(apiKey),
		// Kunci API bervariasi berdasarkan wilayah. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
		// Titik akhir untuk wilayah Asia Pasifik SE 1 (Singapura). Ganti {WorkspaceId} dengan ID Ruang Kerja Anda. URL bervariasi berdasarkan wilayah.
		option.WithBaseURL("https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"),
	)
	chatCompletion, err := client.Chat.Completions.New(
		context.TODO(), openai.ChatCompletionNewParams{
			Messages: []openai.ChatCompletionMessageParamUnion{
				openai.SystemMessage("You are a helpful assistant."),
				openai.UserMessage("Who are you?"),
			},
			Model: "qwen3.8-max",
		},
	)

	if err != nil {
		fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
		// Untuk informasi lebih lanjut, lihat dokumentasi: 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 tanggapan lengkap, hapus komentar baris berikut.
	// jsonData, _ := json.MarshalIndent(chatCompletion, "", "  ")
	// fmt.Println(string(jsonData))

}

Tanggapan

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. 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)
    {
        // Jika Anda belum mengatur variabel lingkungan, ganti baris berikut dengan Kunci API Alibaba Cloud Model Studio Anda: string? apiKey = "sk-xxx";
        string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
        // Titik akhir untuk wilayah Asia Pasifik SE 1 (Singapura). Ganti {WorkspaceId} dengan ID Ruang Kerja Anda. URL bervariasi berdasarkan wilayah.
        string url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions";
        string jsonContent = @"{
            ""model"": ""qwen3.8-max"",
            ""messages"": [
                {
                    ""role"": ""system"",
                    ""content"": ""You are a helpful assistant.""
                },
                {
                    ""role"": ""user"",
                    ""content"": ""Who are you?""
                }
            ]
        }";

        // Kirim permintaan dan terima tanggapan.
        string result = await SendPostRequestAsync(url, jsonContent, apiKey);

        // Untuk melihat tanggapan lengkap, hapus komentar baris berikut.
        // Console.WriteLine(result);

        // Uraikan JSON untuk mengekstrak dan mencetak konten.
        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, lihat dokumentasi: https://www.alibabacloud.com/help/en/model-studio/error-code
                return $"Request failed: {response.StatusCode}";
            }
        }
    }
}

Tanggapan

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!

PHP (HTTP)

<?php
// Atur URL permintaan.
// Titik akhir untuk wilayah Asia Pasifik SE 1 (Singapura). Ganti {WorkspaceId} dengan ID Ruang Kerja Anda. URL bervariasi berdasarkan wilayah.
$url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions';
// Kunci API bervariasi berdasarkan wilayah. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
// Jika Anda belum mengatur variabel lingkungan, ganti baris berikut dengan Kunci API Alibaba Cloud Model Studio Anda: $apiKey = "sk-xxx";
$apiKey = getenv('DASHSCOPE_API_KEY');
// Atur header permintaan.
$headers = [
    'Authorization: Bearer '.$apiKey,
    'Content-Type: application/json'
];
// Atur isi permintaan.
$data = [
    "model" => "qwen3.8-max",
    "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.
// Untuk informasi lebih lanjut, lihat dokumentasi: 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);
// Uraikan dan tampilkan konten tanggapan.
$dataObject = json_decode($response);
$content = $dataObject->choices[0]->message->content;
echo $content;
// Untuk melihat tanggapan lengkap, hapus komentar baris berikut.
//echo $response;
?>

Tanggapan

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!

curl

'base_url' dan kunci API bersifat spesifik wilayah. Lihat Kompatibel OpenAI - Chat untuk URL titik akhir dan Dapatkan kunci API untuk mendapatkan kunci Anda.

# Ubah URL titik akhir sesuai wilayah Anda.
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen3.8-max",
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "Who are you?"
        }
    ]
}'

Tanggapan

{
    "choices": [
        {
            "message": {
                "role": "assistant",
                "content": "I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. 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.8-max",
    "id": "chatcmpl-81951b98-28b8-9659-ab07-xxxxxx"
}

API Responses Kompatibel OpenAI

API Responses menggantikan API Chat Completions. Untuk petunjuk penggunaan, contoh kode, dan panduan migrasi, lihat Responses Kompatibel OpenAI.

Python

import os
from openai import OpenAI

try:
    client = OpenAI(
        # Kunci API bervariasi menurut Wilayah. Dapatkan Kunci API Anda di: https://www.alibabacloud.com/help/en/model-studio/get-api-key
        # Jika Anda tidak mengatur variabel lingkungan, berikan Kunci API Anda secara langsung: api_key="sk-xxx",
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # URL dasar bervariasi menurut Wilayah. Perbarui agar sesuai dengan Wilayah layanan Anda.
        base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
    )

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

    print(response)
except Exception as e:
    print(f"An error occurred: {e}")
    print("For details, see the error code documentation: https://www.alibabacloud.com/help/en/model-studio/error-code")

Tanggapan

Bidang tanggapan utama:

  • id: ID tanggapan.

  • output: Daftar berisi objek reasoning dan message.

    reasoning hanya muncul ketika thinking diaktifkan (diaktifkan secara default untuk seri Qwen3.6).

  • usage: Penggunaan token.

Konten pesan contoh. Untuk tanggapan lengkap, lihat bagian curl.

Hello! I'm an AI assistant with knowledge current as of 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

// Diperlukan Node.js v18+. Kode ini harus dijalankan di lingkungan ES Module.
import OpenAI from "openai";

const openai = new OpenAI({
    // Kunci API bervariasi berdasarkan wilayah. Dapatkan Kunci API Anda di: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    // Jika Anda tidak mengatur variabel lingkungan, berikan Kunci API Anda secara langsung: apiKey: "sk-xxx",
    apiKey: process.env.DASHSCOPE_API_KEY,
    // URL dasar bervariasi berdasarkan wilayah. Perbarui agar sesuai dengan wilayah layanan Anda.
    baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
});

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

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

main();

Tanggapan

Bidang tanggapan utama:

  • id: ID tanggapan.

  • output: Daftar berisi objek reasoning dan message.

    reasoning hanya muncul ketika thinking diaktifkan (diaktifkan secara default untuk seri Qwen3.6).

  • usage: Penggunaan token.

Konten pesan contoh. Untuk tanggapan lengkap, lihat bagian curl.

Hello! I'm an AI assistant with knowledge current as of 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

# URL titik akhir bervariasi berdasarkan wilayah. Perbarui agar sesuai dengan wilayah layanan Anda.
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen3.8-max",
    "input": "Briefly introduce what you can do.",
    "enable_thinking": true
}'

Tanggapan

{
    "created_at": 1772249518,
    "id": "7ad48c6b-3cc4-904f-9284-5f419c6c5xxx",
    "model": "qwen3.8-max",
    "object": "response",
    "output": [
        {
            "id": "msg_94805179-2801-45da-ac1c-a87e8ea20xxx",
            "summary": [
                {
                    "text": "The user is asking for a brief introduction of my capabilities. I will start by recalling the features listed in the system message, ensuring I cover the main points concisely.\n\nFirst, I should mention the enhanced language foundation and architectural efficiency. Next, the upgraded logical reasoning and mathematical capabilities. Visual analysis, including charts and formulas, is a key point. Autonomous agent planning and code generation are also important. Other features include human alignment optimization for better interaction, long-context handling up to 256K tokens, and multilingual support with OCR.\n\nSince the user asked for a \"brief\" overview, I need to be concise. I will group some points together and summarize each capability in a sentence or two, avoiding technical jargon where possible. I'll check the examples in the system message for a suitable structure.\n\nTo make it practical, I'll highlight how these features apply to real tasks, such as handling long documents, solving math problems, analyzing images, and writing code.\n\nI will structure the response as a list of key capabilities with short explanations, starting with a greeting and ending with an offer to help with specific tasks.\n\nMy introduction will identify me as the requested model, qwen3.7-max.\n\nI will not mention the knowledge cutoff unless it's relevant. Since the current date is 2026 and my knowledge is current as of 2026, this is not an issue.\n\nMy draft will be a concise, friendly, and inviting response that highlights each capability.\n",
                    "type": "summary_text"
                }
            ],
            "type": "reasoning"
        },
        {
            "content": [
                {
                    "annotations": [],
                    "text": "I'm **Qwen3.6-plus**, 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"
            }
        ]
    }
}

DashScope

Pentingqwen3.7-max, qwen3.7-max-2026-05-20, dan qwen3.6-max-preview hanya mendukung API teks. qwen3.8-max, qwen3.8-flash, dan qwen3.7-max-2026-06-08 mendukung API multimodal. Seri Qwen3.6 dan Qwen3.5 memerlukan API DashScope multimodal. Menjalankan contoh berikut dengan model-model ini akan mengembalikan url error. Untuk pemanggilan API multimodal yang benar, lihat Pemrosesan Data Gambar dan Video.

Python

import json
import os
from dashscope import Generation
import dashscope

// URL berikut untuk wilayah Singapura. Ganti {WorkspaceId} dengan ID Ruang Kerja Anda. URL bervariasi berdasarkan wilayah.
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"

messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Who are you?"},
]
response = Generation.call(
    // Kunci API bervariasi berdasarkan wilayah. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/en/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"),
    // qwen3.7-max, qwen3.7-max-2026-05-20, dan qwen3.6-max-preview hanya mendukung API teks. qwen3.8-max dan qwen3.7-max-2026-06-08 mendukung API multimodal. Seri Qwen3.6 dan Qwen3.5 memerlukan API multimodal. Mengganti model secara langsung akan menyebabkan kesalahan.
    model="qwen-plus",
    messages=messages,
    result_format="message",
)

if response.status_code == 200:
    print(response.output.choices[0].message.content)
    // Untuk melihat tanggapan lengkap, hapus komentar 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")

Tanggapan

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. 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 berikut untuk wilayah Singapura. Ganti {WorkspaceId} dengan ID Ruang Kerja Anda. URL bervariasi berdasarkan wilayah.
        Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("You are a helpful assistant.")
                .build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content("Who are you?")
                .build();
        GenerationParam param = GenerationParam.builder()
                // Kunci API bervariasi berdasarkan wilayah. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/en/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"))
                // qwen3.7-max, qwen3.7-max-2026-05-20, dan qwen3.6-max-preview hanya mendukung API teks. qwen3.8-max dan qwen3.7-max-2026-06-08 mendukung API multimodal. Seri Qwen3.6 dan Qwen3.5 memerlukan API multimodal. Mengganti model secara langsung akan 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 tanggapan lengkap, hapus komentar 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");
        }
    }
}

Tanggapan

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!

Node.js (HTTP)

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

const data = {
    // qwen3.7-max, qwen3.7-max-2026-05-20, dan qwen3.6-max-preview hanya mendukung API teks. qwen3.8-max dan qwen3.7-max-2026-06-08 mendukung API multimodal. Seri Qwen3.6 dan Qwen3.5 memerlukan API multimodal. Mengganti model secara langsung akan 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 berikut untuk wilayah Singapura. Ganti {WorkspaceId} dengan ID Ruang Kerja Anda. URL bervariasi berdasarkan wilayah.
            const response = await fetch('https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });

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

callApi();

Tanggapan

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. 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() {
	requestBody := map[string]interface{}{
		// qwen3.7-max, qwen3.7-max-2026-05-20, dan qwen3.6-max-preview hanya mendukung API teks. qwen3.8-max dan qwen3.7-max-2026-06-08 mendukung API multimodal. Seri Qwen3.6 dan Qwen3.5 memerlukan API multimodal. Mengganti model secara langsung akan 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 ke JSON.
	jsonData, _ := json.Marshal(requestBody)

	// Buat klien HTTP dan permintaan.
	client := &http.Client{}
	// URL berikut untuk wilayah Singapura. Ganti {WorkspaceId} dengan ID Ruang Kerja Anda. URL bervariasi berdasarkan wilayah.
	req, _ := http.NewRequest("POST", "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation", bytes.NewBuffer(jsonData))

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

	// Uraikan JSON dan cetak konten.
	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 tanggapan lengkap, hapus komentar baris berikut.
	// fmt.Printf("%s\n", bodyText)
}

Tanggapan

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. 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 bervariasi berdasarkan wilayah. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
        // Jika Anda belum mengatur variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: string? apiKey = "sk-xxx";
        string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
        // Atur URL permintaan dan konten.
        // URL berikut untuk wilayah Singapura. Ganti {WorkspaceId} dengan ID Ruang Kerja Anda. URL bervariasi berdasarkan wilayah.
        string url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
        // qwen3.7-max, qwen3.7-max-2026-05-20, dan qwen3.6-max-preview hanya mendukung API teks. qwen3.8-max dan qwen3.7-max-2026-06-08 mendukung API multimodal. Seri Qwen3.6 dan Qwen3.5 memerlukan API multimodal. Mengganti model secara langsung akan 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 dapatkan tanggapan.
        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 tanggapan lengkap, hapus komentar 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 tanggapan.
            HttpResponseMessage response = await httpClient.PostAsync(url, content);

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

Tanggapan

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": "I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. 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 berikut untuk wilayah Singapura. Ganti {WorkspaceId} dengan ID Ruang Kerja Anda. URL bervariasi berdasarkan wilayah.
$url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
$apiKey = getenv('DASHSCOPE_API_KEY');

$data = [
    // qwen3.7-max, qwen3.7-max-2026-05-20, dan qwen3.6-max-preview hanya mendukung API teks. qwen3.8-max dan qwen3.7-max-2026-06-08 mendukung API multimodal. Seri Qwen3.6 dan Qwen3.5 memerlukan API multimodal. Mengganti model secara langsung akan 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 tanggapan lengkap, hapus komentar baris berikut.
    // echo "Model response: " . $response;
} else {
    echo "Request failed: " . $httpCode . " - " . $response;
}

curl_close($ch);
?>

Tanggapan

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!

curl

URL dasar dan kunci API bervariasi berdasarkan wilayah. Untuk detailnya, lihat DashScope dan Dapatkan kunci API.

# URL berikut untuk wilayah Singapura. Ganti {WorkspaceId} dengan ID Ruang Kerja Anda. URL bervariasi berdasarkan wilayah.
curl --location "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
    "model": "qwen-plus",
    "input":{
        "messages":[
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "user",
                "content": "Who are you?"
            }
        ]
    },
    "parameters": {
        "result_format": "message"
    }
}'

Tanggapan

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": "I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. 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"
}

Pemrosesan data gambar dan video

Model multimodal memproses data non-teks (gambar, video) untuk tugas seperti menjawab pertanyaan visual dan deteksi peristiwa. Model ini berbeda dari model teks saja dalam dua hal:

  • Pembuatan pesan pengguna: Pesan pengguna multimodal mencakup teks dan data non-teks seperti gambar dan audio.
  • Antarmuka SDK DashScope: Gunakan antarmuka MultiModalConversation untuk SDK Python DashScope, dan kelas MultiModalConversation untuk SDK Java DashScope.

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

Chat completions kompatibel OpenAI

Python

from openai import OpenAI
import os

client = OpenAI(
    # Kunci API bervariasi menurut wilayah. Untuk mendapatkan kunci API: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    # Jika variabel lingkungan tidak diatur, berikan kunci API Model Studio Anda secara langsung, misalnya: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Ini adalah titik akhir untuk wilayah Singapura. Ganti {WorkspaceId} dengan WorkspaceId Anda. Titik akhir bervariasi menurut wilayah.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.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.6-plus",
    messages=messages,
)
print(completion.choices[0].message.content)

Node.js

import OpenAI from "openai";

const openai = new OpenAI(
    {
        // Kunci API bervariasi berdasarkan wilayah. Untuk mendapatkan kunci API: https://www.alibabacloud.com/help/en/model-studio/get-api-key
        // Jika variabel lingkungan tidak diatur, berikan Kunci API Model Studio Anda secara langsung, misalnya: apiKey: "sk-xxx",
        apiKey: process.env.DASHSCOPE_API_KEY,
        // Ini adalah titik akhir untuk wilayah Singapura. Ganti {WorkspaceId} dengan WorkspaceId Anda. Titik akhir bervariasi berdasarkan wilayah.
        baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.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.6-plus",
        messages: messages
    });
    console.log(response.choices[0].message.content);
}

main()

curl

'base_url' dan kunci API bersifat spesifik wilayah. Lihat Kompatibel OpenAI - Chat untuk URL titik akhir dan Dapatkan kunci API untuk mendapatkan kunci Anda.

# Ini adalah titik akhir untuk wilayah Singapura. Ganti {WorkspaceId} dengan WorkspaceId Anda. Titik akhir bervariasi berdasarkan wilayah.
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
  "model": "qwen3.6-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
# Ini adalah titik akhir untuk wilayah Singapura. Ganti {WorkspaceId} dengan WorkspaceId Anda. Titik akhir bervariasi menurut wilayah.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.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 bervariasi menurut wilayah. Untuk mendapatkan kunci API: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    # Jika variabel lingkungan tidak diatur, berikan kunci API Model Studio Anda secara langsung, contohnya: api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model='qwen3.6-plus',  # Anda dapat mengganti ini dengan model multimodal lain dan mengubah pesan yang sesuai.
    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 {
        // Ini adalah titik akhir untuk wilayah Singapura. Ganti {WorkspaceId} dengan WorkspaceId Anda. Titik akhir bervariasi berdasarkan wilayah.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    private static final String modelName = "qwen3.6-plus";  // Anda dapat mengganti ini dengan model multimodal lain dan memodifikasi 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 bervariasi berdasarkan wilayah. Untuk mendapatkan kunci API: https://www.alibabacloud.com/help/en/model-studio/get-api-key
                // Jika variabel lingkungan tidak diatur, berikan Kunci API Model Studio Anda secara langsung, misalnya: .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 bervariasi berdasarkan wilayah. Untuk detailnya, lihat DashScope dan Dapatkan kunci API.

# Ini adalah titik akhir untuk wilayah Singapura. Ganti {WorkspaceId} dengan WorkspaceId Anda. Titik akhir bervariasi berdasarkan wilayah.
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
    "model": "qwen3.6-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?"}
                ]
            }
        ]
    }
}'

Panggilan asinkron

Panggilan asinkron meningkatkan throughput untuk beban kerja konkurensi tinggi.

API chat completions kompatibel OpenAI

import os
import asyncio
from openai import AsyncOpenAI
import platform

// Buat instance klien asinkron.
client = AsyncOpenAI(
    // Kunci API bervariasi berdasarkan wilayah. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/en/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"),
    // Ini adalah URL untuk wilayah Singapura. Ganti {WorkspaceId} dengan ID ruang kerja Anda.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.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, lihat https://www.alibabacloud.com/help/en/model-studio/getting-started/models
    )
    print(f"Model response: {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)

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 titik akhir kompatibel DashScope.
        OpenAIClientAsync client = OpenAIOkHttpClientAsync.builder()
                // Kunci API bervariasi berdasarkan wilayah. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/en/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"))
                // Ini adalah URL untuk wilayah Singapura. Ganti {WorkspaceId} dengan ID ruang kerja Anda.
                .baseUrl("https://{WorkspaceId}.ap-southeast-1.maas.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 tanggapan.
                    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("Error: " + e.getMessage());
                            System.out.println("Lihat dokumentasi: https://www.alibabacloud.com/help/en/model-studio/error-code");
                            return null;
                        });
                }).thenCompose(future -> future))
                .toArray(CompletableFuture[]::new);

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

DashScope

Generasi teks asinkron dengan SDK DashScope hanya didukung di Python.

// Ini memerlukan DashScope Python SDK v1.19.0 atau yang lebih baru.
import asyncio
import platform
from dashscope.aigc.generation import AioGeneration
import os
import dashscope
// Ini adalah URL untuk wilayah Singapura. Ganti {WorkspaceId} dengan ID ruang kerja Anda.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

// Definisikan tugas asinkron.
async def task(question):
    print(f"Sending question: {question}")
    response = await AioGeneration.call(
        // 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="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": question}],
        result_format="message",
    )
    print(f"Model response: {response.output.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)
Contoh tanggapan

Karena panggilan bersifat asinkron, urutan tanggapan mungkin berbeda dari contoh ini.

Sending question: Who are you?
Sending question: What can you do?
Sending question: What's the weather like?
Model response: Hello! I'm Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, programming, share opinions, play games, and more. If you have any questions or need help, feel free to ask!
Model response: Hello! I am currently unable to access real-time weather information. 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 app to check the real-time weather conditions.
Model response: I have many skills, for example:

1. Answering questions: Whether it's academic questions, general knowledge, or professional topics, I can try to help you find answers.
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. Expressing opinions: I can offer you some perspectives and suggestions to help you make decisions.
7. Playing games: We can play text-based games together, such as riddles or 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!

Penggunaan produksi

Membangun konteks berkualitas tinggi

Memberikan jumlah besar data mentah ke model meningkatkan biaya dan dapat menurunkan kinerja karena keterbatasan jendela konteks. Rekayasa konteks—memuat pengetahuan presisi secara dinamis—meningkatkan kualitas dan efisiensi generasi. Teknik utama meliputi:

  • rekayasa prompt: Rancang dan optimalkan prompt teks untuk mengarahkan model menuju output yang diinginkan. Untuk informasi lebih lanjut, lihat Panduan prompt untuk generasi teks.
  • Retrieval-Augmented Generation (RAG): Memungkinkan model menjawab pertanyaan dari basis pengetahuan eksternal seperti dokumentasi produk atau manual teknis.
  • pemanggilan alat: Mengambil informasi real-time (cuaca, trafik) atau melakukan aksi (panggilan API, mengirim email) atas nama model.
  • memori: Menyediakan memori jangka panjang dan jangka pendek sehingga model dapat mengingat konteks dalam percakapan multi-putaran.

Mengontrol keragaman tanggapan

Parameter temperature dan top_p mengontrol keragaman teks yang dihasilkan. Nilai yang lebih tinggi meningkatkan keragaman; nilai yang lebih rendah meningkatkan determinisme. Untuk mengisolasi efek setiap parameter, sesuaikan hanya satu sekaligus.

  • temperature: Rentang: [0, 2). Terutama menyesuaikan keacakan.
  • top_p: Rentang: [0, 1]. Menyaring tanggapan berdasarkan ambang batas probabilitas.

Contoh berikut menunjukkan bagaimana pengaturan parameter memengaruhi output. Prompt input: "Tulis cerita pendek tiga kalimat di mana karakter utamanya adalah kucing dan sinar matahari."

  • Keragaman tinggi (Contoh: temperature=0.9): Paling baik untuk penulisan kreatif, curah pendapat, atau salinan pemasaran.
Sunlight slanted across the windowsill, and the orange cat crept toward the bright patch as its fur turned the color of melted honey.
It reached out and tapped the light, then sank into it as if stepping into a warm pool, and the sunlight flowed up its back in a quiet tide.
The afternoon grew heavy—curled in drifting gold, the cat heard time melt softly inside its purr.
  • Determinisme tinggi (Contoh: temperature=0.1): Paling baik untuk menjawab pertanyaan berbasis fakta, pembuatan kode, atau teks hukum.
In the afternoon, an old cat curled on the windowsill and dozed while counting the spots of light.
Sunlight hopped across its mottled back, like turning the pages of an old photo album.
Dust rose and fell, as if time whispered: you were once young, and I was once fierce.

Cara kerjanya

temperature:

  • Suhu yang lebih tinggi meratakan distribusi probabilitas token, membuat token yang kurang mungkin menjadi lebih mungkin dan meningkatkan keacakan output.
  • Suhu yang lebih rendah mempertajam distribusi, membuat token berprobabilitas tinggi menjadi semakin mungkin dan mengurangi keacakan output.

top_p:

Pengambilan sampel top_p (nukleus) memilih dari himpunan token terkecil yang probabilitas kumulatifnya memenuhi atau melebihi ambang batas top_p. Token diurutkan berdasarkan probabilitas dan dikumpulkan hingga ambang batas tercapai, lalu token berikutnya dipilih secara acak dari himpunan yang telah direduksi ini.

  • top_p yang lebih tinggi memperluas kumpulan pemilihan token, menghasilkan teks yang lebih beragam.
  • top_p yang lebih rendah mempersempit kumpulan, menghasilkan teks yang lebih fokus dan deterministik.

Contoh pengaturan parameter untuk skenario umum

# Pengaturan parameter yang direkomendasikan untuk skenario umum
SCENARIO_CONFIGS = {
    # Penulisan kreatif
    "creative_writing": {
        "temperature": 0.9,
        "top_p": 0.95
    },
    # Pembuatan kode
    "code_generation": {
        "temperature": 0.2,
        "top_p": 0.8
    },
    # Tanya jawab faktual
    "factual_qa": {
        "temperature": 0.1,
        "top_p": 0.7
    },
    # Terjemahan
    "translation": {
        "temperature": 0.3,
        "top_p": 0.8
    }
}

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

Fitur lainnya

Untuk skenario yang lebih kompleks, fitur-fitur berikut tersedia:

  • percakapan multi-putaran: Untuk interaksi berkelanjutan seperti pertanyaan lanjutan atau pengumpulan informasi.
  • keluaran streaming: Mengembalikan token secara bertahap saat dihasilkan, mencegah timeout untuk chatbot dan pembuatan kode real-time.
  • pemikiran mendalam: Menghasilkan jawaban yang lebih berkualitas dan terstruktur untuk penalaran kompleks atau analisis strategis.
  • output terstruktur: Membatasi tanggapan ke format JSON konsisten untuk penggunaan pemrograman dan penguraian data.
  • penyelesaian awalan: Melanjutkan generasi dari teks yang sudah ada, berguna untuk penyelesaian kode atau penulisan bentuk panjang.

Referensi API

Untuk semua parameter, lihat referensi API kompatibel OpenAI dan referensi API DashScope.

FAQ

T: Mengapa jumlah token input lebih tinggi daripada jumlah token teks yang saya kirim?

J: Saat memproses percakapan, sistem menggunakan Templat Chat untuk membungkus teks input mentah, menambahkan penanda kontrol seperti pengenal peran dan batas pesan. Penanda yang dihasilkan sistem ini juga dihitung sebagai token.

Sebagai contoh, saat Anda mengirim pesan {"role": "user", "content": "Hi"} ke qwen3.8-max, teks "Hi" hanya sesuai dengan 1 token setelah tokenisasi. Namun, selama pemrosesan sistem, teks input lengkap yang sebenarnya diformat sebagai berikut: <|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n<think>. Setelah tokenisasi, teks lengkap ini meningkatkan jumlah total token input menjadi 11.

T: Mengapa API Qianwen tidak bisa menganalisis tautan halaman web?

J: API Qianwen tidak dapat mengakses konten halaman web secara langsung. Sebagai gantinya, gunakan pemanggilan fungsi, atau alat pengambilan web seperti Beautiful Soup Python untuk mengekstrak konten dan meneruskannya ke model.

T: Perbedaan tanggapan:Qianwen (Web)vs. API Qianwen

J: Qianwen (Web) menambahkan fitur di atas API Qianwen, termasuk penguraian halaman web, pencarian web, pembuatan gambar, dan pembuatan PPT. Fitur-fitur ini tidak termasuk dalam API dasar, tetapi Anda dapat membangun fungsionalitas serupa menggunakan , pemanggilan fungsi.

T: Menghasilkan file Word, Excel, PDF, atau PPT

J: Tidak. Model generasi teks hanya menghasilkan teks biasa. Konversi output ke format yang diinginkan menggunakan kode Anda sendiri atau pustaka pihak ketiga.