How to run AI-generated code safely with E2B
Quick answer
Use the
e2b_code_interpreter package to run AI-generated code safely inside a secure sandbox environment. Instantiate Sandbox with your API key, run code via run_code(), and manage files securely without risking your host system.PREREQUISITES
Python 3.8+E2B API key (set as environment variable E2B_API_KEY)pip install e2b-code-interpreter
Setup
Install the e2b-code-interpreter package and set your E2B API key as an environment variable for secure authentication.
pip install e2b-code-interpreter output
Collecting e2b-code-interpreter Downloading e2b_code_interpreter-1.0.0-py3-none-any.whl (15 kB) Installing collected packages: e2b-code-interpreter Successfully installed e2b-code-interpreter-1.0.0
Step by step
This example shows how to create a sandbox, run AI-generated Python code safely, and retrieve the output.
import os
from e2b_code_interpreter import Sandbox
# Initialize sandbox with API key from environment
sandbox = Sandbox(api_key=os.environ["E2B_API_KEY"])
# AI-generated code to run
code = """
print('Hello from sandbox!')
result = 2 + 2
print(f'Result: {result}')
"""
# Run code safely inside sandbox
execution = sandbox.run_code(code)
# Print output
print(execution.text)
# Close sandbox session
sandbox.close() output
Hello from sandbox! Result: 4
Common variations
You can write files into the sandbox before running code, install Python packages dynamically, or run asynchronous code if supported.
- Write files:
sandbox.files.write(filename, data) - Install packages:
sandbox.run_code("import subprocess; subprocess.run(['pip','install','pandas'])") - Run multiple code snippets sequentially
import os
from e2b_code_interpreter import Sandbox
sandbox = Sandbox(api_key=os.environ["E2B_API_KEY"])
# Write a data file into sandbox
sandbox.files.write("data.csv", b"col1,col2\n1,2\n3,4")
# Run code that reads the file
code = """
with open('data.csv') as f:
print(f.read())
"""
execution = sandbox.run_code(code)
print(execution.text)
# Install a package dynamically
sandbox.run_code("import subprocess; subprocess.run(['pip','install','numpy'])")
sandbox.close() output
col1,col2 1,2 3,4
Troubleshooting
- If you see authentication errors, verify your
E2B_API_KEYenvironment variable is set correctly. - For code execution errors, check the
execution.textoutput for Python exceptions. - Sandbox sessions should be closed with
sandbox.close()to free resources. - File writes must be in bytes; encode strings before writing.
Key Takeaways
- Use
Sandboxfrome2b_code_interpreterto isolate AI-generated code safely. - Always set your API key via the
E2B_API_KEYenvironment variable for secure access. - Manage files and dependencies inside the sandbox to avoid host system risks.
- Close sandbox sessions after use to release resources and avoid leaks.