Alibaba Cloud Model Studio provides an OpenAI-compatible Batch File API. Submit requests in bulk through files. The system processes them asynchronously and returns results when all requests complete or the maximum wait time is reached. Costs are only 50% of real-time calls. Ideal for data analytics, model evaluation, and other large-scale workloads where latency is not critical.
Workflow
Prerequisites
You can call the Batch File API through the OpenAI SDK (Python, Node.js) or HTTP API.
- Get an API Key: Get and configure your Model Studio API Key as an environment variable
- Install SDK (optional): Install the OpenAI SDK if you plan to use it.
-
Service endpoints
- North China 2 (Beijing):
https://dashscope.aliyuncs.com/compatible-mode/v1 - Singapore:
https://dashscope-intl.aliyuncs.com/compatible-mode/v1
- North China 2 (Beijing):
Scope
- Singapore
- China (Beijing)
Getting started
Before processing formal tasks, test with the batch-test-model. This test model skips inference and returns a fixed success response, allowing you to verify your API call chain and data format.
- Your test file must meet Input file requirements. Maximum size: 1 MB. Maximum lines: 100.
- Concurrency limit: Up to 2 parallel tasks.
- Cost: 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
Select a code snippet for your programming language. Save it in the same directory as your input file and run it. The code handles the full workflow: upload, create task, poll status, and download results.
To customize the file path or other parameters, modify the code as needed.
file-batch-xxx) can be reused. If the input content remains the same, skip re-uploading and directly create a task with the existing ID:client.files.list(purpose="batch") API to query uploaded Batch file IDs.Sample code
Sample code
Step 3: Verify test results
After the task succeeds, the result file result.jsonl contains the fixed response {"content":"This is a test result."}:
Run a formal task
Input file requirements
- Format: UTF-8 encoded JSONL (one independent JSON object per line).
- Size limits: Maximum 50,000 requests per file, maximum 500 MB.
- Line limit: Each JSON object must not exceed 6 MB and must fit within the model's context window.
- Consistency: All requests in the same file must use the same model and the same thinking mode (if applicable).
- Unique identifier: Each request must include a unique custom_id field within the file. This field is used to match requests with results.
The Base64 strings in the examples above are truncated. Generate full encodings using the Python code below.
Pass Base64-encoded strings (using images as an example)
Pass Base64-encoded strings (using images as an example)
- Convert a local file to Base64 encoding:
-
Build a Data URL format:
data:[MIME_type];base64,{base64_image};- Replace
MIME_typewith the actual media type. It must match theMIME Typevalue (e.g.,image/jpeg,image/png); base64_imageis the Base64 string generated in the previous step.
- Replace
1. Modify the input file
-
In the
test_model.jsonlfile, set themodelparameter to the target model and set theurlfield:Model type
url
Text generation/multimodal models
/v1/chat/completionsText embedding models
/v1/embeddings -
Or use the "JSONL batch generation tool" above to generate a new file for formal tasks. Ensure the
modelandurlfields are correct.
2. Modify the Getting Started code
- Change the input file path to your file name.
- Set the endpoint parameter to match the url field in your input file.
3. Run the code and wait for results
When the task completes, successful request results are saved to the local result.jsonl file. If any requests failed, the error details are saved to the error.jsonl file.
- Successful results (
output_file_id): Each line corresponds to one successful request and includes thecustom_idandresponse.
- Failure details (
error_file_id): Contains information about failed requests with line numbers and error reasons. See Error codes for troubleshooting.
Detailed procedure
The Batch API workflow consists of four steps: upload a file, create a task, query task status, and download results.
1. Upload file
1. Upload file
file_id.When uploading a file, thepurposeparameter must bebatch.
file-batch-xxx) can be reused. If the input content remains the same, skip re-uploading and directly create a task with the existing ID:client.files.list(purpose="batch") API to query uploaded Batch file IDs.- 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 | Method | Required | Description |
|---|---|---|---|---|
input_file_id | String | Body | Yes | The input file ID. Use the file ID returned by the Prepare and upload file API, such as |
endpoint | String | Body | Yes | The API access path. Must match the url field in the input file.
|
completion_window | String | Body | Yes | Maximum wait time. Range: 24h-336h, integers only. Units: "h" or "d" (e.g., "24h" or "14d"). |
metadata | Map | Body | No | Extended metadata for the task, specified as key-value pairs. |
metadata.ds_name | String | Body | No | Task name. Example: Maximum length: 100 characters. If specified multiple times, the last value takes effect. |
metadata.ds_description | String | Body | No | Task description. Example: Maximum length: 200 characters. If specified multiple times, the last value takes effect. |
Response example
Response parameters
Field | Type | Description |
|---|---|---|
id | String | The batch task ID. |
object | String | Fixed value: |
endpoint | String | The API access path. |
errors | Map | Error information. |
input_file_id | String | Input file ID . |
completion_window | String | Maximum wait time. Range: 24h-336h, integers only. Units: "h" or "d" (e.g., "24h" or "14d"). |
status | String | Task status: validating, failed, in_progress, finalizing, completed, expired, cancelling, cancelled. |
output_file_id | String | File ID for successful request results. |
error_file_id | String | File ID for failed request results. |
created_at | Integer | Unix timestamp (seconds) when the task was created. |
in_progress_at | Integer | Unix timestamp (seconds) when the task started processing. |
expires_at | Integer | Unix timestamp (seconds) when the task starts timing out. |
finalizing_at | Integer | Unix timestamp (seconds) when the task last started. |
completed_at | Integer | Unix timestamp (seconds) when the task completed. |
failed_at | Integer | Unix timestamp (seconds) when the task failed. |
expired_at | Integer | Unix timestamp (seconds) when the task expired. |
cancelling_at | Integer | Unix timestamp (seconds) when the task entered the cancelling state. |
cancelled_at | Integer | Unix timestamp (seconds) when the task was cancelled. |
request_counts | Map | Request counts by state. |
metadata | Map | Additional metadata as 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 specific task status
Query specific task status
- OpenAI Python SDK
- OpenAI Node.js SDK
- Java (HTTP)
- curl (HTTP)
Request example
Response example
A successful query returns detailed batch task information. The following is a response example for a task with completed status:Field | Type | Description |
|---|---|---|
id | String | Batch task ID. |
status | String | Task status. Possible values:
|
output_file_id | String | ID of the output file containing successful results. Generated after task completion. |
error_file_id | String | ID of the error file containing failed request details. Generated after task completion if any requests failed. |
request_counts | Object | Request count statistics containing total, completed, and failed counts. |
Query task list
Query task list
batches.list() method to retrieve the list of batch tasks. Use pagination to retrieve the full task list.- OpenAI Python SDK
- OpenAI Node.js SDK
- Java (HTTP)
- curl (HTTP)
Request example
Input parameters
Field | Type | Method | Required | Description |
|---|---|---|---|---|
after | String | Query | No | Cursor for pagination. Set this to the last task ID from the previous page. |
limit | Integer | Query | No | Number of tasks 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 IDs. Specify multiple IDs separated by commas (up to 20). |
status | String | Query | No | Filter by task status. Specify multiple statuses separated by commas. |
create_after | String | Query | No | Filter tasks created after this time. Format: |
create_before | String | Query | No | Filter tasks created before this time. Format: |
Response example
Response parameters
Field | Type | Description |
|---|---|---|
object | String | Object type. Fixed value: list. |
data | Array | Array of batch task objects. See the response parameters for creating a batch task. |
first_id | String | ID of the first batch task on the current page. |
last_id | String | ID of the last batch task on the current page. |
has_more | Boolean | Whether additional pages are available. |
Cancel batch task
Cancel batch task
- OpenAI Python SDK
- OpenAI Node.js SDK
- Java (HTTP)
- curl (HTTP)
Request example
Response example
After you successfully cancel a task, the API returns detailed batch task information. The following is a response example for a task in cancelling status:After you cancel a task, the status first changes tocancellingwhile the system waits for currently executing requests to complete. The status eventually changes tocancelled. Results from completed requests are still saved in the output file.
4. Download Batch result file
4. Download Batch result file
file_id starts with file-batch_output.- OpenAI Python SDK
- OpenAI Node.js SDK
- Java (HTTP)
- curl (HTTP)
content method to retrieve the batch task result file content and use the write_to_file method to save it locally.Request example
Response example
Response example
Single response example:Response parameters
Field | Type | Description |
|---|---|---|
id | String | The request ID. |
custom_id | String | The user-defined request identifier. |
response | Object | The request result. |
status_code | Integer | HTTP status code. 200 indicates success. |
request_id | String | Server-generated unique ID for this request. |
completion_tokens | Integer | Number of tokens in the model-generated response. |
prompt_tokens | Integer | Number of tokens in the input content ( |
total_tokens | Integer | Total number of tokens used by this request. |
model | String | Name of the model used for this request. |
error | Object | The error object. Returns |
error.code | String | Error line and reason information. See Error codes for troubleshooting. |
error.message | String | Error message. |
Advanced features
Set completion notifications
For long-running tasks, use asynchronous notifications instead of polling to reduce resource consumption.
- Callback: Specify a publicly accessible URL when creating the task.
- EventBridge message queue: Deeply integrated with the Alibaba Cloud ecosystem. No public IP required.
Method 1: Callback
Method 1: Callback
metadata. After the task completes, the system sends a POST request containing the task status to the specified URL:- OpenAI Python SDK
- curl (HTTP)
Method 2: EventBridge message queue
Method 2: EventBridge message queue
- Event source (Source):
acs.dashscope - Event type (Type):
dashscope:System:BatchTaskFinish
Going live
-
File management
- Periodically delete unnecessary files using the OpenAI File delete API to avoid reaching storage limits (10,000 files or 100 GB).
- Store large files in OSS instead of uploading directly.
-
Task monitoring
- Use Callback or EventBridge asynchronous notifications.
- If polling is required, set the interval to more than 1 minute and use an exponential backoff strategy.
-
Error handling
- Implement handling for network errors, API errors, and other exceptions.
- Download and analyze error details from
error_file_id. - For common error codes, see Error codes.
-
Cost optimization
- Consolidate small tasks into a single batch.
- Set
completion_windowappropriately to allow greater scheduling flexibility.
Utility tools
CSV to JSONL
CSV to JSONL
To customize the file path or other parameters, modify the code as needed.
JSONL results to CSV
JSONL results to CSV
result.jsonl into result.csv for analysis in Excel.To customize the file path or other parameters, modify the code as needed.
- Use a text editor (such as Sublime Text) to convert the CSV file encoding to GBK, then open it in Excel.
- Alternatively, create a new Excel file and specify UTF-8 encoding when importing the data.
Rate limits
API | Rate limit (per Alibaba Cloud account) |
|---|---|
Create task | 1,000 calls/minute; up to 1,000 concurrent tasks |
Query task | 1,000 calls/minute |
Query task list | 100 calls/minute |
Cancel task | 1,000 calls/minute |
Billing
- Unit price: The input and output tokens for all successful requests are charged at 50% of the real-time inference price for the corresponding model. For more information, see Model list.
-
Billing scope:
- Only requests successfully executed within a task are billed.
- Requests that fail because of file parsing errors, task execution failures, or row-level errors do not incur charges.
- For canceled tasks, requests successfully completed before the cancellation are still billed as normal.
- Batch inference is a separate billing item. It supports AI general-purpose savings plan, but not discounts, such as subscription (other savings plans) or free quotas for new users. It also does not support features such as context cache.
- Some models, such as qwen3.5-plus and qwen3.5-flash, have thinking mode enabled by default. This mode generates additional thinking tokens, which are billed at the output token price and increase costs. To control costs, set the
enable_thinkingparameter based on task complexity. For more information, see Deep thinking.
Error codes
If a request fails and returns an error message, see Error codes for a solution.
FAQ
- How do I choose between Batch Chat and Batch File? Use Batch File when you need to process a large file containing many requests asynchronously. Use Batch Chat when your business logic requires submitting many independent conversation requests synchronously with high concurrency.
- How is the Batch File API billed? Do I need to purchase a separate package? Batch uses pay-as-you-go billing based on tokens consumed by successful requests. No separate resource package is required.
- Are submitted batch files executed in order? No. The system uses dynamic scheduling based on compute load and does not guarantee execution order. Tasks may be delayed when resources are constrained.
- How long does it take to complete a submitted batch file? Execution time depends on system resources and task scale. If a task does not complete within the completion_window, it expires. Unprocessed requests in expired tasks are not executed and do not incur charges. Scenario recommendations: Use real-time calls for scenarios requiring strict real-time model inference. Use batch calls for large-scale data processing scenarios that can tolerate delay.