Submodules API Reference
The AI Computer Python SDK organizes functionality into submodules for better code organization and a more intuitive API. Each submodule provides methods related to a specific domain of functionality.
Submodule Overview
The SandboxClient provides access to the following submodules:
- fs - File system operations (FileSystemModule)
- shell - Shell command execution (ShellModule)
- code - Python code execution (CodeModule)
Each submodule is accessible as a property of the SandboxClient instance:
1from ai_computer import SandboxClient
2
3client = SandboxClient()
4
5# Access submodules
6fs_module = client.fs
7shell_module = client.shell
8code_module = client.code
FileSystemModule
The FileSystemModule provides methods for file and directory operations in the sandbox environment.
Methods
read_file(path: str, encoding: str = 'utf-8') → SandboxResponse
Reads the contents of a file at the specified path.
Parameters:
path
- Path to the file to readencoding
- Character encoding to use (default: 'utf-8')
Returns: A SandboxResponse object with the file contents in the data
field
1response = await client.fs.read_file("example.txt")
2if response.success:
3 content = response.data
4 print(f"File content: {content}")
5else:
6 print(f"Error reading file: {response.error}")
write_file(path: str, content: Union[str, bytes], encoding: str = 'utf-8') → SandboxResponse
Writes content to a file at the specified path.
Parameters:
path
- Path where the file should be writtencontent
- String or bytes content to writeencoding
- Character encoding to use (default: 'utf-8')
Returns: A SandboxResponse object indicating success or failure
1content = "Hello, AI Computer!"
2response = await client.fs.write_file("example.txt", content)
3if response.success:
4 print("File written successfully")
5else:
6 print(f"Error writing file: {response.error}")
upload_file(file_path: Union[str, Path], destination: str = "/workspace", chunk_size: int = 1024 * 1024, timeout: int = 300) → FileOperationResponse
Uploads a file from the local filesystem to the sandbox environment.
Parameters:
file_path
- Path to the local file to uploaddestination
- Destination path in the sandbox (default: "/workspace")chunk_size
- Size of chunks for large file uploads in bytes (default: 1MB)timeout
- Timeout in seconds (default: 300)
Returns: A FileOperationResponse object with details about the uploaded file
1response = await client.fs.upload_file("local_data.csv", "data.csv")
2if response.success:
3 print(f"File uploaded successfully to {response.path}")
4 print(f"File size: {response.size} bytes")
5else:
6 print(f"Error uploading file: {response.error}")
download_file(remote_path: str, local_path: Optional[Union[str, Path]] = None, timeout: int = 300) → FileOperationResponse
Downloads a file from the sandbox environment to the local filesystem.
Parameters:
remote_path
- Path to the file in the sandboxlocal_path
- Local path where the file should be saved (default: same filename in current directory)timeout
- Timeout in seconds (default: 300)
Returns: A FileOperationResponse object with details about the downloaded file
1response = await client.fs.download_file("results.csv", "local_results.csv")
2if response.success:
3 print(f"File downloaded successfully to {response.path}")
4 print(f"File size: {response.size} bytes")
5else:
6 print(f"Error downloading file: {response.error}")
upload_bytes(content: Union[bytes, BinaryIO], filename: str, destination: str = "/workspace", content_type: Optional[str] = None, timeout: int = 300) → FileOperationResponse
Uploads binary data to a file in the sandbox environment.
Parameters:
content
- Binary data or file-like object to uploadfilename
- Name of the file to create in the sandboxdestination
- Destination directory in the sandbox (default: "/workspace")content_type
- MIME type of the content (default: auto-detected)timeout
- Timeout in seconds (default: 300)
Returns: A FileOperationResponse object with details about the uploaded file
1binary_data = b"\x00\x01\x02\x03"
2response = await client.fs.upload_bytes(binary_data, "binary_file.bin")
3if response.success:
4 print(f"Binary data uploaded successfully to {response.path}")
5 print(f"File size: {response.size} bytes")
6else:
7 print(f"Error uploading binary data: {response.error}")
download_bytes(remote_path: str, timeout: int = 300) → FileOperationResponse
Downloads a file from the sandbox environment as binary data.
Parameters:
remote_path
- Path to the file in the sandboxtimeout
- Timeout in seconds (default: 300)
Returns: A FileOperationResponse object with the binary data in the data
field
1response = await client.fs.download_bytes("binary_file.bin")
2if response.success:
3 binary_data = response.data
4 print(f"Downloaded {len(binary_data)} bytes")
5else:
6 print(f"Error downloading binary data: {response.error}")
ShellModule
The ShellModule provides methods for executing shell commands in the sandbox environment.
Methods
execute(command: str, args: Optional[List[str]] = None, timeout: int = 30) → SandboxResponse
Executes a shell command and returns the result.
Parameters:
command
- The shell command to executeargs
- Optional list of arguments for the commandtimeout
- Timeout in seconds (default: 30)
Returns: A SandboxResponse object with the command output in the data
field
1# Simple command
2response = await client.shell.execute("ls -la")
3if response.success:
4 output = response.data
5 print(f"Command output: {output}")
6else:
7 print(f"Error executing command: {response.error}")
8
9# Command with separate arguments
10response = await client.shell.execute("find", ["/workspace", "-name", "*.py"])
11if response.success:
12 output = response.data
13 print(f"Found Python files: {output}")
14else:
15 print(f"Error executing command: {response.error}")
CodeModule
The CodeModule provides methods for executing Python code in the sandbox environment.
Methods
execute(code: str, timeout: int = 30, environment: Optional[Dict[str, str]] = None) → SandboxResponse
Executes Python code and returns the result.
Parameters:
code
- Python code to executetimeout
- Timeout in seconds (default: 30)environment
- Optional dictionary of environment variables
Returns: A SandboxResponse object with the code output in the data
field
1code = """
2import math
3result = math.sqrt(16)
4print(f"The square root of 16 is {result}")
5"""
6response = await client.code.execute(code)
7if response.success:
8 output = response.data
9 print(f"Code output: {output}")
10else:
11 print(f"Error executing code: {response.error}")
12
13# With environment variables
14env_vars = {"DEBUG": "1", "DATA_PATH": "/workspace/data"}
15response = await client.code.execute("import os; print(os.environ['DEBUG'])", environment=env_vars)
16if response.success:
17 print(f"Output with env vars: {response.data}")
18else:
19 print(f"Error: {response.error}")
execute_stream(code: str, timeout: int = 30, environment: Optional[Dict[str, str]] = None) → AsyncGenerator[StreamEvent, None]
Executes Python code and streams the output as events.
Parameters:
code
- Python code to executetimeout
- Timeout in seconds (default: 30)environment
- Optional dictionary of environment variables
Returns: An async generator yielding StreamEvent objects
1code = """
2for i in range(5):
3 print(f"Processing step {i+1}")
4"""
5async for event in client.code.execute_stream(code):
6 if event.type == 'stdout':
7 print(f"Output: {event.data}")
8 elif event.type == 'stderr':
9 print(f"Error: {event.data}")
10 elif event.type == 'error':
11 print(f"Execution error: {event.data}")
12 elif event.type == 'completed':
13 print("Execution completed")
execute_file(file_path: str, timeout: int = 30, environment: Optional[Dict[str, str]] = None) → SandboxResponse
Executes a Python file in the sandbox environment.
Parameters:
file_path
- Path to the Python file in the sandboxtimeout
- Timeout in seconds (default: 30)environment
- Optional dictionary of environment variables
Returns: A SandboxResponse object with the script output in the data
field
1# First, create a Python file
2code = """
3with open('script.py', 'w') as f:
4 f.write('''
5def calculate():
6 result = 0
7 for i in range(10):
8 result += i
9 return result
10
11if __name__ == "__main__":
12 print(f"The result is: {calculate()}")
13''')
14"""
15await client.code.execute(code)
16
17# Then execute the file
18response = await client.code.execute_file("script.py")
19if response.success:
20 output = response.data
21 print(f"Script output: {output}")
22else:
23 print(f"Error executing script: {response.error}")
execute_file_stream(file_path: str, timeout: int = 30, environment: Optional[Dict[str, str]] = None) → AsyncGenerator[StreamEvent, None]
Executes a Python file and streams the output as events.
Parameters:
file_path
- Path to the Python file in the sandboxtimeout
- Timeout in seconds (default: 30)environment
- Optional dictionary of environment variables
Returns: An async generator yielding StreamEvent objects
1# First, create a Python file with a long-running process
2code = """
3with open('long_process.py', 'w') as f:
4 f.write('''
5import time
6
7def process():
8 for i in range(5):
9 print(f"Step {i+1} of 5")
10 time.sleep(1)
11 print("Process completed")
12
13if __name__ == "__main__":
14 process()
15''')
16"""
17await client.code.execute(code)
18
19# Then execute the file with streaming
20async for event in client.code.execute_file_stream("long_process.py"):
21 if event.type == 'stdout':
22 print(f"Output: {event.data}")
23 elif event.type == 'stderr':
24 print(f"Error: {event.data}")
25 elif event.type == 'error':
26 print(f"Execution error: {event.data}")
27 elif event.type == 'completed':
28 print("Execution completed")
Response Objects
The submodules use the following response objects:
SandboxResponse
Used for code execution and shell commands.
1@dataclass
2class SandboxResponse:
3 """Response from sandbox operations.
4
5 Attributes:
6 success: Whether the operation was successful
7 data: Optional response data
8 error: Optional error message if operation failed
9 """
10 success: bool
11 data: Optional[Dict] = None
12 error: Optional[str] = None
FileOperationResponse
Used for file operations.
1@dataclass
2class FileOperationResponse:
3 """Response from file operations.
4
5 Attributes:
6 success: Whether the operation was successful
7 filename: Name of the file
8 size: Size of the file in bytes
9 path: Path where the file was saved
10 message: Optional status message
11 error: Optional error message if operation failed
12 """
13 success: bool
14 filename: Optional[str] = None
15 size: Optional[int] = None
16 path: Optional[str] = None
17 message: Optional[str] = None
18 error: Optional[str] = None
StreamEvent
Used for streaming code execution.
1@dataclass
2class StreamEvent:
3 """Event from streaming code execution.
4
5 Attributes:
6 type: Type of event ('stdout', 'stderr', 'info', 'error', 'completed', 'keepalive')
7 data: Event data
8 """
9 type: str
10 data: str
Best Practices
1. Use Appropriate Submodule
Choose the right submodule for the task: fs for file operations, shell for command execution, and code for Python code execution.
2. Handle Responses Properly
Always check the success status of responses and handle errors appropriately.
3. Use Streaming for Long Operations
For long-running operations, use streaming methods to get real-time feedback.
4. Clean Up Resources
Always call client.cleanup() when finished to release resources.
5. Use Relative Paths
When working with files in the sandbox, use relative paths instead of absolute paths when possible.
6. Set Appropriate Timeouts
Adjust timeout values based on the expected duration of operations, especially for large file transfers.