テキスト生成モデルは、自然言語プロンプトから、チャットボット、コンテンツ作成、ドキュメント要約、コード生成といったアプリケーションで利用できるテキストを生成します。
入力は、1 つのキーワードからコンテキストを含む複雑な複数ステップのプロンプトまで多岐にわたります。一般的なユースケースには、次のようなものがあります:
コンテンツ作成:ニュース記事、製品説明、ショート動画のスクリプトを生成します。
カスタマーサービス:よくある質問に回答する 24 時間対応の自動化されたチャットボットを構築します。
テキスト翻訳:複数の言語間でテキストを翻訳します。
要約:長文の記事、レポート、メールを要約します。
法律文書の起草:契約テンプレートおよび法律意見書を起草します。
基本概念
テキスト生成モデルへの入力は、ロールとコンテントを含む 1 つ以上のメッセージオブジェクトで構成されるプロンプトです。
システムメッセージ:モデルのペルソナ、動作ガイドライン、またはタスク固有の指示を設定します。デフォルトは「You are a helpful assistant.」です。
ユーザーメッセージ:ユーザーからモデルへの質問、指示、または入力です。
アシスタントメッセージ:モデルの応答です。マルチターンの会話では、過去のアシスタントメッセージを渡すことで、コンテキストを維持します。
モデルを呼び出すには、これらのメッセージオブジェクトの配列を 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 キーを取得し、環境変数として設定します。SDK を使用する場合は、さらにOpenAI または DashScope SDK をインストールします。
OpenAI 互換チャット補完 API
Python
import os
from openai import OpenAI
try:
client = OpenAI(
# API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/ja/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.6-plus",
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/ja/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/ja/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.6-plus")
.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/ja/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/ja/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.6-plus",
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/ja/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.6-plus",
},
)
if err != nil {
fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
// 詳細については、ドキュメント「https://www.alibabacloud.com/help/ja/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.6-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);
// 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/ja/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/ja/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.6-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);
// エラーをチェックします。
// 詳細については、ドキュメント「https://www.alibabacloud.com/help/ja/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
ベース URL と API キーはリージョン固有です。エンドポイント URL については「OpenAI 互換チャット」、API キーの取得については「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.6-plus",
"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.6-plus",
"id": "chatcmpl-81951b98-28b8-9659-ab07-xxxxxx"
}OpenAI 互換レスポンス API
レスポンス API は、チャット補完 API の後継です。使用方法、コード例、移行ガイドについては、「OpenAI 互換レスポンス」をご参照ください。
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.6-plus",
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」セクションをご参照ください。
Hello! I'm an AI assistant with knowledge current as of 2026. Here's a brief overview of what I can do:
* Content Creation: Write emails, articles, stories, scripts, and more.
* Coding & Tech: Generate, debug, and explain code across various programming languages.
* Analysis & Summarization: Process documents, interpret data, and extract key insights.
* Problem Solving: Assist with math, logic, reasoning, and strategic planning.
* Learning & Translation: Explain complex topics simply or translate between multiple languages.
Feel free to ask me anything or give me a task to get started!Node.js
// Node.js v18+ が必要です。このコードは ES Module 環境で実行する必要があります。
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.6-plus",
input: "Briefly introduce what you can do."
});
// モデルのレスポンスを取得します
console.log(response);
} catch (error) {
console.error("エラーが発生しました:", error);
}
}
main();レスポンス
主要なレスポンスフィールド:
id:レスポンス ID。output:reasoningとmessageオブジェクトを含むリスト。reasoningは、思考が有効な場合にのみ表示されます (Qwen3.6 シリーズではデフォルトで有効)。usage:トークン使用量。
メッセージ内容のサンプル。完全なレスポンスについては、「curl」セクションをご参照ください。
Hello! I'm an AI assistant with knowledge current as of 2026. Here's a brief overview of what I can do:
* Content Creation: Write emails, articles, stories, scripts, and more.
* Coding & Tech: Generate, debug, and explain code across various programming languages.
* Analysis & Summarization: Process documents, interpret data, and extract key insights.
* Problem Solving: Assist with math, logic, reasoning, and strategic planning.
* Learning & Translation: Explain complex topics simply or translate between multiple languages.
Feel free to ask me anything or give me a task to get started!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.6-plus",
"input": "Briefly introduce what you can do.",
"enable_thinking": true
}'レスポンス
{
"created_at": 1772249518,
"id": "7ad48c6b-3cc4-904f-9284-5f419c6c5xxx",
"model": "qwen3.6-plus",
"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.6-plus.\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.7-max-2026-06-08 は、マルチモーダル API をサポートします。Qwen3.6 および Qwen3.5 シリーズは、マルチモーダル DashScope API が必要です。これらのモデルで以下の例を実行すると、url error が返されます。正しいマルチモーダル 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/en/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.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 ステータスコード: {response.status_code}")
print(f"エラーコード: {response.code}")
print(f"エラーメッセージ: {response.message}")
print("詳細については、「https://www.alibabacloud.com/help/en/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/en/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.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("エラーメッセージ: "+e.getMessage());
System.out.println("詳細については、「https://www.alibabacloud.com/help/en/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.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/en/model-studio/error-code」をご参照ください。
console.error('リクエストが失敗しました:', 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.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/en/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.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/en/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.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"),
# これは Singapore リージョンのエンドポイントです。{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": "この画像に写っている製品は何ですか?"},
],
}
]
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,
// これは Singapore リージョンのエンドポイントです。{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: "この画像に写っている製品は何ですか?" },
]
}]
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
ベース URL と API キーはリージョン固有です。エンドポイント URL については「OpenAI 互換チャット」、API キーの取得については「API キーの取得」をご参照ください。
# これは Singapore リージョンのエンドポイントです。{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": "この画像に写っている製品は何ですか?"
}
]
}
]
}'DashScope
Python
import os
from dashscope import MultiModalConversation
import dashscope
# これは Singapore リージョンのエンドポイントです。{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": "この画像に写っている製品は何ですか?"},
],
}
]
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 {
// これは Singapore リージョンのエンドポイントです。{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", "この画像に写っている製品は何ですか?"))).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 キーの取得」をご参照ください。
# これは Singapore リージョンのエンドポイントです。{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": "この画像に写っている製品は何ですか?"}
]
}
]
}
}'非同期呼び出し
非同期呼び出しは、高同時実行ワークロードのスループットを向上させます。
OpenAI 互換チャット補完 API
Python
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"),
# これは Singapore リージョンの URL です。{WorkspaceId} をワークスペース ID に置き換えてください。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)
# 非同期タスクを定義します。
async def task(question):
print(f"質問を送信中: {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"モデルの応答: {response.choices[0].message.content}")
# メインの非同期関数。
async def main():
questions = ["あなたは誰ですか?", "何ができますか?", "天気はどうですか?"]
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)
Java
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"))
// これは Singapore リージョンの URL です。{WorkspaceId} をワークスペース ID に置き換えてください。
.baseUrl("https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1")
.build();
// 質問のリストを定義します。
List<String> questions = Arrays.asList("あなたは誰ですか?", "何ができますか?", "天気はどうですか?");
// 非同期タスクのリストを作成します。
CompletableFuture<?>[] futures = questions.stream()
.map(question -> CompletableFuture.supplyAsync(() -> {
System.out.println("質問を送信中: " + 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("モデルの応答: " + content);
})
.exceptionally(e -> {
System.err.println("エラー: " + 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
# これは Singapore リージョンの URL です。{WorkspaceId} をワークスペース ID に置き換えてください。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# 非同期タスクを定義します。
async def task(question):
print(f"質問を送信中: {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"モデルの応答: {response.output.choices[0].message.content}")
# メインの非同期関数。
async def main():
questions = ["あなたは誰ですか?", "何ができますか?", "天気はどうですか?"]
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)
応答例
呼び出しは非同期であるため、応答の順序はこの例とは異なる場合があります。
質問を送信中: あなたは誰ですか?
質問を送信中: 何ができますか?
質問を送信中: 天気はどうですか?
モデルの応答: こんにちは! 私は Qwen です。Alibaba Group の Tongyi Lab によって開発された大規模言語モデルです。質問への回答やコンテンツの作成 (ストーリー、公式文書、メール、スクリプトなど) をお手伝いできます。また、論理的推論、プログラミング、意見の提供、ゲームなども行えます。ご質問やサポートが必要な場合は、お気軽にお尋ねください!
モデルの応答: こんにちは! 現在、リアルタイムの天気情報にアクセスすることはできません。都市または地域をお知らせいただければ、一般的な天気のアドバイスや情報を提供できるよう最善を尽くします。または、天気アプリでリアルタイムの天気を確認することもできます。
モデルの応答: 私にはたくさんのスキルがあります。例えば:
1. 質問への回答: 学術的な質問、一般知識、専門的なトピックなど、答えを見つけるお手伝いをします。
2. テキストの作成: ストーリー、公式文書、メール、スクリプトなど、さまざまな種類のテキストを作成できます。
3. 論理的推論: 数学の問題や謎解きなど、論理的推論の問題の解決をお手伝いします。
4. プログラミング: コードの作成、デバッグ、最適化など、プログラミングのサポートを提供できます。
5. 多言語サポート: 中国語、英語、フランス語、スペイン語など、複数の言語に対応しています。
6. 意見の表明: 意思決定に役立つ視点や提案を提供できます。
7. ゲームのプレイ: 謎解きやしりとりなど、テキストベースのゲームを一緒に楽しめます。
具体的なニーズや質問がある場合は、お気軽にお知らせください。最善を尽くしてお手伝いします!本番利用
高品質なコンテキストの構築
大量の未加工データをモデルに入力するとコストが増加し、コンテキストウィンドウの制限によりパフォーマンスが低下する可能性があります。コンテキストエンジニアリング (正確な知識を動的にロードする手法) により、生成品質と効率が向上します。主な手法は次のとおりです:
プロンプトエンジニアリング:モデルを目的の出力へ導くために、テキストプロンプトを設計して最適化します。詳細については、「テキスト生成のプロンプトガイド」をご参照ください。
検索拡張生成 (RAG):製品ドキュメントや技術マニュアルなどの外部ナレッジベースを利用して、モデルが質問に回答できるようにします。
ツール呼び出し:モデルに代わって、リアルタイム情報 (天気、交通) を取得したり、アクション (API 呼び出し、メール送信) を実行したりします。
メモリ:長期および短期メモリを提供し、マルチターン対話にわたってモデルがコンテキストを想起できるようにします。
応答の多様性の制御
temperature と top_p パラメーターは、生成されるテキストの多様性を制御します。値を高くすると多様性が増し、値を低くすると決定性が高まります。各パラメーターの影響を切り分けるには、一度に 1 つのパラメーターのみを調整してください。
温度:範囲:[0, 2)。主にランダム性を調整します。
top_p:範囲:[0, 1]。確率しきい値に基づいて応答をフィルタリングします。
次の例は、パラメーター設定が出力に与える影響を示します。入力プロンプト: "Write a three-sentence short story where the main characters are a cat and a sunbeam."
高い多様性 (例:
temperature=0.9):クリエイティブな文章作成、ブレインストーミング、またはマーケティングコピーに最適です。Sunlight slanted across the windowsill, and the orange cat crept toward the bright patch as its fur turned the color of melted honey. It reached out and tapped the light, then sank into it as if stepping into a warm pool, and the sunlight flowed up its back in a quiet tide. The afternoon grew heavy—curled in drifting gold, the cat heard time melt softly inside its purr.高い決定性 (例:
temperature=0.1):事実に基づく Q&A、コード生成、または法律文書に最適です。In the afternoon, an old cat curled on the windowsill and dozed while counting the spots of light. Sunlight hopped across its mottled back, like turning the pages of an old photo album. Dust rose and fell, as if time whispered: you were once young, and I was once fierce.
その他の機能
より複雑なシナリオでは、次の機能を利用できます:
関連 API
すべてのパラメーターについては、「OpenAI 互換 API リファレンス」および「DashScope API リファレンス」をご参照ください。
よくある質問
Q:送信したテキストのトークン数よりも、入力トークン数の方が多いのはなぜですか?
A:会話を処理する際、システムはチャットテンプレートを使用して未加工の入力テキストをラップし、ロール識別子やメッセージ境界などの制御マーカーを追加します。これらのシステムによって生成されたマーカーもトークンとしてカウントされます。
例えば、qwen3.7-max に {"role": "user", "content": "Hi"} を送信した場合、テキスト "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) と Qianwen API
A:Qianwen (Web) は Qianwen API をベースに、Web ページの解析、Web 検索、画像作成、PPT 生成などの機能を追加しています。これらはベース API には含まれませんが、、関数呼び出し を使用して同様の機能を構築できます。
Q:Word、Excel、PDF、または PPT ファイルの生成
A:いいえ。テキスト生成モデルが出力できるのはプレーンテキストのみです。出力を目的の形式に変換するには、お客様のコードまたはサードパーティライブラリを使用するか 。