全部產品
Search
文件中心

Alibaba Cloud Model Studio:代碼解譯器

更新時間:Nov 05, 2025

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

使用方式

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

以 OpenAI 與 DashScope 的 Python SDK 核心調用代碼為例:

OpenAI 相容

# 匯入依賴與建立用戶端...
completion = client.chat.completions.create(
    # 需使用支援代碼解譯器的模型
    model="qwen3-max-preview",
    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

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

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

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

  • 思考:模型分析使用者請求,並產生解決問題的思路和步驟。通過 reasoning_content 欄位返回。

  • 代碼執行:模型產生並執行 Python 代碼。代碼內容通過 tool_info 欄位返回。OpenAI 相容協議不支援tool_info欄位,無法擷取代碼內容。

  • 結果整合:模型接收代碼執行結果,並規劃最終回複。通過 reasoning_content 欄位返回。

  • 回複:模型產生自然語言回複。通過 content 欄位返回。

適用範圍

  • 支援的地區:僅支援中國大陸(北京)地區,需使用中國大陸(北京)地區的API Key

  • 支援的模型:僅支援思考模式下的 qwen3-max-preview。

快速開始

以下樣本示範代碼解譯器如何高效解決數學計算問題。

DashScope

不支援 Java SDK。
Python
import os
import dashscope

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-preview",
    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-preview",
    "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 相容

Python
from openai import OpenAI
import os

# 初始化OpenAI用戶端
client = OpenAI(
    # 如果沒有配置環境變數,請用阿里雲百鍊API Key替換:api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)

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

completion = client.chat.completions.create(
    model="qwen3-max-preview",
    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, // 從環境變數讀取
    // 以下是北京地區base_url,如果使用新加坡地區的模型,需要將base_url替換為: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-preview',
            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
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-preview",
    "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-preview","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-preview","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-preview","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-preview","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-preview","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-preview","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-preview","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-preview","id":"chatcmpl-2f96ef0b-5924-4dfc-b768-4d53ec538b4e"}

data: [DONE]

響應解析

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

由於 OpenAI 相容協議在代碼執行階段不返回資料,思考結果整合階段之間會出現響應空窗。又因兩個階段均通過 reasoning_content返回內容,可統一視為思考階段處理。響應解析樣本請參見快速開始代碼。
import os  
from dashscope import Generation  

messages = [{"role": "user", "content": "運行兩次代碼解譯器:第一次運行請計算123的23次方的值,第二運行請將前者的結果除以5"}]  

response = Generation.call(  
    api_key=os.getenv("DASHSCOPE_API_KEY"),  
    model="qwen3-max-preview",  
    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 消耗。