Understanding Sandboxes

Sandboxes are the foundation of AI Computer's secure code execution environment. Each sandbox provides an isolated Python environment where your code can run safely.

Lifecycle

A sandbox goes through several stages during its lifecycle:

  1. Creation: When you call client.setup(), a new sandbox is created with a fresh Python environment.
  2. Initialization: The sandbox is configured with your specified settings and resource limits.
  3. Execution: Your code runs in the sandbox, with access only to allowed resources.
  4. Cleanup: After execution or when client.cleanup() is called, the sandbox is destroyed.
1import asyncio
2from ai_computer import SandboxClient
3
4async def main():
5    # Create a new sandbox
6    client = SandboxClient()
7    await client.setup()
8    
9    try:
10        # Use the sandbox
11        response = await client.execute_code("print('Hello from sandbox!')")
12        print(response.data['output'])
13    finally:
14        # Clean up the sandbox
15        await client.cleanup()
16
17asyncio.run(main())

Resource Limits

Each sandbox has configurable resource limits to ensure fair usage and security:

Memory

  • Default: 512MB
  • Maximum: 2GB
  • Configurable per sandbox

CPU

  • Default: 1 core
  • Maximum: 4 cores
  • Usage time limits apply
1# Configure sandbox resources
2client = SandboxClient(
3    memory_limit="1G",  # 1GB memory limit
4    cpu_limit=2,        # 2 CPU cores
5    timeout=300         # 5 minute timeout
6)

File System

Each sandbox has its own isolated file system:

  • Temporary files are automatically cleaned up
  • Default Python packages are pre-installed
  • Custom packages can be installed per session
  • File operations are restricted to the sandbox directory
1# Working with files in a sandbox
2code = """
3with open('example.txt', 'w') as f:
4    f.write('Hello from sandbox!')
5
6with open('example.txt', 'r') as f:
7    content = f.read()
8    print(f'File contents: {content}')
9"""
10
11response = await client.execute_code(code)
12print(response.data['output'])

Best Practices

  • Resource Management: Always use the cleanup() method in a try/finally block to ensure proper resource cleanup.
  • Error Handling: Check response success status and handle errors appropriately in your code.
  • Performance: Reuse sandboxes for multiple executions when possible, rather than creating new ones for each operation.
  • Security: Never store sensitive information in sandbox files, as they are temporary and may be accessible to code running in the sandbox.