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

Alibaba Cloud Model Studio:同期 API

最終更新日:Sep 09, 2026

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

モデル概要

シンガポール

モデル埋め込み次元最大行数

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

価格 (入力トークン 100 万個あたり)サポート言語

無料クォータ(注)

qwen3.7-text-embedding

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

20

128,000

$0.07

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

100 万トークン

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

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 以上の主要言語、および複数のプログラミング言語

中国 (香港)

モデル埋め込み次元最大行数1 行あたりの最大トークン数価格 (入力トークン 100 万個あたり)サポート言語

text-embedding-v4

Qwen3-Embedding シリーズの一部

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

10

8,192

$0.07

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

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

前提条件

OpenAI エコシステムに精通しているユーザーは、OpenAI 互換 API を使用して迅速に移行できます。DashScope API は、より独自の機能を提供します。

API キーを取得し、API キーを環境変数としてエクスポートします。SDK を使用して呼び出しを行う場合は、DashScope SDK をインストールします。

OpenAI 互換性

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

  • シンガポール:https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1。ご利用の実際のワークスペース ID で WorkspaceId を置き換えてください。
  • 中国 (北京):https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1
  • 中国 (香港):https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1。ご利用の実際のワークスペース ID で WorkspaceId を置き換えてください。

HTTP 呼び出し用に設定するendpoint:

  • シンガポール:POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/embeddings。ご利用の実際のワークスペース ID で WorkspaceId を置き換えてください。
  • 中国 (北京):POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/embeddings
  • 中国 (香港):POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1/embeddings。ご利用の実際のワークスペース ID で WorkspaceId を置き換えてください。

ご利用の実際のワークスペース ID で {WorkspaceId} を置き換えてください。

リクエストボディ

modelstring必須

呼び出すモデルの名前。モデル名については、「モデル概要」の表をご参照ください。

inputarray<string> or string or file必須

処理する入力テキスト。入力は、文字列、文字列の配列、またはファイルが可能です。 テキスト長とバッチサイズの制限は、モデルのバージョンによって異なります:

  • qwen3.7-text-embedding モデル:
    • 文字列入力:最大 128,000 トークン。
    • 文字列リストまたはファイル入力:最大 20 アイテム (行)、各アイテム (行) は最大 128,000 トークン。
  • text-embedding-v3 / v4 モデル:
    • 文字列入力:最大長 8,192 トークン。
    • 文字列リストまたはファイル入力:最大 10 アイテム (行)、各アイテム (行) は最大 8,192 トークン。

dimensions integer 任意

出力される埋め込みベクトルの次元。次の値のいずれかである必要があります:2560 (qwen3.7-text-embedding のみ)、2048 (text-embedding-v4 のみ)、1536 (text-embedding-v4 のみ)、1024、768、512、256、128、または 64。デフォルト値は 1024 です。

encoding_format string 任意

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

入力文字列

Python

import os
from openai import OpenAI

client = OpenAI(
    # 中国 (北京) リージョンのモデルを使用する場合、そのリージョンの API キーを使用する必要があります。取得先: https://modelstudio.console.alibabacloud.com/?tab=model#/api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # 環境変数が設定されていない場合は、プレースホルダーをご利用の API キーに置き換えてください。
    # これはシンガポールリージョンの URL です。ご利用の実際のワークスペース ID で {WorkspaceId} を置き換えてください。URL はリージョンによって異なります。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)

completion = client.embeddings.create(
    model="qwen3.7-text-embedding",
    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 キーを使用する必要があります。取得先: https://modelstudio.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 です。ご利用の実際のワークスペース ID で {WorkspaceId} を置き換えてください。URL はリージョンによって異なります。
        String baseUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/embeddings";
        HttpClient client = HttpClient.newHttpClient();

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "qwen3.7-text-embedding");
        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://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/embeddings に置き換える必要があります。以下のコード例では、シンガポールリージョンの URL を使用しています。ご利用の実際のワークスペース ID で {WorkspaceId} を置き換えてください。URL はリージョンによって異なります。

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/embeddings' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "qwen3.7-text-embedding",
    "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 キーを使用する必要があります。取得先: https://modelstudio.console.alibabacloud.com/?tab=model#/api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # 環境変数が設定されていない場合は、プレースホルダーをご利用の API キーに置き換えてください。
    # これはシンガポールリージョンの URL です。ご利用の実際のワークスペース ID で {WorkspaceId} を置き換えてください。URL はリージョンによって異なります。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)

completion = client.embeddings.create(
    model="qwen3.7-text-embedding",
    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 キーを使用する必要があります。取得先: https://modelstudio.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 です。ご利用の実際のワークスペース ID で {WorkspaceId} を置き換えてください。URL はリージョンによって異なります。
        String baseUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/embeddings";
        HttpClient client = HttpClient.newHttpClient();
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "qwen3.7-text-embedding");
        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://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/embeddings に置き換える必要があります。以下のコード例では、シンガポールリージョンの URL を使用しています。ご利用の実際のワークスペース ID で {WorkspaceId} を置き換えてください。URL はリージョンによって異なります。

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/embeddings' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "qwen3.7-text-embedding",
    "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 キーを使用する必要があります。取得先: https://modelstudio.console.alibabacloud.com/?tab=model#/api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # 環境変数が設定されていない場合は、プレースホルダーをご利用の API キーに置き換えてください。
    # これはシンガポールリージョンの URL です。ご利用の実際のワークスペース ID で {WorkspaceId} を置き換えてください。URL はリージョンによって異なります。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.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="qwen3.7-text-embedding",
        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 キーを使用する必要があります。取得先: https://modelstudio.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 です。ご利用の実際のワークスペース ID で {WorkspaceId} を置き換えてください。URL はリージョンによって異なります。
        String baseUrl = "https://{WorkspaceId}.ap-southeast-1.maas.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", "qwen3.7-text-embedding");
        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://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/embeddings に置き換える必要があります。以下のコード例では、シンガポールリージョンの URL を使用しています。ご利用の実際のワークスペース ID で {WorkspaceId} を置き換えてください。URL はリージョンによって異なります。

'texts_to_embedding.txt' をご利用のファイル名またはパスに置き換えてください。

FILE_CONTENT=$(cat texts_to_embedding.txt | jq -Rs .)
curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/embeddings' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "qwen3.7-text-embedding",
    "input": ['"$FILE_CONTENT"'],
    "dimensions": 1024,
    "encoding_format": "float"
}'

レスポンスオブジェクト

dataarray

結果として得られる埋め込みオブジェクトのリスト。

プロパティ

embeddinglist

埋め込みベクトル。浮動小数点数の配列として返されます。

indexinteger

入力配列内の対応する入力テキストのインデックス。

objectstring

オブジェクトタイプ。値は常に embedding です。

modelstring

この呼び出しで使用されたモデルの名前。

objectstring

オブジェクトタイプ。値は常に list です。

usageobject

プロパティ

prompt_tokensinteger

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

total_tokens integer

入力の合計トークン数。この数は、モデルのトークナイザーが入力文字列をどのように解析するかによって決まります。

idstring

リクエストの一意の識別子。トレースとトラブルシューティングに使用されます。

{
  "data": [
    {
      "embedding": [
        -0.0695386752486229, 0.030681096017360687, ...
      ],
      "index": 0,
      "object": "embedding"
    },
    ...
    {
      "embedding": [
        -0.06348952651023865, 0.060446035116910934, ...
      ],
      "index": 5,
      "object": "embedding"
    }
  ],
  "model": "qwen3.7-text-embedding",
  "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"
    }
}

DashScope

SDK 呼び出し用の base_url:

  • シンガポール:https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1。ご利用の実際のワークスペース ID で WorkspaceId を置き換えてください。
  • 中国 (北京):https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1
  • 中国 (香港):https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1。ご利用の実際のワークスペース ID で WorkspaceId を置き換えてください。
HTTP 呼び出し用のエンドポイント:
  • シンガポール:POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding。ご利用の実際のワークスペース ID で WorkspaceId を置き換えてください。
  • 中国 (北京):POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding
  • 中国 (香港):POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding。ご利用の実際のワークスペース ID で WorkspaceId を置き換えてください。

ご利用の実際のワークスペース ID で {WorkspaceId} を置き換えてください。

リクエストボディ

modelstring必須

使用するモデル。「モデル概要」の表で利用可能なモデルのリストをご参照ください。

inputstringまたはarray<string>必須

処理するテキスト。入力は、文字列、文字列の配列、またはファイルが可能です。 サポートされるテキスト長とバッチサイズは、モデルのバージョンによって異なります。

  • qwen3.7-text-embedding モデル:
    • 文字列入力:最大 128,000 トークン。
    • 文字列リストまたはファイル入力:最大 20 アイテム (行)、各アイテム (行) は最大 128,000 トークン。
  • text-embedding-v3 / v4 モデル:
    • 文字列入力:最大長 8,192 トークン。
    • 文字列リストまたはファイル入力:最大 10 アイテム (行)、各アイテム (行) は最大 8,192 トークン。

text_type string任意

HTTP 呼び出しを行う場合、text_typeは parameters オブジェクト内に配置します。

埋め込みに変換されたテキストは、取得、クラスタリング、分類などの後続タスクに適用できます。取得などの非対称タスクでは、より良い取得パフォーマンスを達成するために、クエリテキスト (query) とドキュメントテキスト (document) を区別することを推奨します。インデックス作成、クラスタリング、分類などの対称タスクでは、システムのデフォルト値である document を使用できます。

dimension integer 任意

HTTP 呼び出しを行う場合、dimensionは parameters オブジェクト内に配置します。

出力ベクトルの埋め込み次元を指定します。有効な値は 2560 (qwen3.7-text-embedding のみ)、2048 (text-embedding-v4 のみ)、1536 (text-embedding-v4 のみ)、1024、768、512、256、128、または 64 です。デフォルトは 1024 です。

output_type string 任意

HTTP 呼び出しを行う場合、output_typeは parameters オブジェクト内に配置します。

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

instruct string 任意

モデルがクエリの意図を理解するのをガイドするためのカスタム命令を提供します。英語の命令は通常、パフォーマンスを 1% から 5% 向上させるため、推奨されます。

入力文字列

Python

import dashscope
from http import HTTPStatus

# これはシンガポールリージョンの URL です。ご利用の実際のワークスペース ID で {WorkspaceId} を置き換えてください。URL はリージョンによって異なります。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

resp = dashscope.TextEmbedding.call(
    model="qwen3.7-text-embedding",
    input='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.',
    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 です。ご利用の実際のワークスペース ID で {WorkspaceId} を置き換えてください。URL はリージョンによって異なります。
        Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }
    public static void basicCall() throws ApiException, NoApiKeyException{
        TextEmbeddingParam param = TextEmbeddingParam
        .builder()
        .model("qwen3.7-text-embedding")
        .texts(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.")).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("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.")).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://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding に置き換える必要があります。以下のコード例では、シンガポールリージョンの URL を使用しています。ご利用の実際のワークスペース ID で {WorkspaceId} を置き換えてください。URL はリージョンによって異なります。

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "qwen3.7-text-embedding",
    "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"
    }
}'

入力文字列リスト

Python

import dashscope
from http import HTTPStatus

# これはシンガポールリージョンの URL です。ご利用の実際のワークスペース ID で {WorkspaceId} を置き換えてください。URL はリージョンによって異なります。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
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="qwen3.7-text-embedding",
        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 です。ご利用の実際のワークスペース ID で {WorkspaceId} を置き換えてください。URL はリージョンによって異なります。
        Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }
    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("qwen3.7-text-embedding")
                    .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://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding に置き換える必要があります。以下のコード例では、シンガポールリージョンの URL を使用しています。ご利用の実際のワークスペース ID で {WorkspaceId} を置き換えてください。URL はリージョンによって異なります。

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "qwen3.7-text-embedding",
    "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"
    }
}'

入力ファイル

Python

import dashscope
from http import HTTPStatus
from dashscope import TextEmbedding

# これはシンガポールリージョンの URL です。ご利用の実際のワークスペース ID で {WorkspaceId} を置き換えてください。URL はリージョンによって異なります。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# 'texts_to_embedding.txt' をご利用のファイル名またはパスに置き換えてください。
with open('texts_to_embedding.txt', 'r', encoding='utf-8') as f:
    resp = TextEmbedding.call(
        model="qwen3.7-text-embedding",
        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 です。ご利用の実際のワークスペース ID で {WorkspaceId} を置き換えてください。URL はリージョンによって異なります。
        Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }
    public static void main(String[] args) {
        // 'texts_to_embedding.txt' をご利用のファイルのパスに置き換えてください。
        try (BufferedReader reader = new BufferedReader(new FileReader("texts_to_embedding.txt"))) {
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }

            TextEmbeddingParam param = TextEmbeddingParam.builder()
                    .model("qwen3.7-text-embedding")
                    .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://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding に置き換える必要があります。以下のコード例では、シンガポールリージョンの URL を使用しています。ご利用の実際のワークスペース ID で {WorkspaceId} を置き換えてください。URL はリージョンによって異なります。

'texts_to_embedding.txt' をご利用のファイル名またはパスに置き換えてください。

FILE_CONTENT=$(cat texts_to_embedding.txt | jq -Rs .)
curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "qwen3.7-text-embedding",
    "input": {
        "texts": ['"$FILE_CONTENT"']
    },
    "parameters": {
        "dimension": 1024,
        "output_type": "dense"
    }
}'

レスポンスオブジェクト

status_code string

HTTP ステータスコード。値が 200 の場合は成功を示します。

request_id string

リクエストの一意の識別子。この ID を使用してリクエストのトレースとトラブルシューティングを行います。

code string

リクエストが失敗した場合に返されるエラーコード。成功したリクエストの場合、このフィールドは空です。

message string

リクエストが失敗した場合の詳細なエラーメッセージ。成功したリクエストの場合、このフィールドは空です。

outputobject

タスクの結果。

プロパティ

embeddingsarray

リクエストに対するモデルの出力。これはオブジェクトの配列で、各オブジェクトは入力テキストに対応します。

プロパティ

sparse_embedding array

対応する文字列の疎ベクトル表現。これは text-embedding-v3 および text-embedding-v4 にのみ適用されます。

プロパティ

index integer

ボキャブラリー内のトークンのインデックス。

value float

Token の重みまたは重要度スコアを示します。値が高いほど、現在のテキストコンテキストにおける Token の重要性または関連性が高くなります。

token string

トークンのテキスト。

embedding array

対応する文字列の密ベクトル表現。

text_index integer

入力配列内の対応するテキストのインデックス。

usageobject

プロパティ

total_tokens integer

モデルのトークナイザーによって計算された、入力のトークン数。

{   "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
    }
}
{
    "code":"InvalidApiKey",
    "message":"Invalid API-key provided.",
    "request_id":"xxxxxxxx"
}

エラーコード

モデルの呼び出しが失敗した場合は、「エラーメッセージ」をご参照ください。