Submodule Usage Examples

The AI Computer Python SDK organizes functionality into submodules for better code organization and a more intuitive API. This page provides comprehensive examples of how to use each submodule.

Complete Example

Here's a complete example demonstrating how to use all three submodules:

1import asyncio
2from ai_computer import SandboxClient
3
4async def main():
5    # Initialize the client
6    client = SandboxClient()
7    
8    # Setup the client (gets token and creates sandbox)
9    setup_response = await client.setup()
10    if not setup_response.success:
11        print(f"Setup failed: {setup_response.error}")
12        return
13    
14    try:
15        print("\nExample 1: Using the filesystem submodule")
16        print("-" * 50)
17        
18        # Write a file using the fs submodule
19        write_response = await client.fs.write_file(
20            "hello.txt", 
21            "Hello, world! This file was created using the fs submodule."
22        )
23        
24        if write_response.success:
25            print("File written successfully")
26            
27            # Read the file back
28            read_response = await client.fs.read_file("hello.txt")
29            if read_response.success:
30                print(f"File contents: {read_response.data}")
31            else:
32                print(f"Failed to read file: {read_response.error}")
33        else:
34            print(f"Failed to write file: {write_response.error}")
35        
36        print("\nExample 2: Using the shell submodule")
37        print("-" * 50)
38        
39        # Execute a shell command
40        shell_response = await client.shell.execute("ls", ["-la"])
41        if shell_response.success:
42            print("Shell command output:")
43            print(shell_response.data)
44        else:
45            print(f"Shell command failed: {shell_response.error}")
46        
47        print("\nExample 3: Using the code submodule")
48        print("-" * 50)
49        
50        # Execute Python code
51        code = """
52import os
53import platform
54
55result = {
56    "python_version": platform.python_version(),
57    "platform": platform.platform(),
58    "workspace_files": os.listdir()
59}
60
61print(f"Running Python {platform.python_version()}")
62result
63"""
64        
65        code_response = await client.code.execute(code)
66        if code_response.success:
67            print("Code execution result:")
68            print(f"Output: {code_response.data}")
69        else:
70            print(f"Code execution failed: {code_response.error}")
71            
72        # Execute Python code with streaming output
73        print("\nStreaming code execution:")
74        streaming_code = """
75import time
76
77for i in range(5):
78    print(f"Processing step {i + 1}")
79    time.sleep(0.5)  # Simulate work
80    
81result = "Calculation complete!"
82print(result)
83"""
84        
85        async for event in client.code.execute_stream(streaming_code):
86            if event.type == 'stdout':
87                print(f"Output: {event.data}")
88            elif event.type == 'stderr':
89                print(f"Error: {event.data}")
90            elif event.type == 'error':
91                print(f"Execution error: {event.data}")
92                break
93            elif event.type == 'completed':
94                print("Execution completed")
95                break
96    
97    finally:
98        # Clean up
99        await client.cleanup()
100
101if __name__ == "__main__":
102    asyncio.run(main())

FileSystemModule Advanced Examples

Here are some advanced examples of using the FileSystemModule:

1import asyncio
2import os
3from pathlib import Path
4from io import BytesIO
5from ai_computer import SandboxClient
6
7async def filesystem_examples():
8    client = SandboxClient()
9    await client.setup()
10    
11    try:
12        # Example 1: Upload a local file to the sandbox
13        print("Uploading a local file...")
14        
15        # Create a temporary local file
16        with open("local_data.txt", "w") as f:
17            f.write("This is test data to upload")
18        
19        # Upload the file
20        upload_response = await client.fs.upload_file(
21            "local_data.txt",
22            "uploaded_data.txt"
23        )
24        
25        if upload_response.success:
26            print(f"File uploaded successfully to {upload_response.path}")
27            print(f"File size: {upload_response.size} bytes")
28            
29            # Verify the file exists in the sandbox
30            verify_code = """
31import os
32print(f"File exists: {'uploaded_data.txt' in os.listdir()}")
33with open('uploaded_data.txt', 'r') as f:
34    print(f"Content: {f.read()}")
35"""
36            await client.code.execute(verify_code)
37        
38        # Example 2: Working with binary data
39        print("\nWorking with binary data...")
40        
41        # Create binary data
42        binary_data = bytes([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
43        
44        # Upload binary data
45        binary_upload = await client.fs.upload_bytes(
46            binary_data,
47            "binary_file.bin"
48        )
49        
50        if binary_upload.success:
51            print(f"Binary data uploaded to {binary_upload.path}")
52            
53            # Download the binary data
54            binary_download = await client.fs.download_bytes("binary_file.bin")
55            if binary_download.success:
56                print(f"Downloaded {len(binary_download.data)} bytes")
57                print(f"Data matches: {binary_data == binary_download.data}")
58        
59        # Example 3: Working with BytesIO objects
60        print("\nWorking with BytesIO objects...")
61        
62        # Create a BytesIO object
63        bytes_io = BytesIO(b"This is data from a BytesIO object")
64        
65        # Upload the BytesIO object
66        bytesio_upload = await client.fs.upload_bytes(
67            bytes_io,
68            "bytesio_file.txt"
69        )
70        
71        if bytesio_upload.success:
72            print(f"BytesIO data uploaded to {bytesio_upload.path}")
73            
74            # Read the file
75            read_response = await client.fs.read_file("bytesio_file.txt")
76            if read_response.success:
77                print(f"File content: {read_response.data}")
78        
79        # Example 4: Download a file from the sandbox
80        print("\nDownloading a file...")
81        
82        # Create a file in the sandbox
83        await client.fs.write_file(
84            "download_me.txt",
85            "This file will be downloaded"
86        )
87        
88        # Download the file
89        download_response = await client.fs.download_file(
90            "download_me.txt",
91            "local_download.txt"
92        )
93        
94        if download_response.success:
95            print(f"File downloaded to {download_response.path}")
96            
97            # Verify the local file
98            with open("local_download.txt", "r") as f:
99                print(f"Local file content: {f.read()}")
100            
101            # Clean up the local file
102            os.remove("local_download.txt")
103            print("Local file removed")
104    
105    finally:
106        # Clean up local files
107        if os.path.exists("local_data.txt"):
108            os.remove("local_data.txt")
109        
110        await client.cleanup()
111
112if __name__ == "__main__":
113    asyncio.run(filesystem_examples())

ShellModule Advanced Examples

Here are some advanced examples of using the ShellModule:

1import asyncio
2from ai_computer import SandboxClient
3
4async def shell_examples():
5    client = SandboxClient()
6    await client.setup()
7    
8    try:
9        # Example 1: Basic shell commands
10        print("Basic shell commands...")
11        
12        # Check the current directory
13        pwd_response = await client.shell.execute("pwd")
14        if pwd_response.success:
15            print(f"Current directory: {pwd_response.data}")
16        
17        # List files
18        ls_response = await client.shell.execute("ls", ["-la"])
19        if ls_response.success:
20            print("Directory contents:")
21            print(ls_response.data)
22        
23        # Example 2: Creating and manipulating files with shell commands
24        print("\nCreating and manipulating files...")
25        
26        # Create a directory
27        mkdir_response = await client.shell.execute("mkdir", ["-p", "test_dir/nested_dir"])
28        if mkdir_response.success:
29            print("Created directory structure")
30        
31        # Create a file with content
32        echo_response = await client.shell.execute(
33            "echo", 
34            ["This is a test file created with shell commands > test_dir/test.txt"]
35        )
36        if echo_response.success:
37            print("Created test file")
38        
39        # Check the file content
40        cat_response = await client.shell.execute("cat", ["test_dir/test.txt"])
41        if cat_response.success:
42            print(f"File content: {cat_response.data}")
43        
44        # Example 3: Running multiple commands
45        print("\nRunning multiple commands...")
46        
47        # Use semicolons to run multiple commands
48        multi_cmd = await client.shell.execute("cd test_dir && ls -la && cd .. && pwd")
49        if multi_cmd.success:
50            print("Multiple commands output:")
51            print(multi_cmd.data)
52        
53        # Example 4: Working with environment variables
54        print("\nWorking with environment variables...")
55        
56        # Set and read an environment variable
57        env_cmd = await client.shell.execute("export TEST_VAR='Hello World' && echo $TEST_VAR")
58        if env_cmd.success:
59            print(f"Environment variable value: {env_cmd.data}")
60        
61        # Example 5: Error handling
62        print("\nError handling...")
63        
64        # Try to run a non-existent command
65        error_cmd = await client.shell.execute("non_existent_command")
66        print(f"Command success: {error_cmd.success}")
67        print(f"Error message: {error_cmd.error}")
68    
69    finally:
70        await client.cleanup()
71
72if __name__ == "__main__":
73    asyncio.run(shell_examples())

CodeModule Advanced Examples

Here are some advanced examples of using the CodeModule:

1import asyncio
2from ai_computer import SandboxClient
3
4async def code_examples():
5    client = SandboxClient()
6    await client.setup()
7    
8    try:
9        # Example 1: Basic code execution
10        print("Basic code execution...")
11        
12        code = """
13import sys
14import platform
15
16print(f"Python version: {sys.version}")
17print(f"Platform: {platform.platform()}")
18
19result = {
20    "python_version": platform.python_version(),
21    "platform": platform.platform(),
22    "implementation": platform.python_implementation()
23}
24
25result  # This will be returned as the result
26"""
27        
28        response = await client.code.execute(code)
29        if response.success:
30            print("Code output:")
31            print(response.data)
32        
33        # Example 2: Working with environment variables
34        print("\nWorking with environment variables...")
35        
36        env_code = """
37import os
38
39print("Environment variables:")
40for key, value in os.environ.items():
41    if key.startswith("TEST_"):
42        print(f"{key}={value}")
43"""
44        
45        env_vars = {
46            "TEST_VAR1": "value1",
47            "TEST_VAR2": "value2",
48            "TEST_DEBUG": "true"
49        }
50        
51        env_response = await client.code.execute(env_code, environment=env_vars)
52        if env_response.success:
53            print("Code output with environment variables:")
54            print(env_response.data)
55        
56        # Example 3: Creating and executing a Python file
57        print("\nCreating and executing a Python file...")
58        
59        # Create a Python file
60        create_file_code = """
61with open('calculation.py', 'w') as f:
62    f.write('''
63def fibonacci(n):
64    """Calculate the nth Fibonacci number."""
65    if n <= 0:
66        return 0
67    elif n == 1:
68        return 1
69    else:
70        return fibonacci(n-1) + fibonacci(n-2)
71
72if __name__ == "__main__":
73    import sys
74    
75    try:
76        n = int(sys.argv[1]) if len(sys.argv) > 1 else 10
77    except ValueError:
78        n = 10
79    
80    print(f"Calculating Fibonacci({n})...")
81    result = fibonacci(n)
82    print(f"Fibonacci({n}) = {result}")
83''')
84
85print("Created calculation.py file")
86"""
87        
88        await client.code.execute(create_file_code)
89        
90        # Execute the file
91        file_response = await client.code.execute_file("calculation.py")
92        if file_response.success:
93            print("File execution output:")
94            print(file_response.data)
95        
96        # Example 4: Streaming file execution with arguments
97        print("\nStreaming file execution with arguments...")
98        
99        # Create a Python file with arguments
100        create_args_file = """
101with open('args_example.py', 'w') as f:
102    f.write('''
103import sys
104import time
105
106def main():
107    print(f"Arguments: {sys.argv[1:]}")
108    
109    total_steps = 5
110    for i in range(total_steps):
111        # Simulate processing
112        time.sleep(0.5)
113        
114        # Report progress
115        progress = (i + 1) / total_steps * 100
116        print(f"Progress: {progress:.1f}% ({i + 1}/{total_steps})")
117    
118    return "Processing complete"
119
120if __name__ == "__main__":
121    result = main()
122    print(result)
123''')
124
125print("Created args_example.py file")
126"""
127        
128        await client.code.execute(create_args_file)
129        
130        # Execute the file with streaming and environment variables
131        print("Streaming execution output:")
132        
133        env_vars = {"PYTHONUNBUFFERED": "1"}  # Ensure output is not buffered
134        
135        async for event in client.code.execute_file_stream(
136            "args_example.py",
137            environment=env_vars
138        ):
139            if event.type == 'stdout':
140                print(f"Output: {event.data}")
141            elif event.type == 'stderr':
142                print(f"Error: {event.data}")
143            elif event.type == 'error':
144                print(f"Execution error: {event.data}")
145                break
146            elif event.type == 'completed':
147                print("Execution completed")
148                break
149        
150        # Example 5: Error handling
151        print("\nError handling...")
152        
153        error_code = """
154# This code will raise an exception
155x = 10 / 0
156"""
157        
158        error_response = await client.code.execute(error_code)
159        print(f"Execution success: {error_response.success}")
160        if not error_response.success:
161            print(f"Error message: {error_response.error}")
162        
163        # Example 6: Streaming with error handling
164        print("\nStreaming with error handling...")
165        
166        error_stream_code = """
167import time
168
169try:
170    for i in range(5):
171        print(f"Step {i+1}")
172        if i == 2:
173            # Simulate an error
174            raise ValueError("Simulated error at step 3")
175        time.sleep(0.5)
176except Exception as e:
177    print(f"Error occurred: {str(e)}")
178    raise  # Re-raise to show how errors are handled
179"""
180        
181        try:
182            async for event in client.code.execute_stream(error_stream_code):
183                if event.type == 'stdout':
184                    print(f"Output: {event.data}")
185                elif event.type == 'stderr':
186                    print(f"Error output: {event.data}")
187                elif event.type == 'error':
188                    print(f"Execution error: {event.data}")
189                    break
190                elif event.type == 'completed':
191                    print("Execution completed")
192                    break
193        except Exception as e:
194            print(f"Exception during streaming: {str(e)}")
195    
196    finally:
197        await client.cleanup()
198
199if __name__ == "__main__":
200    asyncio.run(code_examples())

Best Practices

1. Use Try/Finally Blocks

Always wrap your code in try/finally blocks to ensure proper cleanup, even if an error occurs.

1async def safe_execution():
2    client = SandboxClient()
3    await client.setup()
4    
5    try:
6        # Your code here
7        await client.fs.write_file("example.txt", "Hello, World!")
8        await client.code.execute("print('Hello, World!')")
9    finally:
10        # Always clean up
11        await client.cleanup()

2. Check Response Success

Always check the success status of responses before accessing data.

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}")

3. Use Relative Paths

Use relative paths instead of absolute paths when working with files in the sandbox.

1# Good - using relative paths
2await client.fs.write_file("data/example.txt", "Hello, World!")
3
4# Avoid - using absolute paths
5await client.fs.write_file("/workspace/data/example.txt", "Hello, World!")

4. Handle Streaming Events Properly

When using streaming methods, handle all relevant event types.

1async for event in client.code.execute_stream(code):
2    match event.type:
3        case 'stdout':
4            print(f"Output: {event.data}")
5        case 'stderr':
6            print(f"Error output: {event.data}")
7        case 'error':
8            print(f"Execution error: {event.data}")
9            break  # Stop processing on error
10        case 'completed':
11            print("Execution completed")
12            break  # Stop processing when completed
13        case 'keepalive':
14            pass  # Ignore keepalive events