Skip to main content
工具調用

代碼解譯器

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

使用方式

代碼解譯器功能支援三種調用方式,啟用參數有所不同:
  • OpenAI 相容-Responses API
  • OpenAI 相容-Chat Completions API
  • DashScope
通過 tools 參數啟用代碼解譯器功能,需添加 code_interpreter 工具。
為了獲得最佳回複效果,建議同時開啟 code_interpreterweb_searchweb_extractor 工具。
# 匯入依賴與建立用戶端...
response = client.responses.create(
    model="qwen3.8-max",
    input="123的21次方是多少?",
    tools=[
        {"type": "code_interpreter"},
        {"type": "web_search"},
        {"type": "web_extractor"},
    ],
    extra_body={
        "enable_thinking": True
    }
)

print(response.output_text)
啟用後,模型將分階段處理請求:
  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 欄位傳回碼內容。

適用範圍

推薦模型

  • Responses API
  • Chat Completions API / DashScope
千問Max:Qwen3.8-Max系列、Qwen3.7-Max系列千問Plus:Qwen3.7-Plus系列、Qwen3.6-Plus系列、Qwen3.5-Plus系列DeepSeek:deepseek-v4-flash、deepseek-v4-flash-0731Qwen3.8開源系列

其他模型

以下模型也支援此工具調用,但效果不如推薦模型。僅支援通過Responses API調用。
  • 千問Flash:Qwen3.7-Flash系列、Qwen3.6-Flash系列、Qwen3.5-Flash系列
  • Qwen3.6開源系列(qwen3.6-27b除外)
  • Qwen3.5開源系列

快速開始

以下樣本示範代碼解譯器如何高效解決數學計算問題。
  • OpenAI 相容-Responses API
  • OpenAI 相容-Chat Completions API
  • DashScope
為獲得最佳回複效果,建議同時開啟 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"),
    # 以下為新加坡地區的URL,調用時請將 {WorkspaceId} 替換為真實的業務空間ID,各地區的URL不同。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)

response = client.responses.create(
    model="qwen3.8-max",
    input="12的3次方",
    tools=[
        {
            "type": "code_interpreter"
        },
        {
            "type": "web_search"
        },
        {
            "type": "web_extractor"
        }
    ],
    extra_body = {
        "enable_thinking": True
    }
)
# 取消以下注釋查看中間過程輸出
# print(response.output)
print("="*20+"回複內容"+"="*20)
print(response.output_text)
print("="*20+"Token 消耗與工具調用"+"="*20)
print(response.usage)
響應樣本
====================回複內容====================
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 相容-Responses API
  • DashScope
以下樣本使用 OpenAI Python SDK,示範如何在流式響應中解析 API 返回的資料。
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下為新加坡地區的URL,調用時請將 {WorkspaceId} 替換為真實的業務空間ID,各地區的URL不同。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)

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

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

current_section = None
final_response = None

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

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

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

    # 響應完成,儲存最終結果用於擷取 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)}")

注意事項

  • 代碼解譯器與 Function Calling 互斥,不可同時啟用。
    同時啟用會報錯。
  • 啟用代碼解譯器後,單次請求會觸發多次模型推理,usage 欄位匯總所有調用的 Token 消耗。
  • 大模型在進行精確數值計算(如時間戳記轉換、日期格式化、複雜數學運算等)時可能產生偏差。建議在涉及精確計算的情境下啟用代碼解譯器,由 Python 程式碼完成計算,以確保結果準確。

計費說明

啟用代碼解譯器工具限時免費,但會增加 Token 消耗。
Token Plan
模型體驗
用量統計與效能監控
資產中心
服務支援