Skip to main content

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="qwen4-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

deepseek-v4.1-flash-1017 supports the built-in code_interpreter tool in the Responses API in all six regions and corresponding deployment scopes listed on the model page. kimi-k3.1-pro (deployed on Alibaba Cloud Model Studio) supports the built-in code_interpreter tool in the Responses API in Beijing, Singapore, the US (Virginia), Germany (Frankfurt), Japan (Tokyo), and China (Hong Kong).
  • Responses API
  • Chat Completions API / DashScope
Qwen-Max: qwen4-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-0731Qwen3.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.8-Flash series, 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 efficiently solves mathematical calculation 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.
python
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 China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
)

response = client.responses.create(
    model="qwen4-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 the data returned by the API in a streaming response.
import os
from openai import OpenAI

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

response = client.responses.create(
    model="qwen4-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_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}")
    # If the model does not actually invoke the code interpreter (e.g., simple questions answered directly), the response has no x_tools field
    if hasattr(usage, 'x_tools'):
        print(f"Code Interpreter calls: {usage.x_tools.get('code_interpreter', {}).get('count', 0)}")
    else:
        print("Code Interpreter calls: 0")

Notes

  • Code Interpreter and Function calling are mutually exclusive and cannot be enabled at the same time.
    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.
  • Large models may produce inaccurate results in precise numerical calculations (such as timestamp conversion, date formatting, and complex mathematical operations). For scenarios that involve precise calculations, we recommend enabling Code Interpreter and letting Python code perform the calculation to ensure accurate results.

Billing

Code Interpreter is free for a limited time but increases token consumption.