Skip to content

Connect E2B to AI Agents: Orchestrate remote processes and system metrics

Learn how to connect E2B to AI agents using Truto's /tools endpoint. Build autonomous workflows to execute secure code and monitor infrastructure.

Riya Sethi Riya Sethi · · 10 min read
Connect E2B to AI Agents: Orchestrate remote processes and system metrics

You want to connect E2B to an AI agent so your internal systems can independently spawn cloud sandboxes, execute arbitrary code, manipulate remote filesystems, and monitor microVM infrastructure metrics based on user commands. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the need to manually construct complex API wrappers around E2B's environment daemon.

Giving a Large Language Model (LLM) read and write access to your remote compute environments is an engineering headache. You either spend weeks building, hosting, and maintaining a custom connector that understands the difference between an inactive template and a running microVM, or you use a managed infrastructure layer that handles the authentication and tool schemas for you. If your team uses ChatGPT, check out our guide on connecting E2B to ChatGPT, or if you are building on Anthropic's models, read our guide on connecting E2B to Claude. For developers building custom autonomous workflows, you need a programmatic way to fetch these compute tools and bind them directly to your agent framework.

This guide breaks down exactly how to fetch AI-ready tools for E2B, bind them natively to an LLM using frameworks like LangChain, LangGraph, Vercel AI SDK, or CrewAI, and execute complex remote operations workflows. For a deeper look at the architecture behind this approach, refer to our research on architecting AI agents and the SaaS integration bottleneck.

The Engineering Reality of Custom Compute Connectors

Building AI agents is easy. Connecting them to dynamic, ephemeral cloud infrastructure APIs is hard. Giving an LLM access to external compute sounds simple in a prototype. You write a Node.js function that makes a REST call to execute a Python script and wrap it in an @tool decorator. In production, this approach collapses entirely, especially with an ecosystem as specific as E2B.

If you decide to build the E2B connector yourself, you own the entire lifecycle of interacting with remote microVMs. E2B's architecture introduces several highly specific integration challenges that break standard LLM assumptions.

The Asynchronous Sandbox Lifecycle Trap

Standard REST APIs deal with persistent state. You create a record, it stays there. E2B sandboxes are ephemeral microVMs with strict Time-To-Live (TTL) constraints. When an agent creates a sandbox, it receives a sandboxID. If the agent decides to execute a process on that sandbox five minutes later, the sandbox might have timed out and terminated.

If you hand-code this integration, you must teach the LLM how to poll the sandbox state or refresh the TTL before issuing commands. When the LLM inevitably hallucinates and attempts to execute a process on a terminated sandbox, it receives a 404 or 400 error. The agent then gets trapped in a failure loop, repeatedly trying to push commands to a non-existent environment.

Process I/O and PTY Stream Formatting

LLMs operate on text strings. E2B processes operate on standard input (stdin), standard output (stdout), standard error (stderr), and pseudo-terminals (PTY). When you start a process in E2B, the API often returns chunked streams of data or expects asynchronous websocket connections for interactive inputs.

An LLM cannot natively read a raw binary stream or parse a fragmented chunked response without a heavy translation layer. You have to build a middleware that buffers the E2B process output, strips out terminal control characters (ANSI escape codes), and packages it into clean JSON that the LLM's context window can ingest without wasting tokens.

Filesystem Path Hallucinations

When an LLM attempts to upload a file to a sandbox, it needs an absolute path. Models are notoriously bad at guessing file system structures. They will attempt to write to /home/user/app.py when the E2B environment is configured for /code/app.py. If the agent tries to read a file that doesn't exist, the resulting error trace can confuse the model, causing it to abandon the workflow entirely.

Why a Unified Tool Layer Fixes This

Directly exposing raw API endpoints pushes infrastructure quirks into the LLM's context. A standardized tool layer collapses these complexities into deterministic, JSON-schema-backed functions.

  1. Smaller attack surface for hallucination. The LLM only ever chooses from a stable list of clear functions like create_a_e_2_b_sandbox or e_2_b_process_start.
  2. Deterministic input validation. Every tool has a strict JSON schema. Invalid arguments (like missing required paths) are rejected by the proxy layer before they ever hit E2B's environment daemon.
  3. Normalized Error Handling. If a process fails or a sandbox times out, the error is returned in a standard format that the agent can read and understand, prompting it to recover (e.g., creating a new sandbox) rather than failing completely.

Hero Tools for E2B AI Agents

Truto provides a comprehensive suite of pre-configured tools for E2B via the /tools endpoint. By binding these to your agent, you grant it immediate, safe access to your microVM infrastructure. Here are the highest-leverage operations for orchestrating remote environments.

1. Create a Sandbox

Tool Name: create_a_e_2_b_sandbox

This is the foundation of any E2B workflow. It spawns a new isolated microVM from a specified template. The agent must call this to obtain a sandboxID before it can execute any subsequent code or filesystem commands.

"I need a fresh compute environment to run a data analysis script. Create a new sandbox using our standard data-science template and set the timeout to 600 seconds."

2. Start a Remote Process

Tool Name: e_2_b_process_start

Once a sandbox is active, this tool allows the agent to execute arbitrary terminal commands or scripts inside the VM. This is how the agent actually "runs code" remotely, passing the command and retrieving the execution event data.

"Execute the python script located at /home/user/analyze.py in sandbox ID 'sbx-12345' and return the process output."

3. List Directory Contents

Tool Name: e_2_b_filesystem_list_dir

Before an agent can read or modify files, it needs to understand the environment's layout. This tool lets the agent inspect directories inside the sandbox, preventing hallucinations about where files are stored.

"Check the contents of the /tmp/data/ directory in the current sandbox to see if the dataset has finished downloading."

4. Upload Files to Sandbox

Tool Name: e_2_b_filesystem_upload_file

Agents often generate code, configuration files, or synthetic data that needs to be moved into the execution environment. This tool pushes local files into the E2B microVM filesystem, ensuring parent directories are created automatically.

"Upload the generated docker-compose.yml configuration to the /workspace directory in the running sandbox."

5. Monitor Sandbox Metrics

Tool Name: e_2_b_sandboxes_get_metrics

For agents acting as infrastructure overseers, monitoring resource consumption is critical. This tool retrieves CPU, memory, and disk usage for a specific sandbox, allowing the agent to determine if a process is hanging or if the environment needs to be resized.

"Check the memory and CPU utilization for sandbox 'sbx-98765' over the last five minutes to see if our batch job is bottlenecking."

6. Pause a Sandbox

Tool Name: e_2_b_sandboxes_pause

To manage compute costs, agents should clean up after themselves. This tool pauses a running sandbox, persisting its filesystem and memory state so it can be resumed later without losing progress.

"The long-running training job has paused for user input. Suspend the sandbox to save resources until the user responds."

To view the complete inventory of available operations, schemas, and required parameters, visit the E2B integration page.

Workflows in Action

When you combine these tools inside an agent framework, you unlock powerful autonomous infrastructure workflows. Here is how specific engineering scenarios play out when an LLM has access to E2B via Truto.

Scenario 1: Autonomous Code Execution and Debugging

An engineer asks the internal Slackbot (powered by an AI agent) to write and test a script that parses a massive CSV of server logs and extracts specific error codes.

"Write a Python script to parse system_logs.csv, extract all lines containing 'OOM-KILL', and return the count. Run it in a clean environment and tell me the result."

  1. The agent calls create_a_e_2_b_sandbox to spin up a secure, isolated microVM.
  2. The agent generates the Python code internally.
  3. The agent calls e_2_b_filesystem_upload_file to write the generated code to /workspace/parser.py inside the sandbox.
  4. The agent calls e_2_b_process_start with the command python3 /workspace/parser.py.
  5. The tool returns the stdout of the process.
  6. The agent calls delete_a_e_2_b_sandbox_by_id to tear down the environment and sends the final parsed count back to the engineer.

Scenario 2: Infrastructure Cost Auditing

A DevOps administrator asks their agent to find idle environments that are consuming resources needlessly.

"Check all our currently running E2B sandboxes. If any have been sitting at under 5% CPU usage for the last 10 minutes, pause them and give me a summary."

  1. The agent calls list_all_e_2_b_sandboxes to retrieve an array of active sandboxIDs.
  2. The agent loops through the IDs, calling e_2_b_sandboxes_get_metrics for each to analyze recent CPU utilization.
  3. For sandboxes matching the low-usage criteria, the agent calls e_2_b_sandboxes_pause.
  4. The agent compiles the list of paused sandboxes and outputs a markdown summary to the administrator.

Building Multi-Step Workflows with the SDK

To make this work in production, you need an architecture that programmatically fetches these tools and handles the execution loop. Truto makes this framework-agnostic. Whether you use LangChain, LangGraph, or the Vercel AI SDK, the approach is identical: fetch the schema, bind the tools, and handle the tool call results.

Here is a complete architectural view of how the system communicates:

sequenceDiagram
    participant User
    participant Agent as Agent Framework (LangChain)
    participant Truto as Truto Tool Manager
    participant API as Truto Unified API
    participant E2B as E2B Infrastructure

    User->>Agent: Prompt: "Run this python code"
    Agent->>Truto: Request E2B Tools
    Truto->>API: GET /integrated-account/{id}/tools
    API-->>Truto: Return JSON Tool Schemas
    Truto-->>Agent: Bind tools via .bindTools()
    Agent->>Agent: LLM decides to use create_a_e_2_b_sandbox
    Agent->>Truto: Execute Tool Call
    Truto->>API: POST /e2b/sandboxes
    API->>E2B: Create Sandbox
    E2B-->>API: sandboxID: "sbx-123"
    API-->>Truto: Normalized Response
    Truto-->>Agent: Tool Message (sandboxID)
    Agent->>Agent: LLM decides to use e_2_b_process_start
    Agent->>Truto: Execute Tool Call
    Truto->>API: POST /e2b/process
    API->>E2B: Execute Command
    E2B-->>API: stdout: "Success"
    API-->>Truto: Normalized Response
    Truto-->>Agent: Tool Message (stdout)
    Agent-->>User: Final Answer

Initializing the Tool Manager

Using the [truto-langchainjs-toolset](/best-unified-api-for-llm-function-calling-ai-agent-tools-2026/), you start by initializing the tool manager for your specific E2B integrated account.

import { ChatOpenAI } from "@langchain/openai";
import { TrutoToolManager } from "truto-langchainjs-toolset";
import { HumanMessage } from "@langchain/core/messages";
 
async function runE2BAgent() {
  // Initialize the LLM
  const llm = new ChatOpenAI({
    modelName: "gpt-4o",
    temperature: 0,
  });
 
  // Initialize Truto tools for E2B
  const trutoManager = new TrutoToolManager({
    trutoToken: process.env.TRUTO_API_KEY,
    integratedAccountId: "your_e2b_account_id_here",
  });
 
  // Fetch all E2B tools dynamically
  const tools = await trutoManager.getTools();
  
  // Bind the tools to the LLM
  const modelWithTools = llm.bindTools(tools);
 
  // Start the conversation
  const messages = [new HumanMessage("Create a sandbox, run 'echo Hello World', and return the output.")];
  
  // Standard Agent Loop
  const response = await modelWithTools.invoke(messages);
  
  // Frameworks handle the execution mapping automatically based on tool names.
  console.log(response.tool_calls);
}

The Critical Reality of Rate Limits

When building multi-step agent loops, models move fast. An LLM might decide to loop through 50 sandboxes and fetch metrics for all of them in a massive parallel burst of tool calls. This will immediately trigger API rate limits from E2B.

Here is a factual requirement you must design for: Truto does not retry, throttle, or apply backoff on rate limit errors. If the upstream E2B API returns an HTTP 429 Too Many Requests, Truto passes that exact error back to your caller.

However, Truto performs a vital translation step. Every upstream API implements rate limit headers differently. Truto normalizes this upstream rate limit information into standardized IETF spec headers on the response:

  • ratelimit-limit: The maximum number of requests permitted.
  • ratelimit-remaining: The number of requests left in the current window.
  • ratelimit-reset: The time (in seconds) until the quota resets.

Because Truto normalizes these headers, you can write a single, predictable backoff function in your agent loop that handles 429s gracefully, regardless of whether the agent is talking to E2B, Salesforce, or Zendesk.

// Example of handling 429 Rate Limits in an agent executor wrapper
async function executeToolWithBackoff(tool, args, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const result = await tool.invoke(args);
      return result;
    } catch (error) {
      if (error.response && error.response.status === 429) {
        // Read Truto's normalized headers
        const resetTime = parseInt(error.response.headers.get('ratelimit-reset') || '5', 10);
        
        console.warn(`Rate limited by upstream. Waiting ${resetTime} seconds...`);
        
        // Sleep until the window resets
        await new Promise(resolve => setTimeout(resolve, resetTime * 1000));
        continue;
      }
      // If it's not a 429, throw the error back to the LLM to handle
      throw error;
    }
  }
  throw new Error("Max retries exceeded for rate limit.");
}

By catching the 429 error and parsing Truto's ratelimit-reset header, you pause the agent loop exactly as long as needed. When the sleep finishes, the loop continues, the tool executes successfully, and the LLM remains completely unaware that a rate limit hiccup ever occurred. This prevents the LLM from hallucinating workarounds or prematurely declaring the task a failure.

Moving from Prototypes to Production Workloads

Building an integration with E2B is fundamentally different from integrating a standard CRUD CRM. You are orchestrating active cloud infrastructure. When you hand that power to an AI agent, the blast radius of a malformed API call or a hallucinated parameter increases dramatically.

Using a raw API wrapper pushes the responsibility of input validation, error parsing, and endpoint routing directly into your prompt engineering. That is fragile.

By leveraging Truto's /tools endpoint, you abstract the infrastructure quirks away from the model. The agent interacts with strict, predictable JSON schemas. Invalid commands fail deterministically at the proxy layer. Rate limit headers are normalized for easy backoff handling. You stop maintaining endpoint wrappers and focus entirely on building smarter autonomous workflows.

FAQ

How does an AI agent interact with E2B sandboxes?
AI agents use standard tool-calling frameworks (like LangChain) to issue commands. Through Truto's /tools endpoint, the agent receives a strict JSON schema of available E2B actions, such as starting a process or reading a filesystem, and outputs structured arguments to execute those actions.
How do I handle rate limits when an agent calls E2B tools?
Truto passes HTTP 429 rate limit errors directly back to your application but normalizes the headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset) to the IETF spec. Your application's execution loop must read the ratelimit-reset header and implement a sleep function before retrying the tool call.
Can I use frameworks other than LangChain?
Yes. Truto's /tools endpoint returns standard JSON schemas that can be ingested by any modern agent framework, including CrewAI, LangGraph, AutoGen, and the Vercel AI SDK.
Does Truto store the output of the E2B processes?
No. Truto acts as a real-time pass-through proxy. The execution commands and terminal outputs stream through Truto's infrastructure directly to your agent without caching the payload data at rest.

More from our Blog