SandboxClient
The SandboxClient class is the main interface for interacting with AI Computer. It provides methods for creating sandboxes, executing code, and managing resources. The client is organized into submodules for different types of operations.
Constructor
1from ai_computer import SandboxClient
2
3# Basic initialization
4client = SandboxClient()
5
6# With custom configuration
7client = SandboxClient(
8 base_url="https://api.aicomputer.dev",
9 token="your_api_token" # Optional, will be auto-generated if not provided
10)
Options
base_url
API endpoint for AI Computer service.
Type: str, Default: "https://api.aicomputer.dev"
token
API token for authentication. If not provided, a token will be generated automatically.
Type: str, Default: None
Submodules
The SandboxClient is organized into submodules for different types of operations:
fs
File system operations submodule for uploading, downloading, reading, and writing files.
Type: FileSystemModule
shell
Shell operations submodule for executing shell commands.
Type: ShellModule
code
Code execution submodule for running Python code.
Type: CodeModule
1# Using submodules
2client = SandboxClient()
3await client.setup()
4
5# File system operations
6await client.fs.read_file('example.txt')
7await client.fs.write_file('output.txt', 'Hello, world!')
8
9# Shell operations
10await client.shell.execute('ls -la')
11
12# Code execution
13await client.code.execute('print("Hello from Python!")')
Core 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. This method delegates to the code submodule.
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())
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())
File Operations
upload_file(file_path, destination) → FileOperationResponse
Upload a file to the sandbox. This method delegates to the fs submodule.
1async def main():
2 client = SandboxClient()
3 await client.setup()
4
5 try:
6 # Upload a local file to the sandbox
7 response = await client.upload_file(
8 file_path="local_file.txt",
9 destination="uploads" # Relative path in the sandbox
10 )
11
12 if response.success:
13 print(f"File uploaded to {response.path}")
14 print(f"Size: {response.size} bytes")
15 else:
16 print(f"Upload failed: {response.error}")
17 finally:
18 await client.cleanup()
19
20asyncio.run(main())
download_file(remote_path, local_path) → FileOperationResponse
Download a file from the sandbox. This method delegates to the fs submodule.
1async def main():
2 client = SandboxClient()
3 await client.setup()
4
5 try:
6 # Download a file from the sandbox
7 response = await client.download_file(
8 remote_path="uploads/example.txt", # Path in the sandbox
9 local_path="downloaded_file.txt" # Local path to save the file
10 )
11
12 if response.success:
13 print(f"File downloaded to {response.path}")
14 print(f"Size: {response.size} bytes")
15 else:
16 print(f"Download failed: {response.error}")
17 finally:
18 await client.cleanup()
19
20asyncio.run(main())
upload_bytes(content, filename, destination) → FileOperationResponse
Upload bytes or a file-like object to the sandbox. This method delegates to the fs submodule.
1async def main():
2 client = SandboxClient()
3 await client.setup()
4
5 try:
6 # Upload bytes directly
7 content = b"Hello, world!"
8 response = await client.upload_bytes(
9 content=content,
10 filename="hello.txt",
11 destination="uploads"
12 )
13
14 if response.success:
15 print(f"Bytes uploaded to {response.path}")
16 else:
17 print(f"Upload failed: {response.error}")
18
19 # Upload from BytesIO
20 from io import BytesIO
21 buffer = BytesIO(b"Content from BytesIO")
22 response = await client.upload_bytes(
23 content=buffer,
24 filename="from_buffer.txt",
25 destination="uploads"
26 )
27 finally:
28 await client.cleanup()
29
30asyncio.run(main())
download_bytes(remote_path) → Union[bytes, FileOperationResponse]
Download a file from the sandbox as bytes. This method delegates to the fs submodule.
1async def main():
2 client = SandboxClient()
3 await client.setup()
4
5 try:
6 # Download a file as bytes
7 result = await client.download_bytes("uploads/example.txt")
8
9 if isinstance(result, bytes):
10 print(f"Downloaded {len(result)} bytes")
11 print(f"Content: {result.decode('utf-8')}")
12 else:
13 print(f"Download failed: {result.error}")
14 finally:
15 await client.cleanup()
16
17asyncio.run(main())
Error Handling
All methods return a SandboxResponse or FileOperationResponse 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.
- Submodule Organization: Use the appropriate submodule for specific operations to keep your code organized.
- Path Handling: When working with files, use relative paths within the sandbox to avoid permission issues.
- Memory Efficiency: For large files, consider using the file streaming capabilities of the upload and download methods.