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

Incorporação compatível com OpenAI

Incorporação compatível com OpenAI

Antes de chamar a API, obtenha uma chave de API e defini-lo como uma variável de ambiente. Se você usa o OpenAI SDK, instale-o primeiro.

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 Mais de 100 idiomas principais
incorporação de texto-v3 1024 (padrão), 768, 512 8.192 10 Mais de 50 idiomas

Para preços, consulte o Model Marketplace.

A API compatível com OpenAI não suporta saída de vetor esparso. Para usar output_type=sparse com text-embedding-v4, chame a API de incorporação do DashScope. Se output_type=sparse é enviado para a API compatível com OpenAI, ele retorna HTTP 200 com um resultado de incorporação vazio.

Pontos finais

As chaves de API internacionais só podem usar endpoints internacionais. As chaves de API da China só podem usar endpoints da China.

Chave API de Ponto final
Internacional https://maas.qwencloudapi.com/compatible-mode/v1/embeddings
China https://dashscope.aliyuncs.com/compatible-mode/v1/embeddings

SDKs usam o URL base sem /embeddings.

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:
  /compatible-mode/v1/embeddings:
    post:
      operationId: createEmbeddingsOpenAI
      summary: Create embeddings (OpenAI-compatible)
      description: Create text embeddings using the OpenAI-compatible API.
      security:
        - bearer: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/EmbeddingRequest"
      responses:
        "200":
          description: Successful response
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/EmbeddingResponse"
        "400":
          description: Bad request
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
      x-codeSamples:
        - lang: python
          label: Input string
          source: |
            import os
            from openai import OpenAI

            client = OpenAI(
              api_key=os.getenv("DASHSCOPE_API_KEY"),  # If you have not configured an environment variable, replace the placeholder with your API key.
              base_url="https://maas.qwencloudapi.com/compatible-mode/v1"
            )

            completion = client.embeddings.create(
              model="text-embedding-v4",
              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())
        - lang: java
          label: Input string
          source: |
            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) {
                String apiKey = System.getenv("DASHSCOPE_API_KEY");
                if (apiKey == null) {
                  System.out.println("DASHSCOPE_API_KEY not found in environment variables");
                  return;
                }
                String baseUrl = "https://maas.qwencloudapi.com/compatible-mode/v1/embeddings";
                HttpClient client = HttpClient.newHttpClient();

                Map<String, Object> requestBody = new HashMap<>();
                requestBody.put("model", "text-embedding-v4");
                requestBody.put("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.");
                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());
                }
              }
            }
        - lang: bash
          label: Input string
          source: |
            curl --location 'https://maas.qwencloudapi.com/compatible-mode/v1/embeddings' \
            --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
            --header 'Content-Type: application/json' \
            --data '{
              "model": "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.",
              "dimensions": 1024,
              "encoding_format": "float"
            }'
        - lang: python
          label: Input string list
          source: |-
            import os
            from openai import OpenAI

            client = OpenAI(
              api_key=os.getenv("DASHSCOPE_API_KEY"),  # If you have not configured an environment variable, replace the placeholder with your API key.
              base_url="https://maas.qwencloudapi.com/compatible-mode/v1"
            )

            completion = client.embeddings.create(
              model="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.'],
              dimensions=1024,
              encoding_format="float"
            )

            print(completion.model_dump_json())
        - lang: java
          label: Input string list
          source: |
            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 the placeholder with your API key. */
                String apiKey = System.getenv("DASHSCOPE_API_KEY");
                if (apiKey == null) {
                  System.out.println("DASHSCOPE_API_KEY not found in environment variables");
                  return;
                }
                String baseUrl = "https://maas.qwencloudapi.com/compatible-mode/v1/embeddings";
                HttpClient client = HttpClient.newHttpClient();
                Map<String, Object> requestBody = new HashMap<>();
                requestBody.put("model", "text-embedding-v4");
                List<String> inputList = 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.");
                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());
                }
              }
            }
        - lang: bash
          label: Input string list
          source: |-
            curl --location 'https://maas.qwencloudapi.com/compatible-mode/v1/embeddings' \
            --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
            --header 'Content-Type: application/json' \
            --data '{
              "model": "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."
                ],
              "dimensions": 1024,
              "encoding_format": "float"
            }'
        - lang: python
          label: Input file
          source: |
            import os
            from openai import OpenAI

            client = OpenAI(
              api_key=os.getenv("DASHSCOPE_API_KEY"),  # If you have not configured an environment variable, replace the placeholder with your API key.
              base_url="https://maas.qwencloudapi.com/compatible-mode/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:
              completion = client.embeddings.create(
                model="text-embedding-v4",
                input=f,
                encoding_format="float"
              )
            print(completion.model_dump_json())
        - lang: java
          label: Input file
          source: |
            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 the placeholder with your API key. */
                String apiKey = System.getenv("DASHSCOPE_API_KEY");
                if (apiKey == null) {
                  System.out.println("DASHSCOPE_API_KEY not found in environment variables");
                  return;
                }
                String baseUrl = "https://maas.qwencloudapi.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", "text-embedding-v4");
                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());
                }
              }
            }
        - lang: bash
          label: Input file
          source: |-
            FILE_CONTENT=$(cat texts_to_embedding.txt | jq -Rs .)
            curl --location 'https://maas.qwencloudapi.com/compatible-mode/v1/embeddings' \
            --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
            --header 'Content-Type: application/json' \
            --data '{
              "model": "text-embedding-v4",
              "input": ['"$FILE_CONTENT"'],
              "dimensions": 1024,
              "encoding_format": "float"
            }'
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