Skip to main content

Overview

CodeInterpreter provides a secure Python code execution environment using Docker containers with Jupyter kernels.

Class Signature

from qwen_agent.tools import CodeInterpreter

class CodeInterpreter(BaseToolWithFileAccess):
    name = 'code_interpreter'
    description = 'Python code sandbox, which can be used to execute Python code.'
    parameters = {
        'type': 'object',
        'properties': {
            'code': {
                'description': 'The python code.',
                'type': 'string',
            }
        },
        'required': ['code'],
    }

Parameters

code
str
required
Python code to execute
timeout
int
default:"30"
Execution timeout in seconds

Features

  • Isolated Execution: Runs in Docker container
  • File Access: Can read/write files in workspace
  • Visualization: Supports matplotlib plots
  • Libraries: Pre-installed scientific Python libraries

Usage Example

Basic Execution

from qwen_agent.tools import CodeInterpreter

tool = CodeInterpreter()

code = '''
import numpy as np
result = np.array([1, 2, 3]).sum()
print(result)
'''

result = tool.call({'code': code})
print(result)
# Output: stdout: 6

With Timeout

tool = CodeInterpreter()

code = '''
import time
for i in range(5):
    print(f"Step {i}")
    time.sleep(1)
'''

result = tool.call({'code': code}, timeout=10)
print(result)

Data Visualization

code = '''
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.plot(x, y)
plt.title("Sine Wave")
plt.show()
'''

result = tool.call({'code': code})
print(result)
# Output includes image: ![fig-001](path/to/image.png)

File Processing

tool = CodeInterpreter()

code = '''
import pandas as pd

df = pd.read_csv('data.csv')
print(df.describe())
'''

result = tool.call(
    {'code': code},
    files=['data.csv']  # File will be copied to workspace
)
print(result)

With Agent

from qwen_agent.agents import FnCallAgent
from qwen_agent.llm.schema import Message

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

messages = [
    Message(
        role='user',
        content='Calculate the first 10 Fibonacci numbers'
    )
]

for response in agent.run(messages):
    print(response[-1].content)

Pre-installed Libraries

  • numpy
  • pandas
  • matplotlib
  • scipy
  • scikit-learn
  • And more…

Docker Requirements

Docker must be installed and running:
# Check Docker
docker --version
docker info

# Install dependencies
pip install "qwen-agent[code_interpreter]"

Configuration

tool = CodeInterpreter({
    'work_dir': '/path/to/workspace',  # Custom workspace
    'timeout': 60  # Default timeout
})

Error Handling

code = '''
print(undefined_variable)
'''

result = tool.call({'code': code})
print(result)
# Output: error: NameError: name 'undefined_variable' is not defined

Output Format

Results include:
  • stdout: Standard output
  • stderr: Error output
  • error: Exception tracebacks
  • images: Generated plots as markdown images

See Also

Build docs developers (and LLMs) love