Streaming Output Examples
Learn how to use streaming execution to handle real-time output and process events as they occur during code execution.
Basic Streaming
Stream output in real-time as your code executes using the code submodule:
1import asyncio
2from ai_computer import SandboxClient
3
4async def basic_streaming():
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 code = """
13import time
14
15for i in range(5):
16 print(f"Step {i + 1} of 5")
17 time.sleep(1) # Simulate work
18
19print("Task completed!")
20"""
21 print("Starting execution...")
22 async for event in client.code.execute_stream(code):
23 if event.type == 'stdout':
24 print("Output:", event.data)
25 elif event.type == 'stderr':
26 print("Error:", event.data)
27 elif event.type == 'error':
28 print("Execution error:", event.data)
29 break
30 elif event.type == 'completed':
31 print("Execution completed")
32 break
33
34 finally:
35 await client.cleanup()
36
37asyncio.run(basic_streaming())
Event Types
Handle different types of events during streaming execution:
1import asyncio
2from ai_computer import SandboxClient
3
4async def handle_event_types():
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 # Code that generates different types of events
13 code = """
14import sys
15
16# Standard output
17print("This goes to stdout")
18
19# Standard error
20print("This goes to stderr", file=sys.stderr)
21
22# Runtime error
23x = undefined_variable
24"""
25 async for event in client.code.execute_stream(code):
26 # Print event type and data
27 print(f"Event Type: {event.type}")
28 print(f"Event Data: {event.data}")
29 print("-" * 50)
30
31 # Handle specific event types
32 match event.type:
33 case 'stdout':
34 print("Standard output received")
35 case 'stderr':
36 print("Error output received")
37 case 'error':
38 print("Execution error occurred")
39 break
40 case 'completed':
41 print("Execution finished")
42 break
43
44 finally:
45 await client.cleanup()
46
47asyncio.run(handle_event_types())
Executing Files with Streaming
Stream output from executing a Python file:
1import asyncio
2from ai_computer import SandboxClient
3
4async def execute_file_stream():
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 # First, create a Python file in the sandbox
13 create_file_code = """
14with open('process.py', 'w') as f:
15 f.write('''
16import time
17
18def process_data():
19 total_steps = 5
20 for i in range(total_steps):
21 # Simulate processing
22 time.sleep(1)
23
24 # Report progress
25 progress = (i + 1) / total_steps * 100
26 print(f"Progress: {progress:.1f}% ({i + 1}/{total_steps})")
27
28 return "Processing complete"
29
30if __name__ == "__main__":
31 result = process_data()
32 print(result)
33''')
34print("Created process.py file")
35"""
36 await client.execute_code(create_file_code)
37
38 print("Executing file with streaming...")
39
40 # Execute the file with streaming
41 async for event in client.code.execute_file_stream('process.py'):
42 if event.type == 'stdout':
43 print("Output:", event.data)
44 elif event.type == 'stderr':
45 print("Error:", event.data)
46 elif event.type == 'error':
47 print("Execution error:", event.data)
48 break
49 elif event.type == 'completed':
50 print("Execution completed")
51 break
52
53 finally:
54 await client.cleanup()
55
56asyncio.run(execute_file_stream())
Error Handling in Streams
Handle errors and exceptions during streaming execution:
1import asyncio
2from ai_computer import SandboxClient
3
4async def stream_with_error_handling():
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 code = """
13import time
14import sys
15
16try:
17 for i in range(5):
18 print(f"Processing item {i}")
19
20 if i == 2:
21 # Simulate an error
22 raise ValueError("Something went wrong!")
23
24 time.sleep(1)
25except Exception as e:
26 print(f"Error occurred: {str(e)}", file=sys.stderr)
27 raise # Re-raise the error
28"""
29 print("Starting execution with error handling...")
30
31 try:
32 async for event in client.code.execute_stream(code):
33 match event.type:
34 case 'stdout':
35 print("Output:", event.data)
36 case 'stderr':
37 print("Error output:", event.data)
38 case 'error':
39 print("Execution error:", event.data)
40 # Handle the error appropriately
41 break
42 case 'completed':
43 print("Execution completed")
44 break
45 except Exception as e:
46 print(f"Stream processing exception: {str(e)}")
47
48 finally:
49 await client.cleanup()
50
51asyncio.run(stream_with_error_handling())
Best Practices
1. Handle All Event Types
Process all relevant event types (stdout, stderr, error, completed) for robust execution.
2. Use Try/Finally Blocks
Always clean up resources with client.cleanup() in a finally block.
3. Implement Proper Error Handling
Handle both stream events of type 'error' and exceptions that might occur during streaming.
4. Use the Code Submodule
Access streaming functionality through the code submodule for better organization.
5. Consider Performance
For long-running operations, streaming provides better user experience with real-time feedback.