Alibaba Cloud Model Studio menyediakan OpenAI-compatible Batch File API yang memungkinkan pengiriman permintaan secara massal melalui file. Sistem memproses permintaan tersebut secara asinkron dan mengembalikan hasil ketika semua permintaan selesai atau waktu tunggu maksimum tercapai. Biayanya hanya 50% dari panggilan real-time, sehingga ideal untuk analitik data, evaluasi model, dan beban kerja skala besar lainnya di mana latensi tidak kritis.
Untuk menggunakan konsol, lihat panduan konsol.
Alur kerja
Prasyarat
Anda dapat memanggil Batch File API melalui OpenAI SDK (Python, Node.js) atau HTTP API.
-
Dapatkan Kunci API: Dapatkan dan konfigurasikan Kunci API Model Studio Anda sebagai variabel lingkungan
-
Instal SDK (opsional): Instal OpenAI SDK jika Anda berencana menggunakannya.
-
Titik akhir layanan
- North China 2 (Beijing):
https://dashscope.aliyuncs.com/compatible-mode/v1 - Singapura:
https://dashscope-intl.aliyuncs.com/compatible-mode/v1
- North China 2 (Beijing):
Cakupan
Singapura
Model yang didukung: qwen-max, qwen-plus, qwen-flash, qwen-turbo.
Tiongkok (Beijing)
Model yang didukung:
-
Model generasi teks
- Qwen-Max: qwen3.8-max, qwen3.7-max, qwen3-max, qwen-max, qwen-max-latest
- Qwen-Plus: qwen3.7-plus, qwen3.6-plus, qwen3.5-plus, qwen-plus, qwen-plus-latest
- Qwen-Flash: qwen3.8-flash, qwen3.7-flash, qwen3.6-flash, qwen3.5-flash, qwen-flash
- Model yang direkomendasikan: qwen-long-latest
- Model yang direkomendasikan: qwq-plus
- Model pihak ketiga: deepseek-r1, deepseek-v3.2, deepseek-v3
-
Model multimodal
- Pemahaman gambar dan video: qwen3.8-max, qwen3.8-flash, qwen3.7-plus, qwen3.6-plus, qwen3.7-flash, qwen3.6-flash, qwen3.5-plus, qwen3.5-flash, qwen3-vl-plus, qwen3-vl-flash, qwen-vl-max, qwen-vl-max-latest, qwen-vl-plus, qwen-vl-plus-latest
- Ekstraksi teks: qwen-vl-ocr
- Omni-modal: qwen3.5-omni-plus
-
Model text embedding: text-embedding-v4
Penting
- Dalam skenario pemrosesan batch, jumlah maksimum token konteks per permintaan adalah 256 K untuk
qwen3.8-max,qwen3.8-flash,qwen3.7-max,qwen3.7-plus,qwen3.6-plus,qwen3.7-flash,qwen3.6-flash,qwen3.5-plus,qwen3.5-flash, danqwen3.5-omni-plus.qwen3.5-omni-plustidak mendukung output suara. - Beberapa model mendukung mode thinking. Mengaktifkan mode ini menghasilkan
tokenthinking dan meningkatkan biaya. - Model seri
qwen3.8,qwen3.7,qwen3.6, danqwen3.5memiliki mode thinking yang diaktifkan secara default. Jika Anda menggunakan model hybrid thinking, Anda harus secara eksplisit mengatur parameterenable_thinking. Atur parameter ini ketrueuntuk mengaktifkan mode ataufalseuntuk menonaktifkannya. - Dalam badan permintaan JSONL,
enable_thinkingadalah parameter tingkat atas daribodydan harus ditempatkan pada level yang sama denganmodel. Jangan letakkan di dalamextra_body.
Mulai
Sebelum memproses tugas formal, uji dengan batch-test-model. Model uji ini melewati inferensi dan mengembalikan respons sukses tetap, sehingga Anda dapat memverifikasi rantai panggilan API dan format data Anda.
Catatan
Batasan batch-test-model:- File uji Anda harus memenuhi Persyaratan file input. Ukuran maksimum: 1 MB. Jumlah baris maksimum: 100.
- Batas konkurensi: Maksimal 2 tugas paralel.
- Biaya: Model uji tidak dikenakan biaya inferensi model.
Langkah 1: Siapkan file input
Siapkan file bernama test_model.jsonl dengan konten berikut:
{"custom_id":"1","method":"POST","url":"/v1/chat/ds-test","body":{"model":"batch-test-model","messages":[{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":"Hello! How can I help you?"}]}}
{"custom_id":"2","method":"POST","url":"/v1/chat/ds-test","body":{"model":"batch-test-model","messages":[{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":"What is 2+2?"}]}}
Model multimodal (misalnya, qwen-vl-plus) mendukung URL file dan input berkode Base64:
{"custom_id":"image-url","method":"POST","url":"/v1/chat/completions","body":{"model":"qwen-vl-plus","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"}},{"type":"text","text":"Describe this image."}]}]}}
{"custom_id":"image-base64","method":"POST","url":"/v1/chat/completions","body":{"model":"qwen-vl-plus","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEA8ADwAAD..."}},{"type":"text","text":"Describe this image."}]}]}}
Langkah 2: Jalankan kode
Pilih potongan kode sesuai bahasa pemrograman Anda. Simpan di direktori yang sama dengan file input Anda dan jalankan. Kode ini menangani seluruh alur kerja: unggah, buat tugas, periksa status, dan unduh hasil.
Untuk menyesuaikan jalur file atau parameter lainnya, modifikasi kode sesuai kebutuhan.
CatatanGunakan kembali ID file yang ada: ID yang dikembalikan setelah mengunggah file (misalnya, file-batch-xxx) dapat digunakan kembali. Jika konten input tetap sama, lewati pengunggahan ulang dan langsung buat tugas dengan ID yang ada:
batch = client.batches.create(
input_file_id="file-batch-xxx", # Gunakan kembali ID file yang ada, tidak perlu mengunggah ulang
endpoint="/v1/chat/completions",
completion_window="24h"
)
Anda dapat mengambil ID file historis melalui API client.files.list(purpose="batch") untuk menanyakan ID file Batch yang telah diunggah.
Kode contoh
import os
from pathlib import Path
from openai import OpenAI
import time
# Inisialisasi klien
client = OpenAI(
# Jika tidak ada variabel lingkungan yang diatur, ganti baris di bawah dengan api_key="sk-xxx". Namun jangan hard-code di produksi untuk mengurangi risiko kebocoran.
# Kunci API berbeda antara wilayah Singapura dan Beijing.
api_key=os.getenv("DASHSCOPE_API_KEY"),
# base_url wilayah Singapura. Untuk Beijing, gunakan: https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1" # base_url untuk layanan Model Studio
)
def upload_file(file_path):
print(f"Mengunggah file JSONL yang berisi informasi permintaan...")
file_object = client.files.create(file=Path(file_path), purpose="batch")
print(f"File berhasil diunggah. ID File: {file_object.id}\n")
return file_object.id
def create_batch_job(input_file_id):
print(f"Membuat tugas batch berdasarkan ID file...")
# Catatan: Nilai parameter endpoint di sini harus sesuai dengan field url dalam file input.
# Untuk model uji (batch-test-model), gunakan /v1/chat/ds-test.
# Untuk model text embedding, gunakan /v1/embeddings.
# Untuk model lainnya, gunakan /v1/chat/completions.
batch = client.batches.create(input_file_id=input_file_id, endpoint="/v1/chat/ds-test", completion_window="24h")
print(f"Tugas batch dibuat. ID Tugas Batch: {batch.id}\n")
return batch.id
def check_job_status(batch_id):
print(f"Memeriksa status tugas batch...")
batch = client.batches.retrieve(batch_id=batch_id)
print(f"Status tugas batch: {batch.status}\n")
return batch.status
def get_output_id(batch_id):
print(f"Mendapatkan ID file output untuk permintaan yang berhasil dalam tugas batch...")
batch = client.batches.retrieve(batch_id=batch_id)
print(f"ID file output: {batch.output_file_id}\n")
return batch.output_file_id
def get_error_id(batch_id):
print(f"Mendapatkan ID file output untuk permintaan yang gagal dalam tugas batch...")
batch = client.batches.retrieve(batch_id=batch_id)
print(f"ID file error: {batch.error_file_id}\n")
return batch.error_file_id
def download_results(output_file_id, output_file_path):
print(f"Mencetak dan mengunduh hasil permintaan yang berhasil dari tugas batch...")
content = client.files.content(output_file_id)
# Cetak sebagian konten untuk pengujian
print(f"Mencetak 1.000 karakter pertama dari hasil permintaan yang berhasil: {content.text[:1000]}...\n")
# Simpan file hasil secara lokal
content.write_to_file(output_file_path)
print(f"Hasil output lengkap telah disimpan ke file output lokal result.jsonl\n")
def download_errors(error_file_id, error_file_path):
print(f"Mencetak dan mengunduh informasi kegagalan untuk permintaan dari tugas batch...")
content = client.files.content(error_file_id)
# Cetak sebagian konten untuk pengujian
print(f"Mencetak 1.000 karakter pertama dari informasi kegagalan permintaan: {content.text[:1000]}...\n")
# Simpan file informasi error secara lokal
content.write_to_file(error_file_path)
print(f"Informasi kegagalan permintaan lengkap telah disimpan ke file error lokal error.jsonl\n")
def main():
# Jalur file
input_file_path = "test_model.jsonl" # Anda dapat menggantinya dengan jalur file input Anda
output_file_path = "result.jsonl" # Anda dapat menggantinya dengan jalur file output Anda
error_file_path = "error.jsonl" # Anda dapat menggantinya dengan jalur file error Anda
try:
# Langkah 1: Unggah file JSONL yang berisi informasi permintaan untuk mendapatkan ID file input
input_file_id = upload_file(input_file_path)
# Langkah 2: Buat tugas batch berdasarkan ID file input
batch_id = create_batch_job(input_file_id)
# Langkah 3: Periksa status tugas batch hingga selesai
status = ""
while status not in ["completed", "failed", "expired", "cancelled"]:
status = check_job_status(batch_id)
print(f"Menunggu tugas selesai...")
time.sleep(10) # Tunggu 10 detik lalu tanyakan status lagi
# Jika tugas gagal, cetak pesan error dan keluar
if status == "failed":
batch = client.batches.retrieve(batch_id)
print(f"Tugas batch gagal. Pesan error: {batch.errors}\n")
print(f"Untuk informasi lebih lanjut, lihat Kode error: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code
return
# Langkah 4: Unduh hasil: Jika ID file output tidak kosong, cetak 1.000 karakter pertama dari hasil permintaan yang berhasil dan unduh hasil lengkap ke file output lokal.
# Jika ID file error tidak kosong, cetak 1.000 karakter pertama dari informasi kegagalan permintaan dan unduh informasi lengkap ke file error lokal.
output_file_id = get_output_id(batch_id)
if output_file_id:
download_results(output_file_id, output_file_path)
error_file_id = get_error_id(batch_id)
if error_file_id:
download_errors(error_file_id, error_file_path)
print(f"Untuk informasi lebih lanjut, lihat Kode error: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code
except Exception as e:
print(f"Terjadi kesalahan: {e}")
print(f"Untuk informasi lebih lanjut, lihat Kode error: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code
if __name__ == "__main__":
main()
/**
* Uji API Batch Model Studio - Menggunakan OpenAI Node.js SDK
*
* Instal dependensi: npm install openai
* Jalankan: node test-nodejs.js
*/
const OpenAI = require('openai');
const fs = require('fs');
// Base URL untuk wilayah Singapura
const BASE_URL = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1';
// Untuk Beijing, gunakan: const BASE_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
const apiKey = process.env.DASHSCOPE_API_KEY;
if (!apiKey) {
console.error('Error: Harap atur variabel lingkungan DASHSCOPE_API_KEY');
process.exit(1);
}
// Inisialisasi klien
const client = new OpenAI({
apiKey: apiKey,
baseURL: BASE_URL
});
async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function main() {
try {
console.log('=== Mulai Uji API Batch ===\n');
// Langkah 1: Unggah file
console.log('Langkah 1: Mengunggah file JSONL yang berisi informasi permintaan...');
const fileStream = fs.createReadStream('test_model.jsonl');
const fileObject = await client.files.create({
file: fileStream,
purpose: 'batch'
});
const fileId = fileObject.id;
console.log(`✓ File berhasil diunggah, ID File: ${fileId}\n`);
// Langkah 2: Buat tugas batch
console.log('Langkah 2: Membuat tugas batch...');
const batch = await client.batches.create({
input_file_id: fileId,
endpoint: '/v1/chat/ds-test', // Gunakan /v1/chat/ds-test untuk model uji
completion_window: '24h'
});
const batchId = batch.id;
console.log(`✓ Tugas batch berhasil dibuat, ID Tugas: ${batchId}\n`);
// Langkah 3: Periksa status tugas
console.log('Langkah 3: Menunggu tugas selesai...');
let status = batch.status;
let pollCount = 0;
let latestBatch = batch;
while (!['completed', 'failed', 'expired', 'cancelled'].includes(status)) {
await sleep(10000); // Tunggu 10 detik
latestBatch = await client.batches.retrieve(batchId);
status = latestBatch.status;
pollCount++;
console.log(` [${pollCount}] Status tugas: ${status}`);
}
console.log(`\n✓ Tugas selesai, status akhir: ${status}\n`);
// Langkah 4: Proses hasil
if (status === 'completed') {
console.log('Langkah 4: Mengunduh file hasil...');
// Unduh hasil yang berhasil
const outputFileId = latestBatch.output_file_id;
if (outputFileId) {
console.log(` ID file output: ${outputFileId}`);
const content = await client.files.content(outputFileId);
const text = await content.text();
console.log('\n--- Hasil yang berhasil (500 karakter pertama) ---');
console.log(text.substring(0, Math.min(500, text.length)));
console.log('...\n');
}
// Unduh file error (jika ada)
const errorFileId = latestBatch.error_file_id;
if (errorFileId) {
console.log(` ID file error: ${errorFileId}`);
const errorContent = await client.files.content(errorFileId);
const errorText = await errorContent.text();
console.log('\n--- Informasi error ---');
console.log(errorText);
}
console.log('\n=== Uji selesai dengan sukses ===');
} else if (status === 'failed') {
console.error('\n✗ Tugas batch gagal');
if (latestBatch.errors) {
console.error('Pesan error:', latestBatch.errors);
}
console.error('\nLihat dokumentasi kode error: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code
} else {
console.log(`\nStatus tugas: ${status}`);
}
} catch (error) {
console.error('Terjadi kesalahan:', error.message);
console.error(error);
}
}
main();
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
/**
* Uji API Batch Model Studio - Menggunakan HTTP API
*
* Prasyarat:
* 1. Pastikan variabel lingkungan DASHSCOPE_API_KEY diatur
* 2. Siapkan file uji test_model.jsonl (di direktori root proyek)
*
* Konfigurasi wilayah:
* - Wilayah Beijing: https://dashscope.aliyuncs.com/compatible-mode/v1
* - Wilayah Singapura: https://dashscope-intl.aliyuncs.com/compatible-mode/v1
*/
public class BatchAPITest {
// Base URL untuk wilayah Singapura
private static final String BASE_URL = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1";
// Untuk Beijing, gunakan: private static final String BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1";
private static String API_KEY;
public static void main(String[] args) throws Exception {
// Dapatkan Kunci API dari variabel lingkungan
API_KEY = System.getenv("DASHSCOPE_API_KEY");
if (API_KEY == null || API_KEY.isEmpty()) {
System.err.println("Error: Harap atur variabel lingkungan DASHSCOPE_API_KEY");
System.exit(1);
}
System.out.println("=== Mulai Uji API Batch ===\n");
try {
// Langkah 1: Unggah file
System.out.println("Langkah 1: Mengunggah file JSONL yang berisi informasi permintaan...");
String fileId = uploadFile("test_model.jsonl");
System.out.println("✓ File berhasil diunggah, ID File: " + fileId + "\n");
// Langkah 2: Buat tugas batch
System.out.println("Langkah 2: Membuat tugas batch...");
String batchId = createBatch(fileId);
System.out.println("✓ Tugas batch berhasil dibuat, ID Tugas: " + batchId + "\n");
// Langkah 3: Periksa status tugas
System.out.println("Langkah 3: Menunggu tugas selesai...");
String status = "";
int pollCount = 0;
while (!isTerminalStatus(status)) {
Thread.sleep(10000); // Tunggu 10 detik
String batchInfo = getBatch(batchId);
status = parseStatus(batchInfo);
pollCount++;
System.out.println(" [" + pollCount + "] Status tugas: " + status);
// Langkah 4: Jika selesai, unduh hasil
if ("completed".equals(status)) {
System.out.println("\n✓ Tugas selesai!\n");
System.out.println("Langkah 4: Mengunduh file hasil...");
String outputFileId = parseOutputFileId(batchInfo);
if (outputFileId != null && !outputFileId.isEmpty()) {
System.out.println(" ID file output: " + outputFileId);
String content = getFileContent(outputFileId);
System.out.println("\n--- Hasil yang berhasil (500 karakter pertama) ---");
System.out.println(content.substring(0, Math.min(500, content.length())));
System.out.println("...\n");
}
String errorFileId = parseErrorFileId(batchInfo);
if (errorFileId != null && !errorFileId.isEmpty() && !"null".equals(errorFileId)) {
System.out.println(" ID file error: " + errorFileId);
String errorContent = getFileContent(errorFileId);
System.out.println("\n--- Informasi error ---");
System.out.println(errorContent);
}
System.out.println("\n=== Uji selesai dengan sukses ===");
break;
} else if ("failed".equals(status)) {
System.err.println("\n✗ Tugas batch gagal");
System.err.println("Info tugas: " + batchInfo);
System.err.println("\nLihat dokumentasi kode error: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code
break;
} else if ("expired".equals(status) || "cancelled".equals(status)) {
System.out.println("\nStatus tugas: " + status);
break;
}
}
} catch (Exception e) {
System.err.println("Terjadi kesalahan: " + e.getMessage());
e.printStackTrace();
}
}
/**
* Unggah file
*/
private static String uploadFile(String filePath) throws Exception {
String boundary = "----WebKitFormBoundary" + System.currentTimeMillis();
URL url = new URL(BASE_URL + "/files");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Bearer " + API_KEY);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {
// Tambahkan field purpose
out.writeBytes("--" + boundary + "\r\n");
out.writeBytes("Content-Disposition: form-data; name=\"purpose\"\r\n\r\n");
out.writeBytes("batch\r\n");
// Tambahkan file
out.writeBytes("--" + boundary + "\r\n");
out.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + filePath + "\"\r\n");
out.writeBytes("Content-Type: application/octet-stream\r\n\r\n");
byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));
out.write(fileBytes);
out.writeBytes("\r\n");
out.writeBytes("--" + boundary + "--\r\n");
}
String response = readResponse(conn);
return parseField(response, "\"id\":\\s*\"([^\"]+)\"");
}
/**
* Buat tugas batch
*/
private static String createBatch(String fileId) throws Exception {
String jsonBody = String.format(
"{\"input_file_id\":\"%s\",\"endpoint\":\"/v1/chat/ds-test\",\"completion_window\":\"24h\"}",
fileId
);
String response = sendRequest("POST", "/batches", jsonBody);
return parseField(response, "\"id\":\\s*\"([^\"]+)\"");
}
/**
* Dapatkan info tugas batch
*/
private static String getBatch(String batchId) throws Exception {
return sendRequest("GET", "/batches/" + batchId, null);
}
/**
* Dapatkan konten file
*/
private static String getFileContent(String fileId) throws Exception {
return sendRequest("GET", "/files/" + fileId + "/content", null);
}
/**
* Kirim permintaan HTTP
*/
private static String sendRequest(String method, String path, String jsonBody) throws Exception {
URL url = new URL(BASE_URL + path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setRequestProperty("Authorization", "Bearer " + API_KEY);
if (jsonBody != null) {
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
try (OutputStream os = conn.getOutputStream()) {
os.write(jsonBody.getBytes("UTF-8"));
}
}
return readResponse(conn);
}
/**
* Baca respons
*/
private static String readResponse(HttpURLConnection conn) throws Exception {
int responseCode = conn.getResponseCode();
InputStream is = (responseCode < 400) ? conn.getInputStream() : conn.getErrorStream();
try (Scanner scanner = new Scanner(is, "UTF-8").useDelimiter("\\A")) {
return scanner.hasNext() ? scanner.next() : "";
}
}
/**
* Parsing field JSON (implementasi sederhana)
*/
private static String parseField(String json, String regex) {
java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(regex);
java.util.regex.Matcher matcher = pattern.matcher(json);
return matcher.find() ? matcher.group(1) : null;
}
private static String parseStatus(String json) {
return parseField(json, "\"status\":\\s*\"([^\"]+)\"");
}
private static String parseOutputFileId(String json) {
return parseField(json, "\"output_file_id\":\\s*\"([^\"]+)\"");
}
private static String parseErrorFileId(String json) {
return parseField(json, "\"error_file_id\":\\s*\"([^\"]+)\"");
}
/**
* Periksa apakah status terminal
*/
private static boolean isTerminalStatus(String status) {
return "completed".equals(status)
|| "failed".equals(status)
|| "expired".equals(status)
|| "cancelled".equals(status);
}
}
#!/bin/bash
# Uji API Batch Model Studio - Menggunakan curl
#
# Prasyarat:
# 1. Pastikan variabel lingkungan DASHSCOPE_API_KEY diatur
# 2. Siapkan file uji test_model.jsonl (di direktori saat ini)
#
# Konfigurasi wilayah:
# - Wilayah Beijing: https://dashscope.aliyuncs.com/compatible-mode/v1
# - Wilayah Singapura: https://dashscope-intl.aliyuncs.com/compatible-mode/v1
API_KEY="${DASHSCOPE_API_KEY}"
BASE_URL="https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
# Untuk Beijing, gunakan: BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1"
# Periksa Kunci API
if [ -z "$API_KEY" ]; then
echo "Error: Harap atur variabel lingkungan DASHSCOPE_API_KEY"
exit 1
fi
echo "=== Mulai Uji API Batch ==="
echo ""
# Langkah 1: Unggah file
echo "Langkah 1: Mengunggah file JSONL yang berisi informasi permintaan..."
UPLOAD_RESPONSE=$(curl -s -X POST "${BASE_URL}/files" \
-H "Authorization: Bearer ${API_KEY}" \
-F 'file=@test_model.jsonl' \
-F 'purpose=batch')
FILE_ID=$(echo $UPLOAD_RESPONSE | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
echo "✓ File berhasil diunggah, ID File: ${FILE_ID}"
echo ""
# Langkah 2: Buat tugas batch
echo "Langkah 2: Membuat tugas batch..."
BATCH_RESPONSE=$(curl -s -X POST "${BASE_URL}/batches" \
-H "Authorization: Bearer ${API_KEY}" \
-H "Content-Type: application/json" \
-d "{\"input_file_id\":\"${FILE_ID}\",\"endpoint\":\"/v1/chat/ds-test\",\"completion_window\":\"24h\"}")
BATCH_ID=$(echo $BATCH_RESPONSE | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
echo "✓ Tugas batch berhasil dibuat, ID Tugas: ${BATCH_ID}"
echo ""
# Langkah 3: Periksa status tugas
echo "Langkah 3: Menunggu tugas selesai..."
STATUS=""
POLL_COUNT=0
while [[ "$STATUS" != "completed" && "$STATUS" != "failed" && "$STATUS" != "expired" && "$STATUS" != "cancelled" ]]; do
sleep 10
BATCH_INFO=$(curl -s -X GET "${BASE_URL}/batches/${BATCH_ID}" \
-H "Authorization: Bearer ${API_KEY}")
STATUS=$(echo $BATCH_INFO | grep -o '"status":"[^"]*"' | cut -d'"' -f4)
POLL_COUNT=$((POLL_COUNT + 1))
echo " [${POLL_COUNT}] Status tugas: ${STATUS}"
done
echo ""
echo "✓ Tugas selesai, status akhir: ${STATUS}"
echo ""
# Langkah 4: Unduh hasil
if [[ "$STATUS" == "completed" ]]; then
echo "Langkah 4: Mengunduh file hasil..."
OUTPUT_FILE_ID=$(echo $BATCH_INFO | grep -o '"output_file_id":"[^"]*"' | cut -d'"' -f4)
if [[ -n "$OUTPUT_FILE_ID" && "$OUTPUT_FILE_ID" != "null" ]]; then
echo " ID file output: ${OUTPUT_FILE_ID}"
RESULT_CONTENT=$(curl -s -X GET "${BASE_URL}/files/${OUTPUT_FILE_ID}/content" \
-H "Authorization: Bearer ${API_KEY}")
echo ""
echo "--- Hasil yang berhasil (500 karakter pertama) ---"
echo "${RESULT_CONTENT:0:500}"
echo "..."
echo ""
fi
ERROR_FILE_ID=$(echo $BATCH_INFO | grep -o '"error_file_id":"[^"]*"' | cut -d'"' -f4)
if [[ -n "$ERROR_FILE_ID" && "$ERROR_FILE_ID" != "null" ]]; then
echo " ID file error: ${ERROR_FILE_ID}"
ERROR_CONTENT=$(curl -s -X GET "${BASE_URL}/files/${ERROR_FILE_ID}/content" \
-H "Authorization: Bearer ${API_KEY}")
echo ""
echo "--- Informasi error ---"
echo "${ERROR_CONTENT}"
fi
echo ""
echo "=== Uji selesai dengan sukses ==="
elif [[ "$STATUS" == "failed" ]]; then
echo ""
echo "✗ Tugas batch gagal"
echo "Info tugas: ${BATCH_INFO}"
echo ""
echo "Lihat dokumentasi kode error: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code
else
echo ""
echo "Status tugas: ${STATUS}"
fi
Langkah 3: Verifikasi hasil uji
Setelah tugas berhasil, file hasil result.jsonl berisi respons tetap {"content":"This is a test result."}:
{"id":"a2b1ae25-21f4-4d9a-8634-99a29926486c","custom_id":"1","response":{"status_code":200,"request_id":"a2b1ae25-21f4-4d9a-8634-99a29926486c","body":{"created":1743562621,"usage":{"completion_tokens":6,"prompt_tokens":20,"total_tokens":26},"model":"batch-test-model","id":"chatcmpl-bca7295b-67c3-4b1f-8239-d78323bb669f","choices":[{"finish_reason":"stop","index":0,"message":{"content":"This is a test result."}}],"object":"chat.completion"}},"error":null}
{"id":"39b74f09-a902-434f-b9ea-2aaaeebc59e0","custom_id":"2","response":{"status_code":200,"request_id":"39b74f09-a902-434f-b9ea-2aaaeebc59e0","body":{"created":1743562621,"usage":{"completion_tokens":6,"prompt_tokens":20,"total_tokens":26},"model":"batch-test-model","id":"chatcmpl-1e32a8ba-2b69-4dc4-be42-e2897eac9e84","choices":[{"finish_reason":"stop","index":0,"message":{"content":"This is a test result."}}],"object":"chat.completion"}},"error":null}
Jalankan tugas formal
Persyaratan file input
- Format: JSONL berkode UTF-8 (satu objek JSON independen per baris).
- Batas ukuran: Maksimum 50.000 permintaan per file, maksimum 500 MB.
- Batas baris: Setiap objek JSON tidak boleh melebihi 6 MB dan harus sesuai dalam jendela konteks model.
- Konsistensi: Semua permintaan dalam file yang sama harus menggunakan model yang sama dan mode thinking yang sama (jika berlaku).
- Pengenal unik: Setiap permintaan harus menyertakan field custom_id unik dalam file tersebut. Field ini digunakan untuk mencocokkan permintaan dengan hasil.
Contoh konten file:
{"custom_id":"1","method":"POST","url":"/v1/chat/completions","body":{"model":"qwen-plus","messages":[{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":"Hello!"}]}}
{"custom_id":"2","method":"POST","url":"/v1/chat/completions","body":{"model":"qwen-plus","messages":[{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":"What is 2+2?"}]}}
Skenario 2: Pemahaman gambar dan video
Model multimodal (misalnya, qwen-vl-plus) mendukung URL file dan input berkode Base64.
{"custom_id":"image-url","method":"POST","url":"/v1/chat/completions","body":{"model":"qwen-vl-plus","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"}},{"type":"text","text":"Describe this image."}]}]}}
{"custom_id":"image-base64","method":"POST","url":"/v1/chat/completions","body":{"model":"qwen-vl-plus","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEA8ADwAAD..."}},{"type":"text","text":"Describe this image."}]}]}}
{"custom_id":"video-url","method":"POST","url":"/v1/chat/completions","body":{"model":"qwen-vl-plus","messages":[{"role":"user","content":[{"type":"video","video":"https://example.com/video.mp4"},{"type":"text","text":"Describe this video."}]}]}}
{"custom_id":"video-base64","method":"POST","url":"/v1/chat/completions","body":{"model":"qwen-vl-plus","messages":[{"role":"user","content":[{"type":"video","video":["data:image/jpeg;base64,{frame1}","data:image/jpeg;base64,{frame2}","data:image/jpeg;base64,{frame3}"]},{"type":"text","text":"Describe this video."}]}]}}
{"custom_id":"multi-image-url","method":"POST","url":"/v1/chat/completions","body":{"model":"qwen-vl-plus","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"https://example.com/image1.jpg"}},{"type":"image_url","image_url":{"url":"https://example.com/image2.jpg"}},{"type":"text","text":"Compare these two images."}]}]}}
{"custom_id":"multi-image-base64","method":"POST","url":"/v1/chat/completions","body":{"model":"qwen-vl-plus","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/jpeg;base64,{image1_base64}"}},{"type":"image_url","image_url":{"url":"data:image/jpeg;base64,{image2_base64}"}},{"type":"text","text":"Compare these two images."}]}]}}
String Base64 dalam contoh di atas dipotong. Hasilkan encoding lengkap menggunakan kode Python di bawah ini.
Kirim string berkode Base64 (menggunakan gambar sebagai contoh)
- Konversi file lokal ke encoding Base64:
# Fungsi encoding: Konversi file lokal ke string berkode Base64
import base64
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
# Ganti xxx/eagle.png dengan jalur absolut ke gambar lokal Anda
base64_image = encode_image("xxx/eagle.png")
-
Buat format Data URL:
data:[MIME_type];base64,{base64_image};- Ganti
MIME_typedengan jenis media aktual. Harus sesuai dengan nilaiMIME Type(misalnya,image/jpeg,image/png); base64_imageadalah string Base64 yang dihasilkan pada langkah sebelumnya.
- Ganti
CatatanUntuk detail lengkap (termasuk batas file, jenis MIME, dan metode encoding), lihat Kirim file lokal (encoding Base64 atau jalur file).
Gunakan alat ini untuk membuat file JSONL dengan cepat.
1. Modifikasi file input
-
Dalam file
test_model.jsonl, atur parametermodelke model target dan atur fieldurl:Jenis model
url
Model generasi teks/model multimodal
/v1/chat/completionsModel text embedding
/v1/embeddings -
Atau gunakan "Alat pembuatan batch JSONL" di atas untuk membuat file baru untuk tugas formal. Pastikan field
modeldanurlbenar.
2. Ubah kode Getting Started
- Ubah jalur file input ke nama file Anda.
- Atur parameter endpoint agar sesuai dengan field url dalam file input Anda.
3. Jalankan kode dan tunggu hasil
Ketika tugas selesai, hasil permintaan yang berhasil disimpan ke file result.jsonl lokal. Jika ada permintaan yang gagal, detail error disimpan ke file error.jsonl.
- Hasil yang berhasil (
output_file_id): Setiap baris sesuai dengan satu permintaan yang berhasil dan mencakupcustom_iddanresponse.
{"id":"3a5c39d5-3981-4e4c-97f2-e0e821893f03","custom_id":"req-001","response":{"status_code":200,"request_id":"3a5c39d5-3981-4e4c-97f2-e0e821893f03","body":{"created":1768306034,"usage":{"completion_tokens":654,"prompt_tokens":14,"total_tokens":668},"model":"qwen-plus","id":"chatcmpl-3a5c39d5-3981-4e4c-97f2-e0e821893f03","choices":[{"finish_reason":"stop","index":0,"message":{"role":"assistant","content":"Hello! Hangzhou West Lake is a famous scenic spot in China, located in the western part of Hangzhou City, Zhejiang Province, hence the name \"West Lake\". It is one of China's top ten scenic spots and a World Cultural Heritage site (listed by UNESCO in 2011). It is renowned worldwide for its beautiful natural scenery and profound cultural heritage.\n\n### I. Natural Landscape\nWest Lake is surrounded by mountains on three sides and borders the city on one side, covering an area of approximately 6.39 square kilometers, shaped like a ruyi scepter with rippling blue waters. The lake is naturally or artificially divided into multiple water areas by Solitary Hill, Bai Causeway, Su Causeway, and Yanggong Causeway, forming a layout of \"one mountain, two pagodas, three islands, and three causeways\".\n\nMain attractions include the following:\n- **Spring Dawn at Su Causeway**: During the Northern Song Dynasty, the great literary figure Su Dongpo, while serving as the prefect of Hangzhou, led the dredging of West Lake and used the excavated silt to build a causeway, later named \"Su Causeway\". In spring, peach blossoms and willows create a picturesque scene.\n- **Lingering Snow on Broken Bridge**: Located at the eastern end of Bai Causeway, this is where the reunion scene from the Legend of the White Snake took place. After snowfall in winter, it is particularly famous for its silver-white appearance.\n- **Leifeng Pagoda at Sunset**: Leifeng Pagoda glows golden under the setting sun and was once one of the \"Ten Scenes of West Lake\".\n- **Three Pools Mirroring the Moon**: On Xiaoyingzhou Island in the lake, there are three stone pagodas. During the Mid-Autumn Festival, lanterns can be lit inside the pagodas, creating a harmonious interplay of moonlight, lamplight, and lake reflections.\n- **Autumn Moon over Calm Lake**: Located at the western end of Bai Causeway, it is an excellent spot for viewing the moon over the lake.\n- **Viewing Fish at Flower Harbor**: Known for viewing flowers and fish, with peonies and koi complementing each other beautifully in the garden.\n\n### II. Cultural History\nWest Lake not only boasts beautiful scenery but also carries rich historical and cultural significance:\n- Since the Tang and Song dynasties, numerous literati such as Bai Juyi, Su Dongpo, Lin Bu, and Yang Wanli have left poems here.\n- Bai Juyi oversaw the construction of \"Bai Causeway\" and dredged West Lake, benefiting the local people.\n- Around West Lake are many historical sites, including Yuewang Temple (commemorating national hero Yue Fei), Lingyin Temple (a millennium-old Buddhist temple), Liuhe Pagoda, and Longjing Village (the origin of Longjing tea, one of China's top ten famous teas).\n\n### III. Cultural Symbolism\nWest Lake is regarded as a representative of \"paradise on earth\" and a model of traditional Chinese landscape aesthetics. It embodies the philosophical concept of \"harmony between heaven and humanity\" by integrating natural beauty with cultural depth. Many poems, paintings, and operas feature West Lake, making it an important symbol of Chinese culture.\n\n### IV. Travel Recommendations\n- Best visiting seasons: Spring (March-May) for peach blossoms and willows, Autumn (September-November) for clear skies and cool weather.\n- Recommended ways: Walking, cycling (along the lakeside greenway), or boating on the lake.\n- Local cuisine: West Lake vinegar fish, Longjing shrimp, Dongpo pork, pian'erchuan noodles.\n\nIn summary, Hangzhou West Lake is not just a natural wonder but also a living cultural museum worth exploring in detail. If you ever visit Hangzhou, don't miss this earthly paradise that is \"equally charming in light or heavy makeup\"."}}],"object":"chat.completion"}},"error":null}
{"id":"628312ba-172c-457d-ba7f-3e5462cc6899","custom_id":"req-002","response":{"status_code":200,"request_id":"628312ba-172c-457d-ba7f-3e5462cc6899","body":{"created":1768306035,"usage":{"completion_tokens":25,"prompt_tokens":18,"total_tokens":43},"model":"qwen-plus","id":"chatcmpl-628312ba-172c-457d-ba7f-3e5462cc6899","choices":[{"finish_reason":"stop","index":0,"message":{"role":"assistant","content":"The spring breeze brushes green willows,\nNight rain nourishes red flowers.\nBird songs fill the forest,\nMountains and rivers share the same beauty."}}],"object":"chat.completion"}},"error":null}
- Detail kegagalan (
error_file_id): Berisi informasi tentang permintaan yang gagal dengan nomor baris dan alasan error. Lihat Kode error untuk troubleshooting.
Prosedur detail
Alur kerja Batch API terdiri dari empat langkah: unggah file, buat tugas, tanyakan status tugas, dan unduh hasil.
1. Unggah file
Unggah file JSONL Anda menggunakan API pengunggahan file untuk mendapatkan file_id.
Saat mengunggah file, parameter
purposeharusbatch.
CatatanGunakan kembali ID file yang ada: ID yang dikembalikan setelah mengunggah file (misalnya, file-batch-xxx) dapat digunakan kembali. Jika konten input tetap sama, lewati pengunggahan ulang dan langsung buat tugas dengan ID yang ada:
batch = client.batches.create(
input_file_id="file-batch-xxx", # Gunakan kembali ID file yang ada, tidak perlu mengunggah ulang
endpoint="/v1/chat/completions",
completion_window="24h"
)
Anda dapat mengambil ID file historis melalui API client.files.list(purpose="batch") untuk menanyakan ID file Batch yang telah diunggah.
OpenAI Python SDK
Contoh permintaan
import os
from pathlib import Path
from openai import OpenAI
client = OpenAI(
# Jika tidak ada variabel lingkungan yang diatur, gunakan api_key="sk-xxx" (tidak untuk produksi - risiko kebocoran).
# Kunci API berbeda antar wilayah.
api_key=os.getenv("DASHSCOPE_API_KEY"),
# base_url wilayah Singapura. Untuk Beijing, gunakan: https://dashscope.aliyuncs.com/compatible-mode/v1 dan perbarui kunci API.
# Catatan: Saat mengganti wilayah, perbarui juga kunci API.
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
# test.jsonl adalah file sampel lokal. purpose harus batch.
file_object = client.files.create(file=Path("test.jsonl"), purpose="batch")
print(file_object.model_dump_json())
OpenAI Node.js SDK
Contoh permintaan
/**
* API Batch Model Studio - Unggah file
*
* Jika tidak ada variabel lingkungan yang diatur, gunakan apiKey: 'sk-xxx' (tidak untuk produksi - risiko kebocoran).
* Kunci API berbeda antar wilayah.
*
* Instal dependensi: npm install openai
*/
const OpenAI = require('openai');
const fs = require('fs');
// Konfigurasi wilayah Singapura (default)
const BASE_URL = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1';
// Jika menggunakan wilayah Beijing, ganti BASE_URL di atas dengan:
// const BASE_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
// Catatan: Saat mengganti wilayah, perbarui juga kunci API.
const apiKey = process.env.DASHSCOPE_API_KEY;
if (!apiKey) {
console.error('Error: Harap atur variabel lingkungan DASHSCOPE_API_KEY');
console.error('Atau atur dalam kode: const apiKey = "sk-xxx";');
process.exit(1);
}
const client = new OpenAI({
apiKey: apiKey,
baseURL: BASE_URL
});
const fileStream = fs.createReadStream('test.jsonl');
const fileObject = await client.files.create({
file: fileStream,
purpose: 'batch'
});
console.log(fileObject.id);
Java (HTTP)
Contoh permintaan
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
* API Batch Model Studio - Unggah file
*
* Jika tidak ada variabel lingkungan yang diatur, gunakan API_KEY = "sk-xxx" (tidak untuk produksi - risiko kebocoran).
* Kunci API berbeda antar wilayah.
*
* Konfigurasi wilayah:
* - Wilayah Beijing: https://dashscope.aliyuncs.com/compatible-mode/v1
* - Wilayah Singapura: https://dashscope-intl.aliyuncs.com/compatible-mode/v1
* Catatan: Saat mengganti wilayah, perbarui juga kunci API.
*/
public class BatchAPIUploadFile {
// Konfigurasi wilayah Singapura
private static final String BASE_URL = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1";
// Untuk Beijing, gunakan: private static final String BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"; dan perbarui kunci API.
private static String API_KEY;
public static void main(String[] args) throws Exception {
API_KEY = System.getenv("DASHSCOPE_API_KEY");
if (API_KEY == null || API_KEY.isEmpty()) {
System.err.println("Error: Harap atur variabel lingkungan DASHSCOPE_API_KEY");
System.err.println("Atau atur dalam kode: API_KEY = \"sk-xxx\";");
System.exit(1);
}
String fileId = uploadFile("test.jsonl");
System.out.println("ID File: " + fileId);
}
// === Metode utilitas ===
private static String uploadFile(String filePath) throws Exception {
String boundary = "----WebKitFormBoundary" + System.currentTimeMillis();
URL url = new URL(BASE_URL + "/files");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Bearer " + API_KEY);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {
// Tambahkan field purpose
out.writeBytes("--" + boundary + "\r\n");
out.writeBytes("Content-Disposition: form-data; name=\"purpose\"\r\n\r\n");
out.writeBytes("batch\r\n");
// Tambahkan file
out.writeBytes("--" + boundary + "\r\n");
out.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + filePath + "\"\r\n");
out.writeBytes("Content-Type: application/octet-stream\r\n\r\n");
byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));
out.write(fileBytes);
out.writeBytes("\r\n");
out.writeBytes("--" + boundary + "--\r\n");
}
String response = readResponse(conn);
return parseField(response, "\"id\":\\s*\"([^\"]+)\"");
}
private static String readResponse(HttpURLConnection conn) throws Exception {
int responseCode = conn.getResponseCode();
InputStream is = (responseCode < 400) ? conn.getInputStream() : conn.getErrorStream();
try (Scanner scanner = new Scanner(is, "UTF-8").useDelimiter("\\A")) {
return scanner.hasNext() ? scanner.next() : "";
}
}
private static String parseField(String json, String regex) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(json);
return matcher.find() ? matcher.group(1) : null;
}
}
curl (HTTP)
Contoh permintaan
# ======= Penting =======
# Kunci API berbeda antara wilayah Singapura dan Beijing.
# Berikut adalah base_url untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti base_url dengan: https://dashscope.aliyuncs.com/compatible-mode/v1/files
# === Hapus komentar ini sebelum eksekusi ===
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/files \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
--form 'file=@"test.jsonl"' \
--form 'purpose="batch"'
Contoh respons
{
"id": "file-batch-xxx",
"bytes": 437,
"created_at": 1742304153,
"filename": "test.jsonl",
"object": "file",
"purpose": "batch",
"status": "processed",
"status_details": null
}
2. Buat tugas batch
Buat tugas batch menggunakan ID file yang diperoleh dari langkah pengunggahan file.
OpenAI Python SDK
Contoh permintaan
import os
from openai import OpenAI
client = OpenAI(
# Jika tidak ada variabel lingkungan yang diatur, gunakan api_key="sk-xxx" (tidak untuk produksi - risiko kebocoran).
# Kunci API berbeda antar wilayah.
api_key=os.getenv("DASHSCOPE_API_KEY"),
# base_url wilayah Singapura. Untuk Beijing, gunakan: https://dashscope.aliyuncs.com/compatible-mode/v1 dan perbarui kunci API.
# Catatan: Saat mengganti wilayah, perbarui juga kunci API.
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
batch = client.batches.create(
input_file_id="file-batch-xxx", # ID yang dikembalikan setelah mengunggah file
endpoint="/v1/chat/completions", # Untuk model uji batch-test-model, gunakan /v1/chat/ds-test. Untuk model text embedding, gunakan /v1/embeddings. Untuk model generasi teks/multimodal, gunakan /v1/chat/completions.
completion_window="24h",
metadata={'ds_name':"Nama tugas",'ds_description':'Deskripsi tugas'} # Field metadata opsional untuk membuat nama dan deskripsi tugas
)
print(batch)
OpenAI Node.js SDK
Contoh permintaan
/**
* API Batch Model Studio - Buat tugas batch
*
* Jika tidak ada variabel lingkungan yang diatur, gunakan apiKey: 'sk-xxx' (tidak untuk produksi - risiko kebocoran).
* Kunci API berbeda antar wilayah.
*
* Instal dependensi: npm install openai
*/
const OpenAI = require('openai');
// Konfigurasi wilayah Singapura (default)
const BASE_URL = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1';
// Jika menggunakan wilayah Beijing, ganti BASE_URL di atas dengan:
// const BASE_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
// Catatan: Saat mengganti wilayah, perbarui juga kunci API.
const apiKey = process.env.DASHSCOPE_API_KEY;
if (!apiKey) {
console.error('Error: Harap atur variabel lingkungan DASHSCOPE_API_KEY');
console.error('Atau atur dalam kode: const apiKey = "sk-xxx";');
process.exit(1);
}
const client = new OpenAI({
apiKey: apiKey,
baseURL: BASE_URL
});
const batch = await client.batches.create({
input_file_id: 'file-batch-xxx',
endpoint: '/v1/chat/completions',
completion_window: '24h',
metadata: {'ds_name': 'Nama tugas', 'ds_description': 'Deskripsi tugas'}
});
console.log(batch.id);
Java (HTTP)
Contoh permintaan
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
* API Batch Model Studio - Buat tugas batch
*
* Jika tidak ada variabel lingkungan yang diatur, gunakan API_KEY = "sk-xxx" (tidak untuk produksi - risiko kebocoran).
* Kunci API berbeda antar wilayah.
*
* Konfigurasi wilayah:
* - Wilayah Beijing: https://dashscope.aliyuncs.com/compatible-mode/v1
* - Wilayah Singapura: https://dashscope-intl.aliyuncs.com/compatible-mode/v1
* Catatan: Saat mengganti wilayah, perbarui juga kunci API.
*/
public class BatchAPICreateBatch {
// Konfigurasi wilayah Singapura (default)
private static final String BASE_URL = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1";
// Untuk Beijing, gunakan: private static final String BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"; dan perbarui kunci API.
private static String API_KEY;
public static void main(String[] args) throws Exception {
API_KEY = System.getenv("DASHSCOPE_API_KEY");
if (API_KEY == null || API_KEY.isEmpty()) {
System.err.println("Error: Harap atur variabel lingkungan DASHSCOPE_API_KEY");
System.err.println("Atau atur dalam kode: API_KEY = \"sk-xxx\";");
System.exit(1);
}
String jsonBody = "{\"input_file_id\":\"file-batch-xxx\",\"endpoint\":\"/v1/chat/completions\",\"completion_window\":\"24h\",\"metadata\":{\"ds_name\":\"Nama tugas\",\"ds_description\":\"Deskripsi tugas\"}}";
String response = sendRequest("POST", "/batches", jsonBody);
String batchId = parseField(response, "\"id\":\\s*\"([^\"]+)\"");
System.out.println("ID tugas batch: " + batchId);
}
// === Metode utilitas ===
private static String sendRequest(String method, String path, String jsonBody) throws Exception {
URL url = new URL(BASE_URL + path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setRequestProperty("Authorization", "Bearer " + API_KEY);
if (jsonBody != null) {
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
try (OutputStream os = conn.getOutputStream()) {
os.write(jsonBody.getBytes("UTF-8"));
}
}
return readResponse(conn);
}
private static String readResponse(HttpURLConnection conn) throws Exception {
int responseCode = conn.getResponseCode();
InputStream is = (responseCode < 400) ? conn.getInputStream() : conn.getErrorStream();
try (Scanner scanner = new Scanner(is, "UTF-8").useDelimiter("\\A")) {
return scanner.hasNext() ? scanner.next() : "";
}
}
private static String parseField(String json, String regex) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(json);
return matcher.find() ? matcher.group(1) : null;
}
}
curl (HTTP)
Contoh permintaan
# ======= Penting =======
# Kunci API berbeda antara wilayah Singapura dan Beijing.
# Berikut adalah base_url untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti base_url dengan: https://dashscope.aliyuncs.com/compatible-mode/v1/batches
# === Hapus komentar ini sebelum eksekusi ===
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/batches \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"input_file_id": "file-batch-xxx",
"endpoint": "/v1/chat/completions",
"completion_window": "24h",
"metadata":{"ds_name":"Nama tugas","ds_description":"Deskripsi tugas"}
}'
Parameter input
Field | Tipe | Metode | Wajib | Deskripsi |
|---|---|---|---|---|
input_file_id | String | Body | Ya | ID file input. Gunakan ID file yang dikembalikan oleh API Siapkan dan unggah file, seperti |
endpoint | String | Body | Ya | Jalur akses API. Harus sesuai dengan field url dalam file input.
|
completion_window | String | Body | Ya | Waktu tunggu maksimum. Rentang: 24h-336h, hanya bilangan bulat. Unit: "h" atau "d" (misalnya, "24h" atau "14d"). |
metadata | Map | Body | Tidak | Metadata tambahan untuk tugas, ditentukan sebagai pasangan kunci-nilai. |
metadata.ds_name | String | Body | Tidak | Nama tugas. Contoh: Panjang maksimum: 100 karakter. Jika ditentukan beberapa kali, nilai terakhir yang berlaku. |
metadata.ds_description | String | Body | Tidak | Deskripsi tugas. Contoh: Panjang maksimum: 200 karakter. Jika ditentukan beberapa kali, nilai terakhir yang berlaku. |
Contoh respons
{
"id": "batch_xxx",
"object": "batch",
"endpoint": "/v1/chat/completions",
"errors": null,
"input_file_id": "file-batch-xxx",
"completion_window": "24h",
"status": "validating",
"output_file_id": null,
"error_file_id": null,
"created_at": 1742367779,
"in_progress_at": null,
"expires_at": null,
"finalizing_at": null,
"completed_at": null,
"failed_at": null,
"expired_at": null,
"cancelling_at": null,
"cancelled_at": null,
"request_counts": {
"total": 0,
"completed": 0,
"failed": 0
},
"metadata": {
"ds_name": "Nama tugas",
"ds_description": "Deskripsi tugas"
}
}
Parameter respons
Field | Type | Deskripsi |
|---|---|---|
id | String | ID tugas batch. |
object | String | Nilai tetap: |
endpoint | String | Jalur akses API. |
errors | Map | Informasi error. |
input_file_id | String | ID file input . |
completion_window | String | Waktu tunggu maksimum. Rentang: 24h-336h, hanya bilangan bulat. Unit: "h" atau "d" (misalnya, "24h" atau "14d"). |
status | String | Status tugas: validating, failed, in_progress, finalizing, completed, expired, cancelling, cancelled. |
output_file_id | String | ID file untuk hasil permintaan yang berhasil. |
error_file_id | String | ID file untuk hasil permintaan yang gagal. |
created_at | Integer | Timestamp Unix (detik) saat tugas dibuat. |
in_progress_at | Integer | Timestamp Unix (detik) saat tugas mulai diproses. |
expires_at | Integer | Timestamp Unix (detik) saat tugas mulai timeout. |
finalizing_at | Integer | Timestamp Unix (detik) saat tugas terakhir dimulai. |
completed_at | Integer | Timestamp Unix (detik) saat tugas selesai. |
failed_at | Integer | Timestamp Unix (detik) saat tugas gagal. |
expired_at | Integer | Timestamp Unix (detik) saat tugas kedaluwarsa. |
cancelling_at | Integer | Timestamp Unix (detik) saat tugas memasuki status cancelling. |
cancelled_at | Integer | Timestamp Unix (detik) saat tugas dibatalkan. |
request_counts | Map | Jumlah permintaan berdasarkan status. |
metadata | Map | Metadata tambahan sebagai pasangan kunci-nilai. |
metadata.ds_name | String | Nama tugas. |
metadata.ds_description | String | Deskripsi tugas. |
3. Tanyakan dan kelola tugas batch
Setelah membuat tugas, gunakan API berikut untuk menanyakan statusnya, mencantumkan tugas historis, atau membatalkan tugas yang sedang berlangsung.
Tanyakan status tugas tertentu
Tanyakan tugas batch berdasarkan ID-nya. Hanya tugas yang dibuat dalam 30 hari terakhir yang dapat ditanyakan.
OpenAI Python SDK
Contoh permintaan
import os
from openai import OpenAI
client = OpenAI(
# Jika tidak ada variabel lingkungan yang diatur, gunakan api_key="sk-xxx" (tidak untuk produksi - risiko kebocoran).
# Kunci API berbeda antar wilayah.
api_key=os.getenv("DASHSCOPE_API_KEY"),
# base_url wilayah Singapura. Untuk Beijing, gunakan: https://dashscope.aliyuncs.com/compatible-mode/v1 dan perbarui kunci API.
# Catatan: Saat mengganti wilayah, perbarui juga kunci API.
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
batch = client.batches.retrieve("batch_id") # Ganti batch_id dengan ID tugas batch
print(batch)
OpenAI Node.js SDK
Contoh permintaan
/**
* API Batch Model Studio - Tanyakan tugas tunggal
*
* Jika tidak ada variabel lingkungan yang diatur, gunakan apiKey: 'sk-xxx' (tidak untuk produksi - risiko kebocoran).
* Kunci API berbeda antar wilayah.
*
* Instal dependensi: npm install openai
*/
const OpenAI = require('openai');
// Konfigurasi wilayah Singapura (default)
const BASE_URL = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1';
// Jika menggunakan wilayah Beijing, ganti BASE_URL di atas dengan:
// const BASE_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
// Catatan: Saat mengganti wilayah, perbarui juga kunci API.
const apiKey = process.env.DASHSCOPE_API_KEY;
if (!apiKey) {
console.error('Error: Harap atur variabel lingkungan DASHSCOPE_API_KEY');
console.error('Atau atur dalam kode: const apiKey = "sk-xxx";');
process.exit(1);
}
const client = new OpenAI({
apiKey: apiKey,
baseURL: BASE_URL
});
const batch = await client.batches.retrieve('batch_id');
console.log(batch.status);
Java (HTTP)
Contoh permintaan
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
* API Batch Model Studio - Tanyakan tugas tunggal
*
* Jika tidak ada variabel lingkungan yang diatur, gunakan API_KEY = "sk-xxx" (tidak untuk produksi - risiko kebocoran).
* Kunci API berbeda antar wilayah.
*
* Konfigurasi wilayah:
* - Wilayah Beijing: https://dashscope.aliyuncs.com/compatible-mode/v1
* - Wilayah Singapura: https://dashscope-intl.aliyuncs.com/compatible-mode/v1
* Catatan: Saat mengganti wilayah, perbarui juga kunci API.
*/
public class BatchAPIRetrieveBatch {
// Konfigurasi wilayah Singapura
private static final String BASE_URL = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1";
// Untuk Beijing, gunakan: private static final String BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"; dan perbarui kunci API.
private static String API_KEY;
public static void main(String[] args) throws Exception {
API_KEY = System.getenv("DASHSCOPE_API_KEY");
if (API_KEY == null || API_KEY.isEmpty()) {
System.err.println("Error: Harap atur variabel lingkungan DASHSCOPE_API_KEY");
System.err.println("Atau atur dalam kode: API_KEY = \"sk-xxx\";");
System.exit(1);
}
String batchInfo = sendRequest("GET", "/batches/batch_id", null);
String status = parseField(batchInfo, "\"status\":\\s*\"([^\"]+)\"");
System.out.println("Status tugas: " + status);
}
// === Metode utilitas ===
private static String sendRequest(String method, String path, String jsonBody) throws Exception {
URL url = new URL(BASE_URL + path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setRequestProperty("Authorization", "Bearer " + API_KEY);
if (jsonBody != null) {
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
try (OutputStream os = conn.getOutputStream()) {
os.write(jsonBody.getBytes("UTF-8"));
}
}
return readResponse(conn);
}
private static String readResponse(HttpURLConnection conn) throws Exception {
int responseCode = conn.getResponseCode();
InputStream is = (responseCode < 400) ? conn.getInputStream() : conn.getErrorStream();
try (Scanner scanner = new Scanner(is, "UTF-8").useDelimiter("\\A")) {
return scanner.hasNext() ? scanner.next() : "";
}
}
private static String parseField(String json, String regex) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(json);
return matcher.find() ? matcher.group(1) : null;
}
}
curl (HTTP)
Contoh permintaan
# ======= Penting =======
# Kunci API berbeda antara wilayah Singapura dan Beijing.
# Berikut adalah base_url untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti base_url dengan: https://dashscope.aliyuncs.com/compatible-mode/v1/batches/batch_id
# === Hapus komentar ini sebelum eksekusi ===
curl --request GET 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/batches/batch_id' \
-H "Authorization: Bearer $DASHSCOPE_API_KEY"
Contoh respons
Permintaan yang berhasil mengembalikan informasi detail tugas batch. Berikut adalah contoh respons untuk tugas dengan status completed:
{
"id": "batch_abc123",
"object": "batch",
"endpoint": "/v1/chat/completions",
"errors": null,
"input_file_id": "file-abc123",
"completion_window": "24h",
"status": "completed",
"output_file_id": "file-batch_output-xyz789",
"error_file_id": "file-batch_error-xyz789",
"created_at": 1711402400,
"in_progress_at": 1711402450,
"expires_at": 1711488800,
"finalizing_at": 1711405000,
"completed_at": 1711406000,
"failed_at": null,
"expired_at": null,
"cancelling_at": null,
"cancelled_at": null,
"request_counts": {
"total": 100,
"completed": 95,
"failed": 5
},
"metadata": {
"customer_id": "user_123456789",
"batch_description": "Nightly eval job"
}
}
Untuk deskripsi field, lihat tabel di bawah.
Field | Tipe | Deskripsi |
|---|---|---|
id | String | ID tugas batch. |
status | String | Status tugas. Nilai yang mungkin:
|
output_file_id | String | ID file output yang berisi hasil yang berhasil. Dihasilkan setelah tugas selesai. |
error_file_id | String | ID file error yang berisi detail permintaan yang gagal. Dihasilkan setelah tugas selesai jika ada permintaan yang gagal. |
request_counts | Object | Statistik jumlah permintaan yang berisi total, completed, dan failed. |
Tanyakan daftar tugas
Gunakan metode batches.list() untuk mengambil daftar tugas batch. Gunakan pagination untuk mengambil daftar tugas lengkap.
OpenAI Python SDK
Contoh permintaan
import os
from openai import OpenAI
client = OpenAI(
# Jika tidak ada variabel lingkungan yang diatur, gunakan api_key="sk-xxx" (tidak untuk produksi - risiko kebocoran).
# Kunci API berbeda antar wilayah.
api_key=os.getenv("DASHSCOPE_API_KEY"),
# base_url wilayah Singapura. Untuk Beijing, gunakan: https://dashscope.aliyuncs.com/compatible-mode/v1 dan perbarui kunci API.
# Catatan: Saat mengganti wilayah, perbarui juga kunci API.
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
batches = client.batches.list(after="batch_xxx", limit=2,extra_query={'ds_name':'Nama tugas','input_file_ids':'file-batch-xxx,file-batch-xxx','status':'completed,expired','create_after':'20250304000000','create_before':'20250306123000'})
print(batches)
OpenAI Node.js SDK
Contoh permintaan
/**
* API Batch Model Studio - Tanyakan daftar tugas
*
* Jika tidak ada variabel lingkungan yang diatur, gunakan apiKey: 'sk-xxx' (tidak untuk produksi - risiko kebocoran).
* Kunci API berbeda antar wilayah.
*
* Instal dependensi: npm install openai
*/
const OpenAI = require('openai');
// Konfigurasi wilayah Singapura (default)
const BASE_URL = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1';
// Jika menggunakan wilayah Beijing, ganti BASE_URL di atas dengan:
// const BASE_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
// Catatan: Saat mengganti wilayah, perbarui juga kunci API.
const apiKey = process.env.DASHSCOPE_API_KEY;
if (!apiKey) {
console.error('Error: Harap atur variabel lingkungan DASHSCOPE_API_KEY');
console.error('Atau atur dalam kode: const apiKey = "sk-xxx";');
process.exit(1);
}
const client = new OpenAI({
apiKey: apiKey,
baseURL: BASE_URL
});
const batches = await client.batches.list({
after: 'batch_xxx',
limit: 2,
extra_query: {
'ds_name': 'Nama tugas',
'input_file_ids': 'file-batch-xxx,file-batch-xxx',
'status': 'completed,expired',
'create_after': '20250304000000',
'create_before': '20250306123000'
}
});
for (const batch of batches.data) {
console.log(batch.id, batch.status);
}
Java (HTTP)
Contoh permintaan
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
* API Batch Model Studio - Tanyakan daftar tugas
*
* Jika tidak ada variabel lingkungan yang diatur, gunakan API_KEY = "sk-xxx" (tidak untuk produksi - risiko kebocoran).
* Kunci API berbeda antar wilayah.
*
* Konfigurasi wilayah:
* - Wilayah Beijing: https://dashscope.aliyuncs.com/compatible-mode/v1
* - Wilayah Singapura: https://dashscope-intl.aliyuncs.com/compatible-mode/v1
* Catatan: Saat mengganti wilayah, perbarui juga kunci API.
*/
public class BatchAPIListBatches {
// Konfigurasi wilayah Singapura
private static final String BASE_URL = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1";
// Untuk Beijing, gunakan: private static final String BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"; dan perbarui kunci API.
private static String API_KEY;
public static void main(String[] args) throws Exception {
API_KEY = System.getenv("DASHSCOPE_API_KEY");
if (API_KEY == null || API_KEY.isEmpty()) {
System.err.println("Error: Harap atur variabel lingkungan DASHSCOPE_API_KEY");
System.err.println("Atau atur dalam kode: API_KEY = \"sk-xxx\";");
System.exit(1);
}
String response = sendRequest("GET", "/batches?after=batch_xxx&limit=2&ds_name=Batch&input_file_ids=file-batch-xxx,file-batch-xxx&status=completed,failed&create_after=20250303000000&create_before=20250320000000", null);
// Parsing JSON untuk mendapatkan daftar tugas
System.out.println(response);
}
// === Metode utilitas ===
private static String sendRequest(String method, String path, String jsonBody) throws Exception {
URL url = new URL(BASE_URL + path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setRequestProperty("Authorization", "Bearer " + API_KEY);
if (jsonBody != null) {
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
try (OutputStream os = conn.getOutputStream()) {
os.write(jsonBody.getBytes("UTF-8"));
}
}
return readResponse(conn);
}
private static String readResponse(HttpURLConnection conn) throws Exception {
int responseCode = conn.getResponseCode();
InputStream is = (responseCode < 400) ? conn.getInputStream() : conn.getErrorStream();
try (Scanner scanner = new Scanner(is, "UTF-8").useDelimiter("\\A")) {
return scanner.hasNext() ? scanner.next() : "";
}
}
private static String parseField(String json, String regex) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(json);
return matcher.find() ? matcher.group(1) : null;
}
}
curl (HTTP)
Contoh permintaan
# ======= Penting =======
# Kunci API berbeda antara wilayah Singapura dan Beijing.
# Berikut adalah base_url untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti base_url dengan: https://dashscope.aliyuncs.com/compatible-mode/v1/batches?xxx sama seperti di bawah xxx
# === Hapus komentar ini sebelum eksekusi ===
curl --request GET 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/batches?after=batch_xxx&limit=2&ds_name=Batch&input_file_ids=file-batch-xxx,file-batch-xxx&status=completed,failed&create_after=20250303000000&create_before=20250320000000' \
-H "Authorization: Bearer $DASHSCOPE_API_KEY"
Ganti
batch_iddalamafter=batch_iddengan nilai aktual. Aturlimitke jumlah tugas yang akan dikembalikan. Tentukan nama tugas parsial untukds_name. Untuk input_file_ids, tentukan satu atau beberapa ID file. Tentukan satu atau beberapa status tugas batch untukstatus. Untukcreate_afterdancreate_before, tentukan batas waktu.
Parameter input
Field | Tipe | Metode | Wajib | Deskripsi |
|---|---|---|---|---|
after | String | Kueri | Tidak | Kursor untuk pagination. Atur ini ke ID tugas terakhir dari halaman sebelumnya. |
limit | Integer | Kueri | Tidak | Jumlah tugas per halaman. Rentang: [1, 100]. Default: 20. |
ds_name | String | Kueri | Tidak | Pencocokan fuzzy berdasarkan nama tugas. |
input_file_ids | String | Kueri | Tidak | Filter berdasarkan ID file. Tentukan beberapa ID yang dipisahkan koma (maksimal 20). |
status | String | Kueri | Tidak | Filter berdasarkan status tugas. Tentukan beberapa status yang dipisahkan koma. |
create_after | String | Kueri | Tidak | Filter tugas yang dibuat setelah waktu ini. Format: |
create_before | String | Kueri | Tidak | Filter tugas yang dibuat sebelum waktu ini. Format: |
Contoh respons
{
"object": "list",
"data": [
{
"id": "batch_xxx",
"object": "batch",
"endpoint": "/v1/chat/completions",
"errors": null,
"input_file_id": "file-batch-xxx",
"completion_window": "24h",
"status": "completed",
"output_file_id": "file-batch_output-xxx",
"error_file_id": null,
"created_at": 1722234109,
"in_progress_at": 1722234109,
"expires_at": null,
"finalizing_at": 1722234165,
"completed_at": 1722234165,
"failed_at": null,
"expired_at": null,
"cancelling_at": null,
"cancelled_at": null,
"request_counts": {
"total": 100,
"completed": 95,
"failed": 5
},
"metadata": {}
},
{ ... }
],
"first_id": "batch_xxx",
"last_id": "batch_xxx",
"has_more": true
}
Parameter respons
Field | Tipe | Deskripsi |
|---|---|---|
object | String | Jenis objek. Nilai tetap: list. |
data | Array | Array objek tugas batch. Lihat parameter respons untuk membuat tugas batch. |
first_id | String | ID tugas batch pertama pada halaman saat ini. |
last_id | String | ID tugas batch terakhir pada halaman saat ini. |
has_more | Boolean | Apakah halaman tambahan tersedia. |
Batalkan tugas batch
Batalkan tugas yang sedang berlangsung atau dalam antrean. Setelah panggilan berhasil, status tugas berubah menjadi cancelling dan kemudian menjadi cancelled. Anda tetap dikenai biaya untuk permintaan yang berhasil diselesaikan sebelum pembatalan berlaku penuh.
OpenAI Python SDK
Contoh permintaan
import os
from openai import OpenAI
client = OpenAI(
# Jika tidak ada variabel lingkungan yang diatur, gunakan api_key="sk-xxx" (tidak untuk produksi - risiko kebocoran).
# Kunci API berbeda antar wilayah.
api_key=os.getenv("DASHSCOPE_API_KEY"),
# base_url wilayah Singapura. Untuk Beijing, gunakan: https://dashscope.aliyuncs.com/compatible-mode/v1 dan perbarui kunci API.
# Catatan: Saat mengganti wilayah, perbarui juga kunci API.
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
batch = client.batches.cancel("batch_id") # Ganti batch_id dengan ID tugas batch
print(batch)
OpenAI Node.js SDK
Contoh permintaan
/**
* API Batch Model Studio - Batalkan tugas
*
* Jika tidak ada variabel lingkungan yang diatur, gunakan apiKey: 'sk-xxx' (tidak untuk produksi - risiko kebocoran).
* Kunci API berbeda antar wilayah.
*
* Instal dependensi: npm install openai
*/
const OpenAI = require('openai');
// Konfigurasi wilayah Singapura (default)
const BASE_URL = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1';
// Jika menggunakan wilayah Beijing, ganti BASE_URL di atas dengan:
// const BASE_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
// Catatan: Saat mengganti wilayah, perbarui juga kunci API.
const apiKey = process.env.DASHSCOPE_API_KEY;
if (!apiKey) {
console.error('Error: Harap atur variabel lingkungan DASHSCOPE_API_KEY');
console.error('Atau atur dalam kode: const apiKey = "sk-xxx";');
process.exit(1);
}
const client = new OpenAI({
apiKey: apiKey,
baseURL: BASE_URL
});
const batch = await client.batches.cancel('batch_id');
console.log(batch.status); // cancelled
Java (HTTP)
Contoh permintaan
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
* API Batch Model Studio - Batalkan tugas
*
* Jika tidak ada variabel lingkungan yang diatur, gunakan API_KEY = "sk-xxx" (tidak untuk produksi - risiko kebocoran).
* Kunci API berbeda antar wilayah.
*
* Konfigurasi wilayah:
* - Wilayah Beijing: https://dashscope.aliyuncs.com/compatible-mode/v1
* - Wilayah Singapura: https://dashscope-intl.aliyuncs.com/compatible-mode/v1
* Catatan: Saat mengganti wilayah, perbarui juga kunci API.
*/
public class BatchAPICancelBatch {
// Konfigurasi wilayah Singapura
private static final String BASE_URL = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1";
// Untuk Beijing, gunakan: private static final String BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"; dan perbarui kunci API.
private static String API_KEY;
public static void main(String[] args) throws Exception {
API_KEY = System.getenv("DASHSCOPE_API_KEY");
if (API_KEY == null || API_KEY.isEmpty()) {
System.err.println("Error: Harap atur variabel lingkungan DASHSCOPE_API_KEY");
System.err.println("Atau atur dalam kode: API_KEY = \"sk-xxx\";");
System.exit(1);
}
String response = sendRequest("POST", "/batches/batch_id/cancel", null);
System.out.println(response);
}
// === Metode utilitas ===
private static String sendRequest(String method, String path, String jsonBody) throws Exception {
URL url = new URL(BASE_URL + path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setRequestProperty("Authorization", "Bearer " + API_KEY);
if (jsonBody != null) {
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
try (OutputStream os = conn.getOutputStream()) {
os.write(jsonBody.getBytes("UTF-8"));
}
}
return readResponse(conn);
}
private static String readResponse(HttpURLConnection conn) throws Exception {
int responseCode = conn.getResponseCode();
InputStream is = (responseCode < 400) ? conn.getInputStream() : conn.getErrorStream();
try (Scanner scanner = new Scanner(is, "UTF-8").useDelimiter("\\A")) {
return scanner.hasNext() ? scanner.next() : "";
}
}
private static String parseField(String json, String regex) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(json);
return matcher.find() ? matcher.group(1) : null;
}
}
curl (HTTP)
Contoh permintaan
# ======= Penting =======
# Kunci API berbeda antara wilayah Singapura dan Beijing.
# Berikut adalah base_url untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti base_url dengan: https://dashscope.aliyuncs.com/compatible-mode/v1/batches/batch_id/cancel
# === Hapus komentar ini sebelum eksekusi ===
curl --request POST 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/batches/batch_id/cancel' \
-H "Authorization: Bearer $DASHSCOPE_API_KEY"
Ganti
batch_iddengan nilai aktual.
Contoh respons
Setelah Anda berhasil membatalkan tugas, API mengembalikan informasi detail tugas batch. Berikut adalah contoh respons untuk tugas dengan status cancelling:
{
"id": "batch_abc123",
"object": "batch",
"endpoint": "/v1/chat/completions",
"errors": null,
"input_file_id": "file-abc123",
"completion_window": "24h",
"status": "cancelling",
"output_file_id": null,
"error_file_id": null,
"created_at": 1711402400,
"in_progress_at": 1711402450,
"expires_at": 1711488800,
"finalizing_at": null,
"completed_at": null,
"failed_at": null,
"expired_at": null,
"cancelling_at": 1711403000,
"cancelled_at": null,
"request_counts": {
"total": 100,
"completed": 23,
"failed": 1
},
"metadata": null
}
Setelah Anda membatalkan tugas, status pertama kali berubah menjadi
cancellingsementara sistem menunggu permintaan yang sedang dieksekusi selesai. Status akhirnya berubah menjadicancelled. Hasil dari permintaan yang berhasil diselesaikan tetap disimpan dalam file output.
4. Unduh file hasil Batch
Setelah tugas selesai, file hasil (output_file_id) dan file error (error_file_id) mungkin dihasilkan. Unduh kedua jenis file menggunakan API pengunduhan file yang sama.
Anda hanya dapat mengunduh file yang file_id-nya diawali dengan file-batch_output.
OpenAI Python SDK
Gunakan metode content untuk mengambil konten file hasil tugas batch dan gunakan metode write_to_file untuk menyimpannya secara lokal.
Contoh permintaan
import os
from openai import OpenAI
client = OpenAI(
# Jika tidak ada variabel lingkungan yang diatur, gunakan api_key="sk-xxx" (tidak untuk produksi - risiko kebocoran).
# Kunci API berbeda antar wilayah.
api_key=os.getenv("DASHSCOPE_API_KEY"),
# base_url wilayah Singapura. Untuk Beijing, gunakan: https://dashscope.aliyuncs.com/compatible-mode/v1 dan perbarui kunci API.
# Catatan: Saat mengganti wilayah, perbarui juga kunci API.
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
content = client.files.content(file_id="file-batch_output-xxx")
# Cetak konten file hasil
print(content.text)
# Simpan file hasil secara lokal
content.write_to_file("result.jsonl")
Contoh respons
{"id":"c308ef7f-xxx","custom_id":"1","response":{"status_code":200,"request_id":"c308ef7f-0824-9c46-96eb-73566f062426","body":{"created":1742303743,"usage":{"completion_tokens":35,"prompt_tokens":26,"total_tokens":61},"model":"qwen-plus","id":"chatcmpl-c308ef7f-0824-9c46-96eb-73566f062426","choices":[{"finish_reason":"stop","index":0,"message":{"content":"Hello! Of course. Whether you need information, learning materials, problem-solving methods, or any other help, I am here to support you. Please tell me what you need help with."}}],"object":"chat.completion"}},"error":null}
{"id":"73291560-xxx","custom_id":"2","response":{"status_code":200,"request_id":"73291560-7616-97bf-87f2-7d747bbe84fd","body":{"created":1742303743,"usage":{"completion_tokens":7,"prompt_tokens":26,"total_tokens":33},"model":"qwen-plus","id":"chatcmpl-73291560-7616-97bf-87f2-7d747bbe84fd","choices":[{"finish_reason":"stop","index":0,"message":{"content":"2+2 equals 4."}}],"object":"chat.completion"}},"error":null}
OpenAI Node.js SDK
Gunakan metode content untuk mengambil konten file hasil tugas batch.
Contoh permintaan
/**
* API Batch Model Studio - Unduh file hasil
*
* Jika tidak ada variabel lingkungan yang diatur, gunakan apiKey: 'sk-xxx' (tidak untuk produksi - risiko kebocoran).
* Kunci API berbeda antar wilayah.
*
* Instal dependensi: npm install openai
*/
const OpenAI = require('openai');
const fs = require('fs');
// Konfigurasi wilayah Singapura (default)
const BASE_URL = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1';
// Jika menggunakan wilayah Beijing, ganti BASE_URL di atas dengan:
// const BASE_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
// Catatan: Saat mengganti wilayah, perbarui juga kunci API.
const apiKey = process.env.DASHSCOPE_API_KEY;
if (!apiKey) {
console.error('Error: Harap atur variabel lingkungan DASHSCOPE_API_KEY');
console.error('Atau atur dalam kode: const apiKey = "sk-xxx";');
process.exit(1);
}
const client = new OpenAI({
apiKey: apiKey,
baseURL: BASE_URL
});
// Unduh file hasil
const content = await client.files.content('file-batch_output-xxx');
const text = await content.text();
console.log(text);
// Simpan ke file lokal
fs.writeFileSync('result.jsonl', text);
console.log('Hasil disimpan ke result.jsonl');
Java (HTTP)
Gunakan permintaan GET ke endpoint /files/{file_id}/content untuk mengunduh konten file.
Contoh permintaan
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
* API Batch Model Studio - Unduh file hasil
*
* Jika tidak ada variabel lingkungan yang diatur, gunakan API_KEY = "sk-xxx" (tidak untuk produksi - risiko kebocoran).
* Kunci API berbeda antar wilayah.
*
* Konfigurasi wilayah:
* - Wilayah Beijing: https://dashscope.aliyuncs.com/compatible-mode/v1
* - Wilayah Singapura: https://dashscope-intl.aliyuncs.com/compatible-mode/v1
* Catatan: Saat mengganti wilayah, perbarui juga kunci API.
*/
public class BatchAPIDownloadFile {
// Konfigurasi wilayah Singapura
private static final String BASE_URL = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1";
// Untuk Beijing, gunakan: private static final String BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"; dan perbarui kunci API.
private static String API_KEY;
public static void main(String[] args) throws Exception {
API_KEY = System.getenv("DASHSCOPE_API_KEY");
if (API_KEY == null || API_KEY.isEmpty()) {
System.err.println("Error: Harap atur variabel lingkungan DASHSCOPE_API_KEY");
System.err.println("Atau atur dalam kode: API_KEY = \"sk-xxx\";");
System.exit(1);
}
// Unduh file hasil
String content = sendRequest("GET", "/files/file-batch_output-xxx/content", null);
System.out.println(content);
// Simpan ke file lokal
Files.write(Paths.get("result.jsonl"), content.getBytes());
System.out.println("Hasil disimpan ke result.jsonl");
}
// === Metode utilitas ===
private static String sendRequest(String method, String path, String jsonBody) throws Exception {
URL url = new URL(BASE_URL + path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setRequestProperty("Authorization", "Bearer " + API_KEY);
if (jsonBody != null) {
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
try (OutputStream os = conn.getOutputStream()) {
os.write(jsonBody.getBytes("UTF-8"));
}
}
return readResponse(conn);
}
private static String readResponse(HttpURLConnection conn) throws Exception {
int responseCode = conn.getResponseCode();
InputStream is = (responseCode < 400) ? conn.getInputStream() : conn.getErrorStream();
try (Scanner scanner = new Scanner(is, "UTF-8").useDelimiter("\\A")) {
return scanner.hasNext() ? scanner.next() : "";
}
}
private static String parseField(String json, String regex) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(json);
return matcher.find() ? matcher.group(1) : null;
}
}
curl (HTTP)
Unduh file hasil dengan menentukan file_id dalam permintaan GET.
Contoh permintaan
# ======= Penting =======
# Kunci API berbeda antara wilayah Singapura dan Beijing.
# Berikut adalah base_url untuk wilayah Singapura. Jika Anda menggunakan model di wilayah Beijing, ganti base_url dengan: https://dashscope.aliyuncs.com/compatible-mode/v1/files/file-batch_output-xxx/content
# === Hapus komentar ini sebelum eksekusi ===
curl -X GET https://dashscope-intl.aliyuncs.com/compatible-mode/v1/files/file-batch_output-xxx/content \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" > result.jsonl
Contoh respons
Contoh respons tunggal:
{
"id": "c308ef7f-xxx",
"custom_id": "1",
"response": {
"status_code": 200,
"request_id": "c308ef7f-0824-9c46-96eb-73566f062426",
"body": {
"created": 1742303743,
"usage": {
"completion_tokens": 35,
"prompt_tokens": 26,
"total_tokens": 61
},
"model": "qwen-plus",
"id": "chatcmpl-c308ef7f-0824-9c46-96eb-73566f062426",
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"content": "Hello! Of course. Whether you need information, learning materials, problem-solving methods, or any other help, I am here to support you. Please tell me what you need help with."
}
}
],
"object": "chat.completion"
}
},
"error": null
}
Parameter respons
Field | Tipe | Deskripsi |
|---|---|---|
id | String | ID permintaan. |
custom_id | String | Pengenal permintaan yang ditentukan pengguna. |
response | Object | Hasil permintaan. |
status_code | Integer | Kode status HTTP. 200 menunjukkan sukses. |
request_id | String | ID unik yang dihasilkan server untuk permintaan ini. |
completion_tokens | Integer | Jumlah token dalam respons yang dihasilkan model. |
prompt_tokens | Integer | Jumlah token dalam konten input ( |
total_tokens | Integer | Total jumlah token yang digunakan oleh permintaan ini. |
model | String | Nama model yang digunakan untuk permintaan ini. |
error | Object | Objek error. Mengembalikan |
error.code | String | Informasi baris error dan alasannya. Lihat Kode error untuk troubleshooting. |
error.message | String | Pesan error. |
Fitur lanjutan
Atur notifikasi penyelesaian
Untuk tugas berjalan lama, gunakan notifikasi asinkron alih-alih polling untuk mengurangi konsumsi sumber daya.
CatatanNotifikasi penyelesaian hanya didukung di wilayah Beijing.
- Callback: Tentukan URL yang dapat diakses publik saat membuat tugas.
- Antrian pesan EventBridge: Terintegrasi erat dengan ekosistem Alibaba Cloud. Tidak memerlukan IP publik.
Metode 1: Callback
Saat membuat tugas, tentukan URL yang dapat diakses publik melalui metadata. Setelah tugas selesai, sistem mengirim permintaan POST yang berisi status tugas ke URL yang ditentukan:
OpenAI Python SDK
import os
from openai import OpenAI
client = OpenAI(
# Jika tidak ada variabel lingkungan yang diatur, gunakan api_key="sk-xxx" (tidak untuk produksi - risiko kebocoran).
# Kunci API berbeda antar wilayah.
api_key=os.getenv("DASHSCOPE_API_KEY"),
# base_url wilayah Beijing. Untuk Singapura, gunakan: https://dashscope-intl.aliyuncs.com/compatible-mode/v1 dan perbarui kunci API.
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
batch = client.batches.create(
input_file_id="file-batch-xxx", # ID yang dikembalikan setelah mengunggah file
endpoint="/v1/chat/completions", # Untuk model text embedding, masukkan "/v1/embeddings". Untuk model uji batch-test-model, masukkan /v1/chat/ds-test. Untuk model lainnya, masukkan /v1/chat/completions.
completion_window="24h",
metadata={
"ds_batch_finish_callback": "https://xxx/xxx"
}
)
print(batch)
curl (HTTP)
Contoh permintaan
curl -X POST --location "https://dashscope.aliyuncs.com/compatible-mode/v1/batches" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"input_file_id": "file-batch-xxxxx",
"endpoint": "/v1/chat/completions",
"completion_window": "24h",
"metadata": {
"ds_batch_finish_callback": "https://xxx/xxx"
}
}'
Metode 2: Antrian pesan EventBridge
Metode ini tidak memerlukan IP publik dan cocok untuk skenario kompleks yang perlu integrasi dengan layanan seperti Function Compute atau RocketMQ.
Saat tugas batch selesai, sistem mengirim event ke Alibaba Cloud EventBridge. Konfigurasikan aturan EventBridge untuk mendengarkan event ini dan mengarahkannya ke target tertentu.
- Sumber event (Source):
acs.dashscope - Jenis event (Type):
dashscope:System:BatchTaskFinish
Referensi: Arahkan event ke Message Queue for RocketMQ.
Mulai produksi
-
Manajemen file
- Hapus file yang tidak diperlukan secara berkala menggunakan OpenAI File delete API untuk menghindari mencapai batas penyimpanan (10.000 file atau 100 GB).
- Simpan file besar di OSS alih-alih mengunggah langsung.
-
Pemantauan tugas
- Gunakan notifikasi asinkron Callback atau EventBridge.
- Jika polling diperlukan, atur interval lebih dari 1 menit dan gunakan strategi backoff eksponensial.
-
Penanganan error
- Implementasikan penanganan untuk error jaringan, error API, dan exception lainnya.
- Unduh dan analisis detail error dari
error_file_id. - Untuk kode error umum, lihat Kode error.
-
Optimasi biaya
- Gabungkan tugas kecil menjadi satu batch.
- Atur
completion_windowsecara tepat untuk memungkinkan fleksibilitas penjadwalan yang lebih besar.
Alat utilitas
CSV ke JSONL
Jika data Anda dalam file CSV (kolom pertama: ID, kolom kedua: konten), gunakan skrip ini untuk menghasilkan file input batch JSONL.
Untuk menyesuaikan jalur file atau parameter lainnya, modifikasi kode sesuai kebutuhan.
import csv
import json
def messages_builder_example(content):
messages = [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": content}]
return messages
with open("input_demo.csv", "r") as fin:
with open("input_demo.jsonl", 'w', encoding='utf-8') as fout:
csvreader = csv.reader(fin)
for row in csvreader:
body = {"model": "qwen-turbo", "messages": messages_builder_example(row[1])}
# Saat memanggil model text embedding, atur nilai url ke "/v1/embeddings". Untuk model lainnya, atur ke /v1/chat/completions.
request = {"custom_id": row[0], "method": "POST", "url": "/v1/chat/completions", "body": body}
fout.write(json.dumps(request, separators=(',', ':'), ensure_ascii=False) + "\n")
Hasil JSONL ke CSV
Gunakan skrip ini untuk mengonversi result.jsonl menjadi result.csv untuk analisis di Excel.
Untuk menyesuaikan jalur file atau parameter lainnya, modifikasi kode sesuai kebutuhan.
import json
import csv
columns = ["custom_id",
"model",
"request_id",
"status_code",
"error_code",
"error_message",
"created",
"content",
"usage"]
def dict_get_string(dict_obj, path):
obj = dict_obj
try:
for element in path:
obj = obj[element]
return obj
except:
return None
with open("result.jsonl", "r") as fin:
with open("result.csv", 'w', encoding='utf-8') as fout:
rows = [columns]
for line in fin:
request_result = json.loads(line)
row = [dict_get_string(request_result, ["custom_id"]),
dict_get_string(request_result, ["response", "body", "model"]),
dict_get_string(request_result, ["response", "request_id"]),
dict_get_string(request_result, ["response", "status_code"]),
dict_get_string(request_result, ["error", "error_code"]),
dict_get_string(request_result, ["error", "error_message"]),
dict_get_string(request_result, ["response", "body", "created"]),
dict_get_string(request_result, ["response", "body", "choices", 0, "message", "content"]),
dict_get_string(request_result, ["response", "body", "usage"])]
rows.append(row)
writer = csv.writer(fout)
writer.writerows(rows)
Perbaiki teks rusak di Excel- Gunakan editor teks (seperti Sublime Text) untuk mengonversi encoding file CSV ke GBK, lalu buka di Excel.
- Atau, buat file Excel baru dan tentukan encoding UTF-8 saat mengimpor data.
Batas laju
API | Batas laju (per Akun Alibaba Cloud) |
|---|---|
Buat tugas | 1.000 panggilan/menit; maksimal 1.000 tugas konkuren |
Tanyakan tugas | 1.000 panggilan/menit |
Tanyakan daftar tugas | 100 panggilan/menit |
Batalkan tugas | 1.000 panggilan/menit |
Penagihan
-
Harga satuan: Token input dan output untuk semua permintaan yang berhasil dikenai biaya sebesar 50% dari harga inferensi real-time untuk model yang sesuai. Untuk informasi lebih lanjut, lihat Daftar model.
-
Lingkup penagihan:
- Hanya permintaan yang berhasil dieksekusi dalam tugas yang dikenai biaya.
- Permintaan yang gagal karena error parsing file, kegagalan eksekusi tugas, atau error tingkat baris tidak dikenai biaya.
- Untuk tugas yang dibatalkan, permintaan yang berhasil diselesaikan sebelum pembatalan tetap dikenai biaya seperti biasa.
Catatan
- Inferensi batch adalah item penagihan terpisah. Mendukung rencana penghematan AI universal, tetapi tidak mendukung diskon seperti langganan (rencana penghematan lainnya) atau kuota gratis untuk pengguna baru. Juga tidak mendukung fitur seperti cache konteks.
- Beberapa model, seperti qwen3.5-plus dan qwen3.5-flash, memiliki mode thinking yang diaktifkan secara default. Mode ini menghasilkan token thinking tambahan, yang dikenai biaya sesuai harga token output dan meningkatkan biaya. Untuk mengontrol biaya, atur parameter
enable_thinkingberdasarkan kompleksitas tugas. Untuk informasi lebih lanjut, lihat Deep thinking.
Kode error
Jika permintaan gagal dan mengembalikan pesan error, lihat Kode error untuk solusinya.
FAQ
-
Bagaimana cara memilih antara Batch Chat dan Batch File?
Gunakan Batch File ketika Anda perlu memproses file besar yang berisi banyak permintaan secara asinkron. Gunakan Batch Chat ketika logika bisnis Anda memerlukan pengiriman banyak permintaan obrolan independen secara sinkron dengan konkurensi tinggi.
-
Bagaimana penagihan API Batch File? Apakah saya perlu membeli paket terpisah?
Batch menggunakan penagihan bayar sesuai penggunaan berdasarkan token yang dikonsumsi oleh permintaan yang berhasil. Tidak diperlukan paket sumber daya terpisah.
-
Apakah file batch yang dikirim dieksekusi secara berurutan?
Tidak. Sistem menggunakan penjadwalan dinamis berdasarkan beban komputasi dan tidak menjamin urutan eksekusi. Tugas mungkin tertunda ketika sumber daya terbatas.
-
Berapa lama waktu yang dibutuhkan untuk menyelesaikan file batch yang dikirim?
Waktu eksekusi tergantung pada sumber daya sistem dan skala tugas. Jika tugas tidak selesai dalam completion_window, tugas tersebut kedaluwarsa. Permintaan yang tidak diproses dalam tugas yang kedaluwarsa tidak dieksekusi dan tidak dikenai biaya.
Rekomendasi skenario: Gunakan panggilan real-time untuk skenario yang memerlukan inferensi model real-time ketat. Gunakan panggilan batch untuk skenario pemrosesan data skala besar yang dapat mentolerir penundaan.