Skip to main content

Batch inference

For inference scenarios that do not require real-time responses, batch inference asynchronously processes large volumes of data requests at 50% of the cost of real-time inference. Its OpenAI-compatible API is ideal for batch jobs such as model evaluation and data labeling.

How it works

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

Scope

  • China (Beijing)
  • Singapore
Supported models:
  • Text generation models
    • Qwen-Max: qwen4-max, qwen3.8-max, qwen3.7-max
    • Qwen-Plus: qwen3.7-plus, qwen3.6-plus, qwen3.5-plus, qwen-plus, qwen-plus-latest
    • Qwen-Flash: qwen3.8-flash, qwen3.7-flash, qwen3.6-flash, qwen3.5-flash, qwen-flash
    • Qwen-Long: qwen-long
  • Multimodal models
  • Embedding models: text-embedding-v1, text-embedding-v2, text-embedding-v3, text-embedding-v4, qwen3.7-text-embedding, qwen3.7-text-embedding-flash
  • In the batch scenario, the maximum number of context tokens per request is 256 K for 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. qwen3.5-omni-plus, qwen3.5-omni-flash do not support voice output.
  • Some models support thinking mode. Enabling it generates thinking tokens and increases costs.
  • The qwen3.8, qwen3.7, qwen3.6, and qwen3.5 series models have thinking mode enabled by default. When using a hybrid thinking model, explicitly set 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. Do not place it 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 thinking process content, use real-time API calls (streaming or non-streaming both work; simply set enable_thinking=true). For details, see Deep Thinking.

Use batch inference

Step 1: Prepare the input file

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

Field

Type

Required

Description

custom_id

string

Yes

A unique identifier for the request.

method

string

Yes

The 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 embedding models.

body

object

Yes

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

Sample file

You can download the sample file test_model.jsonl. The content is as follows:
{"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! How may I help you?"}]}}
{"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?"}]}}
JSONL Batch 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 of 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

# ═══════════════════════════════════════════════════════
# 配置区:修改以下内容来生成您需要的 JSONL
# ═══════════════════════════════════════════════════════

MODEL = "qwen-max"          # 选择模型(参见上方“适用范围”)
ENABLE_THINKING = False     # 是否开启思考模式(仅部分模型支持)
THINKING_BUDGET = 50        # 思考 token 预算(思考模式下生效)

# 任务列表:每个 dict 代表一条用户消息
TASKS = [
    {"role": "user", "content": "你好!请介绍一下自己。"},
    {"role": "user", "content": "What is 2+2?"},
    {"role": "user", "content": "请用Python写一个快速排序算法"},
]

# ═══════════════════════════════════════════════════════
# 以下为生成逻辑,一般无需修改
# ═══════════════════════════════════════════════════════

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  # 思考模式需开启 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:
# 多模态模型配置示例
MODEL = "qwen3-vl-plus"       # 多模态模型

# 多模态任务:content 为数组格式
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": "这些图描绘了什么内容?"}
    ]},
]

# 注意:
# - qwen3-vl-plus 不使用 system 角色,thinking_budget 设置为 500
# - 其他多模态模型包含 system 角色,thinking_budget 设置为 50
# - 思考模式需额外设置 ENABLE_THINKING = True
Embedding model request format
Embedding models use the /v1/embeddings endpoint, and the request format differs from that of text generation models. You can use the following standalone script to generate the file:
#!/usr/bin/env python3
"""向量模型 Batch JSONL 生成(使用 /v1/embeddings 接口)"""
import json

MODEL = "text-embedding-v3"  # 向量模型,可选型号参见上方“适用范围”

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, at the same level as model. The optional thinking_budget parameter sets an upper limit on the 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 place them in extra_body — extra_body is a mechanism used by the OpenAI Python SDK to pass through non-standard parameters. It is effective only in real-time inference SDK calls and does not apply to batch inference JSONL files.
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":"Hello"}]}}
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":"Please analyze the following question"}]}}

Step 2: Create a batch inference task

  1. On the Batch Inference page, click Create Batch Inference Task.
  2. In the dialog box that appears, enter a Task Name and Task Description, set the Maximum Waiting Time (1 to 14 days), and upload the JSONL file.
    You can click Download Sample File to obtain the template.
  3. When you are done, click Confirm.

Step 3: Monitor and manage tasks

  • View:
    • On the task list page, view the task's progress (processed requests/total requests) and status.
    • Search by task name or ID, or filter by workspace to quickly locate the target task.
  • Manage:
    • Cancel: Tasks in the "Executing" state can be cancelled in the Actions column.
    • Troubleshoot: For a failed task, hover over the status to view an error summary, or download the error file for details. For example, if different models are mixed in the batch file, the task will show a Failed status. Example error message: The model 'qwen-plus' for this request does not match the rest of the batch. Each batch must contain requests for a single model.

Step 4: Download results

Tasks are automatically deleted 30 days after completion. Download your results promptly.
When the task is complete, click View Results to download the output files:
  • Result file: Records all successful requests and their response results.
  • Error file (if any): Records all failed requests and their error details.
Both files contain a 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 Model Usage page, filter and view the usage statistics of batch inference.
  • View data overview: Select Time (up to 30 days), set Inference Type to Batch Inference to view the model call overview of batch inference.
  • View model details:
    • Click a model category, such as Large Language Model, to go to the details page. On the details page, Select Time (up to 30 days), set Inference Type to Batch Inference to view the call information of the models in that category.
    • Click View Details to the right of the target model to view the call details of a single model.
  • Call data of batch inference is recorded based on the task completion time. For running tasks, call information cannot be queried until the task is complete.
  • Monitoring data has a delay of one to two hours.

Use metadata to return custom identifiers

custom_id supports a maximum of 256 characters. To pass back longer identifier information in the result file, use a custom field of metadata.

Metadata fields

metadata is an optional parameter for creating a Batch task. It supports the following fields:
  • ds_name: The task name. When set, it is displayed in the Task Name column on the console.
  • ds_description: The task description. When set, it is displayed in the Task Description column on the console.
  • Custom fields: In addition to the official fields above, metadata also supports any custom fields, and the values of custom fields are not limited to 256 characters. When you query task details, all custom fields are returned in full.

Code example

The following example shows how to use a custom field of metadata to pass back identifier information longer than 256 characters:
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": "A description for my batch inference task",
        "my_custom_field": "The value of this field can exceed 256 characters and is used to pass back longer identifier information..."
    }
)
print(batch)
After a task is successfully created, you can call the task details query operation (GET /v1/batches/{batch_id}) to obtain the complete metadata information, including all custom fields and their full content.

API reference

In a production environment, use the OpenAI-compatible API to automate the creation and management of Batch tasks. The core workflow is as follows:
Batch inference supports only OpenAI-compatible API calls. When using the OpenAI Python SDK, set base_url to https://dashscope.aliyuncs.com/compatible-mode/v1. The DashScope Python SDK (the dashscope package) provides no batch inference interfaces, so you cannot submit batch inference tasks through 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 a file Call POST /v1/files to upload a file and record the returned file ID.
  2. To create a task, pass in the file ID or an OSS path, call POST /v1/batches, and 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 the output_file_id and stop polling.
  4. To download the result file, use output_file_id to call GET /v1/files/{output_file_id}/content.
For the complete Batch API definitions and code examples, see OpenAI-compatible - Batch (file input).

Task lifecycle

Status

Description

validating (validation in progress)

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

in_progress (executing)

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

finalizing (executing)

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

completed (completed)

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

failed (failed)

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

expired (terminated)

The task ran longer than the maximum waiting time set at creation and was terminated by the system. When creating a new task, consider setting a longer waiting time.

cancelled (terminated)

The user cancelled the task. Requests that have not started processing will be terminated.

Billing

  • Pricing: For all successful requests, the unit price of both input and output tokens is 50% of the real-time inference price of the corresponding model. For details, see Model list.
  • Billing scope:
    • You are billed only for the requests that are successfully executed in the task.
    • File parsing failures, task execution failures, or line-level request errors do not incur charges.
    • For a cancelled task, requests that were successfully completed before cancellation are billed normally.
  • Batch inference is a separate billable item and supports the AI Universal Savings Plan. However, it is not eligible for other promotions like prepaid plans (Savings Plans) and new user free quotas, or features like context caching.
  • Some models, such as qwen3.7-plus, qwen3.7-max, and the qwen3.6 and qwen3.5 series, have thinking mode enabled by default. This generates additional thinking tokens, which are billed at the output token price and increase costs. To control costs, set the enable_thinking parameter based on task complexity. For details, see Deep Thinking.

FAQ

  1. Do I need to purchase or enable anything extra to use batch inference? No. The feature is available after you activate Alibaba Cloud Model Studio. Charges are incurred on a pay-as-you-go basis and deducted from your account balance.
  2. Why did my task fail immediately after submission (status changed to failed)? This typically indicates a file-level error, and no inference requests were executed. Check the following in order:
    • File format: Verify that the file uses the strict JSONL format, with one complete JSON object per line.
    • File scale: Ensure the file size and number of lines do not exceed the limits. For details, see Step 1: Prepare the input file.
    • Model consistency: Check that the body.model field is identical for all requests in the file, and that the model used is supported in the current region.
  3. How long does a task take to process? Processing time mainly depends on the system load at that time. During busy periods, tasks may need to be queued. A result (success or failure) is always returned within the specified maximum waiting time.

Error codes

If a call fails and an error message is returned, see Error codes for solutions.