テキスト生成モデルは、プロンプトに基づいて明確かつ一貫性のあるテキストを生成します。
テキスト生成モデルは、単純なキーワードや簡単な説明から、複雑な命令やコンテキスト情報を含む入力まで幅広く受け付けます。これらのモデルは膨大なデータセットでトレーニングされ、言語パターンを学習しており、以下のようなアプリケーションをサポートします。
コンテンツ作成:ニュース記事、商品説明、ショート動画のスクリプトなどを生成します。
カスタマーサポート:チャットボットを駆動し、24 時間 365 日のサポートや一般的な質問への回答を提供します。
テキスト翻訳:高速かつ正確な言語間変換を実行します。
要約生成:長文のドキュメント、レポート、メールから重要な情報を抽出します。
法務文書作成:契約テンプレートや法的意見の基礎となるフレームワークを作成します。
モデル選択
サービスリージョン
Alibaba Cloud Model Studio は、シンガポール、米国 (バージニア)、中国 (北京)、中国 (香港)、および ドイツ (フランクフルト) リージョンでモデルサービスを提供しています。各リージョンには個別の API キーが必要です。近隣のリージョンを利用すると、ネットワーク遅延を低減できます。詳細については、「リージョンとデプロイモードの選択」をご参照ください。
汎用モデル
Qwen テキスト生成モデルは OpenAI API フォーマット と互換性があり、インテリジェントカスタマーサポート、コンテンツ作成、テキスト校正、要約など、さまざまなシナリオに適しています。
Qwen-Plus:パフォーマンス、速度、コストのバランスが取れており、ほとんどのシナリオでの推奨選択肢です。
最新の Qwen-3.5-Plus シリーズは、言語理解、論理的推論、コード生成、エージェントタスク、画像理解、動画理解、グラフィカルユーザーインターフェイス(GUI)操作など、さまざまなタスクで優れた性能を発揮します。このモデルは、組み込みの ツール呼び出し をサポートしており、テキスト処理能力は Qwen-Max と同等です。このモデルを強く推奨します。
Qwen-Max:Qwen-3 シリーズで最高のパフォーマンスを発揮するモデルであり、複雑で多段階のタスクに最適です。
Qwen-Flash:Qwen シリーズで最も高速かつコスト効率に優れたモデルであり、シンプルなタスクに最適です。
Qwen-3.5 オープンソースシリーズ:
qwen3.5-397b-a17b、qwen3.5-122b-a10b、qwen3.5-27b、およびqwen3.5-35b-a3b。
特定のシナリオ向けモデル
特定のビジネスニーズに対応するため、Alibaba Cloud Model Studio は コード、ロングコンテキスト、翻訳、データマイニング、意図認識、ロールプレイ、および ディープサーチ などのドメイン向けに特化・最適化されたモデルを提供しています。
マルチモーダルモデル
Qwen-Plus(テキスト+画像/動画 → テキスト):Qwen-3.5-Plus シリーズは視覚情報とテキストの両方を入力として受け付け、言語理解、論理的推論、コード生成、エージェントタスク、画像理解、動画理解、グラフィカルユーザーインターフェイス(GUI)操作などのタスクで卓越したパフォーマンスを発揮します。その視覚的推論能力は、Qwen-VL シリーズから大幅に進化しています。
Qwen-Omni(オムニモーダル → テキスト+音声):動画、音声、画像、テキストなどさまざまなデータ入力を受け付け、テキストと音声の両方を出力して、複雑なクロスモーダリティタスクを実行します。
音声認識モデル(音声 → テキスト):これらのモデルは、音声を認識してテキストに変換します。対応言語には、中国語(広東語などのさまざまな方言を含む)、英語、日本語、韓国語が含まれます。
サードパーティ製モデル
Alibaba Cloud Model Studio は、DeepSeek や Kimi など、著名なサードパーティ製大規模言語モデル(LLM)を提供しています。モデルの完全なリストについては、「テキスト生成 - サードパーティ製モデル」をご参照ください。
基本概念
テキスト生成モデルへの入力はプロンプトであり、1 つ以上の Message オブジェクトで構成されます。各 Message は Role と Content で構成されます。
システムメッセージ:モデルのロールと従うべき命令を定義します。指定しない場合のデフォルトは「You are a helpful assistant」です。
ユーザーメッセージ:ユーザーが提供する質問または命令です。
アシスタントメッセージ:モデルの返信です。
モデルを呼び出すには、これらの Message オブジェクトで構成される messages 配列を提供します。典型的なリクエストは、行動規範を定義する system メッセージと、命令を含む user メッセージで構成されます。
system メッセージは省略可能ですが、より安定的で一貫性のある出力を得るために、モデルのロールと行動規範を定義することを推奨します。[
{"role": "system", "content": "You are a helpful assistant who provides accurate, efficient, and insightful responses. You are ready to help users with any task or question."},
{"role": "user", "content": "Who are you?"}
]レスポンスオブジェクトには、モデルの返信を含む assistant メッセージが含まれます。
{
"role": "assistant",
"content": "Hello! I am Qwen, a large-scale language model developed by the Tongyi Lab of Alibaba Group. I can help you answer questions, create text, perform logical reasoning, and write code. I can understand and generate multiple languages, and I support multi-turn conversation and complex task processing. If you need any help, just let me know!"
}クイックスタート
前提条件:API キーの取得、API キーを環境変数として設定、および OpenAI または DashScope SDK のインストール。
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://dashscope-intl.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1",
)
response = client.responses.create(
model="qwen3.5-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:レスポンスの一意識別子です。output:reasoning(モデルの思考プロセス)とmessage(モデルのレスポンス)を含む出力のリストです。reasoningフィールドは、ディープシンキング が有効になっている場合にのみ返されます。たとえば、Qwen-3.5 シリーズではデフォルトで有効になっています。usage:トークン使用量の統計情報です。
以下はレスポンス内容のサンプルです。完全なレスポンスについては、curl セクションをご参照ください。
Hello! I'm an AI assistant with knowledge current up to 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://dashscope-intl.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1"
});
async function main() {
try {
const response = await openai.responses.create({
model: "qwen3.5-plus",
input: "Briefly introduce what you can do?"
});
// モデルのレスポンスを取得します。
console.log(response);
} catch (error) {
console.error("An error occurred:", error);
}
}
main();レスポンス
レスポンスオブジェクトには以下のフィールドが含まれます。
id:レスポンスの一意識別子です。output:reasoning(モデルの思考プロセス)とmessage(モデルのレスポンス)を含む出力のリストです。reasoningフィールドは、ディープシンキング が有効になっている場合にのみ返されます。たとえば、Qwen-3.5 シリーズではデフォルトで有効になっています。usage:トークン使用量の統計情報です。
以下はレスポンス内容のサンプルです。完全なレスポンスについては、curl セクションをご参照ください。
Hello! I'm an AI assistant with knowledge current up to 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://dashscope-intl.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.5-plus",
"input": "Briefly introduce what you can do?",
"enable_thinking": true
}'レスポンス
{
"created_at": 1772249518,
"id": "7ad48c6b-3cc4-904f-9284-5f419c6c5xxx",
"model": "qwen3.5-plus",
"object": "response",
"output": [
{
"id": "msg_94805179-2801-45da-ac1c-a87e8ea20xxx",
"summary": [
{
"text": "Okay, the user is asking me to briefly introduce what I can do. Let me start by recalling the capabilities listed in the system message. I need to make sure I cover the main points without getting too detailed.\n\nFirst, I should mention my enhanced language foundation and architecture efficiency. Then, the upgraded logical reasoning and mathematical capabilities. Visual analysis is another key point, including charts and formulas. Autonomous agent planning and code generation are important too. Human alignment optimization for better interaction, long-context handling up to 256K, and multilingual support with OCR.\n\nWait, the user said \"briefly,\" so I need to keep it concise. Maybe group some points together. Let me check the examples given in the system message. They have sections like Enhanced Language Foundation, Advanced Logical Reasoning, etc. But since it's a brief intro, I should summarize each capability in a sentence or two.\n\nAlso, the user might be looking for practical applications. Maybe highlight how these features help in real tasks. For example, handling long documents, solving math problems, analyzing images, writing code, etc.\n\nI should avoid technical jargon where possible. Make it clear and straightforward. Let me structure it as a list of key capabilities with short explanations. Start with a greeting, then list the main points, and end with an offer to help with specific tasks.\n\nWait, the system message says \"You are Qwen3.5,\" so I need to introduce myself as such. But the user just asked what I can do, so maybe start with \"I'm Qwen3.5...\" and then list the capabilities.\n\nCheck if all the upgraded features from Qwen3 to Qwen3.5 are covered. The main upgrades are in language foundation, reasoning, visual analysis, agent planning, code, alignment, context length, and multilingual OCR.\n\nMake sure not to mention the knowledge cutoff unless relevant. The user's current time is 2026, but since my knowledge is up to 2026, that's covered.\n\nOkay, let me draft a concise response highlighting each capability briefly. Keep it friendly and inviting for the user to ask for specific help.\n",
"type": "summary_text"
}
],
"type": "reasoning"
},
{
"content": [
{
"annotations": [],
"text": "I'm **Qwen3.5**, 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"
}
]
}
}OpenAI 互換チャット補完 API
Python
import os
from openai import OpenAI
try:
client = OpenAI(
# API キーはリージョンごとに異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key を参照してください。
# 環境変数が設定されていない場合は、次の行を Model Studio API キーに置き換えてください:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# ベース URL はリージョンによって異なります。
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3.5-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"An error occurred: {e}")
print("詳細については、エラーコードドキュメントをご参照ください:https://www.alibabacloud.com/help/model-studio/error-code")レスポンス
I am Qwen, a large language model developed by the Tongyi Lab at Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask!Java
// OpenAI Java SDK バージョン >= 3.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 を参照してください。
// 環境変数が設定されていない場合は、次の行を Model Studio API キーに置き換えてください: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// ベース URL はリージョンによって異なります。
.baseUrl("https://dashscope-intl.aliyuncs.com/compatible-mode/v1")
.build();
// ChatCompletion パラメーターを作成します。
ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
.model("qwen3.5-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);
// 完全なレスポンスを表示するには、次の行のコメントを外してください。
// System.out.println(chatCompletion);
} catch (Exception e) {
System.err.println("An error occurred: " + e.getMessage());
System.out.println("詳細については、エラーコードドキュメントをご参照ください:https://www.alibabacloud.com/help/model-studio/error-code");
}
}
}レスポンス
I am Qwen, a large language model developed by the Tongyi Lab at Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask!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 を参照してください。
// 環境変数が設定されていない場合は、次の行を Model Studio API キーに置き換えてください:apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
// ベース URL はリージョンによって異なります。
baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
}
);
const completion = await openai.chat.completions.create({
model: "qwen3.5-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 language model developed by the Tongyi Lab at Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, code, and more. I can also express opinions and play games. 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() {
// API キーはリージョンごとに異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key を参照してください。
// 環境変数が設定されていない場合は、次の行を Model Studio API キーに置き換えてください:apiKey := "sk-xxx"
apiKey := os.Getenv("DASHSCOPE_API_KEY")
client := openai.NewClient(
option.WithAPIKey(apiKey),
// ベース URL はリージョンによって異なります。
option.WithBaseURL("https://dashscope-intl.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.5-plus",
},
)
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 language model developed by the Tongyi Lab at Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, code, and more. I can also express opinions and play games. 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)
{
// 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 はリージョンによって異なります。
string url = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions";
string jsonContent = @"{
""model"": ""qwen3.5-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/model-studio/error-code
return $"Request failed with status code: {response.StatusCode}";
}
}
}
}レスポンス
I am Qwen, a large language model developed by the Tongyi Lab at Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask!PHP (HTTP)
<?php
// ベース URL はリージョンによって異なります。
$url = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
// API キーはリージョンごとに異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key を参照してください。
// 環境変数が設定されていない場合は、次の行を Model Studio API キーに置き換えてください: $apiKey = "sk-xxx";
$apiKey = getenv('DASHSCOPE_API_KEY');
// リクエストヘッダーを設定します。
$headers = [
'Authorization: Bearer '.$apiKey,
'Content-Type: application/json'
];
// リクエストボディを設定します。
$data = [
"model" => "qwen3.5-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);
// cURL エラーをチェックします。
if (curl_errno($ch)) {
// 詳細については、エラーコードドキュメントをご参照ください:https://www.alibabacloud.com/help/model-studio/error-code
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 language model developed by the Tongyi Lab at Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask!curl
ベース URL と API キーはリージョンによって異なります。詳細については、「OpenAI Chat」および「API キーの取得」をご参照ください。
# ベース URL はリージョンによって異なります。
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.5-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 language model developed by the Tongyi Lab at Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, code, and more. I can also express opinions and play games. 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.5-plus",
"id": "chatcmpl-81951b98-28b8-9659-ab07-xxxxxx"
}DashScope
Qwen-3.5 シリーズの DashScope API はマルチモーダルインターフェイスを使用します。これらの例は url error を返します。正しい API メソッドについては、「画像および動画データ処理」をご参照ください。
Python
import json
import os
from dashscope import Generation
import dashscope
# ベース URL はリージョンによって異なります。
dashscope.base_http_api_url = "https://dashscope-intl.aliyuncs.com/api/v1"
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Who are you?"},
]
response = Generation.call(
# API キーはリージョンごとに異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key を参照してください。
# 環境変数が設定されていない場合は、次の行を Model Studio API キーに置き換えてください: api_key = "sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# Qwen-3.5 シリーズにはマルチモーダルインターフェイスが必要です。モデルを直接置き換えるとエラーになります。
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 language model developed by the Tongyi Lab at Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, code, and more. I can also express opinions and play games. 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 はリージョンによって異なります。
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
Message systemMsg = Message.builder()
.role(Role.SYSTEM.getValue())
.content("You are a helpful assistant.")
.build();
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("Who are you?")
.build();
GenerationParam param = GenerationParam.builder()
// API キーはリージョンごとに異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key を参照してください。
// 環境変数が設定されていない場合は、次の行を Model Studio API キーに置き換えてください: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Qwen-3.5 シリーズにはマルチモーダルインターフェイスが必要です。モデルを直接置き換えるとエラーになります。
.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 language model developed by the Tongyi Lab at Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask!Node.js (HTTP)
// Node.js v18 以降が必要です。
// API キーはリージョンごとに異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key を参照してください。
// 環境変数が設定されていない場合は、次の行を Model Studio API キーに置き換えてください: const apiKey = "sk-xxx";
const apiKey = process.env.DASHSCOPE_API_KEY;
const data = {
// Qwen-3.5 シリーズにはマルチモーダルインターフェイスが必要です。モデルを直接置き換えるとエラーになります。
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 はリージョンによって異なります。
const response = await fetch('https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
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('Call failed:', error.message);
}
}
callApi();レスポンス
I am Qwen, a large language model developed by the Tongyi Lab at Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, code, and more. I can also express opinions and play games. 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() {
// API キーはリージョンごとに異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key を参照してください。
// 環境変数が設定されていない場合は、apiKey 変数に Model Studio API キーを代入してください。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
// apiKey := "sk-xxx"
requestBody := map[string]interface{}{
// Qwen-3.5 シリーズにはマルチモーダルインターフェイスが必要です。モデルを直接置き換えるとエラーになります。
"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 はリージョンによって異なります。
req, _ := http.NewRequest("POST", "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation", bytes.NewBuffer(jsonData))
// リクエストヘッダーを設定します。
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 language model developed by the Tongyi Lab at Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, code, and more. I can also express opinions and play games. 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 はリージョンによって異なります。
string url = "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// Qwen-3.5 シリーズにはマルチモーダルインターフェイスが必要です。モデルを直接置き換えるとエラーになります。
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 language model developed by the Tongyi Lab at Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, code, and more. I can also express opinions and play games. 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 はリージョンによって異なります。
$url = "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// API キーはリージョンごとに異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key を参照してください。
// 環境変数が設定されていない場合は、次の行を Model Studio API キーに置き換えてください: $apiKey = "sk-xxx";
$apiKey = getenv('DASHSCOPE_API_KEY');
$data = [
// Qwen-3.5 シリーズにはマルチモーダルインターフェイスが必要です。モデルを直接置き換えるとエラーになります。
"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 error: " . $httpCode . " - " . $response;
}
curl_close($ch);
?>レスポンス
I am Qwen, a large language model developed by the Tongyi Lab at Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask!curl
ベース URL と API キーはリージョンによって異なります。「DashScope」および「API キーの取得」をご参照ください。
# ベース URL はリージョンによって異なります。
curl --location "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "qwen-plus",
"input":{
"messages":[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Who are you?"
}
]
},
"parameters": {
"result_format": "message"
}
}'レスポンス
{
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": "I am Qwen, a large language model developed by the Tongyi Lab at Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, code, and more. I can also express opinions and play games. 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"
}画像および動画データの処理
マルチモーダルモデルは、視覚質問応答やイベント検出などのタスクのために、画像や動画などの非テキストデータを受け付けます。マルチモーダルモデルの呼び出しは、テキスト専用モデルの呼び出しとは以下の点で異なります。
ユーザーメッセージの構築:マルチモーダルモデルの場合、ユーザーメッセージにはテキストだけでなく、画像、動画、音声などのマルチモーダルコンテンツも含まれます。
DashScope SDK API:DashScope Python ソフトウェア開発キット(SDK)を使用する場合、
MultiModalConversationAPI を呼び出します。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"),
# ベース URL はリージョンによって異なります。ご利用のリージョンに合わせて変更してください。
base_url="https://dashscope-intl.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.5-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,
// ベース URL はリージョンによって異なります。ご利用のリージョンに合わせて変更してください。
baseURL: "https://dashscope-intl.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.5-plus",
messages: messages
});
console.log(response.choices[0].message.content);
}
main()curl
ベース URL と API キーはリージョンによって異なります。詳細については、「OpenAI Chat」および「API キーの取得」をご参照ください。
# リクエスト URL はリージョンによって異なります。ご利用のリージョンに合わせて変更してください。
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3.5-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
# API エンドポイントはリージョンによって異なります。この行は国際サイト用のエンドポイントを設定します。
dashscope.base_http_api_url = 'https://dashscope-intl.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.5-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 {
// API エンドポイントはリージョンによって異なります。このブロックは国際サイト用のエンドポイントを設定します。
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
}
private static final String modelName = "qwen3.5-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 キーの取得」をご参照ください。
# リクエスト URL はリージョンによって異なります。ご利用のリージョンに合わせて変更してください。
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3.5-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 互換
Python
import os
import asyncio
from openai import AsyncOpenAI
import platform
# 非同期クライアントインスタンスを作成します。
client = AsyncOpenAI(
# 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"),
# ベース URL はリージョンによって異なります。
base_url="https://dashscope-intl.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/en/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__':
# Windows 用のイベントループポリシーを設定します。
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 互換 API に接続するための OpenAI クライアントを作成します。
OpenAIClientAsync client = OpenAIOkHttpClientAsync.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"))
// ベース URL はリージョンによって異なります。
.baseUrl("https://dashscope-intl.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("An error occurred: " + e.getMessage());
System.out.println("詳細については、ドキュメントをご参照ください:https://www.alibabacloud.com/help/en/model-studio/error-codes");
return null;
});
}).thenCompose(future -> future))
.toArray(CompletableFuture[]::new);
// すべての非同期操作が完了するまで待ちます。
CompletableFuture.allOf(futures).join();
}
}DashScope
現在、DashScope SDK を使用した非同期テキスト生成は Python のみでサポートされています。
# DashScope Python SDK バージョン 1.19.0 以降が必要です。
import asyncio
import platform
from dashscope.aigc.generation import AioGeneration
import os
import dashscope
# ベース URL はリージョンによって異なります。
dashscope.base_http_api_url = 'https://dashscope-intl.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/ja/model-studio/models をご参照ください。
messages=[{"role": "system", "content": "あなたは親切なアシスタントです。"},
{"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__':
# Windows 向けのイベントループポリシーを設定します。
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 am Qwen, a large language model developed by the Tongyi Lab at Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to ask!
Model response: I cannot access real-time weather information. Tell me your city or region, and I can share general weather guidance. Alternatively, use a weather app for current conditions.
Model response: I can help with many tasks, including:
1. **Answering questions**: I can help with academic, general knowledge, or professional questions.
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. **Sharing opinions**: I can provide suggestions to help you make decisions.
7. **Playing games**: We can play text-based games together, such as riddles and 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!本番環境に適用
高品質なコンテキストの構築
大規模言語モデル(LLM)に大量の生データをそのまま入力すると、コンテキストウィンドウの制限によりコストが増加し、効果が低下する可能性があります。コンテキストエンジニアリングにより、必要な知識を動的にロードすることで、生成品質と効率を大幅に向上させることができます。主な手法は以下のとおりです。
プロンプトエンジニアリング:テキスト命令(プロンプト)を設計・改良し、モデルが望ましい結果を導き出すように誘導します。詳細については、「テキスト間プロンプトガイド
検索拡張生成(RAG):モデルが外部ナレッジベース(製品ドキュメントや技術マニュアルなど)に基づいて質問に回答する必要がある場合に使用します。
ツール呼び出し:天気や交通状況などのリアルタイム情報を取得したり、API 呼び出しなどの特定の操作を実行したりできるようにします。
メモリメカニズム:モデルに短期記憶および長期記憶を確立し、会話履歴を理解できるようにします。
レスポンスの多様性の制御
temperature および top_p パラメーターは、生成テキストの多様性を制御します。値が高いほど多様なコンテンツになり、値が低いほど決定論的なコンテンツになります。パラメーターの効果を正確に評価するには、一度に 1 つのパラメーターのみを調整することを推奨します。
temperature:範囲:[0, 2)。ランダム性を調整するために使用します。top_p:範囲:[0, 1]。確率しきい値を使用してレスポンスをフィルターします。
以下の例は、異なる設定が生成出力にどのように影響するかを示しています。プロンプトは「猫と日だまりを主人公にした 3 文の短編ストーリーを書いてください」です。
高多様性(例:
temperature=0.9):創造性、想像力、新しい表現が求められるシナリオ(クリエイティブライティング、ブレインストーミング、マーケティングコピーなど)に適しています。Sunlight sliced through the window, and the ginger cat crept toward the glowing square, its fur instantly gilded like molten honey. It tapped the light with a paw, sinking into warmth as if stepping into a sunlit pool, and the golden tide flowed up its spine. The afternoon grew heavy—the cat curled in liquid gold, hearing time melt softly in its purr.高決定論性(例:
temperature=0.1):正確で厳密かつ予測可能なコンテンツが求められるシナリオ(事実に基づく質問応答、コード生成、法務文書など)に適しています。An old cat napped on the windowsill, counting sunbeams. The sunlight hopped across its mottled back like pages turning in an old photo album. Dust rose and settled, whispering: you were young once, and I burned bright.
その他の機能
上記のセクションでは基本的なインタラクションパターンについて説明しました。より高度なシナリオについては、以下のガイドをご参照ください。
マルチターン対話:フォローアップ質問や情報収集など、継続的なインタラクションが必要なシナリオに最適です。
ストリーミング出力:チャットボットやリアルタイムコード生成など、即時のレスポンスが必要なアプリケーションに適しています。これによりユーザーエクスペリエンスが向上し、長い応答時間によるタイムアウトを防ぐことができます。
ディープシンキング:複雑な推論やポリシー分析など、より高品質で構造化された回答が必要なタスクに適しています。
構造化出力:プログラムによる使用やデータ解析のために、モデルが一貫した JSON 形式で応答する必要がある場合に使用します。
部分モード:コード補完や長文作成など、既存のテキストから継続する必要があるシナリオに適しています。
API リファレンス
モデル呼び出しパラメーターの完全なリストについては、「OpenAI 互換 API リファレンス」および「DashScope API リファレンス」をご参照ください。
よくある質問
Q: Qwen API は Web リンクを分析できないのはなぜですか?
A: Qwen API はネイティブで Web リンクにアクセスしたり解析したりできません。この機能を実装するには、関数呼び出し などの機能を使用するか、Python の Beautiful Soup などの Web スクレイピングツールを統合して Web ページのコンテンツを読み取る必要があります。
Q: Web アプリと API のレスポンスが異なるのはなぜですか?
A: Qwen Web アプリは、Qwen API をベースに追加のエンジニアリング最適化を施して構築されており、Web ページの解析、Web 検索、画像生成、PPT 作成などの機能を実現しています。これらは大規模言語モデル API に本来備わっている機能ではありません。関数呼び出し などの機能を使用することで、モデルのパフォーマンスを最適化できます。
Q: モデルはフォーマット済みファイルを生成できますか?
A: いいえ。Model Studio のテキスト生成モデルはプレーンテキストのみを出力します。これらの形式のファイルを作成するには、独自のコードまたはサードパーティ製ライブラリを使用してプレーンテキスト出力を変換するか、