すべてのプロダクト
Search
ドキュメントセンター

Alibaba Cloud Model Studio:同期 API の詳細

最終更新日:Nov 27, 2025

テキスト埋め込みモデルは、テキストデータを数値ベクターに変換し、セマンティック検索、推奨、クラスタリング、分類などの下流タスクに利用します。

モデルの概要

シンガポール

モデル

ベクターディメンション

最大行数

1 行あたりの最大トークン数 ()

価格 (入力 100 万トークンあたり)

サポート言語

無料クォータ(注)

text-embedding-v4

Qwen3-Embedding シリーズの一部

2,048、1,536、1,024 (デフォルト)、768、512、256、128、64

10

8,192

$0.07

中国語、英語、スペイン語、フランス語、ポルトガル語、インドネシア語、日本語、韓国語、ドイツ語、ロシア語、その他 100 以上の主要言語

100 万トークン

Model Studio をアクティベートしてから 90 日間有効です。

text-embedding-v3

1,024 (デフォルト)、768、512

中国語、英語、スペイン語、フランス語、ポルトガル語、インドネシア語、日本語、韓国語、ドイツ語、ロシア語、その他 50 以上の主要言語

50 万トークン

有効期間: Model Studio をアクティベートしてから 90 日間

北京

モデル名

ベクターディメンション

最大行数

1 行あたりの最大トークン数

価格 (入力 100 万トークンあたり)

サポート言語

text-embedding-v4

Qwen3-Embedding シリーズの一部

2,048、1,536、1,024 (デフォルト)、768、512、256、128、64

10

8,192

$0.072

中国語、英語、スペイン語、フランス語、ポルトガル語、インドネシア語、日本語、韓国語、ドイツ語、ロシア語、その他 100 以上の主要言語および複数のプログラミング言語

モデルのレート制限の詳細については、「レート制限」をご参照ください。

事前準備

OpenAI エコシステムに精通している場合は、OpenAI 互換 API を使用して迅速な移行が可能です。DashScope API は、より多くの専用機能を提供します。ニーズに最も適した API を選択してください。

API キーを取得し、API キーを環境変数として設定する必要があります。SDK を使用して呼び出しを行う場合は、DashScope SDK をインストールする必要もあります。

OpenAI 互換

SDK 呼び出し用に設定する base_url:

  • シンガポール: https://dashscope-intl.aliyuncs.com/compatible-mode/v1

  • 中国 (北京): https://dashscope.aliyuncs.com/compatible-mode/v1

HTTP 呼び出し用に設定するエンドポイント:

  • シンガポール: POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/embeddings

  • 中国 (北京): POST https://dashscope.aliyuncs.com/compatible-mode/v1/embeddings

リクエストボディ

入力文字列

Python

import os
from openai import OpenAI

client = OpenAI(
    # 中国 (北京) リージョンのモデルを使用する場合、そのリージョンの API キーを使用する必要があります。API キーは https://bailian.console.alibabacloud.com/?tab=model#/api-key で取得できます。
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # 環境変数を設定していない場合は、プレースホルダーをご自身の API キーに置き換えてください。
    # 中国 (北京) リージョンのモデルを使用する場合、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください。
    base_url="https://dashscope-intl.aliyuncs.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())

Java

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.dashscope.utils.JsonUtils;

public final class Main {
    public static void main(String[] args) {
        // 中国 (北京) リージョンのモデルを使用する場合、そのリージョンの API キーを使用する必要があります。API キーは https://bailian.console.alibabacloud.com/?tab=model#/api-key で取得できます。
        String apiKey = System.getenv("DASHSCOPE_API_KEY");
        if (apiKey == null) {
            System.out.println("DASHSCOPE_API_KEY not found in environment variables");
            return;
        }
        // 中国 (北京) リージョンのモデルを使用する場合、URL を https://dashscope.aliyuncs.com/compatible-mode/v1/embeddings に置き換えてください。
        String baseUrl = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/embeddings";
        HttpClient client = HttpClient.newHttpClient();

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "text-embedding-v4");
        requestBody.put("input", "The wind is strong, the sky is high, and the apes cry mournfully. The islet is clear, the sand is white, and the birds fly back. The boundless forest sheds its leaves shower by shower. The endless river rolls on wave after wave.");
        requestBody.put("dimensions", 1024);
        requestBody.put("encoding_format", "float");

        try {
            String requestBodyString = JsonUtils.toJson(requestBody);
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(baseUrl))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + apiKey)
                    .POST(HttpRequest.BodyPublishers.ofString(requestBodyString))
                    .build();
                    
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            if (response.statusCode() == 200) {
                System.out.println("Response: " + response.body());
            } else {
                System.out.printf("Failed to retrieve response, status code: %d, response: %s%n", response.statusCode(), response.body());
            }
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

curl

中国 (北京) リージョンのモデルを使用する場合、そのリージョンの API キー を使用し、URL を https://dashscope.aliyuncs.com/compatible-mode/v1/embeddings に置き換えてください。
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-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"
}'

入力文字列リスト

Python

import os
from openai import OpenAI

client = OpenAI(
    # 中国 (北京) リージョンのモデルを使用する場合、そのリージョンの API キーを使用する必要があります。API キーは https://bailian.console.alibabacloud.com/?tab=model#/api-key で取得できます。
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # 環境変数を設定していない場合は、プレースホルダーをご自身の API キーに置き換えてください。
    # 中国 (北京) リージョンのモデルを使用する場合、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください。
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1"  
)

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,
    encoding_format="float"
)

print(completion.model_dump_json())

Java

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.Arrays;
import com.alibaba.dashscope.utils.JsonUtils;

public final class Main {
    public static void main(String[] args) {
        /** 環境変数から API キーを取得します。設定されていない場合は、プレースホルダーをご自身の API キーに置き換えてください。 */
        // 中国 (北京) リージョンのモデルを使用する場合、そのリージョンの API キーを使用する必要があります。API キーは https://bailian.console.alibabacloud.com/?tab=model#/api-key で取得できます。
        String apiKey = System.getenv("DASHSCOPE_API_KEY");
        if (apiKey == null) {
            System.out.println("DASHSCOPE_API_KEY not found in environment variables");
            return;
        }
        // 中国 (北京) リージョンのモデルを使用する場合、URL を https://dashscope.aliyuncs.com/compatible-mode/v1/embeddings に置き換えてください。
        String baseUrl = "https://dashscope-intl.aliyuncs.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("The wind is strong, the sky is high, and the apes cry mournfully.", "The islet is clear, the sand is white, and the birds fly back.", "The boundless forest sheds its leaves shower by shower.", "The endless river rolls on wave after wave.");
        requestBody.put("input", inputList);
        requestBody.put("encoding_format", "float");

        try {
            /** リクエストボディを JSON 文字列に変換します。 */
            String requestBodyString = JsonUtils.toJson(requestBody);

            /** HTTP リクエストを構築します。 */
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(baseUrl))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + apiKey)
                    .POST(HttpRequest.BodyPublishers.ofString(requestBodyString))
                    .build();

            /** リクエストを送信し、レスポンスを受信します。 */
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            if (response.statusCode() == 200) {
                System.out.println("Response: " + response.body());
            } else {
                System.out.printf("Failed to retrieve response, status code: %d, response: %s%n", response.statusCode(), response.body());
            }
        } catch (Exception e) {
            /** 例外をキャッチして出力します。 */
            System.err.println("Error: " + e.getMessage());
        }
    }
}

curl

中国 (北京) リージョンのモデルを使用する場合、そのリージョンの API キー を使用し、URL を https://dashscope.aliyuncs.com/compatible-mode/v1/embeddings に置き換えてください。
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-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"
}'

入力ファイル

Python

import os
from openai import OpenAI

client = OpenAI(
    # 中国 (北京) リージョンのモデルを使用する場合、そのリージョンの API キーを使用する必要があります。API キーは https://bailian.console.alibabacloud.com/?tab=model#/api-key で取得できます。
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # 環境変数を設定していない場合は、プレースホルダーをご自身の API キーに置き換えてください。
    # 中国 (北京) リージョンのモデルを使用する場合、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください。
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1"  
)
# 'texts_to_embedding.txt' をご自身のファイル名またはパスに置き換えてください。
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())

Java

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.alibaba.dashscope.utils.JsonUtils;

public class Main {
    public static void main(String[] args) {
        /** 環境変数から API キーを取得します。設定されていない場合は、プレースホルダーをご自身の API キーに置き換えてください。 */
        // 中国 (北京) リージョンのモデルを使用する場合、そのリージョンの API キーを使用する必要があります。API キーは https://bailian.console.alibabacloud.com/?tab=model#/api-key で取得できます。
        String apiKey = System.getenv("DASHSCOPE_API_KEY");
        if (apiKey == null) {
            System.out.println("DASHSCOPE_API_KEY not found in environment variables");
            return;
        }
        // 中国 (北京) リージョンのモデルを使用する場合、URL を https://dashscope.aliyuncs.com/compatible-mode/v1/embeddings に置き換えてください。
        String baseUrl = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/embeddings";
        HttpClient client = HttpClient.newHttpClient();

        /** 入力ファイルを読み込みます。 */
        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);

            /** HTTP リクエストを構築します。 */
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(baseUrl))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + apiKey)
                    .POST(HttpRequest.BodyPublishers.ofString(requestBodyString))
                    .build();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            if (response.statusCode() == 200) {
                System.out.println("Response: " + response.body());
            } else {
                System.out.printf("Failed to retrieve response, status code: %d, response: %s%n", response.statusCode(), response.body());
            }
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

curl

中国 (北京) リージョンのモデルを使用する場合、そのリージョンの API キー を使用し、URL を https://dashscope.aliyuncs.com/compatible-mode/v1/embeddings に置き換えてください。
'texts_to_embedding.txt' をご自身のファイル名またはパスに置き換えてください。
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-v4",
    "input": ['"$FILE_CONTENT"'],
    "dimensions": 1024,
    "encoding_format": "float"
}'

model string 必須

呼び出すモデル。モデルの概要の表からモデル名を選択します。

input array<string> or string or file 必須

埋め込む入力テキスト。文字列、文字列のリスト、または各行が個別のテキストとして扱われるファイルです。

テキストの制限:

  • テキスト入力の制限:

    • 文字列には最大 8,192 トークンを含めることができます。

    • 文字列のリストには最大 10 個の文字列を含めることができ、各文字列の最大トークン数は 8,192 です。

    • ファイルには最大 10 行を含めることができ、各行の最大トークン数は 8,192 です。

dimensions integer 任意

ベクターディメンション。値は、2048 (text-embedding-v4 のみ)、1536 (text-embedding-v4 のみ)、1024、768、512、256、128、または 64 のいずれかである必要があります。デフォルト値は 1024 です。

encoding_format string 任意

返される埋め込みのフォーマット。float フォーマットのみがサポートされています。

レスポンスオブジェクト

成功応答

{
  "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": {
        "message": "Incorrect API key provided. ",
        "type": "invalid_request_error",
        "param": null,
        "code": "invalid_api_key"
    }
}

data array

タスクの出力データ。

プロパティ

embedding list

埋め込みベクター。浮動小数点数の配列です。

index integer

この構造の結果に対応する入力配列内の入力テキストのインデックス。

object string

呼び出しによって返されるオブジェクトのタイプ。デフォルト値は embedding です。

model string

呼び出されたモデル。

object string

呼び出しによって返されるデータのタイプ。デフォルト値は list です。

usage object

プロパティ

prompt_tokens integer

入力テキスト内のトークン数。

total_tokens integer

リクエスト内の合計トークン数。トークン数は、モデルのトークナイザーが入力文字列をどのように解析するかに基づいて計算されます。

id string

一意のリクエスト ID。この ID を使用してリクエストのトレースとトラブルシューティングができます。

DashScope

SDK 呼び出し用に設定する base_url:

  • シンガポール: https://dashscope-intl.aliyuncs.com/api/v1

  • 中国 (北京): https://dashscope.aliyuncs.com/api/v1

HTTP 呼び出しのエンドポイント:

  • シンガポール: POST https://dashscope-intl.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding

  • 中国 (北京): POST https://dashscope.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding

リクエストボディ

入力文字列

Python

import dashscope
from http import HTTPStatus

# 中国 (北京) リージョンのモデルを使用する場合、URL を https://dashscope.aliyuncs.com/api/v1 に置き換えてください。
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

resp = dashscope.TextEmbedding.call(
    model=dashscope.TextEmbedding.Models.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.',
    dimension=1024,
    output_type="dense&sparse"
)

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

Java

import java.util.Arrays;
import java.util.concurrent.Semaphore;
import com.alibaba.dashscope.common.ResultCallback;
import com.alibaba.dashscope.embeddings.TextEmbedding;
import com.alibaba.dashscope.embeddings.TextEmbeddingParam;
import com.alibaba.dashscope.embeddings.TextEmbeddingResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;

public final class Main {
    static {
        // 中国 (北京) リージョンのモデルを使用する場合、URL を https://dashscope.aliyuncs.com/api/v1 に置き換えてください。
        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_V4)
        .texts(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.")).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("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.")).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

中国 (北京) リージョンのモデルを使用する場合、そのリージョンの API キー を使用し、URL を https://dashscope.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding に置き換えてください。
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-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"
    }
}'

入力文字列リスト

Python

import dashscope
from http import HTTPStatus

# 中国 (北京) リージョンのモデルを使用する場合、URL を https://dashscope.aliyuncs.com/api/v1 に置き換えてください。
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
DASHSCOPE_MAX_BATCH_SIZE = 10

inputs = ['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.']

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)

Java

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

public final class Main {
    static {
        // 中国 (北京) リージョンのモデルを使用する場合、URL を https://dashscope.aliyuncs.com/api/v1 に置き換えてください。
        Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
    }
    private static final int DASHSCOPE_MAX_BATCH_SIZE = 10;

    public static void main(String[] args) {
        List<String> inputs = 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."
        );

        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);
    }
}

curl

中国 (北京) リージョンのモデルを使用する場合、そのリージョンの API キー を使用し、URL を https://dashscope.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding に置き換えてください。
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-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"
    }
}'

入力ファイル

Python

import dashscope
from http import HTTPStatus
from dashscope import TextEmbedding

# 中国 (北京) リージョンのモデルを使用する場合、URL を https://dashscope.aliyuncs.com/api/v1 に置き換えてください。
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# 'texts_to_embedding.txt' をご自身のファイル名またはパスに置き換えてください。
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)

Java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.alibaba.dashscope.embeddings.TextEmbedding;
import com.alibaba.dashscope.embeddings.TextEmbeddingParam;
import com.alibaba.dashscope.embeddings.TextEmbeddingResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;

public final class Main {
    static {
        // 中国 (北京) リージョンのモデルを使用する場合、URL を https://dashscope.aliyuncs.com/api/v1 に置き換えてください。
        Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
    }
    public static void main(String[] args) {
        // 'tests_to_embedding.txt' をファイルの完全なパスに置き換えてください。
        try (BufferedReader reader = new BufferedReader(new FileReader("tests_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();
        }
    }
}

curl

中国 (北京) リージョンのモデルを使用する場合、そのリージョンの API キー を使用し、URL を https://dashscope.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding に置き換えてください。
'texts_to_embedding.txt' をご自身のファイル名またはパスに置き換えてください。
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-v4",
    "input": {
        "texts": ['"$FILE_CONTENT"']
    },
    "parameters": {
        "dimension": 1024,
        "output_type": "dense"
    }
}'

model string 必須

呼び出すモデル。モデルの概要の表からモデル名を選択します。

input string または array<string> 必須

入力テキストは、文字列、文字列のリスト、またはファイルです。入力がファイルの場合、各行は埋め込む個別のテキストとして扱われます。

テキストの制限:

  • 文字数:

    • 文字列には最大 8,192 トークンを含めることができます。

    • 文字列のリストには最大 10 個の項目を含めることができます。各文字列には最大 8,192 トークンを含めることができます。

    • ファイルには最大 10 行を含めることができ、各行の最大トークン数は 8,192 です。

text_type string 任意

テキストベクターは、取得、クラスタリング、分類などの下流タスクに使用できます。取得などの非対称タスクでは、より良い結果を得るためにクエリとドキュメントを区別することを推奨します。クラスタリングや分類などの対称タスクでは、デフォルト値の document を使用できます。

dimension integer 任意

ベクターディメンション。値は、2048 (text-embedding-v4 のみ)、1536 (text-embedding-v4 のみ)、1024、768、512、256、128、または 64 のいずれかである必要があります。デフォルト値は 1024 です。

output_type string 任意

疎ベクトル表現を出力するかどうかを指定します。このパラメーターは text-embedding-v3 および text-embedding-v4 モデルにのみ適用されます。有効な値は dense、sparse、および dense&sparse です。デフォルト値は dense で、密ベクトルのみを返します。

instruct string 任意

カスタムのタスクの説明。このパラメーターは、text-embedding-v4 モデルを使用し、text_typequery に設定した場合にのみ有効です。パフォーマンスが約 1% から 5% 向上するため、説明は英語で記述することを推奨します。

レスポンスオブジェクト

成功応答

{   "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
          }, 
          {
             "sparse_embedding":[
               {"index":246351,"value":1.0483,"token":"islet"},
               .....
               {"index":2490,"value":0.8579,"token":"return"}],
             "embedding": [-0.006929283495992422,-0.005336422007530928, ...],
             "text_index": 1
          },
          {
             "sparse_embedding":[
               {"index":3759,"value":0.7065,"token":"none"},
               .....
               {"index":1130,"value":0.815,"token":"down"}],
             "embedding": [-0.006929283495992422,-0.005336422007530928, ...],
             "text_index": 2
          },
          {
             "sparse_embedding":[
               {"index":562,"value":0.6752,"token":"not"},
               .....
               {"index":1589,"value":0.7097,"token":"come"}],
             "embedding": [-0.001945948973298072,-0.005336422007530928, ...],
             "text_index": 3
          }
        ]
    },
    "usage":{
        "total_tokens":27
    }
}

エラー応答

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

status_code string

状態コード。値 200 はリクエストの成功を示します。

request_id string

一意のリクエスト ID。この ID を使用してリクエストのトレースとトラブルシューティングができます。

code string

リクエストが失敗した場合、このパラメーターはエラーコードを示します。リクエストが成功した場合、このパラメーターは空です。

message string

リクエストが失敗した場合、このパラメーターは詳細なエラーメッセージを示します。リクエストが成功した場合、このパラメーターは空です。

output object

タスクの出力データ。

プロパティ

embeddings array

構造の配列。各構造には、対応する入力テキストの出力が含まれます。

プロパティ

sparse_embedding array

対応する文字列の疎ベクトル表現。sparse_embedding パラメーターは text-embedding-v3 と text-embedding-v4 にのみ適用されます。

プロパティ

index integer

語彙内の単語または文字のインデックス。

value float

token の重みまたは重要度スコア。値が高いほど、現在のテキストコンテキストで token がより重要または関連性が高いことを示します。

token string

語彙からの実際のテキスト単位または単語。

embedding array

対応する文字列の密ベクトル表現 (密埋め込み)。

text_index integer

この構造の結果に対応する入力配列内の入力テキストのインデックス。

usage object

プロパティ

total_tokens integer

リクエスト内の合計トークン数。トークン数は、モデルのトークナイザーが入力文字列をどのように解析するかに基づいて計算されます。

エラーコード

モデルの呼び出しが失敗し、エラーメッセージが返された場合は、「エラーメッセージ」を参照して問題の解決方法を確認してください。