Synchronous API

更新时间:
复制 MD 格式

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

Model overview

Model

Embedding dimensions

Max rows

Max tokens per line

Price (per 1K input tokens)

Supported languages

Free quota (Note)

text-embedding-v4

Part of the Qwen3-Embedding series

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

10

8,192

CNY 0.0005

Batch call: CNY 0.00025

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

1 million tokens each

Validity: 90 days after you activate Model Studio

text-embedding-v3

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

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

text-embedding-v2

1,536

25

2,048

CNY 0.0007

Batch call: CNY 0.00035

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

500,000 tokens each

Validity: 90 days after you activate Model Studio

text-embedding-v1

Chinese, English, Spanish, French, Portuguese, Indonesian

For model rate limits, see Rate limiting.

Prerequisites

Users familiar with the OpenAI ecosystem can use the OpenAI-compatible API for a quick migration. The DashScope API provides more unique features.

Obtain an API key and export the API key as an environment variable. If you use an SDK to make calls, install the DashScope SDK.

OpenAI compatibility

Public cloud

The base_url to configure for SDK calls:https://dashscope.aliyuncs.com/compatible-mode/v1

The endpoint to configure for HTTP calls:POSThttps://dashscope.aliyuncs.com/compatible-mode/v1/embeddings

Request body

Input string

Python

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # If the environment variable is not set, replace the placeholder with your API key.
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"  # The base_url for the Model Studio service.
)

completion = client.embeddings.create(
    model="text-embedding-v4",
    input='The quality of the clothes is excellent and they are beautiful. It was well worth the wait. I love them and will buy from here again.',
    dimensions=1024, # Sets the embedding dimensions (only for text-embedding-v3 and text-embedding-v4).
    encoding_format="float"
)

print(completion.model_dump_json())

Java

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

public class Main {
    public static void main(String[] args) {
        // Create a client using the API key from the environment variable.
        OpenAIClient client = OpenAIOkHttpClient.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .build();

        // Create parameters for the vectorization request.
        EmbeddingCreateParams params = EmbeddingCreateParams.builder()
                .model("text-embedding-v4")
                .input(EmbeddingCreateParams.Input.ofString("The quality of the clothes is excellent and they are beautiful. It was well worth the wait. I love them and will buy from here again."))
                // Sets the embedding dimensions (only for text-embedding-v3 and text-embedding-v4).
                .dimensions(1024)
                .build();

        try {
            // Send the request and get the response.
            CreateEmbeddingResponse response = client.embeddings().create(params);
            System.out.println(response);
        } catch (Exception e) {
            System.err.println("Request failed. See the following page for error codes:");
            System.err.println("https://www.alibabacloud.com/help/en/model-studio/faq-about-alibaba-cloud-model-studio#1c38f58abfcml");
            System.err.println("Error details: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

curl

curl --location 'https://dashscope.aliyuncs.com/compatible-mode/v1/embeddings' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "text-embedding-v4",
    "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"
}'

Input string list

Python

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # If the environment variable is not set, replace the placeholder with your API key.
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"  # The base_url for the Model Studio service.
)

completion = client.embeddings.create(
    model="text-embedding-v4",
    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, # Sets the embedding dimensions (only for text-embedding-v3 and text-embedding-v4).
    encoding_format="float"
)

print(completion.model_dump_json())

Java

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

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

public class Main {
    public static void main(String[] args) {
        // Create a client using the API key from the environment variable.
        OpenAIClient client = OpenAIOkHttpClient.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .build();

        // Create a list of input strings.
        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."
        );

        // List to store all responses.
        List<CreateEmbeddingResponse> responses = new ArrayList<>();

        // Process each string in a loop.
        for (String text : inputList) {
            try {
                // Create parameters for the vectorization request.
                EmbeddingCreateParams params = EmbeddingCreateParams.builder()
                        .model("text-embedding-v4")
                        .input(EmbeddingCreateParams.Input.ofString(text))
                        // Sets the embedding dimensions (only for text-embedding-v3 and text-embedding-v4).
                        .dimensions(1024)
                        .build();

                // Send the request and get the response.
                CreateEmbeddingResponse response = client.embeddings().create(params);
                responses.add(response);
                System.out.println("Processing text: " + text);
                System.out.println("Vectorization result: " + response);
                System.out.println("------------------------");
            } catch (Exception e) {
                System.err.println("Error processing text: " + text);
                System.err.println("Error details: " + e.getMessage());
                e.printStackTrace();
            }
        }

        // Print the summary information.
        System.out.println("\nProcessed a total of " + responses.size() + " texts.");
    }
} 

curl

curl --location 'https://dashscope.aliyuncs.com/compatible-mode/v1/embeddings' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "text-embedding-v4",
    "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"
}'

Input file

Python

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # If the environment variable is not set, replace the placeholder with your API key.
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"  # The base_url for the Model Studio service.
)
# 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="text-embedding-v4",
        input=f,
        dimensions=1024, # Sets the embedding dimensions (only for text-embedding-v3 and text-embedding-v4).
        encoding_format="float"
    )
print(completion.model_dump_json())

Java

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

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

public class Main {
    public static void main(String[] args) {
        // Create a client using the API key from the environment variable.
        OpenAIClient client = OpenAIOkHttpClient.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .build();

        // Make sure to replace 'texts_to_embedding.txt' with your file name or absolute path.
        String filePath = "/src/main/java/org/example/text_to_embedding.txt";

        try {
            // Read the file content.
            StringBuilder fileContent = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    fileContent.append(line).append("\n");
                }
            }

            // Create parameters for the vectorization request.
            EmbeddingCreateParams params = EmbeddingCreateParams.builder()
                    .model("text-embedding-v4")
                    .input(EmbeddingCreateParams.Input.ofString(fileContent.toString()))
                    // Sets the embedding dimensions (only for text-embedding-v3 and text-embedding-v4).
                    .dimensions(1024)
                    .build();

            // Send the request and get the response.
            CreateEmbeddingResponse response = client.embeddings().create(params);
            System.out.println(response);

        } catch (IOException e) {
            System.err.println("Error reading the file: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("Request failed. See the following page for error codes:");
            System.err.println("https://www.alibabacloud.com/help/en/model-studio/faq-about-alibaba-cloud-model-studio#1c38f58abfcml");
            System.err.println("Error details: " + e.getMessage());
            e.printStackTrace();
        }
    }
} 

curl

Replace 'texts_to_embedding.txt' with your file name or path.
FILE_CONTENT=$(cat texts_to_embedding.txt | jq -Rs .)
curl --location 'https://dashscope.aliyuncs.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"
}'

model string required

The name of the model to call. See the Model overview table for model names.

input array<string> or string or file required

The input text to process. The input can be a string, an array of strings, or a file. Limits on text length and batch size vary by model version:

  • text-embedding-v3 / v4 models:

    • String input: Maximum length of 8,192 tokens.

    • String list or file input: A maximum of 10 items (lines), where each item (line) can be up to 8,192 tokens.

  • text-embedding-v1 / v2 models:

    • String input: Maximum length of 2,048 tokens.

    • String list or file input: A maximum of 25 items (lines), where each item (line) can be up to 2,048 tokens.

dimensions integer optional

The dimension of the output embedding vectors. Must be one of the following values: 2048 (for text-embedding-v4 only), 1536 (for text-embedding-v4 only), 1024, 768, 512, 256, 128, or 64. The default value is 1024.

encoding_format string optional

The returned embedding format. Currently, only float is supported.

Response object

Successful response

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

Error response

{
    "error": {
        "message": "Incorrect API key provided. ",
        "type": "invalid_request_error",
        "param": null,
        "code": "invalid_api_key"
    }
}

data array

A list of the resulting embedding objects.

Property

embedding list

The embedding vector, returned as an array of floating-point numbers.

index integer

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

object string

The object type. The value is always embedding.

model string

The name of the model used for this call.

object string

The object type. The value is always list.

usage object

Property

prompt_tokens integer

The number of tokens in the input text.

total_tokens integer

The total number of tokens in the input. This count is determined by how the model's tokenizer parses the input string.

id string

A unique request identifier, used for tracing and troubleshooting.

DashScope

Public cloud

base_url for SDK calls: https://dashscope.aliyuncs.com/api/v1

Endpoint for HTTP calls: POST https://dashscope.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding

Request body

Input string

Python

import dashscope
from http import HTTPStatus

resp = dashscope.TextEmbedding.call(
    model="text-embedding-v4",
    input='The quality of the clothes is excellent and they are beautiful. It was well worth the wait. I love them and will buy from here again.',
    dimension=1024,  # Specifies the output embedding dimension. This parameter is available only for text-embedding-v3 and text-embedding-v4 models.
    output_type="dense&sparse"
)

print(resp) if resp.status_code == HTTPStatus.OK else print(resp)

Java

import java.util.Arrays;
import com.alibaba.dashscope.embeddings.TextEmbedding;
import com.alibaba.dashscope.embeddings.TextEmbeddingParam;
import com.alibaba.dashscope.embeddings.TextEmbeddingResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;

/**
 * Qwen text embedding model call example.
 */
public final class Main {
    public static void main(String[] args) {
        try {
            // Build the request parameters.
            TextEmbeddingParam param = TextEmbeddingParam
                    .builder()
                    .model("text-embedding-v4")  // Use the text-embedding-v4 model.
                    .texts(Arrays.asList("The quality of the clothes is excellent and they are beautiful. It was well worth the wait. I love them and will buy from here again."))  // Input text.
                    .parameter("dimension", 1024)  // Specifies the output embedding dimension. This parameter is available only for text-embedding-v3 and text-embedding-v4 models.
                    .build();

            // Create a model instance and call the model.
            TextEmbedding textEmbedding = new TextEmbedding();
            TextEmbeddingResult result = textEmbedding.call(param);
            
            // Print the result.
            System.out.println(result);
            
        } catch (ApiException | NoApiKeyException e) {
            System.out.println("Call failed: " + e.getMessage());
        }
    }
}

curl

curl --location 'https://dashscope.aliyuncs.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": [
        "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."
        ]
    },
    "parameters": {
    	"dimension": 1024,
    	"output_type": "dense"
    }
}'

Input string list

Python

import dashscope
from http import HTTPStatus

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="text-embedding-v4",
        input=batch,
        dimension=1024  # Specifies the output embedding dimension. This parameter is available only for text-embedding-v3 and text-embedding-v4 models.
    )
    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.embeddings.TextEmbeddingResultItem;

public final class Main {
    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("text-embedding-v4")
                    .texts(batch)
                    .parameter("dimension", 1024)  // Specifies the output embedding dimension. This parameter is available only for text-embedding-v3 and text-embedding-v4 models.
                    .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

curl --location 'https://dashscope.aliyuncs.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": [
          "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

from http import HTTPStatus
from dashscope import TextEmbedding

with open('texts_to_embedding.txt', 'r', encoding='utf-8') as f:
    resp = TextEmbedding.call(
        model="text-embedding-v4",
        input=f,
        dimension=1024 # Specifies the output embedding dimension. This parameter is available only for text-embedding-v3 and text-embedding-v4 models.
    )

    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;

public final class Main {
    public static void main(String[] args) {
        try (BufferedReader reader = new BufferedReader(new FileReader("<path_to_your_content_root>"))) {
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }

            TextEmbeddingParam param = TextEmbeddingParam.builder()
                    .model("text-embedding-v4")
                    .text(content.toString())
                    .parameter("dimension", 1024)  // Specifies the output embedding dimension. This parameter is available only for text-embedding-v3 and text-embedding-v4 models.
                    .build();

            TextEmbedding textEmbedding = new TextEmbedding();
            TextEmbeddingResult result = textEmbedding.call(param);

            if (result != null) {
                System.out.println(result);
            } else {
                System.out.println("Failed to get embedding: " + result);
            }
        } catch (IOException | ApiException | NoApiKeyException e) {
            e.printStackTrace();
        }
    }
}

curl

Replace 'texts_to_embedding.txt' with your file name or path.
FILE_CONTENT=$(cat texts_to_embedding.txt | jq -Rs .)
curl --location 'https://dashscope.aliyuncs.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"
    }
}'

model string required

The model to use. For a list of available models, see the Model overview table.

input string or array<string> required

The text to process. The input can be a string, an array of strings, or a file. The supported text length and batch size vary by model version.

  • text-embedding-v3 / v4 models:

    • String input: Up to 8,192 tokens.

    • String list or file input: Up to 10 items (lines), with each item up to 8,192 tokens.

  • text-embedding-v1 / v2 models:

    • String input: Up to 2,048 tokens.

    • String list or file input: Up to 25 items (lines), with each item up to 2,048 tokens.

text_type string optional

When making an HTTP call, place text_type in the parameters object.

Text converted to embeddings can be applied to downstream tasks such as retrieval, clustering, and classification. For asymmetric tasks such as retrieval, it is recommended to differentiate between query text (query) and document text (document) to achieve better retrieval performance. For symmetric tasks such as indexing, clustering, and classification, you can simply use the system default value of document.

dimension integer optional

When making an HTTP call, place dimension in the parameters object.

Specifies the embedding dimension for the output vector. Valid values are 2048 (for text-embedding-v4 only), 1536 (for text-embedding-v4 only), 1024, 768, 512, 256, 128, or 64. Defaults to 1024.

output_type string optional

When making an HTTP call, place output_type in the parameters object.

Specifies the output vector type. This parameter applies only to the text-embedding-v3 and text-embedding-v4 models. Valid values are dense, sparse, and dense&sparse. Defaults to dense, which returns only the dense vector representation.

instruct string optional

Provides custom instructions to guide the model in understanding the query intent. English instructions are recommended, as they typically improve performance by 1% to 5%.

Response object

Successful response

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

Error response

{
    "code":"InvalidApiKey",
    "message":"Invalid API-key provided.",
    "request_id":"xxxxxxxx"
}

status_code string

The HTTP status code. A value of 200 indicates success.

request_id string

A unique identifier for the request. Use this ID to trace and troubleshoot the request.

code string

The error code returned if the request fails. This field is empty for successful requests.

message string

A detailed error message if the request fails. This field is empty for successful requests.

output object

The result of the task.

Properties

embeddings array

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

Properties

sparse_embedding array

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

Properties

index integer

The index of the token in the vocabulary.

value float

Indicates the weight or importance score of the Token. The higher the value, the greater the importance or relevance of the Token in the current text context.

token string

The text of the token.

embedding array

The dense vector representation for the corresponding string.

text_index integer

The index of the corresponding text in the input array.

usage object

Properties

total_tokens integer

The number of tokens in the input, as calculated by the model's tokenizer.

Error codes

If a model call fails, see Error Messages.