Skip to main content

Overview

The Code Interpreter is one of the most powerful built-in tools in Qwen-Agent. It allows agents to execute Python code in an isolated Docker environment, making it perfect for data analysis, visualization, mathematical computations, and more.

Quick Start

Here’s a simple example using Code Interpreter (examples/react_data_analysis.py:26):
from qwen_agent.agents import ReActChat

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

messages = [{
    'role': 'user',
    'content': 'Calculate the sum of squares from 1 to 100'
}]

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

How It Works

The Code Interpreter (qwen_agent/tools/code_interpreter.py:80) provides secure code execution through:
  1. Docker Isolation: Code runs in isolated containers
  2. Jupyter Kernel: Uses IPython kernel for interactive execution
  3. Automatic Setup: Handles image building and container management
  4. Result Capture: Returns stdout, stderr, and generated images

Architecture

┌─────────────────────┐
│   Qwen Agent        │
│                     │
│  ┌──────────────┐   │
│  │Code Interpreter│  │
│  └───────┬──────┘   │
└──────────┼──────────┘


┌─────────────────────┐
│  Docker Container   │
│  ┌───────────────┐  │
│  │ Jupyter Kernel│  │
│  │   (IPython)   │  │
│  └───────────────┘  │
│  • Isolated env     │
│  • Shared work dir  │
│  • Timeout control  │
└─────────────────────┘

Prerequisites

1
Step 1: Install Docker
2
Docker must be installed and running:
3
# Check Docker installation
docker --version
docker info
4
Step 2: Install Python Dependencies
5
pip install "qwen-agent[code_interpreter]"
6
This installs:
7
  • jupyter-client: For kernel communication
  • PIL: For image handling
  • Other dependencies
  • 8
    Step 3: Verify Setup
    9
    The Code Interpreter will automatically build its Docker image on first use (qwen_agent/tools/code_interpreter.py:172).

    Basic Usage

    Simple Code Execution

    from qwen_agent.agents import Assistant
    
    bot = Assistant(
        llm={'model': 'qwen-max'},
        function_list=['code_interpreter']
    )
    
    messages = [{
        'role': 'user',
        'content': 'Write a Python function to calculate Fibonacci numbers'
    }]
    
    for response in bot.run(messages):
        print(response)
    

    Data Analysis with Files

    from qwen_agent.agents import ReActChat
    import os
    
    bot = ReActChat(
        llm={'model': 'qwen-max'},
        function_list=['code_interpreter']
    )
    
    messages = [{
        'role': 'user',
        'content': [
            {'text': 'Analyze this CSV file and create a visualization'},
            {'file': 'data/stock_prices.csv'}
        ]
    }]
    
    for response in bot.run(messages):
        print(response)
    

    Mathematical Computations

    messages = [{
        'role': 'user',
        'content': 'Solve the equation: x^2 + 5x + 6 = 0 using numpy'
    }]
    
    for response in bot.run(messages):
        print(response)
    

    Configuration Options

    Customize the Code Interpreter with configuration parameters:
    from qwen_agent.agents import Assistant
    
    code_config = {
        'name': 'code_interpreter',
        'timeout': 60,  # Execution timeout in seconds
        'work_dir': '/custom/work/dir'  # Custom working directory
    }
    
    bot = Assistant(
        llm={'model': 'qwen-max'},
        function_list=[code_config]
    )
    

    Configuration Parameters

    ParameterTypeDefaultDescription
    timeoutint30Code execution timeout (seconds)
    work_dirstrautoWorking directory for code execution
    The working directory is automatically created and persists across executions within the same session. Files saved here are accessible to subsequent code runs.

    Working with Files

    The Code Interpreter automatically downloads remote files to the working directory (qwen_agent/tools/code_interpreter.py:114):
    messages = [{
        'role': 'user',
        'content': [
            {'text': 'Load and process this image'},
            {'file': 'https://example.com/image.jpg'}
        ]
    }]
    
    # The agent can access the file in its working directory
    for response in bot.run(messages):
        print(response)
    

    File Operations Example

    messages = [{
        'role': 'user',
        'content': '''
    Read the CSV file, calculate statistics, and save results to output.txt:
    1. Load the data with pandas
    2. Calculate mean, median, std
    3. Save results to a file
    ''',
    }, {
        'role': 'user',
        'content': [{'file': 'data.csv'}]
    }]
    

    Image Generation and Display

    Matplotlib plots are automatically captured and returned (qwen_agent/tools/code_interpreter.py:360):
    messages = [{
        'role': 'user',
        'content': '''
    Create a beautiful visualization:
    1. Generate sample data (sine and cosine waves)
    2. Create a plot with proper labels
    3. Use a nice color scheme
    '''
    }]
    
    for response in bot.run(messages):
        print(response)
        # Response includes: ![fig-001](path/to/image.png)
    

    Chinese Font Support

    The Code Interpreter includes built-in Chinese font support (qwen_agent/tools/code_interpreter.py:133):
    import matplotlib.pyplot as plt
    
    plt.rcParams['font.family'] = 'AlibabaPuHuiTi'
    plt.plot([1, 2, 3], [1, 4, 9])
    plt.title('中文标题')  # Chinese characters work!
    plt.show()
    

    Security Considerations

    Security Best Practices
    • Code runs in isolated Docker containers (no access to host system)
    • Each agent instance uses a separate kernel
    • Execution timeout prevents infinite loops
    • Container resources can be limited via Docker configuration
    • Files are only accessible within the working directory

    Timeout Protection

    The Code Interpreter includes automatic timeout protection (qwen_agent/tools/code_interpreter.py:140):
    # Long-running code will be automatically terminated
    messages = [{
        'role': 'user',
        'content': '''
    import time
    time.sleep(100)  # Will timeout after 30 seconds (default)
    '''
    }]
    
    # Response will include: "Timeout: Code execution exceeded the time limit."
    

    Container Isolation

    Each Code Interpreter instance runs in its own Docker container:
    • Network: Isolated from host network
    • Filesystem: Only mounted working directory is accessible
    • Processes: Cannot affect host processes
    • Resources: CPU and memory can be limited

    Advanced Usage

    Custom Docker Image

    The default Docker image is built from code_interpreter_image.dockerfile. You can customize it:
    FROM python:3.9-slim
    
    # Install your dependencies
    RUN pip install numpy pandas matplotlib scikit-learn
    RUN pip install jupyter ipykernel
    
    # Add custom packages
    RUN pip install torch transformers
    
    CMD ["python"]
    

    Environment Variables

    Configure via environment variables:
    # Custom working directory
    export M6_CODE_INTERPRETER_WORK_DIR=/custom/path
    
    # Image server URL for serving generated images
    export M6_CODE_INTERPRETER_STATIC_URL=https://yourserver.com/images
    

    Persistent Sessions

    The kernel persists across calls within the same agent instance (qwen_agent/tools/code_interpreter.py:126):
    bot = ReActChat(llm={'model': 'qwen-max'}, function_list=['code_interpreter'])
    
    # First call - define variables
    messages = [{'role': 'user', 'content': 'x = 10'}]
    for r in bot.run(messages): pass
    
    # Second call - variables still available
    messages.extend([{'role': 'user', 'content': 'print(x + 5)'}])
    for response in bot.run(messages):
        print(response)  # Outputs: 15
    

    Complete Example: Data Analysis Workflow

    Here’s a complete example from the codebase (examples/react_data_analysis.py):
    import os
    from qwen_agent.agents import ReActChat
    from qwen_agent.gui import WebUI
    
    ROOT_RESOURCE = os.path.join(os.path.dirname(__file__), 'resource')
    
    def init_agent_service():
        llm_cfg = {'model': 'qwen-max'}
        tools = ['code_interpreter']
        bot = ReActChat(
            llm=llm_cfg,
            name='Code Interpreter',
            description='This agent can run code to solve problems',
            function_list=tools
        )
        return bot
    
    def app_gui():
        bot = init_agent_service()
        chatbot_config = {
            'prompt.suggestions': [{
                'text': 'Analyze the file and draw a line chart',
                'files': [os.path.join(ROOT_RESOURCE, 'stock_prices.csv')]
            }, 'Draw a line graph y=x^2']
        }
        WebUI(bot, chatbot_config=chatbot_config).run()
    
    if __name__ == '__main__':
        app_gui()
    

    Troubleshooting

    Docker Not Available

    RuntimeError: Docker is not available
    
    Solution: Install and start Docker:
    # Ubuntu/Debian
    sudo apt-get install docker.io
    sudo systemctl start docker
    
    # macOS (install Docker Desktop)
    brew install --cask docker
    

    Permission Denied

    PermissionError: Cannot connect to Docker daemon
    
    Solution: Add user to docker group:
    sudo usermod -aG docker $USER
    # Log out and back in
    

    Image Build Failed

    RuntimeError: Failed to build Docker image
    
    Solution: Check Docker logs and rebuild:
    docker images  # Check existing images
    docker rmi code-interpreter:latest  # Remove if exists
    # Agent will rebuild on next run
    

    Kernel Connection Failed

    RuntimeError: Kernel failed to start
    
    Solution: Check container logs:
    docker ps -a  # Find container ID
    docker logs <container_id>
    

    Performance Tips

    Optimization Strategies
    • Reuse agent instances to maintain kernel sessions
    • Increase timeout for complex computations
    • Use vectorized operations (numpy/pandas) instead of loops
    • Limit image resolution for faster rendering
    • Clean up large temporary files within code

    Next Steps

    Build docs developers (and LLMs) love