Synchronous API

Updated at:

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

Model overview

Beijing

ModelEmbedding dimensionsMax rows

Maxtokensper line

Price (per 1K 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

CNY 0.0005

Batch call: CNY 0.00025

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

qwen3.7-text-embedding-flash

1,024 (default), 768, 512, 256

20

128,000

CNY 0.000125

Batch call: CNY 0.000063

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

Belongs to the Qwen3-Embedding series

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

10

8,192

CNY 0.0005

Batch call: CNY 0.00025

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

1 million tokens

Validity: 90 days after you activate Model Studio

text-embedding-v3

1,024 (default), 768, 512, 256, 128, or 64

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

No free quota

text-embedding-v2

1,536

25

2,048

CNY 0.0007

Batch call: CNY 0.00035

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

No free quota

text-embedding-v1

Chinese, English, Spanish, French, Portuguese, Indonesian

Singapore

ModelEmbedding dimensionsMax rows

MaxTokenper line

Price (per 1K input tokens)Supported languagesFree quota

qwen3.7-text-embedding

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

20

128,000

CNY 0.000525

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

No free quota

text-embedding-v4

Belongs to the Qwen3-Embedding series

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

10

8,192

CNY 0.000514

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

No free quota

text-embedding-v3

1,024 (default), 768, 512

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

No free quota

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. Choose the one that suits your needs.

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

Public cloud

The base_url to configure when calling with the SDK:https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1

The endpoint to configure when calling over HTTP:POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/embeddings

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: A maximum of 10 items (lines), where each item (line) can be up to 8,192 tokens.
  • text-embedding-v1 / v2 models:
    • String input: Maximum length of 2,048 tokens.
    • String list or file input: A maximum of 25 items (lines), where each item (line) can be up to 2,048 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

Controls the format of the returned embeddings. The input parameter supports float and base64, and the embedding data in the output also supports both float and base64 formats. The format actually returned depends on the gateway that the request is routed to:

  • Old gateway: Regardless of whether encoding_format is set to float or base64, only float data is returned. base64 output is not supported.

  • New gateway:

    • Short requests: Data is returned in the format specified by encoding_format.
    • Long requests: These requests are internally routed to the old gateway and return only float data.

Input string

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # 如果您没有配置环境变量,请在此处用您的API Key进行替换
    # 以下为华北2(北京)地域的URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
)

completion = client.embeddings.create(
    model="qwen3.7-text-embedding",
    input='衣服的质量杠杠的,很漂亮,不枉我等了这么久啊,喜欢,以后还来这里买',
    dimensions=1024, # 指定向量维度(仅 qwen3.7-text-embedding、text-embedding-v3及 text-embedding-v4支持该参数)
    encoding_format="float"
)

print(completion.model_dump_json())
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.embeddings.CreateEmbeddingResponse;
import com.openai.models.embeddings.EmbeddingCreateParams;

public class Main {
    public static void main(String[] args) {
        // 创建客户端,使用环境变量中的API密钥
        OpenAIClient client = OpenAIOkHttpClient.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // 以下为华北2(北京)地域的URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
                .baseUrl("https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1")
                .build();

        // 创建向量化请求参数
        EmbeddingCreateParams params = EmbeddingCreateParams.builder()
                .model("qwen3.7-text-embedding")
                .input(EmbeddingCreateParams.Input.ofString("衣服的质量杠杠的,很漂亮,不枉我等了这么久啊,喜欢,以后还来这里买"))
                // 指定向量维度(仅 qwen3.7-text-embedding、text-embedding-v3及 text-embedding-v4支持该参数)
                .dimensions(1024)
                .build();

        try {
            // 发送请求并获取响应
            CreateEmbeddingResponse response = client.embeddings().create(params);
            System.out.println(response);
        } catch (Exception e) {
            System.err.println("请求出错,请查看错误码对照网页:");
            System.err.println("https://help.aliyun.com/zh/model-studio/faq-about-alibaba-cloud-model-studio?spm=a2c4g.11186623.help-menu-2400256.d_0_17_0.18733a66lTrcHv#1c38f58abfcml");
            System.err.println("错误详情:" + e.getMessage());
            e.printStackTrace();
        }
    }
}
curl --location 'https://{WorkspaceId}.cn-beijing.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"
}'
# 通过 dashscope 命令行调用
export DASHSCOPE_API_KEY="your-api-key"
# 将 {WorkspaceId} 替换为业务空间ID,cn-beijing 替换为对应地域(新加坡: ap-southeast-1, 美东: us-east-1)
export DASHSCOPE_HTTP_BASE_URL="https://{WorkspaceId}.cn-beijing.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 in natural language. See

DashScope SDK Expert.

Input string list

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # 如果您没有配置环境变量,请在此处用您的API Key进行替换
    # 以下为华北2(北京)地域的URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
)

completion = client.embeddings.create(
    model="qwen3.7-text-embedding",
    input=['风急天高猿啸哀', '渚清沙白鸟飞回', '无边落木萧萧下', '不尽长江滚滚来'],
    dimensions=1024,# 指定向量维度(仅 qwen3.7-text-embedding、text-embedding-v3及 text-embedding-v4支持该参数)
    encoding_format="float"
)

print(completion.model_dump_json())
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.embeddings.CreateEmbeddingResponse;
import com.openai.models.embeddings.EmbeddingCreateParams;

import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        // 创建客户端,使用环境变量中的API密钥
        OpenAIClient client = OpenAIOkHttpClient.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // 以下为华北2(北京)地域的URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
                .baseUrl("https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1")
                .build();

        // 创建输入字符串列表
        List<String> inputList = Arrays.asList(
            "风急天高猿啸哀",
            "渚清沙白鸟飞回",
            "无边落木萧萧下",
            "不尽长江滚滚来"
        );

        // 存储所有响应的列表
        List<CreateEmbeddingResponse> responses = new ArrayList<>();

        // 循环处理每个字符串
        for (String text : inputList) {
            try {
                // 创建向量化请求参数
                EmbeddingCreateParams params = EmbeddingCreateParams.builder()
                        .model("qwen3.7-text-embedding")
                        .input(EmbeddingCreateParams.Input.ofString(text))
                        // 指定向量维度(仅 qwen3.7-text-embedding、text-embedding-v3及 text-embedding-v4支持该参数)
                        .dimensions(1024)
                        .build();

                // 发送请求并获取响应
                CreateEmbeddingResponse response = client.embeddings().create(params);
                responses.add(response);
                System.out.println("处理文本: " + text);
                System.out.println("向量化结果: " + response);
                System.out.println("------------------------");
            } catch (Exception e) {
                System.err.println("处理文本时出错: " + text);
                System.err.println("错误详情:" + e.getMessage());
                e.printStackTrace();
            }
        }

        // 打印总结信息
        System.out.println("\n总共处理了 " + responses.size() + " 个文本");
    }
}
curl --location 'https://{WorkspaceId}.cn-beijing.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(
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # 如果您没有配置环境变量,请在此处用您的API Key进行替换
    # 以下为华北2(北京)地域的URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
)
# 确保将 'texts_to_embedding.txt' 替换为您自己的文件名或路径
with open('texts_to_embedding.txt', 'r', encoding='utf-8') as f:
    completion = client.embeddings.create(
        model="qwen3.7-text-embedding",
        input=f,
        dimensions=1024,# 指定向量维度(仅 qwen3.7-text-embedding、text-embedding-v3及 text-embedding-v4支持该参数)
        encoding_format="float"
    )
print(completion.model_dump_json())

Java

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.embeddings.CreateEmbeddingResponse;
import com.openai.models.embeddings.EmbeddingCreateParams;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Paths;

public class Main {
    public static void main(String[] args) {
        // 创建客户端,使用环境变量中的API密钥
        OpenAIClient client = OpenAIOkHttpClient.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // 以下为华北2(北京)地域的URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
                .baseUrl("https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1")
                .build();

        // 确保将 'texts_to_embedding.txt' 替换为您自己的文件名或绝对路径
        String filePath = "/src/main/java/org/example/text_to_embedding.txt";

        try {
            // 读取文件内容
            StringBuilder fileContent = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    fileContent.append(line).append("\n");
                }
            }

            // 创建向量化请求参数
            EmbeddingCreateParams params = EmbeddingCreateParams.builder()
                    .model("qwen3.7-text-embedding")
                    .input(EmbeddingCreateParams.Input.ofString(fileContent.toString()))
                    // 指定向量维度(仅 qwen3.7-text-embedding、text-embedding-v3及 text-embedding-v4支持该参数)
                    .dimensions(1024)
                    .build();

            // 发送请求并获取响应
            CreateEmbeddingResponse response = client.embeddings().create(params);
            System.out.println(response);

        } catch (IOException e) {
            System.err.println("读取文件时出错:" + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("请求出错,请查看错误码对照网页:");
            System.err.println("https://help.aliyun.com/zh/model-studio/faq-about-alibaba-cloud-model-studio?spm=a2c4g.11186623.help-menu-2400256.d_0_17_0.18733a66lTrcHv#1c38f58abfcml");
            System.err.println("错误详情:" + e.getMessage());
            e.printStackTrace();
        }
    }
}

curl

Replace 'texts_to_embedding.txt' with your file name or path.

FILE_CONTENT=$(cat texts_to_embedding.txt | jq -Rs .)
curl --location 'https://{WorkspaceId}.cn-beijing.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 returned by this call. The default value is embedding.

modelstring

The name of the model used for this call.

objectstring

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

usageobject

Token usage. qwen3.7-text-embedding-flash returns prompt_tokens and total_tokens; other existing text embedding models return only total_tokens.

Property

prompt_tokensinteger

Returned only by qwen3.7-text-embedding-flash. The total number of tokens in the request input. Its value is the same as total_tokens.

total_tokens integer

The total number of tokens in the request, used for billing and audit. The token count is based on how the model's tokenizer parses the input string, and may differ from your own estimates based on character or word counts.

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": {
    "total_tokens": 184
  },
  "id": "73591b79-d194-9bca-8bb5-xxxxxxxxxxxx"
}
{
  "data": [
    {
      "embedding": [-0.0695386752486229, 0.030681096017360687, ...],
      "index": 0,
      "object": "embedding"
    }
  ],
  "model": "qwen3.7-text-embedding-flash",
  "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

Public cloud

The base_url to configure when calling with the SDK:https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1

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

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 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 and qwen3.7-text-embedding-flash models:
    • 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: A maximum of 10 items (lines), where each item (line) can be up to 8,192 tokens.
  • text-embedding-v1 / v2 models:
    • String input: Maximum length of 2,048 tokens.
    • String list or file input: A maximum of 25 items (lines), where each item (line) can be up to 2,048 tokens.

text_type stringoptional

When calling over HTTP, put text_type in 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 calling over HTTP, put dimension in the parameters object.

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.

output_type string optional

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

Specifying discrete vector output applies only to the qwen3.7-text-embedding、``text-embedding-v3 and text-embedding-v4 models. Valid values are dense, sparse, and dense&sparse. The default is dense, which outputs continuous vectors only. Sparse vector output (sparse and dense&amp;sparse) is supported only when the model is called 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%.

This parameter takes effect only when text_type is set to query, and it is counted in token usage 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

import os
import dashscope
# 以下为华北2(北京)地域的配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的region取值不同。
client = dashscope.Client(
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
    # 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

resp = client.embeddings.create(
    model="qwen3.7-text-embedding",
    input='衣服的质量杠杠的,很漂亮,不枉我等了这么久啊,喜欢,以后还来这里买',
    dimension=1024,  # 指定向量维度(仅 qwen3.7-text-embedding、text-embedding-v3及 text-embedding-v4支持该参数)
    output_type="dense&sparse"
)

print(resp)
import java.util.Arrays;
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 {
    public static void main(String[] args) {
        // 以下为华北2(北京)地域的配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的配置不同。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
        try {
            // 构建请求参数
            TextEmbeddingParam param = TextEmbeddingParam
                    .builder()
                    .model("qwen3.7-text-embedding")  // 使用text-embedding-v4模型
                    .texts(Arrays.asList("衣服的质量杠杠的,很漂亮,不枉我等了这么久啊,喜欢,以后还来这里买"))  // 输入文本
                    .parameter("dimension", 1024)  // 指定向量维度(仅 qwen3.7-text-embedding、text-embedding-v3及 text-embedding-v4支持该参数)
                    .build();

            // 创建模型实例并调用
            TextEmbedding textEmbedding = new TextEmbedding();
            TextEmbeddingResult result = textEmbedding.call(param);

            // 输出结果
            System.out.println(result);

        } catch (ApiException | NoApiKeyException e) {
            System.out.println("调用失败:" + e.getMessage());
        }
    }
}
curl --location 'https://{WorkspaceId}.cn-beijing.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

import os
import dashscope
from dashscope import DashScopeError
# 以下为华北2(北京)地域的配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的region取值不同。
client = dashscope.Client(
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
    # 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

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  # 指定向量维度(仅 qwen3.7-text-embedding、text-embedding-v3及 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返回码:{e.status_code}")
    print(f"错误码:{e.code}")
    print(f"错误信息:{e.message}")
    print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")

print(result)
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.embeddings.TextEmbeddingResultItem;
import com.alibaba.dashscope.utils.Constants;

public final class Main {
    private static final int DASHSCOPE_MAX_BATCH_SIZE = 10;

    public static void main(String[] args) {
        // 以下为华北2(北京)地域的配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的配置不同。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
        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)
                    .parameter("dimension", 1024)  // 指定向量维度(仅 qwen3.7-text-embedding、text-embedding-v3及 text-embedding-v4支持该参数)
                    .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 --location 'https://{WorkspaceId}.cn-beijing.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
# 以下为华北2(北京)地域的配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的region取值不同。
client = dashscope.Client(
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
    # 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

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 # 指定向量维度(仅 qwen3.7-text-embedding、text-embedding-v3及 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 {
    public static void main(String[] args) {
        // 以下为华北2(北京)地域的配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的配置不同。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
        try (BufferedReader reader = new BufferedReader(new FileReader("<文件所来自的内容根的路径>"))) {
            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())
                    .parameter("dimension", 1024)  // 指定向量维度(仅 qwen3.7-text-embedding、text-embedding-v3及 text-embedding-v4支持该参数)
                    .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

Replace 'texts_to_embedding.txt' with your file name or path.

FILE_CONTENT=$(cat texts_to_embedding.txt | jq -Rs .)
curl --location 'https://{WorkspaceId}.cn-beijing.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 DashScope Python SDK 2.0, the response object returned by client.embeddings.create has the following fields (in the JSON returned by the HTTP API, embeddings is wrapped in output).

request_id string

A unique request identifier, used for tracing and troubleshooting.

embeddingsarray

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

Property

sparse_embedding array

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

Property

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.

index integer

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

usageobject

Token usage. qwen3.7-text-embedding-flash returns prompt_tokens and total_tokens; other existing text embedding models return only total_tokens.

Property

prompt_tokens integer

Returned only by qwen3.7-text-embedding-flash. The total number of tokens in the request input. Its value is the same as total_tokens.

total_tokens integer

The total number of tokens in the request, used for billing and audit. The token count is based on how the model's tokenizer parses the input string, and may differ from your own estimates based on character or word counts.

When instruct is set and text_type is set to query, instruct is counted in token usage repeatedly, once for each input text.

Failed calls

When a call 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 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
    }
}
{
    "request_id": "1ba94ac8-e058-99bc-9cc1-7fdb37940a46",
    "embeddings": [
        {
            "index": 0,
            "embedding": [-0.006929283495992422, -0.005336422007530928, ...]
        }
    ],
    "usage": {
        "prompt_tokens": 27,
        "total_tokens": 27
    }
}
{
    "code":"InvalidApiKey",
    "message":"Invalid API-key provided.",
    "request_id":"xxxxxxxx"
}

Error codes

If a model call fails, see Error Messages.