All Products
Search
Document Center

Alibaba Cloud Model Studio:Embedding

Last Updated:Apr 29, 2025

Embedding is the process of converting text data into vectors in a mathematical space. The proximity or angle between vectors indicates the similarity between the data items. This is useful for tasks such as classification, retrieval, and recommendation.

Scenarios

  • Recommendation: Recommends relevant items based on input data. For example, recommends products based on user purchase history and browsing behavior.

  • Clustering: Groups input data by relevance. For example, categorizes news articles into topics such as technology, sports, and entertainment.

  • Search: Ranks search results by relevance to input data. For example, a text embedding model return relevant web pages based on user query.

  • Anomaly detection: Detects data points that deviate from the norm. For example, in the finance sector, extract feature vectors from transaction records to identify unusual transactions as potential frauds.

Supported models

General text embedding

Vector dimension refers to the number of elements in a vector. For example, a 1,024-dimensional vector contains 1,024 numerical values. Higher dimensions allow vectors to represent richer information, thus capturing text characteristics more precisely.

Name

Vector dimensions

Maximum rows

Maximum tokens per row

Supported languages

Price

(Million input tokens)

Free quota

(Note)

text-embedding-v3

1,024 (default), 768 or 512

10

8,192

Chinese, English, Spanish, French, Portuguese, Indonesian, Japanese, Korean, German, Russian, and more than 50 other languages

$0.07

500,000 tokens

Valid for 180 days after activation

Model overview

text-embedding-v3

  • Supported languages: More than 50 languages, including Italian, Polish, Vietnamese, and Thai.

  • Input token length: The maximum input length increased from 2,048 tokens to 8,192 tokens.

    For string input cases, the model treats the entire string as a single line, with an input length limit of 8,192 tokens. If the string content exceeds this limit, you can adjust the input format using these methods:

    • String list input: Split the input content into multiple parts and generate a string list. Ensure the following conditions:

      • The list contains no more than 10 elements.

      • Each element's length is within 8,192 tokens.

    • File upload: Combine the input string content into a file and upload the file. Ensure the following conditions:

      • The total number of lines in the file does not exceed 10.

      • Each line's length is within 8,192 tokens.

  • Customizable vector dimension: You can choose between 64, 128, 256, 512, 768 or 1,024. The default value is 1,024.

  • No distinction between Query and Document: text_type does not distinguish between Query and Document.

  • Support for sparse vector: You can specify dense or sparse vector to output.

    • Dense vectors: More effectively capture text semantic features, suitable for regular retrieval and semantic matching scenarios.

    • Sparse vectors: Reduced computational complexity and storage costs, suitable for scenarios with limited storage resources or requiring efficient semantic matching.

  • Improved performance: Further optimized pre-trained model and SFT strategy ehance the overall performance of text-embedding-v3, as shown in public dataset evaluations.

Performance metrics

Model

MTEB

MTEB (Retrieval task)

CMTEB

CMTEB (Retrieval task)

text-embedding-v3 (512 dimensions)

62.11

54.30

66.81

71.88

text-embedding-v3 (768 dimensions)

62.43

54.74

67.90

72.29

text-embedding-v3 (1,024 dimensions)

63.39

55.41

68.92

73.23

Quick Start

You must first obtain an API key and set the API key as an environment variable. If you need to use OpenAI SDK or DashScope SDK, you must install the SDK.

String input

OpenAI compatible

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # Replace with your API Key if you have not configured environment variables
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1"  # base_url for Model Studio
)

completion = client.embeddings.create(
    model="text-embedding-v3",
    input='The quality of the clothes is excellent, very beautiful, worth the wait, I like it and will buy here again',
    dimensions=1024,
    encoding_format="float"
)

print(completion.model_dump_json())
import OpenAI from "openai";
import process from 'process';

// Initialize OpenAI client
const openai = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY, // Read from environment variable
    baseURL: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1'
});

async function getEmbedding() {
    try {
        const completion = await openai.embeddings.create({
            model: "text-embedding-v3",
            input: 'The quality of the clothing is excellent, very beautiful. It was worth the long wait. I like it, and I will come back here to buy again.',
            dimensions: 1024, // Specify vector dimension (only supported by text-embedding-v3)
            encoding_format: "float"
        });

        console.log(JSON.stringify(completion, null, 2));
    } catch (error) {
        console.error('Error:', error);
    }
}

getEmbedding();
curl --location 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/embeddings' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "text-embedding-v3",
    "input": "The quality of the clothes is excellent, very beautiful, worth the wait, I like it and will buy here again",  
    "dimension": "1024",  
    "encoding_format": "float"
}'

DashScope

import dashscope
from http import HTTPStatus

dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
resp = dashscope.TextEmbedding.call(
    model=dashscope.TextEmbedding.Models.text_embedding_v3,
    input='The quality of the clothes is excellent, very beautiful, worth the wait, I like it and will buy here again',
    dimension=1024,
    output_type="dense&sparse"
)

print(resp) if resp.status_code == HTTPStatus.OK else print(resp)
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://dashscope-intl.aliyuncs.com/api/v1";
    }
    public static void basicCall() throws ApiException, NoApiKeyException{
        TextEmbeddingParam param = TextEmbeddingParam
        .builder()
        .model(TextEmbedding.Models.TEXT_EMBEDDING_V3)
        .texts(Arrays.asList("Shall I compare thee to a summers day", "Thou art more lovely and more temperate", "Rough winds do shake the darling buds of May", "And summers lease hath all too short a date")).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("Shall I compare thee to a summers day", "Thou art more lovely and more temperate", "Rough winds do shake the darling buds of May", "And summers lease hath all too short a date")).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 --location 'https://dashscope-intl.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-v3",
    "input": {
        "texts": [
        "The quality of the clothes is excellent, very beautiful, worth the wait, I like it and will buy here again"
        ]
    },
    "parameters": {
        "dimension": 1024
    }
}'

String list input

OpenAI compatible

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # Replace with your API Key if you have not configured environment variables
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1"  # base_url for DashScope service
)

completion = client.embeddings.create(
    model="text-embedding-v3",
    input=['Shall I compare thee to a summers day', 'Thou art more lovely and more temperate', 'Rough winds do shake the darling buds of May', 'And summers lease hath all too short a date'],
    encoding_format="float"
)

print(completion.model_dump_json())
import OpenAI from "openai";
import process from 'process';

// Initialize OpenAI client
const openai = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY, // Read from environment variable
    baseURL: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1'
});

async function getMultipleEmbeddings() {
    try {
        const completion = await openai.embeddings.create({
            model: "text-embedding-v3",
            input: [
                'Shall I compare thee to a summers day?', 
                'Thou art more lovely and more temperate.', 
                'Rough winds do shake the darling buds of May,', 
                'And summers lease hath all too short a date.'
            ],
            encoding_format: "float"
        });

        console.log(JSON.stringify(completion, null, 2));
    } catch (error) {
        console.error('Error:', error);
    }
}

getMultipleEmbeddings();
curl --location 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/embeddings' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "text-embedding-v3",
    "input": [
        "Shall I compare thee to a summers day",
        "Thou art more lovely and more temperate", 
        "Rough winds do shake the darling buds of May", 
        "And summers lease hath all too short a date"
        ],
    "encoding_format": "float"
}'

DashScope

import dashscope
from http import HTTPStatus

dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
DASHSCOPE_MAX_BATCH_SIZE = 25

inputs = ['Shall I compare thee to a summers day', 'Thou art more lovely and more temperate', 'Rough winds do shake the darling buds of May', 'And summers lease hath all too short a date']

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_v3,
        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)
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://dashscope-intl.aliyuncs.com/api/v1";
    }
    private static final int DASHSCOPE_MAX_BATCH_SIZE = 25;

    public static void main(String[] args) {
        List<String> inputs = Arrays.asList(
                "Shall I compare thee to a summers day",
                "Thou art more lovely and more temperate",
                "Rough winds do shake the darling buds of May",
                "And summers lease hath all too short a date"
        );

        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_V3)
                    .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 --location 'https://dashscope-intl.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-v3",
    "input": {
        "texts": [
          "Shall I compare thee to a summers day",
          "Thou art more lovely and more temperate", 
          "Rough winds do shake the darling buds of May", 
          "And summers lease hath all too short a date"
        ]
    },
    "parameters": {
        "dimension": 1024
    }
}'

File input

Sample file:

OpenAI compatible

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # Replace with your API Key if you have not configured environment variables
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1"  # base_url for Model Studio
)
with open('texts_to_embedding.txt', 'r', encoding='utf-8') as f:
    completion = client.embeddings.create(
        model="text-embedding-v3",
        input=f
    )
print(completion.model_dump_json())
import OpenAI from "openai";
import process from 'process';
import fs from 'fs/promises';

// Initialize OpenAI client
const openai = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY, // Read from environment variable
    baseURL: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1'
});

async function getEmbeddingsFromFile() {
    try {
        // Read the content of the file
        const fileContent = await fs.readFile('texts_to_embedding.txt', 'utf-8');
        
        // Create embedding vectors
        const completion = await openai.embeddings.create({
            model: "text-embedding-v3",
            input: fileContent
        });

        console.log(JSON.stringify(completion, null, 2));
    } catch (error) {
        console.error('Error:', error);
    }
}

getEmbeddingsFromFile();
FILE_CONTENT=$(cat texts_to_embedding.txt | jq -Rs .)
curl --location 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/embeddings' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "text-embedding-v3",
    "input": ['"$FILE_CONTENT"']
}'

DashScope

from http import HTTPStatus
import dashscope
from dashscope import TextEmbedding

dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
with open('texts_to_embedding.txt', 'r', encoding='utf-8') as f:
    resp = TextEmbedding.call(
        model=TextEmbedding.Models.text_embedding_v3,
        input=f
    )

    if resp.status_code == HTTPStatus.OK:
        print(resp)
    else:
        print(resp)
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://dashscope-intl.aliyuncs.com/api/v1";
    }
    public static void main(String[] args) {
        try (BufferedReader reader = new BufferedReader(new FileReader(""))) {
            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_V3)
                    .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();
        }
    }
}
FILE_CONTENT=$(cat texts_to_embedding.txt | jq -Rs .)
curl --location 'https://dashscope-intl.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-v3",
    "input": {
        "texts": ['"$FILE_CONTENT"']
    }
}'

Sample output

OpenAI compatible

{ 
  "data": [
    {
      "embedding": [
        0.0023064255,
        -0.009327292,
        .... 
        -0.0028842222,
      ],
      "index": 0,
      "object": "embedding"
    }
  ],
  "model":"text-embedding-v3",
  "object":"list",
  "usage":{"prompt_tokens":26,"total_tokens":26},
  "id":"f62c2ae7-0906-9758-ab34-47c5764f07e2"
}

DashScope

{
    "status_code": 200,
    "request_id": "617b3670-6f9e-9f47-ad57-997ed8aeba6a",
    "code": "",
    "message": "",
    "output": {
        "embeddings": [
            {
                "embedding": [
                    0.09393704682588577,
                    2.4155092239379883,
                    -1.8923076391220093,
                    .,
                    .,
                    .

                ],
                "text_index": 0
            }
        ]
    },
    "usage": {
        "total_tokens": 26
    }
}

Sample code

Semantic recommendation

1. Import libraries and configure API key

Import the required libraries and modules and configure the API key.

# Import required libraries
import os
import pandas as pd
import pickle
import dashscope
from dashscope import TextEmbedding
import numpy as np

dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# Set DashScope API Key from environment variable
dashscope.api_key = os.getenv("DASHSCOPE_API_KEY")

2. Define embedding function

This function calls API to generate text embeddings. It accepts a single string or a list of strings, processes them using the model, and extracts the embeddings. If the input is a list, it returns all embeddings. For a single string, it returns the first embedding.

# Define function: generate text embeddings
def generate_embeddings(text):
    """
    Generate embeddings for input text using DashScope's text-embedding-v3 model.
    Args:
        text (str or list): Input text string or list of strings.
    Returns:
        list: Returns a single embedding if input is a string, or multiple vectors if input is a list.
    """
    rsp = TextEmbedding.call(model=TextEmbedding.Models.text_embedding_v3, input=text)
    # Extract embeddings from API response
    embeddings = [record['embedding'] for record in rsp.output['embeddings']]
    return embeddings if isinstance(text, list) else embeddings[0]

3. Load dataset and print first n_examples samples

Load the dataset , and print the publication date and title for the first n samples.

# Load dataset
dataset_path = "sampled_file.csv"  # Dataset path
df = pd.read_csv(dataset_path)  # Read CSV file into DataFrame
n_examples = 5  # Set number of examples to display

# Display publish date and title of first few samples in dataset
print("Display first few samples in dataset:")
for idx, row in df.head(n_examples).iterrows():
    print("")
    print(f"Publish date: {row['publish_date']}")
    print(f"Title: {row['headline_text']}")

4. Set up and load embedding cache, define function to obtain embeddings

Set up and load embedding cache to improve the embedding efficiency for tasks such as recommendation systems. To avoid additional costs when calling the model, you can store the complete embedding cache file in your project directory.

recommendations_embeddings_cache.pkl

# Set embedding cache path (to avoid recomputation)
embedding_cache_path = "recommendations_embeddings_cache.pkl"

# Try to load cached embeddings, initialize empty dictionary if no cache exists
try:
    embedding_cache = pd.read_pickle(embedding_cache_path)
except FileNotFoundError:
    embedding_cache = {}

# Define function: obtain text embeddings through caching mechanism
def embedding_from_string(
    string: str,
    embedding_cache=embedding_cache
) -> list:
    """
    Get embedding for given text, using cache mechanism to avoid recomputation.
    Args:
        string (str): Input text string.
        embedding_cache (dict): Embedding cache dictionary.
    Returns:
        list: Generated embedding.
    """
    if string not in embedding_cache.keys():  # If text does not exist in cache
        embedding_cache[string] = generate_embeddings(string)  # Generate and cache embedding
        # Save cache to file
        with open(embedding_cache_path, "wb") as embedding_cache_file:
            pickle.dump(embedding_cache, embedding_cache_file)
    return embedding_cache[string]

5. Calculate embedding for example string

Extract the first string from the description column of the dataframe, calculate its embedding, and output the first 10 elements.

# Calculate embedding for example string
example_string = df["headline_text"].values[0]  # Select first text from dataset
print(f"\nExample text: {example_string}")
example_embedding = embedding_from_string(example_string)  # Get embedding
print(f"\nEmbedding for example text (first 10 dimensions): {example_embedding[:10]}...")
print("\n")

6. Define recommendation function

Calculate the embedding of a string and find the k most similar strings based on cosine similarity distance. Then, output these strings and their similarity distances.

# Define recommendation function: output most similar strings to given text
def print_recommendations_from_strings(
        strings,  # list[str]: List of input strings
        index_of_source_string,  # int: Index of source string in list
        k_nearest_neighbors=1,  # int: Number of similar strings to recommend
):
    """
    Output k strings most similar to source string.
    Args:
        strings (list): List of input strings.
        index_of_source_string (int): Index of source string in list.
        k_nearest_neighbors (int): Number of neighbors to recommend.
    """
    # Generate embeddings for all input strings
    embeddings = [embedding_from_string(string) for string in strings]
    # Get embedding for source string
    query_embedding = embeddings[index_of_source_string]

    # Define cosine similarity function
    def cosine_similarity(vec1, vec2):
        """
        Calculate cosine similarity between two vectors.
        Args:
            vec1 (list): Vector 1
            vec2 (list): Vector 2
        Returns:
            float: Cosine similarity value
        """
        return np.dot(vec1, vec2) / (np.linalg.norm(vec1) * np.linalg.norm(vec2))

    # Calculate distance (1 - similarity) between source embedding and all embeddings
    distances = [1 - cosine_similarity(query_embedding, emb) for emb in embeddings]

    # Sort by distance ascending, get indices of nearest neighbors
    indices_of_nearest_neighbors = np.argsort(distances)

    # Print source string
    query_string = strings[index_of_source_string]
    print(f"Source text: {query_string}")

    # Print k most similar strings and similarities
    k_counter = 0
    for i in indices_of_nearest_neighbors:
        if query_string == strings[i]:  # Skip comparison with self
            continue
        if k_counter >= k_nearest_neighbors:  # Limit number of recommendations
            break
        k_counter += 1
        print(
            f"""
        --- Recommendation #{k_counter} ---
        Similar text: {strings[i]}
        Similarity: {1 - distances[i]:0.3f}"""
        )
    return indices_of_nearest_neighbors

7. Get similar articles

Extract descriptions of all articles from the dataset, then obtain recommendations for 5 most similar articles based on specific topics.

# Get list of article titles
article_titles = df["headline_text"].tolist()

# Get recommendations based on text
print("Text-based recommendation example:")
print("Finance related article recommendations")
recommendations = print_recommendations_from_strings(
    strings=article_titles,  # Input list of article titles
    index_of_source_string=0,  # Select first text as source text
    k_nearest_neighbors=5,  # Recommend 5 most similar texts
)

API reference

Synchronous API call

Error code

If the call failed and an error message is returned, see Error messages.