Basic Usage Examples
Learn how to use AI Computer for common tasks with these basic examples. Each example demonstrates key features and best practices.
Client Initialization
Initialize the client and set up a sandbox:
1import asyncio
2from ai_computer import SandboxClient
3
4async def initialize_client():
5 # Create client instance
6 client = SandboxClient()
7
8 # Setup the client - this gets a token and creates a sandbox
9 setup_response = await client.setup()
10 if not setup_response.success:
11 print(f"Setup failed: {setup_response.error}")
12 return None
13
14 print("Sandbox created:", setup_response.data)
15 return client
16
17# Example usage
18async def main():
19 client = await initialize_client()
20 if client is None:
21 return
22
23 try:
24 print("Client initialized successfully")
25 finally:
26 await client.cleanup()
27
28asyncio.run(main())
Simple Code Execution
Execute Python code and handle the response:
1import asyncio
2from ai_computer import SandboxClient
3
4async def run_code():
5 client = SandboxClient()
6 setup_response = await client.setup()
7 if not setup_response.success:
8 print(f"Setup failed: {setup_response.error}")
9 return
10
11 try:
12 # Simple calculation
13 code = """
14def calculate_factorial(n):
15 if n == 0:
16 return 1
17 return n * calculate_factorial(n - 1)
18
19result = calculate_factorial(5)
20print(f"Factorial of 5 is: {result}")
21"""
22 response = await client.execute_code(code)
23
24 if response.success:
25 print("Execution successful!")
26 print("Output:", response.data['output'])
27 print("Sandbox ID:", response.data['sandbox_id'])
28 else:
29 print("Execution failed:", response.error)
30
31 finally:
32 await client.cleanup()
33
34asyncio.run(run_code())
Response Handling
Work with response objects and handle different outcomes:
1import asyncio
2from ai_computer import SandboxClient
3
4async def handle_responses():
5 client = SandboxClient()
6 setup_response = await client.setup()
7 if not setup_response.success:
8 print(f"Setup failed: {setup_response.error}")
9 return
10
11 try:
12 # Example 1: Successful execution
13 code1 = 'print("Hello, World!")'
14 response1 = await client.execute_code(code1)
15 if response1.success:
16 print("Success Response:")
17 print("- Output:", response1.data['output'])
18 print("- Sandbox ID:", response1.data['sandbox_id'])
19
20 # Example 2: Syntax error
21 code2 = 'print("Unclosed string'
22 response2 = await client.execute_code(code2)
23 if not response2.success:
24 print("\nError Response:")
25 print("- Error:", response2.error)
26
27 # Example 3: Runtime error
28 code3 = 'print(undefined_variable)'
29 response3 = await client.execute_code(code3)
30 if not response3.success:
31 print("\nRuntime Error Response:")
32 print("- Error:", response3.error)
33
34 finally:
35 await client.cleanup()
36
37asyncio.run(handle_responses())
Cleanup Patterns
Ensure proper resource cleanup in different scenarios:
1import asyncio
2from ai_computer import SandboxClient
3
4# Pattern 1: Basic try/finally
5async def basic_cleanup():
6 client = SandboxClient()
7 await client.setup()
8 try:
9 await client.execute_code("print('Hello')")
10 finally:
11 await client.cleanup()
12
13# Pattern 2: Handle setup failure
14async def handle_setup_cleanup():
15 client = SandboxClient()
16 setup_response = await client.setup()
17 if not setup_response.success:
18 print(f"Setup failed: {setup_response.error}")
19 return
20
21 try:
22 await client.execute_code("print('Hello')")
23 finally:
24 await client.cleanup()
25
26# Pattern 3: Multiple executions
27async def multiple_executions():
28 client = SandboxClient()
29 setup_response = await client.setup()
30 if not setup_response.success:
31 print(f"Setup failed: {setup_response.error}")
32 return
33
34 try:
35 # Multiple code executions in the same sandbox
36 await client.execute_code("x = 10")
37 await client.execute_code("y = 20")
38 await client.execute_code("print(x + y)")
39 finally:
40 # Single cleanup at the end
41 await client.cleanup()
42
43# Example usage
44async def main():
45 print("Basic cleanup pattern:")
46 await basic_cleanup()
47
48 print("\nSetup handling pattern:")
49 await handle_setup_cleanup()
50
51 print("\nMultiple executions pattern:")
52 await multiple_executions()
53
54asyncio.run(main())
Best Practices
1. Always Check Setup Response
Verify that setup was successful before proceeding with code execution.
2. Use try/finally for Cleanup
Ensure cleanup is called even if execution fails or raises an exception.
3. Check Response Success
Always check response.success before accessing response.data.
4. Reuse Sandboxes
When executing multiple code blocks, reuse the same sandbox instead of creating new ones.