> ## Documentation Index
> Fetch the complete documentation index at: https://praison.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Code Execution AI Agent

> Learn how to create AI agents that can write and execute Python code safely using e2b code interpreter.

Code agents run model-generated Python in a sandboxed interpreter so numeric and data tasks execute safely.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(name="code-runner", instructions="Write and execute Python to answer questions.")
agent.start("Plot a sine wave and return the peak value.")
```

The user submits a task; the agent writes Python, runs it in the sandbox, and returns the result.

> [!NOTE]
>
> `CodeAgent(model="gpt-4o")` is now accepted (canonical). `llm=` still works as a deprecated alias — see [Model Parameter](https://praison.ai/docs/features/model-parameter.md).

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "Code Agent"
        In[📋 Task] --> Agent[🤖 Agent]
        Agent --> Sandbox[⚙️ Sandbox]
        Sandbox --> Out[✅ Result]
    end

    classDef input fill:#6366F1,stroke:#7C90A0,color:#fff
    classDef agent fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef tool fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef output fill:#10B981,stroke:#7C90A0,color:#fff
    class In input
    class Agent agent
    class Sandbox tool
    class Out output
```

## Quick Start

> [tab] Code
>
> **1. Install Package**
>
> First, install the required packages:
>
> ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> pip install praisonaiagents e2b_code_interpreter
> ```
>
> **2. Set API Key**
>
> Set your OpenAI API key and E2B API key as an environment variable in your terminal:
>
> ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> export OPENAI_API_KEY="${OPENAI_API_KEY:?Set OPENAI_API_KEY in your shell}"
> export E2B_API_KEY=your_e2b_api_key_here
> ```
>
> **3. Create a file**
>
> Create a new file `app.py` with the basic setup:
>
> ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> from praisonaiagents import Agent, Task, AgentTeam
> from e2b_code_interpreter import Sandbox
>
> def code_interpreter(code: str):
>     print(f"\n{'='*50}\n> Running following AI-generated code:\n{code}\n{'='*50}")
>     exec_result = Sandbox().run_code(code)
>     if exec_result.error:
>         print("[Code Interpreter error]", exec_result.error)
>         return {"error": str(exec_result.error)}
>     else:
>         results = []
>         for result in exec_result.results:
>             if hasattr(result, '__iter__'):
>                 results.extend(list(result))
>             else:
>                 results.append(str(result))
>         logs = {"stdout": list(exec_result.logs.stdout), "stderr": list(exec_result.logs.stderr)}
>         return json.dumps({"results": results, "logs": logs})
>
> # Create code agent
> code_agent = Agent(
>     role="Code Developer",
>     goal="Write and execute Python code",
>     backstory="Expert Python developer with strong coding skills",
>     tools=[code_interpreter]
> )
>
> # Create a task
> task = Task(
>     description="Write and execute a Python script to analyze data",
>     expected_output="Working Python script with execution results",
>     agent=code_agent
> )
>
> # Create and start the agents
> agents = AgentTeam(
>     agents=[code_agent],
>     tasks=[task],
>     process="sequential"
> )
>
> # Start execution
> agents.start()
> ```
>
> **4. Start Agents**
>
> Type this in your terminal to run your agents:
>
> ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> python app.py
> ```

> [tab] No Code
>
> **1. Install Package**
>
> Install the PraisonAI package:
>
> ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> pip install praisonai e2b_code_interpreter
> ```
>
> **2. Set API Key**
>
> Set your OpenAI API key as an environment variable in your terminal:
>
> ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> export OPENAI_API_KEY="${OPENAI_API_KEY:?Set OPENAI_API_KEY in your shell}"
> ```
>
> **3. Create a file**
>
> Create a new file `agents.yaml` with the basic setup:
>
> ```yaml theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> framework: praisonai
> process: sequential
> topic: write and execute Python code
> agents:  # Canonical: use 'agents' instead of 'roles'
>   developer:
>     instructions:  # Canonical: use 'instructions' instead of 'backstory' Expert Python developer with strong coding skills.
>     goal: Write and execute Python code safely
>     role: Code Developer
>     tools:
>       - code_interpreter
>     tasks:
>       coding_task:
>         description: Write and execute a Python script to analyze data.
>         expected_output: Working Python script with execution results.
> ```
>
> **4. Start Agents**
>
> Type this in your terminal to run your agents:
>
> ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> praisonai agents.yaml
> ```

> [!NOTE]
>
> **Requirements**
>
> * Python 3.10 or higher
> * OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](https://praison.ai/docs/models.md).
> * e2b\_code\_interpreter package installed

## How It Works

The user submits a task; the agent writes Python, runs it in the sandboxed interpreter, and returns the captured result.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant Agent
    participant Sandbox

    User->>Agent: start("Plot a sine wave")
    Agent->>Agent: Generate Python code
    Agent->>Sandbox: run_code(code)
    Sandbox-->>Agent: stdout + results
    Agent-->>User: Answer
```

***

## Understanding Code Agents

> [card] What are Code Agents?
>
> Code agents are specialized AI agents that can:
>
> * Write Python code based on requirements
> * Execute code safely in a sandboxed environment
> * Handle code execution results and errors
> * Work together in a pipeline (writer → executor)

## Features

> [card] Code Writer
>
> Writes Python code based on requirements.

> [card] Safe Execution
>
> Executes code in a sandboxed environment.

> [card] Error Handling
>
> Manages code execution errors and debugging.

> [card] Results Processing
>
> Processes and formats execution results.

## Multi-Agent Code Development

> [tab] Code
>
> **1. Install Package**
>
> First, install the required packages:
>
> ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> pip install praisonaiagents e2b_code_interpreter
> ```
>
> **2. Set API Key**
>
> Set your OpenAI API key as an environment variable in your terminal:
>
> ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> export OPENAI_API_KEY="${OPENAI_API_KEY:?Set OPENAI_API_KEY in your shell}"
> ```
>
> **3. Create a file**
>
> Create a new file `app.py` with the basic setup:
>
> ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> from praisonaiagents import Agent, Task, AgentTeam
> from e2b_code_interpreter import Sandbox
>
> def code_interpreter(code: str):
>     print(f"\n{'='*50}\n> Running following AI-generated code:\n{code}\n{'='*50}")
>     exec_result = Sandbox().run_code(code)
>     if exec_result.error:
>         print("[Code Interpreter error]", exec_result.error)
>         return {"error": str(exec_result.error)}
>     else:
>         results = []
>         for result in exec_result.results:
>             if hasattr(result, '__iter__'):
>                 results.extend(list(result))
>             else:
>                 results.append(str(result))
>         logs = {"stdout": list(exec_result.logs.stdout), "stderr": list(exec_result.logs.stderr)}
>         return json.dumps({"results": results, "logs": logs})
>
> # Create first agent for writing code
> code_writer = Agent(
>     role="Code Writer",
>     goal="Write efficient Python code",
>     backstory="Expert Python developer specializing in code writing"
> )
>
> # Create second agent for code execution
> code_executor = Agent(
>     role="Code Executor",
>     goal="Execute and validate Python code",
>     backstory="Expert in code execution and testing",
>     tools=[code_interpreter]
> )
>
> # Create first task
> writing_task = Task(
>     description="Write a Python script for data analysis",
>     expected_output="Complete Python script",
>     agent=code_writer
> )
>
> # Create second task
> execution_task = Task(
>     description="Execute and validate the Python script",
>     expected_output="Execution results and validation",
>     agent=code_executor
> )
>
> # Create and start the agents
> agents = AgentTeam(
>     agents=[code_writer, code_executor],
>     tasks=[writing_task, execution_task],
>     process="sequential"
> )
>
> # Start execution
> agents.start()
> ```
>
> **4. Start Agents**
>
> Type this in your terminal to run your agents:
>
> ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> python app.py
> ```

> [tab] No Code
>
> **1. Install Package**
>
> Install the PraisonAI package:
>
> ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> pip install praisonai e2b_code_interpreter
> ```
>
> **2. Set API Key**
>
> Set your OpenAI API key as an environment variable in your terminal:
>
> ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> export OPENAI_API_KEY="${OPENAI_API_KEY:?Set OPENAI_API_KEY in your shell}"
> ```
>
> **3. Create a file**
>
> Create a new file `agents.yaml` with the basic setup:
>
> ```yaml theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> framework: praisonai
> process: sequential
> topic: develop and execute Python code
> agents:  # Canonical: use 'agents' instead of 'roles'
>   writer:
>     instructions:  # Canonical: use 'instructions' instead of 'backstory' Expert Python developer specializing in code writing.
>     goal: Write efficient Python code
>     role: Code Writer
>     tasks:
>       writing_task:
>         description: Write a Python script for data analysis.
>         expected_output: Complete Python script.
>
>   executor:
>     instructions:  # Canonical: use 'instructions' instead of 'backstory' Expert in code execution and testing.
>     goal: Execute and validate Python code
>     role: Code Executor
>     tools:
>       - code_interpreter
>     tasks:
>       execution_task:
>         description: Execute and validate the Python script.
>         expected_output: Execution results and validation.
> ```
>
> **4. Start Agents**
>
> Type this in your terminal to run your agents:
>
> ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> praisonai agents.yaml
> ```

### Configuration Options

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Create an agent with advanced code execution configuration
agent = Agent(
    role="Code Developer",
    goal="Write and execute Python code",
    backstory="Expert in Python development",
    tools=[code_interpreter],
    llm="gpt-4o"  # Language model to use
)
```

## Troubleshooting

> [card] Code Errors
>
> If code execution fails:
>
> * Check syntax errors
> * Verify package imports
> * Enable verbose mode for debugging

> [card] Sandbox Issues
>
> If sandbox execution fails:
>
> * Check environment setup
> * Verify permissions
> * Review resource limits

## Best Practices

> [accordion] Run in sandbox first
>
> Test generated code in the sandbox environment before enabling execution in production workflows.

> [accordion] Limit interpreter scope
>
> Register only the tools and packages the agent needs — fewer imports reduce sandbox escape risk.

> [accordion] Use verbose mode when debugging
>
> Enable verbose output to inspect code the model generates and stderr from failed runs.

> [accordion] Prefer safe execution mode
>
> Keep `code_mode="safe"` unless you explicitly need direct host execution and accept the trade-offs. Safe mode runs code in a subprocess and enforces `ExecutionConfig(timeout=...)` as a hard per-call limit; `"unsafe"` mode runs in-process and has **no hard timeout** — a runaway loop blocks the worker. Choose `"safe"` whenever the timeout must be a guarantee.

## Next Steps

> [card] [AutoAgents](https://praison.ai/docs/features/autoagents.md)
>
> Learn about automatically created and managed AI agents

> [card] [Mini Agents](https://praison.ai/docs/features/mini.md)
>
> Explore lightweight, focused AI agents

> [card] [Code Execution with Tools](https://praison.ai/docs/features/code-execution-with-tools.md)
>
> Let model-generated code call your registered tools directly — collapse multi-step pipelines into a single turn.

> [!NOTE]
>
> For optimal results, ensure code is properly formatted and tested in the sandbox environment before production use.

## Related

> [card]
>
> Use a specialised agent for numerical and mathematical tasks.
>
> [Open](https://praison.ai/docs/features/mathagent.md)

> [card]
>
> Run the PraisonAI coding assistant from the command line.
>
> [Open](https://praison.ai/docs/features/code.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.