Skip to main content
AG-Kit provides powerful code execution capabilities through two main executors: sandboxed execution for security and local execution for performance. This guide helps you choose the right tool and use it effectively in your agent’s workflows.

When to Use Code Execution Tools

Use these tools when your agent needs to run dynamic code snippets or scripts.

Quick Start

import { BuiltInCodeExecutor, UnsafeLocalCodeExecutor } from '@ag-kit/tools';

// Pick executor based on scenario
const executor = process.env.USE_SANDBOX
  ? new BuiltInCodeExecutor()
  : new UnsafeLocalCodeExecutor({});

// Run a small Python snippet
const result = await executor.execute({
  language: 'python',
  code: 'print(3 * 7)'
});

if (result.success) {
  console.log('Output:', result.data.stdout); // '21'
}

Typical Workflows

  • Data Processing: Read a file, execute a Python script to analyze it, and write the results.
  • Code Generation & Testing: Have an LLM generate code, execute it in a sandbox to verify correctness, and report back.
  • DevOps Automation: Run shell scripts to scaffold projects, lint files, or run tests.

Choosing the Right Executor

ExecutorUse CaseKey Benefit
BuiltInCodeExecutorUntrusted Code (from LLMs, users)Security & Isolation
UnsafeLocalCodeExecutorTrusted Code (your own scripts)Performance & Speed
  • Prefer BuiltInCodeExecutor (Sandboxed) when security is paramount. It isolates execution, allows package installation, and provides a controlled environment.
  • Use UnsafeLocalCodeExecutor (Local) for trusted scripts in development or controlled CI environments where you need maximum performance and direct access to local files.

Core Features & Configuration

Both executors share a common API but have different backends.

Configuration

  • Timeout: Set timeoutMs to prevent runaway scripts.
  • Environment Variables: Pass envs to inject secrets or configuration.
  • Streaming Output: Use onStdout and onStderr for real-time feedback from long-running tasks.
// Example: Sandboxed executor with configuration
const executor = new BuiltInCodeExecutor();
// Or create a sandboxed be used in codeE
import { Sandbox } from '@e2b/code-interpreter';
const executor = new BuiltInCodeExecutor({
  sandbox: Sandbox.create({
    apiKey: process.env.E2B_API_KEY,
    timeoutMs: 60000, // 1 minute timeout
    envs: { CUSTOM_VAR: 'value' },
  })
});

Supported Languages

Execute code in multiple languages and get structured results:
const result = await executor.execute({ 
  language: 'python', 
  code: 'import pandas as pd\nprint(pd.__version__)' 
});
// result.data: { stdout: '2.1.4\n', stderr: '', exitCode: 0 }

Workflow Example: Agent Integration

Combine code execution with other tools like the FilesystemToolkit to build powerful agents.