Skip to main content
This example shows how to create agents that can write, execute, and analyze Python code safely.

What You’ll Learn

  • How to enable code execution in agents
  • How to use Docker for safe code execution
  • How to create code-writing assistants
  • Best practices for code execution security

Prerequisites

1

Install AutoGen with Docker support

2

Install Docker

Install Docker Desktop or Docker Engine from docker.com
3

Set your OpenAI API key

Basic Code Execution

Run the Example

Expected Output

---------- code_executor ---------- Code executed successfully. Output: [Plot saved to fibonacci.png]

Security Best Practices

Code execution can be dangerous. Always:
  • Use Docker for isolation
  • Limit network access
  • Set resource limits
  • Review generated code before execution
  • Never execute untrusted code directly

Secure Configuration

Custom Docker Image

Create a custom image with required dependencies:
Build and use:

Key Concepts

Code Executor

Runs code in an isolated environment (Docker container).

Round Robin

Agents take turns in sequence - useful for code generation and execution.

Docker Isolation

Prevents code from affecting the host system.

Work Directory

Shared directory between host and container for file access.

Common Use Cases

  • Data analysis and visualization
  • Mathematical calculations
  • File processing and transformation
  • Testing and validation
  • Automated report generation

Troubleshooting

Docker Not Running

Start Docker Desktop or run:

Image Not Found

Pull the required image:

Permission Denied

Add your user to the docker group:

Next Steps

Data Analysis

Build a complete data analysis agent

Swarm Pattern

Learn advanced multi-agent orchestration