# What Is the Code Interpreter Feature in Twenty CRM? A Deep Dive into AI-Powered Python Execution

> Explore Twenty CRM's Code Interpreter, an AI tool executing Python code for data analysis, file generation, and workflow automation directly within chat. Unlock powerful insights.

- Repository: [Twenty/twenty](https://github.com/twentyhq/twenty)
- Tags: deep-dive
- Published: 2026-03-27

---

**The Code Interpreter is an AI-driven tool in Twenty CRM that executes arbitrary Python code in a sandboxed environment, enabling the AI assistant to perform data analysis, generate files, and automate workflows directly from chat.**

The **Code Interpreter feature in Twenty CRM** extends the platform's AI Assistant with the ability to run real Python scripts safely. Integrated into the `twentyhq/twenty` open-source repository, this feature allows the AI to move beyond text generation and actually compute, transform data, and produce deliverables like CSVs or visualizations. It is exposed as a reusable skill that the AI engine can invoke whenever data processing or complex calculations are required.

## Architecture and Core Components

The feature is implemented across multiple layers of the Twenty CRM server architecture, from skill metadata definition to sandboxed execution drivers.

### Skill Metadata and System Prompts

The AI engine recognizes the Code Interpreter as a tool named **`code_interpreter`**. This capability is registered in the workspace manager utilities at [`create-standard-flat-skill-metadata.util.ts`](https://github.com/twentyhq/twenty/blob/main/create-standard-flat-skill-metadata.util.ts), where the skill metadata, description, and usage constraints are declared.

When the AI decides Python execution is necessary, the `SystemPromptBuilderService` (located at [`system-prompt-builder.service.ts`](https://github.com/twentyhq/twenty/blob/main/system-prompt-builder.service.ts)) constructs explicit instructions telling the model how to structure the tool call. This ensures the LLM outputs properly formatted JSON payloads requesting code execution.

### Tool Implementation Layer

The actual invocation is handled by **`CodeInterpreterTool`** in [`code-interpreter-tool.ts`](https://github.com/twentyhq/twenty/blob/main/code-interpreter-tool.ts). This class acts as the bridge between the AI engine and the execution backend, forwarding the code string and any input files to the core service.

### Execution Service and Drivers

The **`CodeInterpreterService`** (in [`code-interpreter.service.ts`](https://github.com/twentyhq/twenty/blob/main/code-interpreter.service.ts)) orchestrates the execution flow. It delegates the actual sandboxing to driver implementations selected via the `CODE_INTERPRETER_TYPE` environment variable:

- **`LOCAL`** – Runs code directly on the server filesystem (development only), implemented in [`local.driver.ts`](https://github.com/twentyhq/twenty/blob/main/local.driver.ts)
- **`E2B`** – Sends code to the E2B sandbox SaaS for secure, isolated execution, implemented in [`e2b.driver.ts`](https://github.com/twentyhq/twenty/blob/main/e2b.driver.ts)

The driver selection logic resides in [`code-interpreter-driver.factory.ts`](https://github.com/twentyhq/twenty/blob/main/code-interpreter-driver.factory.ts).

## How the Code Interpreter Works

The execution flow follows a strict five-step pipeline that ensures safe, reproducible Python execution within the AI chat context.

### 1. Configuration and Driver Selection

Before execution, the system reads the `CODE_INTERPRETER_TYPE` environment variable. For production deployments, setting this to `E2B` and providing an `E2B_API_KEY` routes all code through E2B's managed sandbox service, preventing malicious or accidental damage to the host server.

```dotenv

# .env configuration for production sandboxing

CODE_INTERPRETER_TYPE=E2B
E2B_API_KEY=your_e2b_api_key_here

```

### 2. AI Tool Invocation

When the AI model determines code execution is required, it generates a tool call with a specific JSON payload structure:

```json
{
  "toolName": "code_interpreter",
  "arguments": {
    "code": "import pandas as pd\nprint(pd.DataFrame({'a':[1,2]}))",
    "files": []
  }
}

```

The `files` array accepts optional file objects (with `fileId` and `name`) that the AI wants to make available to the script, processed via utilities in [`extract-code-interpreter-files.util.ts`](https://github.com/twentyhq/twenty/blob/main/extract-code-interpreter-files.util.ts).

### 3. Sandboxed Execution

The `CodeInterpreterService` instantiates the appropriate driver, writes any input files to a temporary working directory, and executes the Python code. The E2B driver (in [`e2b.driver.ts`](https://github.com/twentyhq/twenty/blob/main/e2b.driver.ts)) leverages the `@e2b/code-interpreter` package to maintain strict process isolation.

### 4. Output Capture and File Handling

Upon completion, the service captures three distinct outputs:

- **`stdout`** – Standard console output from the script
- **`stderr`** – Error streams and traceback information  
- **Generated files** – Any files written to the working directory during execution

These artifacts are packaged into a structured response and returned to the AI engine. Files are uploaded back through the MCP (Model Context Protocol) for the AI to reference or present to the user.

### 5. Frontend Rendering

On the client side, Twenty CRM distinguishes Code Interpreter operations from standard chat messages. The utility [`isThinkingStepPart.ts`](https://github.com/twentyhq/twenty/blob/main/isThinkingStepPart.ts) identifies these execution steps to render a "thinking" or "processing" UI indicator, keeping users informed while Python runs in the background.

## Practical Implementation Examples

### Invoking the Code Interpreter from AI Chat Flow

When building custom AI workflows within Twenty CRM, you can programmatically load and execute the tool:

```typescript
// Load the skill and make the tool available to the AI
await loadSkills(['code-interpreter']);
await learnTools({ toolNames: ['code_interpreter'] });

// Execute Python to analyze data
await executeTool({
  toolName: 'code_interpreter',
  arguments: {
    code: `
import pandas as pd
df = pd.read_csv('/tmp/input.csv')
print(df.describe())
`,
    files: [{ fileId: 'input.csv', name: 'input.csv' }]
  }
});

```

This pattern mirrors the system prompt examples defined in [`chat-system-prompts.const.ts`](https://github.com/twentyhq/twenty/blob/main/chat-system-prompts.const.ts), where the AI is trained to request `code_interpreter` for data processing tasks.

### Direct Service Usage in Backend Modules

For server-side automation outside the chat interface, import and call the service directly:

```typescript
import { CodeInterpreterService } from '@/engine/core-modules/code-interpreter/code-interpreter.service';

async function generateReport() {
  const result = await CodeInterpreterService.execute({
    code: `
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'sales': [100, 200, 150]})
df.plot(kind='bar')
plt.savefig('/tmp/chart.png')
`,
    inputFiles: []  // Optional: [{ name: 'data.csv', content: Buffer.from(...) }]
  });

  console.log('Output:', result.stdout);
  if (result.files.length > 0) {
    console.log('Generated files:', result.files.map(f => f.name));
  }
}

```

This approach, as implemented in [`code-interpreter.service.ts`](https://github.com/twentyhq/twenty/blob/main/code-interpreter.service.ts), provides full programmatic access to the sandbox without AI mediation.

### Driver Configuration Patterns

For local development where sandboxing is unnecessary, configure the local driver:

```dotenv

# .env for development

CODE_INTERPRETER_TYPE=LOCAL

```

The factory in [`code-interpreter-driver.factory.ts`](https://github.com/twentyhq/twenty/blob/main/code-interpreter-driver.factory.ts) will instantiate `LocalDriver` instead of `E2BDriver`, executing code directly on the development machine's filesystem.

## Summary

- The **Code Interpreter feature in Twenty CRM** enables the AI Assistant to execute arbitrary Python via a tool named `code_interpreter`, defined in [`create-standard-flat-skill-metadata.util.ts`](https://github.com/twentyhq/twenty/blob/main/create-standard-flat-skill-metadata.util.ts).
- Execution is handled by **`CodeInterpreterService`** with pluggable drivers selected through the `CODE_INTERPRETER_TYPE` environment variable.
- **Production deployments** should use the **`E2B`** driver for secure sandboxing, while **`LOCAL`** is available for development only.
- The system captures **stdout, stderr, and generated files**, returning them to the AI for further processing or user presentation.
- Frontend components use [`isThinkingStepPart.ts`](https://github.com/twentyhq/twenty/blob/main/isThinkingStepPart.ts) to render appropriate UI states during code execution.

## Frequently Asked Questions

### How does Twenty CRM ensure code execution security?

According to the `twentyhq/twenty` source code, security is enforced through driver selection. The **`E2B`** driver (configured via `CODE_INTERPRETER_TYPE=E2B`) sends all code to the E2B managed sandbox service, which runs Python in an isolated environment with no access to the host server. The **`LOCAL`** driver exists only for development convenience and should never be used in production.

### What types of files can the Code Interpreter generate?

The Code Interpreter can generate any file type writable by Python, including CSVs, Excel spreadsheets, PNG/JPG visualizations, JSON files, and PDFs. As implemented in [`code-interpreter.service.ts`](https://github.com/twentyhq/twenty/blob/main/code-interpreter.service.ts), any file written to the working directory during script execution is captured in the `result.files` array and returned to the AI via the MCP protocol.

### Can I upload files for the AI to process with the Code Interpreter?

Yes. The tool accepts an optional `files` array in its arguments, allowing users or systems to upload documents (like CSVs or text files) that the Python code can read from `/tmp/`. The utility [`extract-code-interpreter-files.util.ts`](https://github.com/twentyhq/twenty/blob/main/extract-code-interpreter-files.util.ts) handles the injection of these file references into the system prompt so the AI knows which files are available to reference in its code.

### Where is the Code Interpreter tool defined in the Twenty CRM codebase?

The tool is defined in [`code-interpreter-tool.ts`](https://github.com/twentyhq/twenty/blob/main/code-interpreter-tool.ts) within the core modules, while its skill metadata is registered in [`create-standard-flat-skill-metadata.util.ts`](https://github.com/twentyhq/twenty/blob/main/create-standard-flat-skill-metadata.util.ts). The actual execution logic lives in [`code-interpreter.service.ts`](https://github.com/twentyhq/twenty/blob/main/code-interpreter.service.ts), and driver implementations are located in the `drivers/` subdirectory, specifically [`e2b.driver.ts`](https://github.com/twentyhq/twenty/blob/main/e2b.driver.ts) for production sandboxing and [`local.driver.ts`](https://github.com/twentyhq/twenty/blob/main/local.driver.ts) for development.