全部產品
Search
文件中心

Alibaba Cloud Model Studio:代碼解譯器

更新時間:Feb 04, 2026

調用模型時啟用內建的 Python 代碼解譯器,可使模型在沙箱環境裡編寫與運行 Python 代碼,以解決數學計算、資料分析等複雜問題。

使用方式

代碼解譯器功能支援三種調用方式,啟用參數有所不同:

OpenAI 相容-Responses API

通過 tools 參數啟用代碼解譯器功能,需添加 code_interpreter 工具。

為了獲得最佳回複效果,建議同時開啟 code_interpreterweb_searchweb_extractor 工具。
# 匯入依賴與建立用戶端...
response = client.responses.create(
    model="qwen3-max-2026-01-23",
    input="123的21次方是多少?",
    tools=[
        {"type": "code_interpreter"},
        {"type": "web_search"},
        {"type": "web_extractor"},
    ],
    extra_body={
        "enable_thinking": True
    }
)

print(response.output_text)

OpenAI 相容-Chat Completions API

在 API 請求中傳入 enable_code_interpreter: true 即可啟用代碼解譯器。

# 匯入依賴與建立用戶端...
completion = client.chat.completions.create(
    # 需使用支援代碼解譯器的模型
    model="qwen3-max-2026-01-23",
    messages=[{"role": "user", "content": "123的21次方是多少?"}],
    # 由於 enable_code_interpreter 非 OpenAI 標準參數,使用 Python SDK 需要通過 extra_body 傳入(使用Node.js SDK 需作為頂層參數傳入)
    extra_body={
        "enable_code_interpreter": True,
        # 代碼解譯器功能僅支援思考模式調用
        "enable_thinking": True,
    },
    # 僅支援流式輸出調用
    stream=True
)
OpenAI 相容協議無法擷取代碼解譯器啟動並執行代碼資訊。

DashScope

在 API 請求中設定 enable_code_interpreter 為true即可啟用代碼解譯器。

# 匯入依賴...
response = dashscope.Generation.call(
    # 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen3-max-2026-01-23",
    messages=[{"role": "user", "content": "123的21次方是多少?"}],
    # 通過 enable_code_interpreter 參數開啟代碼解譯器
    enable_code_interpreter=True,
    # 代碼解譯器功能僅支援思考模式
    enable_thinking=True,
    result_format="message",
    # 僅支援流式輸出調用
    stream=True
)

代碼解譯器啟動並執行代碼將通過tool_info欄位返回。

啟用後,模型將分階段處理請求:

  1. 思考:模型分析使用者請求,並產生解決問題的思路和步驟。

  2. 代碼執行:模型產生並執行 Python 代碼。

  3. 結果整合:模型接收代碼執行結果,並規劃後續步驟。

  4. 回複:模型產生自然語言回複。

第二步和第三步可能迴圈執行多次。

不同 API 返回的欄位有所差異:

  • Responses API:思考內容通過 output 中 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-max、 qwen3-max-2026-01-23。
為獲得最佳回複效果,建議同時開啟 code_interpreterweb_searchweb_extractor 工具。
import os
from openai import OpenAI

client = OpenAI(
    # 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1"
)

response = client.responses.create(
    model="qwen3-max-2026-01-23",
    input="12的3次方",
    tools=[
        {
            "type": "code_interpreter"
        },
        {
            "type": "web_search"
        },
        {
            "type": "web_extractor"
        }
    ],
    extra_body = {
        "enable_thinking": True
    }
)
# 取消以下注釋查看中間過程輸出
# print(response.output)
print("="*20+"回複內容"+"="*20)
print(response.output_text)
print("="*20+"Token 消耗與工具調用"+"="*20)
print(response.usage)
import OpenAI from "openai";
import process from 'process';

const openai = new OpenAI({
    // 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey: "sk-xxx",
    apiKey: process.env.DASHSCOPE_API_KEY,
    baseURL: "https://dashscope.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1"
});

async function main() {
    const response = await openai.responses.create({
        model: "qwen3-max-2026-01-23",
        input: "請計算12的三次方",
        tools: [
            { type: "code_interpreter" },
            { type: "web_search" },
            { type: "web_extractor" }
        ],
        enable_thinking: true
    });

    console.log("====================回複內容====================");
    console.log(response.output_text);

    // 列印工具調用次數
    console.log("====================Token 消耗與工具調用====================");
    if (response.usage && response.usage.x_tools) {
        console.log(`代碼解譯器運行次數: ${response.usage.x_tools.code_interpreter?.count || 0}`);
    }
    // 取消以下注釋查看中間過程的輸出
    // console.log(JSON.stringify(response.output[0], null, 2));
}

main();
curl -X POST https://dashscope.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen3-max-2026-01-23",
    "input": "請計算12的三次方",
    "tools": [
        {"type": "code_interpreter"},
        {"type": "web_search"},
        {"type": "web_extractor"}
    ],
    "enable_thinking": true
}'
響應樣本
====================回複內容====================
12的3次方等於 **1728**。

計算過程:
12³ = 12 × 12 × 12 = 144 × 12 = 1728
====================Token 消耗與工具調用====================
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替換:api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 使用國際地區模型請替換為"https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)

messages = [{"role": "user", "content": "123的21次方是多少?"}]

completion = client.chat.completions.create(
    model="qwen3-max-2026-01-23",
    messages=messages,
    extra_body={"enable_thinking": True, "enable_code_interpreter": True},
    stream=True,
    stream_options={
        "include_usage": True
    },
)

reasoning_content = ""  # 完整思考過程
answer_content = ""  # 完整回複
is_answering = False  # 是否進入回複階段
print("\n" + "=" * 20 + "思考過程" + "=" * 20 + "\n")

for chunk in completion:
    if not chunk.choices:
        print("\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 + "完整回複" + "=" * 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
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: '123的21次方是多少?' }];
        const stream = await openai.chat.completions.create({
            model: 'qwen3-max-2026-01-23',
            messages,
            stream: true,
            enable_thinking: true,
            enable_code_interpreter: true
        });
        console.log('\n' + '='.repeat(20) + '思考過程' + '='.repeat(20) + '\n');

        for await (const chunk of stream) {
            if (!chunk.choices?.length) {
                console.log('\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) + '完整回複' + '='.repeat(20) + '\n');
                    isAnswering = true;
                }
                process.stdout.write(delta.content);
                answerContent += delta.content;
            }
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

main();
響應樣本
====================思考過程====================
  
  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.
  
  ====================完整回複====================
  
  123的21次方是:77269364466549865653073473388030061522211723
curl
# 使用國際地區模型請替換為https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions
curl -X POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen3-max-2026-01-23",
    "messages": [
        {
            "role": "user", 
            "content": "123的21次方是多少?"
        }
    ],
    "enable_code_interpreter": true,
    "enable_thinking": true,
    "stream": true
}'

響應樣本

data: {"choices":[{"delta":{"content":null,"role":"assistant","reasoning_content":""},"index":0,"logprobs":null,"finish_reason":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3-max-2026-01-23","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}
  
data: {"choices":[{"finish_reason":null,"logprobs":null,"delta":{"content":null,"reasoning_content":"使用者"},"index":0}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3-max-2026-01-23","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}

data: {"choices":[{"delta":{"content":null,"reasoning_content":"問"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3-max-2026-01-23","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}

data: {"choices":[{"delta":{"content":null,"reasoning_content":"的是"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3-max-2026-01-23","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}

...

data: {"choices":[{"delta":{"content":"非常大的數字,總","reasoning_content":null},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3-max-2026-01-23","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}

data: {"choices":[{"delta":{"content":"共有43位","reasoning_content":null},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3-max-2026-01-23","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}

data: {"choices":[{"delta":{"content":"。","reasoning_content":null},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3-max-2026-01-23","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}

data: {"choices":[{"finish_reason":"stop","delta":{"content":"","reasoning_content":null},"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1761899724,"system_fingerprint":null,"model":"qwen3-max-2026-01-23","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}

data: [DONE]

DashScope

不支援 Java SDK。
Python
import os
import dashscope

# 如需使用國際地區模型,請取消下行注釋
# dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

messages = [
    {"role": "user", "content": "123的21次方是多少?"},
]

response = dashscope.Generation.call(
    # 若沒有配置環境變數,請用百鍊API Key將下行替換為: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的", "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次方是:\n\n", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "772693", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "644665", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "498656", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "530734", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "733880", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "300615", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "222117", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": "23", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
{"text": null, "finish_reason": null, "choices": [{"finish_reason": "stop", "message": {"role": "assistant", "content": "", "reasoning_content": ""}}], "tool_info": [{"code_interpreter": {"code": "123**21"}, "type": "code_interpreter"}]}
curl
curl -X POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
    "model": "qwen3-max-2026-01-23",
    "input":{
        "messages":[
            {
                "role": "user",
                "content": "123的21次方是多少?"
            }
        ]
    },
    "parameters": {
        "enable_code_interpreter": true,
        "enable_thinking": true,
        "result_format": "message"
    }
}'

響應樣本

<...文字內容...>為說明性注釋,非實際 API 響應,用於標識處理階段。
id:1
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"The","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":290,"output_tokens":3,"input_tokens":287,"output_tokens_details":{"reasoning_tokens":1}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}

id:2
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":" user is asking","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":293,"output_tokens":6,"input_tokens":287,"output_tokens_details":{"reasoning_tokens":4}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}

...思考階段...

id:21
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":388,"output_tokens":101,"input_tokens":287,"output_tokens_details":{"reasoning_tokens":68}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}

...思考結束開始運行代碼解譯器...

id:22
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"","role":"assistant"},"finish_reason":"null"}],"tool_info":[{"code_interpreter":{"code":"123**21"},"type":"code_interpreter"}]},"usage":{"total_tokens":388,"output_tokens":101,"input_tokens":287,"output_tokens_details":{"reasoning_tokens":68},"plugins":{"code_interpreter":{"count":1}}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}

...運行代碼解譯器後開始思考...

id:23
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"The","role":"assistant"},"finish_reason":"null"}],"tool_info":[{"code_interpreter":{"code":"123**21"},"type":"code_interpreter"}]},"usage":{"total_tokens":838,"output_tokens":104,"input_tokens":734,"output_tokens_details":{"reasoning_tokens":69},"plugins":{"code_interpreter":{"count":1}}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}

id:24
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":" user","role":"assistant"},"finish_reason":"null"}],"tool_info":[{"code_interpreter":{"code":"123**21"},"type":"code_interpreter"}]},"usage":{"total_tokens":839,"output_tokens":105,"input_tokens":734,"output_tokens_details":{"reasoning_tokens":70},"plugins":{"code_interpreter":{"count":1}}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}

...思考階段...

id:43
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":" a clear format.","role":"assistant"},"finish_reason":"null"}],"tool_info":[{"code_interpreter":{"code":"123**21"},"type":"code_interpreter"}]},"usage":{"total_tokens":942,"output_tokens":208,"input_tokens":734,"output_tokens_details":{"reasoning_tokens":171},"plugins":{"code_interpreter":{"count":1}}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}

...思考結束,開始回複...

id:44
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"123的","reasoning_content":"","role":"assistant"},"finish_reason":"null"}],"tool_info":[{"code_interpreter":{"code":"123**21"},"type":"code_interpreter"}]},"usage":{"total_tokens":947,"output_tokens":213,"input_tokens":734,"output_tokens_details":{"reasoning_tokens":171},"plugins":{"code_interpreter":{"count":1}}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}

...

id:53
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"23","reasoning_content":"","role":"assistant"},"finish_reason":"null"}],"tool_info":[{"code_interpreter":{"code":"123**21"},"type":"code_interpreter"}]},"usage":{"total_tokens":997,"output_tokens":263,"input_tokens":734,"output_tokens_details":{"reasoning_tokens":171},"plugins":{"code_interpreter":{"count":1}}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}

id:54
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"","role":"assistant"},"finish_reason":"stop"}],"tool_info":[{"code_interpreter":{"code":"123**21"},"type":"code_interpreter"}]},"usage":{"total_tokens":997,"output_tokens":263,"input_tokens":734,"output_tokens_details":{"reasoning_tokens":171},"plugins":{"code_interpreter":{"count":1}}},"request_id":"a1959ad1-2637-4672-a21f-4d351371d254"}

響應解析

OpenAI 相容-Responses API

以下樣本使用 OpenAI Python SDK,示範如何在流式響應中解析 API 返回的資料。

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope-intl.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1"
)

response = client.responses.create(
    model="qwen3-max-2026-01-23",
    input="12的3次方",
    tools=[
        {"type": "code_interpreter"}
    ],
    extra_body={
        "enable_thinking": True
    },
    stream=True
)

def print_section(title):
    print(f"\n{'=' * 20}{title}{'=' * 20}")

current_section = None
final_response = None

for event in response:
    # 思考過程增量輸出
    if event.type == "response.reasoning_summary_text.delta":
        if current_section != "reasoning":
            print_section("思考過程")
            current_section = "reasoning"
        print(event.delta, end="", flush=True)

    # 代碼解譯器調用完成
    elif event.type == "response.output_item.done" and hasattr(event.item, "code"):
        print_section("代碼執行")
        print(f"代碼:\n{event.item.code}")
        if event.item.outputs:
            print(f"結果: {event.item.outputs[0].logs}")
        current_section = "code"

    # 最終回複增量輸出
    elif event.type == "response.output_text.delta":
        if current_section != "answer":
            print_section("完整回複")
            current_section = "answer"
        print(event.delta, end="", flush=True)

    # 響應完成,儲存最終結果用於擷取 usage
    elif event.type == "response.completed":
        final_response = event.response

# 輸出 Token 消耗和工具調用次數
if final_response and final_response.usage:
    print_section("Token 消耗與工具調用")
    usage = final_response.usage
    print(f"輸入 Token: {usage.input_tokens}")
    print(f"輸出 Token: {usage.output_tokens}")
    print(f"思考 Token: {usage.output_tokens_details.reasoning_tokens}")
    print(f"代碼解譯器調用次數: {usage.x_tools.get('code_interpreter', {}).get('count', 0)}")

DashScope

以下 DashScope Python SDK 樣本示範:在單次請求中執行兩次計算,並傳回碼及總調用次數。

由於 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": "運行兩次代碼解譯器:第一次運行請計算123的23次方的值,第二次運行請將前者的結果除以5"}]  

response = Generation.call(  
    api_key=os.getenv("DASHSCOPE_API_KEY"),  
    model="qwen3-max-2026-01-23",  
    messages=messages,  
    result_format="message",
    enable_thinking=True,
    enable_code_interpreter=True,
    stream=True,
    incremental_output=True,
)  

# 狀態標誌:跟蹤是否已列印工具資訊、是否進入回答階段、是否在推理段
is_answering = False  
in_reasoning_section = False  
cur_tools = []

# 列印帶標題的分隔地區
def print_section(title):  
    print(f"\n{'=' * 20}{title}{'=' * 20}")  

# 初始列印“思考過程”標題
print_section("思考過程")  
in_reasoning_section = True  

# 串流模型返回的每個資料區塊
for chunk in response:  
    try:  
        # 提取響應中的關鍵字段:內容、推理文本、工具調用資訊
        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)

響應樣本

====================思考過程====================
使用者要求運行兩次代碼解譯器:
1. 第一次運行:計算123的23次方的值
2. 第二次運行:將前者的結果除以5

我需要先調用代碼解譯器計算123**23,然後用這個結果再調用一次代碼解譯器除以5。

讓我先做第一次計算。

====================工具資訊====================
[{'code_interpreter': {'code': '123**23'}, 'type': 'code_interpreter'}]

====================思考過程====================
第一次計算得到了123的23次方的值:1169008215014432917465348578887506800769541157267

現在需要第二次運行,將這個結果除以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'}]

====================思考過程====================
使用者要求運行兩次代碼解譯器:
1. 第一次計算123的23次方,結果是:1169008215014432917465348578887506800769541157267
2. 第二次將這個結果除以5,得到:2.338016430028866e+47

現在我需要向使用者報告這兩個
====================完整回複====================
第一次運行結果:123的23次方 = 1169008215014432917465348578887506800769541157267

第二次運行結果:將上述結果除以5 = 2.338016430028866e+47
====================代碼解譯器運行次數====================
{'code_interpreter': {'count': 2}}

注意事項

  • 代碼解譯器與 Function Calling 互斥,不可同時啟用。

    同時啟用會報錯。
  • 啟用代碼解譯器後,單次請求會觸發多次模型推理,usage 欄位匯總所有調用的 Token 消耗。

計費說明

啟用代碼解譯器工具限時免費,但會增加 Token 消耗。