# Code Execution

The Code Execution tool enables AI agents to write and execute sandboxed Python code on the fly to perform exact calculations, data analysis, and algorithmic transformations.

Tool Identifier: `code-execution`

## Why Code Execution?

Large language models excel at natural language understanding and conceptual reasoning, but standard next-token prediction can struggle with multi-digit arithmetic, combinatorial math, or statistical aggregations.

With **Code Execution**:

- **Deterministic Accuracy**: Complex arithmetic (e.g. compound interest, mortgage amortizations, currency conversions) is executed directly by Python rather than estimated probabilistically.
- **Data Transformation**: Agents can parse large text tables, sort lists, compute percentiles, and generate formatted summaries.
- **Zero Calculation Hallucinations**: When exact numerical results matter, the model delegates the calculation to code and reports the verified output.

## How It Works

When an agent needs to perform an analytical or mathematical task:

```mermaid
sequenceDiagram
    autonumber
    actor User
    participant Model as AI Model
    participant Sandbox as Python Sandbox

    User->>Model: "What is monthly payment on a $450k 30-year fixed loan at 6.25%?"
    Note over Model: Generates exact Python script
    Model->>Sandbox: Execute calculation script
    Sandbox-->>Model: Output: "2770.83"
    Model-->>User: "Your monthly principal and interest payment will be $2,770.83."
```

## How to Enable

### In the UI

When configuring an agent in the [Agent Builder](/agents/new) or editing an existing agent, check the box for:
☑️ **Code Execution 💻**

### In Agent YAML

Add `code-execution` to the `tools` array:

```yaml
tools:
  - code-execution
```

## Security & Sandboxing

Code execution occurs inside ephemeral, strictly isolated sandboxes with:

- No network access from within the script sandbox.
- Restricted execution time and memory limits.
- No access to underlying filesystem, host environments, or database credentials.

## Related Tools

- 🔎 **[Google Search Grounding](search.md)**: Search for raw data and facts before processing them with code.
- 🌐 **[Web Fetch Tool](fetch.md)**: Download public data tables or CSVs for analysis.
- 📖 **[Connected Tools Overview](index.md)**
