How to use E2B with OpenAI
Quick answer
Use the
e2b_code_interpreter package to create a Sandbox instance with your OpenAI API key from os.environ. Run code securely by calling sandbox.run_code() and manage files with sandbox.files.write(). Always close the sandbox with sandbox.close() to release resources.PREREQUISITES
Python 3.8+OpenAI API key (set in environment variable OPENAI_API_KEY)pip install e2b-code-interpreter>=1.0pip install openai>=1.0
Setup
Install the e2b-code-interpreter package and ensure your OpenAI API key is set in the environment variable OPENAI_API_KEY. This package enables secure sandboxed code execution integrated with OpenAI.
pip install e2b-code-interpreter openai output
Collecting e2b-code-interpreter Collecting openai Successfully installed e2b-code-interpreter-1.0.0 openai-1.0.0
Step by step
Create a Sandbox instance using your OpenAI API key from os.environ. Use sandbox.run_code() to execute Python code securely. You can write files into the sandbox environment with sandbox.files.write(). Always call sandbox.close() to clean up resources.
import os
from e2b_code_interpreter import Sandbox
# Initialize sandbox with OpenAI API key from environment
sandbox = Sandbox(api_key=os.environ["OPENAI_API_KEY"])
# Run simple Python code
result = sandbox.run_code("print('Hello from sandbox')")
print(result.text)
# Write a file into the sandbox
sandbox.files.write("data.csv", b"id,value\n1,100\n2,200")
# Run code that reads the file
code = """
with open('data.csv') as f:
print(f.read())
"""
file_result = sandbox.run_code(code)
print(file_result.text)
# Close sandbox to release resources
sandbox.close() output
Hello from sandbox id,value 1,100 2,200
Common variations
- Use
sandbox.run_code()for synchronous execution; async support is not currently provided. - Install additional Python packages inside the sandbox by running
sandbox.run_code("import subprocess; subprocess.run(['pip','install','package'])"). - Use different OpenAI models by configuring the
Sandboxinstance if supported by thee2b-code-interpreterversion.
Troubleshooting
- If you see
API key missingerrors, ensureOPENAI_API_KEYis set in your environment before running the script. - If code execution hangs or fails, verify network connectivity and that your API key has sufficient quota.
- Always call
sandbox.close()to avoid resource leaks.
Key Takeaways
- Use
Sandboxfrome2b_code_interpreterwith your OpenAI API key for secure code execution. - Write files into the sandbox environment using
sandbox.files.write()before running code that depends on them. - Always close the sandbox with
sandbox.close()to free resources and avoid leaks.