Skip to main content
The Code Interpreter tool allows agents to execute Python code in a secure, isolated Docker container. It’s particularly useful for data analysis, visualization, and computational tasks.

Overview

Code Interpreter provides:
  • Sandboxed Execution: Code runs in an isolated Docker container
  • Data Visualization: Automatic handling of matplotlib plots and images
  • Timeout Protection: Configurable execution timeouts
  • Working Directory: Persistent workspace for file operations
  • Pre-installed Libraries: Common data science packages included

Registration

@register_tool('code_interpreter')
class CodeInterpreter(BaseToolWithFileAccess):
    ...
Tool Name: code_interpreter

Parameters

code
string
required
The Python code to execute. Can be provided as a plain string or within a JSON object.

Parameter Schema

{
  "type": "object",
  "properties": {
    "code": {
      "description": "The python code.",
      "type": "string"
    }
  },
  "required": ["code"]
}

Configuration

When initializing the Code Interpreter, you can configure:
work_dir
string
Working directory for code execution and file storage. Defaults to $DEFAULT_WORKSPACE/tools/code_interpreter.
timeout
int
default:30
Maximum execution time in seconds. Code execution will be terminated if it exceeds this limit.

Environment Variables

M6_CODE_INTERPRETER_WORK_DIR
string
Override the default working directory via environment variable.
M6_CODE_INTERPRETER_STATIC_URL
string
Base URL for serving generated images (useful for web deployments).

Usage

Basic Usage

from qwen_agent.tools import CodeInterpreter

# Initialize the tool
code_interpreter = CodeInterpreter()

# Execute simple code
result = code_interpreter.call(params='{"code": "print(2 + 2)"}')
print(result)
# Output: stdout:
#         ```
#         4
#         ```

With Data Analysis

import json

code = """
import pandas as pd
import matplotlib.pyplot as plt

# Load data
df = pd.read_csv('data.csv')
print(df.head())

# Create visualization
plt.figure(figsize=(10, 6))
plt.plot(df['date'], df['value'])
plt.title('Data Over Time')
plt.savefig('plot.png')
plt.show()
"""

result = code_interpreter.call(
    params=json.dumps({'code': code}),
    files=['path/to/data.csv'],
    timeout=60
)
print(result)

Using with Agents

from qwen_agent.agents import Assistant

bot = Assistant(
    llm={'model': 'qwen-max'},
    function_list=['code_interpreter']
)

messages = [
    {
        'role': 'user',
        'content': [
            {'text': 'Analyze this CSV file and create a visualization'},
            {'file': 'path/to/data.csv'}
        ]
    }
]

for response in bot.run(messages=messages):
    print(response)

Return Format

The tool returns results in markdown format:

Standard Output

stdout:

Output text here

Images

Generated plots are automatically captured and returned:
![fig-001](path/to/image.png)

Errors

error:

Traceback and error message

Timeout

Timeout: Code execution exceeded the time limit.

Docker Image

The tool uses a Docker image named code-interpreter:latest which is automatically built from the included Dockerfile.

Required Dependencies (Host)

The host machine must have Docker installed and the Docker daemon running.
To check Docker availability:
docker --version
docker info
Host Python dependencies:
pip install "qwen-agent[code_interpreter]"
This installs:
  • jupyter-client - For kernel communication
  • Pillow - For image handling

Container Features

  • Jupyter Kernel: IPython kernel for code execution
  • Pre-installed Packages: numpy, pandas, matplotlib, seaborn, scikit-learn, scipy
  • Chinese Font Support: Alibaba PuHuiTi font for matplotlib
  • Isolated Environment: Separate container per agent instance

Advanced Features

Persistent Kernels

Kernels are reused across multiple call() invocations within the same agent instance:
code_interpreter = CodeInterpreter()

# First execution - kernel starts
code_interpreter.call(params='{"code": "x = 42"}')

# Second execution - uses same kernel, x is still defined
result = code_interpreter.call(params='{"code": "print(x)"}')
print(result)  # Output: 42

File Handling

Files passed to call() are automatically copied to the working directory:
result = code_interpreter.call(
    params='{"code": "import pandas as pd; df = pd.read_csv(\'data.csv\'); print(df.shape)"}',
    files=['https://example.com/data.csv', 'local/file.txt']
)

Timeout Mechanism

A countdown timer is injected to enforce timeouts:
result = code_interpreter.call(
    params='{"code": "import time; time.sleep(100)"}',
    timeout=5  # Will timeout after 5 seconds
)
# Returns: "Timeout: Code execution exceeded the time limit."

Error Handling

from qwen_agent.tools.base import ToolServiceError

try:
    result = code_interpreter.call(
        params='{"code": "1/0"}'
    )
    print(result)
except ToolServiceError as e:
    print(f"Error: {e.message}")

Best Practices

  • Code executes in an isolated Docker container
  • No network access by default (can be configured)
  • Limited to the working directory
  • Timeout protection prevents runaway processes
  • Reuse the same CodeInterpreter instance for multiple calls
  • Set appropriate timeouts based on expected execution time
  • Docker image is built once and cached
  • Kernel remains active between calls for faster execution
  • Each CodeInterpreter instance creates one Docker container
  • Containers are automatically cleaned up on instance deletion
  • Use work_dir to control disk usage
  • Monitor Docker resource consumption for production deployments

Example: Data Analysis Agent

from qwen_agent.agents import ReActChat
import os

def create_data_analyst():
    bot = ReActChat(
        llm={'model': 'qwen-max'},
        name='Data Analyst',
        description='This agent can analyze data and create visualizations',
        function_list=['code_interpreter']
    )
    return bot

# Use the agent
bot = create_data_analyst()

messages = [
    {
        'role': 'user',
        'content': [
            {'text': 'Load the CSV, show summary statistics, and create a histogram'},
            {'file': 'stock_prices.csv'}
        ]
    }
]

for response in bot.run(messages):
    print(response)

Troubleshooting

Ensure Docker is installed:
# Ubuntu/Debian
sudo apt-get install docker.io

# macOS
brew install --cask docker
Add your user to the docker group:
sudo usermod -aG docker $USER
# Log out and back in
Check the Dockerfile at qwen_agent/tools/resource/code_interpreter_image.dockerfile and ensure base images are accessible.
Check Docker logs:
docker ps -a  # Find container ID
docker logs <container_id>

Python Executor

Execute Python without Docker (less secure, faster)

ReAct Agent

Agent that can use Code Interpreter for reasoning

Build docs developers (and LLMs) love