Batch processing API reference

Updated at:

Model overview

Model name

Data type

Vector dimensions

Maximum lines per request

Maximum input tokens per line

Supported languages

text-embedding-async-v2

32-bit float

1,536

100,000

2,048

Chinese, English, Spanish, French, Portuguese, Indonesian, Japanese, Korean, German, and Russian

text-embedding-async-v1

Chinese, English, Spanish, French, and Portuguese, Indonesian

Model name

Price

(per 1,000 input tokens)

Free quota (Note)

Throttling conditions (Throttling is triggered if any limit is exceeded)

RPS limit for task submission API

Number of concurrent processing tasks

text-embedding-async-v2

CNY 0.0007

20 million tokens

Validity: 90 days after you activate Model Studio

1

A user can have a maximum of 50 tasks that are queued or running for the general text embedding asynchronous service.

In addition, to prevent resource exhaustion from burst requests, a user can run a maximum of 3 tasks concurrently. Other tasks must wait in the queue.

text-embedding-async-v1

No free quota

Prerequisites

You can call the general text embedding batch processing API using HTTP and the DashScope software development kit (SDK).

Before making a call, get an API key and export the API key as an environment variable. To make calls using the SDK, install the DashScope SDK.

HTTP calls

HTTP calls support only asynchronous mode and involve two steps:

  1. Create a task: Send a request to create a task. The request returns a task ID.
  2. Query the result by task ID: Use the task ID from the previous step to query the result generated by the model.
HTTP call endpoint:

POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding

Replace {WorkspaceId} with your actual workspace ID.

Create a task

Request parameters
Headers

Authorization string (Required)

Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.

Content-Type string (Required)

The content type of the request. Must be application/json.

X-DashScope-Async string (Required)

Enables asynchronous processing. HTTP requests support only asynchronous calls. Must be enable.

ImportantIf this request header is missing, the error "current user api does not support synchronous calls" is returned.

Request body

model string(Required)

The name of the model to call. You can select text-embedding-async-v1 or text-embedding-async-v2.

input object (Required)

The input for batch vectorization.

Property

url string (Required)

The HTTP URL of the file for batch vectorization. Each line contains one entry to be embedded.

Text limits:

  • A single line of a string supports up to 2,048 tokens.
  • A single request supports a maximum of 100,000 lines of text.
  • The file size cannot exceed 200 MB.

parameters object (Optional)

Parameters for vectorization.

Property

text_type string (Optional)

Parameter values:

  • document (default)
  • query

After text is converted to vectors, you can use them for downstream tasks, such as retrieval, clustering, and classification. For asymmetric tasks such as retrieval, distinguish between query text (query) and document text (document) for better results. For symmetric tasks such as clustering and classification, you can use the default value document.

curl -X POST 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -H 'X-DashScope-Async: enable' \
    -d '{
    "model": "text-embedding-async-v2",
    "input": {
        "url": "https://modelscope.oss-cn-beijing.aliyuncs.com/resource/text_embedding_file.txt"
    },
    "parameters": {
        "text_type": "query"
    }
}'
Response parameters

output object

Task output information.

Properties

task_id string

The task ID. Valid for queries for 24 hours.

task_status string

The status of the task.

Enumeration values

  • PENDING
  • RUNNING
  • SUCCEEDED
  • FAILED
  • CANCELED
  • UNKNOWN: The task does not exist or its status is unknown.

request_id string

Unique request identifier for tracing and troubleshooting.

code string

Error code. Returned only for failed requests. See Error codes.

message string

Detailed error message. Returned only for failed requests. See Error codes.

Successful response

Save the task_id to query the task status and result.

{
    "output": {
        "task_status": "PENDING",
        "task_id": "0385dc79-5ff8-4d82-bcb6-xxxxxx"
    },
    "request_id": "4909100c-7b5a-9f92-bfe5-xxxxxx"
}

Error response

Task creation failed. See Error codes.

{
    "code": "InvalidApiKey",
    "message": "Invalid API-key provided.",
    "request_id": "7438d53d-6eb8-4596-8835-xxxxxx"
}

Query the result by task ID

GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}

Request parameters
Headers

Authorization string (Required)

Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.

Path parameters

task_id string (Required)

The ID of the task.

Query task result

Replace 86ecf553-d340-4e21-xxxxxxxxx with your actual task_id.

If you use a model in the Singapore region, replace base_url with https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx, where {WorkspaceId} is your actual workspace ID.

curl -X GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Response parameters

outputobject

Task output information.

Properties

task_id string

The task ID. Valid for queries for 24 hours.

task_status string

The status of the task.

Enumeration values

  • PENDING
  • RUNNING
  • SUCCEEDED
  • FAILED
  • CANCELED
  • UNKNOWN: The task does not exist or its status is unknown.

submit_time string

The time when the task was submitted. format is YYYY-MM-DD HH:mm:ss.SSS.

scheduled_time string

The time when the task was executed. format is YYYY-MM-DD HH:mm:ss.SSS.

end_time string

The time when the task was completed. format is YYYY-MM-DD HH:mm:ss.SSS.

url string

The URL of the output file generated by the model.

code string

Error code. Returned only for failed requests. See Error codes.

message string

Detailed error message. Returned only for failed requests. See Error codes.

usage object

Statistics for the output information. Only successful results are counted.

Property

total_tokensinteger

The number of tokens in the input content for the request. This number is calculated based on the tokens that are parsed by the model's tokenizer from the input text file.

request_id string

Unique request identifier for tracing and troubleshooting.

Task succeeded

Task data, such as the task status and result URL, is retained for only 24 hours and then automatically deleted. You must save the generated output file promptly.

{
    "request_id":"<Your Request ID>",
    "output":{
        "task_id":"<Your Task ID>",
        "task_status":"SUCCEEDED",
        "submit_time":"2025-02-20 14:37:13.328",
        "scheduled_time":"2025-02-20 14:37:13.352",
        "end_time":"2025-02-20 14:37:14.159",
        "url":"<URL containing the output result>"
    },
    "usage":{
        "total_tokens":258
    }
}

Task running

{
    "request_id":"<Your Request ID>",
    "output":{
        "task_id":"<Your Task ID>",
        "task_status":"RUNNING"
    }
}

Task failed

If a task fails, its status is set to FAILED. The code and message fields indicate the reason for the failure.

{
  "request_id": "<Your Request ID>"
  "output": {
        "task_id": "<Your Task ID>",
        "task_status": "FAILED",
        "submit_time":"2025-02-20 15:57:19.039",
        "scheduled_time":"2025-02-20 15:57:19.059",
        "end_time":"2025-02-20 15:57:19.418",
        "code": "xxx",
         "message": "xxxxxx"
  }
}

Dashscope

To avoid errors, make sure that you have installed the latest version of the DashScope SDK. For more information, see Install the SDK.

The DashScope SDK is available in Python and Java.

The parameter names for the SDK and HTTP API are mostly the same. The parameter structure depends on the SDK encapsulation for each language. For parameter descriptions, see Wanxiang text-to-image V2.

Because the model requires a long processing time, the underlying service is provided asynchronously. The SDK is encapsulated to support both synchronous and asynchronous calls.

Request body

model string(Required)

The name of the model to call. You can select text-embedding-async-v1 or text-embedding-async-v2.

url string (Required)

The HTTP URL of the file for batch vectorization. Each line contains one entry to be vectorized.

Text limits:

  • A single line of a string supports up to 2,048 tokens.
  • A single request supports a maximum of 100,000 lines of text.
  • The file size cannot exceed 200 MB.

text_type string(Optional)

After text is converted to vectors, you can use them for downstream tasks, such as retrieval, clustering, and classification. For asymmetric tasks such as retrieval, distinguish between query text (query) and document text (document) for better results. For symmetric tasks such as clustering and classification, you can use the default value document.

Synchronous call

import os
import dashscope
# This configuration is for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. The region value varies by region.
client = dashscope.Client(
    # If you have not set an environment variable, replace this line with your Model Studio API key: api_key="sk-xxx",
    # API keys are region-specific. To get an API key, see https://help.aliyun.com/en/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

# Submit the batch job and wait for it to complete (raises DashScopeError if the job fails or is canceled)
job = client.embeddings.jobs.create(
    model="text-embedding-async-v1",
    file_url="https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241016/nigwvr/text_embedding_file.txt",
    text_type="document")
result = client.embeddings.jobs.wait(job)
print(result)
print(result.result_url)
import com.alibaba.dashscope.embeddings.BatchTextEmbedding;
import com.alibaba.dashscope.embeddings.BatchTextEmbeddingParam;
import com.alibaba.dashscope.embeddings.BatchTextEmbeddingResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.task.AsyncTaskListParam;
import com.alibaba.dashscope.task.AsyncTaskListResult;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;

public class Main {
        // The following is the configuration for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The configuration varies by region.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
    public static void basicCall() throws ApiException, NoApiKeyException {
        BatchTextEmbeddingParam param = BatchTextEmbeddingParam.builder()
                .model(BatchTextEmbedding.Models.TEXT_EMBEDDING_ASYNC_V1)
                .url("https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241016/nigwvr/text_embedding_file.txt")
                .textType(BatchTextEmbeddingParam.TextType.DOCUMENT)
                .build();
        BatchTextEmbedding textEmbedding = new BatchTextEmbedding();
        BatchTextEmbeddingResult result = textEmbedding.call(param);
        System.out.println(result);
    }

    public static void main(String[] args) {
        // The following is the configuration for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The configuration varies by region.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
        try {
            basicCall();
        } catch (ApiException | NoApiKeyException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}

Asynchronous call

import os
import dashscope
from dashscope.v2 import DashScopeError
# This configuration is for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. The region value varies by region.
client = dashscope.Client(
    # If you have not set an environment variable, replace this line with your Model Studio API key: api_key="sk-xxx",
    # API keys are region-specific. To get an API key, see https://help.aliyun.com/en/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

# Create an asynchronous task.
def create_async_task():
    job = client.embeddings.jobs.create(
        model="text-embedding-async-v1",
        file_url="https://modelscope.oss-cn-beijing.aliyuncs.com/resource/text_embedding_file.txt",
        text_type="document")
    print(job.task_id, job.status)
    return job

# Get information about the asynchronous task.
def fetch_task_status(job):
    snapshot = client.embeddings.jobs.fetch(job.task_id)
    print(snapshot.status)

# Wait for the asynchronous task to complete. The SDK encapsulates exponential backoff polling and waits until the task is finished. Raises DashScopeError if the job fails or is canceled.
def wait_task(job):
    done = client.embeddings.jobs.wait(job)
    print(done.status, done.result_url)

# Cancel the asynchronous task. Only tasks in the PENDING state can be canceled.
def cancel_task(job):
    snapshot = client.embeddings.jobs.cancel(job.task_id)
    print(snapshot.status)

if __name__ == '__main__':
    try:
        job = create_async_task()
        fetch_task_status(job)
        wait_task(job)
    except DashScopeError as e:
        print(f"HTTP status code: {e.status_code}")
        print(f"Error code: {e.code}")
        print(f"Error message: {e.message}")
        print("For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code")
import com.alibaba.dashscope.embeddings.BatchTextEmbedding;
import com.alibaba.dashscope.embeddings.BatchTextEmbeddingParam;
import com.alibaba.dashscope.embeddings.BatchTextEmbeddingResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.task.AsyncTaskListParam;
import com.alibaba.dashscope.task.AsyncTaskListResult;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;

public class Main {
        // The following is the configuration for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when calling. The configuration varies by region.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";

    /** Create a batch processing task. */
    public static BatchTextEmbeddingResult createTask() throws ApiException, NoApiKeyException {
        BatchTextEmbeddingParam param = BatchTextEmbeddingParam.builder()
                .model(BatchTextEmbedding.Models.TEXT_EMBEDDING_ASYNC_V1)
                .url("https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241016/nigwvr/text_embedding_file.txt")
                .textType(BatchTextEmbeddingParam.TextType.DOCUMENT)
                .build();
        BatchTextEmbedding textEmbedding = new BatchTextEmbedding();
        return textEmbedding.asyncCall(param);

    }

    /** Get the task status. */
    public static void fetchTaskStatus(BatchTextEmbeddingResult result)
            throws ApiException, NoApiKeyException {
        BatchTextEmbedding textEmbedding = new BatchTextEmbedding();
        result = textEmbedding.fetch(result, null);
        System.out.println(result);
    }

    /** Wait for the task to complete. The wait method encapsulates polling logic and waits until the task is finished. */
    public static void waitTask(BatchTextEmbeddingResult result)
            throws ApiException, NoApiKeyException {
        BatchTextEmbedding textEmbedding = new BatchTextEmbedding();
        result = textEmbedding.wait(result, null);
        System.out.println(result);
    }

    /** Cancel the task. Only tasks in the PENDING state can be canceled. */
    public static void cancelTask(BatchTextEmbeddingResult result)
            throws ApiException, NoApiKeyException {
        BatchTextEmbedding textEmbedding = new BatchTextEmbedding();
        result = textEmbedding.cancel(result, null);
        System.out.println(result);
    }

    /** Query submitted tasks. */
    public static void list() throws ApiException, NoApiKeyException {
        AsyncTaskListParam param = AsyncTaskListParam.builder().pageNo(1).pageSize(20).build();
        BatchTextEmbedding textEmbedding = new BatchTextEmbedding();
        AsyncTaskListResult result = textEmbedding.list(param);
        System.out.println(JsonUtils.toJson(result));
    }

    public static void main(String[] args) {
        try {
            BatchTextEmbeddingResult task = createTask();
            fetchTaskStatus(task);
            waitTask(task);
            // list();
        } catch (ApiException | NoApiKeyException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}

Response parameters

In DashScope Python SDK 2.0, client.embeddings.jobs.create / wait / fetch return a Job object. The following describes its fields.

request_id string

A unique identifier for the request. You can use it to trace request details and troubleshoot issues.

task_idstring

A unique identifier for the task. You can use it to trace task details and troubleshoot issues.

statusstring

The task status.

  • SUCCEEDED: The task was successful.
  • FAILED: The task failed.
  • CANCELED: The task was canceled.
  • PENDING: The task is in the queue.
  • SUSPENDED: The task is suspended.
  • RUNNING: The task is being processed.

result_urlstring

The URL that contains the embedding results. This parameter is empty if the task fails. You can read it via job.result_url.

codestring

If the task fails, this parameter indicates the reason for the failure (corresponding to e.code of the exception). This parameter is not returned for successful executions. For more information, see Error messages.

messagestring

If the task fails, this parameter provides detailed information about the failure (corresponding to e.message of the exception). This parameter is not returned for successful executions.

Failed calls

When a request fails or a task execution fails, the SDK raises DashScopeError; you can obtain the failure details via e.status_code (HTTP status code), e.code (error code), e.message (error message), and e.request_id (unique request ID). For more information, see Error messages.

usageobject

Property

Details

total_tokens integer

The number of tokens in the input content for the request. This number is calculated based on the tokens that are parsed by the model's tokenizer from the input string.

Synchronous call

Successful response

{
    "request_id": "<Your Request ID>",
    "task_id": "<Your Task ID>",
    "status": "SUCCEEDED",
    "result_url": "<URL containing the output result>",
    "usage": {
        "total_tokens": 384
    }
}

Error response

Request failed
{
    "code":"InvalidApiKey",
    "message":"Invalid API-key provided.",
    "request_id":"<Your Request ID>"
}
Task execution failed

When a task is in the FAILED terminal state, jobs.wait / jobs.fetch raise a DashScopeError. The following is the corresponding task snapshot:

{
    "request_id": "<Your Request ID>",
    "task_id": "<Your Task ID>",
    "status": "FAILED",
    "code": "InvalidFile.TypeNotTxt",
    "message": "File type should be txt"
}

Asynchronous call

Successful response

{
    "request_id": "<Your Request ID>",
    "task_id": "<Your Task ID>",
    "status": "SUCCEEDED",
    "result_url": "<URL containing the output result>",
    "usage": {
        "total_tokens": 384
    }
}

Error response

Request failed
{
    "code":"InvalidApiKey",
    "message":"Invalid API-key provided.",
    "request_id":"<Your Request ID>"
}
Task execution failed

When a task is in the FAILED terminal state, jobs.wait / jobs.fetch raise a DashScopeError. The following is the corresponding task snapshot:

{
    "request_id": "<Your Request ID>",
    "task_id": "<Your Task ID>",
    "status": "FAILED",
    "code": "InvalidFile.TypeNotTxt",
    "message": "File type should be txt"
}

FAQ

Input file limits

  • The input file must be a text file encoded in UTF-8. Each line contains a string for which a text vector is computed. The system processes the input line by line and includes the corresponding line number and the generated embedding result in the output file.
  • A single file cannot exceed 200 MB.
  • The number of text lines in a single request cannot exceed 100,000.
  • The content of each line cannot exceed 2,048 tokens.
  • Blank lines, which are lines that do not contain any characters, are automatically skipped by the system, and their text vectors are not computed. However, the line numbers of these blank lines are retained in the output file to facilitate result mapping.

Output file format

  • When the task is successfully completed, the submitted input data is converted into vector results and stored in an output file. To save storage space and facilitate downloading, the output file is compressed into the .gz format. After you download the file, you can decompress it to obtain the text output file.
  • Task data, such as the task status and result URL, is retained for only 24 hours and then automatically deleted. You must save the output file that contains the task results promptly.
  • The output file that is generated by the model after vectorization is a JSONL file. Each line is a complete JSON structure that contains the vectorized output for a specific line from the input file.

Error codes

If the model call fails and returns an error message, see Error codes for resolution.

Throttling

To ensure fair use, basic throttling is applied to general text embedding models. If you exceed the call limits, your API requests fail due to throttling. You must wait until the conditions are met before you can make another call. For detailed throttling conditions for each model, see Throttling.