Examples
Explore practical examples and common use cases for AI Computer. Each example includes complete code and explanations to help you get started quickly.
Quick Example
Here's a simple example showing both basic execution and streaming:
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 # Example 1: Simple code execution
16 code = """x = 10
17y = 20
18result = x + y
19print(f"The sum is: {result}")"""
20
21 print("\nExample 1: Simple execution")
22 print("-" * 50)
23 response = await client.execute_code(code)
24 if response.success:
25 print("Execution result:", response.data)
26 else:
27 print("Execution failed:", response.error)
28
29 # Example 2: Streaming execution
30 code = """import time
31
32for i in range(5):
33 print(f"Processing step {i + 1}")
34 time.sleep(1) # Simulate work
35
36result = "Calculation complete!"
37print(result)"""
38
39 print("\nExample 2: Streaming execution")
40 print("-" * 50)
41 async for event in client.execute_code_stream(code):
42 if event.type == 'stdout':
43 print(f"Output: {event.data}")
44 elif event.type == 'stderr':
45 print(f"Error: {event.data}")
46 elif event.type == 'error':
47 print(f"Execution error: {event.data}")
48 break
49 elif event.type == 'completed':
50 print("Execution completed")
51 break
52
53 finally:
54 # Clean up
55 await client.cleanup()
56
57if __name__ == "__main__":
58 asyncio.run(main())
Example Categories
Basic Usage
Learn the fundamentals of using AI Computer with simple examples.
- Client initialization
- Simple code execution
- Response handling
- Cleanup patterns
Streaming Output
Examples of real-time output streaming and event handling.
- Real-time output handling
- Event types and processing
- Long-running processes
- Error handling in streams
File Operations
Working with files in the sandbox environment.
- Uploading files
- Downloading files
- Working with bytes
- File operation responses
Error Handling
Learn how to handle errors and edge cases effectively.
- Setup errors
- Execution errors
- Network timeouts
- Graceful recovery
Common Patterns
Proper Setup and Cleanup
Always initialize the client and clean up resources:
1async def safe_execution():
2 client = SandboxClient()
3
4 # Setup and check for errors
5 setup_response = await client.setup()
6 if not setup_response.success:
7 print(f"Setup failed: {setup_response.error}")
8 return
9
10 try:
11 # Your code here
12 response = await client.execute_code("print('Hello')")
13 return response
14 finally:
15 # Always clean up
16 await client.cleanup()
Error Handling
Implement comprehensive error handling:
1async def robust_execution(code: str):
2 client = SandboxClient()
3
4 try:
5 # Handle setup errors
6 setup_response = await client.setup()
7 if not setup_response.success:
8 return f"Setup failed: {setup_response.error}"
9
10 # Handle execution errors
11 response = await client.execute_code(code)
12 if not response.success:
13 return f"Execution failed: {response.error}"
14
15 return response.data['output']
16
17 except Exception as e:
18 return f"Unexpected error: {str(e)}"
19
20 finally:
21 await client.cleanup()
Next Steps
Choose an example category above to explore detailed examples and code samples. Each section includes complete, runnable code and explanations of key concepts.
For more information, you can also check:
- API Reference for detailed documentation
- Core Concepts for fundamental principles