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

# Code Interpreter

> Execute Python code in a secure sandbox for data analysis, calculations, and problem-solving

## What is Code Interpreter?

Code Interpreter is a powerful tool that allows AI to write and execute Python code in a secure sandbox environment. It enables complex calculations, data analysis, file manipulation, and more - all within your conversation.

<Note>
  Think of Code Interpreter as giving AI the ability to "show its work" by writing and running actual code to solve problems.
</Note>

## When to Use Code Interpreter

<CardGroup cols={2}>
  <Card title="Data Analysis" icon="chart-bar">
    Analyze CSV files, calculate statistics, identify trends
  </Card>

  <Card title="Mathematical Operations" icon="calculator">
    Complex calculations, equations, mathematical modeling
  </Card>

  <Card title="File Processing" icon="file-code">
    Convert formats, extract data, manipulate files
  </Card>

  <Card title="Visualization" icon="chart-line">
    Create charts, graphs, and data visualizations
  </Card>

  <Card title="Problem Solving" icon="lightbulb">
    Algorithm implementation, logic verification
  </Card>

  <Card title="Simulations" icon="flask">
    Run simulations, test scenarios, model systems
  </Card>
</CardGroup>

## Enabling Code Interpreter

<Tabs>
  <Tab title="Per Message">
    Enable for specific tasks:

    1. Click **Code Interpreter** toggle in top bar
    2. Toggle turns blue when active
    3. Send your request
    4. AI will use code when beneficial

    <Tip>
      AI automatically decides when to use code based on your request.
    </Tip>
  </Tab>

  <Tab title="Always On">
    Enable by default:

    1. Go to **Settings** > **Preferences**
    2. Find **Code Interpreter** section
    3. Toggle **Enable by default**
    4. Save changes

    Can still toggle off for specific messages.
  </Tab>

  <Tab title="In Projects">
    Enable for entire project:

    1. Open Project settings
    2. Go to **Tools** tab
    3. Enable **Code Interpreter**
    4. All chats in project can use it
  </Tab>
</Tabs>

## How It Works

<Steps>
  <Step title="Request Analysis">
    AI determines if code execution would help answer your question
  </Step>

  <Step title="Code Generation">
    AI writes Python code to solve the problem

    ```python theme={null}
    import pandas as pd
    import matplotlib.pyplot as plt

    # AI writes relevant code
    data = pd.read_csv('sales_data.csv')
    total_sales = data['revenue'].sum()
    ```
  </Step>

  <Step title="Code Execution">
    Code runs in secure sandbox environment:

    * Isolated from your system
    * No internet access
    * Time-limited execution
    * Safe and contained
  </Step>

  <Step title="Results Returned">
    AI receives output and incorporates it into response:

    * Calculation results
    * Generated visualizations
    * Error messages (if any)
    * Data outputs
  </Step>

  <Step title="Explanation">
    AI explains the code and results in natural language
  </Step>
</Steps>

## What You Can Do

### Data Analysis

<Tabs>
  <Tab title="CSV Analysis">
    **Analyze uploaded CSV files**:

    ```
    Analyze this sales data and tell me:
    1. Total revenue
    2. Best performing month
    3. Average order value
    4. Revenue trend over time

    [upload sales_data.csv]
    ```

    AI will:

    * Read and parse the CSV
    * Calculate requested metrics
    * Identify patterns
    * Create visualizations
  </Tab>

  <Tab title="Statistical Analysis">
    **Calculate statistics**:

    ```
    Calculate mean, median, mode, and standard deviation 
    for the price column in this dataset
    ```

    ```python theme={null}
    # AI-generated code
    stats = {
        'mean': data['price'].mean(),
        'median': data['price'].median(),
        'mode': data['price'].mode()[0],
        'std': data['price'].std()
    }
    ```
  </Tab>

  <Tab title="Data Cleaning">
    **Clean and prepare data**:

    ```
    Clean this dataset:
    - Remove duplicates
    - Handle missing values
    - Standardize date format
    - Remove outliers
    ```

    AI writes code to clean and export cleaned data.
  </Tab>

  <Tab title="Trend Analysis">
    **Identify patterns**:

    ```
    Plot the trend of website visits over the past 6 months
    and identify any seasonal patterns
    ```

    Creates visualizations and analysis.
  </Tab>
</Tabs>

### Mathematical Operations

<Tabs>
  <Tab title="Complex Calculations">
    **Solve equations**:

    ```
    Calculate compound interest on $10,000 invested at 
    5% annual rate, compounded quarterly for 10 years
    ```

    ```python theme={null}
    principal = 10000
    rate = 0.05
    times_compounded = 4
    years = 10

    amount = principal * (1 + rate/times_compounded)**(times_compounded*years)
    interest = amount - principal
    ```
  </Tab>

  <Tab title="Matrix Operations">
    **Linear algebra**:

    ```
    Multiply these two matrices and find the determinant
    Matrix A: [[1,2],[3,4]]
    Matrix B: [[5,6],[7,8]]
    ```

    Uses NumPy for matrix operations.
  </Tab>

  <Tab title="Financial Calculations">
    **Finance and accounting**:

    ```
    Calculate NPV for a project with initial investment 
    of $100k and cash flows of $30k, $40k, $50k over 
    3 years at 10% discount rate
    ```

    Shows full calculation with explanation.
  </Tab>
</Tabs>

### Visualizations

<Tabs>
  <Tab title="Charts & Graphs">
    **Create visualizations**:

    ```
    Create a bar chart comparing revenue across regions
    ```

    ```python theme={null}
    import matplotlib.pyplot as plt

    regions = ['North', 'South', 'East', 'West']
    revenue = [45000, 38000, 52000, 41000]

    plt.bar(regions, revenue)
    plt.title('Revenue by Region')
    plt.xlabel('Region')
    plt.ylabel('Revenue ($)')
    plt.show()
    ```

    Chart appears directly in chat.
  </Tab>

  <Tab title="Data Plots">
    **Line plots, scatter plots**:

    ```
    Plot the relationship between advertising spend 
    and sales revenue
    ```

    Creates scatter plot with trend line.
  </Tab>

  <Tab title="Heatmaps">
    **Correlation analysis**:

    ```
    Create a heatmap showing correlations between 
    all numeric columns in the dataset
    ```

    Visual correlation matrix.
  </Tab>
</Tabs>

### File Operations

<Tabs>
  <Tab title="Format Conversion">
    **Convert between formats**:

    ```
    Convert this CSV to JSON format
    ```

    ```
    Convert this JSON to a formatted Excel file
    ```

    Downloads converted file.
  </Tab>

  <Tab title="Data Extraction">
    **Extract specific data**:

    ```
    Extract all email addresses from this text file
    ```

    ```
    Pull out dates and amounts from these receipts
    ```

    Returns structured data.
  </Tab>

  <Tab title="File Generation">
    **Create files**:

    ```
    Generate a CSV file with 100 sample customer 
    records including name, email, and purchase history
    ```

    Creates and provides download link.
  </Tab>
</Tabs>

## Understanding Code Output

### Reading Results

<AccordionGroup>
  <Accordion title="Code Block Display">
    AI shows the code it's executing:

    ```python theme={null}
    # Calculating total sales
    df = pd.read_csv('sales.csv')
    total = df['amount'].sum()
    print(f"Total sales: ${total:,.2f}")
    ```

    * Syntax highlighted
    * Comments explaining steps
    * Copyable with one click
  </Accordion>

  <Accordion title="Execution Output">
    Results appear in output block:

    ```
    Total sales: $1,234,567.89

    Top 5 products:
    1. Widget A - $450,233
    2. Gadget B - $389,012
    3. Tool C - $278,901
    4. Device D - $234,567
    5. Gizmo E - $198,432
    ```

    Clear, formatted output.
  </Accordion>

  <Accordion title="Generated Images">
    Charts and graphs display inline:

    <Frame>
      !\[Example chart showing data visualization]
    </Frame>

    * High-quality images
    * Downloadable
    * Regenerate with different styles
  </Accordion>

  <Accordion title="Error Messages">
    If code fails:

    ```
    Error: KeyError: 'revenue'
    Column 'revenue' not found in dataframe.
    Available columns: ['date', 'product', 'sales_amount']
    ```

    * Clear error description
    * What went wrong
    * AI suggests fix
  </Accordion>
</AccordionGroup>

## Available Python Libraries

Code Interpreter includes many popular libraries:

### Data Analysis

```python theme={null}
import pandas as pd           # Data manipulation
import numpy as np            # Numerical computing
from scipy import stats       # Statistical functions
```

### Visualization

```python theme={null}
import matplotlib.pyplot as plt  # Plotting
import seaborn as sns            # Statistical viz
```

### Machine Learning

```python theme={null}
from sklearn import *         # Scikit-learn
```

### Utilities

```python theme={null}
import json                   # JSON handling
import csv                    # CSV operations
import datetime               # Date/time
import re                     # Regular expressions
import math                   # Mathematical functions
```

<Info>
  Most popular Python libraries are available. If you need something specific, just ask!
</Info>

## Advanced Features

### Multi-Step Operations

Complex workflows with multiple code executions:

<Steps>
  <Step title="Load and Clean">
    ```python theme={null}
    # Load data
    df = pd.read_csv('data.csv')
    # Clean data
    df = df.dropna()
    df['date'] = pd.to_datetime(df['date'])
    ```
  </Step>

  <Step title="Transform">
    ```python theme={null}
    # Calculate metrics
    df['month'] = df['date'].dt.month
    monthly_sales = df.groupby('month')['revenue'].sum()
    ```
  </Step>

  <Step title="Visualize">
    ```python theme={null}
    # Create chart
    plt.plot(monthly_sales.index, monthly_sales.values)
    plt.title('Monthly Revenue Trend')
    plt.show()
    ```
  </Step>

  <Step title="Export">
    ```python theme={null}
    # Save results
    monthly_sales.to_csv('monthly_summary.csv')
    ```
  </Step>
</Steps>

### Interactive Analysis

Have conversations about the code:

```
You: Analyze this dataset for trends

AI: [Runs analysis code]
Here's what I found...

You: Can you break down the results by region?

AI: [Modifies code to add regional breakdown]
Sure, here's the regional analysis...

You: Now create a visualization

AI: [Generates chart code]
Here's the visualization...
```

### Error Recovery

AI handles errors gracefully:

1. **Code fails** → AI sees error
2. **AI analyzes** → Understands problem
3. **AI fixes** → Rewrites code
4. **Code runs** → Success!

You see the fix and explanation.

## Security & Limitations

### Sandbox Environment

<CardGroup cols={2}>
  <Card title="Isolated Execution" icon="shield">
    Code runs completely isolated from your system
  </Card>

  <Card title="No Network Access" icon="wifi-slash">
    Cannot make external network requests
  </Card>

  <Card title="Time Limits" icon="clock">
    Execution timeout prevents infinite loops
  </Card>

  <Card title="Memory Limits" icon="memory">
    Limited RAM prevents resource exhaustion
  </Card>
</CardGroup>

### What's Allowed

✅ File operations (uploaded files only)\
✅ Data analysis and calculations\
✅ Image generation (charts/graphs)\
✅ Mathematical operations\
✅ String manipulation\
✅ Data transformations

### What's Not Allowed

❌ Network requests\
❌ System file access\
❌ Installing packages\
❌ Long-running operations (>60s)\
❌ Large file generation (>50MB)\
❌ Cryptocurrency mining

<Warning>
  Code Interpreter is powerful but sandboxed for security. It cannot access your local files or make network requests.
</Warning>

## Best Practices

<AccordionGroup>
  <Accordion title="Be Specific About Goals">
    **Better requests**:

    ❌ "Analyze this data"\
    ✅ "Calculate the average, median, and identify the top 10 highest values in the 'sales' column"

    Specificity helps AI write targeted code.
  </Accordion>

  <Accordion title="Provide Context">
    **Include relevant information**:

    ```
    This CSV contains sales data with columns:
    - date (YYYY-MM-DD format)
    - product_id
    - quantity
    - price
    - region

    Calculate total revenue by region
    ```

    Context prevents errors.
  </Accordion>

  <Accordion title="Start Simple">
    **Build complexity gradually**:

    1. First: "Load and show first 5 rows"
    2. Then: "Calculate summary statistics"
    3. Finally: "Create detailed visualization"

    Step-by-step is more reliable.
  </Accordion>

  <Accordion title="Verify Results">
    **Check important calculations**:

    * Spot check numbers
    * Verify logic makes sense
    * Compare with expected ranges
    * Ask AI to explain unusual results

    AI is powerful but can make mistakes.
  </Accordion>
</AccordionGroup>

## Example Use Cases

### Sales Analysis

```
Analyze this sales data:
1. Total revenue by month
2. Best performing products
3. Growth rate month-over-month
4. Create a line chart of revenue trend
5. Identify any anomalies

[upload sales_data.csv]
```

### Scientific Calculations

```
Calculate the trajectory of a projectile launched at:
- Initial velocity: 50 m/s
- Angle: 45 degrees
- Height: 10 meters

Show:
- Maximum height reached
- Total distance traveled
- Time of flight
- Plot the trajectory
```

### Data Transformation

```
Transform this customer data:
1. Convert dates to ISO format
2. Standardize phone numbers
3. Clean up email addresses
4. Remove duplicates
5. Export as clean CSV
```

## Troubleshooting

<AccordionGroup>
  <Accordion title="Code Not Executing">
    **Possible causes**:

    * Code Interpreter not enabled
    * Syntax error in code
    * Execution timeout

    **Solutions**:

    * Verify toggle is on
    * Ask AI to fix errors
    * Simplify the operation
  </Accordion>

  <Accordion title="Wrong Results">
    **Common issues**:

    * Misunderstood requirements
    * Wrong assumptions about data
    * Logic error in code

    **Solutions**:

    * Clarify your requirements
    * Provide data structure details
    * Ask AI to explain its approach
    * Verify step by step
  </Accordion>

  <Accordion title="File Not Found">
    **Check**:

    * File was uploaded successfully
    * Correct filename used
    * File format supported

    **Solutions**:

    * Re-upload file
    * Check filename spelling
    * Convert to supported format
  </Accordion>
</AccordionGroup>

## Pricing & Limits

### Free Tier

* 10 code executions per day
* 30 second timeout
* Standard Python libraries
* 10MB max file size

### Pro Tier

* 100 code executions per day
* 60 second timeout
* All Python libraries
* 50MB max file size

### Team Tier

* Unlimited executions
* 120 second timeout
* Custom library requests
* 100MB max file size

<Info>
  Execution limits reset daily at midnight UTC.
</Info>

## Next Steps

<CardGroup cols={2}>
  <Card title="Deep Research" icon="magnifying-glass-chart" href="/tools/deep-research">
    Combine with research for data-driven insights
  </Card>

  <Card title="Canvas" icon="code" href="/tools/canvas">
    Edit code in Code Canvas for larger projects
  </Card>

  <Card title="File Uploads" icon="file" href="/getting-started/files-and-history">
    Learn about file upload capabilities
  </Card>

  <Card title="Web Search" icon="globe" href="/tools/web-search">
    Combine with real-time data retrieval
  </Card>
</CardGroup>

<Check>
  Code Interpreter transforms AI from answering questions to solving problems with actual computation!
</Check>
