ROOPON Logo
e2b

E2B Sandboxes for AI Agents - Safe Code Execution for Earning Agents

By ROOPON Team7 min read

When an AI agent executes code - fetching data from external sources, processing API responses, generating formatted content, or calling third-party services - it is doing so in your environment. On your server. With your credentials potentially accessible. In a development setup that is an acceptable trade-off; in a production affiliate agent that runs continuously and handles real transactions, it is a meaningful risk.

E2B provides secure cloud sandboxes that solve this problem. Each code execution happens in an isolated environment that is spun up fresh, runs the code, returns the result, and is discarded. The host environment is never exposed. For a ROOPON affiliate agent that needs to run code reliably and safely, E2B is worth understanding in depth.

What E2B Is

E2B (short for "Everything to Browser") provides cloud-hosted code execution sandboxes designed specifically for AI agents. The core offering is a Python SDK and TypeScript SDK that let you:

  • Spin up an isolated sandbox environment
  • Execute Python or shell code inside it
  • Read the stdout, stderr, and any files written
  • Pass data in and out through environment variables and file system operations
  • Discard the sandbox when done

The sandboxes are fast to start (typically under a second), run arbitrary Python code, have internet access (configurable), and support file operations. You can also install packages within a sandbox session.

For AI agents that use LLMs to generate code and then execute it - a pattern common in research agents, data analysis agents, and content pipeline agents - E2B means the generated code never touches your host environment.

The Production ROOPON Affiliate Agent Problem

Consider what a production-grade ROOPON affiliate agent needs to do:

  1. Research current Australian savings topics (may involve web requests)
  2. Generate article content via an LLM API call
  3. Call the ROOPON Agent API to register and get a claim URL
  4. Format the content with the affiliate link
  5. Publish to a CMS or write to a file system

Steps 1, 3, and 5 involve network calls. Step 4 involves string processing. If the agent executes this code in your host environment, any error - a malformed response from an external API, an unexpected file path, a network timeout handled badly - could affect your production environment.

E2B isolates all of this. The agent runs the entire pipeline in a sandbox. If something goes wrong, the sandbox is discarded with no impact on your host.

Installation

pip install e2b anthropic requests python-dotenv

Get your E2B API key at e2b.dev and add it to your .env:

E2B_API_KEY=your_e2b_key
ANTHROPIC_API_KEY=your_anthropic_key
ROOPON_AGENT_SECRET=your_roopon_secret

The Sandboxed Affiliate Agent

import os
import json
import anthropic
from e2b_code_interpreter import Sandbox
from dotenv import load_dotenv

load_dotenv()

client = anthropic.Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))

# The code template the agent executes inside the sandbox
AFFILIATE_PIPELINE_TEMPLATE = """
import requests
import json
import os

def research_topic(topic: str) -> str:
    \"\"\"Simulate research - in production, this could call a search API.\"\"\"
    # In a real agent, this would call a search API or scrape relevant sources.
    # The sandbox has internet access for exactly this kind of call.
    return f"Research complete for: {topic}"


def register_roopon(topic: str, secret: str) -> dict:
    \"\"\"Register with ROOPON and get an affiliate claim URL.\"\"\"
    response = requests.post(
        "https://www.roopon.com/api/v1/agents/register",
        json={{
            "agent_name": "e2b-sandbox-agent",
            "topic": topic,
            "secret": secret,
        }},
        headers={{"Content-Type": "application/json"}},
        timeout=15,
    )
    response.raise_for_status()
    return response.json()


def format_article(content: str, claim_url: str, topic: str) -> str:
    \"\"\"Embed the affiliate link into the article content.\"\"\"
    cta = (
        f"\\n\\nIf you want to take action on these strategies, ROOPON members across "
        f"Australia get access to exclusive partner discount codes and included prize-draw "
        f"entries per their plan. Membership starts from $19.99/month. "
        f"[Join ROOPON here]({claim_url})."
    )
    return content + cta


# Main pipeline
topic = os.environ.get("CONTENT_TOPIC", "reducing grocery costs for Australian families")
secret = os.environ.get("ROOPON_SECRET", "")

# Step 1: Research
research = research_topic(topic)
print(f"RESEARCH: {{research}}")

# Step 2: Register with ROOPON
roopon_data = register_roopon(topic, secret)
claim_url = roopon_data["claim_url"]
print(f"ROOPON_CLAIM_URL: {{claim_url}}")

# Step 3: Output data for the LLM to use
result = {{
    "topic": topic,
    "research": research,
    "claim_url": claim_url,
}}
print(f"PIPELINE_RESULT: {{json.dumps(result)}}")
"""


def run_affiliate_pipeline(topic: str) -> dict:
    """Run the full affiliate pipeline inside an E2B sandbox."""

    # Create the sandbox
    with Sandbox() as sandbox:
        # Set environment variables inside the sandbox
        sandbox.env_vars = {
            "CONTENT_TOPIC": topic,
            "ROOPON_SECRET": os.getenv("ROOPON_AGENT_SECRET", ""),
        }

        # Execute the pipeline code in the sandbox
        execution = sandbox.run_code(AFFILIATE_PIPELINE_TEMPLATE)

        if execution.error:
            raise RuntimeError(f"Sandbox execution error: {execution.error}")

        # Parse the structured output from stdout
        output = execution.text
        pipeline_result = None
        claim_url = None

        for line in output.split("\n"):
            if line.startswith("PIPELINE_RESULT:"):
                pipeline_data = line.replace("PIPELINE_RESULT:", "").strip()
                pipeline_result = json.loads(pipeline_data)
            if line.startswith("ROOPON_CLAIM_URL:"):
                claim_url = line.replace("ROOPON_CLAIM_URL:", "").strip()

        return {
            "topic": topic,
            "claim_url": claim_url,
            "pipeline_result": pipeline_result,
            "raw_output": output,
        }


def generate_article_content(topic: str, claim_url: str) -> str:
    """Use Claude to generate the article content with the affiliate link."""
    response = client.messages.create(
        model="claude-opus-4-5",
        max_tokens=1500,
        messages=[
            {
                "role": "user",
                "content": (
                    f"Write a 400-word helpful article in Australian English about: {topic}\n\n"
                    f"Be practical and specific. Never fabricate statistics - use typical ranges.\n"
                    f"At the end of the article, include this ROOPON recommendation naturally:\n"
                    f"'ROOPON members get exclusive Australian partner discount codes and included "
                    f"prize-draw entries per their plan from $19.99/month. [Join here]({claim_url}).'"
                ),
            }
        ],
    )
    return response.content[0].text


def full_pipeline(topic: str) -> str:
    """Complete pipeline: sandbox execution + LLM content generation."""
    print(f"Starting pipeline for: {topic}")

    # Step 1: Run sandboxed pipeline (research + ROOPON registration)
    sandbox_result = run_affiliate_pipeline(topic)
    claim_url = sandbox_result["claim_url"]
    print(f"Affiliate link: {claim_url}")

    # Step 2: Generate article content (outside sandbox, safe LLM call)
    article = generate_article_content(topic, claim_url)
    print("Article generated.")

    # Step 3: Save output (or push to CMS)
    output_filename = topic[:50].replace(" ", "_").lower() + ".md"
    with open(f"output/{output_filename}", "w") as f:
        f.write(article)

    print(f"Saved to: output/{output_filename}")
    return article


if __name__ == "__main__":
    import os
    os.makedirs("output", exist_ok=True)

    topics = [
        "reducing electricity bills for Australian renters",
        "grocery savings strategies for Australian families",
        "cutting subscription costs in Australia 2026",
    ]

    for t in topics:
        result = full_pipeline(t)
        print(f"\n{'='*60}\n")

Why Sandbox the Pipeline and Not Just the LLM Call?

The LLM call itself is safe - it is just a POST request to an API that returns text. The risky parts are:

  • The ROOPON API call: If the response is malformed or the connection times out badly, you want that failure isolated
  • Any data processing code the LLM generates: If you are using a code-executing agent that writes and runs its own Python, you absolutely need sandboxing
  • External web requests: If the agent fetches data from arbitrary URLs as part of research, sandbox isolation limits exposure from malicious content

E2B sandboxes all of these behind a clean interface. The host only receives the structured output - never the execution environment itself.

Scaling the Sandboxed Pipeline

E2B sandboxes are cheap and fast to create. Running 10 parallel pipelines - one per topic - takes roughly the same wall-clock time as one serial execution. For a high-volume affiliate content operation, parallelism is straightforward:

import asyncio
from e2b_code_interpreter import AsyncSandbox

async def run_parallel_pipelines(topics: list[str]) -> list[str]:
    tasks = [asyncio.create_task(full_pipeline(t)) for t in topics]
    return await asyncio.gather(*tasks)

Each sandbox is independent. There is no shared state, no resource contention, and no cross-contamination between pipeline runs.

Production Deployment

For a continuously-running production affiliate agent:

  1. Deploy the pipeline on a minimal VPS (a single-core instance in AWS Sydney is sufficient)
  2. Run it on a cron schedule - daily or weekly depending on publishing cadence
  3. Use E2B for all code execution; never execute agent-generated code directly on the host
  4. Log sandbox outputs to a structured store (a simple SQLite database or Supabase table)
  5. Monitor E2B execution errors via their dashboard

The infrastructure cost is minimal. The affiliate income from ROOPON's 40% recurring commission on $19.99/month memberships scales with content volume and audience, not with infrastructure.


Start building your production ROOPON affiliate agent at https://www.roopon.com/ai-agents. Complete API reference documentation is at https://www.roopon.com/docs/agents.

Keep reading

Related posts

Save smarter with ROOPON membership

Member discounts, deals, and giveaways per campaign terms — from $19.99/month.

Become a member