Todos os produtos
Search
Central de documentação

Alibaba Cloud Model Studio:Compatível com OpenAI - Batch (entrada de arquivo)

Última atualização: Jul 09, 2026

O Alibaba Cloud Model Studio oferece uma API de Arquivo em Lote compatível com a OpenAI. Envie solicitações em massa por meio de arquivos. O sistema as processa de forma assíncrona e retorna os resultados quando todas as solicitações são concluídas ou quando o tempo máximo de espera é atingido. Os custos correspondem a apenas 50% das chamadas em tempo real. Essa abordagem é ideal para análise de dados, avaliação de modelos e outras cargas de trabalho em grande escala nas quais a latência não é crítica.

Para usar o console, consulte o guia do console.

Fluxo de trabalho

image

Pré-requisitos

É possível chamar a API de Arquivo em Lote por meio do SDK da OpenAI (Python, Node.js) ou da API HTTP.

Importante

O Model Studio lançou domínios específicos de workspace para as regiões de Singapura. Os novos domínios dedicados oferecem desempenho superior e maior estabilidade para solicitações de inferência. Recomendamos a migração para os novos domínios:

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

{WorkspaceId} corresponde ao ID do seu workspace, que pode ser encontrado na página Workspace Details no console do Model Studio. O domínio existente permanece totalmente funcional.

Escopo

China (Beijing)

Modelos suportados:

Importante
  • No cenário de processamento em lote, o número máximo de tokens de contexto por solicitação é de 256 K para qwen3.7-max, qwen3.7-plus, qwen3.6-plus, qwen3.5-plus, qwen3.5-flash e qwen3.5-omni-plus. O modelo qwen3.5-omni-plus não suporta saída de voz.

  • Alguns modelos suportam o modo de raciocínio. Ativar esse modo gera tokens de raciocínio e aumenta os custos.

  • As séries de modelos qwen3.7, qwen3.6 e qwen3.5 têm o modo de raciocínio ativado por padrão. Ao utilizar um modelo de raciocínio híbrido, defina explicitamente o parâmetro enable_thinking. Defina este parâmetro como true para ativar o modo ou false para desativá-lo.

  • No corpo da solicitação JSONL, enable_thinking é um parâmetro de nível superior de body e deve estar no mesmo nível de model. Não o coloque dentro de extra_body.

Singapore

Modelos suportados: qwen-max, qwen-plus, qwen-turbo.

Singapore

Modelos suportados: qwen-max, qwen-plus, qwen-flash, qwen-turbo.

China (Beijing)

Modelos suportados:

Importante
  • No cenário de processamento em lote, o número máximo de tokens de contexto por solicitação é de 256 K para qwen3.7-max, qwen3.7-plus, qwen3.6-plus, qwen3.5-plus, qwen3.5-flash e qwen3.5-omni-plus. O modelo qwen3.5-omni-plus não suporta saída de voz.

  • Alguns modelos suportam o modo de raciocínio. Ativar esse modo gera tokens de raciocínio e aumenta os custos.

  • As séries de modelos qwen3.7, qwen3.6 e qwen3.5 têm o modo de raciocínio ativado por padrão. Ao utilizar um modelo de raciocínio híbrido, defina explicitamente o parâmetro enable_thinking. Defina este parâmetro como true para ativar o modo ou false para desativá-lo.

  • No corpo da solicitação JSONL, enable_thinking é um parâmetro de nível superior de body e deve estar no mesmo nível de model. Não o coloque dentro de extra_body.

Primeiros passos

Antes de processar tarefas formais, faça testes com o batch-test-model. Esse modelo de teste ignora a inferência e retorna uma resposta de sucesso fixa, permitindo que você verifique sua cadeia de chamadas de API e o formato dos dados.

Nota

Limitações do batch-test-model:

  • Seu arquivo de teste deve atender aos Requisitos do arquivo de entrada. Tamanho máximo: 1 MB. Máximo de linhas: 100.

  • Limite de simultaneidade: Até 2 tarefas paralelas.

  • Custo: O modelo de teste não gera taxas de inferência de modelo.

Etapa 1: Preparar o arquivo de entrada

Prepare um arquivo chamado test_model.jsonl com o seguinte conteúdo:

{"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?"}]}}

Modelos multimodais (por exemplo, qwen-vl-plus) suportam URLs de arquivos e entradas codificadas em 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."}]}]}}

Etapa 2: Executar o código

Selecione o trecho de código correspondente à sua linguagem de programação. Salve-o no mesmo diretório do seu arquivo de entrada e execute-o. O código gerencia todo o fluxo de trabalho: upload, criação da tarefa, consulta de status e download dos resultados.

Para personalizar o caminho do arquivo ou outros parâmetros, modifique o código conforme necessário.
Nota

Reutilizar um ID de arquivo existente: O ID retornado após o upload de um arquivo (por exemplo, file-batch-xxx) pode ser reutilizado. Se o conteúdo de entrada permanecer o mesmo, pule o novo upload e crie diretamente uma tarefa com o ID existente:

batch = client.batches.create(
    input_file_id="file-batch-xxx",  # Reuse existing file ID, no need to re-upload
    endpoint="/v1/chat/completions",
    completion_window="24h"
)

É possível recuperar IDs de arquivos históricos por meio da API client.files.list(purpose="batch") para consultar os IDs de arquivos Batch enviados anteriormente.

Código de exemplo

OpenAI Python SDK

import os
from pathlib import Path
from openai import OpenAI
import time

# Initialize the client
client = OpenAI(
    # If no environment variable is set, replace the line below with api_key="sk-xxx". But never hard-code in production to reduce leak risk.
    # API keys differ between Singapore and Beijing regions.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore region's base_url. For Beijing, use: https://dashscope.aliyuncs.com/compatible-mode/v1
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"  # The base_url for the Model Studio service
)

def upload_file(file_path):
    print(f"Uploading the JSONL file that contains request information...")
    file_object = client.files.create(file=Path(file_path), purpose="batch")
    print(f"File uploaded successfully. File ID: {file_object.id}\n")
    return file_object.id

def create_batch_job(input_file_id):
    print(f"Creating a batch task based on the file ID...")
    # Note: The value of the endpoint parameter here must match the url field in the input file.
    # For the test model (batch-test-model), use /v1/chat/ds-test.
    # For text embedding models, use /v1/embeddings.
    # For other models, use /v1/chat/completions.
    batch = client.batches.create(input_file_id=input_file_id, endpoint="/v1/chat/ds-test", completion_window="24h")
    print(f"Batch task created. Batch task ID: {batch.id}\n")
    return batch.id

def check_job_status(batch_id):
    print(f"Checking the batch task status...")
    batch = client.batches.retrieve(batch_id=batch_id)
    print(f"Batch task status: {batch.status}\n")
    return batch.status

def get_output_id(batch_id):
    print(f"Getting the output file ID for successful requests in the batch task...")
    batch = client.batches.retrieve(batch_id=batch_id)
    print(f"Output file ID: {batch.output_file_id}\n")
    return batch.output_file_id

def get_error_id(batch_id):
    print(f"Getting the output file ID for failed requests in the batch task...")
    batch = client.batches.retrieve(batch_id=batch_id)
    print(f"Error file ID: {batch.error_file_id}\n")
    return batch.error_file_id

def download_results(output_file_id, output_file_path):
    print(f"Printing and downloading the results of successful requests from the batch task...")
    content = client.files.content(output_file_id)
    # Print some content for testing
    print(f"Printing the first 1,000 characters of the successful request results: {content.text[:1000]}...\n")
    # Save the result file locally
    content.write_to_file(output_file_path)
    print(f"The complete output results have been saved to the local output file result.jsonl\n")

def download_errors(error_file_id, error_file_path):
    print(f"Printing and downloading the failure information for requests from the batch task...")
    content = client.files.content(error_file_id)
    # Print some content for testing
    print(f"Printing the first 1,000 characters of the request failure information: {content.text[:1000]}...\n")
    # Save the error information file locally
    content.write_to_file(error_file_path)
    print(f"The complete request failure information has been saved to the local error file error.jsonl\n")

def main():
    # File paths
    input_file_path = "test_model.jsonl"  # You can replace this with your input file path
    output_file_path = "result.jsonl"  # You can replace this with your output file path
    error_file_path = "error.jsonl"  # You can replace this with your error file path
    try:
        # Step 1: Upload the JSONL file containing request information to get the input file ID
        input_file_id = upload_file(input_file_path)
        # Step 2: Create a batch task based on the input file ID
        batch_id = create_batch_job(input_file_id)
        # Step 3: Check the batch task status until it is finished
        status = ""
        while status not in ["completed", "failed", "expired", "cancelled"]:
            status = check_job_status(batch_id)
            print(f"Waiting for the task to complete...")
            time.sleep(10)  # Wait 10 seconds and then query the status again
        # If the task fails, print the error message and exit
        if status == "failed":
            batch = client.batches.retrieve(batch_id)
            print(f"Batch task failed. Error message: {batch.errors}\n")
            print(f"For more information, see Error codes: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code
            return
        # Step 4: Download results: If the output file ID is not empty, print the first 1,000 characters of the successful request results and download the complete results to a local output file.
        # If the error file ID is not empty, print the first 1,000 characters of the request failure information and download the complete information to a local error file.
        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"For more information, see Error codes: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code
    except Exception as e:
        print(f"An error occurred: {e}")
        print(f"For more information, see Error codes: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code

if __name__ == "__main__":
    main()

OpenAI Node.js SDK

/**
 * Model Studio Batch API Test - Using OpenAI Node.js SDK
 *
 * Install dependencies: npm install openai
 * Run: node test-nodejs.js
 */

const OpenAI = require('openai');
const fs = require('fs');

// Base URL for the Singapore region
const BASE_URL = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1';
// For Beijing, use: const BASE_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';

const apiKey = process.env.DASHSCOPE_API_KEY;
if (!apiKey) {
    console.error('Error: Please set the environment variable DASHSCOPE_API_KEY');
    process.exit(1);
}

// Initialize the client
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('=== Start Batch API Test ===\n');

        // Step 1: Upload file
        console.log('Step 1: Uploading the JSONL file that contains request information...');
        const fileStream = fs.createReadStream('test_model.jsonl');
        const fileObject = await client.files.create({
            file: fileStream,
            purpose: 'batch'
        });
        const fileId = fileObject.id;
        console.log(`✓ File uploaded successfully, File ID: ${fileId}\n`);

        // Step 2: Create batch task
        console.log('Step 2: Creating batch task...');
        const batch = await client.batches.create({
            input_file_id: fileId,
            endpoint: '/v1/chat/ds-test',  // Use /v1/chat/ds-test for the test model
            completion_window: '24h'
        });
        const batchId = batch.id;
        console.log(`✓ Batch task created successfully, Task ID: ${batchId}\n`);

        // Step 3: Poll task status
        console.log('Step 3: Waiting for task to complete...');
        let status = batch.status;
        let pollCount = 0;
        let latestBatch = batch;

        while (!['completed', 'failed', 'expired', 'cancelled'].includes(status)) {
            await sleep(10000); // Wait 10 seconds
            latestBatch = await client.batches.retrieve(batchId);
            status = latestBatch.status;
            pollCount++;
            console.log(`  [${pollCount}] Task status: ${status}`);
        }

        console.log(`\n✓ Task completed, final status: ${status}\n`);

        // Step 4: Process results
        if (status === 'completed') {
            console.log('Step 4: Downloading result file...');

            // Download successful results
            const outputFileId = latestBatch.output_file_id;
            if (outputFileId) {
                console.log(`  Output file ID: ${outputFileId}`);
                const content = await client.files.content(outputFileId);
                const text = await content.text();
                console.log('\n--- Successful results (first 500 characters) ---');
                console.log(text.substring(0, Math.min(500, text.length)));
                console.log('...\n');
            }

            // Download error file (if any)
            const errorFileId = latestBatch.error_file_id;
            if (errorFileId) {
                console.log(`  Error file ID: ${errorFileId}`);
                const errorContent = await client.files.content(errorFileId);
                const errorText = await errorContent.text();
                console.log('\n--- Error information ---');
                console.log(errorText);
            }

            console.log('\n=== Test completed successfully ===');
        } else if (status === 'failed') {
            console.error('\n✗ Batch task failed');
            if (latestBatch.errors) {
                console.error('Error message:', latestBatch.errors);
            }
            console.error('\nSee error code documentation: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code
        } else {
            console.log(`\nTask status: ${status}`);
        }

    } catch (error) {
        console.error('An error occurred:', 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;

/**
 * Model Studio Batch API Test - Using HTTP API
 *
 * Prerequisites:
 * 1. Ensure the environment variable DASHSCOPE_API_KEY is set
 * 2. Prepare the test file test_model.jsonl (in the project root directory)
 *
 * Region configuration:
 * - Beijing region: https://dashscope.aliyuncs.com/compatible-mode/v1
 * - Singapore region: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
 */
public class BatchAPITest {

    // Base URL for the Singapore region
    private static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1";
    // For Beijing, use: 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 {
        // Get API Key from environment variable
        API_KEY = System.getenv("DASHSCOPE_API_KEY");
        if (API_KEY == null || API_KEY.isEmpty()) {
            System.err.println("Error: Please set the environment variable DASHSCOPE_API_KEY");
            System.exit(1);
        }

        System.out.println("=== Start Batch API Test ===\n");

        try {
            // Step 1: Upload file
            System.out.println("Step 1: Uploading the JSONL file that contains request information...");
            String fileId = uploadFile("test_model.jsonl");
            System.out.println("✓ File uploaded successfully, File ID: " + fileId + "\n");

            // Step 2: Create batch task
            System.out.println("Step 2: Creating batch task...");
            String batchId = createBatch(fileId);
            System.out.println("✓ Batch task created successfully, Task ID: " + batchId + "\n");

            // Step 3: Poll task status
            System.out.println("Step 3: Waiting for task to complete...");
            String status = "";
            int pollCount = 0;

            while (!isTerminalStatus(status)) {
                Thread.sleep(10000); // Wait 10 seconds
                String batchInfo = getBatch(batchId);
                status = parseStatus(batchInfo);
                pollCount++;
                System.out.println("  [" + pollCount + "] Task status: " + status);

                // Step 4: If completed, download results
                if ("completed".equals(status)) {
                    System.out.println("\n✓ Task completed!\n");
                    System.out.println("Step 4: Downloading result file...");

                    String outputFileId = parseOutputFileId(batchInfo);
                    if (outputFileId != null && !outputFileId.isEmpty()) {
                        System.out.println("  Output file ID: " + outputFileId);
                        String content = getFileContent(outputFileId);
                        System.out.println("\n--- Successful results (first 500 characters) ---");
                        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("  Error file ID: " + errorFileId);
                        String errorContent = getFileContent(errorFileId);
                        System.out.println("\n--- Error information ---");
                        System.out.println(errorContent);
                    }

                    System.out.println("\n=== Test completed successfully ===");
                    break;
                } else if ("failed".equals(status)) {
                    System.err.println("\n✗ Batch task failed");
                    System.err.println("Task info: " + batchInfo);
                    System.err.println("\nSee error code documentation: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code
                    break;
                } else if ("expired".equals(status) || "cancelled".equals(status)) {
                    System.out.println("\nTask status: " + status);
                    break;
                }
            }

        } catch (Exception e) {
            System.err.println("An error occurred: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * Upload 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())) {
            // Add purpose field
            out.writeBytes("--" + boundary + "\r\n");
            out.writeBytes("Content-Disposition: form-data; name=\"purpose\"\r\n\r\n");
            out.writeBytes("batch\r\n");

            // Add 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*\"([^\"]+)\"");
    }

    /**
     * Create batch task
     */
    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*\"([^\"]+)\"");
    }

    /**
     * Get batch task info
     */
    private static String getBatch(String batchId) throws Exception {
        return sendRequest("GET", "/batches/" + batchId, null);
    }

    /**
     * Get file content
     */
    private static String getFileContent(String fileId) throws Exception {
        return sendRequest("GET", "/files/" + fileId + "/content", null);
    }

    /**
     * Send HTTP request
     */
    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);
    }

    /**
     * Read response
     */
    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() : "";
        }
    }

    /**
     * Parse JSON field (simple implementation)
     */
    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*\"([^\"]+)\"");
    }

    /**
     * Check if status is terminal
     */
    private static boolean isTerminalStatus(String status) {
        return "completed".equals(status)
            || "failed".equals(status)
            || "expired".equals(status)
            || "cancelled".equals(status);
    }
}

curl (HTTP)

#!/bin/bash
# Model Studio Batch API Test - Using curl
#
# Prerequisites:
# 1. Ensure the environment variable DASHSCOPE_API_KEY is set
# 2. Prepare the test file test_model.jsonl (in the current directory)
#
# Region configuration:
# - Beijing region: https://dashscope.aliyuncs.com/compatible-mode/v1
# - Singapore region: 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"

# For Beijing, use: BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1"

# Check API Key
if [ -z "$API_KEY" ]; then
    echo "Error: Please set the environment variable DASHSCOPE_API_KEY"
    exit 1
fi

echo "=== Start Batch API Test ==="
echo ""

# Step 1: Upload file
echo "Step 1: Uploading the JSONL file that contains request information..."
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 uploaded successfully, File ID: ${FILE_ID}"
echo ""

# Step 2: Create batch task
echo "Step 2: Creating batch task..."
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 "✓ Batch task created successfully, Task ID: ${BATCH_ID}"
echo ""

# Step 3: Poll task status
echo "Step 3: Waiting for task to complete..."
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}] Task status: ${STATUS}"
done

echo ""
echo "✓ Task completed, final status: ${STATUS}"
echo ""

# Step 4: Download results
if [[ "$STATUS" == "completed" ]]; then
    echo "Step 4: Downloading result file..."

    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 "  Output file ID: ${OUTPUT_FILE_ID}"

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

        echo ""
        echo "--- Successful results (first 500 characters) ---"
        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 "  Error file ID: ${ERROR_FILE_ID}"

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

        echo ""
        echo "--- Error information ---"
        echo "${ERROR_CONTENT}"
    fi

    echo ""
    echo "=== Test completed successfully ==="
elif [[ "$STATUS" == "failed" ]]; then
    echo ""
    echo "✗ Batch task failed"
    echo "Task info: ${BATCH_INFO}"
    echo ""
    echo "See error code documentation: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code
else
    echo ""
    echo "Task status: ${STATUS}"
fi

Etapa 3: Verificar os resultados do teste

Após a conclusão bem-sucedida da tarefa, o arquivo de resultado result.jsonl contém a resposta fixa {"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}

Executar uma tarefa formal

Requisitos do arquivo de entrada

  • Formato: JSONL codificado em UTF-8 (um objeto JSON independente por linha).

  • Limites de tamanho: Máximo de 50.000 solicitações por arquivo, com limite de 500 MB.

  • Limite por linha: Cada objeto JSON não deve exceder 6 MB e precisa caber na janela de contexto do modelo.

  • Consistência: Todas as solicitações no mesmo arquivo devem usar o mesmo modelo e o mesmo modo de raciocínio (se aplicável).

  • Identificador único: Cada solicitação deve incluir um campo custom_id exclusivo dentro do arquivo. Esse campo serve para correlacionar solicitações aos respectivos resultados.

Cenário 1: Chat de texto

Exemplo de conteúdo do arquivo:

{"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?"}]}}

Cenário 2: Compreensão de imagens e vídeos

Modelos multimodais (como qwen-vl-plus) aceitam URLs de arquivos e entradas codificadas em 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."}]}]}}
As strings Base64 nos exemplos acima estão truncadas. Gere as codificações completas usando o código Python abaixo.

Passar strings codificadas em Base64 (usando imagens como exemplo)

  1. Converta um arquivo local para codificação Base64:

    # Encoding function: Convert a local file to a Base64-encoded string
    import base64
    def encode_image(image_path):
        with open(image_path, "rb") as image_file:
            return base64.b64encode(image_file.read()).decode("utf-8")
    
    # Replace xxx/eagle.png with the absolute path to your local image
    base64_image = encode_image("xxx/eagle.png")
  2. Monte o formato Data URL: data:[MIME_type];base64,{base64_image};

    1. Substitua MIME_type pelo tipo de mídia real. Ele deve corresponder ao valor de MIME Type (por exemplo, image/jpeg, image/png);

    2. base64_image é a string Base64 gerada na etapa anterior.

Nota

Para detalhes completos (incluindo limites de arquivos, tipos MIME e métodos de codificação), consulte Passar arquivos locais (codificação Base64 ou caminhos de arquivo).

1. Modificar o arquivo de entrada

  • No arquivo test_model.jsonl, defina o parâmetro model para o modelo desejado e configure o campo url:

    Tipo de modelo

    url

    Modelos de geração de texto/multimodais

    /v1/chat/completions

    Modelos de embedding de texto

    /v1/embeddings

  • Como alternativa, utilize a "Ferramenta de geração de lotes JSONL" acima para criar um novo arquivo destinado a tarefas formais. Verifique se os campos model e url estão corretos.

2. Ajustar o código de introdução

  1. Altere o caminho do arquivo de entrada para o nome do seu arquivo.

  2. Configure o parâmetro endpoint para corresponder ao campo url no seu arquivo de entrada.

3. Executar o código e aguardar os resultados

Quando a tarefa for concluída, os resultados das solicitações bem-sucedidas serão salvos no arquivo local result.jsonl. Caso alguma solicitação falhe, os detalhes do erro serão gravados no arquivo error.jsonl.

  • Resultados bem-sucedidos (output_file_id): Cada linha corresponde a uma solicitação bem-sucedida e inclui o custom_id e a 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}
  • Detalhes de falha (error_file_id): Contém informações sobre solicitações malsucedidas, incluindo números de linha e motivos do erro. Consulte Códigos de erro para solução de problemas.

Procedimento detalhado

O fluxo de trabalho da Batch API consiste em quatro etapas: carregar um arquivo, criar uma tarefa, consultar o status da tarefa e baixar os resultados.

1. Carregar arquivo

Carregue seu arquivo JSONL usando a API de upload de arquivos para obter um file_id.

Ao carregar um arquivo, o parâmetro purpose deve ser batch .
Nota

Reutilizar um ID de arquivo existente: O ID retornado após o upload de um arquivo (por exemplo, file-batch-xxx) pode ser reutilizado. Se o conteúdo de entrada permanecer o mesmo, pule o novo upload e crie diretamente uma tarefa com o ID existente:

batch = client.batches.create(
    input_file_id="file-batch-xxx",  # Reuse existing file ID, no need to re-upload
    endpoint="/v1/chat/completions",
    completion_window="24h"
)

É possível recuperar IDs de arquivos históricos por meio da API client.files.list(purpose="batch") para consultar IDs de arquivos Batch carregados anteriormente.

OpenAI Python SDK

Exemplo de solicitação

import os
from pathlib import Path
from openai import OpenAI

client = OpenAI(
    # If no environment variable is set, use api_key="sk-xxx" (not in production - risk of leaks).
    # API keys differ between regions.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore region's base_url. For Beijing, use: https://dashscope.aliyuncs.com/compatible-mode/v1 and update the API key.
    # Note: When switching regions, also update the API key accordingly.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

# test.jsonl is a local sample file. purpose must be batch.
file_object = client.files.create(file=Path("test.jsonl"), purpose="batch")

print(file_object.model_dump_json())

OpenAI Node.js SDK

Exemplo de solicitação

/**
 * Model Studio Batch API - Upload file
 * 
 * If no environment variable is set, use apiKey: 'sk-xxx' (not in production - risk of leaks).
 * API keys differ between regions.
 * 
 * Install dependencies: npm install openai
 */
const OpenAI = require('openai');
const fs = require('fs');

// Singapore region configuration (default)
const BASE_URL = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1';
// If using the Beijing region, replace the above BASE_URL with:
// const BASE_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
// Note: When switching regions, also update the API key accordingly.

const apiKey = process.env.DASHSCOPE_API_KEY;
if (!apiKey) {
    console.error('Error: Please set the environment variable DASHSCOPE_API_KEY');
    console.error('Or set in code: 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)

Exemplo de solicitação

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;

/**
 * Model Studio Batch API - Upload file
 * 
 * If no environment variable is set, use API_KEY = "sk-xxx" (not in production - risk of leaks).
 * API keys differ between regions.
 * 
 * Region configuration:
 * - Beijing region: https://dashscope.aliyuncs.com/compatible-mode/v1
 * - Singapore region: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
 * Note: When switching regions, also update the API key accordingly.
 */
public class BatchAPIUploadFile {
    
    // Singapore region configuration
    private static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1";
    // For Beijing, use: private static final String BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"; and update the API key.
    
    private static String API_KEY;
    
    public static void main(String[] args) throws Exception {
        API_KEY = System.getenv("DASHSCOPE_API_KEY");
        if (API_KEY == null || API_KEY.isEmpty()) {
            System.err.println("Error: Please set the environment variable DASHSCOPE_API_KEY");
            System.err.println("Or set in code: API_KEY = \"sk-xxx\";");
            System.exit(1);
        }
        
String fileId = uploadFile("test.jsonl");
        System.out.println("File ID: " + fileId);
    }
    
    // === Utility methods ===
    
    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())) {
            // Add purpose field
            out.writeBytes("--" + boundary + "\r\n");
            out.writeBytes("Content-Disposition: form-data; name=\"purpose\"\r\n\r\n");
            out.writeBytes("batch\r\n");

            // Add 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)

Exemplo de solicitação

# ======= Important =======
# API keys differ between Singapore and Beijing regions.
# The following is the base_url for the Singapore region. If you use a model in the Beijing region, replace the base_url with: https://dashscope.aliyuncs.com/compatible-mode/v1/files
# === Delete this comment before execution ===
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"'

Exemplo de resposta

{
    "id": "file-batch-xxx",
    "bytes": 437,
    "created_at": 1742304153,
    "filename": "test.jsonl",
    "object": "file",
    "purpose": "batch",
    "status": "processed",
    "status_details": null
}

2. Criar uma tarefa em lote

Crie uma tarefa em lote usando o ID do arquivo obtido na etapa de upload de arquivo.

OpenAI Python SDK

Exemplo de solicitação

import os
from openai import OpenAI

client = OpenAI(
    # If no environment variable is set, use api_key="sk-xxx" (not in production - risk of leaks).
    # API keys differ between regions.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore region's base_url. For Beijing, use: https://dashscope.aliyuncs.com/compatible-mode/v1 and update the API key.
    # Note: When switching regions, also update the API key accordingly.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

batch = client.batches.create(
    input_file_id="file-batch-xxx",  # The ID returned after uploading the file
    endpoint="/v1/chat/completions",  # For the test model batch-test-model, use /v1/chat/ds-test. For text embedding models, use /v1/embeddings. For text generation/multimodal models, use /v1/chat/completions.
    completion_window="24h",
    metadata={'ds_name':"Task name",'ds_description':'Task description'} # Optional metadata field for creating task name and description
)
print(batch)

OpenAI Node.js SDK

Exemplo de solicitação

/**
 * Model Studio Batch API - Create batch task
 * 
 * If no environment variable is set, use apiKey: 'sk-xxx' (not in production - risk of leaks).
 * API keys differ between regions.
 * 
 * Install dependencies: npm install openai
 */
const OpenAI = require('openai');

// Singapore region configuration (default)
const BASE_URL = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1';
// If using the Beijing region, replace the above BASE_URL with:
// const BASE_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
// Note: When switching regions, also update the API key accordingly.

const apiKey = process.env.DASHSCOPE_API_KEY;
if (!apiKey) {
    console.error('Error: Please set the environment variable DASHSCOPE_API_KEY');
    console.error('Or set in code: 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': 'Task name', 'ds_description': 'Task description'}
});
console.log(batch.id);

Java (HTTP)

Exemplo de solicitação

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;

/**
 * Model Studio Batch API - Create batch task
 * 
 * If no environment variable is set, use API_KEY = "sk-xxx" (not in production - risk of leaks).
 * API keys differ between regions.
 * 
 * Region configuration:
 * - Beijing region: https://dashscope.aliyuncs.com/compatible-mode/v1
 * - Singapore region: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
 * Note: When switching regions, also update the API key accordingly.
 */
public class BatchAPICreateBatch {
    
    // Singapore region configuration (default)
    private static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1";
    // For Beijing, use: private static final String BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"; and update the API key.
    
    private static String API_KEY;
    
    public static void main(String[] args) throws Exception {
        API_KEY = System.getenv("DASHSCOPE_API_KEY");
        if (API_KEY == null || API_KEY.isEmpty()) {
            System.err.println("Error: Please set the environment variable DASHSCOPE_API_KEY");
            System.err.println("Or set in code: 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\":\"Task name\",\"ds_description\":\"Task description\"}}";
String response = sendRequest("POST", "/batches", jsonBody);
        String batchId = parseField(response, "\"id\":\\s*\"([^\"]+)\"");
        System.out.println("Batch task ID: " + batchId);
    }
    
    // === Utility methods ===
    
    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)

Exemplo de requisição

# ======= Important =======
# API keys differ between Singapore and Beijing regions.
# The following is the base_url for the Singapore region. If you use a model in the Beijing region, replace the base_url with: https://dashscope.aliyuncs.com/compatible-mode/v1/batches
# === Delete this comment before execution ===
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":"Task name","ds_description":"Task description"}
  }'

Parâmetros de entrada

Campo

Tipo

Método

Obrigatório

Descrição

input_file_id

String

Body

Sim

ID do arquivo de entrada.

Utilize o ID do arquivo retornado pela API Preparar e enviar arquivo, como file-batch-xxx.

endpoint

String

Body

Sim

Caminho de acesso da API. Deve corresponder ao campo url no arquivo de entrada.

  • Para o modelo de teste batch-test-model, insira /v1/chat/ds-test

  • Para os demais modelos, insira /v1/chat/completions

completion_window

String

Body

Sim

Tempo máximo de espera. Intervalo: 24h a 336h, apenas números inteiros.

Unidades: "h" ou "d" (ex.: "24h" ou "14d").

metadata

Map

Body

Não

Metadados estendidos da tarefa, especificados como pares chave-valor.

metadata.ds_name

String

Body

Não

Nome da tarefa.

Exemplo: "ds_name": "Batch task"

Comprimento máximo: 100 caracteres.

Se especificado várias vezes, o último valor prevalece.

metadata.ds_description

String

Body

Não

Descrição da tarefa.

Exemplo: "ds_description": "Batch inference task test"

Comprimento máximo: 200 caracteres.

Se especificado várias vezes, o último valor prevalece.

Exemplo de resposta

{
    "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": "Task name",
        "ds_description": "Task description"
    }
}

Parâmetros de resposta

Campo

Tipo

Descrição

id

String

ID da tarefa em lote.

object

String

Valor fixo: batch.

endpoint

String

Caminho de acesso da API.

errors

Map

Informações de erro.

input_file_id

String

ID do arquivo de entrada .

completion_window

String

Tempo máximo de espera. Intervalo: 24h a 336h, apenas números inteiros.

Unidades: "h" ou "d" (ex.: "24h" ou "14d").

status

String

Status da tarefa: validating, failed, in_progress, finalizing, completed, expired, cancelling, cancelled.

output_file_id

String

ID do arquivo com os resultados das requisições bem-sucedidas.

error_file_id

String

ID do arquivo com os resultados das requisições com falha.

created_at

Integer

Timestamp Unix (segundos) de criação da tarefa.

in_progress_at

Integer

Timestamp Unix (segundos) de início do processamento da tarefa.

expires_at

Integer

Timestamp Unix (segundos) em que a tarefa começa a expirar.

finalizing_at

Integer

Timestamp Unix (segundos) da última vez que a tarefa foi iniciada.

completed_at

Integer

Timestamp Unix (segundos) de conclusão da tarefa.

failed_at

Integer

Timestamp Unix (segundos) de falha da tarefa.

expired_at

Integer

Timestamp Unix (segundos) de expiração da tarefa.

cancelling_at

Integer

Timestamp Unix (segundos) em que a tarefa entrou no estado de cancelamento.

cancelled_at

Integer

Timestamp Unix (segundos) em que a tarefa foi cancelada.

request_counts

Map

Contagem de requisições por estado.

metadata

Map

Metadados adicionais como pares chave-valor.

metadata.ds_name

String

Nome da tarefa.

metadata.ds_description

String

Descrição da tarefa.

3. Consultar e gerenciar tarefas em lote

Após criar uma tarefa, utilize as APIs a seguir para consultar seu status, listar tarefas históricas ou cancelar uma tarefa em andamento.

Consultar status de uma tarefa específica

Consulte uma tarefa em lote pelo seu ID. Apenas tarefas criadas nos últimos 30 dias podem ser consultadas.

OpenAI Python SDK

Exemplo de requisição

import os
from openai import OpenAI

client = OpenAI(
    # If no environment variable is set, use api_key="sk-xxx" (not in production - risk of leaks).
    # API keys differ between regions.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore region's base_url. For Beijing, use: https://dashscope.aliyuncs.com/compatible-mode/v1 and update the API key.
    # Note: When switching regions, also update the API key accordingly.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
batch = client.batches.retrieve("batch_id")  # Replace batch_id with the batch task ID
print(batch)

OpenAI Node.js SDK

Exemplo de requisição

/**
 * Model Studio Batch API - Query single task
 * 
 * If no environment variable is set, use apiKey: 'sk-xxx' (not in production - risk of leaks).
 * API keys differ between regions.
 * 
 * Install dependencies: npm install openai
 */
const OpenAI = require('openai');

// Singapore region configuration (default)
const BASE_URL = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1';
// If using the Beijing region, replace the above BASE_URL with:
// const BASE_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
// Note: When switching regions, also update the API key accordingly.

const apiKey = process.env.DASHSCOPE_API_KEY;
if (!apiKey) {
    console.error('Error: Please set the environment variable DASHSCOPE_API_KEY');
    console.error('Or set in code: 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)

Exemplo de requisição

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;

/**
 * Model Studio Batch API - Query single task
 * 
 * If no environment variable is set, use API_KEY = "sk-xxx" (not in production - risk of leaks).
 * API keys differ between regions.
 * 
 * Region configuration:
 * - Beijing region: https://dashscope.aliyuncs.com/compatible-mode/v1
 * - Singapore region: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
 * Note: When switching regions, also update the API key accordingly.
 */
public class BatchAPIRetrieveBatch {
    
    // Singapore region configuration
    private static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1";
    // For Beijing, use: private static final String BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"; and update the API key.
    
    private static String API_KEY;
    
    public static void main(String[] args) throws Exception {
        API_KEY = System.getenv("DASHSCOPE_API_KEY");
        if (API_KEY == null || API_KEY.isEmpty()) {
            System.err.println("Error: Please set the environment variable DASHSCOPE_API_KEY");
            System.err.println("Or set in code: API_KEY = \"sk-xxx\";");
            System.exit(1);
        }
        
        String batchInfo = sendRequest("GET", "/batches/batch_id", null);
        String status = parseField(batchInfo, "\"status\":\\s*\"([^\"]+)\"");
        System.out.println("Task status: " + status);
    }
    
    // === Utility methods ===
    
    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)

Exemplo de requisição

# ======= Important =======
# API keys differ between Singapore and Beijing regions.
# The following is the base_url for the Singapore region. If you use a model in the Beijing region, replace the base_url with: https://dashscope.aliyuncs.com/compatible-mode/v1/batches/batch_id
# === Delete this comment before execution ===
curl --request GET 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/batches/batch_id' \
 -H "Authorization: Bearer $DASHSCOPE_API_KEY"

Exemplo de resposta

Uma consulta bem-sucedida retorna informações detalhadas sobre a tarefa em lote. A seguir, veja um exemplo de resposta para uma tarefa com status concluído:

{
  "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"
  }
}

Para descrições dos campos, consulte a tabela abaixo.

Campo

Tipo

Descrição

id

String

ID da tarefa em lote.

status

String

Status da tarefa. Valores possíveis:

  • validating

  • in_progress

  • finalizing

  • completed

  • failed

  • expired

  • cancelling

  • cancelled

output_file_id

String

ID do arquivo de saída contendo os resultados bem-sucedidos. Gerado após a conclusão da tarefa.

error_file_id

String

ID do arquivo de erros contendo detalhes das requisições com falha. Gerado após a conclusão da tarefa se houver requisições com falha.

request_counts

Object

Estatísticas de contagem de requisições, incluindo totais, concluídas e com falha.

Consultar lista de tarefas

Utilize o método batches.list() para recuperar a lista de tarefas em lote. Use paginação para obter a lista completa de tarefas.

OpenAI Python SDK

Exemplo de requisição

import os
from openai import OpenAI

client = OpenAI(
    # If no environment variable is set, use api_key="sk-xxx" (not in production - risk of leaks).
    # API keys differ between regions.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore region's base_url. For Beijing, use: https://dashscope.aliyuncs.com/compatible-mode/v1 and update the API key.
    # Note: When switching regions, also update the API key accordingly.
    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':'Task name','input_file_ids':'file-batch-xxx,file-batch-xxx','status':'completed,expired','create_after':'20250304000000','create_before':'20250306123000'})
print(batches)

OpenAI Node.js SDK

Exemplo de requisição

/**
 * Model Studio Batch API - Query task list
 * 
 * If no environment variable is set, use apiKey: 'sk-xxx' (not in production - risk of leaks).
 * API keys differ between regions.
 * 
 * Install dependencies: npm install openai
 */
const OpenAI = require('openai');

// Singapore region configuration (default)
const BASE_URL = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1';
// If using the Beijing region, replace the above BASE_URL with:
// const BASE_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
// Note: When switching regions, also update the API key accordingly.

const apiKey = process.env.DASHSCOPE_API_KEY;
if (!apiKey) {
    console.error('Error: Please set the environment variable DASHSCOPE_API_KEY');
    console.error('Or set in code: 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': 'Task name',
        '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)

Exemplo de requisição

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;

/**
 * Model Studio Batch API - Query task list
 * 
 * If no environment variable is set, use API_KEY = "sk-xxx" (not in production - risk of leaks).
 * API keys differ between regions.
 * 
 * Region configuration:
 * - Beijing region: https://dashscope.aliyuncs.com/compatible-mode/v1
 * - Singapore region: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
 * Note: When switching regions, also update the API key accordingly.
 */
public class BatchAPIListBatches {
    
    // Singapore region configuration
    private static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1";
    // For Beijing, use: private static final String BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"; and update the API key.
    
    private static String API_KEY;
    
    public static void main(String[] args) throws Exception {
        API_KEY = System.getenv("DASHSCOPE_API_KEY");
        if (API_KEY == null || API_KEY.isEmpty()) {
            System.err.println("Error: Please set the environment variable DASHSCOPE_API_KEY");
            System.err.println("Or set in code: 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);
// Parse JSON to get task list
        System.out.println(response);
    }
    
    // === Utility methods ===
    
    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)

Exemplo de requisição

# ======= Important =======
# API keys differ between Singapore and Beijing regions.
# The following is the base_url for the Singapore region. If you use a model in the Beijing region, replace the base_url with: https://dashscope.aliyuncs.com/compatible-mode/v1/batches?xxx same as below xxx
# === Delete this comment before execution ===
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"
Substitua batch_id em after=batch_id pelo valor real. Defina limit como o número de tarefas a retornar. Especifique um nome parcial da tarefa para ds_name . Para input_file_ids, especifique um ou mais IDs de arquivo. Especifique um ou mais status de tarefa em lote para status . Para create_after e create_before , especifique os limites de tempo.

Parâmetros de entrada

Campo

Tipo

Método

Obrigatório

Descrição

after

String

Query

Não

Cursor para paginação. Defina este valor como o último ID de tarefa da página anterior.

limit

Integer

Query

Não

Número de tarefas por página. Intervalo: [1, 100]. Padrão: 20.

ds_name

String

Query

Não

Correspondência aproximada pelo nome da tarefa.

input_file_ids

String

Query

Não

Filtrar por IDs de arquivo. Especifique vários IDs separados por vírgulas (até 20).

status

String

Query

Não

Filtrar por status da tarefa. Especifique vários status separados por vírgulas.

create_after

String

Query

Não

Filtrar tarefas criadas após este horário. Formato: yyyyMMddHHmmss.

create_before

String

Query

Não

Filtrar tarefas criadas antes deste horário. Formato: yyyyMMddHHmmss.

Exemplo de resposta

{
  "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
}

Parâmetros de resposta

Campo

Tipo

Descrição

object

String

Tipo do objeto. Valor fixo: list.

data

Array

Array de objetos de tarefa em lote. Consulte os parâmetros de resposta para criação de uma tarefa em lote.

first_id

String

ID da primeira tarefa em lote na página atual.

last_id

String

ID da última tarefa em lote na página atual.

has_more

Boolean

Indica se há páginas adicionais disponíveis.

Cancelar tarefa em lote

Cancele uma tarefa que esteja em andamento ou na fila. Após uma chamada bem-sucedida, o status da tarefa muda para cancelling e depois para cancelled. Você ainda será cobrado pelas requisições concluídas antes que o cancelamento tenha efeito total.

OpenAI Python SDK

Exemplo de requisição

import os
from openai import OpenAI

client = OpenAI(
    # If no environment variable is set, use api_key="sk-xxx" (not in production - risk of leaks).
    # API keys differ between regions.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore region's base_url. For Beijing, use: https://dashscope.aliyuncs.com/compatible-mode/v1 and update the API key.
    # Note: When switching regions, also update the API key accordingly.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
batch = client.batches.cancel("batch_id")  # Replace batch_id with the batch task ID
print(batch)

OpenAI Node.js SDK

Exemplo de requisição

/**
 * Model Studio Batch API - Cancel task
 * 
 * If no environment variable is set, use apiKey: 'sk-xxx' (not in production - risk of leaks).
 * API keys differ between regions.
 * 
 * Install dependencies: npm install openai
 */
const OpenAI = require('openai');

// Singapore region configuration (default)
const BASE_URL = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1';
// If using the Beijing region, replace the above BASE_URL with:
// const BASE_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
// Note: When switching regions, also update the API key accordingly.

const apiKey = process.env.DASHSCOPE_API_KEY;
if (!apiKey) {
    console.error('Error: Please set the environment variable DASHSCOPE_API_KEY');
    console.error('Or set in code: 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)

Exemplo de requisição

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;

/**
 * Model Studio Batch API - Cancel task
 * 
 * If no environment variable is set, use API_KEY = "sk-xxx" (not in production - risk of leaks).
 * API keys differ between regions.
 * 
 * Region configuration:
 * - Beijing region: https://dashscope.aliyuncs.com/compatible-mode/v1
 * - Singapore region: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
 * Note: When switching regions, also update the API key accordingly.
 */
public class BatchAPICancelBatch {
    
    // Singapore region configuration
    private static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1";
    // For Beijing, use: private static final String BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"; and update the API key.
    
    private static String API_KEY;
    
    public static void main(String[] args) throws Exception {
        API_KEY = System.getenv("DASHSCOPE_API_KEY");
        if (API_KEY == null || API_KEY.isEmpty()) {
            System.err.println("Error: Please set the environment variable DASHSCOPE_API_KEY");
            System.err.println("Or set in code: API_KEY = \"sk-xxx\";");
            System.exit(1);
        }
        
        String response = sendRequest("POST", "/batches/batch_id/cancel", null);
        System.out.println(response);
    }
    
    // === Utility methods ===
    
    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)

Exemplo de requisição

# ======= Important =======
# API keys differ between Singapore and Beijing regions.
# The following is the base_url for the Singapore region. If you use a model in the Beijing region, replace the base_url with: https://dashscope.aliyuncs.com/compatible-mode/v1/batches/batch_id/cancel
# === Delete this comment before execution ===
curl --request POST 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/batches/batch_id/cancel' \
 -H "Authorization: Bearer $DASHSCOPE_API_KEY"
Substitua batch_id pelo valor real.

Exemplo de resposta

Após cancelar uma tarefa com sucesso, a API retorna informações detalhadas da tarefa em lote. A seguir, um exemplo de resposta para uma tarefa com 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
}
Ao cancelar uma tarefa, o status muda primeiro para cancelling enquanto o sistema aguarda a conclusão das requisições em execução. Posteriormente, o status muda para cancelled . Os resultados das requisições concluídas ainda são salvos no arquivo de saída.

4. Baixar arquivo de resultado do Batch

Após a conclusão de uma tarefa, arquivos de resultado (output_file_id) e arquivos de erro (error_file_id) podem ser gerados. Baixe ambos os tipos de arquivo usando a mesma API de download de arquivos.

Você só pode baixar arquivos cujo file_id começa com file-batch_output.

OpenAI Python SDK

Use o método content para recuperar o conteúdo do arquivo de resultado da tarefa em lote e o método write_to_file para salvá-lo localmente.

Exemplo de requisição

import os
from openai import OpenAI

client = OpenAI(
    # If no environment variable is set, use api_key="sk-xxx" (not in production - risk of leaks).
    # API keys differ between regions.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore region's base_url. For Beijing, use: https://dashscope.aliyuncs.com/compatible-mode/v1 and update the API key.
    # Note: When switching regions, also update the API key accordingly.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
content = client.files.content(file_id="file-batch_output-xxx")
# Print result file content
print(content.text)
# Save result file locally
content.write_to_file("result.jsonl")

Exemplo de resposta

{"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

Use o método content para recuperar o conteúdo do arquivo de resultado da tarefa em lote.

Exemplo de requisição

/**
 * Model Studio Batch API - Download result file
 * 
 * If no environment variable is set, use apiKey: 'sk-xxx' (not in production - risk of leaks).
 * API keys differ between regions.
 * 
 * Install dependencies: npm install openai
 */
const OpenAI = require('openai');
const fs = require('fs');

// Singapore region configuration (default)
const BASE_URL = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1';
// If using the Beijing region, replace the above BASE_URL with:
// const BASE_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
// Note: When switching regions, also update the API key accordingly.

const apiKey = process.env.DASHSCOPE_API_KEY;
if (!apiKey) {
    console.error('Error: Please set the environment variable DASHSCOPE_API_KEY');
    console.error('Or set in code: const apiKey = "sk-xxx";');
    process.exit(1);
}

const client = new OpenAI({
    apiKey: apiKey,
    baseURL: BASE_URL
});

// Download result file
const content = await client.files.content('file-batch_output-xxx');
const text = await content.text();
console.log(text);

// Save to local file
fs.writeFileSync('result.jsonl', text);
console.log('Results saved to result.jsonl');

Java (HTTP)

Use uma requisição GET para o endpoint /files/{file_id}/content para baixar o conteúdo do arquivo.

Exemplo de requisição

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;

/**
 * Model Studio Batch API - Download result file
 * 
 * If no environment variable is set, use API_KEY = "sk-xxx" (not in production - risk of leaks).
 * API keys differ between regions.
 * 
 * Region configuration:
 * - Beijing region: https://dashscope.aliyuncs.com/compatible-mode/v1
 * - Singapore region: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
 * Note: When switching regions, also update the API key accordingly.
 */
public class BatchAPIDownloadFile {
    
    // Singapore region configuration
    private static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1";
    // For Beijing, use: private static final String BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"; and update the API key.
    
    private static String API_KEY;
    
    public static void main(String[] args) throws Exception {
        API_KEY = System.getenv("DASHSCOPE_API_KEY");
        if (API_KEY == null || API_KEY.isEmpty()) {
            System.err.println("Error: Please set the environment variable DASHSCOPE_API_KEY");
            System.err.println("Or set in code: API_KEY = \"sk-xxx\";");
            System.exit(1);
        }

// Download result file
String content = sendRequest("GET", "/files/file-batch_output-xxx/content", null);
System.out.println(content);

// Save to local file
        Files.write(Paths.get("result.jsonl"), content.getBytes());
        System.out.println("Results saved to result.jsonl");
    }
    
    // === Utility methods ===
    
    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)

Baixe o arquivo de resultado especificando o file_id em uma requisição GET.

Instruções

  1. Leia o inglês para entender O QUE precisa ser comunicado

  2. Escreva o português brasileiro DO ZERO — esqueça a estrutura da frase em inglês

  3. Preserve toda a formatação markdown, blocos de código, links e imagens exatamente como estão

  4. Tags xref (<a data-tag="xref" ...>texto</a>) — preserve a tag INTEIRA com todos os atributos na ordem e caixa originais, traduza APENAS o texto visível entre > e

  5. Aplique todas as regras específicas do idioma rigorosamente

  6. Aplique as regras de stopwords com tolerância zero

  7. Use o modo imperativo em passos numerados e listas de procedimentos

  8. Garanta consistência terminológica — mesmo termo = mesma tradução em todo o documento

  9. Varie os inícios de frase em listas/tabelas — nenhum início repetido 3+ vezes

  10. Retorne APENAS o documento markdown em português brasileiro, sem explicações

    Exemplo de requisição

    # ======= Important =======
    # API keys differ between Singapore and Beijing regions.
    # The following is the base_url for the Singapore region. If you use a model in the Beijing region, replace the base_url with: https://dashscope.aliyuncs.com/compatible-mode/v1/files/file-batch_output-xxx/content
    # === Delete this comment before execution ===
    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

Exemplo de resposta

Exemplo de resposta única:

{
    "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
}

Parâmetros de resposta

Campo

Tipo

Descrição

id

String

O ID da requisição.

custom_id

String

O identificador de requisição definido pelo usuário.

response

Object

O resultado da requisição.

status_code

Integer

Código de status HTTP. 200 indica sucesso.

request_id

String

ID exclusivo gerado pelo servidor para esta requisição.

completion_tokens

Integer

Número de tokens na resposta gerada pelo modelo.

prompt_tokens

Integer

Quantidade de tokens no conteúdo de entrada (prompt) enviado ao modelo.

total_tokens

Integer

Total de tokens utilizados por esta requisição.

model

String

Nome do modelo usado nesta requisição.

error

Object

O objeto de erro. Retorna null em caso de sucesso. Em caso de falha, contém o código de erro e a mensagem detalhada.

error.code

String

Informações sobre a linha e o motivo do erro. Consulte Códigos de erro para solução de problemas.

error.message

String

Mensagem de erro.

Recursos avançados

Configurar notificações de conclusão

Para tarefas de longa duração, utilize notificações assíncronas em vez de polling para reduzir o consumo de recursos.

Nota

A notificação de conclusão é suportada apenas na região de Pequim.

  • Callback: Especifique uma URL acessível publicamente ao criar a tarefa.

  • Fila de mensagens do EventBridge: Integração profunda com o ecossistema Alibaba Cloud. Não requer IP público.

Método 1: Callback

Ao criar uma tarefa, especifique uma URL acessível publicamente via metadata. Após a conclusão da tarefa, o sistema envia uma requisição POST contendo o status da tarefa para a URL especificada:

OpenAI Python SDK

import os
from openai import OpenAI

client = OpenAI(
    # If no environment variable is set, use api_key="sk-xxx" (not in production - risk of leaks).
    # API keys differ between regions.
    api_key=os.getenv("DASHSCOPE_API_KEY"), 
    # Beijing region's base_url. For Singapore, use: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1 and update the API key.
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)

batch = client.batches.create(
    input_file_id="file-batch-xxx",  # The ID returned after uploading the file
    endpoint="/v1/chat/completions",  # For text embedding models, enter "/v1/embeddings". For the test model batch-test-model, enter /v1/chat/ds-test. For other models, enter /v1/chat/completions.
    completion_window="24h", 
    metadata={
            "ds_batch_finish_callback": "https://xxx/xxx"
          }
)
print(batch)

curl (HTTP)

Exemplo de requisição

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"
          }
        }'

Método 2: Fila de mensagens do EventBridge

Este método não exige IP público e é adequado para cenários complexos que precisam de integração com serviços como Function Compute ou RocketMQ.

Quando uma tarefa em lote é concluída, o sistema envia um evento para o Alibaba Cloud EventBridge. Configure regras do EventBridge para ouvir esse evento e roteá-lo para um destino especificado.

  • Origem do evento (Source): acs.dashscope

  • Tipo de evento (Type): dashscope:System:BatchTaskFinish

Referência: Roteamento de eventos para o Message Queue for RocketMQ.

Entrando em produção

  • Gerenciamento de arquivos

    • Exclua periodicamente arquivos desnecessários usando a API de exclusão de arquivos da OpenAI para evitar atingir os limites de armazenamento (10.000 arquivos ou 100 GB).

    • Armazene arquivos grandes no OSS em vez de fazer upload direto.

  • Monitoramento de tarefas

    • Utilize notificações assíncronas via Callback ou EventBridge.

    • Caso o polling seja necessário, defina o intervalo para mais de 1 minuto e adote uma estratégia de backoff exponencial.

  • Tratamento de erros

    • Implemente tratamento para erros de rede, erros de API e outras exceções.

    • Baixe e analise os detalhes dos erros a partir de error_file_id.

    • Para códigos de erro comuns, consulte Códigos de erro.

  • Otimização de custos

    • Consolide pequenas tarefas em um único lote.

    • Defina completion_window adequadamente para permitir maior flexibilidade de agendamento.

Ferramentas utilitárias

CSV para JSONL

Se seus dados estiverem em um arquivo CSV (primeira coluna: ID, segunda coluna: conteúdo), use este script para gerar um arquivo de entrada em lote JSONL.

Para personalizar o caminho do arquivo ou outros parâmetros, modifique o código conforme necessário.
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])}
            # When calling a text embedding model, set the url value to "/v1/embeddings". For other models, set it to /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")

Resultados JSONL para CSV

Utilize este script para converter result.jsonl em result.csv para análise no Excel.

Para personalizar o caminho do arquivo ou outros parâmetros, modifique o código conforme necessário.
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)

Corrigir texto ilegível no Excel

  • Use um editor de texto (como Sublime Text) para converter a codificação do arquivo CSV para GBK e, em seguida, abra-o no Excel.

  • Alternativamente, crie um novo arquivo Excel e especifique a codificação UTF-8 ao importar os dados.

Limites de taxa

API

Limite de taxa (por conta Alibaba Cloud)

Criar tarefa

1.000 chamadas/minuto; até 1.000 tarefas simultâneas

Consultar tarefa

1.000 chamadas/minuto

Consultar lista de tarefas

100 chamadas/minuto

Cancelar tarefa

1.000 chamadas/minuto

Faturamento

  • Preço unitário: Os tokens de entrada e saída de todas as requisições bem-sucedidas são cobrados a 50% do preço de inferência em tempo real do modelo correspondente. Para mais informações, consulte Lista de modelos.

  • Escopo de faturamento:

    • Apenas requisições executadas com sucesso dentro de uma tarefa são faturadas.

    • Requisições que falham devido a erros de análise de arquivo, falhas na execução da tarefa ou erros no nível da linha não geram cobranças.

    • Para tarefas canceladas, as requisições concluídas com sucesso antes do cancelamento ainda são faturadas normalmente.

Nota
  • A inferência em lote é um item de faturamento separado. Ela suporta o Plano de economia de uso geral de IA, mas não aceita descontos como assinatura (outros planos de economia) ou cotas gratuitas para novos usuários. Também não suporta recursos como cache de contexto.

  • Alguns modelos, como qwen3.5-plus e qwen3.5-flash, têm o modo de pensamento ativado por padrão. Esse modo gera tokens de pensamento adicionais, que são cobrados pelo preço de tokens de saída e aumentam os custos. Para controlar despesas, defina o parâmetro enable_thinking com base na complexidade da tarefa. Para mais informações, consulte Pensamento profundo.

Códigos de erro

Se uma requisição falhar e retornar uma mensagem de erro, consulte Códigos de erro para obter uma solução.

Perguntas frequentes

  1. Como escolher entre Batch Chat e Batch File?

    Use Batch File quando precisar processar assincronamente um arquivo grande contendo muitas requisições. Opte por Batch Chat quando sua lógica de negócio exigir o envio síncrono de muitas requisições de conversa independentes com alta concorrência.

  2. Como é feito o faturamento da API Batch File? Preciso comprar um pacote separado?

    O Batch utiliza faturamento conforme o uso (pay-as-you-go) com base nos tokens consumidos pelas requisições bem-sucedidas. Nenhum pacote de recursos separado é necessário.

  3. Os arquivos em lote enviados são executados em ordem?

    Não. O sistema usa agendamento dinâmico baseado na carga computacional e não garante a ordem de execução. As tarefas podem sofrer atrasos quando os recursos estiverem limitados.

  4. Quanto tempo leva para concluir um arquivo em lote enviado?

    O tempo de execução depende dos recursos do sistema e da escala da tarefa. Se uma tarefa não for concluída dentro do completion_window, ela expira. Requisições não processadas em tarefas expiradas não são executadas e não geram cobranças.

    Recomendações de cenário: Utilize chamadas em tempo real para cenários que exigem inferência de modelo estritamente em tempo real. Use chamadas em lote para cenários de processamento de dados em larga escala que toleram atrasos.