ディープシンキングモデルは、応答を生成する前に推論を実行します。これにより、論理的推論や数値計算などの複雑なタスクの精度が向上します。このトピックでは、Qwen や DeepSeek などのディープシンキングモデルを呼び出す方法について説明します。
実装ガイド
Alibaba Cloud Model Studio は、さまざまなディープシンキングモデルの API を提供します。これらのモデルは、ハイブリッドシンキングとシンキングオンリーの 2 つのモードをサポートしています。
ハイブリッドシンキングモード:
enable_thinkingパラメーターを使用して、シンキングモードを有効にするかどうかを制御します。trueに設定:モデルは応答する前に思考します。falseに設定:モデルは直接応答します。
OpenAI 互換
# 依存関係をインポートし、クライアントを作成... completion = client.chat.completions.create( model="qwen-plus", # モデルを選択 messages=[{"role": "user", "content": "あなたは誰ですか"}], # enable_thinking は標準の OpenAI パラメーターではないため、extra_body を使用して渡します extra_body={"enable_thinking":True}, # ストリーミング出力モードで呼び出します stream=True, # ストリーム応答の最後のデータパケットにトークン消費情報を含めます stream_options={ "include_usage": True } )DashScope
# 依存関係をインポート... response = Generation.call( # 環境変数を設定していない場合は、次の行をご利用の Model Studio API キーに置き換えます: api_key = "sk-xxx", api_key=os.getenv("DASHSCOPE_API_KEY"), # 必要に応じて、これを別のディープシンキングモデルに置き換えることができます model="qwen-plus", messages=messages, result_format="message", enable_thinking=True, stream=True, incremental_output=True )シンキングオンリーモード:モデルは常に応答する前に思考し、この動作は無効にできません。リクエストのフォーマットはハイブリッドシンキングモードと同じですが、enable_thinking パラメーターは不要です。
思考プロセスは reasoning_content フィールドで返され、応答は content フィールドで返されます。ディープシンキングモデルは応答する前に推論するため、応答時間が増加します。これらのモデルのほとんどはストリーミング出力のみをサポートしています。したがって、このトピックの例ではストリーミング呼び出しを使用しています。
サポートされているモデル
Qwen3
商用版
Qwen-Max シリーズ (ハイブリッドシンキングモード、デフォルトで無効):qwen3-max-2026-01-23、qwen3-max-preview
Qwen-Plus シリーズ (ハイブリッドシンキングモード、デフォルトで無効):qwen-plus、qwen-plus-latest、qwen-plus-2025-04-28、およびそれ以降のスナップショットモデル
Qwen-Flash シリーズ (ハイブリッドシンキングモード、デフォルトで無効):qwen-flash、qwen-flash-2025-07-28、およびそれ以降のスナップショットモデル
Qwen-Turbo シリーズ (ハイブリッドシンキングモード、デフォルトで無効):qwen-turbo、qwen-turbo-latest、qwen-turbo-2025-04-28、およびそれ以降のスナップショットモデル
オープンソース版
ハイブリッドシンキングモード、デフォルトで有効:qwen3-235b-a22b、qwen3-32b、qwen3-30b-a3b、qwen3-14b、qwen3-8b、qwen3-4b、qwen3-1.7b、qwen3-0.6b
シンキングオンリーモード:qwen3-next-80b-a3b-thinking、qwen3-235b-a22b-thinking-2507、qwen3-30b-a3b-thinking-2507
QwQ (Qwen2.5 ベース)
シンキングオンリーモード:qwq-plus、qwq-plus-latest、qwq-plus-2025-03-05、qwq-32b
DeepSeek (中国 (北京) リージョン)
ハイブリッドシンキングモード、デフォルトで無効:deepseek-v3.2、deepseek-v3.2-exp、deepseek-v3.1
シンキングオンリーモード:deepseek-r1、deepseek-r1-0528、deepseek-r1 蒸留モデル
Kimi (中国 (北京) リージョン)
シンキングオンリーモード:kimi-k2-thinking
モデル名、コンテキスト、価格、スナップショットバージョンの詳細については、「モデルリスト」をご参照ください。レート制限の詳細については、「レート制限」をご参照ください。
はじめに
前提条件:API キーを作成し、API キーを環境変数として設定します。SDK を使用する場合は、OpenAI または DashScope SDK をインストールする必要があります (Java 用の DashScope SDK はバージョン 2.19.4 以降である必要があります)。
次のコードを実行して、ストリーミング出力でシンキングモードの qwen-plus モデルを呼び出します。
OpenAI 互換
Python
サンプルコード
from openai import OpenAI
import os
# OpenAI クライアントを初期化
client = OpenAI(
# 環境変数を設定していない場合は、次の行をご利用の Model Studio API キーに置き換えてください: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下はシンガポールリージョンの base_url です。米国 (バージニア) リージョンのモデルを使用する場合は、base_url を https://dashscope-us.aliyuncs.com/compatible-mode/v1 に置き換えてください
# 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
messages = [{"role": "user", "content": "あなたは誰ですか"}]
completion = client.chat.completions.create(
model="qwen-plus", # 必要に応じて、これを別のディープシンキングモデルに置き換えることができます
messages=messages,
extra_body={"enable_thinking": True},
stream=True,
stream_options={
"include_usage": True
},
)
reasoning_content = "" # 完全な思考プロセス
answer_content = "" # 完全な応答
is_answering = False # 応答フェーズが開始されたかどうかを示します
print("\n" + "=" * 20 + "思考プロセス" + "=" * 20 + "\n")
for chunk in completion:
if not chunk.choices:
print("\n使用量:")
print(chunk.usage)
continue
delta = chunk.choices[0].delta
# 思考コンテンツのみを収集
if hasattr(delta, "reasoning_content") and delta.reasoning_content is not None:
if not is_answering:
print(delta.reasoning_content, end="", flush=True)
reasoning_content += delta.reasoning_content
# コンテンツが受信されたら、応答を開始
if hasattr(delta, "content") and delta.content:
if not is_answering:
print("\n" + "=" * 20 + "完全な応答" + "=" * 20 + "\n")
is_answering = True
print(delta.content, end="", flush=True)
answer_content += delta.content
応答
====================思考プロセス====================
わかりました、ユーザーは「あなたは誰ですか」と尋ねましたので、正確でフレンドリーな応答を提供する必要があります。まず、私のアイデンティティ、つまり Alibaba Group 傘下の Tongyi Lab によって開発された Qwen であることを確認する必要があります。次に、質問への回答、テキストの作成、論理的推論などの主な機能を説明する必要があります。同時に、ユーザーが安心できるように、フレンドリーなトーンを保ち、専門的になりすぎないようにする必要があります。また、応答が簡潔で明確であることを保証するために、複雑な専門用語の使用を避ける必要があります。さらに、さらなるコミュニケーションを促すために、ユーザーに質問を促すなどのインタラクティブな要素を追加する必要があるかもしれません。最後に、中国語名「通义千问」と英語名「Qwen」、そして親会社とラボなど、重要な情報を見逃していないか確認します。応答が包括的で、ユーザーの期待に応えるものであることを確認する必要があります。
====================完全な応答====================
こんにちは!私は Qwen、Alibaba Group 傘下の Tongyi Lab が独自に開発した超大規模言語モデルです。質問への回答、テキストの作成、論理的推論、コードの作成などが可能で、ユーザーに高品質な情報とサービスを提供することを目指しています。Qwen と呼んでいただいても、通义千问と呼んでいただいても構いません。何かお手伝いできることはありますか?Node.js
サンプルコード
import OpenAI from "openai";
import process from 'process';
// OpenAI クライアントを初期化
const openai = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY, // 環境変数から読み込み
// 以下はシンガポールリージョンの base_url です。米国 (バージニア) リージョンのモデルを使用する場合は、base_url を https://dashscope-us.aliyuncs.com/compatible-mode/v1 に置き換えてください
// 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
baseURL: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1'
});
let reasoningContent = '';
let answerContent = '';
let isAnswering = false;
async function main() {
try {
const messages = [{ role: 'user', content: 'あなたは誰ですか' }];
const stream = await openai.chat.completions.create({
model: 'qwen-plus',
messages,
stream: true,
enable_thinking: true
});
console.log('\n' + '='.repeat(20) + '思考プロセス' + '='.repeat(20) + '\n');
for await (const chunk of stream) {
if (!chunk.choices?.length) {
console.log('\n使用量:');
console.log(chunk.usage);
continue;
}
const delta = chunk.choices[0].delta;
// 思考コンテンツのみを収集
if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
if (!isAnswering) {
process.stdout.write(delta.reasoning_content);
}
reasoningContent += delta.reasoning_content;
}
// コンテンツが受信されたら、応答を開始
if (delta.content !== undefined && delta.content) {
if (!isAnswering) {
console.log('\n' + '='.repeat(20) + '完全な応答' + '='.repeat(20) + '\n');
isAnswering = true;
}
process.stdout.write(delta.content);
answerContent += delta.content;
}
}
} catch (error) {
console.error('エラー:', error);
}
}
main();戻り値
====================思考プロセス====================
わかりました、ユーザーは「あなたは誰ですか」と尋ねましたので、私のアイデンティティについて答える必要があります。まず、私が Alibaba Cloud によって開発された超大規模言語モデルである Qwen であることを明確に述べるべきです。次に、質問への回答、テキストの作成、論理的推論などの主な機能について言及できます。また、ユーザーが異なる言語でのリクエストを処理できることを知るように、中国語と英語を含む多言語サポートを強調する必要があります。さらに、学習、仕事、日常生活の支援など、私のアプリケーションシナリオを説明する必要があるかもしれません。しかし、ユーザーの質問は非常に直接的なので、あまり詳細な情報を提供する必要はないでしょう。簡潔かつ明確に保つべきです。同時に、フレンドリーなトーンを確保し、ユーザーにさらなる質問を促す必要があります。バージョンや最新の更新など、重要な情報を見逃していないか確認しますが、ユーザーはおそらくそれほど詳細を必要としていないでしょう。最後に、応答が正確でエラーがないことを確認します。
====================完全な応答====================
私は Qwen、Alibaba Group 傘下の Tongyi Lab が独自に開発した超大規模言語モデルです。質問への回答、テキストの作成、論理的推論、コーディングなど、さまざまなタスクを実行できます。中国語と英語を含む複数の言語をサポートしています。ご質問やお手伝いが必要な場合は、お気軽にお知らせください!HTTP
サンプルコード
curl
# ======= 重要 =======
# 以下はシンガポールの base_url です。中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions に置き換えてください
# 米国 (バージニア) リージョンのモデルを使用する場合は、base_url を https://dashscope-us.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": "user",
"content": "あなたは誰ですか"
}
],
"stream": true,
"stream_options": {
"include_usage": true
},
"enable_thinking": true
}'応答
data: {"choices":[{"delta":{"content":null,"role":"assistant","reasoning_content":""},"index":0,"logprobs":null,"finish_reason":null}],"object":"chat.completion.chunk","usage":null,"created":1745485391,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503"}
.....
data: {"choices":[{"finish_reason":"stop","delta":{"content":"","reasoning_content":null},"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1745485391,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503"}
data: {"choices":[],"object":"chat.completion.chunk","usage":{"prompt_tokens":10,"completion_tokens":360,"total_tokens":370},"created":1745485391,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503"}
data: [DONE]DashScope
Python
サンプルコード
import os
from dashscope import Generation
import dashscope
# 以下はシンガポールリージョンの base_url です。米国 (バージニア) リージョンのモデルを使用する場合は、base_url を https://dashscope-us.aliyuncs.com/api/v1 に置き換えます
# 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/api/v1 に置き換えます
dashscope.base_http_api_url = "https://dashscope-intl.aliyuncs.com/api/v1"
messages = [{"role": "user", "content": "Who are you?"}]
completion = Generation.call(
# 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えます:api_key = "sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen-plus",
messages=messages,
result_format="message",
enable_thinking=True,
stream=True,
incremental_output=True,
)
# 完全な思考プロセスを定義します。
reasoning_content = ""
# 完全な応答を定義します。
answer_content = ""
# 思考プロセスが終了し、応答が開始されたかどうかを判断します。
is_answering = False
print("=" * 20 + "Thinking process" + "=" * 20)
for chunk in completion:
# 思考プロセスと応答の両方が空の場合は無視します。
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 + "Full response" + "=" * 20)
is_answering = True
print(chunk.output.choices[0].message.content, end="", flush=True)
answer_content += chunk.output.choices[0].message.content
# 完全な思考プロセスと応答を出力するには、次のコードのコメントを解除して実行します。
# print("=" * 20 + "Full thinking process" + "=" * 20 + "\n")
# print(f"{reasoning_content}")
# print("=" * 20 + "Full response" + "=" * 20 + "\n")
# print(f"{answer_content}")
応答
====================Thinking process====================
ユーザーからの「あなたは誰ですか?」という質問に答える必要があります。まず、自身のアイデンティティを明確にします。私は Alibaba Cloud が開発した大規模言語モデルの Qwen です。次に、質問への回答、テキスト作成、論理的推論といった、自身の機能と用途を説明します。また、ユーザーの役に立つアシスタントとして、ヘルプとサポートを提供することが目標である点も強調します。
応答する際は、会話的なトーンを保ち、専門用語や複雑な文章は避けるべきです。「こんにちは!〜」のようなフレンドリーなフレーズを加えて、会話をより自然にすることができます。また、情報が正確であること、そして開発元、主な機能、ユースケースといった要点を見落とさないようにする必要があります。
さらに、具体的な応用例や技術的な詳細など、ユーザーからの追加の質問も想定しておく必要があります。そのため、応答の中に、さらなる質問を促すようなヒントをさりげなく含めることができます。例えば、「日常生活の質問から専門的なトピックまで、全力でお手伝いします」と述べることで、網羅的かつオープンな印象を与えられます。
最後に、応答が流暢で、繰り返しや冗長な情報がなく、簡潔で明確であることを確認します。また、親しみやすさと専門性のバランスを保ち、ユーザーに親近感と信頼感の両方を持ってもらえるようにします。
====================Full response====================
こんにちは!〜 私は Alibaba Cloud が開発した大規模言語モデルの Qwen です。私は質問に答えたり、テキストを作成したり、論理的推論を行ったり、コードを書いたりすることができ、ユーザーにヘルプとサポートを提供することを目標としています。日常生活に関する質問でも、専門的なトピックでも、最善を尽くしてお手伝いします。何かお手伝いできることはありますか?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 com.alibaba.dashscope.utils.Constants;
public class Main {
static {
// 以下はシンガポールリージョンの base_url です。米国 (バージニア) リージョンのモデルを使用する場合は、base_url を https://dashscope-us.aliyuncs.com/api/v1 に置き換えます
// 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/api/v1 に置き換えます
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
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) {
String reasoning = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();
String content = message.getOutput().getChoices().get(0).getMessage().getContent();
if (!reasoning.isEmpty()) {
reasoningContent.append(reasoning);
if (isFirstPrint) {
System.out.println("====================Thinking process====================");
isFirstPrint = false;
}
System.out.print(reasoning);
}
if (!content.isEmpty()) {
finalContent.append(content);
if (!isFirstPrint) {
System.out.println("\n====================Full response====================");
isFirstPrint = true;
}
System.out.print(content);
}
}
private static GenerationParam buildGenerationParam(Message userMsg) {
return GenerationParam.builder()
// 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えます:.apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen-plus")
.enableThinking(true)
.incrementalOutput(true)
.resultFormat("message")
.messages(Arrays.asList(userMsg))
.build();
}
public static void streamCallWithMessage(Generation gen, Message userMsg)
throws NoApiKeyException, ApiException, InputRequiredException {
GenerationParam param = buildGenerationParam(userMsg);
Flowable<GenerationResult> result = gen.streamCall(param);
result.blockingForEach(message -> handleGenerationResult(message));
}
public static void main(String[] args) {
try {
Generation gen = new Generation();
Message userMsg = Message.builder().role(Role.USER.getValue()).content("Who are you?").build();
streamCallWithMessage(gen, userMsg);
// 最終結果を出力します。
// if (reasoningContent.length() > 0) {
// System.out.println("\n====================Full response====================");
// System.out.println(finalContent.toString());
// }
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
logger.error("An exception occurred: {}", e.getMessage());
}
System.exit(0);
}
}戻り値
====================Thinking process====================
ユーザーからの「あなたは誰ですか?」という質問に対し、事前定義された設定に基づいて回答する必要があります。まず、私のロールは Alibaba Group 製の大規模言語モデル Qwen です。会話的で、シンプルかつ分かりやすいトーンを維持します。
ユーザーは私のことを初めて知ったか、私のアイデンティティを確認したいのかもしれません。まず、私が誰であるかを直接述べ、次に質問への回答、テキスト作成、コーディングといった機能と用途を簡潔に説明します。また、ユーザーが様々な言語でのリクエストに対応できることを理解できるよう、多言語サポートについても言及します。
さらに、ガイドラインに従って人間らしいペルソナを維持するため、トーンはフレンドリーにします。絵文字を使って温かみを加えることもできます。同時に、例えば「何かお手伝いできることはありますか?」と尋ねることで、ユーザーがさらに質問したり、私の機能を使ったりするように促すことも必要です。
複雑な専門用語の使用を避け、冗長にならないよう注意します。多言語サポートや特定の機能といった重要な点を見落としていないかを確認します。応答が、会話的で簡潔であることなど、すべての要件を満たしていることを確認します。
====================Full response====================
こんにちは!私は Alibaba Group の大規模言語モデル Qwen です。質問への回答や、物語、公式ドキュメント、メール、プレイブックなどのテキスト作成ができます。また、論理的推論、コード作成、意見表明、ゲームなども可能です。中国語、英語、ドイツ語、フランス語、スペイン語をはじめとする多言語に堪能です。何かお手伝いできることはありますか?HTTP
サンプルコード
curl
# ======= 重要 =======
# 以下はシンガポールリージョンの URL です。中国 (北京) リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation に置き換えます
# 米国 (バージニア) リージョンのモデルを使用する場合は、base_url を https://dashscope-us.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": "Who are you?"
}
]
},
"parameters":{
"enable_thinking": true,
"incremental_output": true,
"result_format": "message"
}
}'応答
id:1
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"Hmm","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":14,"input_tokens":11,"output_tokens":3},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:2
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":",","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":15,"input_tokens":11,"output_tokens":4},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:3
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"the user","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":16,"input_tokens":11,"output_tokens":5},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:4
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":" asks","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":17,"input_tokens":11,"output_tokens":6},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:5
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":" '","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":18,"input_tokens":11,"output_tokens":7},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
......
id:358
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"help","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":373,"input_tokens":11,"output_tokens":362},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:359
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":",","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":374,"input_tokens":11,"output_tokens":363},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:360
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":" feel free","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":375,"input_tokens":11,"output_tokens":364},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:361
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":" to","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":376,"input_tokens":11,"output_tokens":365},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:362
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":" let me know","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":377,"input_tokens":11,"output_tokens":366},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:363
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"!","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":378,"input_tokens":11,"output_tokens":367},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:364
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"","role":"assistant"},"finish_reason":"stop"}]},"usage":{"total_tokens":378,"input_tokens":11,"output_tokens":367},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}コア機能
思考モードと非思考モードの切り替え
思考モードを有効にすると、通常、応答品質は向上しますが、応答レイテンシーとコストが増加します。ハイブリッド思考モードをサポートするモデルを使用する場合、モデルを変更することなく、質問の複雑さに応じて思考モードと非思考モードを動的に切り替えることができます:
日常的なチャットや簡単な Q&A ペアなど、複雑な推論を必要としないタスクの場合は、
enable_thinkingをfalseに設定して思考モードを無効にします。論理的推論、コード生成、数学の問題の解決など、複雑な推論を必要とするタスクの場合は、
enable_thinkingをtrueに設定して思考モードを有効にします。
OpenAI 互換
enable_thinking は標準の OpenAI パラメーターではありません。OpenAI Python SDK を使用する場合は、このパラメーターを extra_body を使用して渡してください。Node.js SDK では、トップレベルパラメーターとして渡します。
Python
サンプルコード
from openai import OpenAI
import os
# OpenAI クライアントを初期化します
client = OpenAI(
# 環境変数を設定していない場合は、以下をご利用の Model Studio API キーに置き換えてください: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下はシンガポールリージョンの base_url です。米国 (バージニア) リージョンのモデルを使用する場合は、base_url を https://dashscope-us.aliyuncs.com/compatible-mode/v1 に置き換えてください # 北京リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
# 北京リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
messages = [{"role": "user", "content": "Who are you"}]
completion = client.chat.completions.create(
model="qwen-plus",
messages=messages,
# extra_body を介して enable_thinking を設定し、思考プロセスを有効にします
extra_body={"enable_thinking": True},
stream=True,
stream_options={
"include_usage": True
},
)
reasoning_content = "" # 完全な思考プロセス
answer_content = "" # 完全な応答
is_answering = False # 応答フェーズが開始されたかどうかを示します
print("\n" + "=" * 20 + "Thinking process" + "=" * 20 + "\n")
for chunk in completion:
if not chunk.choices:
print("\n" + "=" * 20 + "Token consumption" + "=" * 20 + "\n")
print(chunk.usage)
continue
delta = chunk.choices[0].delta
# 思考コンテンツのみを収集します
if hasattr(delta, "reasoning_content") and delta.reasoning_content is not None:
if not is_answering:
print(delta.reasoning_content, end="", flush=True)
reasoning_content += delta.reasoning_content
# コンテンツが受信されると、応答を開始します
if hasattr(delta, "content") and delta.content:
if not is_answering:
print("\n" + "=" * 20 + "Full response" + "=" * 20 + "\n")
is_answering = True
print(delta.content, end="", flush=True)
answer_content += delta.content
応答
====================Thinking process====================
ユーザーは「あなたは誰ですか」と尋ねています。彼らが何を知りたいのかを理解する必要があります。初めて私と対話しているか、私の ID を確認したいのかもしれません。まず、私が Tongyi Lab によって開発された Qwen であると自己紹介から始めるべきです。次に、質問への回答、テキストの作成、プログラミングなどの私の能力を説明し、ユーザーが私がどのように役立つかを理解できるようにします。また、多言語をサポートしていることにも言及し、海外のユーザーが異なる言語でコミュニケーションできることを知らせるべきです。最後に、フレンドリに接し、さらなる対話を促すために、もっと質問するように促すべきです。ユーザーが理解しやすいように、専門用語を多用せず、簡潔かつ明確にする必要があります。ユーザーはおそらく私の能力の簡単な概要を求めているので、私の機能と用途に焦点を当てます。Alibaba Group やより技術的な詳細に言及するなど、情報を見逃していないかどうかも確認する必要があります。しかし、ユーザーはおそらく詳細な説明ではなく、基本的な情報を必要としているでしょう。私の応答がフレンドリでプロフェッショナルであり、ユーザーが質問を続けることを奨励するようにします。
====================Full response====================
私は Qwen、Tongyi Lab によって開発された大規模言語モデルです。質問への回答、テキストの作成、コードの記述、アイデアの表現をお手伝いできます。多言語での会話をサポートしています。何かお手伝いできることはありますか?
====================Token consumption====================
CompletionUsage(completion_tokens=221, prompt_tokens=10, total_tokens=231, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=None, audio_tokens=None, reasoning_tokens=172, rejected_prediction_tokens=None), prompt_tokens_details=PromptTokensDetails(audio_tokens=None, cached_tokens=0))Node.js
サンプルコード
import OpenAI from "openai";
import process from 'process';
// OpenAI クライアントを初期化します
const openai = new OpenAI({
// 環境変数を設定していない場合は、以下をご利用の Model Studio API キーに置き換えてください: apiKey: "sk-xxx"
apiKey: process.env.DASHSCOPE_API_KEY,
// 以下はシンガポールリージョンの baseURL です。米国 (バージニア) リージョンのモデルを使用する場合は、baseURL を https://dashscope-us.aliyuncs.com/compatible-mode/v1 に置き換えてください
// 北京リージョンのモデルを使用する場合は、baseURL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
baseURL: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1'
});
let reasoningContent = ''; // 完全な思考プロセス
let answerContent = ''; // 完全な応答
let isAnswering = false; // 応答フェーズが開始されたかどうかを示します
async function main() {
try {
const messages = [{ role: 'user', content: 'Who are you' }];
const stream = await openai.chat.completions.create({
model: 'qwen-plus',
messages,
// Node.js SDK では、enable_thinking のような非標準パラメーターはトップレベルプロパティとして渡され、extra_body に配置する必要はありません。
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('\n' + '='.repeat(20) + 'Token consumption' + '='.repeat(20) + '\n');
console.log(chunk.usage);
continue;
}
const delta = chunk.choices[0].delta;
// 思考コンテンツのみを収集します
if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
if (!isAnswering) {
process.stdout.write(delta.reasoning_content);
}
reasoningContent += delta.reasoning_content;
}
// コンテンツが受信されると、応答を開始します
if (delta.content !== undefined && delta.content) {
if (!isAnswering) {
console.log('\n' + '='.repeat(20) + 'Full response' + '='.repeat(20) + '\n');
isAnswering = true;
}
process.stdout.write(delta.content);
answerContent += delta.content;
}
}
} catch (error) {
console.error('Error:', error);
}
}
main();応答
====================Thinking process====================
ユーザーは「あなたは誰ですか」と尋ねています。彼らが何を知りたいのかを理解する必要があります。初めて私と対話しているか、私の ID を確認したいのかもしれません。まず、私の名前と ID、例えば Qwen、英語名 Qwen を紹介することから始めるべきです。次に、私が Alibaba Group 傘下の Tongyi Lab によって独自に開発された大規模言語モデルであることを述べるべきです。次に、質問への回答、テキストの作成、プログラミング、意見の表明など、私の能力に言及し、ユーザーが私の目的を理解できるようにします。また、多言語をサポートしていることにも言及すべきです。これは海外のユーザーにとって便利でしょう。最後に、質問するように促し、フレンドリでオープンな態度を保つべきです。専門用語を多用せず、シンプルで分かりやすい言葉を使う必要があります。ユーザーは助けを必要としているか、単に好奇心から尋ねているのかもしれないので、応答は丁寧で、さらなる対話を促すものであるべきです。さらに、ユーザーが私の能力をテストしたり、特定の助けを求めたりするなど、より深いニーズを持っている可能性があるかどうかも考慮する必要があるかもしれませんが、最初の応答は基本的な情報とガイダンスに焦点を当てるべきです。情報をより効果的にするために、会話的なトーンを保ち、複雑な文を避けます。
====================Full response====================
こんにちは!私は Qwen、Alibaba Group 傘下の Tongyi Lab によって独自に開発された大規模言語モデルです。質問への回答、テキストの作成 (物語、公式ドキュメント、メール、プレイブックなど)、論理的推論の実行、コードの記述、さらには意見の表明やゲームのプレイをお手伝いできます。中国語、英語、ドイツ語、フランス語、スペイン語を含むがこれらに限定されない多言語をサポートしています。
ご質問やお手伝いが必要な場合は、いつでもお気軽にお尋ねください!
====================Token consumption====================
{
prompt_tokens: 10,
completion_tokens: 288,
total_tokens: 298,
completion_tokens_details: { reasoning_tokens: 188 },
prompt_tokens_details: { cached_tokens: 0 }
}HTTP
サンプルコード
curl
# ======= 重要 =======
# 以下はシンガポールの base_url です。北京リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions に置き換えてください
# 米国 (バージニア) リージョンのモデルを使用する場合は、base_url を https://dashscope-us.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": "user",
"content": "Who are you"
}
],
"stream": true,
"stream_options": {
"include_usage": true
},
"enable_thinking": true
}'DashScope
Python
サンプルコード
import os
from dashscope import Generation
import dashscope
# 以下はシンガポールリージョンの base_url です。米国 (バージニア) リージョンのモデルを使用する場合は、base_url を https://dashscope-us.aliyuncs.com/api/v1 に置き換えてください
# 北京リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/api/v1 に置き換えてください
dashscope.base_http_api_url = "https://dashscope-intl.aliyuncs.com/api/v1/"
# リクエストパラメーターを初期化します
messages = [{"role": "user", "content": "Who are you?"}]
completion = Generation.call(
# 環境変数を設定していない場合は、以下をご利用の Model Studio API キーに置き換えてください: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen-plus",
messages=messages,
result_format="message", # 結果のフォーマットを message に設定します
enable_thinking=True, # 思考プロセスを有効にします
stream=True, # ストリーミング出力を有効にします
incremental_output=True, # 増分出力を有効にします
)
reasoning_content = "" # 完全な思考プロセス
answer_content = "" # 完全な応答
is_answering = False # 応答フェーズが開始されたかどうかを示します
print("\n" + "=" * 20 + "Thinking process" + "=" * 20 + "\n")
for chunk in completion:
message = chunk.output.choices[0].message
# 思考コンテンツのみを収集します
if message.reasoning_content:
if not is_answering:
print(message.reasoning_content, end="", flush=True)
reasoning_content += message.reasoning_content
# コンテンツが受信されると、応答を開始します
if message.content:
if not is_answering:
print("\n" + "=" * 20 + "Full response" + "=" * 20 + "\n")
is_answering = True
print(message.content, end="", flush=True)
answer_content += message.content
print("\n" + "=" * 20 + "Token consumption" + "=" * 20 + "\n")
print(chunk.usage)
# ループが終了した後、reasoning_content と answer_content 変数には完全なコンテンツが含まれます。
# 必要に応じて、ここで後続の処理を実行できます。
# print(f"\n\nFull thinking process:\n{reasoning_content}")
# print(f"\nFull response:\n{answer_content}")
応答
====================Thinking process====================
ユーザーは「あなたは誰ですか?」と尋ねています。彼らが何を知りたいのかを理解する必要があります。初めて私と対話しているか、私の ID を確認したいのかもしれません。まず、私が Qwen であり、Tongyi Lab によって開発された大規模言語モデルであることを自己紹介すべきです。次に、質問への回答、テキストの作成、プログラミングなど、私の能力を説明し、ユーザーが私の目的を理解できるようにする必要があるかもしれません。また、多言語をサポートしていることにも言及し、海外のユーザーが異なる言語でコミュニケーションできることを知らせるべきです。最後に、フレンドリに接し、さらなる対話を促すために、もっと質問するように促すべきです。専門用語を多用せず、シンプルで分かりやすい言葉を使う必要があります。ユーザーは私の能力をテストしたり、助けを求めたりするなど、より深いニーズを持っているかもしれないので、物語、公式ドキュメント、メールの作成などの具体的な例を挙げた方が良いでしょう。また、応答がうまく構成されていることを確認する必要があり、おそらく私の機能をリストアップする方が良いかもしれませんが、箇条書きよりも自然なトランジションの方が良いかもしれません。さらに、誤解を避けるために、私が個人的な意識を持たない AI アシスタントであり、すべての回答がトレーニングデータに基づいていることを強調すべきです。マルチモーダル機能や最近の更新など、重要な情報を見逃していないか確認する必要があるかもしれませんが、以前の応答に基づくと、あまり深く掘り下げる必要はないでしょう。要するに、応答は包括的でありながら簡潔で、フレンドリで役立つものであり、ユーザーが理解され、サポートされていると感じられるようにする必要があります。
====================Full response====================
私は Qwen、Alibaba Group 傘下の Tongyi Lab によって独自に開発された大規模言語モデルです。私は以下のことをお手伝いできます:
1. **質問への回答**:学術的な質問、一般的な知識、ドメイン固有の問題など、どのような質問にもお答えします。
2. **テキストの作成**:物語、公式ドキュメント、メール、プレイブックなどの作成をお手伝いします。
3. **論理的推論**:論理的推論や問題解決をお手伝いします。
4. **プログラミング**:さまざまなプログラミング言語のコードを理解し、生成できます。
5. **多言語サポート**:中国語、英語、ドイツ語、フランス語、スペイン語を含むがこれらに限定されない多言語をサポートしています。
ご質問やお手伝いが必要な場合は、いつでもお気軽にお尋ねください!
====================Token consumption====================
{"input_tokens": 11, "output_tokens": 405, "total_tokens": 416, "output_tokens_details": {"reasoning_tokens": 256}, "prompt_tokens_details": {"cached_tokens": 0}}Java
サンプルコード
// DashScope SDK バージョン >= 2.19.4
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import io.reactivex.Flowable;
import java.lang.System;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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) {
String reasoning = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();
String content = message.getOutput().getChoices().get(0).getMessage().getContent();
if (!reasoning.isEmpty()) {
reasoningContent.append(reasoning);
if (isFirstPrint) {
System.out.println("====================Thinking process====================");
isFirstPrint = false;
}
System.out.print(reasoning);
}
if (!content.isEmpty()) {
finalContent.append(content);
if (!isFirstPrint) {
System.out.println("\n====================Full response====================");
isFirstPrint = true;
}
System.out.print(content);
}
}
private static GenerationParam buildGenerationParam(Message userMsg) {
return GenerationParam.builder()
// 環境変数を設定していない場合は、次の行をご利用の Model Studio API キーに置き換えてください: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen-plus")
.enableThinking(true)
.incrementalOutput(true)
.resultFormat("message")
.messages(Arrays.asList(userMsg))
.build();
}
public static void streamCallWithMessage(Generation gen, Message userMsg)
throws NoApiKeyException, ApiException, InputRequiredException {
GenerationParam param = buildGenerationParam(userMsg);
Flowable<GenerationResult> result = gen.streamCall(param);
result.blockingForEach(message -> handleGenerationResult(message));
}
public static void main(String[] args) {
try {
// 以下はシンガポールリージョンの base_url です。米国 (バージニア) リージョンのモデルを使用する場合は、base_url を https://dashscope-us.aliyuncs.com/api/v1 に置き換えてください
// 北京リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/api/v1 に置き換えてください
Generation gen = new Generation("http", "https://dashscope-intl.aliyuncs.com/api/v1");
Message userMsg = Message.builder().role(Role.USER.getValue()).content("Who are you?").build();
streamCallWithMessage(gen, userMsg);
// 最終結果を出力します。
// if (reasoningContent.length() > 0) {
// System.out.println("\n====================Full response====================");
// System.out.println(finalContent.toString());
// }
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
logger.error("An exception occurred: {}", e.getMessage());
}
System.exit(0);
}
}戻り値
====================Thinking process====================
ユーザーは「あなたは誰ですか?」と尋ねています。彼らが何を知りたいのかを理解する必要があります。彼らは私の ID を知りたいのか、私の応答をテストしているのかもしれません。まず、私が Alibaba Group の大規模言語モデルである Qwen であることを明確に述べるべきです。次に、質問への回答、テキストの作成、プログラミングなど、私の能力を簡単に紹介し、ユーザーが私の目的を理解できるようにする必要があるかもしれません。また、多言語をサポートしていることにも言及し、海外のユーザーが異なる言語でコミュニケーションできることを知らせるべきです。最後に、フレンドリに接し、質問するように促すことで、彼らが歓迎されていると感じ、対話を続けたいと思うようにすべきです。回答が長すぎず、しかし包括的であることを確認する必要があります。ユーザーは私の技術的な詳細やユースケースなど、フォローアップの質問をするかもしれませんが、最初の応答は簡潔で明確であるべきです。すべてのユーザーが理解できるように、専門用語を使わないようにします。多言語サポートや私の機能の具体例など、重要な情報を見逃していないか確認します。これでユーザーのニーズはカバーできるはずです。
====================Full response====================
私は Alibaba Group の大規模言語モデルである Qwen です。質問への回答、テキストの作成 (物語、公式ドキュメント、メール、プレイブックなど)、論理的推論の実行、コードの記述、意見の表明、ゲームのプレイなどができます。中国語、英語、ドイツ語、フランス語、スペイン語を含むがこれらに限定されない多言語での会話をサポートしています。ご質問やお手伝いが必要な場合は、いつでもお気軽にお尋ねください!HTTP
サンプルコード
curl
# ======= 重要 =======
# 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation に置き換えてください
# 米国 (バージニア) リージョンのモデルを使用する場合は、base_url を https://dashscope-us.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": "Who are you?"
}
]
},
"parameters":{
"enable_thinking": true,
"incremental_output": true,
"result_format": "message"
}
}'応答
id:1
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"Hmm","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":14,"input_tokens":11,"output_tokens":3},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:2
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":",","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":15,"input_tokens":11,"output_tokens":4},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:3
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"the user","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":16,"input_tokens":11,"output_tokens":5},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:4
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":" asks","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":17,"input_tokens":11,"output_tokens":6},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:5
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":" '","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":18,"input_tokens":11,"output_tokens":7},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
......
id:358
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"help","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":373,"input_tokens":11,"output_tokens":362},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:359
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":",","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":374,"input_tokens":11,"output_tokens":363},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:360
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":" feel free","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":375,"input_tokens":11,"output_tokens":364},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:361
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":" to","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":376,"input_tokens":11,"output_tokens":365},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:362
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":" let me know","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":377,"input_tokens":11,"output_tokens":366},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:363
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"!","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":378,"input_tokens":11,"output_tokens":367},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:364
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"","role":"assistant"},"finish_reason":"stop"}]},"usage":{"total_tokens":378,"input_tokens":11,"output_tokens":367},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}さらに、オープンソースの Qwen3 エディション、qwen-plus-2025-04-28、および qwen-turbo-2025-04-28 のハイブリッド思考モデルは、プロンプトを使用して思考モードを動的に制御するメソッドを提供します。enable_thinking が true の場合、プロンプトに /no_think を追加して思考モードを無効にします。マルチターン対話で思考モードを再度有効にするには、最新の入力プロンプトに /think を追加します。モデルは、最新の /think または /no_think 命令に従います。
思考の長さの制限
ディープシンキングモデルは、長い思考プロセスを生成することがあります。これにより、待機時間が増加し、より多くのトークンが消費されます。思考プロセスの最大トークン数を制限するには、thinking_budget パラメーターを使用します。上限を超えると、モデルはすぐに応答を生成します。
thinking_budget パラメーターは、モデルの思考連鎖の最大長を指定します。詳細については、「モデルリスト」をご参照ください。thinking_budget パラメーターは、Qwen3 (思考モード)および Kimi モデルでサポートされています。
OpenAI 互換
Python
サンプルコード
from openai import OpenAI
import os
# OpenAI クライアントを初期化します
client = OpenAI(
# 環境変数を設定していない場合は、以下を Model Studio API キーに置き換えてください: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下はシンガポールリージョンの base_url です。米国 (バージニア) リージョンのモデルを使用する場合は、base_url を https://dashscope-us.aliyuncs.com/compatible-mode/v1 に置き換えてください # 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
# 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
messages = [{"role": "user", "content": "Who are you"}]
completion = client.chat.completions.create(
model="qwen-plus",
messages=messages,
# enable_thinking パラメーターは思考プロセスを有効にし、thinking_budget パラメーターは思考プロセスの最大トークン数を設定します。
extra_body={
"enable_thinking": True,
"thinking_budget": 50
},
stream=True,
stream_options={
"include_usage": True
},
)
reasoning_content = "" # 完全な思考プロセス
answer_content = "" # 完全な応答
is_answering = False # 応答フェーズが開始されたかどうかを示します
print("\n" + "=" * 20 + "思考プロセス" + "=" * 20 + "\n")
for chunk in completion:
if not chunk.choices:
print("\nUsage:")
print(chunk.usage)
continue
delta = chunk.choices[0].delta
# 思考コンテンツのみを収集します
if hasattr(delta, "reasoning_content") and delta.reasoning_content is not None:
if not is_answering:
print(delta.reasoning_content, end="", flush=True)
reasoning_content += delta.reasoning_content
# コンテンツが受信されたら、応答を開始します
if hasattr(delta, "content") and delta.content:
if not is_answering:
print("\n" + "=" * 20 + "完全な応答" + "=" * 20 + "\n")
is_answering = True
print(delta.content, end="", flush=True)
answer_content += delta.content応答
====================思考プロセス====================
ユーザーからの「あなたは誰ですか」という質問に対し、明確でフレンドリーな応答を返す必要があります。まず、自身のアイデンティティ、つまり Alibaba Group 傘下の Tongyi Lab によって開発された Qwen であることを伝えます。次に、質問応答などの主要な機能を説明します
====================完全な応答====================
私は Qwen、Alibaba Group の Tongyi Lab によって開発された大規模言語モデルです。質問への回答、テキストの作成、論理的推論、コーディングなどが可能で、ユーザーの皆様に役立つ便利な機能を提供することを目指しています。何かお手伝いできることはありますか?Node.js
サンプルコード
import OpenAI from "openai";
import process from 'process';
// OpenAI クライアントを初期化します
const openai = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY, // 環境変数から読み取ります
// 以下はシンガポールリージョンの base_url です。米国 (バージニア) リージョンのモデルを使用する場合は、base_url を https://dashscope-us.aliyuncs.com/compatible-mode/v1 に置き換えてください
// 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
baseURL: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1'
});
let reasoningContent = '';
let answerContent = '';
let isAnswering = false;
async function main() {
try {
const messages = [{ role: 'user', content: 'Who are you' }];
const stream = await openai.chat.completions.create({
model: 'qwen-plus',
messages,
stream: true,
// enable_thinking パラメーターは思考プロセスを有効にし、thinking_budget パラメーターは思考プロセスの最大トークン数を設定します。
enable_thinking: true,
thinking_budget: 50
});
console.log('\n' + '='.repeat(20) + '思考プロセス' + '='.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 !== undefined && delta.reasoning_content !== null) {
if (!isAnswering) {
process.stdout.write(delta.reasoning_content);
}
reasoningContent += delta.reasoning_content;
}
// コンテンツが受信されたら、応答を開始します
if (delta.content !== undefined && delta.content) {
if (!isAnswering) {
console.log('\n' + '='.repeat(20) + '完全な応答' + '='.repeat(20) + '\n');
isAnswering = true;
}
process.stdout.write(delta.content);
answerContent += delta.content;
}
}
} catch (error) {
console.error('エラー:', error);
}
}
main();応答
====================思考プロセス====================
ユーザーからの「あなたは誰ですか」という質問に対し、明確で正確な応答を返す必要があります。まず、自身のアイデンティティ、つまり Alibaba Group 傘下の Tongyi Lab によって開発された Qwen であることを紹介します。次に、質問応答などの主要な機能を説明します
====================完全な応答====================
私は Qwen、Alibaba Group 傘下の Tongyi Lab が独自に開発した超大規模言語モデルです。質問への回答、テキストの作成、論理的推論、コーディングなど、様々なタスクを実行できます。ご質問やサポートが必要な場合は、お気軽にお知らせください!HTTP
サンプルコード
curl
# ======= 重要 =======
# 以下はシンガポールの base_url です。中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions に置き換えてください
# 米国 (バージニア) リージョンのモデルを使用する場合は、base_url を https://dashscope-us.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": "user",
"content": "Who are you"
}
],
"stream": true,
"stream_options": {
"include_usage": true
},
"enable_thinking": true,
"thinking_budget": 50
}'応答
data: {"choices":[{"delta":{"content":null,"role":"assistant","reasoning_content":""},"index":0,"logprobs":null,"finish_reason":null}],"object":"chat.completion.chunk","usage":null,"created":1745485391,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503"}
.....
data: {"choices":[{"finish_reason":"stop","delta":{"content":"","reasoning_content":null},"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1745485391,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503"}
data: {"choices":[],"object":"chat.completion.chunk","usage":{"prompt_tokens":10,"completion_tokens":360,"total_tokens":370},"created":1745485391,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503"}
data: [DONE]DashScope
Python
サンプルコード
import os
from dashscope import Generation
import dashscope
# 以下はシンガポールリージョンの base_url です。米国 (バージニア) リージョンのモデルを使用する場合は、base_url を https://dashscope-us.aliyuncs.com/api/v1 に置き換えてください
# 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/api/v1 に置き換えてください
dashscope.base_http_api_url = "https://dashscope-intl.aliyuncs.com/api/v1/"
messages = [{"role": "user", "content": "Who are you?"}]
completion = Generation.call(
# 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えてください: api_key = "sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen-plus",
messages=messages,
result_format="message",
enable_thinking=True,
# 思考プロセスの最大トークン数を設定します。
thinking_budget=50,
stream=True,
incremental_output=True,
)
# 完全な思考プロセスを定義します。
reasoning_content = ""
# 完全な応答を定義します。
answer_content = ""
# 思考プロセスが終了し、応答が開始されたかどうかを判断します。
is_answering = False
print("=" * 20 + "思考プロセス" + "=" * 20)
for chunk in completion:
# 思考プロセスと応答の両方が空の場合は無視します。
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 + "完全な応答" + "=" * 20)
is_answering = True
print(chunk.output.choices[0].message.content, end="", flush=True)
answer_content += chunk.output.choices[0].message.content
# 完全な思考プロセスと完全な応答を出力するには、次のコードのコメントを解除して実行します。
# print("=" * 20 + "完全な思考プロセス" + "=" * 20 + "\n")
# print(f"{reasoning_content}")
# print("=" * 20 + "完全な応答" + "=" * 20 + "\n")
# print(f"{answer_content}")
戻り値
====================思考プロセス====================
ユーザーが「あなたは誰ですか」と尋ねているので、明確でフレンドリーな応答を返す必要があります。まず、自身のアイデンティティ、つまり Alibaba Group 傘下の Tongyi Lab によって開発された Qwen であることを紹介します。次に、主要な機能などを説明します
====================完全な応答====================
私は Qwen、Alibaba Group の Tongyi Lab が独自に開発した大規模言語モデルです。質問への回答、テキストの作成、論理的推論、コーディングなどが可能で、ユーザーの皆様に包括的で正確、かつ有用な情報と支援を提供することを目指しています。何かお手伝いできることはありますか?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 com.alibaba.dashscope.utils.Constants;
public class Main {
static {
// 以下はシンガポールリージョンの base_url です。米国 (バージニア) リージョンのモデルを使用する場合は、base_url を https://dashscope-us.aliyuncs.com/api/v1 に置き換えてください
// 中国 (北京) リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/api/v1 に置き換えてください
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
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) {
String reasoning = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();
String content = message.getOutput().getChoices().get(0).getMessage().getContent();
if (!reasoning.isEmpty()) {
reasoningContent.append(reasoning);
if (isFirstPrint) {
System.out.println("====================思考プロセス====================");
isFirstPrint = false;
}
System.out.print(reasoning);
}
if (!content.isEmpty()) {
finalContent.append(content);
if (!isFirstPrint) {
System.out.println("\n====================完全な応答====================");
isFirstPrint = true;
}
System.out.print(content);
}
}
private static GenerationParam buildGenerationParam(Message userMsg) {
return GenerationParam.builder()
// 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えてください: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen-plus")
.enableThinking(true)
.thinkingBudget(50)
.incrementalOutput(true)
.resultFormat("message")
.messages(Arrays.asList(userMsg))
.build();
}
public static void streamCallWithMessage(Generation gen, Message userMsg)
throws NoApiKeyException, ApiException, InputRequiredException {
GenerationParam param = buildGenerationParam(userMsg);
Flowable<GenerationResult> result = gen.streamCall(param);
result.blockingForEach(message -> handleGenerationResult(message));
}
public static void main(String[] args) {
try {
Generation gen = new Generation();
Message userMsg = Message.builder().role(Role.USER.getValue()).content("Who are you?").build();
streamCallWithMessage(gen, userMsg);
// 最終結果を出力します。
// if (reasoningContent.length() > 0) {
// System.out.println("\n====================完全な応答====================");
// System.out.println(finalContent.toString());
// }
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
logger.error("例外が発生しました: {}", e.getMessage());
}
System.exit(0);
}
}応答
====================思考プロセス====================
ユーザーが「あなたは誰ですか」と尋ねているので、明確でフレンドリーな応答を返す必要があります。まず、自身のアイデンティティ、つまり Alibaba Group 傘下の Tongyi Lab によって開発された Qwen であることを紹介します。次に、主要な機能などを説明します
====================完全な応答====================
私は Qwen、Alibaba Group の Tongyi Lab が独自に開発した大規模言語モデルです。質問への回答、テキストの作成、論理的推論、コーディングなどが可能で、ユーザーの皆様に包括的で正確、かつ有用な情報と支援を提供することを目指しています。何かお手伝いできることはありますか?HTTP
サンプルコード
curl
# ======= 重要 =======
# 以下はシンガポールリージョンの URL です。中国 (北京) リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation に置き換えてください
# 米国 (バージニア) リージョンのモデルを使用する場合は、base_url を https://dashscope-us.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": "Who are you?"
}
]
},
"parameters":{
"enable_thinking": true,
"thinking_budget": 50,
"incremental_output": true,
"result_format": "message"
}
}'戻り値
id:1
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"Okay","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":14,"output_tokens":3,"input_tokens":11,"output_tokens_details":{"reasoning_tokens":1}},"request_id":"2ce91085-3602-9c32-9c8b-fe3d583a2c38"}
id:2
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":",","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":15,"output_tokens":4,"input_tokens":11,"output_tokens_details":{"reasoning_tokens":2}},"request_id":"2ce91085-3602-9c32-9c8b-fe3d583a2c38"}
......
id:133
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"!","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":149,"output_tokens":138,"input_tokens":11,"output_tokens_details":{"reasoning_tokens":50}},"request_id":"2ce91085-3602-9c32-9c8b-fe3d583a2c38"}
id:134
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"","role":"assistant"},"finish_reason":"stop"}]},"usage":{"total_tokens":149,"output_tokens":138,"input_tokens":11,"output_tokens_details":{"reasoning_tokens":50}},"request_id":"2ce91085-3602-9c32-9c8b-fe3d583a2c38"}その他の機能
課金詳細
思考プロセスは、出力トークンに基づいて課金されます。
一部のハイブリッド思考モデルでは、思考モードと非思考モードで料金が異なります。
思考モードのモデルが思考プロセスを出力しない場合、非思考モードの料金で課金されます。
よくある質問
Q: 思考モードを無効にする方法
Q: 非ストリーミング出力をサポートしているモデル
Q: トークンは、無料クォータ を使い切った後、どのように購入しますか?
Q: 画像やドキュメントをアップロードして質問できますか?
Q: トークンの消費量と呼び出し回数を表示する方法
API リファレンス
ディープシンキングモデルの入出力パラメーターの詳細については、Qwen をご参照ください。
エラーコード
エラーが発生した場合のトラブルシューティングについては、「エラーメッセージ」をご参照ください。
