HEX
Server: LiteSpeed
System: Linux houston.panomity.com 6.8.0-100-generic #100-Ubuntu SMP PREEMPT_DYNAMIC Tue Jan 13 16:40:06 UTC 2026 x86_64
User: nudepix (1011)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: //opt/PraisonAI/docs/features/codeagent.mdx
---
title: "Code Execution AI Agent"
sidebarTitle: "Code Agent"
description: "Learn how to create AI agents that can write and execute Python code safely using e2b code interpreter."
icon: "code"
---

## Quick Start

<Tabs>
  <Tab title="Code">
    <Steps>
        <Step title="Install Package">
            First, install the required packages:
            ```bash
            pip install praisonaiagents e2b_code_interpreter
            ```
        </Step>

        <Step title="Set API Key">
            Set your OpenAI API key and E2B API key as an environment variable in your terminal:
            ```bash
            export OPENAI_API_KEY=your_api_key_here
            export E2B_API_KEY=your_e2b_api_key_here
            ```
        </Step>

        <Step title="Create a file">
            Create a new file `app.py` with the basic setup:
            ```python
            from praisonaiagents import Agent, Task, PraisonAIAgents
            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],
                verbose=True
            )

            # 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 = PraisonAIAgents(
                agents=[code_agent],
                tasks=[task],
                process="sequential",
                verbose=2
            )

            # Start execution
            agents.start()
            ```
        </Step>

        <Step title="Start Agents">
            Type this in your terminal to run your agents:
            ```bash
            python app.py
            ```
        </Step>
    </Steps>
  </Tab>
  <Tab title="No Code">
    <Steps>
        <Step title="Install Package">
            Install the PraisonAI package:
            ```bash
            pip install praisonai e2b_code_interpreter
            ```
        </Step>
        <Step title="Set API Key">
            Set your OpenAI API key as an environment variable in your terminal:
            ```bash
            export OPENAI_API_KEY=your_api_key_here
            ```
        </Step>
        <Step title="Create a file">
            Create a new file `agents.yaml` with the basic setup:
```yaml
framework: praisonai
process: sequential
topic: write and execute Python code
roles:
  developer:
    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.
```
        </Step>
        <Step title="Start Agents">
            Type this in your terminal to run your agents:
```bash
praisonai agents.yaml
```
        </Step>
    </Steps>
  </Tab>
</Tabs>

<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](/models).   
  - e2b_code_interpreter package installed
</Note>

## Understanding Code Agents

<Card title="What are Code Agents?" icon="question">
  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)
</Card>

## Features

<CardGroup cols={2}>
  <Card title="Code Writer" icon="pencil">
    Writes Python code based on requirements.
  </Card>
  <Card title="Safe Execution" icon="shield">
    Executes code in a sandboxed environment.
  </Card>
  <Card title="Error Handling" icon="bug">
    Manages code execution errors and debugging.
  </Card>
  <Card title="Results Processing" icon="output">
    Processes and formats execution results.
  </Card>
</CardGroup>

## Multi-Agent Code Development

<Tabs>
  <Tab title="Code">
    <Steps>
        <Step title="Install Package">
            First, install the required packages:
            ```bash
            pip install praisonaiagents e2b_code_interpreter
            ```
        </Step>

        <Step title="Set API Key">
            Set your OpenAI API key as an environment variable in your terminal:
            ```bash
            export OPENAI_API_KEY=your_api_key_here
            ```
        </Step>

        <Step title="Create a file">
            Create a new file `app.py` with the basic setup:
            ```python
            from praisonaiagents import Agent, Task, PraisonAIAgents
            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",
                verbose=True
            )

            # 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],
                verbose=True
            )

            # 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 = PraisonAIAgents(
                agents=[code_writer, code_executor],
                tasks=[writing_task, execution_task],
                process="sequential"
            )

            # Start execution
            agents.start()
            ```
        </Step>

        <Step title="Start Agents">
            Type this in your terminal to run your agents:
            ```bash
            python app.py
            ```
        </Step>
    </Steps>
  </Tab>
  <Tab title="No Code">
    <Steps>
        <Step title="Install Package">
            Install the PraisonAI package:
            ```bash
            pip install praisonai e2b_code_interpreter
            ```
        </Step>
        <Step title="Set API Key">
            Set your OpenAI API key as an environment variable in your terminal:
            ```bash
            export OPENAI_API_KEY=your_api_key_here
            ```
        </Step>
        <Step title="Create a file">
            Create a new file `agents.yaml` with the basic setup:
```yaml
framework: praisonai
process: sequential
topic: develop and execute Python code
roles:
  writer:
    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:
    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.
```
        </Step>
        <Step title="Start Agents">
            Type this in your terminal to run your agents:
```bash
praisonai agents.yaml
```
        </Step>
    </Steps>
  </Tab>
</Tabs>

### Configuration Options

```python
# 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],
    verbose=True,  # Enable detailed logging
    llm="gpt-4o"  # Language model to use
)
```

## Troubleshooting

<CardGroup cols={2}>
  <Card title="Code Errors" icon="triangle-exclamation">
    If code execution fails:
    - Check syntax errors
    - Verify package imports
    - Enable verbose mode for debugging
  </Card>

  <Card title="Sandbox Issues" icon="box">
    If sandbox execution fails:
    - Check environment setup
    - Verify permissions
    - Review resource limits
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="AutoAgents" icon="robot" href="./autoagents">
    Learn about automatically created and managed AI agents
  </Card>
  <Card title="Mini Agents" icon="microchip" href="./mini">
    Explore lightweight, focused AI agents
  </Card>
</CardGroup>

<Note>
  For optimal results, ensure code is properly formatted and tested in the sandbox environment before production use.
</Note>