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.8-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"),
    # 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
    base_url="https://{WorkspaceId}.cn-beijing.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"),
    # 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
    base_url="https://{WorkspaceId}.cn-beijing.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
模型体验
模型调优
模型压缩目录节点
用量统计与性能监控
资产中心
服务支持