Execution Models
AI Computer provides two execution models to suit different use cases: synchronous execution for simple operations and streaming execution for real-time output and long-running processes.
Synchronous Execution
Synchronous execution is the simplest way to run code. It follows a request-response pattern where you send code and receive the complete output when execution finishes.
Use Cases
- Quick calculations and data transformations
- Short-running scripts
- Simple API integrations
- Code that produces a single result
Example
1import asyncio
2from ai_computer import SandboxClient
3
4async def main():
5 client = SandboxClient()
6 await client.setup()
7
8 try:
9 code = """
10def fibonacci(n):
11 if n <= 1:
12 return n
13 return fibonacci(n-1) + fibonacci(n-2)
14
15result = fibonacci(10)
16print(f"Fibonacci(10) = {result}")
17"""
18 response = await client.execute_code(code)
19 if response.success:
20 print("Output:", response.data['output'])
21 finally:
22 await client.cleanup()
23
24asyncio.run(main())
Streaming Execution
Streaming execution provides real-time output as your code runs. This is ideal for long-running processes, interactive applications, or when you need to show progress.
Use Cases
- Long-running computations with progress updates
- Interactive AI agents and chatbots
- Real-time data processing
- Training machine learning models
Example
1import asyncio
2from ai_computer import SandboxClient
3
4async def main():
5 client = SandboxClient()
6 await client.setup()
7
8 try:
9 code = """
10import time
11
12def process_data(items):
13 for i, item in enumerate(items, 1):
14 print(f"Processing item {i}...")
15 time.sleep(1) # Simulate work
16 print(f"Item {i} processed")
17
18data = range(5)
19process_data(data)
20print("All items processed!")
21"""
22 print("Starting streaming execution...")
23 async for event in client.execute_code_stream(code):
24 if event.type == 'stdout':
25 print("Output:", event.data)
26 elif event.type == 'stderr':
27 print("Error:", event.data)
28 elif event.type == 'completed':
29 print("Execution completed")
30 finally:
31 await client.cleanup()
32
33asyncio.run(main())
Event Types
When using streaming execution, you'll receive different types of events:
stdout
Standard output from your code, including print statements and normal program output.
stderr
Error messages and warnings from your code or the Python interpreter.
error
Execution errors that prevent your code from running or completing.
completed
Signals that code execution has finished successfully.
Best Practices
- Choose the Right Model: Use synchronous execution for simple, quick operations and streaming for long-running or interactive tasks.
- Handle All Events: When streaming, handle all event types to ensure proper error handling and state management.
- Progress Updates: For long-running tasks, include regular progress updates in your code to keep users informed.
- Error Handling: Always handle potential errors in both execution models to ensure robust applications.