All Products
Search
Document Center

Alibaba Cloud Model Studio:OpenAI-compatible - Batch (masukan file)

Last Updated:Jun 27, 2026

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 yang tidak sensitif terhadap latensi.

Untuk menggunakan konsol, lihat panduan konsol.

Alur kerja

Prasyarat

Anda dapat memanggil Batch File API melalui OpenAI SDK (Python, Node.js) atau HTTP API.

Penting

Model Studio telah merilis domain khusus ruang kerja untuk wilayah Singapura. Domain khusus baru ini memberikan performa lebih unggul dan stabilitas lebih tinggi untuk permintaan inferensi. Kami merekomendasikan migrasi ke domain baru:

  • Singapura: dari https://dashscope-intl.aliyuncs.com ke https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com

{WorkspaceId} adalah ID ruang kerja Anda, yang dapat ditemukan di halaman Detail Ruang Kerja pada konsol Model Studio. Domain lama tetap berfungsi penuh.

Cakupan

Singapura

Model yang didukung: qwen-max, qwen-plus, qwen-flash, qwen-turbo.

China (Beijing)

Model yang didukung:

  • Model generasi teks: Versi stabil dan beberapa versi latest Qwen-Max, Qwen-Plus, Qwen-Flash, dan Qwen-Long. Seri QwQ (qwq-plus) serta beberapa model pihak ketiga (deepseek-r1, deepseek-v3.2, deepseek-v3) juga didukung.

  • Model multimodal: Versi stabil dan beberapa versi latest Qwen-VL-Max, Qwen-VL-Plus, dan Qwen-VL-Flash. Model Qwen-OCR juga didukung.

  • Model penyematan teks: text-embedding-v4.

Daftar nama model yang didukung

Penting
  • Dalam skenario pemrosesan batch, jumlah maksimum token konteks per permintaan adalah 256 K untuk qwen3.7-max, qwen3.7-plus, qwen3.6-plus, qwen3.5-plus, dan qwen3.5-flash.

  • Beberapa model mendukung mode thinking. Mengaktifkan mode ini menghasilkan token thinking dan meningkatkan biaya.

  • Model seri qwen3.7, qwen3.6, dan qwen3.5 memiliki mode thinking aktif secara default. Jika Anda menggunakan model hybrid thinking, Anda harus secara eksplisit mengatur parameter enable_thinking. Atur parameter ini ke true untuk mengaktifkan mode atau false untuk menonaktifkannya.

  • Dalam badan permintaan JSONL, enable_thinking adalah parameter tingkat atas dari body dan harus ditempatkan pada level yang sama dengan model. Jangan letakkan di dalam extra_body.

Mulai

Sebelum memproses tugas formal, uji dengan batch-test-model. Model uji ini melewati inferensi dan mengembalikan respons sukses tetap, memungkinkan Anda memverifikasi rantai panggilan API dan format data Anda.

Catatan

Batasan batch-test-model:

  • File uji Anda harus memenuhi Persyaratan file masukan. 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 masukan

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 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 untuk bahasa pemrograman Anda. Simpan di direktori yang sama dengan file masukan Anda dan jalankan. Kode ini menangani seluruh alur kerja: unggah, buat tugas, periksa status, dan unduh hasil.

Untuk menyesuaikan jalur file atau parameter lainnya, ubah kode sesuai kebutuhan.
Catatan

Gunakan kembali ID file yang ada: ID yang dikembalikan setelah mengunggah file (misalnya, file-batch-xxx) dapat digunakan kembali. Jika konten masukan 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 diunggah.

Kode contoh

OpenAI Python SDK

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 pernah 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://{WorkspaceId}.ap-southeast-1.maas.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 masukan.
    # Untuk model uji (batch-test-model), gunakan /v1/chat/ds-test.
    # Untuk model penyematan teks, 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 keluaran untuk permintaan yang berhasil dalam tugas batch...")
    batch = client.batches.retrieve(batch_id=batch_id)
    print(f"ID file keluaran: {batch.output_file_id}\n")
    return batch.output_file_id

def get_error_id(batch_id):
    print(f"Mendapatkan ID file keluaran untuk permintaan yang gagal dalam tugas batch...")
    batch = client.batches.retrieve(batch_id=batch_id)
    print(f"ID file kesalahan: {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 keluaran lengkap telah disimpan ke file 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 kesalahan secara lokal
    content.write_to_file(error_file_path)
    print(f"Informasi kegagalan permintaan lengkap telah disimpan ke file kesalahan lokal error.jsonl\n")

def main():
    # Jalur file
    input_file_path = "test_model.jsonl"  # Anda dapat mengganti ini dengan jalur file masukan Anda
    output_file_path = "result.jsonl"  # Anda dapat mengganti ini dengan jalur file keluaran Anda
    error_file_path = "error.jsonl"  # Anda dapat mengganti ini dengan jalur file kesalahan Anda
    try:
        # Langkah 1: Unggah file JSONL yang berisi informasi permintaan untuk mendapatkan ID file masukan
        input_file_id = upload_file(input_file_path)
        # Langkah 2: Buat tugas batch berdasarkan ID file masukan
        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 kesalahan dan keluar
        if status == "failed":
            batch = client.batches.retrieve(batch_id)
            print(f"Tugas batch gagal. Pesan kesalahan: {batch.errors}\n")
            print(f"Untuk informasi lebih lanjut, lihat Kode kesalahan: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code
            return
        # Langkah 4: Unduh hasil: Jika ID file keluaran tidak kosong, cetak 1.000 karakter pertama dari hasil permintaan yang berhasil dan unduh hasil lengkap ke file keluaran lokal.
        # Jika ID file kesalahan tidak kosong, cetak 1.000 karakter pertama dari informasi kegagalan permintaan dan unduh informasi lengkap ke file kesalahan 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 kesalahan: 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 kesalahan: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code

if __name__ == "__main__":
    main()

OpenAI Node.js SDK

/**
 * 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');

// URL dasar untuk wilayah Singapura
const BASE_URL = 'https://{WorkspaceId}.ap-southeast-1.maas.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('Kesalahan: 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 keluaran: ${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 kesalahan (jika ada)
            const errorFileId = latestBatch.error_file_id;
            if (errorFileId) {
                console.log(`  ID file kesalahan: ${errorFileId}`);
                const errorContent = await client.files.content(errorFileId);
                const errorText = await errorContent.text();
                console.log('\n--- Informasi kesalahan ---');
                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 kesalahan:', latestBatch.errors);
            }
            console.error('\nLihat dokumentasi kode kesalahan: 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();

Java (HTTP)

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://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
 */
public class BatchAPITest {

    // URL dasar untuk wilayah Singapura
    private static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.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("Kesalahan: 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 keluaran: " + 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 kesalahan: " + errorFileId);
                        String errorContent = getFileContent(errorFileId);
                        System.out.println("\n--- Informasi kesalahan ---");
                        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 kesalahan: 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);
    }
}

curl (HTTP)

#!/bin/bash
# Tes API Batch Model Studio - Menggunakan curl
#
# Prasyarat:
# 1. Pastikan variabel lingkungan DASHSCOPE_API_KEY telah 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://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1

API_KEY="${DASHSCOPE_API_KEY}"
BASE_URL="https://{WorkspaceId}.ap-southeast-1.maas.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 "Kesalahan: Harap atur variabel lingkungan DASHSCOPE_API_KEY"
    exit 1
fi

echo "=== Mulai Tes 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: Lakukan polling 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 kesalahan: ${ERROR_FILE_ID}"

        ERROR_CONTENT=$(curl -s -X GET "${BASE_URL}/files/${ERROR_FILE_ID}/content" \
          -H "Authorization: Bearer ${API_KEY}")

        echo ""
        echo "--- Informasi kesalahan ---"
        echo "${ERROR_CONTENT}"
    fi

    echo ""
    echo "=== Tes berhasil diselesaikan ==="
elif [[ "$STATUS" == "failed" ]]; then
    echo ""
    echo "✗ Tugas batch gagal"
    echo "Info tugas: ${BATCH_INFO}"
    echo ""
    echo "Lihat dokumentasi kode kesalahan: 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 masukan

  • 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.

Skenario 1: Obrolan teks

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 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 Base64 (menggunakan gambar sebagai contoh)

  1. Konversi file lokal ke encoding Base64:

    # Fungsi encoding: Konversi file lokal ke string 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 mutlak ke gambar lokal Anda
    base64_image = encode_image("xxx/eagle.png")
  2. Buat format Data URL: data:[MIME_type];base64,{base64_image};

    1. Ganti MIME_type dengan jenis media aktual. Harus sesuai dengan nilai MIME Type (misalnya, image/jpeg, image/png);

    2. base64_image adalah string Base64 yang dihasilkan pada langkah sebelumnya.

Catatan

Untuk detail lengkap (termasuk batas file, jenis MIME, dan metode encoding), lihat Kirim file lokal (encoding Base64 atau jalur file).

1. Ubah file masukan

  • Dalam file test_model.jsonl, atur parameter model ke model target dan atur field url:

    Jenis model

    url

    Model generasi teks/model multimodal

    /v1/chat/completions

    Model penyematan teks

    /v1/embeddings

  • Atau gunakan "alat pembuat batch JSONL" di atas untuk menghasilkan file baru untuk tugas formal. Pastikan field model dan url benar.

2. Ubah kode Getting Started

  1. Ubah jalur file masukan ke nama file Anda.

  2. Atur parameter endpoint agar sesuai dengan field url dalam file masukan Anda.

3. Jalankan kode dan tunggu hasil

Saat tugas selesai, hasil permintaan yang berhasil disimpan ke file lokal result.jsonl. Jika ada permintaan yang gagal, detail kesalahan disimpan ke file error.jsonl.

  • Hasil yang berhasil (output_file_id): Setiap baris sesuai dengan satu permintaan yang berhasil dan mencakup custom_id dan response.

    {"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 kesalahan. Lihat Kode kesalahan 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 unggah file untuk mendapatkan file_id.

Saat mengunggah file, parameter purpose harus diatur ke batch.
Catatan

Gunakan kembali ID file yang ada: ID yang dikembalikan setelah mengunggah file (misalnya, file-batch-xxx) dapat digunakan kembali. Jika konten masukan 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 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 yang sesuai.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.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://{WorkspaceId}.ap-southeast-1.maas.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 yang sesuai.

const apiKey = process.env.DASHSCOPE_API_KEY;
if (!apiKey) {
    console.error('Kesalahan: 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://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
 * Catatan: Saat mengganti wilayah, perbarui juga kunci API yang sesuai.
 */
public class BatchAPIUploadFile {
    
    // Konfigurasi wilayah Singapura
    private static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.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("Kesalahan: 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://{WorkspaceId}.ap-southeast-1.maas.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 unggah 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 yang sesuai.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.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 penyematan teks, 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://{WorkspaceId}.ap-southeast-1.maas.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 yang sesuai.

const apiKey = process.env.DASHSCOPE_API_KEY;
if (!apiKey) {
    console.error('Kesalahan: 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://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
 * Catatan: Saat mengganti wilayah, perbarui juga kunci API yang sesuai.
 */
public class BatchAPICreateBatch {
    
    // Konfigurasi wilayah Singapura (default)
    private static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.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("Kesalahan: 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://{WorkspaceId}.ap-southeast-1.maas.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 masukan

Field

Tipe

Metode

Wajib

Deskripsi

input_file_id

String

Body

Ya

ID file masukan.

Gunakan ID file yang dikembalikan oleh API Siapkan dan unggah file, seperti file-batch-xxx.

endpoint

String

Body

Ya

Jalur akses API. Harus sesuai dengan field url dalam file masukan.

  • Untuk model uji batch-test-model, masukkan /v1/chat/ds-test

  • Untuk model lainnya, masukkan /v1/chat/completions

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: "ds_name": "Tugas batch"

Panjang maksimum: 100 karakter.

Jika ditentukan beberapa kali, nilai terakhir yang berlaku.

metadata.ds_description

String

Body

Tidak

Deskripsi tugas.

Contoh: "ds_description": "Uji tugas inferensi batch"

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

Tipe

Deskripsi

id

String

ID tugas batch.

object

String

Nilai tetap: batch.

endpoint

String

Jalur akses API.

errors

Map

Informasi kesalahan.

input_file_id

String

ID file masukan .

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 berjalan.

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 yang sesuai.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.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://{WorkspaceId}.ap-southeast-1.maas.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 yang sesuai.

const apiKey = process.env.DASHSCOPE_API_KEY;
if (!apiKey) {
    console.error('Kesalahan: 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://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
 * Catatan: Saat mengganti wilayah, perbarui juga kunci API yang sesuai.
 */
public class BatchAPIRetrieveBatch {
    
    // Konfigurasi wilayah Singapura
    private static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.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("Kesalahan: 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://{WorkspaceId}.ap-southeast-1.maas.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:

  • validating

  • in_progress

  • finalizing

  • completed

  • failed

  • expired

  • cancelling

  • cancelled

output_file_id

String

ID file keluaran yang berisi hasil yang berhasil. Dihasilkan setelah tugas selesai.

error_file_id

String

ID file kesalahan 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.

Kueri 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 yang sesuai.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.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://{WorkspaceId}.ap-southeast-1.maas.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 yang sesuai.

const apiKey = process.env.DASHSCOPE_API_KEY;
if (!apiKey) {
    console.error('Kesalahan: 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://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
 * Catatan: Saat mengganti wilayah, perbarui juga kunci API yang sesuai.
 */
public class BatchAPIListBatches {
    
    // Konfigurasi wilayah Singapura
    private static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.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("Kesalahan: 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://{WorkspaceId}.ap-southeast-1.maas.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_id dalam after=batch_id dengan nilai aktual. Atur limit ke jumlah tugas yang dikembalikan. Tentukan nama tugas parsial untuk ds_name. Untuk input_file_ids, tentukan satu atau beberapa ID file. Tentukan satu atau beberapa status tugas batch untuk status. Untuk create_after dan create_before, tentukan batas waktu.

Parameter masukan

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 dipisahkan koma (maksimal 20).

status

String

Kueri

Tidak

Filter berdasarkan status tugas. Tentukan beberapa status dipisahkan koma.

create_after

String

Kueri

Tidak

Filter tugas yang dibuat setelah waktu ini. Format: yyyyMMddHHmmss.

create_before

String

Kueri

Tidak

Filter tugas yang dibuat sebelum waktu ini. Format: yyyyMMddHHmmss.

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 berjalan atau dalam antrian. Setelah panggilan berhasil, status tugas berubah menjadi cancelling lalu 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 yang sesuai.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.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://{WorkspaceId}.ap-southeast-1.maas.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 yang sesuai.

const apiKey = process.env.DASHSCOPE_API_KEY;
if (!apiKey) {
    console.error('Kesalahan: 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://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
 * Catatan: Saat mengganti wilayah, perbarui juga kunci API yang sesuai.
 */
public class BatchAPICancelBatch {
    
    // Konfigurasi wilayah Singapura
    private static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.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("Kesalahan: 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://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/batches/batch_id/cancel' \
 -H "Authorization: Bearer $DASHSCOPE_API_KEY"
Ganti batch_id dengan nilai aktual.

Contoh respons

Setelah Anda berhasil membatalkan tugas, API mengembalikan informasi detail tugas batch. Berikut adalah contoh respons untuk tugas dalam 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 cancelling sementara sistem menunggu permintaan yang sedang dieksekusi selesai. Status akhirnya berubah menjadi cancelled. Hasil dari permintaan yang berhasil disimpan dalam file keluaran.

4. Unduh file hasil Batch

Setelah tugas selesai, file hasil (output_file_id) dan file kesalahan (error_file_id) mungkin dihasilkan. Unduh kedua jenis file menggunakan API unduh 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 yang sesuai.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.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://{WorkspaceId}.ap-southeast-1.maas.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 yang sesuai.

const apiKey = process.env.DASHSCOPE_API_KEY;
if (!apiKey) {
    console.error('Kesalahan: 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://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
 * Catatan: Saat mengganti wilayah, perbarui juga kunci API yang sesuai.
 */
public class BatchAPIDownloadFile {
    
    // Konfigurasi wilayah Singapura
    private static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.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("Kesalahan: 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://{WorkspaceId}.ap-southeast-1.maas.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 keberhasilan.

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 masukan (prompt) yang dikirim ke model.

total_tokens

Integer

Total jumlah token yang digunakan oleh permintaan ini.

model

String

Nama model yang digunakan untuk permintaan ini.

error

Object

Objek kesalahan. Mengembalikan null saat berhasil. Saat gagal, berisi kode kesalahan dan pesan detail.

error.code

String

Informasi baris dan alasan kesalahan. Lihat Kode kesalahan untuk troubleshooting.

error.message

String

Pesan kesalahan.

Fitur lanjutan

Atur notifikasi penyelesaian

Untuk tugas berjalan lama, gunakan notifikasi asinkron daripada polling untuk mengurangi konsumsi sumber daya.

Catatan

Notifikasi penyelesaian hanya didukung di wilayah Beijing.

  • Callback: Tentukan URL yang dapat diakses publik saat membuat tugas.

  • Antrian pesan EventBridge: Terintegrasi mendalam 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://{WorkspaceId}.ap-southeast-1.maas.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 penyematan teks, 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 yang ditentukan.

  • Sumber event (Source): acs.dashscope

  • Jenis event (Type): dashscope:System:BatchTaskFinish

Referensi: Arahkan event ke Message Queue for RocketMQ.

Produksi

  • Manajemen file

    • Secara berkala, hapus file yang tidak diperlukan menggunakan OpenAI File delete API untuk menghindari tercapainya batas penyimpanan (10.000 file atau 100 GB).

    • Simpan file berukuran besar di OSS alih-alih mengunggahnya secara langsung.

  • Pemantauan tugas

    • Gunakan notifikasi asinkron Callback atau EventBridge.

    • Jika polling diperlukan, atur interval lebih dari 1 menit dan gunakan strategi exponential backoff.

  • Penanganan kesalahan

    • Implementasikan penanganan untuk kesalahan jaringan, kesalahan API, dan pengecualian lainnya.

    • Unduh dan analisis detail kesalahan dari error_file_id.

    • Untuk kode kesalahan umum, lihat Kode kesalahan.

  • Optimasi biaya

    • Konsolidasikan tugas kecil menjadi satu batch.

    • Atur completion_window secara 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 masukan batch JSONL.

Untuk menyesuaikan jalur file atau parameter lainnya, ubah 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 penyematan teks, 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, ubah 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 masukan dan keluaran 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 ditagih.

    • Permintaan yang gagal karena kesalahan parsing file, kegagalan eksekusi tugas, atau kesalahan tingkat baris tidak dikenai biaya.

    • Untuk tugas yang dibatalkan, permintaan yang berhasil diselesaikan sebelum pembatalan tetap ditagih secara normal.

Catatan
  • Inferensi batch adalah item penagihan terpisah. Mendukung rencana penghematan dan paket sumber daya, 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 aktif secara default. Mode ini menghasilkan token thinking tambahan, yang ditagih dengan harga token keluaran dan meningkatkan biaya. Untuk mengontrol biaya, atur parameter `enable_thinking` berdasarkan kompleksitas tugas. Untuk informasi lebih lanjut, lihat Deep thinking.

Kode kesalahan

Jika permintaan gagal dan mengembalikan pesan kesalahan, lihat Kode kesalahan untuk solusinya.

FAQ

  1. Bagaimana memilih antara Batch Chat dan Batch File?

    Gunakan Batch File saat Anda perlu memproses file besar yang berisi banyak permintaan secara asinkron. Gunakan Batch Chat saat logika bisnis Anda memerlukan pengiriman banyak permintaan obrolan independen secara sinkron dengan konkurensi tinggi.

  2. 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.

  3. Apakah file batch yang dikirim dieksekusi secara berurutan?

    Tidak. Sistem menggunakan penjadwalan dinamis berdasarkan beban komputasi dan tidak menjamin urutan eksekusi. Tugas mungkin tertunda saat sumber daya terbatas.

  4. 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.