Skip to main content

Batch Inference

For inference scenarios that do not require real-time responses, batch inference can asynchronously process large batches of data requests at only 50% of the cost of real-time inference, with an OpenAI-compatible API. It is ideal for batch jobs such as model evaluation and data annotation.

How it works

  1. Submit the task: Upload a JSONL file containing multiple requests to create a batch inference task.
  2. Asynchronous processing: The system processes the task in a background queue. You can query task progress and status via the console or API.
  3. Download the results: After the task is completed, the system generates a result file (recording successful responses) and an error file (recording failure details, if any).

Applicable scope

  • Singapore
  • China (Beijing)
Supported models:
  • Text generation models
    • Qwen Max: qwen3.8-max, qwen-max
    • Qwen Plus: qwen3.7-plus, qwen-plus
    • Qwen Flash: qwen-flash
  • Multi-modal models
  • In Batch scenarios, 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, and qwen3.5-omni-plus support a maximum of 256K context tokens per request. qwen3.5-omni-plus and qwen3.5-omni-flash do not support speech output.
  • Some models support thinking mode. Enabling it generates thinking tokens, which increases costs.
  • The qwen3.8, qwen3.7, qwen3.6, and qwen3.5 series models have thinking mode enabled by default. When using hybrid thinking models, we recommend explicitly setting the enable_thinking parameter (true to enable / false to disable).
  • In the JSONL request body, enable_thinking is a top-level parameter of body and must be passed at the same level as model; it cannot be placed inside extra_body.
  • Batch inference result files do not contain the reasoning_content field. Even if enable_thinking=true is set, choices[0].message in the result file contains only the content and role fields. To obtain the thinking process content, use real-time API calls (streaming or non-streaming both work; simply set enable_thinking=true). For more information, see Deep thinking.

Use batch inference

Step 1: Prepare the input file

Before creating a task, prepare a JSONL file that complies with the following specifications:
  • Format: UTF-8 encoded JSONL (one independent JSON object per line).
  • Size limits: Up to 50,000 requests and 500 MB per file.
    If your data volume exceeds these limits, split it into multiple tasks and submit them separately.
  • Per-line limit: Each JSON object must be ≤ 1 MB and must not exceed the model's context length.
  • Consistency requirement: All requests in the same file must use the same model.
  • Unique identifier: Each request must include a custom_id field that is unique within the file, used for matching results. custom_id supports up to 256 characters; exceeding this limit causes task validation to fail. To pass longer identifier information, use a custom field of metadata when creating the task. For more information, see Using metadata to return custom identifiers.
  • Media file addresses: Media files referenced via fields such as image_url and video_url in the body of multimodal requests must use publicly accessible URLs. Local file paths (such as file:///home/user/test.mp4) and intranet addresses are not supported. Tasks created with such addresses can be submitted successfully but will never be processed to completion. Upload the files to publicly accessible storage first, then reference their URLs.
Each JSON object must follow these field specifications:

Field

Type

Whether Required

Description

custom_id

string

Yes

Unique identifier of the request

method

string

Yes

HTTP method; only POST is supported

url

string

Yes

The request endpoint. Enter /v1/chat/completions for text generation and multimodal models, and /v1/embeddings for text embedding models

body

object

Yes

The request body, whose format is the same as the API corresponding to the specified url (/v1/chat/completions or /v1/embeddings)

Sample file

You can download the sample file test_model.jsonl, which contains:
{"custom_id":"1","method":"POST","url":"/v1/chat/completions","body":{"model":"qwen-max","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-max","messages":[{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":"What is 2+2?"}]}}
Batch inference JSONL file generation tool Batch inference requires constructing a JSONL file where each line is an independent request. The following Python script can be run directly to generate a JSONL file that conforms to the format.

Usage

  1. Save the following code as generate_batch_jsonl.py
  2. Modify the request content in the TASKS list in the script
  3. Run python generate_batch_jsonl.py
  4. The generated batch_input.jsonl file can be used directly for Batch inference tasks
Text generation model JSONL generation script
#!/usr/bin/env python3
"""
Batch 推理 JSONL 文件生成工具

支持的地域与模型请参见上方“适用范围”。

文件大小限制:单行 ≤6MB,总文件 ≤500MB,建议 ≤10000 行

使用方式:
  1. 修改下方 TASKS 列表
  2. 运行: python generate_batch_jsonl.py
  3. 输出: batch_input.jsonl
"""
import json

# ═══════════════════════════════════════════════════════
# Configuration: edit the following settings to generate your JSONL
# ═══════════════════════════════════════════════════════

MODEL = "qwen-max"          # Select the model (see Scope of application above)
ENABLE_THINKING = False     # Enable thinking mode (supported by some models only)
THINKING_BUDGET = 50        # Thinking token budget (effective in thinking mode)

# Task list: each dict represents a user message
TASKS = [
    {"role": "user", "content": "你好!请介绍一下自己。"},
    {"role": "user", "content": "What is 2+2?"},
    {"role": "user", "content": "请用Python写一个快速排序算法"},
]

# ═══════════════════════════════════════════════════════
# Generation logic below usually requires no changes
# ═══════════════════════════════════════════════════════

def build_request(custom_id: str, model: str, messages: list,
                  enable_thinking: bool = False, thinking_budget: int = 50) -> dict:
    """构造单条 Batch 请求"""
    body = {"model": model, "messages": messages}
    if enable_thinking:
        body["enable_thinking"] = True
        body["thinking_budget"] = thinking_budget
        body["stream"] = True  # Thinking mode requires stream
    return {
        "custom_id": custom_id,
        "method": "POST",
        "url": "/v1/chat/completions",
        "body": body
    }

def main():
    output_file = "batch_input.jsonl"
    with open(output_file, "w", encoding="utf-8") as f:
        for i, task in enumerate(TASKS, 1):
            messages = [
                {"role": "system", "content": "You are a helpful assistant."},
                task
            ]
            req = build_request(
                custom_id=f"request-{i}",
                model=MODEL,
                messages=messages,
                enable_thinking=ENABLE_THINKING,
                thinking_budget=THINKING_BUDGET
            )
            f.write(json.dumps(req, ensure_ascii=False) + "\n")
    print(f"已生成 {output_file},共 {len(TASKS)} 条请求")

if __name__ == "__main__":
    main()
Multimodal model request format
The content field of multimodal models is in array format, containing media objects and text questions. The media URLs in each request line must be of the same type (image, video, or audio). Replace TASKS in the script above with the following format:
# Multimodal model configuration example

# Multimodal task: content is an array
TASKS = [
    {"role": "user", "content": [
        {"type": "image_url", "image_url": {"url": "https://example.com/image1.jpg"}},
        {"type": "image_url", "image_url": {"url": "https://example.com/image2.jpg"}},
        {"type": "text", "text": "这些图描绘了什么内容?"}
    ]},
]

# {"type": "input_audio", "input_audio": {"data": "https://example.com/audio.wav", "format": "wav"}}
# {"type": "video_url", "video_url": "https://example.com/video.mp4"}

# Note:
# - Other multimodal models include the system role and set thinking_budget to 50
# - Thinking mode also requires ENABLE_THINKING = True
Text embedding model request format
Text embedding models use the /v1/embeddings API, and the request format differs from that of text generation models. You can use the following standalone script to generate it:
#!/usr/bin/env python3
"""文本向量模型 Batch JSONL 生成(使用 /v1/embeddings 接口)"""
import json

MODEL = "text-embedding-v3"  # Embedding model; see Scope of application above for available models

TEXTS = [
    "衣服的质量杠杠的,很漂亮,不枉我等了这么久啊,喜欢,以后还来这里买。",
    "风急天高猿啸哀",
    "The quick brown fox jumps over the lazy dog",
]

output_file = "batch_embedding.jsonl"
with open(output_file, "w", encoding="utf-8") as f:
    for i, text in enumerate(TEXTS, 1):
        req = {
            "custom_id": f"emb-{i}",
            "method": "POST",
            "url": "/v1/embeddings",
            "body": {"model": MODEL, "input": text, "encoding_format": "float"}
        }
        f.write(json.dumps(req, ensure_ascii=False) + "\n")
print(f"已生成 {output_file},共 {len(TEXTS)} 条请求")

Configure thinking mode in batch inference

Some models (such as qwen3.7-plus, qwen3.7-max, and the qwen3.6 and qwen3.5 series) have thinking mode enabled by default, which generates additional thinking tokens. To configure thinking mode in batch inference, set the enable_thinking parameter in the body of each request line in the JSONL file, placing it at the same level as model. The optional parameter thinking_budget is used to limit the maximum number of thinking tokens.
enable_thinking and thinking_budget must be placed directly at the top level of body (at the same level as model). Do not put them into extra_body — extra_body is a mechanism used by the OpenAI Python SDK to pass through non-standard parameters, which only works in SDK calls for real-time inference and does not apply to JSONL files for batch inference.
Example: Disable thinking mode
{"custom_id":"request-1","method":"POST","url":"/v1/chat/completions","body":{"model":"qwen3.5-plus","enable_thinking":false,"messages":[{"role":"user","content":"你好"}]}}
Example: Enable thinking mode and limit the thinking token budget
{"custom_id":"request-2","method":"POST","url":"/v1/chat/completions","body":{"model":"qwen3.5-plus","enable_thinking":true,"thinking_budget":50,"messages":[{"role":"user","content":"请分析以下问题"}]}}

Step 2: Create a batch inference task

  1. On the **Batch inference** page, click Create Batch.
  2. In the dialog box that appears: enter the Task Name and Task Description, set the Maximum Waiting Time (1–14 days), and upload a JSONL file.
    You can click Download Sample File to get a template.
  3. After completing the form, click Confirm.

Step 3: Monitor and manage tasks

  • View:
    • On the Tasks page, view the progress (number of processed requests/total number of requests) and status of a task.
    • Search by task name or ID, or filter by workspace to quickly locate the target task.
  • Manage:
    • Cancel: tasks in the "Running" state can be canceled in the Actions column.

Step 4: Download the results

Tasks are automatically deleted 30 days after completion. Download the results in a timely manner.
After a task is completed, click View Results to download the output files:
  • Results file: records all successful requests and their response results.
  • Error file (if any): records all failed requests and their error details.
Both files contain the custom_id field, which is used to match the original input data, associate results, or locate errors.

Step 5: View usage statistics (Optional)

On the Monitoring page, filter and view the usage statistics of batch inference.
  • View data overview: select a time (up to 30 days), set Inference Type to Batch Inference, and you can view:
    • Monitoring Data: Summary statistics of all models within the time period, such as total number of calls and total number of failures.
    • Models: Detailed data of each model, such as total calls, failure rate, and average call duration.
    To view inference data from more than 30 days ago, go to the Bill page.
  • View model details: In the Models list, click Monitoring in the Actions column of the target model to view Call Statistics details (such as number of calls and call volume).
    image
  • Call data of batch inference is counted based on the task end time. For tasks that are running, the call information cannot be queried until the task is completed.
  • Monitoring data has a 1 to 2 hour delay.

Use metadata to return custom identifiers

custom_id supports up to 256 characters. To return longer identifier information in the result file, you can use the custom fields of metadata.

metadata fields

metadata is an optional parameter when creating a Batch task and supports the following fields:
  • ds_name: Task name. Once set, it is displayed in the Task Name column of the console.
  • ds_description: Task description. Once set, it is displayed in the Task Description column of the console.
  • Custom fields: In addition to the official fields above, metadata also supports arbitrary custom fields, and the values of custom fields are not subject to the 256-character limit. When you query task details, all custom fields are returned in full.

Sample Code

The following example shows how to return identifier information longer than 256 characters through the custom fields of metadata:
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)

batch = client.batches.create(
    input_file_id="file-batch-xxxxxxxxxxxxxxxxxxxx",
    endpoint="/v1/chat/completions",
    completion_window="24h",
    metadata={
        "ds_name": "my_batch_task",
        "ds_description": "批量推理任务描述",
        "my_custom_field": "此字段的值可以超过256个字符,用于回传更长的标识信息..."
    }
)
print(batch)
After the task is created, you can call the task details query API (GET /v1/batches/{batch_id}) to obtain the complete metadata information, including all custom fields and their full content.

API Reference

In production environments, use OpenAI-compatible APIs to create and manage Batch tasks automatically. The core workflow is as follows:
Batch inference only supports API calls in OpenAI-compatible format. When using the OpenAI Python SDK, set base_url to https://dashscope.aliyuncs.com/compatible-mode/v1. The DashScope Python SDK (the dashscope package) does not provide batch inference interfaces, so batch inference tasks cannot be submitted via dashscope.BatchInference, dashscope.Batches, or similar methods.
Example:
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
batch = client.batches.create(
    input_file_id=file_id,
    endpoint="/v1/chat/completions",
    completion_window="24h",
)
  1. Upload File Call POST /v1/files to upload the file and record the returned file ID.
  2. Create Task Pass in the file ID and call POST /v1/batches to create a task, then record the returned batch_id.
  3. Poll the status Use batch_id to poll GET /v1/batches/{batch_id}. When status changes to completed, record output_file_id and stop polling.
  4. Download results Use output_file_id to call GET /v1/files/{output_file_id}/content to download the result file.
For the complete Batch API definitions and sample code, see OpenAI-compatible Batch (file input).

Task lifecycle

Status

Description

validating (Verifying)

The system is validating the file format (JSONL specification) and the API format validity of each request line.

in_progress (Running)

The file has passed validation, and the system has started processing inference requests line by line.

finalizing (Running)

All requests have been processed, and the results are being written to the result file and the error file respectively. In the console task list, this stage shares the Running status label with in_progress and has no separate display text.

completed (Completed)

The result file and error file have been written and are ready for download.

failed

The task failed during the validating stage, usually due to file-level errors (such as invalid JSONL format or oversized files). In this state, no inference requests are executed and no result file is generated.

expired

The task's running time exceeded the maximum waiting time set at creation and was terminated by the system. When creating a new task, we recommend setting a longer waiting time.

cancelled

The user cancels the task, and requests that have not started processing will be terminated.

Billing Details

  • Billing unit price: For all successful requests, the unit price of both input and output tokens is 50% of the corresponding model's real-time inference price. For more information, see Models.
  • Billing scope:
    • Only requests that are successfully executed in the task are billed.
    • File parsing failed, failed task execution, or row-level erroneous requests incur no fees.
    • For cancelled tasks, requests that were successfully completed before cancellation are still billed normally.
  • Batch inference is an independent billing item. It supports the AI Universal Savings Plan, but does not support discounts such as upfront (savings plan) and new-user free quota, or features such as context cache.
  • Some models (such as qwen3.7-plus, qwen3.7-max, and the qwen3.6 and qwen3.5 series) have thinking mode enabled by default, which generates additional thinking tokens billed at the output token price, increasing costs. We recommend setting the enable_thinking parameter based on task complexity to control costs. For more information, see deep thinking.

FAQ

  1. Do I need to make an additional purchase or activation to use batch inference? No. You can use it once Alibaba Cloud Model Studio is activated, and fees are deducted from your account balance under the pay-as-you-go model.
  2. Why does a task fail immediately after submission (status changes to failed)? This is usually caused by file-level errors, and the task has not executed any inference requests. Troubleshoot in the following order:
    • File format: Is it strict JSONL format, with one complete JSON object per line?
    • File size: Do the file size, number of lines, etc. exceed the limits? For more information, see Prepare input files.
    • Model consistency: Check that the body.model field of all requests in the file is exactly the same, and that the models used are supported in the current region.
  3. How long does task processing take? Processing time mainly depends on the system load at the time. When the system is busy, tasks may need to queue, but the results, whether success or failure, will be returned within the set maximum waiting time.

Error codes

If a call fails and returns an error message, see Error codes for troubleshooting.