SandboxClient

The SandboxClient class is the main interface for interacting with AI Computer. It provides methods for creating sandboxes, executing code, and managing resources.

Constructor

1from ai_computer import SandboxClient
2
3# Basic initialization
4client = SandboxClient()
5
6# With custom configuration
7client = SandboxClient(
8    memory_limit="1G",
9    cpu_limit=2,
10    timeout=300,
11    allow_network=True,
12    allowed_hosts=["api.example.com"],
13    base_url="https://api.aicomputer.dev"
14)

Options

memory_limit

Maximum memory allocation for the sandbox. Format: "512M", "1G", etc.

Type: str, Default: "512M"

cpu_limit

Number of CPU cores available to the sandbox.

Type: int, Default: 1

timeout

Maximum execution time in seconds.

Type: int, Default: 30

allow_network

Whether to allow network access from the sandbox.

Type: bool, Default: False

allowed_hosts

List of hosts that can be accessed when network access is enabled.

Type: List[str], Default: []

base_url

API endpoint for AI Computer service.

Type: str, Default: "https://api.aicomputer.dev"

Methods

setup()

Initialize the sandbox environment. Must be called before executing any code.

1async def main():
2    client = SandboxClient()
3    response = await client.setup()
4    
5    if response.success:
6        print("Sandbox ready")
7    else:
8        print(f"Setup failed: {response.error}")
9
10asyncio.run(main())

execute_code(code: str) → SandboxResponse

Execute Python code synchronously and return the complete output.

1async def main():
2    client = SandboxClient()
3    await client.setup()
4    
5    try:
6        code = """
7x = 10
8y = 20
9print(f"Sum: {x + y}")
10"""
11        response = await client.execute_code(code)
12        if response.success:
13            print(response.data['output'])
14    finally:
15        await client.cleanup()
16
17asyncio.run(main())

execute_code_stream(code: str) → AsyncGenerator[StreamEvent, None]

Execute Python code and stream the output in real-time.

1async def main():
2    client = SandboxClient()
3    await client.setup()
4    
5    try:
6        code = """
7for i in range(5):
8    print(f"Step {i}")
9"""
10        async for event in client.execute_code_stream(code):
11            if event.type == 'stdout':
12                print("Output:", event.data)
13            elif event.type == 'stderr':
14                print("Error:", event.data)
15            elif event.type == 'completed':
16                print("Execution completed")
17    finally:
18        await client.cleanup()
19
20asyncio.run(main())

cleanup() → SandboxResponse

Clean up the sandbox environment and release all resources.

1async def main():
2    client = SandboxClient()
3    await client.setup()
4    
5    try:
6        # Your code here
7        pass
8    finally:
9        # Always clean up
10        response = await client.cleanup()
11        if response.success:
12            print("Cleanup successful")
13        else:
14            print(f"Cleanup failed: {response.error}")
15
16asyncio.run(main())

Error Handling

All methods return a SandboxResponse object that includes success status and error information.

1async def main():
2    client = SandboxClient()
3    
4    try:
5        # Handle setup errors
6        setup_response = await client.setup()
7        if not setup_response.success:
8            raise Exception(f"Setup failed: {setup_response.error}")
9        
10        # Handle execution errors
11        code = "print(undefined_variable)"
12        response = await client.execute_code(code)
13        
14        if response.success:
15            print(response.data['output'])
16        else:
17            print(f"Execution failed: {response.error}")
18            
19    except Exception as e:
20        print(f"Error: {str(e)}")
21        
22    finally:
23        await client.cleanup()
24
25asyncio.run(main())

Best Practices

  • Resource Management: Always use try/finally blocks to ensure proper cleanup of sandbox resources.
  • Error Handling: Check the success status of all operations and handle errors appropriately.
  • Streaming: Use streaming execution for long-running tasks or when you need real-time output.
  • Configuration: Set appropriate resource limits based on your workload requirements.
  • Security: Disable network access unless specifically required, and always validate input code.