Todos los productos
Search
Centro de documentos

Alibaba Cloud Model Studio:Compatible con OpenAI - Batch (entrada de archivo)

Última actualización: Oct 12, 2026

Alibaba Cloud Model Studio proporciona una API de Batch File compatible con OpenAI. Envíe solicitudes en masa a través de archivos. El sistema las procesa asincrónicamente y devuelve resultados cuando todas las solicitudes se completan o se alcanza el tiempo máximo de espera. Los costos son solo del 50% de las llamadas en tiempo real. Ideal para análisis de datos, evaluación de modelos y otras cargas de trabajo a gran escala donde la latencia no es crítica.

Para usar la consola, consulte la guía de la consola.

Flujo de trabajo

imagen

Requisitos previos

Puede llamar a la API Batch File a través del SDK de OpenAI (Python, Node.js) o la API HTTP.

Ámbito

Singapore

Modelos compatibles: qwen3.7-plus, qwen-max, qwen-plus, qwen-flash

China (Beijing)

Modelos compatibles:

Importante

  • En el escenario de procesamiento por lotes, el máximo de tokens de contexto por solicitud es de 256 K para qwen3.8-max, qwen3.8-flash, qwen3.7-max, qwen3.7-plus, qwen3.6-plus, qwen3.7-flash, qwen3.6-flash, qwen3.5-plus, qwen3.5-flash, qwen3.5-omni-flash y qwen3.5-omni-plus. qwen3.5-omni-plus y qwen3.5-omni-flash no admiten salida de voz.
  • Algunos modelos admiten el modo de pensamiento. Activar este modo genera tokens de pensamiento y aumenta los costos.
  • Los modelos de las series qwen3.8, qwen3.7, qwen3.6 y qwen3.5 tienen el modo de pensamiento activado de forma predeterminada. Si utiliza un modelo de pensamiento híbrido, debe configurar explícitamente el parámetro enable_thinking. Configure este parámetro en true para activar el modo o en false para desactivarlo.
  • En el cuerpo de la solicitud JSONL, enable_thinking es un parámetro de nivel superior de body y debe colocarse al mismo nivel que model. No lo coloque dentro de extra_body.

Introducción

Antes de procesar tareas formales, realice pruebas con el batch-test-model. Este modelo de prueba omite la inferencia y devuelve una respuesta de éxito fija, lo que le permite verificar su cadena de llamadas API y el formato de datos.

Nota

Limitaciones de batch-test-model:
  • Su archivo de prueba debe cumplir con los Requisitos del archivo de entrada. Tamaño máximo: 1 MB. Líneas máximas: 100.
  • Límite de concurrencia: Hasta 2 tareas paralelas.
  • Costo: El modelo de prueba no genera cargos por inferencia del modelo.

Paso 1: Preparar el archivo de entrada

Prepare un archivo llamado test_model.jsonl con el siguiente contenido:

{"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 multimodales (p. ej.

Paso 2: Ejecutar el código

Seleccione un fragmento de código para su lenguaje de programación. Guárdelo en el mismo directorio que su archivo de entrada y ejecútelo. El código maneja el flujo de trabajo completo: carga, creación de tarea, sondeo de estado y descarga de resultados.

Para personalizar la ruta del archivo u otros parámetros, modifique el código según sea necesario.

NotaReutilizar un ID de archivo existente: El ID devuelto después de cargar un archivo (por ejemplo, file-batch-xxx) se puede reutilizar. Si el contenido de entrada permanece igual, omita la recarga y cree directamente una tarea con el 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"
)

Puede recuperar ID de archivos históricos a través de la API client.files.list(purpose="batch") para consultar ID de archivos Batch cargados.

Código de ejemplo

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://dashscope-intl.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/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/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/model-studio/developer-reference/error-code

if __name__ == "__main__":
    main()
/**
 * 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://dashscope-intl.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/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();
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://dashscope-intl.aliyuncs.com/compatible-mode/v1
 */
public class BatchAPITest {

    // Base URL for the Singapore region
    private static final String BASE_URL = "https://dashscope-intl.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/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);
    }
}
#!/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://dashscope-intl.aliyuncs.com/compatible-mode/v1

API_KEY="${DASHSCOPE_API_KEY}"
BASE_URL="https://dashscope-intl.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/model-studio/developer-reference/error-code
else
    echo ""
    echo "Task status: ${STATUS}"
fi

Paso 3: Verificar resultados de la prueba

Después de que la tarea tenga éxito, el archivo de resultados result.jsonl contiene la respuesta fija {"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}

Ejecutar una tarea formal

Requisitos del archivo de entrada

  • Formato: JSONL codificado en UTF-8 (un objeto JSON independiente por línea).
  • Límites de tamaño: Máximo 50,000 solicitudes por archivo, máximo 500 MB.
  • Límite de líneas: Cada objeto JSON no debe exceder 6 MB y debe caber dentro de la ventana de contexto del modelo.
  • Consistencia: Todas las solicitudes en el mismo archivo deben utilizar el mismo modelo y el mismo modo de pensamiento (si corresponde).
  • Identificador único: Cada solicitud debe incluir un campo custom_id único dentro del archivo. Este campo se utiliza para hacer coincidir las solicitudes con los resultados.
Escenario 1: Chat de texto

Contenido del archivo de ejemplo:

{"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?"}]}}
Escenario 2: Comprensión de imágenes y videos

Modelos multimodales (p. ej.

Las cadenas Base64 en los ejemplos anteriores están truncadas. Genere codificaciones completas utilizando el código Python a continuación.

Pasar cadenas codificadas en Base64 (usando imágenes como ejemplo)

  1. Convertir un archivo local a codificación 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")
  1. Construya un formato Data URL: data:[MIME_type];base64,{base64_image};

    1. Reemplace MIME_type con el tipo de medio real. Debe coincidir con el valor de MIME Type (p. ej., image/jpeg, image/png);
    2. base64_image es la cadena Base64 generada en el paso anterior.

NotaPara obtener todos los detalles (incluidos límites de archivos, tipos MIME y métodos de codificación), consulte Pasar archivos locales (codificación Base64 o rutas de archivo).

Herramienta de generación por lotes JSONL

Utilice esta herramienta para generar rápidamente archivos JSONL.

1. Modificar el archivo de entrada

  • En el archivo test_model.jsonl, configure el parámetro model al modelo objetivo y configure el campo url:

    Tipo de modelo

    url

    Modelos de generación de texto/multimodales

    /v1/chat/completions

    Modelos de incrustación de texto

    /v1/embeddings

  • O utilice la "herramienta de generación de lotes JSONL" anterior para generar un nuevo archivo para tareas formales. Asegúrese de que los campos model y url sean correctos.

2. Modificar el código de Introducción

  1. Cambie la ruta del archivo de entrada por el nombre de su archivo.
  2. Configure el parámetro endpoint para que coincida con el campo url en su archivo de entrada.

3. Ejecutar el código y esperar resultados

Cuando la tarea finaliza, los resultados de las solicitudes exitosas se guardan en el archivo local result.jsonl. Si alguna solicitud falló, los detalles del error se guardan en el archivo error.jsonl.

  • Resultados exitosos (output_file_id): Cada línea corresponde a una solicitud exitosa e incluye el custom_id y la 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}
  • Detalles de fallos (error_file_id): Contiene información sobre solicitudes fallidas con números de línea y motivos de error. Consulte Códigos de error para solucionar problemas.

Procedimiento detallado

El flujo de trabajo de la API Batch consta de cuatro pasos: cargar un archivo, crear una tarea, consultar el estado de la tarea y descargar los resultados.

1. Cargar archivo

Cargue su archivo JSONL mediante la API de carga de archivos para obtener un file_id.

Al cargar un archivo, el parámetro purpose debe ser batch .

NotaReutilizar un ID de archivo existente: El ID devuelto después de cargar un archivo (por ejemplo, file-batch-xxx) se puede reutilizar. Si el contenido de entrada permanece igual, omita la recarga y cree directamente una tarea con el 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"
)

Puede recuperar ID de archivos históricos a través de la API client.files.list(purpose="batch") para consultar ID de archivos Batch cargados.

SDK de Python de OpenAI

Ejemplo de solicitud

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://dashscope-intl.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())

SDK de Node.js de OpenAI

Ejemplo de solicitud

/**
 * 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://dashscope-intl.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)

Ejemplo de solicitud

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://dashscope-intl.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://dashscope-intl.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)

Ejemplo de solicitud

# ======= 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://dashscope-intl.aliyuncs.com/compatible-mode/v1/files \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
--form 'file=@"test.jsonl"' \
--form 'purpose="batch"'

Ejemplo de respuesta

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

2. Crear una tarea por lotes

Cree una tarea por lotes utilizando el ID de archivo obtenido del paso de carga de archivos.

SDK de Python de OpenAI

Ejemplo de solicitud

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://dashscope-intl.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)

SDK de Node.js de OpenAI

Ejemplo de solicitud

/**
 * 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://dashscope-intl.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)

Ejemplo de solicitud

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://dashscope-intl.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://dashscope-intl.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)

Ejemplo de solicitud

# ======= 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://dashscope-intl.aliyuncs.com/compatible-mode/v1/batches \
  -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "input_file_id": "file-batch-xxx",
    "endpoint": "/v1/chat/completions",
    "completion_window": "24h",
    "metadata":{"ds_name":"Task name","ds_description":"Task description"}
  }'

Parámetros de entrada

Campo

Tipo

Método

Obligatorio

Descripción

input_file_id

String

Cuerpo

Sí

El ID del archivo de entrada.

Utilice el ID de archivo devuelto por la API Preparar y cargar archivo, como file-batch-xxx.

endpoint

String

Cuerpo

Sí

La ruta de acceso a la API. Debe coincidir con el campo url en el archivo de entrada.

  • Para el modelo de prueba batch-test-model, ingrese /v1/chat/ds-test

  • Para otros modelos, ingrese /v1/chat/completions

completion_window

String

Cuerpo

Sí

Tiempo máximo de espera. Rango: 24h-336h, solo números enteros.

Unidades: "h" o "d" (p. ej., "24h" o "14d").

metadata

Mapa

Cuerpo

No

Metadatos extendidos para la tarea, especificados como pares clave-valor.

metadata.ds_name

String

Cuerpo

No

Nombre de la tarea.

Ejemplo: "ds_name": "Batch task"

Longitud máxima: 100 caracteres.

Si se especifica varias veces, el último valor tendrá efecto.

metadata.ds_description

String

Cuerpo

No

Descripción de la tarea.

Ejemplo: "ds_description": "Batch inference task test"

Longitud máxima: 200 caracteres.

Si se especifica varias veces, el último valor tendrá efecto.

Ejemplo de respuesta

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

Campo

Tipo

Descripción

id

String

El ID de la tarea por lotes.

object

String

Valor fijo: batch.

endpoint

String

La ruta de acceso a la API.

errors

Mapa

Información de error.

input_file_id

String

ID del archivo de entrada .

completion_window

String

Tiempo máximo de espera. Rango: 24h-336h, solo números enteros.

Unidades: "h" o "d" (p. ej., "24h" o "14d").

status

String

Estado de la tarea: validating, failed, in_progress, finalizing, completed, expired, cancelling, cancelled.

output_file_id

String

ID de archivo para resultados de solicitudes exitosas.

error_file_id

String

ID de archivo para resultados de solicitudes fallidas.

created_at

Integer

Marca de tiempo Unix (segundos) en la que se creó la tarea.

in_progress_at

Integer

Marca de tiempo Unix (segundos) en la que la tarea comenzó a procesarse.

expires_at

Integer

Marca de tiempo Unix (segundos) en la que la tarea comienza a agotar el tiempo de espera.

finalizing_at

Integer

Marca de tiempo Unix (segundos) en la que la tarea se inició por última vez.

completed_at

Integer

Marca de tiempo Unix (segundos) en la que se completó la tarea.

failed_at

Integer

Marca de tiempo Unix (segundos) cuando falló la tarea.

expired_at

Integer

Marca de tiempo Unix (segundos) en la que expiró la tarea.

cancelling_at

Integer

Marca de tiempo Unix (segundos) en la que la tarea entró en estado de cancelación.

cancelled_at

Integer

Marca de tiempo Unix (segundos) en la que se canceló la tarea.

request_counts

Mapa

Recuentos de solicitudes por estado.

metadata

Mapa

Metadatos adicionales como pares clave-valor.

metadata.ds_name

String

Nombre de la tarea.

metadata.ds_description

String

Descripción de la tarea.

3. Consultar y gestionar tareas por lotes

Después de crear una tarea, utilice las siguientes API para consultar su estado, listar tareas históricas o cancelar una tarea en curso.

Consultar estado de tarea específica

Consulte una tarea por lotes por su ID. Solo se pueden consultar tareas creadas en los últimos 30 días.

SDK de Python de OpenAI

Ejemplo de solicitud

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://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
batch = client.batches.retrieve("batch_id")  # Replace batch_id with the batch task ID
print(batch)

SDK de Node.js de OpenAI

Ejemplo de solicitud

/**
 * 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://dashscope-intl.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)

Ejemplo de solicitud

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://dashscope-intl.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://dashscope-intl.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)

Ejemplo de solicitud

# ======= 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://dashscope-intl.aliyuncs.com/compatible-mode/v1/batches/batch_id' \
 -H "Authorization: Bearer $DASHSCOPE_API_KEY"

Ejemplo de respuesta

Una consulta exitosa devuelve información detallada de la tarea por lotes. A continuación se muestra un ejemplo de respuesta para una tarea con estado completado:

{
  "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 descripciones de campos, consulte la tabla a continuación.

Campo

Tipo

Descripción

id

String

ID de tarea por lotes.

status

String

Estado de la tarea. Valores posibles:

  • validando

  • in_progress

  • finalizando

  • completado

  • fallido

  • expirado

  • cancelando

  • cancelado

output_file_id

String

ID del archivo de salida que contiene los resultados exitosos. Generado tras la finalización de la tarea.

error_file_id

String

ID del archivo de errores que contiene los detalles de las solicitudes fallidas. Generado tras la finalización de la tarea si alguna solicitud falló.

request_counts

Object

Estadísticas de recuento de solicitudes que contienen totales, completadas y fallidas.

Consultar lista de tareas

Utilice el método batches.list() para recuperar la lista de tareas por lotes. Utilice la paginación para recuperar la lista completa de tareas.

SDK de Python de OpenAI

Ejemplo de solicitud

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://dashscope-intl.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)

SDK de Node.js de OpenAI

Ejemplo de solicitud

/**
 * 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://dashscope-intl.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)

Ejemplo de solicitud

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://dashscope-intl.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://dashscope-intl.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)

Ejemplo de solicitud

# ======= 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://dashscope-intl.aliyuncs.com/compatible-mode/v1/batches?after=batch_xxx&limit=2&ds_name=Batch&input_file_ids=file-batch-xxx,file-batch-xxx&status=completed,failed&create_after=20250303000000&create_before=20250320000000' \
 -H "Authorization: Bearer $DASHSCOPE_API_KEY"

Reemplace batch_id en after=batch_id con el valor real. Establezca limit en el número de tareas a devolver. Especifique un nombre parcial de tarea para ds_name. Para input_file_ids, especifique uno o más IDs de archivo. Especifique uno o más estados de tarea por lotes para status. Para create_after y create_before, especifique los límites de tiempo.

Parámetros de entrada

Campo

Tipo

Método

Obligatorio

Descripción

after

String

Consulta

No

Cursor para paginación. Establezca esto en el último ID de tarea de la página anterior.

limit

Integer

Consulta

No

Número de tareas por página. Rango: [1, 100]. Valor predeterminado: 20.

ds_name

String

Consulta

No

Coincidencia aproximada por nombre de tarea.

input_file_ids

String

Consulta

No

Filtrar por ID de archivos. Especifique varios ID separados por comas (hasta 20).

status

String

Consulta

No

Filtrar por estado de la tarea. Especifique varios estados separados por comas.

create_after

String

Consulta

No

Filtrar tareas creadas después de esta hora. Formato: yyyyMMddHHmmss.

create_before

String

Consulta

No

Filtrar tareas creadas antes de esta hora. Formato: yyyyMMddHHmmss.

Ejemplo de respuesta

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

Campo

Tipo

Descripción

object

String

Tipo de objeto. Valor fijo: list.

data

Array

Matriz de objetos de tareas por lotes. Consulte los parámetros de respuesta para crear una tarea por lotes.

first_id

String

ID de la primera tarea por lotes en la página actual.

last_id

String

ID de la última tarea por lotes en la página actual.

has_more

Boolean

Si hay páginas adicionales disponibles.

Cancelar tarea por lotes

Cancele una tarea que esté en curso o en cola. Después de una llamada exitosa, el estado de la tarea cambia a cancelling y luego a cancelled. Se le seguirán facturando las solicitudes que se completaron antes de que la cancelación surta efecto completo.

SDK de Python de OpenAI

Ejemplo de solicitud

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://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
batch = client.batches.cancel("batch_id")  # Replace batch_id with the batch task ID
print(batch)

SDK de Node.js de OpenAI

Ejemplo de solicitud

/**
 * 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://dashscope-intl.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)

Ejemplo de solicitud

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://dashscope-intl.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://dashscope-intl.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)

Ejemplo de solicitud

# ======= 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://dashscope-intl.aliyuncs.com/compatible-mode/v1/batches/batch_id/cancel' \
 -H "Authorization: Bearer $DASHSCOPE_API_KEY"

Reemplace batch_id con el valor real.

Ejemplo de respuesta

Después de cancelar exitosamente una tarea, la API devuelve información detallada de la tarea por lotes. A continuación se muestra un ejemplo de respuesta para una tarea en estado de cancelación:

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

Después de cancelar una tarea, el estado primero cambia a cancelling mientras el sistema espera que se completen las solicitudes actualmente en ejecución. El estado eventualmente cambia a cancelled. Los resultados de las solicitudes completadas aún se guardan en el archivo de salida.

4. Descargar archivo de resultados de Batch

Una vez completada una tarea, se pueden generar archivos de resultados (output_file_id) y archivos de errores (error_file_id). Descargue ambos tipos de archivos utilizando la misma API de descarga de archivos.

Solo puede descargar archivos cuyo file_id comience con file-batch_output.

SDK de Python de OpenAI

Utilice el método content para recuperar el contenido del archivo de resultados de la tarea por lotes y utilice el método write_to_file para guardarlo localmente.

Ejemplo de solicitud

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://dashscope-intl.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")

Ejemplo de respuesta

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

SDK de Node.js de OpenAI

Utilice el método content para recuperar el contenido del archivo de resultados de la tarea por lotes.

Ejemplo de solicitud

/**
 * 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://dashscope-intl.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)

Utilice una solicitud GET al endpoint /files/{file_id}/content para descargar el contenido del archivo.

Ejemplo de solicitud

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://dashscope-intl.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://dashscope-intl.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)

Descargue el archivo de resultados especificando el file_id en una solicitud GET.

Ejemplo de solicitud

# ======= 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://dashscope-intl.aliyuncs.com/compatible-mode/v1/files/file-batch_output-xxx/content \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" > result.jsonl

Ejemplo de respuesta

Ejemplo de respuesta ú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 respuesta

Campo

Tipo

Descripción

id

String

El ID de la solicitud.

custom_id

String

El identificador de solicitud definido por el usuario.

response

Object

El resultado de la solicitud.

status_code

Integer

Código de estado HTTP. 200 indica éxito.

request_id

String

ID único generado por el servidor para esta solicitud.

completion_tokens

Integer

Número de tokens en la respuesta generada por el modelo.

prompt_tokens

Integer

Número de tokens en el contenido de entrada (prompt) enviado al modelo.

total_tokens

Integer

Número total de tokens utilizados por esta solicitud.

model

String

Nombre del modelo utilizado para esta solicitud.

error

Object

El objeto de error. Devuelve null en caso de éxito. En caso de fallo, contiene el código de error y el mensaje detallado.

error.code

String

Información de la línea de error y el motivo. Consulte Códigos de error para solucionar problemas.

error.message

String

Mensaje de error.

Funciones avanzadas

Configurar notificaciones de finalización

Para tareas de larga duración, utilice notificaciones asíncronas en lugar de sondeo para reducir el consumo de recursos.

NotaLa notificación de finalización solo es compatible en la región de Beijing.

  • Callback: Especifique una URL accesible públicamente al crear la tarea.
  • Cola de mensajes EventBridge: Profundamente integrada con el ecosistema de Alibaba Cloud. No requiere IP pública.

Método 1: Callback

Al crear una tarea, especifique una URL accesible públicamente mediante metadata. Una vez completada la tarea, el sistema envía una solicitud POST que contiene el estado de la tarea a la URL especificada:

SDK de Python de OpenAI

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://dashscope-intl.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)

Ejemplo de solicitud

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: Cola de mensajes de EventBridge

Este método no requiere una IP pública y es adecuado para escenarios complejos que necesitan integración con servicios como Function Compute o RocketMQ.

Cuando una tarea por lotes finaliza, el sistema envía un evento a Alibaba Cloud EventBridge. Configure reglas de EventBridge para escuchar este evento y enrutarlo a un destino especificado.

  • Origen del evento (Source): acs.dashscope
  • Tipo de evento (Type): dashscope:System:BatchTaskFinish

Referencia: Enrutar eventos a Message Queue for RocketMQ.

Puesta en marcha

  • Gestión de archivos
    • Elimine periódicamente los archivos innecesarios utilizando la API de eliminación de archivos de OpenAI para evitar alcanzar los límites de almacenamiento (10,000 archivos o 100 GB).
    • Almacene archivos grandes en OSS en lugar de cargarlos directamente.
  • Monitoreo de tareas
    • Utilice notificaciones asíncronas de Callback o EventBridge.
    • Si se requiere sondeo, establezca el intervalo en más de 1 minuto y utilice una estrategia de retroceso exponencial.
  • Manejo de errores
    • Implemente el manejo de errores de red, errores de API y otras excepciones.
    • Descargue y analice los detalles de error desde error_file_id.
    • Para códigos de error comunes, consulte Códigos de error.
  • Optimización de costos
    • Consolidar tareas pequeñas en un solo lote.
    • Configure completion_window adecuadamente para permitir una mayor flexibilidad de programación.

Herramientas de utilidad

CSV a JSONL

Si sus datos están en un archivo CSV (primera columna: ID, segunda columna: contenido), utilice este script para generar un archivo de entrada por lotes JSONL.

Para personalizar la ruta del archivo u otros parámetros, modifique el código según sea necesario.

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:
"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 a CSV

Utilice este script para convertir result.jsonl en result.csv para su análisis en Excel.

Para personalizar la ruta del archivo u otros parámetros, modifique el código según sea necesario.

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)
Corregir texto ilegible en Excel
  • Utilice un editor de texto (como Sublime Text) para convertir la codificación del archivo CSV a GBK y luego ábralo en Excel.
  • Alternativamente, cree un nuevo archivo de Excel y especifique la codificación UTF-8 al importar los datos.

Límites de tasa

API

Límite de tasa (por cuenta de Alibaba Cloud)

Crear tarea

1,000 llamadas/minuto; hasta 1,000 tareas simultáneas

Consultar tarea

1,000 llamadas/minuto

Consultar lista de tareas

100 llamadas/minuto

Cancelar tarea

1,000 llamadas/minuto

Facturación

  • Precio unitario: Los tokens de entrada y salida de todas las solicitudes exitosas se cobran al 50% del precio de inferencia en tiempo real para el modelo correspondiente. Para más información, consulte Lista de modelos.

  • Ámbito de facturación:
    • Solo se facturan las solicitudes ejecutadas correctamente dentro de una tarea.
    • Las solicitudes que fallan debido a errores de análisis de archivos, fallos en la ejecución de tareas o errores a nivel de fila no generan cargos.
    • Para tareas canceladas, las solicitudes completadas exitosamente antes de la cancelación se facturan normalmente.

Nota

  • La inferencia por lotes es un elemento de facturación separado. Admite el Plan de ahorros de propósito general de IA, pero no descuentos, como suscripción (otros planes de ahorros) o cuotas gratuitas para nuevos usuarios. Tampoco admite funciones como caché de contexto.
  • Algunos modelos, como qwen3.5-plus y qwen3.5-flash, tienen el modo de pensamiento habilitado de forma predeterminada. Este modo genera tokens de pensamiento adicionales, que se facturan al precio de tokens de salida y aumentan los costos. Para controlar los costos, establezca el parámetro enable_thinking según la complejidad de la tarea. Para más información, consulte Pensamiento profundo.

Códigos de error

Si una solicitud falla y devuelve un mensaje de error, consulte Códigos de error para obtener una solución.

FAQ

  1. ¿Cómo elijo entre Batch Chat y Batch File?

    Utilice Batch File cuando necesite procesar asincrónicamente un archivo grande que contenga muchas solicitudes. Utilice Batch Chat cuando su lógica de negocio requiera enviar sincrónicamente muchas solicitudes de conversación independientes con alta concurrencia.

  2. ¿Cómo se factura la API Batch File? ¿Necesito comprar un paquete separado?

    Batch utiliza facturación de pago por uso basada en los tokens consumidos por las solicitudes exitosas. No se requiere un paquete de recursos separado.

  3. ¿Los archivos por lotes enviados se ejecutan en orden?

    No. El sistema utiliza programación dinámica basada en la carga de cómputo y no garantiza el orden de ejecución. Las tareas pueden retrasarse cuando los recursos son limitados.

  4. ¿Cuánto tiempo tarda en completarse un archivo por lotes enviado?

    El tiempo de ejecución depende de los recursos del sistema y la escala de la tarea. Si una tarea no se completa dentro del completion_window, caduca. Las solicitudes no procesadas en tareas caducadas no se ejecutan y no generan cargos.

    Recomendaciones de escenario: Utilice llamadas en tiempo real para escenarios que requieren inferencia de modelos estrictamente en tiempo real. Utilice llamadas por lotes para escenarios de procesamiento de datos a gran escala que pueden tolerar retrasos.