Skip to main content

OpenAI-compatible Batch (File input)

Alibaba Cloud Model Studio provides an OpenAI-compatible Batch File API that supports submitting requests in batches through files. The system processes all requests asynchronously and returns the results after all requests are completed or the maximum waiting time is reached. Fees are only 50% of real-time calls. This is suitable for scenarios such as data analysis and model evaluation that are not time-sensitive but require large-scale processing.

To use the console, see Batch inference.

Workflow

image

Prerequisites

You can call the Batch File API through the OpenAI SDK (Python, Node.js) or the HTTP API.

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
  • Multimodal 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. When enabled, thinking tokens are generated, which 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, 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 in extra_body.

QuickStart

Before processing production tasks, use the test model batch-test-model for an end-to-end test. This model skips the inference process and directly returns a fixed success response, which is used to verify that the API call chain and data format are correct.
Test model (batch-test-model) limitations:
  • Test files must meet the input file requirements, with a file size no larger than 1 MB and no more than 100 lines.
  • Concurrency limit: up to 2 concurrent tasks.
  • Fees: the test model does not incur model inference fees.

Step 1: Prepare the input file

Prepare a file named test_model.jsonl with the following content:
{"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":"你好!有什么可以帮助你的吗?"}]}}
{"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?"}]}}
Input via Base64 encoding:

Step 2: Run the code

Based on the programming language you use, select one of the following sample code examples, save it to the same directory as the input file, and then run it. The code covers the complete workflow: uploading the file, creating a task, polling the status, and downloading the results.
To change the file path or other parameters, modify the code as needed.
Reuse an existing file ID: The ID returned after file upload (such as file-batch-xxx) can be reused. If the input content is unchanged, there is no need to upload it again each time; you can directly create a task with the existing ID:
batch = client.batches.create(
    input_file_id="file-batch-xxx",  # Use the existing file ID without uploading again
    endpoint="/v1/chat/completions",
    completion_window="24h"
)
You can query uploaded Batch file IDs via the client.files.list(purpose="batch") API.
OpenAI Python SDK
import os
from pathlib import Path
from openai import OpenAI
import time

# Initialize the client
client = OpenAI(
    # If the environment variable is unset, insert your Model Studio API key: api_key="sk-xxx". Avoid hardcoding API keys in production to reduce the risk of key exposure.
    # Singapore and Beijing use different API keys.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore base_url. For a Beijing model, use https://dashscope.aliyuncs.com/compatible-mode/v1
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1"  # Model Studio service base_url
)

def upload_file(file_path):
    print(f"正在上传包含请求信息的JSONL文件...")
    file_object = client.files.create(file=Path(file_path), purpose="batch")
    print(f"文件上传成功。得到文件ID: {file_object.id}\n")
    return file_object.id

def create_batch_job(input_file_id):
    print(f"正在基于文件ID,创建Batch任务...")
    # endpoint must match the url field in the input file: /v1/chat/ds-test for batch-test-model, /v1/embeddings for embedding models, and /v1/chat/completions for other models
    batch = client.batches.create(input_file_id=input_file_id, endpoint="/v1/chat/ds-test", completion_window="24h")
    print(f"Batch任务创建完成。 得到Batch任务ID: {batch.id}\n")
    return batch.id

def check_job_status(batch_id):
    print(f"正在检查Batch任务状态...")
    batch = client.batches.retrieve(batch_id=batch_id)
    print(f"Batch任务状态: {batch.status}\n")
    return batch.status

def get_output_id(batch_id):
    print(f"正在获取Batch任务中执行成功请求的输出文件ID...")
    batch = client.batches.retrieve(batch_id=batch_id)
    print(f"输出文件ID: {batch.output_file_id}\n")
    return batch.output_file_id

def get_error_id(batch_id):
    print(f"正在获取Batch任务中执行错误请求的输出文件ID...")
    batch = client.batches.retrieve(batch_id=batch_id)
    print(f"错误文件ID: {batch.error_file_id}\n")
    return batch.error_file_id

def download_results(output_file_id, output_file_path):
    print(f"正在打印并下载Batch任务的请求成功结果...")
    content = client.files.content(output_file_id)
    # Print part of the contents for testing
    print(f"打印请求成功结果的前1000个字符内容: {content.text[:1000]}...\n")
    # Save the result file locally
    content.write_to_file(output_file_path)
    print(f"完整的输出结果已保存至本地输出文件result.jsonl\n")

def download_errors(error_file_id, error_file_path):
    print(f"正在打印并下载Batch任务的请求失败信息...")
    content = client.files.content(error_file_id)
    # Print part of the contents for testing
    print(f"打印请求失败信息的前1000个字符内容: {content.text[:1000]}...\n")
    # Save the error file locally
    content.write_to_file(error_file_path)
    print(f"完整的请求失败信息已保存至本地错误文件error.jsonl\n")

def main():
    # File path
    input_file_path = "test_model.jsonl"  # Replace with your input file path
    output_file_path = "result.jsonl"  # Replace with your output file path
    error_file_path = "error.jsonl"  # Replace with your error file path
    try:
        # Step 1: Upload the JSONL request file to obtain the input file ID
        input_file_id = upload_file(input_file_path)
        # Step 2: Create a Batch task using the input file ID
        batch_id = create_batch_job(input_file_id)
        # Step 3: Check the Batch task status until it finishes
        status = ""
        while status not in ["completed", "failed", "expired", "cancelled"]:
            status = check_job_status(batch_id)
            print(f"等待任务完成...")
            time.sleep(10)  # Wait 10 seconds before checking the status again
        # Print the error and exit if the task fails
        if status == "failed":
            batch = client.batches.retrieve(batch_id)
            print(f"Batch任务失败。错误信息为:{batch.errors}\n")
            print(f"参见错误码文档: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code")
            return
        # Step 4: Download results: if the output file ID is nonempty, print the first 1000 characters of successful results and download the complete results to the local output file
        # If the error file ID is nonempty, print the first 1000 characters of error information and download the complete errors to the 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"参见错误码文档: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code")
    except Exception as e:
        print(f"An error occurred: {e}")
        print(f"参见错误码文档: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code")

if __name__ == "__main__":
    main()

Step 3: Verify the test result

After the task completes successfully, the result file result.jsonl contains the fixed response {"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}

Run formal tasks

Input file requirements

  • Format: UTF-8 encoded JSONL (one independent JSON object per line)
  • Size limits: At most 50,000 requests per file, and no more than 500 MB
  • Per-line limits: Each JSON object must not exceed 6 MB, and must not exceed the model context length
  • Consistency requirements: All requests in the same file must use the same model and thinking mode (if applicable)
  • Unique identifier: Each request must contain a custom_id field that is unique within the file, used to match requests with results
Scenario 1: Text chat Sample file content:
{"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?"}]}}
Scenario 2: Image and video understanding Base64-encoded input method.
The Base64 strings in the examples have been omitted; use the Python code below to generate the complete encoding.
  1. Convert the local file to Base64 encoding:
#  Encoding function: convert a local file to a Base64 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 xxxx/eagle.png with the absolute path to your local image
base64_image = encode_image("xxx/eagle.png")
  1. Construct the Data URL format: data:[MIME_type];base64,{base64_image};
    1. MIME_type must be replaced with the actual media type, ensuring it matches the value of MIME Type (e.g., image/jpeg, image/png);
    2. base64_image is the Base64 string generated in the previous step.
For complete details (including file limits, MIME types, and encoding methods), see Pass local files (Base64-encoded or file path).
Batch inference JSONL file generation tool Batch inference requires constructing a JSONL file, with each line being 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

JSONL generation script for text generation models

#!/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

For multimodal models, the content field is in array format, containing media objects and text prompts. 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 their 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)} 条请求")

1. Modify the input file

  • You can directly modify the test_model.jsonl file used for testing, set the model parameter to the target formal model, and set the URL field:

    Model Type

    url

    Text generation/multimodal models

    /v1/chat/completions

    Text embedding models

    /v1/embeddings

  • Alternatively, use the "JSONL batch generation tool" above to generate a new file for the formal task. The key is to ensure that the model and url fields are correct.

2. Modify the QuickStart code

  1. Change the input file path to your file name
  2. Change the endpoint parameter value to the value consistent with the url field in the input file

3. Run the code and wait for the results

After the task is completed, the results of successful requests are saved in the local result.jsonl file. If any request fails, the error details are saved in the error.jsonl file.
  • Successful results (output_file_id): each line corresponds to one successful original request, containing custom_id and 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":"你好!杭州西湖是中国著名的风景名胜区,位于浙江省杭州市西部,因此得名“西湖”。它是中国十大风景名胜之一,也是世界文化遗产(2011年被联合国教科文组织列入《世界遗产名录》),以其秀丽的自然风光与深厚的人文底蕴闻名于世。\n\n### 一、自然景观\n西湖三面环山,一面邻城,湖面面积约6.39平方公里,形似如意,碧波荡漾。湖中被孤山、白堤、苏堤、杨公堤等自然或人工分隔成多个水域,形成“一山二塔三岛三堤”的格局。\n\n主要景点包括:\n- **苏堤春晓**:北宋大文豪苏东坡任杭州知州时主持疏浚西湖,用挖出的淤泥堆筑成堤,后人称为“苏堤”。春天桃红柳绿,景色如画。\n- **断桥残雪**:位于白堤东端,是白蛇传中“断桥相会”的发生地,冬日雪后银装素裹,尤为著名。\n- **雷峰夕照**:雷峰塔在夕阳映照下金光熠熠,曾是“西湖十景”之一。\n- **三潭印月**:湖中小瀛洲上的三座石塔,中秋夜可在塔内点灯,月影、灯光、湖光交相辉映。\n- **平湖秋月**:位于白堤西端,是观赏湖上明月的绝佳地点。\n- **花港观鱼**:以赏花和观鱼著称,园内牡丹、锦鲤相映成趣。\n\n### 二、人文历史\n西湖不仅风景优美,还承载着丰富的历史文化:\n- 自唐宋以来,众多文人墨客如白居易、苏东坡、林逋、杨万里等在此留下诗篇。\n- 白居易曾主持修建“白堤”,疏浚西湖,造福百姓。\n- 西湖周边有众多古迹,如岳王庙(纪念民族英雄岳飞)、灵隐寺(千年古刹)、六和塔、龙井村(中国十大名茶龙井茶的产地)等。\n\n### 三、文化象征\n西湖被誉为“人间天堂”的代表,是中国传统山水美学的典范。它融合了自然美与人文美,体现了“天人合一”的哲学思想。许多诗词、绘画、戏曲都以西湖为题材,成为中国文化的重要符号。\n\n### 四、旅游建议\n- 最佳游览季节:春季(3-5月)桃红柳绿,秋季(9-11月)天高气爽。\n- 推荐方式:步行、骑行(环湖绿道)、乘船游湖。\n- 周边美食:西湖醋鱼、龙井虾仁、东坡肉、片儿川等。\n\n总之,杭州西湖不仅是一处自然美景,更是一座活着的文化博物馆,值得细细品味。如果你有机会到杭州,一定不要错过这个“淡妆浓抹总相宜”的人间仙境。"}}],"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":"春风拂柳绿,  \n夜雨润花红。  \n鸟语林间闹,  \n山川处处同。"}}],"object":"chat.completion"}},"error":null}
  • Failed request details (error_file_id): contain the information of the request lines that failed to be processed and the error causes. Refer to Error codes for troubleshooting.

Detailed Process

The Batch API workflow consists of four steps: upload files, create tasks, query task status, and download results.
Before creating a Batch task, upload a JSONL file that meets the format requirements through the file upload API to obtain the file_id.
When uploading a file, purpose must be batch.
Reuse an existing file ID: The ID returned after file upload (such as file-batch-xxx) can be reused. If the input content is unchanged, there is no need to upload it again each time; you can directly create a task with the existing ID:
batch = client.batches.create(
    input_file_id="file-batch-xxx",  # Use the existing file ID without uploading again
    endpoint="/v1/chat/completions",
    completion_window="24h"
)
You can query uploaded Batch file IDs via the client.files.list(purpose="batch") API.
  • OpenAI Python SDK
  • OpenAI Node.js SDK
  • Java(HTTP)
  • curl(HTTP)

Request example

import os
from pathlib import Path
from openai import OpenAI

client = OpenAI(
    # If the environment variable is unset, insert your Model Studio API key: api_key="sk-xxx". Avoid hardcoding API keys in production to reduce the risk of key exposure.
    # Singapore and Beijing use different API keys.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore base_url. For a Beijing model, use https://dashscope.aliyuncs.com/compatible-mode/v1
    # Note: Change the API key when switching regions
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)

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

print(file_object.model_dump_json())

Response example

{
    "id": "file-batch-xxx",
    "bytes": 437,
    "created_at": 1742304153,
    "filename": "test.jsonl",
    "object": "file",
    "purpose": "batch",
    "status": "processed",
    "status_details": null
}
Use the file ID returned by the file upload to create a Batch task.
  • OpenAI Python SDK
  • OpenAI Node.js SDK
  • Java(HTTP)
  • curl(HTTP)

Request example

import os
from openai import OpenAI

client = OpenAI(
    # If the environment variable is unset, insert your Model Studio API key: api_key="sk-xxx". Avoid hardcoding API keys in production to reduce the risk of key exposure.
    # Singapore and Beijing use different API keys.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore base_url. For a Beijing model, use https://dashscope.aliyuncs.com/compatible-mode/v1
    # Note: Change the API key when switching regions
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)

batch = client.batches.create(
    input_file_id="file-batch-xxx",  # id returned by the file upload
    endpoint="/v1/chat/completions",  # # Use /v1/chat/ds-test for batch-test-model, /v1/embeddings for text embedding models, and /v1/chat/completions for text generation/multimodal models
    completion_window="24h",
    metadata={'ds_name':"任务名称",'ds_description':'任务描述'} # Optional metadata for the task name and description
)
print(batch)

Input Parameters

Field

Type

Pass parameter

method

Required

Description

input_file_id

String

Body

Yes

Specifies the file ID used as the input file for the Batch task.

Use the file ID returned by the Prepare and upload files interface, such as file-batch-xxx.

endpoint

String

Body

Yes

The access path, which must match the URL field in the input file.

  • For the test model batch-test-model, enter /v1/chat/ds-test

  • For other models, enter /v1/chat/completions

completion_window

String

Body

Yes

The waiting time, minimum 24h and maximum 336h; only integers are supported.

Supports two units: "h" and "d", such as "24h" or "14d".

metadata

Map

Body

No

Task extension metadata for attaching additional information as key-value pairs.

metadata.ds_name

String

Body

No

Task name.

Example: "ds_name": "Batch task"

Limit: up to 100 characters.

If this field is defined repeatedly, the last value passed in takes precedence.

metadata.ds_description

String

Body

No

Task description.

Example: "ds_description": "Batch inference task test"

Limit: up to 200 characters.

If this field is defined repeatedly, the last value passed in takes precedence.

Response example

{
    "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": "任务名称",
        "ds_description": "任务描述"
    }
}

Response parameters

Field

Type

Description

id

String

The ID of the Batch task created this time.

object

String

The object type, with a fixed value of batch.

endpoint

String

The access path.

errors

Map

The error message.

input_file_id

String

The file ID.

completion_window

String

The waiting time. The minimum waiting time is 24h and the maximum is 336h; only integers are supported.

Supports two units: "h" and "d", such as "24h" or "14d".

status

String

The task status. Possible values: validating, failed, in_progress, finalizing, completed, expired, cancelling, cancelled.

output_file_id

String

The output file ID for successful requests.

error_file_id

String

The error file ID for failed requests.

created_at

Integer

Unix timestamp (in seconds) when the task was created.

in_progress_at

Integer

Unix timestamp (in seconds) when the task started running.

expires_at

Integer

Unix timestamp (in seconds) when the task is expected to expire.

finalizing_at

Integer

Unix timestamp (in seconds) when the task started aggregating results.

completed_at

Integer

Unix timestamp (in seconds) when the task was completed.

failed_at

Integer

Unix timestamp (in seconds) when the task failed.

expired_at

Integer

Unix timestamp (in seconds) when the task expired.

cancelling_at

Integer

Unix timestamp (in seconds) when the task started being cancelled.

cancelled_at

Integer

Unix timestamp (in seconds) when the task cancellation was completed.

request_counts

Map

Statistics of request counts by status.

metadata

Map

Additional metadata in key-value pairs.

metadata.ds_name

String

Task name.

metadata.ds_description

String

Task description.

After a task is created, you can use the following API operations to query its status, list historical tasks, or cancel in-progress tasks.
Pass in a Batch task ID to query the details of a specified task. Currently, only Batch tasks created within the last 30 days can be queried.
  • OpenAI Python SDK
  • OpenAI Node.js SDK
  • Java(HTTP)
  • curl(HTTP)

Request example

import os
from openai import OpenAI

client = OpenAI(
    # If the environment variable is unset, insert your Model Studio API key: api_key="sk-xxx". Avoid hardcoding API keys in production to reduce the risk of key exposure.
    # Singapore and Beijing use different API keys.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore base_url. For a Beijing model, use https://dashscope.aliyuncs.com/compatible-mode/v1
    # Note: Change the API key when switching regions
    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)

Response example

After a successful query, the details of the Batch task are returned. The following is a response example for a task in the completed state:
{
  "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"
  }
}
The returned JSON object contains the complete information of the Batch task, including the task status, output file ID, request statistics, and more. See the table below for field descriptions.

Field

Type

Description

id

String

Batch task ID.

status

String

Task status. Possible values include:

  • validating: The input file is being validated

  • in_progress: The task is being processed

  • finalizing: Processing is complete and the output file is being generated

  • completed: The task completed successfully

  • failed: The task failed due to a critical error

  • expired: The task expired because it was not completed within the completion_window

  • cancelling: The task is being cancelled

  • cancelled: The task has been cancelled

output_file_id

String

The ID of the success result file, generated after the task is completed.

error_file_id

String

The ID of the failure result file, generated when the task is completed and there are failed requests.

request_counts

Object

The request count statistics object, containing the total, completed, and failed fields.

You can use the batches.list() method to query the list of Batch tasks and retrieve the complete task list progressively through pagination.
  • OpenAI Python SDK
  • OpenAI Node.js SDK
  • Java(HTTP)
  • curl(HTTP)

Request example

import os
from openai import OpenAI

client = OpenAI(
    # If the environment variable is unset, insert your Model Studio API key: api_key="sk-xxx". Avoid hardcoding API keys in production to reduce the risk of key exposure.
    # Singapore and Beijing use different API keys.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore base_url. For a Beijing model, use https://dashscope.aliyuncs.com/compatible-mode/v1
    # Note: Change the API key when switching regions
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
batches = client.batches.list(after="batch_xxx", limit=2,extra_query={'ds_name':'任务名称','input_file_ids':'file-batch-xxx,file-batch-xxx','status':'completed,expired','create_after':'20250304000000','create_before':'20250306123000'})
print(batches)

Input Parameters

Field

Type

Passing Method

Required

Description

after

String

Query

No

The cursor used for pagination, whose value is the ID of the last task on the previous page.

limit

Integer

Query

No

The number of tasks returned per page, range [1, 100], default 20.

ds_name

String

Query

No

Fuzzy match by task name.

input_file_ids

String

Query

No

Filter by file ID. Multiple IDs are separated by commas, up to 20.

status

String

Query

No

Filter by task status. Multiple statuses are separated by commas.

create_after

String

Query

No

Filter tasks created after this point in time, in the format yyyyMMddHHmmss.

create_before

String

Query

No

Filter tasks created before this point in time, in the format yyyyMMddHHmmss.

Response example

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

Response parameters

Field

Type

Description

object

String

The type, with a fixed value of list.

data

Array

The Batch task object. See the response parameters of creating a Batch task.

first_id

String

The ID of the first Batch task on the current page.

last_id

String

The ID of the last Batch task on the current page.

has_more

Boolean

Whether there is a next page.

Cancel a task that is in progress or queued. After a successful call, the task status changes to cancelling and eventually to cancelled. Before the task is fully cancelled, the completed portion is still billed.
  • OpenAI Python SDK
  • OpenAI Node.js SDK
  • Java(HTTP)
  • curl(HTTP)

Request example

import os
from openai import OpenAI

client = OpenAI(
    # If the environment variable is unset, insert your Model Studio API key: api_key="sk-xxx". Avoid hardcoding API keys in production to reduce the risk of key exposure.
    # Singapore and Beijing use different API keys.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore base_url. For a Beijing model, use https://dashscope.aliyuncs.com/compatible-mode/v1
    # Note: Change the API key when switching regions
    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)

Response example

After the task is successfully canceled, the details of the Batch task are returned. The following is a response example in the cancelling state:
{
  "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
}
After you cancel the task, the status first changes to cancelling, waiting for in-flight requests to complete; it eventually changes to cancelled. Results of completed requests are still saved in the output file.
After the task finishes, a result file (output_file_id) and possibly an error file (error_file_id) are generated; both are obtained through the same file download API.Only the file corresponding to the file_id that starts with file-batch_output can be downloaded.
  • OpenAI Python SDK
  • OpenAI Node.js SDK
  • Java(HTTP)
  • curl(HTTP)
You can use the content method to retrieve the content of the Batch result file, and the write_to_file method to save it locally.

Request example

import os
from openai import OpenAI

client = OpenAI(
    # If the environment variable is unset, insert your Model Studio API key: api_key="sk-xxx". Avoid hardcoding API keys in production to reduce the risk of key exposure.
    # Singapore and Beijing use different API keys.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore base_url. For a Beijing model, use https://dashscope.aliyuncs.com/compatible-mode/v1
    # Note: Change the API key when switching regions
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
content = client.files.content(file_id="file-batch_output-xxx")
# Print the result file contents
print(content.text)
# Save the result file locally
content.write_to_file("result.jsonl")

Response example

{"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":"你好!当然可以。无论是需要信息查询、学习资料、解决问题的方法,还是其他任何帮助,我都在这里为你提供支持。请告诉我你需要什么方面的帮助?"}}],"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}

Response example

Single response result:
{
    "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": "你好!当然可以。无论是需要信息查询、学习资料、解决问题的方法,还是其他任何帮助,我都在这里为你提供支持。请告诉我你需要什么方面的帮助?"
                    }
                }
            ],
            "object": "chat.completion"
        }
    },
    "error": null
}

Response parameters

Field

Type

Description

id

String

Request ID.

custom_id

String

User-defined ID.

response

Object

Request result.

status_code

Integer

Status code. 200 indicates a successful request.

request_id

String

The unique ID generated by the server for this request.

completion_tokens

Integer

The number of tokens consumed by the model-generated reply content (completion).

prompt_tokens

Integer

The number of tokens consumed by the input content (prompt) sent to the model.

total_tokens

Integer

The total number of tokens consumed by this call.

model

String

The name of the model used by this call.

error

Object

The error message object. If the API call succeeds, this value is null. If an error occurs, it contains the error code and detailed error message.

error.code

String

Error row information and error causes. Refer to error codes for troubleshooting.

error.message

String

The error message.

Advanced Features

Configure Task Completion Notifications

Polling long-running tasks consumes unnecessary resources. We recommend configuring asynchronous notifications so that the system proactively notifies you when a task completes.
The task completion notification feature is only supported in the Beijing region.
  • Callback: Specify a publicly accessible URL when creating a task
  • EventBridge message queue: Deeply integrated with the Alibaba Cloud ecosystem, no public IP required
Specify a publicly accessible URL via metadata when creating a task. After the task completes, the system sends a POST request containing the task status to that URL:
  • OpenAI Python SDK
  • curl(HTTP)
import os
from openai import OpenAI

client = OpenAI(
    # If the environment variable is unset, insert your Model Studio API key: api_key="sk-xxx". Avoid hardcoding API keys in production to reduce the risk of key exposure.
    # Singapore and Beijing use different API keys.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Beijing base_url. For a Singapore model, use https://dashscope-intl.aliyuncs.com/compatible-mode/v1
    # Note: Change the API key when switching regions
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)

batch = client.batches.create(
    input_file_id="file-batch-xxx",  # id returned by the file upload
    endpoint="/v1/chat/completions",  # Use "/v1/embeddings" for embedding models, /v1/chat/ds-test for batch-test-model, and /v1/chat/completions for other models
    completion_window="24h",
    metadata={
            "ds_batch_finish_callback": "https://xxx/xxx"
          }
)
print(batch)
This method does not require a public IP and is suitable for scenarios where you integrate with other Alibaba Cloud services (such as Function Compute and RocketMQ).When a batch task completes, the system sends an event to Alibaba Cloud EventBridge. You can configure EventBridge rules to listen for this event and route it to a specified target.
  • Source: acs.dashscope
  • Type: dashscope:System:BatchTaskFinish
Related documentation: Routing to Message Queue for Apache RocketMQ.

Going Live

  • File management
    • Periodically call the OpenAI-File delete file API to delete unneeded files and avoid reaching the file storage limit (10,000 files or 100 GB)
    • For large files, we recommend storing them in Alibaba Cloud OSS
  • Task monitoring
    • Prefer Callback or EventBridge asynchronous notifications
    • Use a polling interval > 1 minute with an exponential backoff strategy
  • Error handling
    • Implement a complete exception handling mechanism covering network errors, API errors, and more
    • Download and analyze the error details in error_file_id
    • For common error codes, refer to error codes to resolve them
  • Cost optimization
    • Merge small tasks into a single batch
    • Set completion_window appropriately to provide more scheduling flexibility

Utilities

When your raw data is stored in a CSV file (first column as ID, second column as content), you can use the following script to quickly generate the JSONL file required for batch tasks.
To change the file path or other parameters, modify the code as needed.
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])}
            # Use "/v1/embeddings" for embedding models and /v1/chat/completions for other models
            request = {"custom_id": row[0], "method": "POST", "url": "/v1/chat/completions", "body": body}
            fout.write(json.dumps(request, separators=(',', ':'), ensure_ascii=False) + "\n")
Use the following script to parse the result.jsonl file into a result.csv file that is easy to analyze in Excel.
To change the file path or other parameters, modify the code as needed.
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)
Fixing garbled characters in Excel
  • Use a text editor (such as Sublime) to convert the CSV file encoding to GBK, and then open it in Excel.
  • Or create a new file in Excel and specify the correct encoding format (UTF-8) when importing the data.

API rate limits

API

Rate limit (primary account level)

Create Task

1000 times/minute, up to 1000 concurrent tasks

Query task

1000 times/minute

Query the task list

100 times/minute

Cancel Task

1000 times/minute

Billing details

  • Unit price: 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 more information, see Models.
  • Billing scope:
    • Only successfully executed requests are billed.
    • File parsing failed, task execution failures, and row-level error requests incur no fees.
    • For canceled tasks, requests that were successfully completed before cancellation are still billed normally.
  • Batch inference is a separate billing item. It supports the AI universal savings plan, but does not support upfront (savings plan) or new user free quota discounts, or features such as context cache.
  • Some models (such as qwen3.5-plus and qwen3.5-flash) have thinking mode enabled by default, which generates additional thinking tokens billed at the output token price and increases costs. We recommend setting the enable_thinking parameter based on task complexity to control costs. For more information, see deep thinking.

Error codes

If a call fails, see error codes for troubleshooting.

FAQ

  1. How do I choose between Batch Chat and Batch File? Choose Batch File when processing a single large file that contains a large number of requests and retrieving results asynchronously. Choose Batch Chat when you need to submit a large number of independent conversation requests at high concurrency through synchronous API calls.
  2. How is Batch File usage billed? Do I need to purchase it separately? Batch is a calling method that uses a pay-as-you-go model and is billed based on the token usage of successful requests, so you do not need to purchase additional packages.
  3. Are submitted Batch Files executed in order? No. The system uses a dynamic scheduling mechanism to arrange task execution based on compute resource load and does not guarantee strict adherence to the submission order. When resources are tight, task startup and execution may be delayed.
  4. How long does it take for a submitted Batch File to complete? The execution time depends on system resource allocation and task scale. If a task is not completed within the specified completion_window, its status changes to expired, and unprocessed requests are no longer executed and incur no fees. Scenario recommendations: For scenarios with strict timeliness requirements, we recommend using real-time calls. For large-scale data processing scenarios with some tolerance for latency, we recommend using Batch calls.