All Products
Search
Document Center

Alibaba Cloud Model Studio:Synchronous API

Last Updated:Oct 11, 2026

The general-purpose text embedding model converts text data into numerical vectors for downstream tasks like semantic search, recommendation, clustering, and classification.

Model overview

Singapore

ModelEmbedding dimensionsMax rows

Max tokens per line(Note)

Price (per 1M input tokens)Supported languages

Free quota(Note)

qwen3.7-text-embedding

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

20

128,000

$0.07

Chinese, English, Spanish, French, Portuguese, Indonesian, Japanese, Korean, German, Russian, and over 200 other major languages and dialects

1 million tokens

Validity: 90 days after you activate Model Studio

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

Chinese, English, Spanish, French, Portuguese, Indonesian, Japanese, Korean, German, Russian, and over 100 other major languages

1 million tokens

Validity: 90 days after you activate Model Studio

text-embedding-v3

1,024 (default), 768, 512

Chinese, English, Spanish, French, Portuguese, Indonesian, Japanese, Korean, German, Russian, and over 50 other major languages

500,000 tokens

Validity: 90 days after you activate Model Studio

China (Beijing)

ModelEmbedding dimensionsMax rowsMax tokens per linePrice (per 1M 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

Chinese, English, Spanish, French, Portuguese, Indonesian, Japanese, Korean, German, Russian, and over 100 other major languages, plus multiple programming languages

China (Hong Kong)

ModelEmbedding dimensionsMax rowsMax tokens per linePrice (per 1M 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

Chinese, English, Spanish, French, Portuguese, Indonesian, Japanese, Korean, German, Russian, and over 100 other major languages, plus multiple programming languages

For model rate limits, see Rate limiting.

Prerequisites

Users familiar with the OpenAI ecosystem can use the OpenAI-compatible API for a quick migration. The DashScope API provides more unique features.

Obtain an API key and export the API key as an environment variable. If you use an SDK to make calls, install the DashScope SDK.

OpenAI compatibility

Thebase_urlto configure for SDK calls:

  • Singapore: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1. Replace WorkspaceId with your actual workspace ID.
  • China (Beijing): https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1
  • China (Hong Kong): https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1. Replace WorkspaceId with your actual workspace ID.

Theendpointto configure for HTTP calls:

  • Singapore: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/embeddings. Replace WorkspaceId with your actual workspace ID.
  • China (Beijing): POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/embeddings
  • China (Hong Kong): POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1/embeddings. Replace WorkspaceId with your actual workspace ID.

Replace {WorkspaceId} with your actual workspace ID.

Request body

modelstringrequired

The name of the model to call. See the Model overview table for model names.

inputarray<string> or string or filerequired

The input text to process. The input can be a string, an array of strings, or a file. Limits on text length and batch size vary by model version:

  • qwen3.7-text-embedding model:
    • String input: Up to 128,000 tokens.
    • String list or file input: Up to 20 items (lines), with each item (line) up to 128,000 tokens.
  • text-embedding-v3 / v4 models:
    • String input: Maximum length of 8,192 tokens.
    • String list or file input: Up to 10 items (lines), with each item (line) up to 8,192 tokens.

dimensions integer optional

The dimension of the output embedding vectors. Must be one of the following values: 2560 (for qwen3.7-text-embedding only),2048 (for text-embedding-v4 only), 1536 (for text-embedding-v4 only), 1024, 768, 512, 256, 128, or 64. The default value is 1024.

encoding_format string optional

The returned embedding format. Currently, only float is supported.

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 not set, replace the placeholder with your API key.
    # This is the Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs differ 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;
        }
        // This is the Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs differ 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", "The wind is strong, the sky is high, and the apes cry mournfully. The islet is clear, the sand is white, and the birds fly back. The boundless forest sheds its leaves shower by shower. The endless river rolls on wave after wave.");
        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 a model in the China (Beijing) region, you must use an API key from that region and replace the URL with https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/embeddings. The code example below uses the Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs differ by region.

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": "The wind is strong, the sky is high, and the apes cry mournfully. The islet is clear, the sand is white, and the birds fly back. The boundless forest sheds its leaves shower by shower. The endless river rolls on wave after wave.",
    "dimensions": 1024,
    "encoding_format": "float"
}'

dashscope CLI

Call via 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 "Hello world"

ImportantThe SDK Expert interactive assistant can accomplish the same development and troubleshooting via natural language, see

DashScope SDK Expert.

For the complete region table, see Base URL overview.

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 not set, replace the placeholder with your API key.
    # This is the Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs differ 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 wind is strong, the sky is high, and the apes cry mournfully.', 'The islet is clear, the sand is white, and the birds fly back.', 'The boundless forest sheds its leaves shower by shower.', 'The endless river rolls on wave after wave.'],
    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 an environment variable. If not configured, replace it 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;
        }
        // This is the Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs differ 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("The wind is strong, the sky is high, and the apes cry mournfully.", "The islet is clear, the sand is white, and the birds fly back.", "The boundless forest sheds its leaves shower by shower.", "The endless river rolls on wave after wave.");
        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 the exception.
            System.err.println("Error: " + e.getMessage());
        }
    }
}

curl

If you use a model in the China (Beijing) region, you must use an API key from that region and replace the URL with https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/embeddings. The code example below uses the Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs differ by region.

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": [
        "The wind is strong, the sky is high, and the apes cry mournfully.",
        "The islet is clear, the sand is white, and the birds fly back.",
        "The boundless forest sheds its leaves shower by shower.",
        "The endless river rolls on wave after wave."
        ],
    "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 not set, replace the placeholder with your API key.
    # This is the Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs differ 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 an environment variable. If not configured, replace it 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;
        }
        // This is the Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs differ 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("<path_to_your_content_root>"))) {
            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 a model in the China (Beijing) region, you must use an API key from that region and replace the URL with https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/embeddings. The code example below uses the Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs differ by region.

Replace 'texts_to_embedding.txt' with your 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

A list of the resulting embedding objects.

Property

embeddinglist

The embedding vector, returned as an array of floating-point numbers.

indexinteger

The index of the corresponding input text in the input array.

objectstring

The object type. The value is always embedding.

modelstring

The name of the model used for this call.

objectstring

The object type. The value is always list.

usageobject

Property

prompt_tokensinteger

The number of tokens in the input text.

total_tokens integer

The total number of tokens in the input. This count is determined by how the model's tokenizer parses the input string.

idstring

A unique request identifier, used for tracing 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_urlfor SDK calls:

  • Singapore: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1. Replace WorkspaceId with your actual workspace ID.
  • China (Beijing): https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1
  • China (Hong Kong): https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1. Replace WorkspaceId with your actual workspace ID.
Endpoint for HTTP calls:
  • Singapore: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding. Replace WorkspaceId with your actual workspace ID.
  • China (Beijing): POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding
  • China (Hong Kong): POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding. Replace WorkspaceId with your actual workspace ID.

Replace {WorkspaceId} with your actual workspace ID.

Request body

modelstringrequired

The model to use. For a list of available models, see the Model overview table.

inputstringorarray<string>required

The text to process. The input can be a string, an array of strings, or a file. The supported text length and batch size vary by model version.

  • qwen3.7-text-embedding model:
    • String input: Up to 128,000 tokens.
    • String list or file input: Up to 20 items (lines), with each item (line) up to 128,000 tokens.
  • text-embedding-v3 / v4 models:
    • String input: Maximum length of 8,192 tokens.
    • String list or file input: Up to 10 items (lines), with each item (line) up to 8,192 tokens.

text_type stringoptional

When making an HTTP call, place text_typein the parameters object.

Text converted to embeddings can be applied to downstream tasks such as retrieval, clustering, and classification. For asymmetric tasks such as retrieval, it is recommended to differentiate between query text (query) and document text (document) to achieve better retrieval performance. For symmetric tasks such as indexing, clustering, and classification, you can simply use the system default value of document.

dimension integer optional

When making an HTTP call, place dimensionin the parameters object.

Specifies the embedding dimension for the output vector. Valid values are 2560 (for qwen3.7-text-embedding only),2048 (for text-embedding-v4 only), 1536 (for text-embedding-v4 only), 1024, 768, 512, 256, 128, or 64. Defaults to 1024.

output_type string optional

When making an HTTP call, place output_typein the parameters object.

Specifies the output vector type. This parameter applies only to the qwen3.7-text-embedding,``text-embedding-v3, and text-embedding-v4 models. Valid values are dense, sparse, and dense&sparse. Defaults to dense, which returns only the dense vector representation. Sparse vector outputs (sparse and dense&sparse) are supported only through the DashScope API.

instruct string optional

Provides custom instructions to guide the model in understanding the query intent. English instructions are recommended, as they typically improve performance by 1% to 5%.

Input string

Python

import dashscope
from http import HTTPStatus

# This is the Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs differ by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

resp = dashscope.TextEmbedding.call(
    model="qwen3.7-text-embedding",
    input='A swift wind, a high sky, and the gibbons cry mournfully. A clear islet, white sand, and the birds fly back. Boundless rustling woods shed their leaves. The endless Yangtze River comes rolling in.',
    dimension=1024,
    output_type="dense&sparse"
)

print(resp) if resp.status_code == HTTPStatus.OK else 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 {
        // This is the Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs differ 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("A swift wind, a high sky, and the gibbons cry mournfully.", "A clear islet, white sand, and the birds fly back.", "Boundless rustling woods shed their leaves.", "The endless Yangtze River comes rolling in.")).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("A swift wind, a high sky, and the gibbons cry mournfully.", "A clear islet, white sand, and the birds fly back.", "Boundless rustling woods shed their leaves.", "The endless Yangtze River comes rolling in.")).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 for that region and replace the URL with: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding. The code example below uses the Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs differ 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": [
        "A swift wind, a high sky, and the gibbons cry mournfully. A clear islet, white sand, and the birds fly back. Boundless rustling woods shed their leaves. The endless Yangtze River comes rolling in."
        ]
    },
    "parameters": {
        "dimension": 1024,
        "output_type": "dense"
    }
}'

Input string list

Python

import dashscope
from http import HTTPStatus

# This is the Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs differ by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
DASHSCOPE_MAX_BATCH_SIZE = 10

inputs = ['A swift wind, a high sky, and the gibbons cry mournfully.', 'A clear islet, white sand, and the birds fly back.', 'Boundless rustling woods shed their leaves.', 'The endless Yangtze River comes rolling in.']

result = None
batch_counter = 0
for i in range(0, len(inputs), DASHSCOPE_MAX_BATCH_SIZE):
    batch = inputs[i:i + DASHSCOPE_MAX_BATCH_SIZE]
    resp = dashscope.TextEmbedding.call(
        model="qwen3.7-text-embedding",
        input=batch,
        dimension=1024
    )
    if resp.status_code == HTTPStatus.OK:
        if result is None:
            result = resp
        else:
            for emb in resp.output['embeddings']:
                emb['text_index'] += batch_counter
                result.output['embeddings'].append(emb)
            result.usage['total_tokens'] += resp.usage['total_tokens']
    else:
        print(resp)
    batch_counter += len(batch)

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 {
        // This is the Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs differ 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(
                "A swift wind, a high sky, and the gibbons cry mournfully.",
                "A clear islet, white sand, and the birds fly back.",
                "Boundless rustling woods shed their leaves.",
                "The endless Yangtze River comes rolling in."
        );

        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 for that region and replace the URL with: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding. The code example below uses the Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs differ 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": [
          "A swift wind, a high sky, and the gibbons cry mournfully.",
          "A clear islet, white sand, and the birds fly back.",
          "Boundless rustling woods shed their leaves.",
          "The endless Yangtze River comes rolling in."
        ]
    },
    "parameters": {
          "dimension": 1024,
          "output_type": "dense"
    }
}'

Input file

Python

import dashscope
from http import HTTPStatus
from dashscope import TextEmbedding

# This is the Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs differ by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# 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 = TextEmbedding.call(
        model="qwen3.7-text-embedding",
        input=f,
        dimension=1024
    )

    if resp.status_code == HTTPStatus.OK:
        print(resp)
    else:
        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 {
        // This is the Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs differ by region.
        Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }
    public static void main(String[] args) {
        // Replace 'texts_to_embedding.txt' with the path to your file.
        try (BufferedReader reader = new BufferedReader(new FileReader("texts_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 for that region and replace the URL with: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding. The code example below uses the Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs differ by region.

Replace 'texts_to_embedding.txt' with your 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

status_code string

The HTTP status code. A value of 200 indicates success.

request_id string

A unique identifier for the request. Use this ID to trace and troubleshoot the request.

code string

The error code returned if the request fails. This field is empty for successful requests.

message string

A detailed error message if the request fails. This field is empty for successful requests.

outputobject

The result of the task.

Properties

embeddingsarray

The model's output for the request. This is an array of objects, with each object corresponding to an input text.

Properties

sparse_embedding array

The sparse vector representation of the corresponding string. This applies only to text-embedding-v3 and text-embedding-v4.

Properties

index integer

The index of the token in the vocabulary.

value float

Indicates the weight or importance score of the Token. The higher the value, the greater the importance or relevance of the Token in the current text context.

token string

The text of the token.

embedding array

The dense vector representation for the corresponding string.

text_index integer

The index of the corresponding text in the input array.

usageobject

Properties

total_tokens integer

The number of tokens in the input, as calculated by the model's tokenizer.

{   "status_code": 200,
    "request_id": "1ba94ac8-e058-99bc-9cc1-7fdb37940a46",
    "code": "",
    "message": "",
    "output":{
        "embeddings": [
          {
             "sparse_embedding":[
               {"index":7149,"value":0.829,"token":"swift"},
               .....
               {"index":111290,"value":0.9004,"token":"mournfully"}],
             "embedding": [-0.006929283495992422,-0.005336422007530928, ...],
             "text_index": 0
          },
          {
             "sparse_embedding":[
               {"index":246351,"value":1.0483,"token":"islet"},
               .....
               {"index":2490,"value":0.8579,"token":"back"}],
             "embedding": [-0.006929283495992422,-0.005336422007530928, ...],
             "text_index": 1
          },
          {
             "sparse_embedding":[
               {"index":3759,"value":0.7065,"token":"Boundless"},
               .....
               {"index":1130,"value":0.815,"token":"leaves"}],
             "embedding": [-0.006929283495992422,-0.005336422007530928, ...],
             "text_index": 2
          },
          {
             "sparse_embedding":[
               {"index":562,"value":0.6752,"token":"endless"},
               .....
               {"index":1589,"value":0.7097,"token":"in"}],
             "embedding": [-0.001945948973298072,-0.005336422007530928, ...],
             "text_index": 3
          }
        ]
    },
    "usage":{
        "total_tokens":27
    }
}
{
    "code":"InvalidApiKey",
    "message":"Invalid API-key provided.",
    "request_id":"xxxxxxxx"
}

Error codes

If a model call fails, see Error Messages.