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

Alibaba Cloud Model Studio:サブワークスペースのモデルを呼び出す

最終更新日:Jul 10, 2025

このトピックでは、Qwen-Plus を例に、API を使用してサブワークスペース(デフォルト以外のワークスペース)でモデルを呼び出す方法について説明します。

Scenarios

  • モデル権限の制御: デフォルト ワークスペースのユーザーはすべてのモデルにアクセスできます(過剰な場合があります)。モデル アクセスを制御するには、ユーザーをサブワークスペースに追加し、呼び出し可能なモデルを指定します。

  • モデル コストの追跡: 複数のビジネスがデフォルト ワークスペースを共有している場合、モデル コストを追跡することは困難です。個別のサブワークスペースを作成することにより、各ワークスペースで個別の請求書を生成できるため、コストの割り当てが容易になります。

Before you go

  1. サブワークスペースを準備する: サブワークスペースの作成方法について学ぶ。既にサブワークスペースをお持ちの場合は、この手順をスキップしてください。すべてのワークスペースを表示する方法

    モデルスタジオ コンソールの上部に次のメッセージが表示されている場合は、モデルスタジオをアクティブ化する必要があります(無料クォータを取得します)。このメッセージが表示されていない場合は、サービスは既にアクティブになっています。

    image

  2. API キーを取得する: このサブワークスペースでAPI キーを作成する

  3. モデルの承認: ワークスペースの API キーを使用して、サブワークスペースにリスト内のモデルQwen-Plusなど)を呼び出す権限を付与する

Call the model

OpenAI

このセクションでは、OpenAI 互換メソッドで Qwen-Plus を呼び出します。モデルは事前に承認されています。サブワークスペースのモデルを呼び出す場合とデフォルト ワークスペースのモデルを呼び出す場合の唯一の違いは、そのサブワークスペースで作成された API キーを使用する必要があることです。

Public cloud

SDK の base_url: https://dashscope-intl.aliyuncs.com/compatible-mode/v1

HTTP エンドポイント: POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions

Before running the samples:

Python

import os
from openai import OpenAI

client = OpenAI(
    # If environment variables are not configured, replace the following line with: api_key="sk-xxx" using the API key of your sub-workspace
    api_key=os.getenv("DASHSCOPE_API_KEY"), 
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen-plus", # This example uses qwen-plus. You can change the model name as needed (model authorization is required). For supported models, see: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
    messages=[
        {'role': 'system', 'content': 'You are a helpful assistant.'},
        {'role': 'user', 'content': 'Who are you?'}],
    )
    
print(completion.model_dump_json())

Node.js

import OpenAI from "openai";

const openai = new OpenAI(
    {
        // If environment variables are not configured, replace the following line with: apiKey: "sk-xxx" using the API key of your sub-workspace
        apiKey: process.env.DASHSCOPE_API_KEY,
        baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
    }
);

async function main() {
    const completion = await openai.chat.completions.create({
        model: "qwen-plus",  // This example uses qwen-plus. You can change the model name as needed (model authorization is required). For supported models, see: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
        messages: [
            { role: "system", content: "You are a helpful assistant." },
            { role: "user", content: "Who are you?" }
        ],
    });
    console.log(JSON.stringify(completion))
}

main();

HTTP

curl

環境変数を設定していない場合は、$DASHSCOPE_API_KEY をサブワークスペースの API キー sk-xxx に置き換えます。

この例では qwen-plus を使用しています。承認されている他のモデルを使用できます。

curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen-plus",
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user", 
            "content": "Who are you?"
        }
    ]
}'

PHP

<?php
// リクエスト URL を設定します
$url = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
// 環境変数が設定されていない場合は、次の行をサブワークスペースの API キーを使用して $apiKey = "sk-xxx" に置き換えます
$apiKey = getenv('DASHSCOPE_API_KEY');
// リクエストヘッダーを設定します
$headers = [
    'Authorization: Bearer '.$apiKey,
    'Content-Type: application/json'
];
// リクエスト本文を設定します
$data = [
// この例では qwen-plus を使用しています。必要に応じてモデル名を変更できます(モデルの承認が必要です)。サポートされているモデルについては、https://www.alibabacloud.com/help/en/model-studio/getting-started/models を参照してください。
    "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;
?>

C#

using System.Net.Http.Headers;
using System.Text;

class Program
{
    private static readonly HttpClient httpClient = new HttpClient();

    static async Task Main(string[] args)
    {
        // 環境変数が設定されていない場合は、次の行をサブワークスペースの API キーを使用して string? apiKey = "sk-xxx" に置き換えます
        string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");

        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("API キーが設定されていません。環境変数 'DASHSCOPE_API_KEY' が設定されていることを確認してください。");
            return;
        }

        // リクエスト URL とコンテンツを設定します
        string url = "https://dashscope.aliyuncs-intl.com/compatible-mode/v1/chat/completions";
        // この例では qwen-plus を使用しています。必要に応じてモデル名を変更できます(モデルの承認が必要です)。サポートされているモデルについては、https://www.alibabacloud.com/help/en/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 $"リクエストが失敗しました: {response.StatusCode}";
            }
        }
    }
}

Go

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{
		// この例では qwen-plus を使用しています。必要に応じてモデル名を変更できます(モデルの承認が必要です)。サポートされているモデルについては、https://www.alibabacloud.com/help/en/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 リクエストを作成します
	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 キーを使用して apiKey := "sk-xxx" に置き換えます
	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)
}

Java

OpenAI は Java SDK を提供していません。代わりに、このトピックのDashScopeセクションを使用できます。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import com.google.gson.Gson;

public class Main {

    static class Message {
        String role;
        String content;

        public Message(String role, String content) {
            this.role = role;
            this.content = content;
        }
    }

    static class RequestBody {
        String model;
        Message[] messages;

        public RequestBody(String model, Message[] messages) {
            this.model = model;
            this.messages = messages;
        }
    }

    public static void main(String[] args) {
        try {
            // リクエスト本文を作成します
            RequestBody requestBody = new RequestBody(
                    // この例では qwen-plus を使用しています。必要に応じてモデル名を変更できます(モデルの承認が必要です)。サポートされているモデルについては、https://www.alibabacloud.com/help/en/model-studio/getting-started/models を参照してください。
                    "qwen-plus",
                    new Message[] {
                            new Message("system", "You are a helpful assistant."),
                            new Message("user", "Who are you?")
                    }
            );

            // リクエスト本文を JSON に変換します
            Gson gson = new Gson();
            String jsonInputString = gson.toJson(requestBody);

            // URL オブジェクトを作成します
            URL url = new URL("https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            // リクエストメソッドを POST に設定します
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Content-Type", "application/json; utf-8");
            httpURLConnection.setRequestProperty("Accept", "application/json");

            // 環境変数が設定されていない場合は、次の行をサブワークスペースの API キーを使用して String apiKey = "sk-xxx" に置き換えます
            String apiKey = System.getenv("DASHSCOPE_API_KEY");
            String auth = "Bearer " + apiKey;
            httpURLConnection.setRequestProperty("Authorization", auth);

            // 入力ストリームと出力ストリームを有効にします
            httpURLConnection.setDoOutput(true);

            // リクエスト本文を書き込みます
            try (OutputStream os = httpURLConnection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // レスポンスコードを取得します
            int responseCode = httpURLConnection.getResponseCode();
            System.out.println("レスポンスコード: " + responseCode);

            // レスポンス本文を読み取ります
            try (BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                System.out.println("レスポンス本文: " + response);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.exit(0);
        }
    }
}

DashScope

このセクションでは、DashScope メソッドで Qwen-Plus を呼び出します。モデルは事前に承認されています。サブワークスペースとデフォルトワークスペースでのモデル呼び出しの違いは、サブワークスペースで作成された API キーを使用する必要があることだけです。

Public cloud

  • HTTP endpoint:

    Qwen LM の場合:POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation

    Qwen VL の場合:POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

  • base_url for SDK:

    • Python コード:

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

    • Java コード:

      • Method 1:

        import com.alibaba.dashscope.protocol.Protocol;
        Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
      • Method 2:

        import com.alibaba.dashscope.utils.Constants;
        Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";

サンプルを実行する前に:

Python

import os
import dashscope
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 = dashscope.Generation.call(
    # 環境変数が構成されていない場合は、次の行をサブワークスペースの API キーを使用して api_key="sk-xxx" に置き換えます
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-plus", # この例では qwen-plus を使用しています。必要に応じてモデル名を変更できます(モデル承認が必要です)。対応しているモデルについては、次を参照してください:https://www.alibabacloud.com/help/en/model-studio/getting-started/models
    messages=messages,
    result_format='message'
    )
print(response)

Java

// 推奨 dashscope SDK バージョン >= 2.12.0
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.utils.JsonUtils;
import com.alibaba.dashscope.protocol.Protocol;

public class Main {
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        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 キーを使用して .apiKey("sk-xxx") に置き換えます。
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // この例では qwen-plus を使用しています。必要に応じてモデル名を変更できます(モデル承認が必要です)。対応しているモデルについては、次を参照してください:https://www.alibabacloud.com/help/en/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(JsonUtils.toJson(result));
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            // ロギングフレームワークを使用して例外を記録します
            System.err.println("An error occurred while calling the generation service: " + e.getMessage());
        }
        System.exit(0);
    }
}

HTTP

curl

環境変数を設定していない場合は、$DASHSCOPE_API_KEY をサブワークスペースの API キー sk-xxx に置き換えます。

この例では qwen-plus を使用しています。承認されている他のモデルを使用できます。

curl --location "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
    "model": "qwen-plus",
    "input":{
        "messages":[      
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "user",
                "content": "Who are you?"
            }
        ]
    },
    "parameters": {
        "result_format": "message"
    }
}'

PHP

<?php

$url = "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// 環境変数が構成されていない場合は、次の行を、サブワークスペースの API キーを使用して $apiKey = "sk-xxx" に置き換えます。
$apiKey = getenv('DASHSCOPE_API_KEY');

$data = [
// この例では qwen-plus を使用しています。必要に応じてモデル名を変更できます(モデル承認が必要です)。対応しているモデルについては、次を参照してください:https://www.alibabacloud.com/help/en/model-studio/getting-started/models
    "model" => "qwen-plus",
    "input" => [
        "messages" => [
            [
                "role" => "system",
                "content" => "You are a helpful assistant."
            ],
            [
                "role" => "user",
                "content" => "Who are you?"
            ]
        ]
    ],
    "parameters" => [
        "result_format" => "message"
    ]
];

$jsonData = json_encode($data);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $apiKey",
    "Content-Type: application/json"
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($httpCode == 200) {
    echo "Response: " . $response;
} else {
    echo "Error: " . $httpCode . " - " . $response;
}

curl_close($ch);
?>

Node.js

DashScope は Node.js 環境用の SDK を提供していません。 OpenAI Node.js SDK を使用するには、このトピックのOpenAIセクションを参照してください。

import fetch from 'node-fetch';

// 環境変数が構成されていない場合は、次の行をサブワークスペースの API キーを使用して apiKey = "sk-xxx" に置き換えます
const apiKey = process.env.DASHSCOPE_API_KEY;

const data = {
    // この例では qwen-plus を使用しています。必要に応じてモデル名を変更できます(モデル承認が必要です)。対応しているモデルについては、次を参照してください:https://www.alibabacloud.com/help/en/model-studio/getting-started/models
    model: "qwen-plus",
    input: {
        messages: [
            {
                role: "system",
                content: "You are a helpful assistant."
            },
            {
                role: "user",
                content: "Who are you?"
            }
        ]
    },
    parameters: {
        result_format: "message"
    }
};

fetch('https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
    method: 'POST',
    headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
    console.log(JSON.stringify(data));
})
.catch(error => {
    console.error('Error:', error);
});

C#

using System.Net.Http.Headers;
using System.Text;

class Program
{
    private static readonly HttpClient httpClient = new HttpClient();

    static async Task Main(string[] args)
    {
        // 環境変数が構成されていない場合は、次の行をサブワークスペースの API キーを使用して string? apiKey = "sk-xxx" に置き換えます
        string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");

        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("API Key is not set. Please ensure the environment variable 'DASHSCOPE_API_KEY' is set.");
            return;
        }

        // リクエスト URL とコンテンツを設定します
        string url = "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
        // この例では qwen-plus を使用しています。必要に応じてモデル名を変更できます(モデル承認が必要です)。対応しているモデルについては、次を参照してください:https://www.alibabacloud.com/help/en/model-studio/getting-started/models
        string jsonContent = @"{
            ""model"": ""qwen-plus"",
            ""input"": {
                ""messages"": [
                    {
                        ""role"": ""system"",
                        ""content"": ""You are a helpful assistant.""
                    },
                    {
                        ""role"": ""user"",
                        ""content"": ""Who are you?""
                    }
                ]
            },
            ""parameters"": {
                ""result_format"": ""message""
            }
        }";

        // リクエストを送信し、レスポンスを取得します
        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}";
            }
        }
    }
}

Java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import com.google.gson.Gson;

public class Main {

    static class Message {
        String role;
        String content;

        public Message(String role, String content) {
            this.role = role;
            this.content = content;
        }
    }

    static class Input {
        Message[] messages;

        public Input(Message[] messages) {
            this.messages = messages;
        }
    }

    static class Parameters {
        String result_format;

        public Parameters(String result_format) {
            this.result_format = result_format;
        }
    }

    static class RequestBody {
        String model;
        Input input;
        Parameters parameters;

        public RequestBody(String model, Input input, Parameters parameters) {
            this.model = model;
            this.input = input;
            this.parameters = parameters;
        }
    }

    public static void main(String[] args) {
        try {
            // リクエストボディを作成します
            RequestBody requestBody = new RequestBody(
                    // この例では qwen-plus を使用しています。必要に応じてモデル名を変更できます(モデル承認が必要です)。対応しているモデルについては、次を参照してください:https://www.alibabacloud.com/help/en/model-studio/getting-started/models
                    "qwen-plus",
                    new Input(new Message[] {
                            new Message("system", "You are a helpful assistant."),
                            new Message("user", "Who are you?")
                    }),
                    new Parameters("message")
            );

            // リクエストボディを JSON に変換します
            Gson gson = new Gson();
            String jsonInputString = gson.toJson(requestBody);

            // URL オブジェクトを作成します
            URL url = new URL("https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            // リクエストメソッドを POST に設定します
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Content-Type", "application/json; utf-8");
            httpURLConnection.setRequestProperty("Accept", "application/json");

            // 環境変数が構成されていない場合は、次の行をサブワークスペースの API キーを使用して String apiKey = "sk-xxx" に置き換えます
            String apiKey = System.getenv("DASHSCOPE_API_KEY");
            String auth = "Bearer " + apiKey;
            httpURLConnection.setRequestProperty("Authorization", auth);

            // 入力ストリームと出力ストリームを有効にします
            httpURLConnection.setDoOutput(true);

            // リクエストボディを書き込みます
            try (OutputStream os = httpURLConnection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // レスポンスボディを読み取ります
            try (BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                System.out.println(response);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.exit(0);
        }
    }
}

Error codes

HTTP status code

Code

Message

Description

400

InvalidParameter

Model not exist.

指定したモデル名は正しくありません。

401

InvalidApiKey

Invalid API-key provided.

Incorrect API key provided.

The API key you provided is incorrect.

invalid_api_key

403

Model.AccessDenied

Model access denied.

You are not authorized to call the model.

サブワークスペースの API キーを使用するには権限が必要です。詳細については、「事前準備:モデルの権限付与」をご参照ください。

404

ModelNotFound

Model can not be found.

The model xx does not exist or you do not have access to it.

指定したモデル名は正しくありません。

model_not_found

-

NoPermission

You are not authorized to do this operation. Action: sfm:CreateSession;Resource: acs:sfm::xxx:* (1-1).

Alibaba Cloud アカウントを使用して、RAM コンソールで RAM ユーザーに AliyunBailianDataFullAccess システムポリシー(AliyunBailianDataReadOnlyAccess ではなく)を付与します。詳細については、「RAM ユーザーにデータ権限を付与する」をご参照ください。

-

-

openai.OpenAIError: The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable.

You did not provide an API key. Set your API key as an environment variable or write the API key as plaintext in the code (not recommended).

-

-

AuthenticationError: No api key provided. You can set by dashscope.api_key = your_api_key in code, or you can set it via environment variable DASHSCOPE_API_KEY= your_api_key.

FAQ

  1. How to view all my workspaces?

    Model Studio コンソールの左下隅で、承認されたワークスペースを表示および切り替えることができます。

  1. How to check whether model authorization is required for the current sub-workspace?

    サブワークスペースに切り替える手順に従って モデル ページに移動します。目的のモデルの [Playground] が無効になっていて、次のメッセージが表示されている場合は、Alibaba Cloud アカウント所有者から モデルの承認をリクエストする必要があります。このようなメッセージが表示されていない場合は、このモデルをすでに使用できます。

    image

What to do next

More models

サンプルコードでは、Qwen-Plus を例として使用しています。 Model Studio は、他の Qwen モデルもサポートしています。 サポートされているモデルとその API リファレンスについては、「モデル」をご参照ください。

Advanced features

サンプルコードは、基本的な機能のみを示しています。Qwen API の特徴の詳細については、ストリームJSON モード関数呼び出し、およびテキスト生成の配下にあるその他のトピックをご参照ください。