コードインタープリターは、モデルがサンドボックス環境で Python コードを記述・実行できるようにし、数学的計算やデータ分析などの複雑な課題を解決します。
使用方法
以下のいずれかのパラメーター構成を用いて、コードインタープリターを有効化します。
OpenAI 互換 — Responses API
tools パラメーターを追加し、code_interpreter ツールを含めます。
最適な結果を得るため、code_interpreter、web_search、およびweb_extractorの各ツールを同時に有効化することを推奨します。
# 依存関係をインポートしてクライアントを作成...
response = client.responses.create(
model="qwen3-max-2026-01-23",
input="123 の 21 乗はいくつですか?",
tools=[
{"type": "code_interpreter"},
{"type": "web_search"},
{"type": "web_extractor"},
],
extra_body={
"enable_thinking": True
}
)
print(response.output_text)
OpenAI 互換 — Chat Completions API
API リクエストで enable_code_interpreter: true を設定します。
# 依存関係をインポートしてクライアントを作成...
completion = client.chat.completions.create(
# コードインタープリターをサポートするモデルを使用
model="qwen3-max-2026-01-23",
messages=[{"role": "user", "content": "123 の 21 乗はいくつですか?"}],
# enable_code_interpreter は標準の OpenAI パラメーターではないため、Python SDK を使用する場合は extra_body 経由で渡します(Node.js SDK の場合はトップレベルパラメーターとして渡します)
extra_body={
"enable_code_interpreter": True,
# コードインタープリターには思考モードが必要です
"enable_thinking": True,
},
# ストリーミング出力のみ
stream=True
)
OpenAI 互換 API では、インタープリターが実行したコードは返されません。
DashScope
enable_code_interpreter を true に設定します。
# 依存関係をインポート...
response = dashscope.Generation.call(
# 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えます:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen3-max-2026-01-23",
messages=[{"role": "user", "content": "123 の 21 乗はいくつですか?"}],
# コードインタープリターを有効化
enable_code_interpreter=True,
# コードインタープリターには思考モードが必要です
enable_thinking=True,
result_format="message",
# ストリーミング出力のみ
stream=True
)
インタープリターが実行したコードは、tool_info フィールドで返されます。
有効化後、モデルはリクエストを以下のフェーズで処理します。
-
思考:モデルがリクエストを分析し、解決手法を決定します。
-
コード実行:モデルが Python コードを生成・実行します。
-
結果統合:モデルが実行結果を処理し、次のステップを判断します。
-
応答:モデルが自然言語による応答を生成します。
ステップ 2 および 3 は複数回繰り返される場合があります。
各 API は異なるフィールドを返します。
-
Responses API:思考内容は type="reasoning" の出力項目で返され、コード実行の詳細は type="code_interpreter_call" で返され、最終応答は type="message" で返されます。
-
Chat Completions API および DashScope:思考内容は reasoning_content フィールドで返され、応答は content フィールドで返されます。DashScope では、さらに tool_info フィールドでコードの詳細も返されます。
適用範囲
国際
-
Qwen-Max:思考モードでの qwen3-max および qwen3-max-2026-01-23
-
Qwen-Plus:qwen3.5-plus、qwen3.5-plus-2026-02-15
-
Qwen-Flash:qwen3.5-flash、qwen3.5-flash-2026-02-23
-
オープンソース Qwen:qwen3.5-397b-a17b、qwen3.5-122b-a10b、qwen3.5-27b、qwen3.5-35b-a3b
グローバル
-
Qwen-Plus:qwen3.5-plus、qwen3.5-plus-2026-02-15
-
Qwen-Flash:qwen3.5-flash、qwen3.5-flash-2026-02-23
-
オープンソース Qwen:qwen3.5-397b-a17b、qwen3.5-122b-a10b、qwen3.5-27b、qwen3.5-35b-a3b
中国本土
-
Qwen-Max:思考モードでの qwen3-max、qwen3-max-2026-01-23、および qwen3-max-preview
-
Qwen-Plus:qwen3.5-plus、qwen3.5-plus-2026-02-15
-
Qwen-Flash:qwen3.5-flash、qwen3.5-flash-2026-02-23
-
オープンソース Qwen:qwen3.5-397b-a17b、qwen3.5-122b-a10b、qwen3.5-27b、qwen3.5-35b-a3b
クイックスタート
以下の例では、コードインタープリターによる数学的計算の処理方法を示します。
OpenAI 互換 — Responses API
最適な結果を得るため、code_interpreter、web_search、およびweb_extractorの各ツールを同時に有効化することを推奨します。
import os
from openai import OpenAI
client = OpenAI(
# 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えます:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1"
)
response = client.responses.create(
model="qwen3-max-2026-01-23",
input="12 の 3 乗はいくつですか?",
tools=[
{
"type": "code_interpreter"
},
{
"type": "web_search"
},
{
"type": "web_extractor"
}
],
extra_body = {
"enable_thinking": True
}
)
# 中間出力を確認する場合は、次の行のコメントを解除してください
# print(response.output)
print("="*20+"応答"+"="*20)
print(response.output_text)
print("="*20+"トークン使用量およびツール呼び出し数"+"="*20)
print(response.usage)import OpenAI from "openai";
import process from 'process';
const openai = new OpenAI({
// 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えます:apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://dashscope.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1"
});
async function main() {
const response = await openai.responses.create({
model: "qwen3-max-2026-01-23",
input: "12 の 3 乗はいくつですか?",
tools: [
{ type: "code_interpreter" },
{ type: "web_search" },
{ type: "web_extractor" }
],
enable_thinking: true
});
console.log("====================応答====================");
console.log(response.output_text);
// ツール呼び出し数を表示
console.log("====================トークン使用量およびツール呼び出し数====================");
if (response.usage && response.usage.x_tools) {
console.log(`コードインタープリター実行回数: ${response.usage.x_tools.code_interpreter?.count || 0}`);
}
// 中間出力を確認する場合は、次の行のコメントを解除してください
// console.log(JSON.stringify(response.output[0], null, 2));
}
main();curl -X POST https://dashscope.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3-max-2026-01-23",
"input": "12 の 3 乗はいくつですか?",
"tools": [
{"type": "code_interpreter"},
{"type": "web_search"},
{"type": "web_extractor"}
],
"enable_thinking": true
}'応答例
====================応答====================
12 の 3 乗は **1728** です。
計算式:
12³ = 12 × 12 × 12 = 144 × 12 = 1728
====================トークン使用量およびツール呼び出し数====================
ResponseUsage(input_tokens=1160, input_tokens_details=InputTokensDetails(cached_tokens=0), output_tokens=195, output_tokens_details=OutputTokensDetails(reasoning_tokens=105), total_tokens=1355, x_tools={'code_interpreter': {'count': 1}})
OpenAI 互換 — Chat Completions API
Python
from openai import OpenAI
import os
# OpenAI クライアントを初期化
client = OpenAI(
# 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えます:api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 国際リージョン向けには「https://dashscope-intl.aliyuncs.com/compatible-mode/v1」を使用
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
messages = [{"role": "user", "content": "123 の 21 乗はいくつですか?"}]
completion = client.chat.completions.create(
model="qwen3-max-2026-01-23",
messages=messages,
extra_body={"enable_thinking": True, "enable_code_interpreter": 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
# 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応答例
====================思考プロセス====================
ユーザーは 123 の 21 乗を尋ねています。これは数学的な計算問題であり、123^21 を計算する必要があります。
この値を計算するためにコードインタープリターを使用できます。Python コードを実行する code_interpreter 関数を呼び出し、123**21 を計算します。
この関数呼び出しを構築しましょう。
ユーザーは 123 の 21 乗を尋ねており、私は Python コードを使用してその結果を計算しました。結果は 123 の 21 乗が 77269364466549865653073473388030061522211723 であることを示しています。これは非常に大きな数です。これを直接提示すべきです。
====================完全な応答====================
123 の 21 乗は:77269364466549865653073473388030061522211723
使用量:
CompletionUsage(completion_tokens=245, prompt_tokens=719, total_tokens=964, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=None, audio_tokens=None, reasoning_tokens=153, rejected_prediction_tokens=None), prompt_tokens_details=None)
Node.js
import OpenAI from "openai";
import process from 'process';
// OpenAI クライアントを初期化
const openai = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY, // 環境変数から読み込み
// 国際リージョン向けには https://dashscope-intl.aliyuncs.com/compatible-mode/v1 を使用
baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1'
});
let reasoningContent = '';
let answerContent = '';
let isAnswering = false;
async function main() {
try {
const messages = [{ role: 'user', content: '123 の 21 乗はいくつですか?' }];
const stream = await openai.chat.completions.create({
model: 'qwen3-max-2026-01-23',
messages,
stream: true,
enable_thinking: true,
enable_code_interpreter: 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;
}
// 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();応答例
====================思考プロセス====================
ユーザーは 123 を 21 乗した値を尋ねています。これは Python のコードインタープリターで実行可能な数学的計算です。指数演算子 ** を使ってこの計算を行います。
123**21 を計算するコードを記述しましょう。計算は正常に完了しました。123 の 21 乗の結果は非常に大きな数で、77269364466549865653073473388030061522211723 です。
この結果をユーザーに明確に提示する必要があります。
====================完全な応答====================
123 の 21 乗は:77269364466549865653073473388030061522211723
curl
# 国際リージョン向けには https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions を使用
curl -X POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3-max-2026-01-23",
"messages": [
{
"role": "user",
"content": "123 の 21 乗はいくつですか?"
}
],
"enable_code_interpreter": true,
"enable_thinking": true,
"stream": true
}'
応答例
data: {"choices":[{"delta":{"content":null,"role":"assistant","reasoning_content":""},"index":0,"logprobs":null,"finish_reason":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3-max-2026-01-23","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
data: {"choices":[{"finish_reason":null,"logprobs":null,"delta":{"content":null,"reasoning_content":"ユーザー"},"index":0}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3-max-2026-01-23","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
data: {"choices":[{"delta":{"content":null,"reasoning_content":"は"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3-max-2026-01-23","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
data: {"choices":[{"delta":{"content":null,"reasoning_content":"、"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3-max-2026-01-23","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
...
data: {"choices":[{"delta":{"content":"非常に大きな数で、合計","reasoning_content":null},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3-max-2026-01-23","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
data: {"choices":[{"delta":{"content":"43 桁です","reasoning_content":null},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3-max-2026-01-23","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
data: {"choices":[{"delta":{"content":"。","reasoning_content":null},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3-max-2026-01-23","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
data: {"choices":[{"finish_reason":"stop","delta":{"content":"","reasoning_content":null},"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3-max-2026-01-23","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
data: [DONE]
DashScope
Java SDK はサポートされていません。
Python
import os
import dashscope
# 国際リージョン向けには、次の行のコメントを解除してください
# dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [
{"role": "user", "content": "123 の 21 乗はいくつですか?"},
]
response = dashscope.Generation.call(
# 環境変数を設定していない場合は、次の行を Model Studio API キーに置き換えます:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen3-max-2026-01-23",
messages=messages,
enable_code_interpreter=True,
enable_thinking=True,
result_format="message",
# ストリーミング出力のみ
stream=True
)
for chunk in response:
output = chunk["output"]
print(output)応答例
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": "The"}}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": " user is asking"}}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": " me"}}]}
...
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": " I'll write a"}}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": " simple Python program to calculate"}}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": ""}}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": ""}}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": ""}}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": ""}}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": ""}}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": "The"}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": " user"}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": " asked"}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
...
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": " I should present this result"}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": " to the user in"}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "", "reasoning_content": " a clear format."}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "123 to the power of ", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "21 is:\n\n", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "772693", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "644665", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "498656", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "530734", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "733880", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "300615", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "222117", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "23", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "stop", "message": {"role": "assistant", "content": "", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
curl
curl -X POST https://dashscope.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": "qwen3-max-2026-01-23",
"input":{
"messages":[
{
"role": "user",
"content": "123 の 21 乗はいくつですか?"
}
]
},
"parameters": {
"enable_code_interpreter": true,
"enable_thinking": true,
"result_format": "message"
}
}'
応答例
<...テキスト内容...> は処理フェーズを識別する説明コメントであり、実際の API 応答の一部ではありません。
id:1
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"The","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":290,"output_tokens":3,"input_tokens":287,"output_tokens_details":{"reasoning_tokens":1}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}
id:2
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":" user is asking","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":293,"output_tokens":6,"input_tokens":287,"output_tokens_details":{"reasoning_tokens":4}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}
...思考フェーズ...
id:21
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":388,"output_tokens":101,"input_tokens":287,"output_tokens_details":{"reasoning_tokens":68}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}
...思考フェーズ終了、コードインタープリター起動...
id:22
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"","role":"assistant"},"finish_reason":"null"}],"tool_info":[{"code_interpreter":{"code":"123**21"},"type":"code_interpreter"}]},"usage":{"total_tokens":388,"output_tokens":101,"input_tokens":287,"output_tokens_details":{"reasoning_tokens":68},"plugins":{"code_interpreter":{"count":1}}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}
...コードインタープリター実行後の思考フェーズ...
id:23
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"The","role":"assistant"},"finish_reason":"null"}],"tool_info":[{"code_interpreter":{"code":"123**21"},"type":"code_interpreter"}]},"usage":{"total_tokens":838,"output_tokens":104,"input_tokens":734,"output_tokens_details":{"reasoning_tokens":69},"plugins":{"code_interpreter":{"count":1}}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}
id:24
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":" user","role":"assistant"},"finish_reason":"null"}],"tool_info":[{"code_interpreter":{"code":"123**21"},"type":"code_interpreter"}]},"usage":{"total_tokens":839,"output_tokens":105,"input_tokens":734,"output_tokens_details":{"reasoning_tokens":70},"plugins":{"code_interpreter":{"count":1}}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}
...思考フェーズ...
id:43
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":" a clear format.","role":"assistant"},"finish_reason":"null"}],"tool_info":[{"code_interpreter":{"code":"123**21"},"type":"code_interpreter"}]},"usage":{"total_tokens":942,"output_tokens":208,"input_tokens":734,"output_tokens_details":{"reasoning_tokens":171},"plugins":{"code_interpreter":{"count":1}}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}
...思考フェーズ終了、応答フェーズ開始...
id:44
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"123 to the power of ","reasoning_content":"","role":"assistant"},"finish_reason":"null"}],"tool_info":[{"code_interpreter":{"code":"123**21"},"type":"code_interpreter"}]},"usage":{"total_tokens":947,"output_tokens":213,"input_tokens":734,"output_tokens_details":{"reasoning_tokens":171},"plugins":{"code_interpreter":{"count":1}}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}
...
id:53
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"23","reasoning_content":"","role":"assistant"},"finish_reason":"null"}],"tool_info":[{"code_interpreter":{"code":"123**21"},"type":"code_interpreter"}]},"usage":{"total_tokens":997,"output_tokens":263,"input_tokens":734,"output_tokens_details":{"reasoning_tokens":171},"plugins":{"code_interpreter":{"count":1}}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}
id:54
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"","role":"assistant"},"finish_reason":"stop"}],"tool_info":[{"code_interpreter":{"code":"123**21"},"type":"code_interpreter"}]},"usage":{"total_tokens":997,"output_tokens":263,"input_tokens":734,"output_tokens_details":{"reasoning_tokens":171},"plugins":{"code_interpreter":{"count":1}}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}
応答の解析
OpenAI 互換 Responses API
以下の例では、OpenAI Python SDK を使用して、ストリーミング応答から API のデータを解析する方法を示します。
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope-intl.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1"
)
response = client.responses.create(
model="qwen3-max-2026-01-23",
input="12 の 3 乗",
tools=[
{"type": "code_interpreter"}
],
extra_body={
"enable_thinking": True
},
stream=True
)
def print_section(title):
print(f"\n{'=' * 20}{title}{'=' * 20}")
current_section = None
final_response = None
for event in response:
# 推論プロセスの増分出力
if event.type == "response.reasoning_summary_text.delta":
if current_section != "reasoning":
print_section("思考プロセス")
current_section = "reasoning"
print(event.delta, end="", flush=True)
# コードインタープリター呼び出しが完了
elif event.type == "response.output_item.done" and hasattr(event.item, "code"):
print_section("コード実行")
print(f"コード:\n{event.item.code}")
if event.item.outputs:
print(f"結果: {event.item.outputs[0].logs}")
current_section = "code"
# 最終応答の増分出力
elif event.type == "response.output_text.delta":
if current_section != "answer":
print_section("完全な応答")
current_section = "answer"
print(event.delta, end="", flush=True)
# 応答が完了。使用量データを取得するために最終結果を保存。
elif event.type == "response.completed":
final_response = event.response
# 使用量とツール呼び出し数を出力。
if final_response and final_response.usage:
print_section("トークン使用量およびツール呼び出し数")
usage = final_response.usage
print(f"入力トークン数: {usage.input_tokens}")
print(f"出力トークン数: {usage.output_tokens}")
print(f"思考トークン数: {usage.output_tokens_details.reasoning_tokens}")
print(f"コードインタープリター呼び出し回数: {usage.x_tools.get('code_interpreter', {}).get('count', 0)}")DashScope
この DashScope Python SDK の例では、単一のリクエストで 2 回の計算を実行し、コードおよび総呼び出し回数を返す方法を示します。
OpenAI Chat Completions API では、コード実行フェーズ中のデータは返されません。これにより、思考フェーズと結果統合フェーズの間に応答のギャップが生じます。両方のフェーズが reasoning_content フィールドを通じてコンテンツを返すため、これらを 思考フェーズの一部とみなすことができます。応答の解析例については、「クイックスタート」のコードをご参照ください。import os
from dashscope import Generation
# 国際リージョンのモデルを使用する場合は、次の行のコメントを解除してください。
# dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [{"role": "user", "content": "コードインタープリターを 2 回実行します。まず、123 の 23 乗の値を計算します。次に、その結果を 5 で割ります。"}]
response = Generation.call(
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen3-max-2026-01-23",
messages=messages,
result_format="message",
enable_thinking=True,
enable_code_interpreter=True,
stream=True,
incremental_output=True,
)
# ステータスフラグ:ツール情報の出力状況、応答フェーズの開始状況、思考セクション内の処理状況を追跡します。
is_answering = False
in_reasoning_section = False
cur_tools = []
# セクションタイトルを出力します。
def print_section(title):
print(f"\n{'=' * 20}{title}{'=' * 20}")
# 処理開始時に「思考プロセス」のタイトルを出力します。
print_section("思考プロセス")
in_reasoning_section = True
# モデルからストリームで返される各データブロックを処理します。
for chunk in response:
try:
# 応答から重要なフィールドを抽出:content、reasoning_content、およびツール呼び出し情報。
choice = chunk.output.choices[0]
msg = choice.message
content = msg.get("content", "") # 最終応答のコンテンツ
reasoning = msg.get("reasoning_content", "") # 思考プロセスのテキスト
tools = chunk.output.get("tool_info", None) # ツール呼び出し情報
except (IndexError, AttributeError, KeyError):
# 構造が異常なデータブロックはスキップします。
continue
# 有効なコンテンツがない場合は、現在のブロックをスキップします。
if not content and not reasoning and tools is None:
continue
# 思考プロセスを出力します。
if reasoning and not is_answering:
if not in_reasoning_section:
print_section("思考プロセス")
in_reasoning_section = True
print(reasoning, end="", flush=True)
if tools is not None and tools != cur_tools:
print_section("ツール情報")
print(tools)
in_reasoning_section = False
cur_tools = tools
# 最終応答のコンテンツを出力します。
if content:
if not is_answering:
print_section("完全な応答")
is_answering = True
in_reasoning_section = False
print(content, end="", flush=True)
# コードインタープリターの実行回数を出力します。
print_section("コードインタープリター実行回数")
print(chunk.usage.plugins)応答例
====================思考プロセス====================
ユーザーはコードインタープリターを 2 回実行するよう依頼しました:
1. 最初の実行:123 の 23 乗の値を計算します。
2. 2 回目の実行:最初の実行の結果を 5 で割ります。
まず、123**23 を計算するためにコードインタープリターを呼び出す必要があります。その後、この結果を使って、5 で割るためのコードインタープリターを再度呼び出します。
最初の計算を実行しましょう。
====================ツール情報====================
[{'code_interpreter': {'code': '123**23'}, 'type': 'code_interpreter'}]
====================思考プロセス====================
最初の計算の結果は、123 の 23 乗が 1169008215014432917465348578887506800769541157267 であることを示しています。
次に、2 回目の実行では、この結果を 5 で割る必要があります。正確な値を用いて除算を行う必要があります。
====================ツール情報====================
[{'code_interpreter': {'code': '123**23'}, 'type': 'code_interpreter'}, {'code_interpreter': {'code': ''}, 'type': 'code_interpreter'}]
====================ツール情報====================
[{'code_interpreter': {'code': '123**23'}, 'type': 'code_interpreter'}, {'code_interpreter': {'code': '1169008215014432917465348578887506800769541157267 / 5'}, 'type': 'code_interpreter'}]
====================思考プロセス====================
ユーザーはコードインタープリターを 2 回実行するよう依頼しました:
1. 最初に、123 の 23 乗を計算します。その結果は:1169008215014432917465348578887506800769541157267 です。
2. 次に、この結果を 5 で割って:2.338016430028866e+47 を得ます。
これらの 2 つの結果をユーザーに報告する必要があります。
====================完全な応答====================
最初の実行の結果:123 の 23 乗 = 1169008215014432917465348578887506800769541157267
2 回目の実行の結果:上記の結果を 5 で割った値 = 2.338016430028866e+47
====================コードインタープリター実行回数====================
{'code_interpreter': {'count': 2}}注意事項
-
コードインタープリターと関数呼び出しは相互排他であり、同時に有効化できません。両方を有効化するとエラーになります。
両方を同時に有効化するとエラーが発生します。
-
コードインタープリターを有効化すると、1 回のリクエストで複数回のモデル推論がトリガーされます。
usageフィールドは、すべての推論にわたるトークン使用量を集計します。
課金
コードインタープリターは一時的に無料ですが、トークン使用量が増加します。