Skip to main content
Tool calling

Code Interpreter

Enable the built-in Python Code Interpreter when calling a model. The model writes and runs Python code in a sandbox to solve complex problems such as mathematical calculations and data analytics.

How to use

Code Interpreter supports three invocation methods. The parameters differ for each method:
  • OpenAI-compatible - Responses API
  • OpenAI-compatible - Chat Completions API
  • DashScope
To enable Code Interpreter, add the code_interpreter tool to the tools parameter.
For the best results, enable the code_interpreter, web_search, and web_extractor tools at the same time.
# Import dependencies and create the client...
response = client.responses.create(
    model="qwen3.8-max",
    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)
After Code Interpreter is enabled, the model processes requests in these stages:
  1. Thinking: The model analyzes the user's request and generates ideas and steps to solve the problem.
  2. Code execution: The model generates and executes Python code.
  3. Result integration: The model receives the code execution result and plans the next steps.
  4. Response: The model generates a natural language response.
Steps 2 and 3 may loop multiple times.
The fields returned by different APIs vary:
  • Responses API: Thinking content is returned in an object with type="reasoning" in the output. Code execution is returned with type="code_interpreter_call". The response is returned with type="message".
  • Chat Completions API / DashScope: Thinking content is returned in the reasoning_content field. The response is returned in the content field. DashScope also supports returning code content in the tool_info field.

Scope

  • Responses API
  • Chat Completions API / DashScope
Qwen-Max: Qwen3.8-Max series, Qwen3.7-Max seriesQwen-Plus: Qwen3.7-Plus series, Qwen3.6-Plus series, Qwen3.5-Plus seriesDeepSeek: deepseek-v4-flash, deepseek-v4-flash-0731, deepseek-v4-proGLM: glm-5.2Qwen3.8 open source series

Other models

These models also support Code Interpreter but may not perform as well. Only supported through the Responses API.
  • Qwen-Flash: Qwen3.7-Flash series, Qwen3.6-Flash series, Qwen3.5-Flash series
  • Qwen3.6 open-source series (except qwen3.6-27b)
  • Qwen3.5 open source series

Getting started

These examples show how Code Interpreter solves mathematical problems.
  • OpenAI-compatible - Responses API
  • OpenAI-compatible - Chat Completions API
  • DashScope
For the best results, enable the code_interpreter, web_search, and web_extractor tools at the same time.
import os
from openai import OpenAI

client = OpenAI(
    # If the environment variable is not configured, replace the next line with: api_key="sk-xxx", using your Model Studio API key.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)

response = client.responses.create(
    model="qwen3.8-max",
    input="12 to the power of 3",
    tools=[
        {
            "type": "code_interpreter"
        },
        {
            "type": "web_search"
        },
        {
            "type": "web_extractor"
        }
    ],
    extra_body = {
        "enable_thinking": True
    }
)
# Uncomment the following line to view the intermediate process output
# print(response.output)
print("="*20+"Response Content"+"="*20)
print(response.output_text)
print("="*20+"Token Consumption and Tool Calls"+"="*20)
print(response.usage)
Example response
====================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}})

Parsing responses

  • OpenAI-compatible - Responses API
  • DashScope
The following OpenAI Python SDK example shows how to parse a streaming response.
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)

response = client.responses.create(
    model="qwen3.8-max",
    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:
    # Incremental output of the thinking process
    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)

    # Code Interpreter call completed
    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"

    # Incremental output of the final response
    elif event.type == "response.output_text.delta":
        if current_section != "answer":
            print_section("Complete Response")
            current_section = "answer"
        print(event.delta, end="", flush=True)

    # Response completed, save the final result to get usage
    elif event.type == "response.completed":
        final_response = event.response

# Output token consumption and number of tool calls
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)}")

Notes

  • Code Interpreter and Function calling are mutually exclusive.
    Enabling both in the same request causes an error.
  • When Code Interpreter is enabled, a single request may trigger multiple model inferences. The usage field summarizes the total token consumption for all calls in that request.

Billing

Code Interpreter is free for a limited time but increases token consumption.
Token Plan
Model Playground
Statistics and Monitoring
Support