モデルの呼び出し時に、組み込みの Python コードインタープリターを有効にします。モデルは、数学計算やデータ分析などの複雑な問題を解決するため、サンドボックスで Python コードを記述・実行します。
使用方法
コードインタープリターは 3 つの呼び出しメソッドをサポートしています。メソッドごとにパラメーターが異なります:
OpenAI 互換 - レスポンス API
コードインタープリターを有効にするには、code_interpreter ツールを tools パラメーターに追加します。
最良の結果を得るには、
code_interpreter、web_search、およびweb_extractorツールを同時に有効にしてください。
# 依存関係をインポートし、クライアントを作成します。
response = client.responses.create(
model="qwen3.8-max",
input="What is 123 to the power of 21?",
tools=[
{"type": "code_interpreter"},
{"type": "web_search"},
{"type": "web_extractor"},
],
extra_body={
"enable_thinking": True
}
)
print(response.output_text)
OpenAI 互換 - チャット補完 API
Code Interpreter を有効にするには、API リクエストで enable_code_interpreter: true を渡します。
# 依存関係をインポートし、クライアントを作成します。
completion = client.chat.completions.create(
# コードインタープリターをサポートするモデルを使用します。
model="qwen3-max",
messages=[{"role": "user", "content": "What is 123 to the power of 21?"}],
# enable_code_interpreter は標準の OpenAI パラメーターではないため、Python SDK を使用する場合は extra_body を介して渡す必要があります。Node.js SDK を使用する場合は、トップレベルパラメーターとして渡します。
extra_body={
"enable_code_interpreter": True,
# コードインタープリター機能は、思考モードでの呼び出しのみをサポートします。
"enable_thinking": True,
},
# ストリーミング出力の呼び出しのみがサポートされています。
stream=True
)
OpenAI 互換プロトコルでは、コード実行の詳細は返されません。
DashScope
Code Interpreter を有効にするには、API リクエストで enable_code_interpreter を true に設定します。
# 依存関係をインポートします。
response = dashscope.MultiModalConversation.call(
# 環境変数が設定されていない場合は、次の行を api_key="sk-xxx" に置き換えて、ご自身の Model Studio API キーを使用してください。
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen3.5-plus",
messages=[{"role": "user", "content": "What is 123 to the power of 21?"}],
# enable_code_interpreter パラメーターを使用してコードインタープリターを有効にします。
enable_code_interpreter=True,
# コードインタープリター機能は思考モードのみをサポートします。
enable_thinking=True,
result_format="message",
# ストリーミング出力の呼び出しのみがサポートされています。
stream=True
)
実行されたコードは、tool_info フィールドに返されます。
コードインタープリターが有効になると、モデルはリクエストを以下の段階で処理します:
- 思考:モデルはユーザーのリクエストを分析し、問題を解決するためのアイデアと手順を生成します。
- コード実行:モデルは Python コードを生成して実行します。
- 結果の統合:モデルはコード実行の結果を受け取り、次のステップを計画します。
- 応答:モデルは自然言語応答を生成します。
ステップ 2 と 3 は複数回ループすることがあります。
API ごとに返されるフィールドは異なります:
- レスポンス API の出力では、思考内容は
type="reasoning"を持つオブジェクトで返されます。コード実行はtype="code_interpreter_call"で返されます。レスポンスはtype="message"で返されます。 - Chat Completions API / DashScope: 思考コンテンツは
reasoning_contentフィールドで返されます。レスポンスはcontentフィールドで返されます。DashScope は、tool_infoフィールドでコードコンテンツを返すこともサポートしています。
対応範囲
推奨モデル
Responses API
Qwen-Max:Qwen3.8-Max シリーズ、Qwen3.7-Max シリーズ
Qwen-Plus:Qwen3.7-Plus シリーズ、Qwen3.6-Plus シリーズ、Qwen3.5-Plus シリーズ
DeepSeek:deepseek-v4-flash、deepseek-v4-flash-0731、deepseek-v4-pro
GLM:glm-5.2
Qwen3.8 オープンソースシリーズ
Chat Completions API / DashScope
- Qwen-Max (思考モード):Qwen3.8-Max シリーズ、Qwen3.7-Max シリーズ
- Qwen-Plus:Qwen3.5-Plus シリーズ
その他のモデル
以下のモデルもコードインタープリターをサポートしていますが、パフォーマンスは推奨モデルほどではない場合があります。これらのモデルは Responses API 経由でのみサポートされます。
- Qwen-Flash:Qwen3.7-Flash シリーズ、Qwen3.6-Flash シリーズ、Qwen3.5-Flash シリーズ
- Qwen3.6 オープンソースシリーズ (qwen3.6-27b を除く)
- Qwen3.5 オープンソースシリーズ
クイックスタート
以下の例では、コードインタープリターが数学的な問題をどのように解決するかを示します。
OpenAI 互換 - Responses API
最良の結果を得るには、
code_interpreter、web_search、web_extractorの各ツールを同時に有効にしてください。
import os
from openai import OpenAI
client = OpenAI(
# 環境変数が設定されていない場合、次の行を `api_key="sk-xxx"` のように、ご自身の Alibaba Cloud Model Studio API キーに置き換えてください。
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下の URL はシンガポールリージョン用です。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)
response = client.responses.create(
model="qwen3.8-max",
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({
// 環境変数が設定されていない場合、次の行を `apiKey: "sk-xxx"` のように、ご自身の Alibaba Cloud Model Studio API キーに置き換えてください。
apiKey: process.env.DASHSCOPE_API_KEY,
// 以下の URL はシンガポールリージョン用です。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
});
async function main() {
const response = await openai.responses.create({
model: "qwen3.8-max",
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();
# 以下の URL はシンガポールリージョン用です。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.8-max",
"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(
# 環境変数が設定されていない場合、`api_key="sk-xxx"` のように、ご自身の Alibaba Cloud Model Studio API キーに置き換えてください。
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下の URL は中国 (北京) リージョン用です。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [{"role": "user", "content": "123 の 21 乗はいくつですか?"}]
completion = client.chat.completions.create(
model="qwen3.5-plus",
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
# コンテンツを受信したら、応答を開始
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 を計算する必要があります。
コードインタープリターを使用してこの値を計算できます。code_interpreter 関数を呼び出して、123**21 を計算する Python コードを渡す必要があります。
この関数呼び出しを構築します。
ユーザーは 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, // 環境変数から読み取り
// 以下の URL は中国 (北京) リージョン用です。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
baseURL: 'https://{WorkspaceId}.cn-beijing.maas.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.5-plus',
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;
}
// コンテンツを受信したら、応答を開始
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
# 以下の URL は中国 (北京) リージョン用です。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.5-plus",
"messages": [
{
"role": "user",
"content": "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.5-plus","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
data: {"choices":[{"finish_reason":null,"logprobs":null,"delta":{"content":null,"reasoning_content":"The user"},"index":0}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3.5-plus","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
data: {"choices":[{"delta":{"content":null,"reasoning_content":" is asking"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3.5-plus","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
data: {"choices":[{"delta":{"content":null,"reasoning_content":" for"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3.5-plus","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.5-plus","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.5-plus","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.5-plus","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.5-plus","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
data: [DONE]
DashScope
Java SDK はサポート対象外です。
Python
import os
import dashscope
# 中国 (北京) リージョン。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'
messages = [
{"role": "user", "content": "123 の 21 乗はいくつですか?"},
]
response = dashscope.MultiModalConversation.call(
# 環境変数が設定されていない場合、次の行を `api_key="sk-xxx"` のように、ご自身の Model Studio API キーに置き換えてください。
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen3.5-plus",
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 の 21 乗は: ", "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": "\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://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
"model": "qwen3.5-plus",
"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 の 21 乗は","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 の例は、ストリーミング応答を解析する方法を示しています。
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下の URL はシンガポールリージョン用です。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)
response = client.responses.create(
model="qwen3.8-max",
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}")
# モデルが実際にコードインタープリターを呼び出さなかった場合(例:単純な質問に直接回答した場合)、レスポンスに x_tools フィールドが含まれません
if hasattr(usage, 'x_tools'):
print(f"コードインタープリター呼び出し回数: {usage.x_tools.get('code_interpreter', {}).get('count', 0)}")
else:
print("コードインタープリター呼び出し回数: 0")
DashScope
以下の DashScope Python SDK の例は、1 つのリクエストで 2 つの計算を実行し、返されたコードと呼び出し回数を解析します。
OpenAI Chat Completions API は、コード実行 段階ではデータを返さないため、思考 段階と 結果統合 段階の間に応答は送信されません。両方の段階は
reasoning_contentフィールドを通じて内容を返すため、思考 段階としてまとめて処理できます。応答解析の例については、クイックスタート セクションのコードをご参照ください。
import os
from dashscope import MultiModalConversation
# 中国 (北京) リージョン。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'
messages = [{"role": "user", "content": "コードインタープリターを 2 回実行してください: 最初に、123 の 23 乗の値を計算します。次に、結果を 5 で割ります。"}]
response = MultiModalConversation.call(
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen3.5-plus",
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:
# 応答から主要フィールドを抽出: コンテンツ、思考プロセステキスト、ツール呼び出し情報
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フィールドには、そのリクエスト内のすべての呼び出しの合計トークン消費量が要約されます。
課金
コードインタープリターは 期間限定で無料 ですが、トークン消費量は増加します。