テキスト生成モデルは、自然言語プロンプトからテキストを生成し、チャットボット、コンテンツ作成、ドキュメント要約、コード生成などのアプリケーションに利用されます。
入力は、単一のキーワードから、コンテキストを含む複雑な複数ステップのプロンプトまで多岐にわたります。一般的なユースケースは次のとおりです。
- コンテンツ作成:ニュース記事、製品説明、ショートビデオのスクリプトを生成します。
- カスタマーサービス:24 時間 365 日対応の自動チャットボットを構築し、よくある質問に回答します。
- テキスト翻訳:複数の言語間でテキストを翻訳します。
- 要約:長い記事、レポート、メールを要約します。
- 法的文書の起草:契約書のテンプレートや法的意見書を起草します。
基本概念
テキスト生成モデルへの入力はプロンプトであり、それぞれがロールとコンテンツを含む 1 つ以上のメッセージオブジェクトで構成されます。
- システムメッセージ:モデルのペルソナ、動作ガイドライン、またはタスク固有の指示を設定します。デフォルトは「あなたは役に立つアシスタントです。」です。
- ユーザーメッセージ:ユーザーの質問、指示、またはモデルへの入力です。
- アシスタントメッセージ:モデルの応答です。マルチターン対話では、コンテキストを維持するために過去のアシスタントメッセージを渡します。
モデルを呼び出すには、これらのメッセージオブジェクトの配列を messages という名前で構築します。一般的なリクエストは、動作ガイドラインを定義する system メッセージと、ユーザーの入力を含む user メッセージで構成されます。
systemメッセージは任意ですが、推奨されます。モデルのロールと動作上の制約を定義することで、より一貫性があり予測可能な出力が生成されます。
[
{"role": "system", "content": "You are a helpful assistant who provides precise, efficient, and insightful responses, ready to assist users with various tasks and questions."},
{"role": "user", "content": "Who are you?"}
]
応答には、assistant メッセージにモデルの返信が含まれます。
{
"role": "assistant",
"content": "Hello! I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you with tasks like answering questions, creating text, logical reasoning, and coding. I understand and generate multiple languages, and can handle multi-turn conversations and complex instructions. If there is anything you need help with, just let me know!"
}
クイックスタート
前提条件:API キーの取得とAPI キーを環境変数として設定。SDK を使用する場合は、OpenAI または DashScope SDK のインストールも必要です。サンプルベース URL の {WorkspaceId} は、ご利用のワークスペース ID です。取得方法については、「リージョンとアクセスドメイン」をご参照ください。
OpenAI 互換の Chat Completions API
Python
import os
from openai import OpenAI
try:
client = OpenAI(
# API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
# 環境変数を設定していない場合は、次の行を Alibaba Cloud Model Studio API キーに置き換えてください:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# アジアパシフィック SE 1 (シンガポール) リージョンのエンドポイントです。{WorkspaceId} をご利用のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3.8-max",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Who are you?"},
],
)
print(completion.choices[0].message.content)
# 完全な応答を表示するには、次の行のコメントを解除してください。
# print(completion.model_dump_json())
except Exception as e:
print(f"Error message: {e}")
print("詳細については、ドキュメントをご参照ください:https://www.alibabacloud.com/help/model-studio/error-code")
応答
I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!
Java
// OpenAI Java SDK v3.5.0 以降の使用を推奨します。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
public class Main {
public static void main(String[] args) {
try {
OpenAIClient client = OpenAIOkHttpClient.builder()
// API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
// 環境変数を設定していない場合は、次の行を Alibaba Cloud Model Studio API キーに置き換えてください:.apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// アジアパシフィック SE 1 (シンガポール) リージョンのエンドポイントです。{WorkspaceId} をご利用のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
.baseUrl("https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1")
.build();
// ChatCompletion パラメーターを作成します。
ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
.model("qwen3.8-max")
.addSystemMessage("You are a helpful assistant.")
.addUserMessage("Who are you?")
.build();
// リクエストを送信し、応答を受信します。
ChatCompletion chatCompletion = client.chat().completions().create(params);
String content = chatCompletion.choices().get(0).message().content().orElse("No valid content returned");
System.out.println(content);
} catch (Exception e) {
System.err.println("Error message: " + e.getMessage());
System.out.println("詳細については、ドキュメントをご参照ください:https://www.alibabacloud.com/help/model-studio/error-code");
}
}
}
応答
I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!
Node.js
// このコードには Node.js v18+ が必要で、ES モジュール環境で実行する必要があります。
import OpenAI from "openai";
const openai = new OpenAI(
{
// API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
// 環境変数を設定していない場合は、次の行を Alibaba Cloud Model Studio API キーに置き換えてください:apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
// アジアパシフィック SE 1 (シンガポール) リージョンのエンドポイントです。{WorkspaceId} をご利用のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
}
);
const completion = await openai.chat.completions.create({
model: "qwen3.8-max",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Who are you?" }
],
});
console.log(completion.choices[0].message.content);
// 完全な応答を表示するには、次の行のコメントを解除してください。
// console.log(JSON.stringify(completion, null, 4));
応答
I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!
Go
// OpenAI Go SDK v2.4.0 以降の使用を推奨します。
package main
import (
"context"
// 完全な応答を表示するには、以下のインポートと末尾の関連コードのコメントを解除してください。
// "encoding/json"
"fmt"
"os"
"github.com/openai/openai-go/v2"
"github.com/openai/openai-go/v2/option"
)
func main() {
// 環境変数を設定していない場合は、次の行を Alibaba Cloud Model Studio API キーに置き換えてください:apiKey := "sk-xxx"
apiKey := os.Getenv("DASHSCOPE_API_KEY")
client := openai.NewClient(
option.WithAPIKey(apiKey),
// API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
// アジアパシフィック SE 1 (シンガポール) リージョンのエンドポイントです。{WorkspaceId} をご利用のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
option.WithBaseURL("https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"),
)
chatCompletion, err := client.Chat.Completions.New(
context.TODO(), openai.ChatCompletionNewParams{
Messages: []openai.ChatCompletionMessageParamUnion{
openai.SystemMessage("You are a helpful assistant."),
openai.UserMessage("Who are you?"),
},
Model: "qwen3.8-max",
},
)
if err != nil {
fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
// 詳細については、ドキュメントをご参照ください:https://www.alibabacloud.com/help/model-studio/error-code
os.Exit(1)
}
if len(chatCompletion.Choices) > 0 {
fmt.Println(chatCompletion.Choices[0].Message.Content)
}
// 完全な応答を表示するには、次の行のコメントを解除してください。
// jsonData, _ := json.MarshalIndent(chatCompletion, "", " ")
// fmt.Println(string(jsonData))
}
応答
I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!
C# (HTTP)
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
class Program
{
private static readonly HttpClient httpClient = new HttpClient();
static async Task Main(string[] args)
{
// 環境変数を設定していない場合は、次の行を Alibaba Cloud Model Studio API キーに置き換えてください:string? apiKey = "sk-xxx";
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
// アジアパシフィック SE 1 (シンガポール) リージョンのエンドポイントです。{WorkspaceId} をご利用のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
string url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions";
string jsonContent = @"{
""model"": ""qwen3.8-max"",
""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);
// JSON を解析してコンテンツを抽出し、表示します。
using JsonDocument doc = JsonDocument.Parse(result);
JsonElement root = doc.RootElement;
if (root.TryGetProperty("choices", out JsonElement choices) &&
choices.GetArrayLength() > 0)
{
JsonElement firstChoice = choices[0];
if (firstChoice.TryGetProperty("message", out JsonElement message) &&
message.TryGetProperty("content", out JsonElement content))
{
Console.WriteLine(content.GetString());
}
}
}
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
{
// 詳細については、ドキュメントをご参照ください:https://www.alibabacloud.com/help/model-studio/error-code
return $"Request failed: {response.StatusCode}";
}
}
}
}
応答
I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!
PHP (HTTP)
<?php
// リクエスト URL を設定します。
// アジアパシフィック SE 1 (シンガポール) リージョンのエンドポイントです。{WorkspaceId} をご利用のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
$url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions';
// API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
// 環境変数を設定していない場合は、次の行を Alibaba Cloud Model Studio API キーに置き換えてください:$apiKey = "sk-xxx";
$apiKey = getenv('DASHSCOPE_API_KEY');
// リクエストヘッダーを設定します。
$headers = [
'Authorization: Bearer '.$apiKey,
'Content-Type: application/json'
];
// リクエストボディを設定します。
$data = [
"model" => "qwen3.8-max",
"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);
// エラーを確認します。
// 詳細については、ドキュメントをご参照ください:https://www.alibabacloud.com/help/model-studio/error-code
if (curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
}
// cURL リソースを閉じます。
curl_close($ch);
// 応答コンテンツを解析して出力します。
$dataObject = json_decode($response);
$content = $dataObject->choices[0]->message->content;
echo $content;
// 完全な応答を表示するには、次の行のコメントを解除してください。
//echo $response;
?>
応答
I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!
curl
「base_url」と API キーはリージョン固有です。詳細については、「OpenAI 互換 - チャット」でエンドポイント URL を、「API キーの取得」でキーの取得方法をご参照ください。
# ご利用のリージョンに合わせてエンドポイント URL を変更してください。
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.8-max",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Who are you?"
}
]
}'
応答
{
"choices": [
{
"message": {
"role": "assistant",
"content": "I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!"
},
"finish_reason": "stop",
"index": 0,
"logprobs": null
}
],
"object": "chat.completion",
"usage": {
"prompt_tokens": 26,
"completion_tokens": 66,
"total_tokens": 92
},
"created": 1726127645,
"system_fingerprint": null,
"model": "qwen3.8-max",
"id": "chatcmpl-81951b98-28b8-9659-ab07-xxxxxx"
}
OpenAI 互換の Responses API
Responses API は Chat Completions API の後継です。使用方法、コード例、移行ガイドについては、「OpenAI 互換の Responses」をご参照ください。
Python
import os
from openai import OpenAI
try:
client = OpenAI(
# API キーはリージョンによって異なります。API キーの取得先:https://www.alibabacloud.com/help/model-studio/get-api-key
# 環境変数を設定しない場合は、API キーを直接指定してください:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# ベース URL はリージョンによって異なります。ご利用のサービスリージョンに合わせて更新してください。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
response = client.responses.create(
model="qwen3.8-max",
input="Briefly introduce what you can do."
)
print(response)
except Exception as e:
print(f"An error occurred: {e}")
print("詳細については、エラーコードのドキュメントをご参照ください:https://www.alibabacloud.com/help/model-studio/error-code")
応答
主要な応答フィールド:
-
id:応答 ID。 -
output:reasoningとmessageオブジェクトを含むリスト。reasoningは、思考が有効な場合にのみ表示されます (Qwen3.6 シリーズではデフォルトで有効)。 -
usage:トークン使用量。
メッセージコンテンツのサンプル。完全な応答については、curl セクションをご参照ください。
こんにちは!私は 2026 年時点の知識を持つ AI アシスタントです。私ができることの概要は以下の通りです:
* **コンテンツ作成**:メール、記事、物語、スクリプトなどを執筆します。
* **コーディング & 技術**:さまざまなプログラミング言語でコードを生成、デバッグ、説明します。
* **分析 & 要約**:ドキュメントを処理し、データを解釈し、主要なインサイトを抽出します。
* **問題解決**:数学、論理、推論、戦略的計画を支援します。
* **学習 & 翻訳**:複雑なトピックを簡単に説明したり、複数の言語間で翻訳したりします。
何でもお気軽にご質問いただくか、タスクを依頼してください!
Node.js
// Node.js v18+ が必要です。このコードは ES モジュール環境で実行する必要があります。
import OpenAI from "openai";
const openai = new OpenAI({
// API キーはリージョンによって異なります。API キーの取得先:https://www.alibabacloud.com/help/model-studio/get-api-key
// 環境変数を設定しない場合は、API キーを直接指定してください:apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
// ベース URL はリージョンによって異なります。ご利用のサービスリージョンに合わせて更新してください。
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
});
async function main() {
try {
const response = await openai.responses.create({
model: "qwen3.8-max",
input: "Briefly introduce what you can do."
});
// モデルの応答を取得
console.log(response);
} catch (error) {
console.error("An error occurred:", error);
}
}
main();
応答
主要な応答フィールド:
-
id:応答 ID。 -
output:reasoningとmessageオブジェクトを含むリスト。reasoningは、思考が有効な場合にのみ表示されます (Qwen3.6 シリーズではデフォルトで有効)。 -
usage:トークン使用量。
メッセージコンテンツのサンプル。完全な応答については、curl セクションをご参照ください。
こんにちは!私は 2026 年時点の知識を持つ AI アシスタントです。私ができることの概要は以下の通りです:
* **コンテンツ作成**:メール、記事、物語、スクリプトなどを執筆します。
* **コーディング & 技術**:さまざまなプログラミング言語でコードを生成、デバッグ、説明します。
* **分析 & 要約**:ドキュメントを処理し、データを解釈し、主要なインサイトを抽出します。
* **問題解決**:数学、論理、推論、戦略的計画を支援します。
* **学習 & 翻訳**:複雑なトピックを簡単に説明したり、複数の言語間で翻訳したりします。
何でもお気軽にご質問いただくか、タスクを依頼してください!
curl
# エンドポイント URL はリージョンによって異なります。ご利用のサービスリージョンに合わせて更新してください。
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.8-max",
"input": "Briefly introduce what you can do.",
"enable_thinking": true
}'
応答
{
"created_at": 1772249518,
"id": "7ad48c6b-3cc4-904f-9284-5f419c6c5xxx",
"model": "qwen3.8-max",
"object": "response",
"output": [
{
"id": "msg_94805179-2801-45da-ac1c-a87e8ea20xxx",
"summary": [
{
"text": "The user is asking for a brief introduction of my capabilities. I will start by recalling the features listed in the system message, ensuring I cover the main points concisely.\n\nFirst, I should mention the enhanced language foundation and architectural efficiency. Next, the upgraded logical reasoning and mathematical capabilities. Visual analysis, including charts and formulas, is a key point. Autonomous agent planning and code generation are also important. Other features include human alignment optimization for better interaction, long-context handling up to 256K tokens, and multilingual support with OCR.\n\nSince the user asked for a \"brief\" overview, I need to be concise. I will group some points together and summarize each capability in a sentence or two, avoiding technical jargon where possible. I'll check the examples in the system message for a suitable structure.\n\nTo make it practical, I'll highlight how these features apply to real tasks, such as handling long documents, solving math problems, analyzing images, and writing code.\n\nI will structure the response as a list of key capabilities with short explanations, starting with a greeting and ending with an offer to help with specific tasks.\n\nMy introduction will identify me as the requested model, qwen3.7-max.\n\nI will not mention the knowledge cutoff unless it's relevant. Since the current date is 2026 and my knowledge is current as of 2026, this is not an issue.\n\nMy draft will be a concise, friendly, and inviting response that highlights each capability.\n",
"type": "summary_text"
}
],
"type": "reasoning"
},
{
"content": [
{
"annotations": [],
"text": "I'm **Qwen3.6-plus**, a large language model designed to assist with a wide range of tasks. Here's what I can do: \n\n- **Understand & Generate Text**: Handle complex instructions, creative writing, and multi-step tasks with improved accuracy. \n- **Solve Problems**: Tackle advanced math, logic puzzles, and scientific reasoning with step-by-step clarity. \n- **Analyze Visuals**: Interpret charts, diagrams, formulas, and even extract text from images (OCR). \n- **Plan & Execute**: Break down goals into actionable steps, run code, or interact with tools autonomously. \n- **Code & Debug**: Write, explain, or fix code in multiple programming languages. \n- **Long-Context Mastery**: Process documents, books, or videos up to **256K tokens** without losing key details. \n- **Multilingual Support**: Communicate fluently in **100+ languages**, including low-resource ones. \n\nNeed help with something specific? Just ask!",
"type": "output_text"
}
],
"id": "msg_35be06c6-ca4d-4f2b-9677-7897e488dxxx",
"role": "assistant",
"status": "completed",
"type": "message"
}
],
"parallel_tool_calls": false,
"status": "completed",
"tool_choice": "auto",
"tools": [],
"usage": {
"input_tokens": 54,
"input_tokens_details": {
"cached_tokens": 0
},
"output_tokens": 662,
"output_tokens_details": {
"reasoning_tokens": 447
},
"total_tokens": 716,
"x_details": [
{
"input_tokens": 54,
"output_tokens": 662,
"output_tokens_details": {
"reasoning_tokens": 447
},
"total_tokens": 716,
"x_billing_type": "response_api"
}
]
}
}
DashScope
重要qwen3.7-max、qwen3.7-max-2026-05-20、および qwen3.6-max-preview はテキスト API のみをサポートします。qwen3.8-max、qwen3.8-flash、および qwen3.7-max-2026-06-08 はマルチモーダル API をサポートします。Qwen3.6 および Qwen3.5 シリーズでは、マルチモーダル DashScope API が必要です。これらのモデルで以下の例を実行すると、URL エラーが返されます。正しいマルチモーダル API 呼び出しについては、「画像および動画データ処理」をご参照ください。
Python
import json
import os
from dashscope import Generation
import dashscope
# 次の URL はシンガポールリージョン用です。{WorkspaceId} をご利用のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.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"),
# qwen3.7-max、qwen3.7-max-2026-05-20、および qwen3.6-max-preview はテキスト API のみをサポートします。qwen3.8-max と qwen3.7-max-2026-06-08 はマルチモーダル API をサポートします。Qwen3.6 および Qwen3.5 シリーズでは、マルチモーダル API が必要です。モデルを直接置き換えるとエラーが発生します。
model="qwen-plus",
messages=messages,
result_format="message",
)
if response.status_code == 200:
print(response.output.choices[0].message.content)
# 完全な応答を表示するには、次の行のコメントを解除してください。
# print(json.dumps(response, default=lambda o: o.__dict__, indent=4))
else:
print(f"HTTP status code: {response.status_code}")
print(f"Error code: {response.code}")
print(f"Error message: {response.message}")
print("詳細については、以下をご参照ください:https://www.alibabacloud.com/help/model-studio/error-code")
応答
I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!
Java
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;
import com.alibaba.dashscope.utils.JsonUtils;
public class Main {
public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
// 次の URL はシンガポールリージョン用です。{WorkspaceId} をご利用のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.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"))
// qwen3.7-max、qwen3.7-max-2026-05-20、および qwen3.6-max-preview はテキスト API のみをサポートします。qwen3.8-max と qwen3.7-max-2026-06-08 はマルチモーダル API をサポートします。Qwen3.6 および Qwen3.5 シリーズでは、マルチモーダル API が必要です。モデルを直接置き換えるとエラーが発生します。
.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());
// 完全な応答を表示するには、次の行のコメントを解除してください。
// System.out.println(JsonUtils.toJson(result));
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("Error message: "+e.getMessage());
System.out.println("詳細については、以下をご参照ください:https://www.alibabacloud.com/help/model-studio/error-code");
}
}
}
応答
I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!
Node.js (HTTP)
// Node.js v18+ が必要です
// 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えてください:const apiKey = "sk-xxx";
const apiKey = process.env.DASHSCOPE_API_KEY;
const data = {
// qwen3.7-max、qwen3.7-max-2026-05-20、および qwen3.6-max-preview はテキスト API のみをサポートします。qwen3.8-max と qwen3.7-max-2026-06-08 はマルチモーダル API をサポートします。Qwen3.6 および Qwen3.5 シリーズでは、マルチモーダル API が必要です。モデルを直接置き換えるとエラーが発生します。
model: "qwen-plus",
input: {
messages: [
{
role: "system",
content: "You are a helpful assistant."
},
{
role: "user",
content: "Who are you?"
}
]
},
parameters: {
result_format: "message"
}
};
async function callApi() {
try {
// 次の URL はシンガポールリージョン用です。{WorkspaceId} をご利用のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
const response = await fetch('https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
const result = await response.json();
console.log(result.output.choices[0].message.content);
// 完全な応答を表示するには、次の行のコメントを解除してください。
// console.log(JSON.stringify(result));
} catch (error) {
// 詳細については、以下をご参照ください:https://www.alibabacloud.com/help/model-studio/error-code
console.error('Request failed:', error.message);
}
}
callApi();
応答
I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!
Go (HTTP)
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
func main() {
requestBody := map[string]interface{}{
// qwen3.7-max、qwen3.7-max-2026-05-20、および qwen3.6-max-preview はテキスト API のみをサポートします。qwen3.8-max と qwen3.7-max-2026-06-08 はマルチモーダル API をサポートします。Qwen3.6 および Qwen3.5 シリーズでは、マルチモーダル API が必要です。モデルを直接置き換えるとエラーが発生します。
"model": "qwen-plus",
"input": map[string]interface{}{
"messages": []map[string]string{
{
"role": "system",
"content": "You are a helpful assistant.",
},
{
"role": "user",
"content": "Who are you?",
},
},
},
"parameters": map[string]string{
"result_format": "message",
},
}
// JSON にシリアル化します。
jsonData, _ := json.Marshal(requestBody)
// HTTP クライアントとリクエストを作成します。
client := &http.Client{}
// 次の URL はシンガポールリージョン用です。{WorkspaceId} をご利用のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
req, _ := http.NewRequest("POST", "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation", bytes.NewBuffer(jsonData))
// リクエストヘッダーを設定します。
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, _ := io.ReadAll(resp.Body)
// JSON を解析し、コンテンツを表示します。
var result map[string]interface{}
json.Unmarshal(bodyText, &result)
content := result["output"].(map[string]interface{})["choices"].([]interface{})[0].(map[string]interface{})["message"].(map[string]interface{})["content"].(string)
fmt.Println(content)
// 完全な応答を表示するには、次の行のコメントを解除してください。
// fmt.Printf("%s\n", bodyText)
}
応答
I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!
C# (HTTP)
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 をご参照ください
// 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えてください:string? apiKey = "sk-xxx";
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
// リクエスト URL とコンテンツを設定します。
// 次の URL はシンガポールリージョン用です。{WorkspaceId} をご利用のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
string url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// qwen3.7-max、qwen3.7-max-2026-05-20、および qwen3.6-max-preview はテキスト API のみをサポートします。qwen3.8-max と qwen3.7-max-2026-06-08 はマルチモーダル API をサポートします。Qwen3.6 および Qwen3.5 シリーズでは、マルチモーダル API が必要です。モデルを直接置き換えるとエラーが発生します。
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);
var jsonResult = System.Text.Json.JsonDocument.Parse(result);
var content = jsonResult.RootElement.GetProperty("output").GetProperty("choices")[0].GetProperty("message").GetProperty("content").GetString();
Console.WriteLine(content);
// 完全な応答を表示するには、次の行のコメントを解除してください。
// 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}";
}
}
}
}
応答
{
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": "I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!"
}
}
]
},
"usage": {
"total_tokens": 92,
"output_tokens": 66,
"input_tokens": 26
},
"request_id": "09dceb20-ae2e-999b-85f9-xxxxxx"
}
PHP (HTTP)
<?php
// 次の URL はシンガポールリージョン用です。{WorkspaceId} をご利用のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
$url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
$apiKey = getenv('DASHSCOPE_API_KEY');
$data = [
// qwen3.7-max、qwen3.7-max-2026-05-20、および qwen3.6-max-preview はテキスト API のみをサポートします。qwen3.8-max と qwen3.7-max-2026-06-08 はマルチモーダル API をサポートします。Qwen3.6 および Qwen3.5 シリーズでは、マルチモーダル API が必要です。モデルを直接置き換えるとエラーが発生します。
"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_HTTPHEADER, [
"Authorization: Bearer $apiKey",
"Content-Type: application/json"
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode == 200) {
$jsonResult = json_decode($response, true);
$content = $jsonResult['output']['choices'][0]['message']['content'];
echo $content;
// 完全な応答を表示するには、次の行のコメントを解除してください。
// echo "Model response: " . $response;
} else {
echo "Request failed: " . $httpCode . " - " . $response;
}
curl_close($ch);
?>
応答
I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!
curl
ベース URL と API キーはリージョンによって異なります。詳細については、「DashScope」および「API キーの取得」をご参照ください。
# 次の URL はシンガポールリージョン用です。{WorkspaceId} をご利用のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
curl --location "https://{WorkspaceId}.ap-southeast-1.maas.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"
}
}'
応答
{
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": "I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, program, share opinions, play games, and more. If you have any questions or need help, feel free to ask!"
}
}
]
},
"usage": {
"total_tokens": 92,
"output_tokens": 66,
"input_tokens": 26
},
"request_id": "09dceb20-ae2e-999b-85f9-xxxxxx"
}
画像および動画データ処理
マルチモーダルモデルは、画像や動画などの非テキストデータを処理し、視覚的質問応答やイベント検出などのタスクを実行します。テキストのみのモデルとは、次の 2 つの点で異なります。
- ユーザーメッセージの構築:マルチモーダルユーザーメッセージには、テキストと、画像や音声などの非テキストデータが含まれます。
- DashScope SDK インターフェイス:DashScope Python SDK には
MultiModalConversationインターフェイスを使用し、DashScope Java SDK にはMultiModalConversationクラスを使用します。
画像および動画ファイルの制限については、「画像と動画の理解」をご参照ください。
OpenAI 互換のチャット補完
Python
from openai import OpenAI
import os
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"),
# これはシンガポールリージョンのエンドポイントです。{WorkspaceId} をご利用の WorkspaceId に置き換えてください。エンドポイントはリージョンによって異なります。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)
messages = [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"
},
},
{"type": "text", "text": "What products are shown in the image?"},
],
}
]
completion = client.chat.completions.create(
model="qwen3.6-plus",
messages=messages,
)
print(completion.choices[0].message.content)
Node.js
import OpenAI from "openai";
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,
// これはシンガポールリージョンのエンドポイントです。{WorkspaceId} をご利用の WorkspaceId に置き換えてください。エンドポイントはリージョンによって異なります。
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
}
);
let messages = [
{
role: "user",
content: [
{ type: "image_url", image_url: { "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png" } },
{ type: "text", text: "What products are shown in the image?" },
]
}]
async function main() {
let response = await openai.chat.completions.create({
model: "qwen3.6-plus",
messages: messages
});
console.log(response.choices[0].message.content);
}
main()
curl
「base_url」と API キーはリージョン固有です。詳細については、「OpenAI 互換 - チャット」でエンドポイント URL を、「API キーの取得」でキーの取得方法をご参照ください。
# これはシンガポールリージョンのエンドポイントです。{WorkspaceId} をご利用の WorkspaceId に置き換えてください。エンドポイントはリージョンによって異なります。
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3.6-plus",
"messages": [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"
}
},
{
"type": "text",
"text": "What products are shown in the image?"
}
]
}
]
}'
DashScope
Python
import os
from dashscope import MultiModalConversation
import dashscope
# これはシンガポールリージョンのエンドポイントです。{WorkspaceId} をご利用の WorkspaceId に置き換えてください。エンドポイントはリージョンによって異なります。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": [
{
"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"
},
{"text": "What products are shown in the image?"},
],
}
]
response = MultiModalConversation.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='qwen3.6-plus', # これを別のマルチモーダルモデルに置き換え、メッセージを適宜変更できます。
messages=messages
)
print(response.output.choices[0].message.content[0]['text'])
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
// これはシンガポールリージョンのエンドポイントです。{WorkspaceId} をご利用の WorkspaceId に置き換えてください。エンドポイントはリージョンによって異なります。
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
private static final String modelName = "qwen3.6-plus"; // これを別のマルチモーダルモデルに置き換え、メッセージを適宜変更できます。
public static void MultiRoundConversationCall() throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(Collections.singletonMap("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"),
Collections.singletonMap("text", "What products are shown in the image?"))).build();
List<MultiModalMessage> messages = new ArrayList<>();
messages.add(userMessage);
MultiModalConversationParam param = MultiModalConversationParam.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"))
.model(modelName)
.messages(messages)
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
}
public static void main(String[] args) {
try {
MultiRoundConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
curl
ベース URL と API キーはリージョンによって異なります。詳細については、「DashScope」および「API キーの取得」をご参照ください。
# これはシンガポールリージョンのエンドポイントです。{WorkspaceId} をご利用の WorkspaceId に置き換えてください。エンドポイントはリージョンによって異なります。
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3.6-plus",
"input":{
"messages":[
{
"role": "user",
"content": [
{"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"},
{"text": "What products are shown in the image?"}
]
}
]
}
}'
非同期呼び出し
非同期呼び出しは、高い同時実行性が求められるワークロードのスループットを向上させます。
OpenAI 互換の Chat Completions API
import os
import asyncio
from openai import AsyncOpenAI
import platform
# 非同期クライアントインスタンスを作成します。
client = AsyncOpenAI(
# 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"),
# これはシンガポールリージョンの URL です。{WorkspaceId} をご利用のワークスペース ID に置き換えてください。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)
# 非同期タスクを定義します。
async def task(question):
print(f"Sending question: {question}")
response = await client.chat.completions.create(
messages=[
{"role": "user", "content": question}
],
model="qwen-plus", # モデルのリストについては、https://www.alibabacloud.com/help/model-studio/getting-started/models をご参照ください
)
print(f"Model response: {response.choices[0].message.content}")
# メインの非同期関数。
async def main():
questions = ["Who are you?", "What can you do?", "What's the weather like?"]
tasks = [task(q) for q in questions]
await asyncio.gather(*tasks)
if __name__ == '__main__':
# イベントループポリシーを設定します。
if platform.system() == 'Windows':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# メインのコルーチンを実行します。
asyncio.run(main(), debug=False)
import com.openai.client.OpenAIClientAsync;
import com.openai.client.okhttp.OpenAIOkHttpClientAsync;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
// DashScope 互換エンドポイントに接続するための OpenAI クライアントを作成します。
OpenAIClientAsync client = OpenAIOkHttpClientAsync.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"))
// これはシンガポールリージョンの URL です。{WorkspaceId} をご利用のワークスペース ID に置き換えてください。
.baseUrl("https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1")
.build();
// 質問のリストを定義します。
List<String> questions = Arrays.asList("Who are you?", "What can you do?", "What's the weather like?");
// 非同期タスクのリストを作成します。
CompletableFuture<?>[] futures = questions.stream()
.map(question -> CompletableFuture.supplyAsync(() -> {
System.out.println("Sending question: " + question);
// ChatCompletion パラメーターを作成します。
ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
.model("qwen-plus") // モデルを指定します。
.addSystemMessage("You are a helpful assistant.")
.addUserMessage(question)
.build();
// 非同期リクエストを送信し、応答を処理します。
return client.chat().completions().create(params)
.thenAccept(chatCompletion -> {
String content = chatCompletion.choices().get(0).message().content().orElse("No content in response");
System.out.println("Model response: " + content);
})
.exceptionally(e -> {
System.err.println("Error: " + e.getMessage());
System.out.println("ドキュメントをご参照ください:https://www.alibabacloud.com/help/model-studio/error-code");
return null;
});
}).thenCompose(future -> future))
.toArray(CompletableFuture[]::new);
// すべての非同期操作が完了するのを待ちます。
CompletableFuture.allOf(futures).join();
}
}
DashScope
DashScope SDK を使用した非同期テキスト生成は、Python でのみサポートされています。
# これには DashScope Python SDK v1.19.0 以降が必要です。
import asyncio
import platform
from dashscope.aigc.generation import AioGeneration
import os
import dashscope
# これはシンガポールリージョンの URL です。{WorkspaceId} をご利用のワークスペース ID に置き換えてください。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# 非同期タスクを定義します。
async def task(question):
print(f"Sending question: {question}")
response = await AioGeneration.call(
# 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えてください:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen-plus", # モデルのリストについては、https://www.alibabacloud.com/help/model-studio/models をご参照ください
messages=[{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": question}],
result_format="message",
)
print(f"Model response: {response.output.choices[0].message.content}")
# メインの非同期関数。
async def main():
questions = ["Who are you?", "What can you do?", "What's the weather like?"]
tasks = [task(q) for q in questions]
await asyncio.gather(*tasks)
if __name__ == '__main__':
# イベントループポリシーを設定します。
if platform.system() == 'Windows':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# メインのコルーチンを実行します。
asyncio.run(main(), debug=False)
呼び出しは非同期であるため、応答の順序はこの例と異なる場合があります。
Sending question: Who are you?
Sending question: What can you do?
Sending question: What's the weather like?
Model response: Hello! I'm Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can help you answer questions and create content, such as writing stories, official documents, emails, and scripts. I can also do logical reasoning, programming, share opinions, play games, and more. If you have any questions or need help, feel free to ask!
Model response: Hello! I am currently unable to access real-time weather information. You can tell me your city or region, and I will do my best to provide you with general weather advice or information. Alternatively, you can use a weather app to check the real-time weather conditions.
Model response: I have many skills, for example:
1. Answering questions: Whether it's academic questions, general knowledge, or professional topics, I can try to help you find answers.
2. Creating text: I can write various types of text, such as stories, official documents, emails, and scripts.
3. Logical reasoning: I can help you solve logical reasoning problems, such as math problems and riddles.
4. Programming: I can provide programming assistance, including code writing, debugging, and optimization.
5. Multilingual support: I support multiple languages, including but not limited to Chinese, English, French, and Spanish.
6. Expressing opinions: I can offer you some perspectives and suggestions to help you make decisions.
7. Playing games: We can play text-based games together, such as riddles or idiom solitaire.
If you have any specific needs or questions, feel free to let me know, and I will do my best to help you!
本番運用
高品質なコンテキストの構築
大量の生データをモデルに供給すると、コストが増加し、コンテキストウィンドウの制限によりパフォーマンスが低下する可能性があります。コンテキストエンジニアリング (正確な知識を動的に読み込むこと) は、生成の品質と効率を向上させます。主要な手法は次のとおりです。
- プロンプトエンジニアリング:テキストプロンプトを設計・最適化し、モデルを目的の出力に導きます。詳細については、「テキスト生成のためのプロンプトガイド」ページをご参照ください。
- RAG (Retrieval-Augmented Generation):製品ドキュメントや技術マニュアルなどの外部ナレッジベースからモデルが質問に回答できるようにします。
- ツール呼び出し:リアルタイム情報 (天気、交通状況) を取得したり、モデルに代わってアクション (API 呼び出し、メール送信) を実行したりします。
- メモリ:長期および短期メモリを提供し、モデルがマルチターン対話全体でコンテキストを記憶できるようにします。
応答の多様性の制御
temperature と top_p パラメーターは、生成されるテキストの多様性を制御します。値が高いほど多様性が増し、低いほど決定性が増します。各パラメーターの効果を分離するには、一度に 1 つだけを調整してください。
- temperature:範囲:[0, 2)。主にランダム性を調整します。
- top_p:範囲:[0, 1]。確率のしきい値に基づいて応答をフィルタリングします。
以下の例は、パラメーター設定が出力にどのように影響するかを示しています。入力プロンプト:「主人公が猫と太陽の光である 3 文の短い物語を書いてください。」
- 高い多様性 (例:
temperature=0.9):創造的な執筆、ブレインストーミング、またはマーケティングコピーに最適です。
窓辺に太陽の光が差し込み、オレンジ色の猫がその明るい斑点に忍び寄ると、その毛皮は溶けた蜂蜜の色に変わった。
猫は光に手を伸ばして軽くたたくと、まるで暖かいプールに足を踏み入れるかのようにその中に沈み込み、太陽の光は静かな潮のようにその背中を流れ上った。
午後は重くなり、漂う金色の中に丸まって、猫はゴロゴロという喉の音の中で時間が静かに溶けていくのを聞いた。
- 高い決定性 (例:
temperature=0.1):事実に基づく質疑応答、コード生成、または法的文書に最適です。
午後、年老いた猫が窓辺で丸くなり、光の斑点を数えながらうたた寝をしていた。
太陽の光がそのまだら模様の背中を飛び跳ね、まるで古い写真アルバムのページをめくるようだった。
埃が舞い上がり、また落ちていく。まるで時間が「君もかつては若かったし、私もかつては猛々しかった」と囁いているかのようだった。
仕組み
temperature:
- temperature が高いと、トークンの確率分布が平坦化され、確率の低いトークンが出現しやすくなり、出力のランダム性が増します。
- temperature が低いと、分布がシャープになり、確率の高いトークンがさらに出やすくなり、出力のランダム性が減少します。
top_p:
top_p (ニュークリアス) サンプリングは、累積確率が top_p のしきい値以上になる最小のトークンセットから選択します。トークンは確率順にソートされ、しきい値に達するまで累積されます。その後、この縮小されたセットから次のトークンがランダムにサンプリングされます。
- top_p が高いと、トークン選択のプールが広がり、より多様なテキストが生成されます。
- top_p が低いと、プールが狭まり、より焦点を絞った決定論的なテキストが生成されます。
一般的なシナリオのパラメーター設定例
# 一般的なシナリオで推奨されるパラメーター設定
SCENARIO_CONFIGS = {
# 創造的な執筆
"creative_writing": {
"temperature": 0.9,
"top_p": 0.95
},
# コード生成
"code_generation": {
"temperature": 0.2,
"top_p": 0.8
},
# 事実に基づく Q&A
"factual_qa": {
"temperature": 0.1,
"top_p": 0.7
},
# 翻訳
"translation": {
"temperature": 0.3,
"top_p": 0.8
}
}
# OpenAI の例
# completion = client.chat.completions.create(
# model="qwen-plus",
# messages=[{"role": "user", "content": "Write a poem about the moon"}],
# **SCENARIO_CONFIGS["creative_writing"]
# )
# DashScope の例
# response = Generation.call(
# # 環境変数を設定していない場合は、次の行を Alibaba Cloud Model Studio API キーに置き換えてください:api_key = "sk-xxx",
# api_key=os.getenv("DASHSCOPE_API_KEY"),
# model="qwen-plus",
# messages=[{"role": "user", "content": "Write a Python function that determines whether the input n is a prime number. Output code only."}],
# result_format="message",
# **SCENARIO_CONFIGS["code_generation"]
# )
その他の機能
より複雑なシナリオでは、以下の機能が利用可能です。
- マルチターン対話:フォローアップの質問や情報収集など、継続的な対話に使用します。
- ストリーミング出力:トークンが生成されると同時に逐次的に返すことで、チャットボットやリアルタイムのコード生成でのタイムアウトを防ぎます。
- ディープシンキング:複雑な推論や戦略分析のために、より高品質で構造化された回答を生成します。
- 構造化出力:プログラムでの使用やデータ解析のために、応答を一貫した JSON 形式に制約します。
- プレフィックス補完:既存のテキストから生成を継続し、コード補完や長文執筆に役立ちます。
API リファレンス
すべてのパラメーターについては、「OpenAI 互換 API リファレンス」および「DashScope API リファレンス」をご参照ください。
よくある質問
Q:なぜ入力トークン数が送信したテキストのトークン数より多いのですか?
A:会話を処理する際、システムはチャットテンプレートを使用して生の入力テキストをラップし、ロール識別子やメッセージ境界などの制御マーカーを追加します。これらのシステムが生成したマーカーもトークンとしてカウントされます。
例えば、メッセージ {"role": "user", "content": "Hi"} を qwen3.8-max に送信すると、テキスト「Hi」はトークン化後、1 トークンにしか対応しません。しかし、システム処理中、実際の完全な入力テキストは次のようにフォーマットされます:<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n<think>。トークン化後、この完全なテキストにより、総入力トークン数は 11 に増加します。
Q:なぜ Qianwen API は Web ページのリンクを分析できないのですか?
A:Qianwen API は Web ページのコンテンツに直接アクセスできません。代わりに、関数呼び出し、または Python の Beautiful Soup のような Web スクレイピングツールを使用してコンテンツを抽出し、モデルに渡してください。
Q:応答の違い:Qianwen (Web)vs. Qianwen API
A:Qianwen (Web) は、Qianwen API の上に、Web ページ解析、Web 検索、画像生成、PPT 生成などの機能を追加しています。これらはベース API には含まれていませんが、、関数呼び出し を使用して同様の機能を構築できます。
Q:Word、Excel、PDF、または PPT ファイルの生成
A:いいえ。テキスト生成モデルはプレーンテキストのみを出力します。独自のコードやサードパーティのライブラリを使用して、出力を目的の形式に変換してください。