Alibaba Cloud の Model Studio は、モデルを呼び出すための API を提供します。OpenAI 互換のインターフェイスまたは DashScope SDK を使用して接続できます。
このトピックでは、Qwen を例として、モデル API を呼び出すプロセスを説明します。このトピックでは、以下の方法を学習します:
API キーの取得
ローカル開発環境のセットアップ
Qwen API の呼び出し
アカウント設定
アカウントの作成:Alibaba Cloud アカウントをお持ちでない場合は、まず作成してください。
問題が発生した場合は、「Alibaba Cloud アカウントの登録」をご参照ください。
Model Studio の有効化: Alibaba Cloud アカウントを使用してModel Studio コンソールに移動します。利用規約を読み、同意すると、Model Studio は自動的に有効化されます。利用規約が表示されない場合、サービスはすでに有効化されています。
API キーの作成: [キー管理] ページに移動し、[API キーの作成] をクリックします。その後、[API キー] を使用してモデルを呼び出すことができます。
API キーを環境変数として設定
コード内でキーを公開することを避け、漏洩のリスクを低減するために、API キーを環境変数として設定します。
プログラミング言語の選択
使い慣れた言語またはツールを選択して、モデル API を呼び出します。
Python
ステップ 1: Python 環境の設定
Python バージョンの確認
仮想環境の設定 (任意)
OpenAI Python SDK または DashScope Python SDK のインストール
ステップ 2: モデル API の呼び出し
OpenAI Python SDK
Python と OpenAI Python SDK をインストールしている場合は、次の手順に従って API リクエストを送信します。
hello_qwen.pyという名前の新しいファイルを作成します。次のコードを
hello_qwen.pyにコピーしてファイルを保存します。import os from openai import OpenAI try: client = OpenAI( # シンガポール、米国 (バージニア)、中国 (北京) リージョンの API キーは相互に交換できません。API キーの取得: https://www.alibabacloud.com/help/model-studio/get-api-key # 環境変数が設定されていない場合は、お使いの Model Studio API キーを使用して、次の行を api_key="sk-xxx" に置き換えてください。 api_key=os.getenv("DASHSCOPE_API_KEY"), # 注: base_url はリージョンごとに異なります。以下の例では、シンガポールリージョンの base_url を使用しています。 # - シンガポール: https://dashscope-intl.aliyuncs.com/compatible-mode/v1 # - 米国 (バージニア): https://dashscope-us.aliyuncs.com/compatible-mode/v1 # - 中国 (北京): https://dashscope.aliyuncs.com/compatible-mode/v1 base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1", ) completion = client.chat.completions.create( model="qwen-plus", messages=[ {'role': 'system', 'content': 'あなたは役立つアシスタントです。'}, {'role': 'user', 'content': 'あなたは誰ですか?'} ] ) print(completion.choices[0].message.content) except Exception as e: print(f"エラーメッセージ: {e}") print("詳細については、ドキュメントをご参照ください: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code")コマンドラインから
python hello_qwen.pyまたはpython3 hello_qwen.pyを実行します。No such file or directoryと表示された場合は、ファイルの完全なパスを指定してください。コマンドを実行すると、次の出力が表示されます:
I am a large-scale language model developed by Alibaba Cloud. My name is Qwen.
DashScope Python SDK
Python と DashScope Python SDK をインストールしている場合は、次の手順に従って API リクエストを送信します。
hello_qwen.pyという名前の新しいファイルを作成します。次のコードを
hello_qwen.pyにコピーしてファイルを保存します。import os from dashscope import Generation import dashscope # 注: base_url はリージョンごとに異なります。 以下の例では、シンガポールリージョンの base_url を使用しています。 # - シンガポール: https://dashscope-intl.aliyuncs.com/api/v1 # - 米国 (バージニア): https://dashscope-us.aliyuncs.com/api/v1 # - 中国 (北京): https://dashscope.aliyuncs.com/api/v1 dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1' messages = [ {'role': 'system', 'content': 'You are a helpful assistant.'}, {'role': 'user', 'content': 'Who are you?'} ] response = Generation.call( # シンガポール、米国 (バージニア)、中国 (北京) リージョンの API キーに互換性はありません。 API キーの取得: https://www.alibabacloud.com/help/model-studio/get-api-key # 環境変数が設定されていない場合は、ご自身の Model Studio API キーを使用して、次の行を api_key = "sk-xxx" のように置き換えます。 api_key=os.getenv("DASHSCOPE_API_KEY"), model="qwen-plus", messages=messages, result_format="message" ) if response.status_code == 200: print(response.output.choices[0].message.content) else: print(f"HTTP status code: {response.status_code}") print(f"Error code: {response.code}") print(f"Error message: {response.message}") print("For more information, see the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code")コマンドラインから
python hello_qwen.pyまたはpython3 hello_qwen.pyを実行します。説明このコマンドは、Python ファイルが含まれているディレクトリから実行してください。どの場所からでも実行するには、ファイルの完全なパスを指定してください。
コマンドを実行すると、次の出力が表示されます:
I am a large-scale language model from Alibaba Cloud. My name is Qwen.
Node.js
ステップ 1: Node.js 環境の設定
Node.js のインストール状況の確認
モデル呼び出し SDK のインストール
ステップ 2: モデル API の呼び出し
新しい
hello_qwen.mjsファイルを作成します。次のコードをファイルにコピーします。
import OpenAI from "openai"; try { const openai = new OpenAI( { // シンガポール、米国 (バージニア)、中国 (北京) の各リージョンで API キーは異なります。 API キーの取得: https://www.alibabacloud.com/help/model-studio/get-api-key // 環境変数が設定されていない場合は、次の行をお使いの Model Studio API キーを使用して、apiKey: "sk-xxx" のように置き換えてください。 apiKey: process.env.DASHSCOPE_API_KEY, // 注: base_url はリージョンごとに異なります。 以下の例では、シンガポールリージョンの base_url を使用しています。 // - シンガポール: https://dashscope-intl.aliyuncs.com/compatible-mode/v1 // - 米国 (バージニア): https://dashscope-us.aliyuncs.com/compatible-mode/v1 // - 中国 (北京): https://dashscope.aliyuncs.com/compatible-mode/v1 baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1" } ); const completion = await openai.chat.completions.create({ model: "qwen-plus", messages: [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: "Who are you?" } ], }); console.log(completion.choices[0].message.content); } catch (error) { console.log(`エラーメッセージ: ${error}`); console.log("詳細については、ドキュメントをご参照ください: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code"); }コマンドラインから次のコマンドを実行して API リクエストを送信します:
node hello_qwen.mjs説明このコマンドは
hello_qwen.mjsが含まれているディレクトリから実行してください。どの場所からでも実行するには、ファイルの完全なパスを指定してください。SDK が
hello_qwen.mjsと同じディレクトリにインストールされていることを確認してください。異なるディレクトリにある場合、Cannot find package 'openai' imported from xxxというエラーが表示されます。
コマンドが正常に実行されると、次の出力が表示されます:
I am a language model from Alibaba Cloud. My name is Qwen.
Java
ステップ 1: Java 環境の設定
Java バージョンの確認
モデル呼び出し SDK のインストール
ステップ 2: モデル API の呼び出し
次のコードを実行して、モデル API を呼び出すことができます。
import java.util.Arrays;
import java.lang.System;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.protocol.Protocol;
public class Main {
public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
// 注:base_url はリージョンごとに異なります。 以下の例では、シンガポールリージョンの base_url を使用しています。
// - シンガポール: https://dashscope-intl.aliyuncs.com/api/v1
// - 米国 (バージニア): https://dashscope-us.aliyuncs.com/api/v1
// - 中国 (北京): https://dashscope.aliyuncs.com/api/v1
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
Message systemMsg = Message.builder()
.role(Role.SYSTEM.getValue())
.content("You are a helpful assistant.")
.build();
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("Who are you?")
.build();
GenerationParam param = GenerationParam.builder()
// シンガポール、米国 (バージニア) 、および中国 (北京) リージョンの API キーに互換性はありません。 API キーの取得: https://www.alibabacloud.com/help/model-studio/get-api-key
// 環境変数が設定されていない場合は、次の行をご自身の Model Studio API キーを使用して、.apiKey("sk-xxx") に置き換えます。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// モデルリスト: https://www.alibabacloud.com/help/model-studio/getting-started/models
.model("qwen-plus")
.messages(Arrays.asList(systemMsg, userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.build();
return gen.call(param);
}
public static void main(String[] args) {
try {
GenerationResult result = callWithMessage();
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("エラーメッセージ: "+e.getMessage());
System.out.println("詳細については、ドキュメントをご参照ください: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}コードを実行すると、対応する出力が表示されます:
I am a large-scale language model developed by Alibaba Cloud. My name is Qwen.curl
Model Studio プラットフォーム上のモデルは、OpenAI 互換の HTTP メソッドまたは DashScope HTTP メソッドを使用して呼び出すことができます。モデルのリストについては、「モデル」をご参照ください。
環境変数が設定されていない場合は、-H "Authorization: Bearer $DASHSCOPE_API_KEY" \ を -H "Authorization: Bearer sk-xxx" \ に置き換え、ご利用の Model Studio API キーを使用してください。
OpenAI 互換 HTTP
コード例の URL は「シンガポール」リージョン用です。「中国 (北京)」リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions に置き換える必要があります。
次のコマンドを実行して API リクエストを送信できます:
API リクエストを送信すると、次のレスポンスが返されます:
{
"choices": [
{
"message": {
"role": "assistant",
"content": "I am a large-scale language model from Alibaba Cloud. My name is Qwen."
},
"finish_reason": "stop",
"index": 0,
"logprobs": null
}
],
"object": "chat.completion",
"usage": {
"prompt_tokens": 22,
"completion_tokens": 16,
"total_tokens": 38
},
"created": 1728353155,
"system_fingerprint": null,
"model": "qwen-plus",
"id": "chatcmpl-39799876-eda8-9527-9e14-2214d641cf9a"
}DashScope HTTP
コード例の URL はシンガポールリージョン用です。
米国 (バージニア) リージョンのモデルを使用する場合は、URL を
https://dashscope-us.aliyuncs.com/api/v1/services/aigc/text-generation/generationに置き換える必要があります。中国 (北京) リージョンのモデルを使用する場合は、URL を
https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generationに置き換える必要があります。
次のコマンドを実行して API リクエストを送信できます:
API リクエストを送信すると、次のレスポンスが返されます:
{
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": "I am a large-scale language model from Alibaba Cloud. My name is Qwen."
}
}
]
},
"usage": {
"total_tokens": 38,
"output_tokens": 16,
"input_tokens": 22
},
"request_id": "87f776d7-3c82-9d39-b238-d1ad38c9b6a9"
}その他の言語
モデル API の呼び出し
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type RequestBody struct {
Model string `json:"model"`
Messages []Message `json:"messages"`
}
func main() {
// HTTP クライアントを作成
client := &http.Client{}
// リクエストボディを構築
requestBody := RequestBody{
// モデルリスト: https://www.alibabacloud.com/help/model-studio/getting-started/models
Model: "qwen-plus",
Messages: []Message{
{
Role: "system",
Content: "You are a helpful assistant.",
},
{
Role: "user",
Content: "Who are you?",
},
},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
log.Fatal(err)
}
// POST リクエストを作成。注意: base_url はリージョンごとに異なります。以下の例では、シンガポールリージョンの base_url を使用しています。
// - シンガポール: https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions
// - 米国 (バージニア): https://dashscope-us.aliyuncs.com/compatible-mode/v1/chat/completions
// - 中国 (北京): https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
req, err := http.NewRequest("POST", "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions", bytes.NewBuffer(jsonData))
if err != nil {
log.Fatal(err)
}
// リクエストヘッダーを設定
// シンガポール、米国 (バージニア)、中国 (北京) リージョンの API キーは相互に交換できません。API キーの取得: https://www.alibabacloud.com/help/model-studio/get-api-key
// 環境変数が設定されていない場合は、次の行を apiKey := "sk-xxx" に置き換え、ご利用の Model Studio API キーを使用します。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// リクエストを送信
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// レスポンスボディを読み取り
bodyText, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
// レスポンス内容を出力
fmt.Printf("%s\n", bodyText)
}
<?php
// 注意: base_url はリージョンごとに異なります。以下の例では、シンガポールリージョンの base_url を使用しています。
// - シンガポール: https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions
// - 米国 (バージニア): https://dashscope-us.aliyuncs.com/compatible-mode/v1/chat/completions
// - 中国 (北京): https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
$url = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
// シンガポール、米国 (バージニア)、中国 (北京) リージョンの API キーは相互に交換できません。API キーの取得: https://www.alibabacloud.com/help/model-studio/get-api-key
// 環境変数が設定されていない場合は、次の行を $apiKey = "sk-xxx"; に置き換え、ご利用の Model Studio API キーを使用します。
$apiKey = getenv('DASHSCOPE_API_KEY');
// リクエストヘッダーを設定
$headers = [
'Authorization: Bearer '.$apiKey,
'Content-Type: application/json'
];
// リクエストボディを設定
$data = [
"model" => "qwen-plus",
"messages" => [
[
"role" => "system",
"content" => "You are a helpful assistant."
],
[
"role" => "user",
"content" => "Who are you?"
]
]
];
// cURL セッションを初期化
$ch = curl_init();
// cURL オプションを設定
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// cURL セッションを実行
$response = curl_exec($ch);
// エラーをチェック
if (curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
}
// cURL リソースを閉じる
curl_close($ch);
// レスポンスを出力
echo $response;
?>using System.Net.Http.Headers;
using System.Text;
class Program
{
private static readonly HttpClient httpClient = new HttpClient();
static async Task Main(string[] args)
{
// シンガポール、米国 (バージニア)、中国 (北京) リージョンの API キーは相互に交換できません。API キーの取得: https://www.alibabacloud.com/help/model-studio/get-api-key
// 環境変数が設定されていない場合は、次の行を string? apiKey = "sk-xxx"; に置き換え、ご利用の Model Studio API キーを使用します。
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("API Key not set. Make sure the 'DASHSCOPE_API_KEY' environment variable is set.");
return;
}
// 注意: base_url はリージョンごとに異なります。以下の例では、シンガポールリージョンの base_url を使用しています。
// - シンガポール: https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions
// - 米国 (バージニア): https://dashscope-us.aliyuncs.com/compatible-mode/v1/chat/completions
// - 中国 (北京): https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
string url = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions";
// モデルリスト: https://www.alibabacloud.com/help/model-studio/getting-started/models
string jsonContent = @"{
""model"": ""qwen-plus"",
""messages"": [
{
""role"": ""system"",
""content"": ""You are a helpful assistant.""
},
{
""role"": ""user"",
""content"": ""Who are you?""
}
]
}";
// リクエストを送信してレスポンスを取得
string result = await SendPostRequestAsync(url, jsonContent, apiKey);
// 結果を出力
Console.WriteLine(result);
}
private static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
{
using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
{
// リクエストヘッダーを設定
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// リクエストを送信してレスポンスを取得
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// レスポンスを処理
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return $"Request failed: {response.StatusCode}";
}
}
}
}API リファレンス
よくある質問
モデル API を呼び出した後に「Model.AccessDenied」というエラーが報告された場合はどうすればよいですか?
A: このエラーは、サブワークスペースの API キーを使用しているために発生します。サブワークスペースは、デフォルトのワークスペース内のアプリケーションまたはモデルにアクセスできません。Qwen-Plus などのモデルを使用するには、ルートアカウントの管理者がサブワークスペースに権限を付与する必要があります。詳細については、「モデルの呼び出し権限を設定する」をご参照ください。
次のステップ
その他のモデルの表示 | サンプルコードでは qwen-plus モデルを使用します。 Model Studio は他の Qwen モデルもサポートしています。 サポートされているモデルとそれらに対応する API リファレンスのリストについては、「モデル」をご参照ください。 |
高度な使用方法の学習 | サンプルコードは基本的な Q&A のみをカバーしています。ストリーミング出力、構造化出力、関数呼び出しなど、Qwen API の高度な機能については、「テキスト生成モデルの概要」フォルダをご参照ください。 |
モデルをオンラインで試す | 「Qwen Chat」のようにダイアログボックス形式でモデルと対話するには、Playground (シンガポール、米国 (バージニア)、または中国 (北京)) にアクセスしてください。 |











