Qwen API はステートレスであり、対話履歴を保存しません。マルチターン対話を実現するには、各リクエストで対話履歴を渡す必要があります。また、切り捨て、要約、検索などの戦略を使用して、コンテキストを効率的に管理し、トークン消費量を削減することもできます。
このトピックでは、OpenAI 互換の Chat Completion または DashScope インターフェイスを使用してマルチターン対話を実現する方法について説明します。Responses API はより便利な代替手段を提供します。詳細については、「OpenAI 互換 - 応答」をご参照ください。
仕組み
マルチターン対話を実現するには、messages 配列を維持する必要があります。各対話で、ユーザーの最新の質問とモデルの応答をこの配列に追加します。次に、更新された配列を次のリクエストの入力として使用します。
次の例は、マルチターン対話中に messages 配列の状態がどのように変化するかを示しています。
1 回目の対話
ユーザーの質問を
messages配列に追加します。// テキストモデルを使用 [ {"role": "user", "content": "宇宙探査に関する SF 映画をおすすめしてください。"} ] // マルチモーダルモデル (例: Qwen-VL) を使用 // {"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": "画像に写っているプロダクトは何ですか?"}] // }第2ラウンド
モデルの応答とユーザーの最新の質問を
messages配列に追加します。// テキストモデルを使用 [ {"role": "user", "content": "宇宙探査に関する SF 映画をおすすめしてください。"}, {"role": "assistant", "content": "「XXX」をおすすめします。古典的な SF 作品です。"}, {"role": "user", "content": "この映画の監督は誰ですか?"} ] // マルチモーダルモデル (例: Qwen-VL) を使用 //[ // {"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": "画像に写っているプロダクトは何ですか?"}]}, // {"role": "assistant", "content": "画像には、水色のオーバーオール、青と白のストライプの半袖シャツ、白いスニーカーの 3 点が写っています。"}, // {"role": "user", "content": "どのようなスタイルですか?"} //]
クイックスタート
OpenAI 互換
Python
import os
from openai import OpenAI
def get_response(messages):
client = OpenAI(
# API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
# 環境変数を設定していない場合は、次の行をご利用の Model Studio API キーに置き換えてください: api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
# モデルのリストについては、https://www.alibabacloud.com/help/model-studio/getting-started/models をご参照ください
completion = client.chat.completions.create(model="qwen-plus", messages=messages)
return completion
# messages 配列を初期化
messages = [
{
"role": "system",
"content": """あなたはアリババモバイルショップの販売員です。ユーザーに携帯電話をおすすめする責任があります。携帯電話には、画面サイズ (6.1 インチ、6.5 インチ、6.7 インチを含む) と解像度 (2K と 4K を含む) の 2 つのパラメーターがあります。
一度に 1 つのパラメーターしかユーザーに尋ねることはできません。ユーザーが完全な情報を提供しない場合は、不足しているパラメーターを取得するために追加の質問をする必要があります。すべてのパラメーターが収集されたら、「ご購入の意図を理解しました。しばらくお待ちください。」と言う必要があります。""",
}
]
assistant_output = "アリババモバイルショップへようこそ。どの画面サイズをお探しですか?"
print(f"モデルの出力: {assistant_output}\n")
while "ご購入の意図を理解しました" not in assistant_output:
user_input = input("入力してください: ")
# ユーザーの質問を messages リストに追加
messages.append({"role": "user", "content": user_input})
assistant_output = get_response(messages).choices[0].message.content
# モデルの応答を messages リストに追加
messages.append({"role": "assistant", "content": assistant_output})
print(f"モデルの出力: {assistant_output}")
print("\n")Node.js
import OpenAI from "openai";
import { createInterface } from 'readline/promises';
// 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
const BASE_URL = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1";
// API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
const openai = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: BASE_URL
});
async function getResponse(messages) {
try {
const completion = await openai.chat.completions.create({
// モデルのリストについては、https://www.alibabacloud.com/help/model-studio/getting-started/models をご参照ください
model: "qwen-plus",
messages: messages,
});
return completion.choices[0].message.content;
} catch (error) {
console.error("応答のフェッチ中にエラーが発生しました:", error);
throw error; // 上位レイヤーで処理するために例外を再スロー
}
}
// messages 配列を初期化
const messages = [
{
"role": "system",
"content": `あなたはアリババモバイルショップの販売員です。ユーザーに携帯電話をおすすめする責任があります。携帯電話には、画面サイズ (6.1 インチ、6.5 インチ、6.7 インチを含む) と解像度 (2K と 4K を含む) の 2 つのパラメーターがあります。
一度に 1 つのパラメーターしかユーザーに尋ねることはできません。ユーザーが完全な情報を提供しない場合は、不足しているパラメーターを取得するために追加の質問をする必要があります。すべてのパラメーターが収集されたら、「ご購入の意図を理解しました。しばらくお待ちください。」と言う必要があります。`,
}
];
let assistant_output = "アリババモバイルショップへようこそ。どの画面サイズをお探しですか?";
console.log(assistant_output);
const readline = createInterface({
input: process.stdin,
output: process.stdout
});
(async () => {
while (!assistant_output.includes("ご購入の意図を理解しました")) {
const user_input = await readline.question("入力してください: ");
messages.push({ role: "user", content: user_input});
try {
const response = await getResponse(messages);
assistant_output = response;
messages.push({ role: "assistant", content: assistant_output });
console.log(assistant_output);
console.log("\n");
} catch (error) {
console.error("応答のフェッチ中にエラーが発生しました:", error);
}
}
readline.close();
})();curl
# ======= 重要 =======
# API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
# 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions に置き換えてください
# === 実行前にこのコメントを削除してください ===
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-plus",
"messages":[
{
"role": "system",
"content": "あなたは役に立つアシスタントです。"
},
{
"role": "user",
"content": "こんにちは"
},
{
"role": "assistant",
"content": "こんにちは、私は Qwen です。"
},
{
"role": "user",
"content": "何ができますか?"
}
]
}'DashScope
Python
このサンプルコードは、携帯電話店の販売員が顧客とマルチターン対話を行い、購入意図を判断してからセッションを終了する例を提供します。
import os
from dashscope import Generation
import dashscope
# 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/api/v1 に置き換えてください
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
def get_response(messages):
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"),
# モデルのリストについては、https://www.alibabacloud.com/help/model-studio/getting-started/models をご参照ください
model="qwen-plus",
messages=messages,
result_format="message",
)
return response
messages = [
{
"role": "system",
"content": """あなたはアリババモバイルショップの販売員です。ユーザーに携帯電話をおすすめする責任があります。携帯電話には、画面サイズ (6.1 インチ、6.5 インチ、6.7 インチを含む) と解像度 (2K と 4K を含む) の 2 つのパラメーターがあります。
一度に 1 つのパラメーターしかユーザーに尋ねることはできません。ユーザーが完全な情報を提供しない場合は、不足しているパラメーターを取得するために追加の質問をする必要があります。すべてのパラメーターが収集されたら、「ご購入の意図を理解しました。しばらくお待ちください。」と言う必要があります。""",
}
]
assistant_output = "アリババモバイルショップへようこそ。どの画面サイズをお探しですか?"
print(f"モデルの出力: {assistant_output}\n")
while "ご購入の意図を理解しました" not in assistant_output:
user_input = input("入力してください: ")
# ユーザーの質問を messages リストに追加
messages.append({"role": "user", "content": user_input})
assistant_output = get_response(messages).output.choices[0].message.content
# モデルの応答を messages リストに追加
messages.append({"role": "assistant", "content": assistant_output})
print(f"モデルの出力: {assistant_output}")
print("\n")Java
import java.util.ArrayList;
import java.util.List;
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 java.util.Scanner;
import com.alibaba.dashscope.protocol.Protocol;
public class Main {
public static GenerationParam createGenerationParam(List<Message> messages) {
return GenerationParam.builder()
// API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
// 環境変数を設定していない場合は、次の行をご利用の Model Studio API キーに置き換えてください: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// モデルのリストについては、https://www.alibabacloud.com/help/model-studio/getting-started/models をご参照ください
.model("qwen-plus")
.messages(messages)
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.build();
}
public static GenerationResult callGenerationWithMessages(GenerationParam param) throws ApiException, NoApiKeyException, InputRequiredException {
// 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/api/v1 に置き換えてください
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
return gen.call(param);
}
public static void main(String[] args) {
try {
List<Message> messages = new ArrayList<>();
messages.add(createMessage(Role.SYSTEM, "あなたは役に立つアシスタントです。"));
for (int i = 0; i < 3;i++) {
Scanner scanner = new Scanner(System.in);
System.out.print("入力してください: ");
String userInput = scanner.nextLine();
if ("exit".equalsIgnoreCase(userInput)) {
break;
}
messages.add(createMessage(Role.USER, userInput));
GenerationParam param = createGenerationParam(messages);
GenerationResult result = callGenerationWithMessages(param);
System.out.println("モデルの出力: "+result.getOutput().getChoices().get(0).getMessage().getContent());
messages.add(result.getOutput().getChoices().get(0).getMessage());
}
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
e.printStackTrace();
}
System.exit(0);
}
private static Message createMessage(Role role, String content) {
return Message.builder().role(role.getValue()).content(content).build();
}
}curl
# ======= 重要 =======
# API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
# 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation に置き換えてください
# === 実行前にこのコメントを削除してください ===
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-plus",
"input":{
"messages":[
{
"role": "system",
"content": "あなたは役に立つアシスタントです。"
},
{
"role": "user",
"content": "こんにちは"
},
{
"role": "assistant",
"content": "こんにちは、私は Qwen です。"
},
{
"role": "user",
"content": "何ができますか?"
}
]
}
}'マルチモーダルモデルによるマルチターン対話
本セクションは、Qwen-VL、Kimi-K2.5 モデルに適用されます。
Qwen-Omniの実装詳細については、「omni-modal」をご参照ください。Qwen-VL-OCR および Qwen3-Omni-Captioner は特定のシングルターンタスク向けに設計されており、マルチターン対話をサポートしていません。
マルチモーダルモデルでは、画像や音声などのコンテンツを対話に追加できます。これらのモデルにおけるマルチターン対話の実装は、テキストモデルとは以下の点で異なります。
ユーザー メッセージの構築:マルチモーダルモデルのユーザー メッセージには、テキストに加えて画像や音声などのマルチモーダル情報も含めることができます。
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/ja/model-studio/get-api-key をご参照ください。
# 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えてください: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください。
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-vl-plus", # 他のマルチモーダルモデルに置き換え、必要に応じて messages を修正できます。
messages=messages,
)
print(f"First round output: {completion.choices[0].message.content}")
assistant_message = completion.choices[0].message
messages.append(assistant_message.model_dump())
messages.append({
"role": "user",
"content": [
{
"type": "text",
"text": "What style are they?"
}
]
})
completion = client.chat.completions.create(
model="qwen3-vl-plus",
messages=messages,
)
print(f"Second round output: {completion.choices[0].message.content}")Node.js
import OpenAI from "openai";
const openai = new OpenAI(
{
// API キーはリージョンによって異なります。API キーの取得方法については、https://www.alibabacloud.com/help/ja/model-studio/get-api-key をご参照ください。
// 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えてください: apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
// 中国 (北京) リージョンのモデルを使用する場合は、baseURL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください。
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-vl-plus", // 他のマルチモーダルモデルに置き換え、必要に応じて messages を修正できます。
messages: messages
});
console.log(`First round output: ${response.choices[0].message.content}`);
messages.push(response.choices[0].message);
messages.push({"role": "user", "content": "Write a poem describing this scene"});
response = await openai.chat.completions.create({
model: "qwen3-vl-plus",
messages: messages
});
console.log(`Second round output: ${response.choices[0].message.content}`);
}
main()curl
# ======= Important =======
# 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions に置き換えてください。
# API キーはリージョンによって異なります。API キーの取得方法については、https://www.alibabacloud.com/help/ja/model-studio/get-api-key をご参照ください。
# === 実行前にこのコメントを削除してください ===
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-vl-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?"
}
]
},
{
"role": "assistant",
"content": [
{
"type": "text",
"text": "The image shows three items: a pair of light blue overalls, a blue and white striped short-sleeve shirt, and a pair of white sneakers."
}
]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "What style are they?"
}
]
}
]
}'DashScope
Python
import os
from dashscope import MultiModalConversation
import dashscope
# 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/api/v1 に置き換えてください。
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/ja/model-studio/get-api-key をご参照ください。
api_key=os.getenv('DASHSCOPE_API_KEY'),
model='qwen3-vl-plus', # 他のマルチモーダルモデルに置き換え、必要に応じて messages を修正できます。
messages=messages
)
print(f"Model first round output {response.output.choices[0].message.content[0]['text']}")
messages.append(response['output']['choices'][0]['message'])
user_msg = {"role": "user", "content": [{"text": "What style are they?"}]}
messages.append(user_msg)
response = MultiModalConversation.call(
# 環境変数が設定されていない場合は、次の行を api_key="sk-xxx" に置き換えてください。
api_key=os.getenv('DASHSCOPE_API_KEY'),
model='qwen3-vl-plus',
messages=messages
)
print(f"Model second round output {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 {
// 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/api/v1 に置き換えてください。
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
private static final String modelName = "qwen3-vl-plus"; // 他のマルチモーダルモデルに置き換え、必要に応じて messages を修正できます。
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/ja/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("First round output: "+result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text")); // 応答を会話履歴に追加
messages.add(result.getOutput().getChoices().get(0).getMessage());
MultiModalMessage msg = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(Collections.singletonMap("text", "What style are they?"))).build();
messages.add(msg);
param.setMessages((List)messages);
result = conv.call(param);
System.out.println("Second round output: "+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
# ======= Important =======
# API キーはリージョンによって異なります。API キーの取得方法については、https://www.alibabacloud.com/help/ja/model-studio/get-api-key をご参照ください。
# 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation に置き換えてください。
# === 実行前にこのコメントを削除してください ===
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-vl-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?"}
]
},
{
"role": "assistant",
"content": [
{"text": "The image shows three items: a pair of light blue overalls, a blue and white striped short-sleeve shirt, and a pair of white sneakers."}
]
},
{
"role": "user",
"content": [
{"text": "What style are they?"}
]
}
]
}
}'思考モデルのマルチターン対話
思考モデルは、reasoning_content (思考プロセス) と content (応答) の 2 つのフィールドを返します。messages 配列を更新する際は、content フィールドのみを保持し、reasoning_content フィールドは無視してください。
[
{"role": "user", "content": "宇宙探査に関する SF 映画をおすすめしてください。"},
{"role": "assistant", "content": "「XXX」をおすすめします。古典的な SF 作品です。"}, # コンテキストに追加する際に、reasoning_content フィールドを追加しないでください
{"role": "user", "content": "この映画の監督は誰ですか?"}
]思考モデルの詳細については、「ディープシンキング」、「ビジュアル理解」、および「ビジュアル推論」をご参照ください。
Qwen3-Omni-Flash (思考モード) を使用したマルチターン対話の実装に関する詳細については、「omni-modal」をご参照ください。
OpenAI 互換
Python
サンプルコード
from openai import OpenAI
import os
# OpenAI クライアントを初期化します
client = OpenAI(
# API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
# 環境変数を設定していない場合は、次の行をご利用の Model Studio API キーに置き換えます: api_key="sk-xxx"
api_key = os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
)
messages = []
conversation_idx = 1
while True:
reasoning_content = "" # 完全な思考プロセスを定義します
answer_content = "" # 完全な応答を定義します
is_answering = False # 思考プロセスを終了して応答を開始するかどうかを判断します
print("="*20+f"Conversation Round {conversation_idx}"+"="*20)
conversation_idx += 1
user_msg = {"role": "user", "content": input("Enter your message: ")}
messages.append(user_msg)
# チャット補完リクエストを作成します
completion = client.chat.completions.create(
# 必要に応じて、他のディープシンキングモデルに置き換えることができます
model="qwen-plus",
messages=messages,
extra_body={"enable_thinking": True},
stream=True,
# stream_options={
# "include_usage": True
# }
)
print("\n" + "=" * 20 + "Thinking Process" + "=" * 20 + "\n")
for chunk in completion:
# chunk.choices が空の場合は、usage を出力します
if not chunk.choices:
print("\nUsage:")
print(chunk.usage)
else:
delta = chunk.choices[0].delta
# 思考プロセスを出力します
if hasattr(delta, 'reasoning_content') and delta.reasoning_content != None:
print(delta.reasoning_content, end='', flush=True)
reasoning_content += delta.reasoning_content
else:
# 応答を開始します
if delta.content != "" and is_answering is False:
print("\n" + "=" * 20 + "Complete Response" + "=" * 20 + "\n")
is_answering = True
# 応答プロセスを出力します
print(delta.content, end='', flush=True)
answer_content += delta.content
# モデルの応答の content をコンテキストに追加します
messages.append({"role": "assistant", "content": answer_content})
print("\n")Node.js
サンプルコード
import OpenAI from "openai";
import process from 'process';
import readline from 'readline/promises';
// readline インターフェイスを初期化します
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// openai クライアントを初期化します
const openai = new OpenAI({
// API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
apiKey: process.env.DASHSCOPE_API_KEY, // 環境変数から読み取ります
baseURL: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1'
});
let reasoningContent = '';
let answerContent = '';
let isAnswering = false;
let messages = [];
let conversationIdx = 1;
async function main() {
while (true) {
console.log("=".repeat(20) + `Conversation Round ${conversationIdx}` + "=".repeat(20));
conversationIdx++;
// ユーザー入力を読み取ります
const userInput = await rl.question("Enter your message: ");
messages.push({ role: 'user', content: userInput });
// 状態をリセットします
reasoningContent = '';
answerContent = '';
isAnswering = false;
try {
const stream = await openai.chat.completions.create({
// 必要に応じて、他のディープシンキングモデルに置き換えることができます
model: 'qwen-plus',
messages: messages,
enable_thinking: true,
stream: true,
// stream_options:{
// include_usage: true
// }
});
console.log("\n" + "=".repeat(20) + "Thinking Process" + "=".repeat(20) + "\n");
for await (const chunk of stream) {
if (!chunk.choices?.length) {
console.log('\nUsage:');
console.log(chunk.usage);
continue;
}
const delta = chunk.choices[0].delta;
// 思考プロセスを処理します
if (delta.reasoning_content) {
process.stdout.write(delta.reasoning_content);
reasoningContent += delta.reasoning_content;
}
// 正式な応答を処理します
if (delta.content) {
if (!isAnswering) {
console.log('\n' + "=".repeat(20) + "Complete Response" + "=".repeat(20) + "\n");
isAnswering = true;
}
process.stdout.write(delta.content);
answerContent += delta.content;
}
}
// 完全な応答をメッセージ履歴に追加します
messages.push({ role: 'assistant', content: answerContent });
console.log("\n");
} catch (error) {
console.error('Error:', error);
}
}
}
// プログラムを開始します
main().catch(console.error);HTTP
サンプルコード
curl
# ======= 重要 =======
# 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions に置き換えてください
# API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
# === 実行前にこのコメントを削除してください ===
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-plus",
"messages": [
{
"role": "user",
"content": "Hello"
},
{
"role": "assistant",
"content": "Hello! Nice to meet you. Is there anything I can help you with?"
},
{
"role": "user",
"content": "Who are you?"
}
],
"stream": true,
"stream_options": {
"include_usage": true
},
"enable_thinking": true
}'DashScope
Python
サンプルコード
import os
import dashscope
# 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/api/v1 に置き換えてください
dashscope.base_http_api_url = "https://dashscope-intl.aliyuncs.com/api/v1/"
messages = []
conversation_idx = 1
while True:
print("=" * 20 + f"Conversation Round {conversation_idx}" + "=" * 20)
conversation_idx += 1
user_msg = {"role": "user", "content": input("Enter your message: ")}
messages.append(user_msg)
response = dashscope.Generation.call(
# 環境変数を設定していない場合は、次の行をご利用の Model Studio API キーに置き換えます: api_key="sk-xxx",
api_key=os.getenv('DASHSCOPE_API_KEY'),
# この例では qwen-plus を使用しています。必要に応じて、他のディープシンキングモデルに置き換えることができます
model="qwen-plus",
messages=messages,
enable_thinking=True,
result_format="message",
stream=True,
incremental_output=True
)
# 完全な思考プロセスを定義します
reasoning_content = ""
# 完全な応答を定義します
answer_content = ""
# 思考プロセスを終了して応答を開始するかどうかを判断します
is_answering = False
print("=" * 20 + "Thinking Process" + "=" * 20)
for chunk in response:
# 思考プロセスと応答の両方が空の場合は無視します
if (chunk.output.choices[0].message.content == "" and
chunk.output.choices[0].message.reasoning_content == ""):
pass
else:
# 現在が思考プロセスの場合
if (chunk.output.choices[0].message.reasoning_content != "" and
chunk.output.choices[0].message.content == ""):
print(chunk.output.choices[0].message.reasoning_content, end="",flush=True)
reasoning_content += chunk.output.choices[0].message.reasoning_content
# 現在が応答の場合
elif chunk.output.choices[0].message.content != "":
if not is_answering:
print("\n" + "=" * 20 + "Complete Response" + "=" * 20)
is_answering = True
print(chunk.output.choices[0].message.content, end="",flush=True)
answer_content += chunk.output.choices[0].message.content
# モデルの応答の content をコンテキストに追加します
messages.append({"role": "assistant", "content": answer_content})
print("\n")
# 完全な思考プロセスと完全な応答を出力するには、次のコードのコメントを解除して実行します
# print("=" * 20 + "Complete Thinking Process" + "=" * 20 + "\n")
# print(f"{reasoning_content}")
# print("=" * 20 + "Complete Response" + "=" * 20 + "\n")
# print(f"{answer_content}")Java
サンプルコード
// DashScope SDK バージョン >= 2.19.4
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 io.reactivex.Flowable;
import java.lang.System;
import java.util.List;
import com.alibaba.dashscope.protocol.Protocol;
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
private static StringBuilder reasoningContent = new StringBuilder();
private static StringBuilder finalContent = new StringBuilder();
private static boolean isFirstPrint = true;
private static void handleGenerationResult(GenerationResult message) {
if (message != null && message.getOutput() != null
&& message.getOutput().getChoices() != null
&& !message.getOutput().getChoices().isEmpty()
&& message.getOutput().getChoices().get(0) != null
&& message.getOutput().getChoices().get(0).getMessage() != null) {
String reasoning = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();
String content = message.getOutput().getChoices().get(0).getMessage().getContent();
if (reasoning != null && !reasoning.isEmpty()) {
reasoningContent.append(reasoning);
if (isFirstPrint) {
System.out.println("====================Thinking Process====================");
isFirstPrint = false;
}
System.out.print(reasoning);
}
if (content != null && !content.isEmpty()) {
finalContent.append(content);
if (!isFirstPrint) {
System.out.println("\n====================Complete Response====================");
isFirstPrint = true;
}
System.out.print(content);
}
}
}
private static GenerationParam buildGenerationParam(List<Message> messages) {
return GenerationParam.builder()
// 環境変数を設定していない場合は、次の行をご利用の Model Studio API キーに置き換えます: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// この例では qwen-plus を使用しています。必要に応じて、他のモデル名に置き換えることができます。
.model("qwen-plus")
.enableThinking(true)
.messages(messages)
.incrementalOutput(true)
.resultFormat("message")
.build();
}
public static void streamCallWithMessage(Generation gen, List<Message> messages)
throws NoApiKeyException, ApiException, InputRequiredException {
GenerationParam param = buildGenerationParam(messages);
Flowable<GenerationResult> result = gen.streamCall(param);
result.doOnError(throwable -> logger.error("Error occurred in stream processing: {}", throwable.getMessage(), throwable))
.blockingForEach(Main::handleGenerationResult);
}
public static void main(String[] args) {
try {
// 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/api/v1 に置き換えてください
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
Message userMsg1 = Message.builder()
.role(Role.USER.getValue())
.content("Hello")
.build();
Message assistantMsg = Message.builder()
.role(Role.ASSISTANT.getValue())
.content("Hello! Nice to meet you. Is there anything I can help you with?")
.build();
Message userMsg2 = Message.builder()
.role(Role.USER.getValue())
.content("Who are you")
.build();
List<Message> messages = Arrays.asList(userMsg1, assistantMsg, userMsg2);
streamCallWithMessage(gen, messages);
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
logger.error("An exception occurred: {}", e.getMessage(), e);
} catch (Exception e) {
logger.error("Unexpected error occurred: {}", e.getMessage(), e);
} finally {
// プログラムが正常に終了することを確認します
System.exit(0);
}
}
}HTTP
サンプルコード
curl
# ======= 重要 =======
# API キーはリージョンによって異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
# 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation に置き換えてください
# === 実行前にこのコメントを削除してください ===
curl -X POST "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
"model": "qwen-plus",
"input":{
"messages":[
{
"role": "user",
"content": "Hello"
},
{
"role": "assistant",
"content": "Hello! Nice to meet you. Is there anything I can help you with?"
},
{
"role": "user",
"content": "Who are you?"
}
]
},
"parameters":{
"enable_thinking": true,
"incremental_output": true,
"result_format": "message"
}
}'本番公開
マルチターン対話では多くのトークンを消費し、モデルの最大コンテキスト長を超える可能性があり、エラーの原因となります。以下の戦略は、コンテキストを効果的に管理し、コストをコントロールするのに役立ちます。
1. コンテキスト管理
messages 配列は対話のターンごとに増加し、最終的にモデルのトークン上限を超える可能性があります。対話中にコンテキスト長を管理するには、以下のメソッドを使用します。
1.1. コンテキストの切り捨て
対話履歴が長くなりすぎた場合、直近の N 回の対話のみを保持します。このメソッドは実装が簡単ですが、以前の対話情報が失われるという結果になります。
1.2. ローリングサマリー
コア情報を失うことなく対話履歴を動的に圧縮し、コンテキスト長をコントロールするには、対話の進行に合わせてコンテキストを要約します:
a. 対話履歴が最大コンテキスト長の 70% など、特定の長さに達したら、履歴の前の部分 (前半など) を抽出します。次に、モデルに対して別途 API 呼び出しを行い、この部分の「メモリサマリー」を生成します。
b. 次のリクエストを構築する際、長くなった対話履歴を「メモリサマリー」で置き換え、直近の対話を追加します。
1.3. ベクトル化された取得
ローリングサマリーでは、一部の情報が失われる可能性があります。モデルが大量の対話履歴から関連情報を呼び出せるようにするには、線形的なコンテキストの受け渡しから、オンデマンドの取得に切り替えます:
a. 各対話ターンの後、対話をベクトルデータベースに保存します。
b. ユーザーが質問をすると、類似性に基づいて関連する対話レコードを取得します。
c. 取得した対話レコードと直近のユーザー入力を組み合わせ、結合したコンテンツをモデルに送信します。
2. コストコントロール
入力トークンの数は対話のターンごとに増加し、コストが大幅に増加します。以下のコスト管理戦略を使用してください。
2.1. 入力トークンの削減
前述のコンテキスト管理戦略を使用して入力トークンを削減し、コストを低減します。
2.2. コンテキストキャッシュをサポートするモデルの使用
マルチターン対話のリクエストを行う際、messages 配列内のコンテンツは繰り返し処理され、課金されます。Alibaba Cloud の Model Studio は、qwen-max や qwen-plus などのモデルに対して コンテキストキャッシュ 機能を提供しています。この機能により、コストを削減し、応答速度を向上させることができます。コンテキストキャッシュをサポートするモデルを優先的に使用することを推奨します。
コンテキストキャッシュ機能は自動的に有効になります。コードの変更は必要ありません。
エラーコード
呼び出しが失敗した場合のトラブルシューティングについては、エラーメッセージをご参照ください。