QwenCloudBRASIL
Tradução de apoio para consulta. Código e identificadores técnicos preservados. Consultar referência original ↗

Incorporação DashScope

API de incorporação DashScope

Converta texto em vetores para pesquisa semântica, recomendações, agrupamento e classificação.

Antes de começar: obtenha uma chave de API, defini-lo como uma variável de ambiente e instalar o SDK do DashScope se você usar o SDK.

Defina o URL base do SDK

SDK Python:

import dashscope
dashscope.base_http_api_url = 'https://maas.qwencloudapi.com/api/v1'

SDK Java:

import com.alibaba.dashscope.utils.Constants;
Constants.baseHttpApiUrl = "https://maas.qwencloudapi.com/api/v1";

Modelos suportados

Modelo Dimensões Máximo de tokens Tamanho do lote Idiomas
incorporação de texto-v4 2048, 1536, 1024 (padrão), 768, 512, 256, 128, 64 8.192 10 100+
incorporação de texto-v3 1024 (padrão), 768, 512 8.192 10 50+

Para preços, consulte o Model Marketplace.

Formatos de entrada

Recursos específicos do DashScope

Consulte Limites de taxa.

OpenAPI

openapi: 3.1.0
info:
  title: Text Embedding API
  description: API reference for text embedding models. Supports OpenAI-compatible and DashScope protocols.
  version: 1.0.0
servers:
  - url: https://maas.qwencloudapi.com
    description: Singapore
security:
  - bearer: []
paths:
  /api/v1/services/embeddings/text-embedding/text-embedding:
    post:
      operationId: createEmbeddingsDashScope
      summary: Create embeddings (DashScope)
      description: Create text embeddings using the DashScope API.
      security:
        - bearer: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/DashScopeEmbeddingRequest"
      responses:
        "200":
          description: Successful response
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/DashScopeEmbeddingResponse"
        "400":
          description: Bad request
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
      x-codeSamples:
        - lang: python
          label: Input string
          source: |
            import dashscope
            from http import HTTPStatus

            dashscope.base_http_api_url = 'https://maas.qwencloudapi.com/api/v1'

            resp = dashscope.TextEmbedding.call(
              model=dashscope.TextEmbedding.Models.text_embedding_v4,
              input='Semantic search finds documents by meaning rather than exact keyword matching. Text embeddings map words and sentences into high-dimensional vector spaces. Retrieval-augmented generation combines search results with language models. Document clustering groups similar texts based on their vector representations.',
              dimension=1024,
              output_type="dense&sparse"
            )

            print(resp) if resp.status_code == HTTPStatus.OK else print(resp)
        - lang: java
          label: Input string
          source: |-
            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 {
                    Constants.baseHttpApiUrl="https://maas.qwencloudapi.com/api/v1";
                }
                public static void basicCall() throws ApiException, NoApiKeyException{
                    TextEmbeddingParam param = TextEmbeddingParam
                    .builder()
                    .model(TextEmbedding.Models.TEXT_EMBEDDING_V4)
                    .texts(Arrays.asList("Semantic search finds documents by meaning rather than exact keyword matching.", "Text embeddings map words and sentences into high-dimensional vector spaces.", "Retrieval-augmented generation combines search results with language models.", "Document clustering groups similar texts based on their vector representations.")).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_V4)
                    .texts(Arrays.asList("Semantic search finds documents by meaning rather than exact keyword matching.", "Text embeddings map words and sentences into high-dimensional vector spaces.", "Retrieval-augmented generation combines search results with language models.", "Document clustering groups similar texts based on their vector representations.")).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);
              }
            }
        - lang: bash
          label: Input string
          source: |-
            curl --location 'https://maas.qwencloudapi.com/api/v1/services/embeddings/text-embedding/text-embedding' \
            --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
            --header 'Content-Type: application/json' \
            --data '{
              "model": "text-embedding-v4",
              "input": {
                "texts": [
                "Semantic search finds documents by meaning rather than exact keyword matching. Text embeddings map words and sentences into high-dimensional vector spaces. Retrieval-augmented generation combines search results with language models. Document clustering groups similar texts based on their vector representations."
                ]
              },
              "parameters": {
                "dimension": 1024,
                "output_type": "dense"
              }
            }'
        - lang: python
          label: Input string list
          source: |
            import dashscope
            from http import HTTPStatus

            dashscope.base_http_api_url = 'https://maas.qwencloudapi.com/api/v1'
            DASHSCOPE_MAX_BATCH_SIZE = 10

            inputs = ['Semantic search finds documents by meaning rather than exact keyword matching.', 'Text embeddings map words and sentences into high-dimensional vector spaces.', 'Retrieval-augmented generation combines search results with language models.', 'Document clustering groups similar texts based on their vector representations.']

            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=dashscope.TextEmbedding.Models.text_embedding_v4,
                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)
        - lang: java
          label: Input string list
          source: |
            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 {
                Constants.baseHttpApiUrl="https://maas.qwencloudapi.com/api/v1";
              }
              private static final int DASHSCOPE_MAX_BATCH_SIZE = 10;

              public static void main(String[] args) {
                List<String> inputs = Arrays.asList(
                    "Semantic search finds documents by meaning rather than exact keyword matching.",
                    "Text embeddings map words and sentences into high-dimensional vector spaces.",
                    "Retrieval-augmented generation combines search results with language models.",
                    "Document clustering groups similar texts based on their vector representations."
                );

                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(TextEmbedding.Models.TEXT_EMBEDDING_V4)
                      .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);
              }
            }
        - lang: bash
          label: Input string list
          source: |-
            curl --location 'https://maas.qwencloudapi.com/api/v1/services/embeddings/text-embedding/text-embedding' \
            --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
            --header 'Content-Type: application/json' \
            --data '{
              "model": "text-embedding-v4",
              "input": {
              "texts": [
                      "Semantic search finds documents by meaning rather than exact keyword matching.",
                      "Text embeddings map words and sentences into high-dimensional vector spaces.",
                      "Retrieval-augmented generation combines search results with language models.",
                      "Document clustering groups similar texts based on their vector representations."
              ]
              },
              "parameters": {
                	  "dimension": 1024,
                	  "output_type": "dense"
              }
            }'
        - lang: python
          label: Input file
          source: |
            import dashscope
            from http import HTTPStatus
            from dashscope import TextEmbedding

            dashscope.base_http_api_url = 'https://maas.qwencloudapi.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=TextEmbedding.Models.text_embedding_v4,
                input=f,
                dimension=1024
              )

              if resp.status_code == HTTPStatus.OK:
                print(resp)
              else:
                print(resp)
        - lang: java
          label: Input file
          source: |-
            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 {
                Constants.baseHttpApiUrl="https://maas.qwencloudapi.com/api/v1";
              }
              public static void main(String[] args) {
                // Make sure to replace 'tests_to_embedding.txt' with the full path of 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(TextEmbedding.Models.TEXT_EMBEDDING_V4)
                      .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();
                }
              }
            }
        - lang: bash
          label: Input file
          source: |
            FILE_CONTENT=$(cat texts_to_embedding.txt | jq -Rs .)
            curl --location 'https://maas.qwencloudapi.com/api/v1/services/embeddings/text-embedding/text-embedding' \
            --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
            --header 'Content-Type: application/json' \
            --data '{
              "model": "text-embedding-v4",
              "input": {
                "texts": ['"$FILE_CONTENT"']
              },
              "parameters": {
                "dimension": 1024,
                "output_type": "dense"
              }
            }'
components:
  securitySchemes:
    bearer:
      type: http
      scheme: bearer
      description: DashScope API key. Obtain from the QwenCloud console.
  schemas:
    EmbeddingRequest:
      type: object
      required:
        - model
        - input
      properties:
        model:
          type: string
          description: "The model to call. Supported values: `text-embedding-v4`, `text-embedding-v3`."
          example: text-embedding-v4
        input:
          description: The input text to process. The value can be a string, an array of strings, or a file. When the input is a string, it can contain up to 8,192 tokens. When the input is a list of strings or a file, it can contain up to 10 items (lines), each with a maximum of 8,192 tokens.
          oneOf:
            - type: string
              description: A single text string.
            - type: array
              items:
                type: string
              description: An array of text strings (up to 10 items).
        dimensions:
          type: integer
          description: "The embedding dimensions. Valid values: 2048 (text-embedding-v4 only), 1536 (text-embedding-v4 only), 1024, 768, 512, 256, 128, or 64. text-embedding-v4 default: 1024; text-embedding-v3 default: 1024."
          default: 1024
          enum:
            - 2048
            - 1536
            - 1024
            - 768
            - 512
            - 256
            - 128
            - 64
        encoding_format:
          type: string
          description: The format of the returned embedding. Only `float` is supported.
          default: float
          enum:
            - float
    EmbeddingResponse:
      type: object
      properties:
        data:
          type: array
          description: The output data for the task.
          items:
            type: object
            properties:
              embedding:
                type: array
                items:
                  type: number
                description: The embedding vector, which is an array of floating-point numbers.
              index:
                type: integer
                description: The index of the input text in the input array that corresponds to the result in this structure.
              object:
                type: string
                description: "The type of object returned by the call. Default: `embedding`."
                default: embedding
        model:
          type: string
          description: The model that was called.
        object:
          type: string
          description: "The type of data returned by the call. Default: `list`."
          default: list
        usage:
          type: object
          description: Token usage statistics.
          properties:
            prompt_tokens:
              type: integer
              description: The number of tokens in the input text.
            total_tokens:
              type: integer
              description: The total number of tokens in the request. Calculated based on the model's tokenizer.
        id:
          type: string
          description: The unique request ID. Use this ID to trace and troubleshoot requests.
      example:
        data:
          - embedding:
              - -0.0695386752486229
              - 0.030681096017360687
            index: 0
            object: embedding
          - embedding:
              - -0.06348952651023865
              - 0.060446035116910934
            index: 5
            object: embedding
        model: text-embedding-v4
        object: list
        usage:
          prompt_tokens: 184
          total_tokens: 184
        id: 73591b79-d194-9bca-8bb5-xxxxxxxxxxxx
    DashScopeEmbeddingRequest:
      type: object
      required:
        - model
        - input
      properties:
        model:
          type: string
          description: "The model to call. Supported values: `text-embedding-v4`, `text-embedding-v3`."
          example: text-embedding-v4
        input:
          type: object
          required:
            - texts
          description: The input object containing texts to embed.
          properties:
            texts:
              description: The input text to process. The value can be a string or an array of strings. A string input can contain up to 8,192 tokens. A list of strings can contain up to 10 items, each with up to 8,192 tokens.
              oneOf:
                - type: string
                  description: A single text string.
                - type: array
                  items:
                    type: string
                  description: An array of text strings (up to 10 items).
        parameters:
          type: object
          description: Optional parameters for the embedding request.
          properties:
            text_type:
              type: string
              description: Specifies the text type for asymmetric tasks. For retrieval, distinguish between `query` and `document` for better results. For symmetric tasks (clustering, categorization), use the default `document`.
              default: document
              enum:
                - query
                - document
            dimension:
              type: integer
              description: "The embedding dimensions. Valid values: 2048 (text-embedding-v4 only), 1536 (text-embedding-v4 only), 1024, 768, 512, 256, 128, or 64. text-embedding-v4 default: 1024; text-embedding-v3 default: 1024."
              default: 1024
              enum:
                - 2048
                - 1536
                - 1024
                - 768
                - 512
                - 256
                - 128
                - 64
            output_type:
              type: string
              description: "Specifies whether to output a sparse vector representation. Applies only to text-embedding-v3 and text-embedding-v4. Default: `dense` (returns only dense vector)."
              default: dense
              enum:
                - dense
                - sparse
                - dense&sparse
            instruct:
              type: string
              description: A custom task description. Takes effect only with text-embedding-v4 when `text_type` is `query`. English descriptions are recommended (~1-5% performance improvement).
    DashScopeEmbeddingResponse:
      type: object
      properties:
        status_code:
          type: integer
          description: The status code. A value of 200 indicates a successful request.
        request_id:
          type: string
          description: The unique request ID. Use this ID to trace and troubleshoot requests.
        code:
          type: string
          description: If the request fails, this indicates the error code. Empty on success.
        message:
          type: string
          description: If the request fails, this indicates the detailed error message. Empty on success.
        output:
          type: object
          description: The output data for the task.
          properties:
            embeddings:
              type: array
              description: An array of structures. Each structure contains the output for the corresponding input text.
              items:
                type: object
                properties:
                  sparse_embedding:
                    type: array
                    description: The sparse vector representation. Applies only to text-embedding-v3 and text-embedding-v4 when `output_type` includes `sparse`.
                    items:
                      type: object
                      properties:
                        index:
                          type: integer
                          description: The index of the word or character in the vocabulary.
                        value:
                          type: number
                          description: The weight or importance score of the token. Higher values indicate greater importance.
                        token:
                          type: string
                          description: The actual text unit or word from the vocabulary.
                  embedding:
                    type: array
                    items:
                      type: number
                    description: The dense vector representation (dense embedding).
                  text_index:
                    type: integer
                    description: The index of the input text in the input array that corresponds to the result in this structure.
        usage:
          type: object
          description: Token usage statistics.
          properties:
            total_tokens:
              type: integer
              description: The total number of tokens in the request. Calculated based on the model's tokenizer.
      example:
        status_code: 200
        request_id: 1ba94ac8-e058-99bc-9cc1-7fdb37940a46
        code: ""
        message: ""
        output:
          embeddings:
            - sparse_embedding:
                - index: 7149
                  value: 0.829
                  token: wind
                - index: 111290
                  value: 0.9004
                  token: sorrow
              embedding:
                - -0.006929283495992422
                - -0.005336422007530928
              text_index: 0
        usage:
          total_tokens: 27
    ErrorResponse:
      type: object
      properties:
        code:
          type: string
          description: The error code.
        message:
          type: string
          description: The detailed error message.
        request_id:
          type: string
          description: The unique request ID. Use this ID to trace and troubleshoot requests.
      example:
        code: InvalidParameter
        message: "The model name is invalid. Supported models: text-embedding-v4, text-embedding-v3."
        request_id: a1b2c3d4-e5f6-7890-abcd-xxxxxxxxxxxx