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

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

最終更新日:Jun 18, 2026

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

使用方法

コード インタープリターは、次の 3 種類の呼び出し方法をサポートしています。各メソッドで使用するパラメーターは異なります。

OpenAI 互換 - Responses API

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

最適な結果を得るには、code_interpreterweb_search、および web_extractor の各ツールを同時に有効にしてください。
# 依存関係をインポートしてクライアントを作成...
response = client.responses.create(
    model="qwen3.7-plus",
    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.7-plus",
    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.MultiModalConversation.call(
    # 環境変数が設定されていない場合は、次の行を api_key="sk-xxx"(ご自身の Model Studio API キーを使用)に置き換えてください。
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen3.7-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 フィールドで返されます。

コード インタープリターを有効にすると、モデルは次のステージでリクエストを処理します。

  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 フィールドで返すことも可能です。

対応範囲

推奨モデル

Responses API

Qwen-Max:Qwen3.7-Max シリーズ

Qwen-Plus:Qwen3.7-Plus シリーズ、Qwen3.6-Plus シリーズ、Qwen3.5-Plus シリーズ

Chat Completions API / DashScope

  • Qwen-Max (思考モード):Qwen3-Max シリーズ

  • Qwen-Plus:Qwen3.7-Plus シリーズ、Qwen3.6-Plus シリーズ、Qwen3.5-Plus シリーズ

その他のモデル

これらのモデルもコード インタープリターをサポートしていますが、パフォーマンスが劣る可能性があります。

  • Qwen-Flash:Qwen3.6-Flash シリーズ、Qwen3.5-Flash シリーズ

  • Qwen3.6 オープンソースシリーズ (qwen3.6-27b を除く)

  • Qwen3.5 オープンソースシリーズ

クイックスタート

以下の例は、コード インタープリターが数学的問題を解決する方法を示しています。

OpenAI 互換 - Responses API

最適な結果を得るには、code_interpreterweb_search、および web_extractor の各ツールを同時に有効にしてください。
import os
from openai import OpenAI

client = OpenAI(
    # 環境変数が設定されていない場合は、次の行を api_key="sk-xxx"(ご自身の 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.7-plus",
    input="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 Content"+"="*20)
print(response.output_text)
print("="*20+"Token Consumption and Tool Calls"+"="*20)
print(response.usage)
import OpenAI from "openai";
import process from 'process';

const openai = new OpenAI({
    // 環境変数が設定されていない場合は、次の行を apiKey: "sk-xxx"(ご自身の 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.7-plus",
        input: "Calculate 12 to the power of 3",
        tools: [
            { type: "code_interpreter" },
            { type: "web_search" },
            { type: "web_extractor" }
        ],
        enable_thinking: true
    });

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

    // ツール呼び出し回数を出力
    console.log("====================Token Consumption 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();
# 以下の 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.7-plus",
    "input": "Calculate 12 to the power of 3",
    "tools": [
        {"type": "code_interpreter"},
        {"type": "web_search"},
        {"type": "web_extractor"}
    ],
    "enable_thinking": true
}'
応答例
====================Response Content====================
12 to the power of 3 is **1728**.

Calculation process:
12³ = 12 × 12 × 12 = 144 × 12 = 1728
====================Token Consumption 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(
    # 環境変数が設定されていない場合は、Alibaba Cloud Model Studio API キーを使用して api_key="sk-xxx" に置き換えてください
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # シンガポールリージョンのモデルを使用する場合は、"https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1" に置き換えてください
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)

messages = [{"role": "user", "content": "What is 123 to the power of 21?"}]

completion = client.chat.completions.create(
    model="qwen3.7-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 + "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

    # 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 the value of 123 to the power of 21. This is a mathematical calculation problem. I need to calculate 123^21.

I can use the code calculator to compute this value. I need to call the code_interpreter function and pass 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 calculated the result using Python code. The calculation shows that 123 to the power of 21 equals 77269364466549865653073473388030061522211723. This is a very large number, and I should provide it 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://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1 に置き換えてください
    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: 'What is 123 to the power of 21?' }];
        const stream = await openai.chat.completions.create({
            model: 'qwen3.7-plus',
            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;
            }

            // 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://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions に置き換えてください
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.7-plus",
    "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.7-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.7-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.7-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.7-plus","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}

...

data: {"choices":[{"delta":{"content":"is 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.7-plus","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.7-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.7-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.7-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": "What is 123 to the power of 21?"},
]

response = dashscope.MultiModalConversation.call(
    # 環境変数が設定されていない場合は、次の行を api_key="sk-xxx"(ご自身の Model Studio API キーを使用)に置き換えてください。
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen3.7-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 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://{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.7-plus",
    "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"}

応答の解析

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.7-plus",
    input="12 to the power of 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("Thinking Process")
            current_section = "reasoning"
        print(event.delta, end="", flush=True)

    # コード インタープリター呼び出し完了
    elif event.type == "response.output_item.done" and hasattr(event.item, "code"):
        print_section("Code Execution")
        print(f"Code:\n{event.item.code}")
        if event.item.outputs:
            print(f"Result: {event.item.outputs[0].logs}")
        current_section = "code"

    # 最終応答の増分出力
    elif event.type == "response.output_text.delta":
        if current_section != "answer":
            print_section("Complete Response")
            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("Token Consumption and Tool Calls")
    usage = final_response.usage
    print(f"Input Tokens: {usage.input_tokens}")
    print(f"Output Tokens: {usage.output_tokens}")
    print(f"Thinking Tokens: {usage.output_tokens_details.reasoning_tokens}")
    print(f"Code Interpreter calls: {usage.x_tools.get('code_interpreter', {}).get('count', 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": "Run Code Interpreter twice: first, calculate the value of 123 to the power of 23. Second, divide the result by 5."}]  

response = MultiModalConversation.call(  
    api_key=os.getenv("DASHSCOPE_API_KEY"),  
    model="qwen3.7-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("Thinking Process")  
in_reasoning_section = True  

# ストリームでモデルから返される各ブロックを処理
for chunk in response:  
    try:  
        # 応答から主要フィールドを抽出:content、reasoning text、tool call info
        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)  
# コード インタープリター呼び出し回数を出力
print_section("Code Interpreter Runs")  
print(chunk.usage.plugins)

応答例

====================Thinking Process====================
The user wants to run Code Interpreter twice:
1. First run: Calculate the value of 123 to the power of 23.
2. Second run: Divide the result of the first run by 5.

I need to first call Code Interpreter to calculate 123**23, then use this result to call Code Interpreter again to divide by 5.

Let me do the first calculation.

====================Tool Information====================
[{'code_interpreter': {'code': '123**23'}, 'type': 'code_interpreter'}]

====================Thinking Process====================
The first calculation yielded the value of 123 to the power of 23: 1169008215014432917465348578887506800769541157267

Now for the second run, I need to divide this result by 5. I need to use this exact value for the division.
====================Tool Information====================
[{'code_interpreter': {'code': '123**23'}, 'type': 'code_interpreter'}, {'code_interpreter': {'code': ''}, 'type': 'code_interpreter'}]

====================Tool Information====================
[{'code_interpreter': {'code': '123**23'}, 'type': 'code_interpreter'}, {'code_interpreter': {'code': '1169008215014432917465348578887506800769541157267 / 5'}, 'type': 'code_interpreter'}]

====================Thinking Process====================
The user requested to run Code Interpreter twice:
1. First, calculate 123 to the power of 23. The result is: 1169008215014432917465348578887506800769541157267
2. Second, divide this result by 5. The result is: 2.338016430028866e+47

Now I need to report these two results to the user.
====================Complete Response====================
First run result: 123 to the power of 23 = 1169008215014432917465348578887506800769541157267

Second run result: The above result divided by 5 = 2.338016430028866e+47
====================Code Interpreter Runs====================
{'code_interpreter': {'count': 2}}

注意事項

  • コード インタープリターと関数呼び出しは相互排他です。

    同一リクエストで両方を有効にするとエラーが発生します。
  • コード インタープリターを有効にすると、1 回のリクエストで複数回のモデル推論がトリガーされる場合があります。usage フィールドは、そのリクエスト内のすべての呼び出しにおける合計トークン消費量をまとめたものです。

課金

コード インタープリターは期間限定で無料ですが、トークン消費量が増加します。