Todos los productos
Search
Centro de documentos

Alibaba Cloud Model Studio:API síncrona

Última actualización: Oct 12, 2026

El modelo de embedding de texto de propósito general convierte datos de texto en vectores numéricos para tareas posteriores como búsqueda semántica, recomendación, agrupación y clasificación.

Resumen de modelos

Singapore

ModeloDimensiones de embeddingFilas máximas

Máximo de tokens por línea(Nota)

Precio (por 1M tokens de entrada)Idiomas admitidos

Cuota gratuita(Nota)

qwen3.7-text-embedding

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

20

128,000

$0.07

Chino, inglés, español, francés, portugués, indonesio, japonés, coreano, alemán, ruso y más de 200 idiomas y dialectos principales adicionales

1 millón de tokens

Validez: 90 días después de activar Model Studio

text-embedding-v4

Parte de la serie Qwen3-Embedding

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

10

8,192

$0.07

Chino, inglés, español, francés, portugués, indonesio, japonés, coreano, alemán, ruso y más de 100 idiomas principales adicionales

1 millón de tokens

Validez: 90 días después de activar Model Studio

text-embedding-v3

1,024 (predeterminado), 768, 512

Chino, inglés, español, francés, portugués, indonesio, japonés, coreano, alemán, ruso y más de 50 idiomas principales adicionales

500,000 tokens

Validez: 90 días después de activar Model Studio

China (Beijing)

ModeloDimensiones de embeddingFilas máximasMáximo de tokens por líneaPrecio (por 1M tokens de entrada)Idiomas admitidos

text-embedding-v4

Parte de la serie Qwen3-Embedding

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

10

8,192

$0.072

Chino, inglés, español, francés, portugués, indonesio, japonés, coreano, alemán, ruso y más de 100 idiomas principales adicionales, además de múltiples lenguajes de programación

China (Hong Kong)

ModeloDimensiones de embeddingFilas máximasMáximo de tokens por líneaPrecio (por 1M tokens de entrada)Idiomas admitidos

text-embedding-v4

Parte de la serie Qwen3-Embedding

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

10

8,192

$0.07

Chino, inglés, español, francés, portugués, indonesio, japonés, coreano, alemán, ruso y más de 100 idiomas principales adicionales, además de múltiples lenguajes de programación

Para conocer los límites de tasa del modelo, consulte Limitación de tasa.

Requisitos previos

Los usuarios familiarizados con el ecosistema OpenAI pueden utilizar la API compatible con OpenAI para una migración rápida. La API DashScope ofrece funciones únicas adicionales.

Obtenga una clave API y exporte la clave API como variable de entorno. Si utiliza un SDK para realizar las llamadas, instale el SDK de DashScope.

Compatibilidad con OpenAI

Elbase_urla configurar para llamadas SDK:

  • Singapur: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1. Reemplace WorkspaceId con su ID de espacio de trabajo real.
  • China (Pekín): https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1
  • China (Hong Kong): https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1. Reemplace WorkspaceId con su ID de espacio de trabajo real.

Elendpointa configurar para llamadas HTTP:

  • Singapur: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/embeddings. Reemplace WorkspaceId con su ID de espacio de trabajo real.
  • China (Pekín): 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. Reemplace WorkspaceId con su ID de espacio de trabajo real.

Reemplace {WorkspaceId} con su ID de espacio de trabajo real.

Cuerpo de la solicitud

modelstringrequerido

El nombre del modelo a llamar. Consulte la tabla Resumen de modelos para ver los nombres de los modelos.

inputarray<string> or string or filerequerido

El texto de entrada a procesar. La entrada puede ser una cadena, una matriz de cadenas o un archivo. Los límites de longitud de texto y tamaño de lote varían según la versión del modelo:

  • Modelo qwen3.7-text-embedding:
    • Entrada de cadena: Hasta 128,000 tokens.
    • Entrada de lista de cadenas o archivo: Hasta 20 elementos (líneas), con cada elemento (línea) de hasta 128,000 tokens.
  • Modelos text-embedding-v3 / v4:
    • Entrada de cadena: Longitud máxima de 8,192 tokens.
    • Entrada de lista de cadenas o archivo: Hasta 10 elementos (líneas), con cada elemento (línea) de hasta 8,192 tokens.

dimensions integer opcional

La dimensión de los vectores de embedding de salida. Debe ser uno de los siguientes valores: 2560 (for qwen3.7-text-embedding only),2048 (solo para text-embedding-v4), 1536 (solo para text-embedding-v4), 1024, 768, 512, 256, 128 o 64. El valor predeterminado es 1024.

encoding_format string opcional

El formato de embedding devuelto. Actualmente, solo se admite float.

Cadena de entrada

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

Si utiliza un modelo en la región China (Pekín), debe usar una clave API de esa región y reemplazar la URL con https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/embeddings. El ejemplo de código a continuación utiliza la URL de la región de Singapur. Reemplace {WorkspaceId} con su ID de espacio de trabajo real. Las URLs varían según la región.

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

CLI de dashscope

Llamada a través de la línea de comandos dashscope.

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"

ImportanteEl asistente interactivo SDK Expert puede realizar las mismas tareas de desarrollo y solución de problemas mediante lenguaje natural; consulte

DashScope SDK Expert.

Para la tabla completa de regiones, consulte Resumen de URL base.

Lista de cadenas de entrada

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

Si utiliza un modelo en la región China (Pekín), debe usar una clave API de esa región y reemplazar la URL con https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/embeddings. El ejemplo de código a continuación utiliza la URL de la región de Singapur. Reemplace {WorkspaceId} con su ID de espacio de trabajo real. Las URLs varían según la región.

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

Archivo de entrada

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

Si utiliza un modelo en la región China (Pekín), debe usar una clave API de esa región y reemplazar la URL con https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/embeddings. El ejemplo de código a continuación utiliza la URL de la región de Singapur. Reemplace {WorkspaceId} con su ID de espacio de trabajo real. Las URLs varían según la región.

Reemplace 'texts_to_embedding.txt' con el nombre o la ruta de su archivo.

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

Objeto de respuesta

dataarray

Una lista de los objetos de embedding resultantes.

Propiedad

embeddinglist

El vector de embedding, devuelto como una matriz de números de punto flotante.

indexinteger

El índice del texto de entrada correspondiente en la matriz de entrada.

objectstring

El tipo de objeto. El valor siempre es embedding.

modelstring

El nombre del modelo utilizado para esta llamada.

objectstring

El tipo de objeto. El valor siempre es list.

usageobject

Propiedad

prompt_tokensinteger

El número de tokens en el texto de entrada.

total_tokens integer

El número total de tokens en la entrada. Este recuento se determina según cómo el tokenizador del modelo analiza la cadena de entrada.

idstring

Un identificador único de solicitud, utilizado para rastreo y solución de problemas.

{
  "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_urlpara llamadas SDK:

  • Singapur: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1. Reemplace WorkspaceId con su ID de espacio de trabajo real.
  • China (Pekín): https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1
  • China (Hong Kong): https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1. Reemplace WorkspaceId con su ID de espacio de trabajo real.
Endpoint para llamadas HTTP:
  • Singapur: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding. Reemplace WorkspaceId con su ID de espacio de trabajo real.
  • China (Pekín): 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. Reemplace WorkspaceId con su ID de espacio de trabajo real.

Reemplace {WorkspaceId} con su ID de espacio de trabajo real.

Cuerpo de la solicitud

modelstringrequerido

El modelo a utilizar. Para obtener una lista de modelos disponibles, consulte la tabla Resumen de modelos.

inputstringoarray<string>requerido

El texto a procesar. La entrada puede ser una cadena, una matriz de cadenas o un archivo. La longitud de texto admitida y el tamaño del lote varían según la versión del modelo.

  • Modelo qwen3.7-text-embedding:
    • Entrada de cadena: Hasta 128,000 tokens.
    • Entrada de lista de cadenas o archivo: Hasta 20 elementos (líneas), con cada elemento (línea) de hasta 128,000 tokens.
  • Modelos text-embedding-v3 / v4:
    • Entrada de cadena: Longitud máxima de 8,192 tokens.
    • Entrada de lista de cadenas o archivo: Hasta 10 elementos (líneas), con cada elemento (línea) de hasta 8,192 tokens.

text_type stringopcional

Al realizar una llamada HTTP, coloque text_typeen el objeto parameters.

El texto convertido a embeddings se puede aplicar a tareas posteriores como recuperación, agrupación y clasificación. Para tareas asimétricas como la recuperación, se recomienda diferenciar entre texto de consulta (query) y texto de documento (document) para lograr un mejor rendimiento de recuperación. Para tareas simétricas como indexación, agrupación y clasificación, simplemente puede usar el valor predeterminado del sistema de document.

dimension integer opcional

Al realizar una llamada HTTP, coloque dimensionen el objeto parameters.

Especifica la dimensión de embedding para el vector de salida. Los valores válidos son 2560 (for qwen3.7-text-embedding only),2048 (solo para text-embedding-v4), 1536 (solo para text-embedding-v4), 1024, 768, 512, 256, 128 o 64. El valor predeterminado es 1024.

output_type string opcional

Al realizar una llamada HTTP, coloque output_typeen el objeto parameters.

Especifica el tipo de vector de salida. Este parámetro aplica solo a los modelos qwen3.7-text-embedding,``text-embedding-v3 y text-embedding-v4. Los valores válidos son dense, sparse y dense&sparse. El valor predeterminado es dense, que devuelve solo la representación vectorial densa. Las salidas de vectores dispersos (sparse y dense&sparse) solo se admiten a través de la API DashScope.

instruct string opcional

Proporciona instrucciones personalizadas para guiar al modelo en la comprensión de la intención de la consulta. Se recomiendan instrucciones en inglés, ya que generalmente mejoran el rendimiento entre un 1% y un 5%.

Cadena de entrada

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

Si utiliza un modelo en la región China (Pekín), use una clave API para esa región y reemplace la URL con: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding. El ejemplo de código a continuación utiliza la URL de la región de Singapore. Reemplace {WorkspaceId} con su ID de espacio de trabajo real. Las URLs varían según la región.

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

Lista de cadenas de entrada

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

Si utiliza un modelo en la región China (Pekín), use una clave API para esa región y reemplace la URL con: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding. El ejemplo de código a continuación utiliza la URL de la región de Singapore. Reemplace {WorkspaceId} con su ID de espacio de trabajo real. Las URLs varían según la región.

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

Archivo de entrada

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

Si utiliza un modelo en la región China (Pekín), use una clave API para esa región y reemplace la URL con: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding. El ejemplo de código a continuación utiliza la URL de la región de Singapore. Reemplace {WorkspaceId} con su ID de espacio de trabajo real. Las URLs varían según la región.

Reemplace 'texts_to_embedding.txt' con el nombre o la ruta de su archivo.

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

Objeto de respuesta

status_code string

El código de estado HTTP. Un valor de 200 indica éxito.

request_id string

Un identificador único para la solicitud. Utilice este ID para rastrear y solucionar problemas de la solicitud.

code string

El código de error devuelto si la solicitud falla. Este campo está vacío para solicitudes exitosas.

message string

Un mensaje de error detallado si la solicitud falla. Este campo está vacío para solicitudes exitosas.

outputobject

El resultado de la tarea.

Propiedades

embeddingsarray

La salida del modelo para la solicitud. Es una matriz de objetos, donde cada objeto corresponde a un texto de entrada.

Propiedades

sparse_embedding array

La representación vectorial dispersa de la cadena correspondiente. Esto aplica solo a text-embedding-v3 y text-embedding-v4.

Propiedades

index integer

El índice del token en el vocabulario.

valor float

Indica el peso o la puntuación de importancia del Token. Cuanto mayor sea el valor, mayor será la importancia o relevancia del Token en el contexto de texto actual.

token string

El texto del token.

embedding array

La representación vectorial densa para la cadena correspondiente.

text_index integer

El índice del texto correspondiente en la matriz de entrada.

usageobject

Propiedades

total_tokens integer

El número de tokens en la entrada, calculado por el tokenizador del modelo.

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

Códigos de error

Si falla una llamada al modelo, consulte Mensajes de error.