すべてのプロダクト
Search
ドキュメントセンター

Alibaba Cloud Model Studio:コードインタープリター

最終更新日:Feb 05, 2026

モデルを呼び出す際に、組み込みの Python コードインタープリターを有効にすると、モデルはサンドボックス環境で Python コードを記述・実行し、数学計算やデータ分析などの複雑な問題を解決できます。

使用方法

コードインタープリターは 3 つの呼び出しメソッドをサポートしており、それぞれ有効化パラメーターが異なります。

OpenAI 互換 - Responses API

tools パラメーターに code_interpreter ツールを追加することで、コードインタープリターを有効にします。

最適な結果を得るためには、code_interpreterweb_searchweb_extractor ツールを一緒に有効にすることを推奨します。
# 依存関係をインポートし、クライアントを作成...
response = client.responses.create(
    model="qwen3-max-2026-01-23",
    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 互換 - Chat Completions API

API リクエストで enable_code_interpreter: true を渡して、コードインタープリターを有効にします。

# 依存関係をインポートし、クライアントを作成...
completion = client.chat.completions.create(
    # コードインタープリターをサポートするモデルを使用
    model="qwen3-max-2026-01-23",
    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

API リクエストで enable_code_interpretertrue に設定して、コードインタープリターを有効にします。

# 依存関係をインポート...
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": "What is 123 to the power of 21?"}],
    # コードインタープリターを有効にする
    enable_code_interpreter=True,
    # コードインタープリターには思考モードが必要です
    enable_thinking=True,
    result_format="message",
    # ストリーミング出力のみ
    stream=True
)

インタープリターによって実行されたコードは、tool_info フィールドで返されます。

有効にすると、モデルはリクエストを以下の段階で処理します。

  1. 思考:モデルはユーザーのリクエストを分析し、問題を解決するためのアイデアとステップを生成します。

  2. コード実行:モデルは Python コードを生成して実行します。

  3. 結果の統合:モデルは実行結果を受け取り、次のステップを計画します。

  4. 応答:モデルは自然言語の応答を生成します。

ステップ 2 と 3 は、ループ内で複数回実行される場合があります。

API によって返されるフィールドは異なります。

  • Responses API:思考コンテンツは `type="reasoning"` の出力オブジェクトで、コード実行は `type="code_interpreter_call"` で、応答は `type="message"` で返されます。

  • Chat Completions API / DashScope:思考コンテンツは `reasoning_content` フィールドで、応答は `content` フィールドで返されます。DashScope はさらに、コードコンテンツ用に `tool_info` フィールドをサポートします。

可用性

国際

  • 思考モードの `qwen3-max` および `qwen3-max-2026-01-23`

中国

思考モードの `qwen3-max`、`qwen3-max-2026-01-23`、`qwen3-max-preview`

Responses API は現在サポートされていません。

はじめに

以下の例では、コードインタープリターを使用して数学計算の問題を効率的に解決する方法を説明します。

OpenAI 互換 - Responses API

思考モードの `qwen3-coder-next` および `qwen3-max-2026-01-23` のみでサポートされています。
最適な結果を得るためには、code_interpreterweb_searchweb_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-intl.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1"
)

response = client.responses.create(
    model="qwen3-max-2026-01-23",
    input="What is 12 to the power of 3?",
    tools=[
        {
            "type": "code_interpreter"
        },
        {
            "type": "web_search"
        },
        {
            "type": "web_extractor"
        }
    ],
    extra_body = {
        "enable_thinking": True
    }
)
# 次の行のコメントを解除すると、中間出力が表示されます
# print(response.output)
print("="*20+"Response"+"="*20)
print(response.output_text)
print("="*20+"Token usage and tool calls"+"="*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-intl.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: "What is 12 to the power of 3?",
        tools: [
            { type: "code_interpreter" },
            { type: "web_search" },
            { type: "web_extractor" }
        ],
        enable_thinking: true
    });

    console.log("====================Response====================");
    console.log(response.output_text);

    // ツール呼び出し回数を出力
    console.log("====================Token usage and tool calls====================");
    if (response.usage && response.usage.x_tools) {
        console.log(`Code interpreter runs: ${response.usage.x_tools.code_interpreter?.count || 0}`);
    }
    // 次の行のコメントを解除すると、中間出力が表示されます
    // console.log(JSON.stringify(response.output[0], null, 2));
}

main();
curl -X POST https://dashscope-intl.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen3-max-2026-01-23",
    "input": "What is 12 to the power of 3?",
    "tools": [
        {"type": "code_interpreter"},
        {"type": "web_search"},
        {"type": "web_extractor"}
    ],
    "enable_thinking": true
}'
応答例
====================Response====================
12 to the power of 3 equals **1728**.

Calculation:
12³ = 12 × 12 × 12 = 144 × 12 = 1728
====================Token usage and tool calls====================
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": "What is 123 to the power of 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 + "Thinking process" + "=" * 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 + "Complete response" + "=" * 20 + "\n")
            is_answering = True
        print(delta.content, end="", flush=True)
        answer_content += delta.content
応答例
====================Thinking process====================

The user is asking for 123 to the power of 21. This is a mathematical calculation problem. I need to calculate 123^21.

I can use the code interpreter to calculate this value. I need to call the code_interpreter function and pass in the Python code to calculate 123**21.

Let me construct this function call.
The user asked for 123 to the power of 21, and I used Python code to calculate the result. The result shows that 123 to the power of 21 equals 77269364466549865653073473388030061522211723. This is a very large number. I should provide this directly
====================Complete response====================

123 to the power of 21 is: 77269364466549865653073473388030061522211723
Usage:
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: 'What is 123 to the power of 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) + 'Thinking process' + '='.repeat(20) + '\n');

        for await (const chunk of stream) {
            if (!chunk.choices?.length) {
                console.log('\nUsage:');
                console.log(chunk.usage);
                continue;
            }

            const delta = chunk.choices[0].delta;

            // 思考コンテンツのみを収集
            if (delta.reasoning_content !== 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) + 'Complete response' + '='.repeat(20) + '\n');
                    isAnswering = true;
                }
                process.stdout.write(delta.content);
                answerContent += delta.content;
            }
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

main();
応答例
====================Thinking process====================

  The user is asking for the value of 123 raised to the power of 21. This is a mathematical calculation that I can perform using Python's code interpreter. I'll use the exponentiation operator ** to calculate this.

  Let me write the code to compute 123**21.The calculation has been completed successfully. The result of 123 raised to the power of 21 is a very large number: 77269364466549865653073473388030061522211723.

  I should present this result clearly to the user.

  ====================Complete response====================

  123 to the power of 21 is: 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": "What is 123 to the power of 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":"The user"},"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":" is asking"},"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":" for"},"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":"a very large number, with a total","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":" of 43 digits","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": "What is 123 to the power of 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": "What is 123 to the power of 21?"
            }
        ]
    },
    "parameters": {
        "enable_code_interpreter": true,
        "enable_thinking": true,
        "result_format": "message"
    }
}'

応答例

<...text content...> は処理段階を特定するための説明的なコメントであり、実際の 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"}

応答の解析

以下の DashScope Python SDK の例では、1 回のリクエストで 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": "Code Interpreter を 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}")

# 最初に「Thinking process」というタイトルを出力します
print_section("Thinking process")
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("Thinking process")
            in_reasoning_section = True
        print(reasoning, end="", flush=True)
    if tools is not None and tools != cur_tools:
        print_section("Tool information")
        print(tools)
        in_reasoning_section = False
        cur_tools = tools
    # 最終的な回答コンテンツを出力します
    if content:
        if not is_answering:
            print_section("Complete response")
            is_answering = True
            in_reasoning_section = False
        print(content, end="", flush=True)
# Code Interpreter の呼び出し回数を出力します
print_section("Code interpreter run count")
print(chunk.usage.plugins)

応答例

====================思考プロセス====================
  ユーザーは Code Interpreter を 2 回実行したいと考えています:
  1. 1 回目の実行:123 の 23 乗を計算
  2. 2 回目の実行:その結果を 5 で割る

  まず Code Interpreter を呼び出して 123**23 を計算し、その結果を使って再度 Code Interpreter を呼び出して 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'}]

  ====================思考プロセス====================
  ユーザーは Code Interpreter を 2 回実行するようリクエストしました:
  1. まず、123 の 23 乗を計算、結果:1169008215014432917465348578887506800769541157267
  2. 次に、この結果を 5 で割り、2.338016430028866e+47 を得ます

  では、これら 2 つの結果をユーザーに報告する必要があります
  ====================完全な応答====================
  1 回目の実行結果:123 の 23 乗 = 1169008215014432917465348578887506800769541157267

  2 回目の実行結果:上記の結果を 5 で割った値 = 2.338016430028866e+47
  ====================Code Interpreter の実行回数====================
  {'code_interpreter': {'count': 2}}

注意事項

  • コードインタープリターと関数呼び出しは相互排他的であり、同時に有効にすることはできません。

    両方を有効にすると、エラーが発生します。
  • コードインタープリターを有効にすると、1 つのリクエストで複数のモデル推論がトリガーされます。usage フィールドでは、すべての呼び出しにわたるトークンの消費量が集計されます。

課金

コードインタープリターツールの有効化は一時的に無料ですが、トークンの消費量が増加します。