Tous les produits
Search
Centre de documentation

Alibaba Cloud Model Studio:API synchrone

Dernière mise à jour :Oct 11, 2026

Le modèle d'embedding de texte généraliste convertit des données textuelles en vecteurs numériques. Ces vecteurs alimentent ensuite des tâches en aval telles que la recherche sémantique, la recommandation, le clustering et la classification.

Présentation des modèles

Singapour

ModèleDimensions de l'embeddingNombre maximal de lignes

Nombre maximal de tokens par ligne(Remarque)

Tarif (pour 1 M de tokens en entrée)Langues prises en charge

Quota gratuit(Remarque)

qwen3.7-text-embedding

2 560, 2 048, 1 536, 1 024 (par défaut), 768, 512, 256

20

128 000

0,07 $

Chinois, anglais, espagnol, français, portugais, indonésien, japonais, coréen, allemand, russe, ainsi que plus de 200 autres langues et dialectes majeurs

1 million de tokens

Validité : 90 jours après l'activation de Model Studio

text-embedding-v4

Fait partie de la série Qwen3-Embedding

2 048, 1 536, 1 024 (par défaut), 768, 512, 256, 128, 64

10

8 192

0,07 $

Chinois, anglais, espagnol, français, portugais, indonésien, japonais, coréen, allemand, russe, ainsi que plus de 100 autres langues majeures

1 million de tokens

Validité : 90 jours après l'activation de Model Studio

text-embedding-v3

1 024 (par défaut), 768, 512

Chinois, anglais, espagnol, français, portugais, indonésien, japonais, coréen, allemand, russe, ainsi que plus de 50 autres langues majeures

500 000 tokens

Validité : 90 jours après l'activation de Model Studio

Chine (Pékin)

ModèleDimensions de l'embeddingNombre maximal de lignesNombre maximal de tokens par ligneTarif (pour 1 M de tokens en entrée)Langues prises en charge

text-embedding-v4

Fait partie de la série Qwen3-Embedding

2 048, 1 536, 1 024 (par défaut), 768, 512, 256, 128, 64

10

8 192

0,072 $

Chinois, anglais, espagnol, français, portugais, indonésien, japonais, coréen, allemand, russe, ainsi que plus de 100 autres langues majeures et plusieurs langages de programmation

Chine (Hong Kong)

ModèleDimensions de l'embeddingNombre maximal de lignesNombre maximal de tokens par ligneTarif (pour 1 M de tokens en entrée)Langues prises en charge

text-embedding-v4

Fait partie de la série Qwen3-Embedding

2 048, 1 536, 1 024 (par défaut), 768, 512, 256, 128, 64

10

8 192

0,07 $

Chinois, anglais, espagnol, français, portugais, indonésien, japonais, coréen, allemand, russe, ainsi que plus de 100 autres langues majeures et plusieurs langages de programmation

Pour connaître les limites de taux des modèles, consultez Limitation du débit.

Prérequis

Les utilisateurs familiers de l'écosystème OpenAI peuvent utiliser l'API compatible OpenAI pour une migration rapide. L'API DashScope offre quant à elle des fonctionnalités supplémentaires spécifiques.

Obtenir une clé API et exporter la clé API en tant que variable d'environnement. Si vous utilisez un SDK pour effectuer vos appels, installez le SDK DashScope.

Compatibilité OpenAI

Cloud public

Labase_urlà configurer pour les appels SDK :

L'endpointà configurer pour les appels HTTP :POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/embeddings

Remplacez {WorkspaceId} par votre véritable ID d'espace de travail.

Labase_urlà configurer pour les appels SDK :
  • Singapour : https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1. Remplacez WorkspaceId par votre véritable ID d'espace de travail.
  • Chine (Pékin) : https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1
  • Chine (Hong Kong) : https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1. Remplacez WorkspaceId par votre véritable ID d'espace de travail.
L'endpointà configurer pour les appels HTTP :
  • Singapour : POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/embeddings. Remplacez WorkspaceId par votre véritable ID d'espace de travail.
  • Chine (Pékin) : POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/embeddings
  • Chine (Hong Kong) : POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1/embeddings. Remplacez WorkspaceId par votre véritable ID d'espace de travail.

Remplacez {WorkspaceId} par votre véritable ID d'espace de travail.

Corps de la requête

Chaîne en entrée

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/?tab=model#/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/?tab=model#/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"
    }'

Liste de chaînes en entrée

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/?tab=model#/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/?tab=model#/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"
    }'

Fichier en entrée

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/?tab=model#/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/?tab=model#/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"
}'

modelstringobligatoire

Nom du modèle à appeler. Consultez le tableau Présentation des modèles pour obtenir la liste des noms de modèles.

inputarray<string> or string or fileobligatoire

Texte d'entrée à traiter. L'entrée peut être une chaîne, un tableau de chaînes ou un fichier. Les limites de longueur de texte et de taille de lot varient selon la version du modèle :

  • Modèle qwen3.7-text-embedding :
    • Entrée de type chaîne : jusqu'à 128 000 tokens.
    • Entrée de type liste de chaînes ou fichier : jusqu'à 20 éléments (lignes), chaque élément (ligne) pouvant contenir jusqu'à 128 000 tokens.
  • Modèles text-embedding-v3 / v4 :
    • Entrée de type chaîne : longueur maximale de 8 192 tokens.
    • Entrée de type liste de chaînes ou fichier : jusqu'à 10 éléments (lignes), chaque élément (ligne) pouvant contenir jusqu'à 8 192 tokens.

dimensions integer facultatif

Dimension des vecteurs d'embedding en sortie. Doit correspondre à l'une des valeurs suivantes : 2560 (uniquement pour qwen3.7-text-embedding),2048 (uniquement pour text-embedding-v4), 1536 (uniquement pour text-embedding-v4), 1024, 768, 512, 256, 128 ou 64. La valeur par défaut est 1024.

encoding_format string facultatif

Format des embeddings retournés. Actuellement, seul le format float est pris en charge.

Objet de réponse

{
  "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"
    }
}

dataarray

Liste des objets d'embedding résultants.

Propriété

embeddinglist

Vecteur d'embedding, retourné sous forme de tableau de nombres à virgule flottante.

indexinteger

Index du texte d'entrée correspondant dans le tableau d'entrée.

objectstring

Type d'objet. La valeur est toujours embedding.

modelstring

Nom du modèle utilisé pour cet appel.

objectstring

Type d'objet. La valeur est toujours list.

usageobject

Propriété

prompt_tokensinteger

Nombre de tokens dans le texte d'entrée.

total_tokens integer

Nombre total de tokens dans l'entrée. Ce décompte dépend de la manière dont le tokenizer du modèle analyse la chaîne d'entrée.

idstring

Identifiant unique de la requête, utilisé pour le suivi et le dépannage.

DashScope

Cloud public

base_urlpour les appels SDK : https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1

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

Remplacez {WorkspaceId} par votre véritable ID d'espace de travail.

base_urlpour les appels SDK :
  • Singapour : https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1. Remplacez WorkspaceId par votre véritable ID d'espace de travail.
  • Chine (Pékin) : https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1
  • Chine (Hong Kong) : https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1. Remplacez WorkspaceId par votre véritable ID d'espace de travail.
Endpoint pour les appels HTTP :
  • Singapour : POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding. Remplacez WorkspaceId par votre véritable ID d'espace de travail.
  • Chine (Pékin) : POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding
  • Chine (Hong Kong) : POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding. Remplacez WorkspaceId par votre véritable ID d'espace de travail.

Remplacez {WorkspaceId} par votre véritable ID d'espace de travail.

Request body

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"
    }
}'

modelstringrequired

Modèle à utiliser. Pour consulter la liste des modèles disponibles, reportez-vous au tableau Présentation des modèles.

inputstringouarray<string>required

Texte à traiter. L'entrée peut être une chaîne de caractères, un tableau de chaînes ou un fichier. La longueur du texte et la taille de lot prises en charge varient selon la version du modèle.

  • Modèle qwen3.7-text-embedding :
    • Entrée de type chaîne : jusqu'à 128 000 tokens.
    • Entrée de type liste de chaînes ou fichier : jusqu'à 20 éléments (lignes), chaque élément (ligne) pouvant contenir jusqu'à 128 000 tokens.
  • Modèles text-embedding-v3 / v4 :
    • Entrée de type chaîne : longueur maximale de 8 192 tokens.
    • Entrée de type liste de chaînes ou fichier : jusqu'à 10 éléments (lignes), chaque élément (ligne) pouvant contenir jusqu'à 8 192 tokens.

text_type stringoptional

Lors d'un appel HTTP, placez text_typedans l'objet parameters.

Le texte converti en embeddings peut servir à des tâches en aval telles que la récupération, le clustering et la classification. Pour les tâches asymétriques comme la récupération, il est recommandé de distinguer le texte de requête (query) du texte de document (document) afin d'optimiser les performances. Pour les tâches symétriques telles que l'indexation, le clustering ou la classification, la valeur par défaut du système, document, suffit généralement.

dimension integer optional

Lors d'un appel HTTP, placez dimensiondans l'objet parameters.

Définit la dimension d'embedding pour le vecteur de sortie. Les valeurs valides sont 2560 (uniquement pour qwen3.7-text-embedding),2048 (uniquement pour text-embedding-v4), 1536 (uniquement pour text-embedding-v4), 1024, 768, 512, 256, 128 ou 64. La valeur par défaut est 1024.

output_type string optional

Lors d'un appel HTTP, placez output_typedans l'objet parameters.

Spécifie le type de vecteur de sortie. Ce paramètre s'applique uniquement aux modèles qwen3.7-text-embedding,``text-embedding-v3 et text-embedding-v4. Les valeurs valides sont dense, sparse et dense&sparse. La valeur par défaut est dense, ce qui renvoie uniquement la représentation vectorielle dense.

instruct string optional

Fournit des instructions personnalisées pour guider le modèle dans la compréhension de l'intention de la requête. Il est recommandé d'utiliser des instructions en anglais, car elles améliorent généralement les performances de 1 % à 5 %.

Response object

{   "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"
}

status_code string

Code de statut HTTP. La valeur 200 indique un succès.

request_id string

Identifiant unique de la requête. Utilisez cet ID pour tracer et diagnostiquer la requête.

code string

Code d'erreur renvoyé en cas d'échec de la requête. Ce champ est vide pour les requêtes réussies.

message string

Message d'erreur détaillé en cas d'échec de la requête. Ce champ est vide pour les requêtes réussies.

outputobject

Résultat de la tâche.

Properties

embeddingsarray

Sortie du modèle pour la requête. Il s'agit d'un tableau d'objets, chaque objet correspondant à un texte d'entrée.

Properties

sparse_embedding array

Représentation vectorielle creuse de la chaîne correspondante. Cela s'applique uniquement à text-embedding-v3 et text-embedding-v4.

Properties

index integer

Index du token dans le vocabulaire.

value float

Indique le poids ou le score d'importance du Token. Plus la valeur est élevée, plus l'importance ou la pertinence du Token dans le contexte textuel actuel est grande.

token string

Texte du token.

embedding array

Représentation vectorielle dense pour la chaîne correspondante.

text_index integer

Index du texte correspondant dans le tableau d'entrée.

usageobject

Properties

total_tokens integer

Nombre de tokens dans l'entrée, tel que calculé par le tokenizer du modèle.

Codes d'erreur

En cas d'échec lors de l'appel d'un modèle, consultez la rubrique Messages d'erreur.