Model generasi teks menghasilkan teks yang jelas dan koheren berdasarkan prompt input.
Input untuk model generasi teks dapat berupa kata kunci sederhana, ringkasan satu kalimat, atau instruksi dan konteks yang lebih kompleks. Model ini mempelajari pola bahasa dengan menganalisis data dalam jumlah besar dan banyak digunakan untuk:
Pembuatan konten: Menghasilkan laporan berita, deskripsi produk, dan skrip video pendek.
Layanan pelanggan: Memberdayakan chatbot untuk menyediakan dukungan 24/7 dan menjawab pertanyaan umum.
Terjemahan teks: Mencapai konversi lintas bahasa yang cepat dan akurat.
Generasi ringkasan: Menyaring konten inti dari artikel panjang, laporan, dan email.
Penyusunan dokumen hukum: Menghasilkan kerangka dasar untuk templat kontrak dan opini hukum.
Rekomendasi pemilihan model
Wilayah layanan
Alibaba Cloud Model Studio menyediakan layanan model di wilayah Singapura, Virginia, dan Beijing. Setiap wilayah memiliki Kunci API yang berbeda, dan mengakses layanan dari wilayah terdekat dapat mengurangi latensi jaringan. Untuk informasi selengkapnya, lihat Pilih mode penyebaran.
Model tujuan umum
Qwen-Max, Qwen-Plus, dan Qwen-Flash semuanya telah ditingkatkan ke seri Qwen3 dan Kompatibel dengan OpenAI. Model-model ini cocok untuk berbagai skenario, seperti layanan pelanggan cerdas, pembuatan teks, penyempurnaan konten, dan ringkasan.
Qwen-Plus: Menyeimbangkan performa, kecepatan, dan biaya, sehingga menjadi pilihan yang direkomendasikan untuk sebagian besar skenario.
Qwen-Max: Model dengan performa terbaik dalam seri Qwen, cocok untuk menangani tugas kompleks multi-langkah. Model qwen3-max-2026-01-23 mendukung pemanggilan alat bawaan untuk mencapai akurasi lebih tinggi saat menyelesaikan masalah kompleks.
Qwen-Flash: Model tercepat dan paling hemat biaya dalam seri Qwen, cocok untuk menjalankan tugas sederhana.
Model spesifik skenario
Untuk kebutuhan bisnis tertentu, Alibaba Cloud Model Studio menyediakan berbagai model khusus dan teroptimalkan yang mencakup bidang seperti kemampuan kode, konteks panjang, terjemahan, penambangan data, pengenalan niat, asumsi peran, dan penelitian mendalam.
Model multimodal
Qwen-VL (Teks + Gambar -> Teks): Memiliki kemampuan pemahaman gambar dan mendukung tugas seperti pengenalan karakter optik (OCR), penalaran visual, dan pemahaman teks-gambar.
Qwen-Omni (Omni-modal -> Teks + Audio): Mendukung berbagai input data, termasuk video, audio, gambar, dan teks, serta menghasilkan output teks dan ucapan untuk menangani tugas lintas-modalitas kompleks.
Model pengenalan ucapan (Audio -> Teks): Mengenali dan mentranskripsikan ucapan dari audio. Model ini mendukung bahasa seperti Mandarin (termasuk berbagai dialek seperti Kanton), Inggris, Jepang, dan Korea.
Model pihak ketiga
Alibaba Cloud Model Studio menyediakan model bahasa besar pihak ketiga terkenal, termasuk DeepSeek dan Kimi. Untuk daftar lengkap model, lihat Generasi Teks - Model Pihak Ketiga.
Konsep inti
Input untuk model generasi teks adalah prompt, yang terdiri dari satu atau beberapa objek pesan. Setiap pesan memiliki peran dan konten:
Pesan Sistem: Menentukan peran model atau instruksi yang harus diikuti. Jika tidak ditentukan, nilai default-nya adalah "You are a helpful assistant."
Pesan Pengguna: Pertanyaan atau instruksi dari pengguna kepada model.
Pesan Asisten: Balasan dari model.
Saat memanggil model, buat array objek pesan tersebut dengan nama messages. Permintaan tipikal terdiri dari pesan system yang menentukan kode etik dan pesan user yang memberikan instruksi.
system bersifat opsional, tetapi disarankan untuk menyertakannya guna menetapkan peran dan kode etik model agar menghasilkan output yang lebih stabil dan konsisten.[
{"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?"}
]Objek respons output berisi balasan model sebagai pesan assistant.
{
"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 program. I can understand and generate multiple languages, and I support multi-turn conversations and complex task processing. If you need any help, just let me know!"
}Memulai
Prasyarat: Anda telah mendapatkan Kunci API dan mengonfigurasi Kunci API sebagai variabel lingkungan. Jika Anda memanggil model melalui kit pengembangan perangkat lunak (SDK), Anda harus menginstal SDK OpenAI atau DashScope.
Kompatibel dengan OpenAI - API Responses
API Responses merupakan evolusi dari API Chat Completions. Untuk petunjuk penggunaan, contoh kode, dan panduan migrasi, lihat Kompatibel dengan OpenAI - Responses.
Python
import os
from openai import OpenAI
try:
client = OpenAI(
# Setiap wilayah memiliki Kunci API yang berbeda. Untuk mendapatkan Kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan api_key="sk-xxx", menggunakan Kunci API Alibaba Cloud Model Studio Anda.
api_key=os.getenv("DASHSCOPE_API_KEY"),
# API Responses saat ini hanya mendukung wilayah Singapura.
base_url="https://dashscope-intl.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1",
)
response = client.responses.create(
# API Responses saat ini hanya mendukung model qwen3-max-2026-01-23.
model="qwen3-max-2026-01-23",
input="Hello, please introduce yourself in one sentence."
)
# Dapatkan respons model
print(response.output_text)
except Exception as e:
print(f"Error message: {e}")
print("For more information, see https://www.alibabacloud.com/help/en/model-studio/error-code")Respons
Hello! I'm Qwen, a large language model developed by Alibaba Cloud's Tongyi Lab, designed to assist with answering questions, creating content, coding, and more—always up-to-date as of January 27, 2026.Node.js
// Memerlukan Node.js v18+ dan harus dijalankan di lingkungan ES Module.
import OpenAI from "openai";
const openai = new OpenAI({
// Setiap wilayah memiliki Kunci API yang berbeda. Untuk mendapatkan Kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan apiKey: "sk-xxx", menggunakan Kunci API Alibaba Cloud Model Studio Anda.
apiKey: process.env.DASHSCOPE_API_KEY,
// API Responses saat ini hanya mendukung wilayah Singapura.
baseURL: "https://dashscope-intl.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1"
});
async function main() {
try {
const response = await openai.responses.create({
// API Responses saat ini hanya mendukung model qwen3-max-2026-01-23.
model: "qwen3-max-2026-01-23",
input: "Hello, please introduce yourself in one sentence."
});
// Dapatkan respons model
console.log(response.output_text);
} catch (error) {
console.error("Error:", error);
}
}
main();Respons
I am Qwen, a large-scale language model independently developed by the Tongyi Lab of Alibaba Group.curl
API Responses saat ini hanya mendukung wilayah Singapore dan model qwen3-max-2026-01-23.
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-max-2026-01-23",
"input": "Hello, please introduce yourself in one sentence."
}'Respons
{
"id": "351e34cc-5f75-483b-b948-35be954dbxxx",
"created_at": 1769408284,
"model": "qwen3-max-2026-01-23",
"object": "response",
"status": "completed",
"output": [
{
"type": "message",
"id": "msg_59a7339e-77d0-4451-8f51-75fb8dbefxxx",
"role": "assistant",
"status": "completed",
"content": [
{
"type": "output_text",
"text": "I am Qwen, a large-scale language model independently developed by the Tongyi Lab of Alibaba Group."
}
]
}
],
"usage": {
"input_tokens": 39,
"output_tokens": 46,
"total_tokens": 85
}
}Kompatibel dengan OpenAI - API Chat Completions
Python
import os
from openai import OpenAI
try:
client = OpenAI(
# Setiap wilayah memiliki Kunci API yang berbeda. Untuk mendapatkan Kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan api_key="sk-xxx", menggunakan Kunci API Alibaba Cloud Model Studio Anda.
api_key=os.getenv("DASHSCOPE_API_KEY"),
# Setiap wilayah memiliki base_url yang berbeda.
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
# Untuk daftar model, lihat https://www.alibabacloud.com/help/en/model-studio/models
model="qwen-plus",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Who are you?"},
],
)
print(completion.choices[0].message.content)
# Untuk melihat respons lengkap, hapus komentar pada baris berikut.
# print(completion.model_dump_json())
except Exception as e:
print(f"Error message: {e}")
print("For more information, see https://www.alibabacloud.com/help/en/model-studio/error-code")Respons
I am Qwen, a large-scale language model independently developed by the Tongyi Lab of Alibaba Group. I can help you answer questions and create text, such as writing stories, official documents, emails, and scripts, along with perform logical reasoning, programming, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask me at any time!Java
// Kami merekomendasikan menggunakan OpenAI Java SDK versi 3.5.0 atau lebih baru.
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
public class Main {
public static void main(String[] args) {
try {
OpenAIClient client = OpenAIOkHttpClient.builder()
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan .apiKey("sk-xxx"), menggunakan Kunci API Alibaba Cloud Model Studio Anda.
// Setiap wilayah memiliki Kunci API yang berbeda. Untuk mendapatkan Kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Setiap wilayah memiliki base_url yang berbeda.
.baseUrl("https://dashscope-intl.aliyuncs.com/compatible-mode/v1")
.build();
// Buat parameter ChatCompletion.
ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
.model("qwen-plus") // Tentukan model.
.addSystemMessage("You are a helpful assistant.")
.addUserMessage("Who are you?")
.build();
// Kirim permintaan dan dapatkan respons.
ChatCompletion chatCompletion = client.chat().completions().create(params);
String content = chatCompletion.choices().get(0).message().content().orElse("No valid content returned");
System.out.println(content);
} catch (Exception e) {
System.err.println("Error message: " + e.getMessage());
System.out.println("For more information, see https://www.alibabacloud.com/help/en/model-studio/error-code");
}
}
}Respons
I am Qwen, a large-scale language model independently developed by the Tongyi Lab of Alibaba Group. I can help you answer questions and create text, such as writing stories, official documents, emails, and scripts, along with perform logical reasoning, programming, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask me at any time!Node.js
// Memerlukan Node.js v18+ dan harus dijalankan di lingkungan ES Module.
import OpenAI from "openai";
const openai = new OpenAI(
{
// Setiap wilayah memiliki Kunci API yang berbeda. Untuk mendapatkan Kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan apiKey: "sk-xxx", menggunakan Kunci API Alibaba Cloud Model Studio Anda.
apiKey: process.env.DASHSCOPE_API_KEY,
// Setiap wilayah memiliki base_url yang berbeda.
baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
}
);
const completion = await openai.chat.completions.create({
model: "qwen-plus", // Untuk daftar model, lihat https://www.alibabacloud.com/help/en/model-studio/models
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Who are you?" }
],
});
console.log(completion.choices[0].message.content);
// Untuk melihat respons lengkap, hapus komentar pada baris berikut.
// console.log(JSON.stringify(completion, null, 4));Respons
I am Qwen, a large-scale language model independently developed by the Tongyi Lab of Alibaba Group. I can help you answer questions and create text, such as writing stories, official documents, emails, and scripts, along with perform logical reasoning, programming, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask me at any time!Go
// 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 di akhir kode.
// "encoding/json"
"fmt"
"os"
"github.com/openai/openai-go/v2"
"github.com/openai/openai-go/v2/option"
)
func main() {
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan: apiKey := "sk-xxx", menggunakan Kunci API Alibaba Cloud Model Studio Anda.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
client := openai.NewClient(
option.WithAPIKey(apiKey),
// Setiap wilayah memiliki Kunci API yang berbeda. Untuk mendapatkan Kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
// Setiap wilayah memiliki base_url yang berbeda.
option.WithBaseURL("https://dashscope-intl.aliyuncs.com/compatible-mode/v1"),
)
chatCompletion, err := client.Chat.Completions.New(
context.TODO(), openai.ChatCompletionNewParams{
Messages: []openai.ChatCompletionMessageParamUnion{
openai.SystemMessage("You are a helpful assistant."),
openai.UserMessage("Who are you?"),
},
Model: "qwen-plus",
},
)
if err != nil {
fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
// Untuk informasi error lebih lanjut, lihat https://www.alibabacloud.com/help/en/model-studio/error-code
os.Exit(1)
}
if len(chatCompletion.Choices) > 0 {
fmt.Println(chatCompletion.Choices[0].Message.Content)
}
// Untuk melihat respons lengkap, hapus komentar pada baris berikut.
// jsonData, _ := json.MarshalIndent(chatCompletion, "", " ")
// fmt.Println(string(jsonData))
}
Respons
I am Qwen, a large-scale language model independently developed by the Tongyi Lab of Alibaba Group. I can help you answer questions and create text, such as writing stories, official documents, emails, and scripts, along with perform logical reasoning, programming, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask me at any time!C# (HTTP)
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
class Program
{
private static readonly HttpClient httpClient = new HttpClient();
static async Task Main(string[] args)
{
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan: string? apiKey = "sk-xxx"; menggunakan Kunci API Alibaba Cloud Model Studio Anda.
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
// Setiap wilayah memiliki base_url yang berbeda.
string url = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions";
// Untuk daftar model, lihat https://www.alibabacloud.com/help/en/model-studio/getting-started/models
string jsonContent = @"{
""model"": ""qwen-plus"",
""messages"": [
{
""role"": ""system"",
""content"": ""You are a helpful assistant.""
},
{
""role"": ""user"",
""content"": ""Who are you?""
}
]
}";
// Kirim permintaan dan dapatkan respons.
string result = await SendPostRequestAsync(url, jsonContent, apiKey);
// Untuk melihat respons lengkap, hapus komentar pada baris berikut.
// Console.WriteLine(result);
// Uraikan JSON dan keluarkan hanya bagian kontennya.
using JsonDocument doc = JsonDocument.Parse(result);
JsonElement root = doc.RootElement;
if (root.TryGetProperty("choices", out JsonElement choices) &&
choices.GetArrayLength() > 0)
{
JsonElement firstChoice = choices[0];
if (firstChoice.TryGetProperty("message", out JsonElement message) &&
message.TryGetProperty("content", out JsonElement content))
{
Console.WriteLine(content.GetString());
}
}
}
private static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
{
using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await httpClient.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
// Untuk informasi error lebih lanjut, lihat https://www.alibabacloud.com/help/en/model-studio/error-code
return $"Request failed: {response.StatusCode}";
}
}
}
}Respons
I am Qwen, a large-scale language model independently developed by the Tongyi Lab of Alibaba Group. I can help you answer questions and create text, such as writing stories, official documents, emails, and scripts, along with perform logical reasoning, programming, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask me at any time!PHP (HTTP)
<?php
// Tetapkan URL permintaan.
// Setiap wilayah memiliki base_url yang berbeda.
$url = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
// Setiap wilayah memiliki Kunci API yang berbeda. Untuk mendapatkan Kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan: $apiKey = "sk-xxx"; menggunakan Kunci API Alibaba Cloud Model Studio Anda.
$apiKey = getenv('DASHSCOPE_API_KEY');
// Tetapkan header permintaan.
$headers = [
'Authorization: Bearer '.$apiKey,
'Content-Type: application/json'
];
// Tetapkan isi permintaan.
$data = [
"model" => "qwen-plus",
"messages" => [
[
"role" => "system",
"content" => "You are a helpful assistant."
],
[
"role" => "user",
"content" => "Who are you?"
]
]
];
// Inisialisasi sesi cURL.
$ch = curl_init();
// Tetapkan opsi cURL.
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Jalankan sesi cURL.
$response = curl_exec($ch);
// Periksa kesalahan.
// Untuk informasi error lebih lanjut, lihat https://www.alibabacloud.com/help/en/model-studio/error-code
if (curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
}
// Tutup resource cURL.
curl_close($ch);
// Keluarkan hasil 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-scale language model independently developed by the Tongyi Lab of Alibaba Group. I can help you answer questions and create text, such as writing stories, official documents, emails, and scripts, along with perform logical reasoning, programming, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask me at any time!curl
Setiap wilayah memiliki base_url dan Kunci API yang berbeda. Untuk informasi selengkapnya, lihat OpenAI Chat dan Dapatkan Kunci API.
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-plus",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Who are you?"
}
]
}'Respons
{
"choices": [
{
"message": {
"role": "assistant",
"content": "I am Qwen, a large-scale language model independently developed by the Tongyi Lab of Alibaba Group. I can help you answer questions and create text, such as writing stories, official documents, emails, and scripts, along with perform logical reasoning, programming, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask me at any time!"
},
"finish_reason": "stop",
"index": 0,
"logprobs": null
}
],
"object": "chat.completion",
"usage": {
"prompt_tokens": 26,
"completion_tokens": 66,
"total_tokens": 92
},
"created": 1726127645,
"system_fingerprint": null,
"model": "qwen-plus",
"id": "chatcmpl-81951b98-28b8-9659-ab07-xxxxxx"
}DashScope
Python
import json
import os
from dashscope import Generation
import dashscope
# Setiap wilayah memiliki base_url yang berbeda.
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(
# Setiap wilayah memiliki Kunci API yang berbeda. Untuk mendapatkan Kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan: api_key = "sk-xxx", menggunakan Kunci API Alibaba Cloud Model Studio Anda.
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen-plus",
messages=messages,
result_format="message",
)
if response.status_code == 200:
print(response.output.choices[0].message.content)
# Untuk melihat respons lengkap, hapus komentar pada baris berikut.
# print(json.dumps(response, default=lambda o: o.__dict__, indent=4))
else:
print(f"HTTP return code: {response.status_code}")
print(f"Error code: {response.code}")
print(f"Error message: {response.message}")
print("For more information, see https://www.alibabacloud.com/help/en/model-studio/error-code")Respons
I am Qwen, a large-scale language model independently developed by the Tongyi Lab of Alibaba Group. I can help you answer questions and create text, such as writing stories, official documents, emails, and scripts, along with perform logical reasoning, programming, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask me at any time!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 {
// Setiap wilayah memiliki base_url yang berbeda.
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()
// Setiap wilayah memiliki Kunci API yang berbeda. Untuk mendapatkan Kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan: .apiKey("sk-xxx"), menggunakan Kunci API Alibaba Cloud Model Studio Anda.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen-plus")
.messages(Arrays.asList(systemMsg, userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.build();
return gen.call(param);
}
public static void main(String[] args) {
try {
GenerationResult result = callWithMessage();
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
// Untuk melihat respons lengkap, hapus komentar pada baris berikut.
// System.out.println(JsonUtils.toJson(result));
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("Error message: "+e.getMessage());
System.out.println("For more information, see https://www.alibabacloud.com/help/en/model-studio/error-code");
}
}
}Respons
I am Qwen, a large-scale language model independently developed by the Tongyi Lab of Alibaba Group. I can help you answer questions and create text, such as writing stories, official documents, emails, and scripts, along with perform logical reasoning, programming, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask me at any time!Node.js (HTTP)
// Memerlukan Node.js v18+.
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan: const apiKey = "sk-xxx"; menggunakan Kunci API Alibaba Cloud Model Studio Anda.
const apiKey = process.env.DASHSCOPE_API_KEY;
const data = {
model: "qwen-plus",
input: {
messages: [
{
role: "system",
content: "You are a helpful assistant."
},
{
role: "user",
content: "Who are you?"
}
]
},
parameters: {
result_format: "message"
}
};
async function callApi() {
try {
// Setiap wilayah memiliki base_url yang berbeda.
const response = await fetch('https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
const result = await response.json();
console.log(result.output.choices[0].message.content);
// Untuk melihat respons lengkap, hapus komentar pada baris berikut.
// console.log(JSON.stringify(result));
} catch (error) {
// Untuk informasi error lebih lanjut, lihat https://www.alibabacloud.com/help/en/model-studio/error-code
console.error('Call failed:', error.message);
}
}
callApi();Respons
I am Qwen, a large-scale language model independently developed by the Tongyi Lab of Alibaba Group. I can help you answer questions and create text, such as writing stories, official documents, emails, and scripts, along with perform logical reasoning, programming, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask me at any time!Go (HTTP)
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
func main() {
requestBody := map[string]interface{}{
"model": "qwen-plus",
"input": map[string]interface{}{
"messages": []map[string]string{
{
"role": "system",
"content": "You are a helpful assistant.",
},
{
"role": "user",
"content": "Who are you?",
},
},
},
"parameters": map[string]string{
"result_format": "message",
},
}
// Serialisasi ke JSON.
jsonData, _ := json.Marshal(requestBody)
// Buat klien HTTP dan permintaan.
client := &http.Client{}
// Setiap wilayah memiliki base_url yang berbeda.
req, _ := http.NewRequest("POST", "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation", bytes.NewBuffer(jsonData))
// Tetapkan header permintaan.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Kirim permintaan.
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// Baca isi respons.
bodyText, _ := io.ReadAll(resp.Body)
// Uraikan JSON dan keluarkan kontennya.
var result map[string]interface{}
json.Unmarshal(bodyText, &result)
content := result["output"].(map[string]interface{})["choices"].([]interface{})[0].(map[string]interface{})["message"].(map[string]interface{})["content"].(string)
fmt.Println(content)
// Untuk melihat respons lengkap, hapus komentar pada baris berikut.
// fmt.Printf("%s\n", bodyText)
}
Respons
I am Qwen, a large-scale language model independently developed by the Tongyi Lab of Alibaba Group. I can help you answer questions and create text, such as writing stories, official documents, emails, and scripts, along with perform logical reasoning, programming, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask me at any time!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)
{
// Setiap wilayah memiliki Kunci API yang berbeda. Untuk mendapatkan Kunci API, lihat https://www.alibabacloud.com/help/en/model-studio/get-api-key
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan: string? apiKey = "sk-xxx"; menggunakan Kunci API Alibaba Cloud Model Studio Anda.
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
// Tetapkan URL dan konten permintaan.
// Setiap wilayah memiliki base_url yang berbeda.
string url = "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
string jsonContent = @"{
""model"": ""qwen-plus"",
""input"": {
""messages"": [
{
""role"": ""system"",
""content"": ""You are a helpful assistant.""
},
{
""role"": ""user"",
""content"": ""Who are you?""
}
]
},
""parameters"": {
""result_format"": ""message""
}
}";
// Kirim permintaan dan dapatkan respons.
string result = await SendPostRequestAsync(url, jsonContent, apiKey);
var jsonResult = System.Text.Json.JsonDocument.Parse(result);
var content = jsonResult.RootElement.GetProperty("output").GetProperty("choices")[0].GetProperty("message").GetProperty("content").GetString();
Console.WriteLine(content);
// Untuk melihat respons lengkap, hapus komentar pada baris berikut.
// Console.WriteLine(result);
}
private static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
{
using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
{
// Tetapkan header permintaan.
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Kirim permintaan dan dapatkan respons.
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// Tangani respons.
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return $"Request failed: {response.StatusCode}";
}
}
}
}Respons
{
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": "I am Qwen, a large-scale language model independently developed by the Tongyi Lab of Alibaba Group. I can help you answer questions and create text, such as writing stories, official documents, emails, and scripts, along with perform logical reasoning, programming, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask me at any time!"
}
}
]
},
"usage": {
"total_tokens": 92,
"output_tokens": 66,
"input_tokens": 26
},
"request_id": "09dceb20-ae2e-999b-85f9-xxxxxx"
}PHP (HTTP)
<?php
// Setiap wilayah memiliki base_url yang berbeda.
$url = "https://dashscope-intl.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 = [
"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-scale language model independently developed by the Tongyi Lab of Alibaba Group. I can help you answer questions and create text, such as writing stories, official documents, emails, and scripts, along with perform logical reasoning, programming, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask me at any time!curl
Setiap wilayah memiliki base_url dan Kunci API yang berbeda. Untuk informasi selengkapnya, lihat DashScope dan Dapatkan Kunci API.
curl --location "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "qwen-plus",
"input":{
"messages":[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Who are you?"
}
]
},
"parameters": {
"result_format": "message"
}
}'Respons
{
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": "I am Qwen, a large-scale language model independently developed by the Tongyi Lab of Alibaba Group. I can help you answer questions and create text, such as writing stories, official documents, emails, and scripts, along with perform logical reasoning, programming, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask me at any time!"
}
}
]
},
"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, seperti gambar dan video. Anda dapat menggunakan model ini untuk tugas-tugas seperti visual question answering dan deteksi event. Pemanggilan model multimodal berbeda dari pemanggilan model teks biasa dalam hal-hal berikut:
Konstruksi pesan pengguna: Pesan pengguna untuk model multimodal mencakup informasi multimodal, seperti gambar dan audio, selain teks.
Antarmuka SDK DashScope: Saat menggunakan DashScope Python SDK, panggil antarmuka
MultiModalConversation. Saat menggunakan DashScope Java SDK, panggil kelasMultiModalConversation.
Untuk informasi lebih lanjut mengenai batasan file gambar dan video, lihat Visual understanding.
OpenAI compatible-Chat Completions API
Python
from openai import OpenAI
import os
client = OpenAI(
# Kunci API bervariasi berdasarkan wilayah. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
# Base_url bervariasi berdasarkan wilayah.
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
)
messages = [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"
},
},
{"type": "text", "text": "What products are shown in the image?"},
],
}
]
completion = client.chat.completions.create(
model="qwen3-vl-plus", # Ganti ini dengan model multimodal lain dan sesuaikan messages sesuai kebutuhan.
messages=messages,
)
print(completion.choices[0].message.content)
Node.js
import OpenAI from "openai";
const openai = new OpenAI(
{
// Kunci API bervariasi berdasarkan wilayah. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
// Base_url bervariasi berdasarkan wilayah.
baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
}
);
let messages = [
{
role: "user",
content: [
{ type: "image_url", image_url: { "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png" } },
{ type: "text", text: "What products are shown in the image?" },
]
}]
async function main() {
let response = await openai.chat.completions.create({
model: "qwen3-vl-plus", // Ganti ini dengan model multimodal lain dan sesuaikan messages sesuai kebutuhan.
messages: messages
});
console.log(response.choices[0].message.content);
}
main()curl
Setiap wilayah memiliki base_url dan kunci API yang berbeda. Untuk informasi selengkapnya, lihat OpenAI Chat dan Get an API key.
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3-vl-plus",
"messages": [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"
}
},
{
"type": "text",
"text": "What products are shown in the image?"
}
]
}
]
}'DashScope
Python
import os
from dashscope import MultiModalConversation
import dashscope
# Base_url bervariasi berdasarkan wilayah.
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 bervariasi berdasarkan wilayah. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx",
api_key=os.getenv('DASHSCOPE_API_KEY'),
model='qwen3-vl-plus', # Ganti ini dengan model multimodal lain dan sesuaikan messages 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 {
// Base_url bervariasi berdasarkan wilayah.
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
}
private static final String modelName = "qwen3-vl-plus"; // Ganti ini dengan model multimodal lain dan sesuaikan messages 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, lihat https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model(modelName)
.messages(messages)
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text")); // tambahkan hasil ke percakapan
}
public static void main(String[] args) {
try {
MultiRoundConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}curl
Setiap wilayah memiliki base_url dan kunci API yang berbeda. Untuk informasi selengkapnya, lihat DashScope dan Get an API key.
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3-vl-plus",
"input":{
"messages":[
{
"role": "user",
"content": [
{"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"},
{"text": "What products are shown in the image?"}
]
}
]
}
}'Pemanggilan model secara asinkron
Pemanggilan API secara asinkron meningkatkan efisiensi pemrosesan untuk permintaan dengan tingkat konkurensi tinggi.
API Chat Completions yang kompatibel dengan OpenAI
Python
import os
import asyncio
from openai import AsyncOpenAI
import platform
# Buat instans klien asinkron.
client = AsyncOpenAI(
# Kunci API berbeda-beda tergantung wilayah. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# Jika variabel lingkungan tidak diatur, ganti baris berikut dengan kunci API Model Studio Anda: api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# base_url berbeda-beda tergantung wilayah.
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
)
# Definisikan daftar tugas asinkron.
async def task(question):
print(f"Mengirim pertanyaan: {question}")
response = await client.chat.completions.create(
messages=[
{"role": "user", "content": question}
],
model="qwen-plus", # Untuk daftar model, lihat https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
)
print(f"Tanggapan model: {response.choices[0].message.content}")
# Fungsi utama asinkron.
async def main():
questions = ["Who are you?", "What can you do?", "How is the weather?"]
tasks = [task(q) for q in questions]
await asyncio.gather(*tasks)
if __name__ == '__main__':
# Atur kebijakan loop peristiwa.
if platform.system() == 'Windows':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# Jalankan korutin utama.
asyncio.run(main(), debug=False)
Java
import com.openai.client.OpenAIClientAsync;
import com.openai.client.okhttp.OpenAIOkHttpClientAsync;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
// Buat klien OpenAI dan hubungkan ke titik akhir kompatibel DashScope.
OpenAIClientAsync client = OpenAIOkHttpClientAsync.builder()
// Kunci API berbeda-beda tergantung wilayah. Untuk mendapatkan kunci API, lihat https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// Jika variabel lingkungan tidak diatur, ganti baris berikut dengan kunci API Model Studio Anda: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// base_url 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?", "How is the weather?");
// Buat daftar tugas asinkron.
CompletableFuture<?>[] futures = questions.stream()
.map(question -> CompletableFuture.supplyAsync(() -> {
System.out.println("Mengirim pertanyaan: " + question);
// Buat parameter ChatCompletion.
ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
.model("qwen-plus") // Tentukan model.
.addSystemMessage("You are a helpful assistant.")
.addUserMessage(question)
.build();
// Kirim permintaan asinkron dan proses respons.
return client.chat().completions().create(params)
.thenAccept(chatCompletion -> {
String content = chatCompletion.choices().get(0).message().content().orElse("No response content");
System.out.println("Tanggapan model: " + content);
})
.exceptionally(e -> {
System.err.println("Pesan error: " + e.getMessage());
System.out.println("Untuk informasi lebih lanjut, lihat https://www.alibabacloud.com/help/zh/model-studio/error-code");
return null;
});
}).thenCompose(future -> future))
.toArray(CompletableFuture[]::new);
// Tunggu hingga semua operasi asinkron selesai.
CompletableFuture.allOf(futures).join();
}
}DashScope
Saat ini, SDK DashScope hanya mendukung pemanggilan asinkron untuk generasi teks dalam Python.
# Diperlukan SDK Python DashScope versi 1.19.0 atau yang lebih baru.
import asyncio
import platform
from dashscope.aigc.generation import AioGeneration
import os
import dashscope
# base_url berbeda-beda tergantung wilayah.
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# Definisikan daftar tugas asinkron.
async def task(question):
print(f"Mengirim pertanyaan: {question}")
response = await AioGeneration.call(
# Jika variabel lingkungan tidak 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, lihat https://www.alibabacloud.com/help/zh/model-studio/models
messages=[{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": question}],
result_format="message",
)
print(f"Tanggapan model: {response.output.choices[0].message.content}")
# Fungsi utama asinkron.
async def main():
questions = ["Who are you?", "What can you do?", "How is the weather?"]
tasks = [task(q) for q in questions]
await asyncio.gather(*tasks)
if __name__ == '__main__':
# Atur kebijakan loop peristiwa.
if platform.system() == 'Windows':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# Jalankan korutin utama.
asyncio.run(main(), debug=False)
Respons
Karena pemanggilannya bersifat asinkron, urutan respons mungkin berbeda dari contoh.
Mengirim pertanyaan: Siapa Anda?
Mengirim pertanyaan: Apa yang bisa Anda lakukan?
Mengirim pertanyaan: Bagaimana cuacanya?
Tanggapan model: Halo! Saya Qwen, model bahasa tingkat tinggi yang dikembangkan oleh Tongyi Lab di bawah Alibaba Group. Saya dapat membantu Anda menjawab pertanyaan dan membuat teks, seperti cerita, dokumen resmi, email, dan playbook. Saya juga dapat melakukan penalaran logis, menulis kode, menyatakan pendapat, dan bermain game. Jika Anda memiliki pertanyaan atau butuh bantuan, jangan ragu untuk bertanya kepada saya kapan saja!
Tanggapan model: Halo! Saat ini saya tidak bisa mendapatkan informasi cuaca real-time. Anda dapat memberi tahu saya kota atau Wilayah Anda, dan saya akan berusaha sebaik mungkin untuk memberi Anda saran atau informasi cuaca umum. Atau, Anda dapat menggunakan aplikasi cuaca untuk memeriksa cuaca real-time.
Tanggapan model: Saya memiliki banyak keterampilan, seperti:
1. **Menjawab pertanyaan**: Saya dapat mencoba menjawab pertanyaan Anda, baik tentang topik akademik, pengetahuan umum, maupun subjek profesional.
2. **Membuat teks**: Saya dapat menulis berbagai jenis teks, seperti cerita, dokumen resmi, email, dan playbook.
3. **Penalaran logis**: Saya dapat membantu Anda menyelesaikan soal penalaran logis, seperti soal matematika dan teka-teki.
4. **Pemrograman**: Saya dapat memberikan bantuan pemrograman, termasuk menulis, melakukan debugging, dan mengoptimalkan kode.
5. **Dukungan multibahasa**: Saya mendukung beberapa bahasa, termasuk tetapi tidak terbatas pada bahasa Mandarin, Inggris, Prancis, dan Spanyol.
6. **Menyatakan pendapat**: Saya dapat memberi Anda pendapat dan saran untuk membantu Anda membuat keputusan.
7. **Bermain game**: Kita bisa bermain game berbasis teks bersama, seperti teka-teki dan game sambung kata.
Jika Anda memiliki kebutuhan atau pertanyaan spesifik, jangan ragu untuk memberi tahu saya, dan saya akan berusaha sebaik mungkin untuk membantu Anda!Going live
Build high-quality context
Memberikan sejumlah besar data mentah langsung ke Large Language Model (LLM) meningkatkan biaya dan menurunkan performa karena keterbatasan ukuran konteks. Context Engineering meningkatkan kualitas dan efisiensi generasi dengan memuat pengetahuan yang relevan secara dinamis. Teknik utamanya meliputi hal-hal berikut:
Prompt engineering: Rancang dan optimalkan instruksi teks, yang disebut prompt, untuk memandu model secara lebih tepat, sehingga outputnya lebih selaras dengan hasil yang diharapkan. Untuk informasi lebih lanjut, lihat Text Generation Prompt Guide .
Retrieval-augmented generation (RAG): Berguna ketika model perlu menjawab pertanyaan berdasarkan basis pengetahuan eksternal, seperti dokumen produk atau manual teknis.
Tool calling: Memungkinkan model mengambil informasi real-time—misalnya, pembaruan cuaca—atau melakukan operasi tertentu, seperti memanggil API atau mengirim email.
Memory: Teknik ini membangun memori jangka pendek dan jangka panjang untuk model, sehingga memungkinkannya memahami riwayat percakapan yang berkelanjutan.
Control response diversity
Anda dapat menggunakan parameter temperature dan top_p untuk mengontrol keragaman teks yang dihasilkan. Nilai yang lebih tinggi menghasilkan konten yang lebih beragam, sedangkan nilai yang lebih rendah menghasilkan konten yang lebih deterministik. Untuk menilai efek suatu parameter secara akurat, ubah hanya satu parameter dalam satu waktu.
temperature: Rentang nilainya adalah [0, 2). Parameter ini terutama mengatur tingkat keacakan.top_p: Rentang nilainya adalah [0, 1]. Parameter ini menyaring respons berdasarkan ambang batas probabilitas kumulatif.
Contoh berikut menunjukkan bagaimana pengaturan parameter yang berbeda memengaruhi konten yang dihasilkan. Prompt inputnya adalah: "Tulis cerita pendek tiga kalimat di mana tokoh utamanya adalah seekor kucing dan seberkas sinar matahari."
Keragaman tinggi (
temperature= 0.9): Cocok untuk skenario yang membutuhkan kreativitas, imajinasi, dan ekspresi baru, seperti penulisan kreatif, brainstorming, atau copywriting pemasaran.Sunlight slanted onto the windowsill. A ginger cat tiptoed to the glowing patch of light, its fur instantly turning the color of melted honey. It reached out a paw to tap the sunbeam and sank in as if stepping into warm water, the light flowing up its back from its paw pads. The afternoon grew heavy. The cat, curled in the flowing gold, heard time melt away with its purrs.Determinisme tinggi (
temperature= 0.1): Cocok untuk skenario yang membutuhkan konten yang akurat, ketat, dan dapat diprediksi, seperti tanya jawab faktual, generasi kode, atau teks hukum.An old cat dozed on the windowsill in the afternoon sun. The light danced on its mottled back like someone flipping through an old photo album. Dust motes floated in the air. It was as if time whispered, "You were young once, and I was bright."
More features
Bagian sebelumnya menjelaskan metode interaksi dasar. Untuk skenario yang lebih kompleks, lihat fitur-fitur berikut:
Multi-turn conversation: Berguna untuk skenario yang memerlukan komunikasi berkelanjutan, seperti mengajukan pertanyaan lanjutan atau mengumpulkan informasi.
Streaming output: Berguna untuk skenario yang memerlukan respons segera, seperti chatbot dan penyelesaian kode real-time. Fitur ini meningkatkan pengalaman pengguna dan membantu mencegah timeout akibat waktu respons yang lama.
Deep thinking: Berguna untuk skenario yang memerlukan jawaban berkualitas tinggi, terstruktur dengan baik, dan mendalam, seperti penalaran kompleks dan analisis kebijakan.
Structured output: Berguna ketika Anda memerlukan model memberikan respons dalam format JSON yang stabil agar mudah diurai oleh program atau untuk pemrosesan data.
Partial mode: Berguna untuk skenario di mana model perlu melanjutkan dari teks yang sudah ada, seperti penyelesaian kode atau penulisan bentuk panjang.
Referensi API
Untuk daftar lengkap parameter pemanggilan model, lihat referensi API yang kompatibel dengan OpenAI dan referensi API DashScope.
FAQ
T: Mengapa API Qwen tidak dapat mengurai tautan web?
J: API Qwen tidak dapat langsung mengakses dan mengurai tautan web. Anda dapat menggunakan fitur seperti Function Calling, atau menggunakan alat web scraping seperti Beautiful Soup dari Python untuk membaca konten halaman web.
T: Mengapa respons dari antarmuka web Qwen dan API Qwen berbeda?
J: Antarmuka web Qwen dan API Qwen memberikan respons yang berbeda karena antarmuka web mencakup optimisasi teknis tambahan. Optimisasi tersebut memungkinkan fitur seperti penguraian halaman web, pencarian web, pembuatan gambar, dan pembuatan PPT, yang tidak didukung secara native oleh API Large Language Model (LLM). Anda dapat meningkatkan output model menggunakan fitur seperti Function Calling.
T: Apakah model dapat langsung menghasilkan file dalam format Word, Excel, PDF, atau PPT?
J: Tidak. Model generasi teks di Alibaba Cloud Model Studio hanya menghasilkan teks biasa. Untuk membuat file dalam format tersebut, Anda dapat mengonversi output teks biasa tersebut secara terprogram atau menggunakan pustaka pihak ketiga.