All Products
Search
Document Center

Alibaba Cloud Model Studio:Synchronous API details

Last Updated:Nov 26, 2026

General text embedding models convert text data into numerical vectors for downstream tasks such as semantic search, recommendation, clustering, and classification.

Model overview

Singapore

ModelVector dimensionsMaximum rows

Maximum tokens processed per row (Note)

Unit price (per million input tokens)Supported languages

Free quota(Note)

qwen3.7-text-embedding

2560, 2,048, 1,536, 1,024 (default), 768, 512, 256

20

128,000

$0.07

201 mainstream languages and dialects, including Chinese, English, Spanish, French, Portuguese, Indonesian, Japanese, Korean, German, and Russian

1 million tokens

Validity: within 90 days after Model Studio activation

text-embedding-v4

Part of the Qwen3-Embedding series

2,048, 1,536, 1,024 (default), 768, 512, 256, 128, 64

10

8,192

$0.07

100+ mainstream languages, including Chinese, English, Spanish, French, Portuguese, Indonesian, Japanese, Korean, German, and Russian

1 million tokens

Validity: within 90 days after Model Studio activation

text-embedding-v3

1,024 (default), 768, 512

50+ mainstream languages, including Chinese, English, Spanish, French, Portuguese, Indonesian, Japanese, Korean, German, and Russian

500,000 tokens

Validity: within 90 days after Model Studio activation

Beijing

ModelVector dimensionsMaximum rowsMaximum tokens per rowUnit price (per million input tokens)Supported languages

text-embedding-v4

Part of the Qwen3-Embedding series

2,048, 1,536, 1,024 (default), 768, 512, 256, 128, 64

10

8,192

$0.072

100+ mainstream languages including Chinese, English, Spanish, French, Portuguese, Indonesian, Japanese, Korean, German, and Russian, as well as multiple programming languages

Hong Kong (China)

ModelVector dimensionsMaximum rowsMaximum tokens per rowUnit price (per million input tokens)Supported languages

text-embedding-v4

Part of the Qwen3-Embedding series

2,048, 1,536, 1,024 (default), 768, 512, 256, 128, 64

10

8,192

$0.07

100+ mainstream languages including Chinese, English, Spanish, French, Portuguese, Indonesian, Japanese, Korean, German, and Russian, as well as multiple programming languages

dashscope CLI

Called through the dashscope command line.

export DASHSCOPE_API_KEY="your-api-key"
# Replace {WorkspaceId} with your workspace ID, ap-southeast-1 with your region (e.g., us-east-1, eu-central-1)
export DASHSCOPE_HTTP_BASE_URL="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
dashscope embeddings create -m text-embedding-v3 -i "你好世界"

ImportantThe SDK Expert interactive assistant can accomplish the same development and troubleshooting tasks in natural language. See

DashScope SDK Expert.

For the complete region list, see Base URL overview.

For model rate limiting, see Rate limiting.

Prerequisites

If you are familiar with the OpenAI ecosystem, you can use the compatible API for quick migration; the DashScope API offers richer exclusive features. Choose based on your needs.

You need to have obtained and configured an API Key and configured the API Key in environment variables. If you call through the SDK, you also need to install the DashScope SDK.

OpenAI compatibility

base_url to configure when calling with the SDK:
  • Singapore: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
  • China (Beijing): https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1
  • Hong Kong (China): https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1
endpoint to configure when calling with HTTP:
  • Singapore: POSThttps://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/embeddings
  • China (Beijing): POSThttps://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/embeddings
  • Hong Kong (China): POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1/embeddings

Replace {WorkspaceId} with your actual workspace ID when calling.

Request body

modelstringRequired

The model name to call. Select from the model names in the Model overview table.

inputarray<string> or string or fileRequired

The input text to process. It can be a string, an array of strings, or a file. Different model versions support different text lengths and batch sizes, as follows:

  • qwen3.7-text-embedding model:
    • When the input is a string: supports up to 128,000 tokens.
    • When the input is a list of strings or a file: supports up to 20 items (rows), each up to 128,000 tokens.
  • text-embedding-v3 / v4 models:
    • When the input is a string: supports up to 8,192 tokens.
    • When the input is a list of strings or a file: supports up to 10 items (rows), each up to 8,192 tokens.

dimensions integer Optional

The specified vector dimensions, which must be one of the following values: 2560 (only applies to qwen3.7-text-embedding), 2048 (only applies to text-embedding-v4), 1536 (only applies to text-embedding-v4) 1024, 768, 512, 256, 128, or 64. The default value is 1024.

encoding_format string Optional

Controls the returned embedding format. The input supports float and base64, and the returned embedding data also supports both float and base64 formats. The actual returned format depends on the gateway the request is routed to:

  • Legacy gateway: regardless of whether encoding_format is set to float or base64, it only returns float data and does not support base64 output.

  • New gateway:

    • Short requests: data is returned in the format set by encoding_format.
    • Long requests: internally routed to the legacy gateway, only float data is returned.

Input string

Python

import os
from openai import OpenAI

client = OpenAI(
    # If you use a model in the China (Beijing) region, you must use an API key from that region. Get one at: https://modelstudio.console.alibabacloud.com/model/settings/api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # If the environment variable is unset, insert your API key here
    # The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)

completion = client.embeddings.create(
    model="qwen3.7-text-embedding",
    input='The clothes are of good quality and look good, definitely worth the wait. I love them.',
    dimensions=1024,
    encoding_format="float"
)

print(completion.model_dump_json())

Java

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.dashscope.utils.JsonUtils;

public final class Main {
    public static void main(String[] args) {
        // If you use a model in the China (Beijing) region, you must use an API key from that region. Get one at: https://modelstudio.console.alibabacloud.com/model/settings/api-key
        String apiKey = System.getenv("DASHSCOPE_API_KEY");
        if (apiKey == null) {
            System.out.println("DASHSCOPE_API_KEY not found in environment variables");
            return;
        }
        // The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
        String baseUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/embeddings";
        HttpClient client = HttpClient.newHttpClient();

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "qwen3.7-text-embedding");
        requestBody.put("input", "风急天高猿啸哀,渚清沙白鸟飞回,无边落木萧萧下,不尽长江滚滚来");
        requestBody.put("dimensions", 1024);
        requestBody.put("encoding_format", "float");

        try {
            String requestBodyString = JsonUtils.toJson(requestBody);
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(baseUrl))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + apiKey)
                    .POST(HttpRequest.BodyPublishers.ofString(requestBodyString))
                    .build();

            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            if (response.statusCode() == 200) {
                System.out.println("Response: " + response.body());
            } else {
                System.out.printf("Failed to retrieve response, status code: %d, response: %s%n", response.statusCode(), response.body());
            }
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

curl

If you use models in the China (Beijing) region, use an API KEY from the China (Beijing) region and replace the url with: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/embeddings. The following uses the Singapore region URL. Replace {WorkspaceId} with your actual workspace ID when calling. URLs differ across regions.

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/embeddings' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "qwen3.7-text-embedding",
    "input": "风急天高猿啸哀,渚清沙白鸟飞回,无边落木萧萧下,不尽长江滚滚来",
    "dimensions": 1024,
    "encoding_format": "float"
}'

Input string list

Python

import os
from openai import OpenAI

client = OpenAI(
    # If you use a model in the China (Beijing) region, you must use an API key from that region. Get one at: https://modelstudio.console.alibabacloud.com/model/settings/api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # If the environment variable is unset, insert your API key here
    # The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)

completion = client.embeddings.create(
    model="qwen3.7-text-embedding",
    input=['风急天高猿啸哀', '渚清沙白鸟飞回', '无边落木萧萧下', '不尽长江滚滚来'],
    dimensions=1024,
    encoding_format="float"
)

print(completion.model_dump_json())

Java

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.Arrays;
import com.alibaba.dashscope.utils.JsonUtils;

public final class Main {
    public static void main(String[] args) {
        /** Get the API key from the environment variable; if unset, replace with your API key*/
        // If you use a model in the China (Beijing) region, you must use an API key from that region. Get one at: https://modelstudio.console.alibabacloud.com/model/settings/api-key
        String apiKey = System.getenv("DASHSCOPE_API_KEY");
        if (apiKey == null) {
            System.out.println("DASHSCOPE_API_KEY not found in environment variables");
            return;
        }
        // The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
        String baseUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/embeddings";
        HttpClient client = HttpClient.newHttpClient();
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "qwen3.7-text-embedding");
        List<String> inputList = Arrays.asList("风急天高猿啸哀", "渚清沙白鸟飞回", "无边落木萧萧下", "不尽长江滚滚来");
        requestBody.put("input", inputList);
        requestBody.put("encoding_format", "float");

        try {
            /** Convert the request body to a JSON string*/
            String requestBodyString = JsonUtils.toJson(requestBody);

            /**Build the HTTP request*/
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(baseUrl))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + apiKey)
                    .POST(HttpRequest.BodyPublishers.ofString(requestBodyString))
                    .build();

            /**Send the request and receive the response*/
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            if (response.statusCode() == 200) {
                System.out.println("Response: " + response.body());
            } else {
                System.out.printf("Failed to retrieve response, status code: %d, response: %s%n", response.statusCode(), response.body());
            }
        } catch (Exception e) {
            /** Catch and print exceptions*/
            System.err.println("Error: " + e.getMessage());
        }
    }
}

curl

If you use models in the China (Beijing) region, use an API KEY from the China (Beijing) region and replace the url with: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/embeddings. The following uses the Singapore region URL. Replace {WorkspaceId} with your actual workspace ID when calling. URLs differ across regions.

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/embeddings' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "qwen3.7-text-embedding",
    "input": [
        "风急天高猿啸哀",
        "渚清沙白鸟飞回",
        "无边落木萧萧下",
        "不尽长江滚滚来"
        ],
    "dimensions": 1024,
    "encoding_format": "float"
}'

Input file

Python

import os
from openai import OpenAI

client = OpenAI(
    # If you use a model in the China (Beijing) region, you must use an API key from that region. Get one at: https://modelstudio.console.alibabacloud.com/model/settings/api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # If the environment variable is unset, insert your API key here
    # The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)
# Make sure to replace 'texts_to_embedding.txt' with your file name or path.
with open('texts_to_embedding.txt', 'r', encoding='utf-8') as f:
    completion = client.embeddings.create(
        model="qwen3.7-text-embedding",
        input=f,
        encoding_format="float"
    )
print(completion.model_dump_json())

Java

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.alibaba.dashscope.utils.JsonUtils;

public class Main {
    public static void main(String[] args) {
        /** Get the API key from the environment variable; if unset, replace with your API key*/
        // If you use a model in the China (Beijing) region, you must use an API key from that region. Get one at: https://modelstudio.console.alibabacloud.com/model/settings/api-key
        String apiKey = System.getenv("DASHSCOPE_API_KEY");
        if (apiKey == null) {
            System.out.println("DASHSCOPE_API_KEY not found in environment variables");
            return;
        }
        // The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
        String baseUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/embeddings";
        HttpClient client = HttpClient.newHttpClient();

        /** Read the input file*/
        StringBuilder inputText = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader("<文件所来自的内容根的路径>"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                inputText.append(line).append("\n");
            }
        } catch (IOException e) {
            System.err.println("Error reading input file: " + e.getMessage());
            return;
        }

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "qwen3.7-text-embedding");
        requestBody.put("input", inputText.toString().trim());
        requestBody.put("dimensions", 1024);
        requestBody.put("encoding_format", "float");

        try {
            String requestBodyString = JsonUtils.toJson(requestBody);

            /**Build the HTTP request*/
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(baseUrl))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + apiKey)
                    .POST(HttpRequest.BodyPublishers.ofString(requestBodyString))
                    .build();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            if (response.statusCode() == 200) {
                System.out.println("Response: " + response.body());
            } else {
                System.out.printf("Failed to retrieve response, status code: %d, response: %s%n", response.statusCode(), response.body());
            }
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

curl

If you use models in the China (Beijing) region, use an API KEY from the China (Beijing) region and replace the url with: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/embeddings. The following uses the Singapore region URL. Replace {WorkspaceId} with your actual workspace ID when calling. URLs differ across regions.

Make sure to replace 'texts_to_embedding.txt' with your own file name or path

FILE_CONTENT=$(cat texts_to_embedding.txt | jq -Rs .)
curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/embeddings' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "qwen3.7-text-embedding",
    "input": ['"$FILE_CONTENT"'],
    "dimensions": 1024,
    "encoding_format": "float"
}'

Response object

dataarray

Task output information.

Property

embeddinglist

The value of the object returned by this call, which is an array of float elements containing the specific embedding vectors.

indexinteger

The index of the input text in the input array that corresponds to the algorithm result in this structure.

objectstring

The type of the object returned by this call. The default value is embedding.

modelstring

The name of the model called.

objectstring

The type of data returned by this call. The default value is list.

usageobject

The Token usage of this request. Embedding models only have input and no output, so prompt_tokens and total_tokens always have the same value.

Property

prompt_tokensinteger

The number of Tokens corresponding to the input content of this request. The value is the same as total_tokens.

total_tokens integer

The total number of Tokens consumed by this request, used for metering and billing. The Token count is based on the result of the input string parsed by the model Tokenizer, which may differ from the character or word count you estimate on your own.

idstring

The unique identifier of the request. It can be used for tracing request details and troubleshooting.

{
  "data": [
    {
      "embedding": [
        -0.0695386752486229, 0.030681096017360687, ...
      ],
      "index": 0,
      "object": "embedding"
    },
    ...
    {
      "embedding": [
        -0.06348952651023865, 0.060446035116910934, ...
      ],
      "index": 5,
      "object": "embedding"
    }
  ],
  "model": "qwen3.7-text-embedding",
  "object": "list",
  "usage": {
    "prompt_tokens": 184,
    "total_tokens": 184
  },
  "id": "73591b79-d194-9bca-8bb5-xxxxxxxxxxxx"
}
{
    "error": {
        "message": "Incorrect API key provided. ",
        "type": "invalid_request_error",
        "param": null,
        "code": "invalid_api_key"
    }
}

DashScope

base_url to configure when calling with the SDK:
  • Singapore: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
  • China (Beijing): https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1
  • Hong Kong (China): https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1
endpoint to configure when calling with HTTP:
  • Singapore: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding
  • China (Beijing): POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding
  • Hong Kong (China): POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding

Replace {WorkspaceId} with your actual workspace ID when calling.

Request body

modelstringRequired

The model to call. Select one from the model names in the table in Model overview.

inputstringorarray<string>Required

The input text to process. It can be a string, an array of strings, or a file. Different model versions support different text lengths and batch sizes, as follows:

  • qwen3.7-text-embedding model:
    • When the input is a string: supports up to 128,000 tokens.
    • When the input is a list of strings or a file: supports up to 20 items (rows), each up to 128,000 tokens.
  • text-embedding-v3 / v4 models:
    • When the input is a string: supports up to 8,192 tokens.
    • When the input is a list of strings or a file: supports up to 10 items (rows), each up to 8,192 tokens.

text_type stringOptional

When calling over HTTP, put text_type into the parameters object.

After text is converted into vectors, it can be applied to downstream tasks such as retrieval, clustering, and classification. For asymmetric tasks such as retrieval, to achieve better retrieval performance, it is recommended to distinguish between the query text (query) type and the corpus text (document) type. For symmetric tasks such as ingestion, clustering, and classification, you do not need to specify this explicitly; the system default value document is used.

dimension integer Optional

When calling over HTTP, put dimension into the parameters object.

The specified vector dimensions, which must be one of the following values: 2560 (only applies to qwen3.7-text-embedding), 2048 (only applies to text-embedding-v4), 1536 (only applies to text-embedding-v4) 1024, 768, 512, 256, 128, or 64. The default value is 1024.

output_type string Optional

When calling over HTTP, put output_type into the parameters object.

The user-specified discrete vector output only applies to the qwen3.7-text-embedding、``text-embedding-v3 and text-embedding-v4 models. The value can be dense, sparse, or dense&sparse, and the default is dense, which outputs only continuous vectors. Sparse vector output (sparse and dense&amp;sparse) is only supported when called through the DashScope API.

instruct string Optional

Add a custom task description to guide the model in understanding the query intent. It is recommended to write it in English, which typically brings about a 1%–5% performance improvement.

This parameter only takes effect when text_type is set to query, and the Token usage is counted based on the number of input texts. When text_type is set to document or text_type is not set, this parameter does not take effect and is not counted in Token usage.

Input string

Python

import os
import dashscope

# The following configuration is for the Singapore (ap-southeast-1) 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 the following line with your Model Studio API key: api_key="sk-xxx"
    # API keys are region-specific. To get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

resp = client.embeddings.create(
    model="qwen3.7-text-embedding",
    input='风急天高猿啸哀, 渚清沙白鸟飞回, 无边落木萧萧下, 不尽长江滚滚来',
    dimension=1024,  # Specify the vector dimension (only supported by qwen3.7-text-embedding, text-embedding-v3, and text-embedding-v4)
    output_type="dense&sparse"
)

print(resp)

Java

import java.util.Arrays;
import java.util.concurrent.Semaphore;
import com.alibaba.dashscope.common.ResultCallback;
import com.alibaba.dashscope.embeddings.TextEmbedding;
import com.alibaba.dashscope.embeddings.TextEmbeddingParam;
import com.alibaba.dashscope.embeddings.TextEmbeddingResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;

public final class Main {
    static {
        // The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
        Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }
    public static void basicCall() throws ApiException, NoApiKeyException{
        TextEmbeddingParam param = TextEmbeddingParam
        .builder()
        .model("qwen3.7-text-embedding")
        .texts(Arrays.asList("风急天高猿啸哀", "渚清沙白鸟飞回", "无边落木萧萧下", "不尽长江滚滚来")).build();
        TextEmbedding textEmbedding = new TextEmbedding();
        TextEmbeddingResult result = textEmbedding.call(param);
        System.out.println(result);
    }

    public static void callWithCallback() throws ApiException, NoApiKeyException, InterruptedException{
        TextEmbeddingParam param = TextEmbeddingParam
        .builder()
        .model(TextEmbedding.Models.TEXT_EMBEDDING_V3)
        .texts(Arrays.asList("风急天高猿啸哀", "渚清沙白鸟飞回", "无边落木萧萧下", "不尽长江滚滚来")).build();
        TextEmbedding textEmbedding = new TextEmbedding();
        Semaphore sem = new Semaphore(0);
        textEmbedding.call(param, new ResultCallback<TextEmbeddingResult>() {

          @Override
          public void onEvent(TextEmbeddingResult message) {
            System.out.println(message);
          }
          @Override
          public void onComplete(){
            sem.release();
          }

          @Override
          public void onError(Exception err){
            System.out.println(err.getMessage());
            err.printStackTrace();
            sem.release();
          }

        });
        sem.acquire();
    }

  public static void main(String[] args){
    try{
      callWithCallback();
    }catch(ApiException|NoApiKeyException|InterruptedException e){
      e.printStackTrace();
      System.out.println(e);

    }
      try {
        basicCall();
    } catch (ApiException | NoApiKeyException e) {
        System.out.println(e.getMessage());
    }
    System.exit(0);
  }
}

curl

If you use a model in the China (Beijing) region, use an API KEY from the China (Beijing) region and replace the url with: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding. The following is the URL for the Singapore region. When calling, replace {WorkspaceId} with the actual workspace ID. The URLs vary by region.

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "qwen3.7-text-embedding",
    "input": {
        "texts": [
        "风急天高猿啸哀,渚清沙白鸟飞回,无边落木萧萧下,不尽长江滚滚来"
        ]
    },
    "parameters": {
        "dimension": 1024,
        "output_type": "dense"
    }
}'

Input string list

Python

import os
import dashscope
from dashscope import DashScopeError

# The following configuration is for the Singapore (ap-southeast-1) 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 the following line with your Model Studio API key: api_key="sk-xxx"
    # API keys are region-specific. To get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)
DASHSCOPE_MAX_BATCH_SIZE = 10

inputs = ['风急天高猿啸哀', '渚清沙白鸟飞回', '无边落木萧萧下', '不尽长江滚滚来']

result = None
batch_counter = 0
try:
    for i in range(0, len(inputs), DASHSCOPE_MAX_BATCH_SIZE):
        batch = inputs[i:i + DASHSCOPE_MAX_BATCH_SIZE]
        resp = client.embeddings.create(
            model="qwen3.7-text-embedding",
            input=batch,
            dimension=1024  # Specify the vector dimension (only supported by qwen3.7-text-embedding, text-embedding-v3, and text-embedding-v4)
        )
        if result is None:
            result = resp
        else:
            for emb in resp.embeddings:
                emb.index += batch_counter
                result.embeddings.append(emb)
            result.usage.total_tokens += resp.usage.total_tokens
        batch_counter += len(batch)
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("See: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code")

print(result)

Java

import java.util.Arrays;
import java.util.List;
import com.alibaba.dashscope.embeddings.TextEmbedding;
import com.alibaba.dashscope.embeddings.TextEmbeddingParam;
import com.alibaba.dashscope.embeddings.TextEmbeddingResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;

public final class Main {
    static {
        // The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
        Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }
    private static final int DASHSCOPE_MAX_BATCH_SIZE = 10;

    public static void main(String[] args) {
        List<String> inputs = Arrays.asList(
                "风急天高猿啸哀",
                "渚清沙白鸟飞回",
                "无边落木萧萧下",
                "不尽长江滚滚来"
        );

        TextEmbeddingResult result = null;
        int batchCounter = 0;

        for (int i = 0; i < inputs.size(); i += DASHSCOPE_MAX_BATCH_SIZE) {
            List<String> batch = inputs.subList(i, Math.min(i + DASHSCOPE_MAX_BATCH_SIZE, inputs.size()));
            TextEmbeddingParam param = TextEmbeddingParam.builder()
                    .model("qwen3.7-text-embedding")
                    .texts(batch)
                    .build();

            TextEmbedding textEmbedding = new TextEmbedding();
            try {
                TextEmbeddingResult resp = textEmbedding.call(param);
                if (resp != null) {
                    if (result == null) {
                        result = resp;
                    } else {
                        for (var emb : resp.getOutput().getEmbeddings()) {
                            emb.setTextIndex(emb.getTextIndex() + batchCounter);
                            result.getOutput().getEmbeddings().add(emb);
                        }
                        result.getUsage().setTotalTokens(result.getUsage().getTotalTokens() + resp.getUsage().getTotalTokens());
                    }
                } else {
                    System.out.println(resp);
                }
            } catch (ApiException | NoApiKeyException e) {
                e.printStackTrace();
            }
            batchCounter += batch.size();
        }

        System.out.println(result);
    }
}

curl

If you use a model in the China (Beijing) region, use an API KEY from the China (Beijing) region and replace the url with: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding. The following is the URL for the Singapore region. When calling, replace {WorkspaceId} with the actual workspace ID. The URLs vary by region.

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "qwen3.7-text-embedding",
    "input": {
        "texts": [
          "风急天高猿啸哀",
          "渚清沙白鸟飞回",
          "无边落木萧萧下",
          "不尽长江滚滚来"
        ]
    },
    "parameters": {
          "dimension": 1024,
          "output_type": "dense"
    }
}'

Input file

Python

import os
import dashscope

# The following configuration is for the Singapore (ap-southeast-1) 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 the following line with your Model Studio API key: api_key="sk-xxx"
    # API keys are region-specific. To get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

# Make sure to replace 'texts_to_embedding.txt' with your own file name or path
with open('texts_to_embedding.txt', 'r', encoding='utf-8') as f:
    resp = client.embeddings.create(
        model="qwen3.7-text-embedding",
        input=f,
        dimension=1024  # Specify the vector dimension (only supported by qwen3.7-text-embedding, text-embedding-v3, and text-embedding-v4)
    )

    print(resp)

Java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.alibaba.dashscope.embeddings.TextEmbedding;
import com.alibaba.dashscope.embeddings.TextEmbeddingParam;
import com.alibaba.dashscope.embeddings.TextEmbeddingResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;

public final class Main {
    static {
        // The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
        Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }
    public static void main(String[] args) {
        // Replace 'tests_to_embedding.txt' with the full path to your file
        try (BufferedReader reader = new BufferedReader(new FileReader("tests_to_embedding.txt"))) {
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }

            TextEmbeddingParam param = TextEmbeddingParam.builder()
                    .model("qwen3.7-text-embedding")
                    .text(content.toString())
                    .build();

            TextEmbedding textEmbedding = new TextEmbedding();
            TextEmbeddingResult result = textEmbedding.call(param);

            if (result != null) {
                System.out.println(result);
            } else {
                System.out.println("Failed to get embedding: " + result);
            }
        } catch (IOException | ApiException | NoApiKeyException e) {
            e.printStackTrace();
        }
    }
}

curl

If you use a model in the China (Beijing) region, use an API KEY from the China (Beijing) region and replace the url with: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding. The following is the URL for the Singapore region. When calling, replace {WorkspaceId} with the actual workspace ID. The URLs vary by region.

Make sure to replace 'texts_to_embedding.txt' with your own file name or path

FILE_CONTENT=$(cat texts_to_embedding.txt | jq -Rs .)
curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "qwen3.7-text-embedding",
    "input": {
        "texts": ['"$FILE_CONTENT"']
    },
    "parameters": {
        "dimension": 1024,
        "output_type": "dense"
    }
}'

Response object

In Python SDK 2.0, the fields of the response object returned by client.embeddings.create are as follows (in the JSON returned by the HTTP API, embeddings is wrapped in output).

request_id string

The unique identifier of the request. It can be used for tracing request details and troubleshooting.

embeddingsarray

The algorithm output of this request, which is an array of structures, each containing the algorithm output for the corresponding input text.

Property

sparse_embedding array

The discrete vector representation of the algorithm output for the corresponding string (sparse embedding only applies to text-embedding-v3 and text-embedding-v4).

Property

index integer

The position index of the word or character in the vocabulary.

value float

Indicates the weight or importance score of the Token. A higher value indicates that the Token is more important or relevant in the context of the current text.

token string

The actual text unit or word in the vocabulary.

embedding array

The continuous vector representation of the algorithm output for the corresponding string (dense embedding).

index integer

The index of the input text in the input array that corresponds to the algorithm result in this structure.

usageobject

The token usage of this request. Embedding models only have input and no output, so the values of the fields in this object are always the same.

Property

input_tokens integer

The number of Tokens corresponding to the input content of this request. The value is the same as total_tokens.

Only qwen3.7-text-embedding returns this parameter. text-embedding-v4, text-embedding-v3, text-embedding-v2, and text-embedding-v1 do not return this parameter.

total_tokens integer

The total number of Tokens consumed by this request, used for metering and billing. The Token count is based on the result of the input string parsed by the model Tokenizer, which may differ from the character or word count you estimate on your own.

When instruct is set and text_type is set to query, instruct is counted repeatedly in token usage based on the number of input texts.

Call Failed

When a call fails, the SDK throws DashScopeError. You can obtain failure details through e.status_code (HTTP return code), e.code (error code), e.message (error message), and e.request_id (unique request identifier). For more information, see Error codes.

{
    "request_id": "1ba94ac8-e058-99bc-9cc1-7fdb37940a46",
    "embeddings": [
      {
         "index": 0,
         "sparse_embedding":[
           {"index":7149,"value":0.829,"token":"风"},
           .....
           {"index":111290,"value":0.9004,"token":"哀"}],
         "embedding": [-0.006929283495992422,-0.005336422007530928, ...]
      },
      {
         "index": 1,
         "sparse_embedding":[
           {"index":246351,"value":1.0483,"token":"渚"},
           .....
           {"index":2490,"value":0.8579,"token":"回"}],
         "embedding": [-0.006929283495992422,-0.005336422007530928, ...]
      },
      {
         "index": 2,
         "sparse_embedding":[
           {"index":3759,"value":0.7065,"token":"无"},
           .....
           {"index":1130,"value":0.815,"token":"下"}],
         "embedding": [-0.006929283495992422,-0.005336422007530928, ...]
      },
      {
         "index": 3,
         "sparse_embedding":[
           {"index":562,"value":0.6752,"token":"不"},
           .....
           {"index":1589,"value":0.7097,"token":"来"}],
         "embedding": [-0.001945948973298072,-0.005336422007530928, ...]
      }
    ],
    "usage":{
        "total_tokens":27
    }
}
{
    "code":"InvalidApiKey",
    "message":"Invalid API-key provided.",
    "request_id":"xxxxxxxx"
}

Error codes

If a model call fails and returns an error message, see Error codes for troubleshooting.