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.
Workflow
Prerequisites
You can call the Batch File API through the OpenAI SDK (Python, Node.js) or the HTTP API.
- Obtain an API Key: Obtain and configure your API key in environment variables
- Install the SDK (Optional): To call the API with the SDK, install the OpenAI SDK
-
Endpoints
- China (Beijing):
https://dashscope.aliyuncs.com/compatible-mode/v1 - Singapore:
https://dashscope-intl.aliyuncs.com/compatible-mode/v1
- China (Beijing):
Scope
- Singapore
- China (Beijing)
-
Text generation models
- Qwen Max: qwen3.8-max, qwen-max
- Qwen Plus: qwen3.7-plus, qwen-plus
- Qwen Flash: qwen-flash
-
Multimodal models
- Image and video understanding: qwen3.8-max, qwen3.7-plus
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 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:
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.
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:client.files.list(purpose="batch") API.Sample Code
Sample Code
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."}:
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
The Base64 strings in the examples have been omitted; use the Python code below to generate the complete encoding.
Pass a Base64-encoded string (using an image as an example)
Pass a Base64-encoded string (using an image as an example)
- Convert the local file to Base64 encoding:
-
Construct the Data URL format:
data:[MIME_type];base64,{base64_image};MIME_typemust be replaced with the actual media type, ensuring it matches the value ofMIME Type(e.g.,image/jpeg,image/png);base64_imageis the Base64 string generated in the previous step.
Usage
- Save the following code as
generate_batch_jsonl.py - Modify the request content of the
TASKSlist in the script - Run
python generate_batch_jsonl.py - The generated
batch_input.jsonlfile can be used directly for Batch inference tasks
JSONL generation script for text generation models
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:
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:
1. Modify the input file
-
You can directly modify the
test_model.jsonlfile 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/completionsText 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
modelandurlfields are correct.
2. Modify the QuickStart code
- Change the input file path to your file name
- 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, containingcustom_idandresponse.
- 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.
1. Upload files
1. Upload files
file_id.When uploading a file,purposemust bebatch.
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:client.files.list(purpose="batch") API.- OpenAI Python SDK
- OpenAI Node.js SDK
- Java(HTTP)
- curl(HTTP)
Request example
Response example
2. Create a Batch task
2. Create a Batch task
- OpenAI Python SDK
- OpenAI Node.js SDK
- Java(HTTP)
- curl(HTTP)
Request example
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 |
endpoint | String | Body | Yes | The access path, which must match the URL field in the input file.
|
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: 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: Limit: up to 200 characters. If this field is defined repeatedly, the last value passed in takes precedence. |
Response example
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 |
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. |
3. Query and manage Batch tasks
3. Query and manage Batch tasks
Query the status of a specified task
Query the status of a specified task
- OpenAI Python SDK
- OpenAI Node.js SDK
- Java(HTTP)
- curl(HTTP)
Request example
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:Field | Type | Description |
|---|---|---|
id | String | Batch task ID. |
status | String | Task status. Possible values include:
|
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. |
Query the task list
Query the task list
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
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 |
create_before | String | Query | No | Filter tasks created before this point in time, in the format |
Response example
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 Batch task
Cancel Batch task
- OpenAI Python SDK
- OpenAI Node.js SDK
- Java(HTTP)
- curl(HTTP)
Request example
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:After you cancel the task, the status first changes tocancelling, waiting for in-flight requests to complete; it eventually changes tocancelled. Results of completed requests are still saved in the output file.
4. Download the Batch result file
4. Download the Batch result file
file_id that starts with file-batch_output can be downloaded.- OpenAI Python SDK
- OpenAI Node.js SDK
- Java(HTTP)
- curl(HTTP)
content method to retrieve the content of the Batch result file, and the write_to_file method to save it locally.Request example
Response example
Response example
Single response result: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 ( |
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 |
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.
- Callback: Specify a publicly accessible URL when creating a task
- EventBridge message queue: Deeply integrated with the Alibaba Cloud ecosystem, no public IP required
Method 1: Callback
Method 1: Callback
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)
Method 2: EventBridge Message Queue
Method 2: EventBridge Message Queue
- Source:
acs.dashscope - Type:
dashscope:System:BatchTaskFinish
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_windowappropriately to provide more scheduling flexibility
Utilities
CSV to JSONL
CSV to JSONL
To change the file path or other parameters, modify the code as needed.
JSONL Results to CSV
JSONL Results to CSV
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.
- 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
- 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.
- 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.
- 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.
- 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.