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:
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.execute_code_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# Syntax error (uncomment to test)
23# print("Unclosed string
24
25# Runtime error
26x = undefined_variable
27"""
28 async for event in client.execute_code_stream(code):
29 # Print event type and data
30 print(f"Event Type: {event.type}")
31 print(f"Event Data: {event.data}")
32 print("-" * 50)
33
34 # Handle specific event types
35 match event.type:
36 case 'stdout':
37 print("Standard output received")
38 case 'stderr':
39 print("Error output received")
40 case 'error':
41 print("Execution error occurred")
42 break
43 case 'completed':
44 print("Execution finished")
45 break
46
47 finally:
48 await client.cleanup()
49
50asyncio.run(handle_event_types())
Long-Running Processes
Handle output from long-running computations:
1import asyncio
2from ai_computer import SandboxClient
3
4async def long_running_process():
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 # Simulate a long computation with progress updates
13 code = """
14import time
15
16def process_data(items):
17 total = len(items)
18 for i, item in enumerate(items, 1):
19 # Simulate processing
20 time.sleep(1)
21
22 # Report progress
23 progress = (i / total) * 100
24 print(f"Progress: {progress:.1f}% ({i}/{total})")
25
26 return "Processing complete"
27
28# Create sample data and process it
29data = list(range(10))
30result = process_data(data)
31print(result)
32"""
33 print("Starting long-running process...")
34
35 async for event in client.execute_code_stream(code):
36 if event.type == 'stdout':
37 print(event.data)
38 elif event.type == 'error':
39 print("Error:", event.data)
40 break
41 elif event.type == 'completed':
42 print("Process finished")
43 break
44
45 finally:
46 await client.cleanup()
47
48asyncio.run(long_running_process())
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
14
15try:
16 for i in range(5):
17 print(f"Processing item {i}")
18
19 if i == 2:
20 # Simulate an error
21 raise ValueError("Something went wrong!")
22
23 time.sleep(1)
24except Exception as e:
25 print(f"Error occurred: {str(e)}", file=sys.stderr)
26 raise # Re-raise the error
27"""
28 print("Starting execution with error handling...")
29
30 async for event in client.execute_code_stream(code):
31 match event.type:
32 case 'stdout':
33 print("Output:", event.data)
34 case 'stderr':
35 print("Error output:", event.data)
36 case 'error':
37 print("Execution error:", event.data)
38 # Handle the error appropriately
39 break
40 case 'completed':
41 print("Execution completed")
42 break
43
44 except Exception as e:
45 print(f"Stream processing error: {str(e)}")
46 finally:
47 await client.cleanup()
48
49asyncio.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 Break Conditions
Break the event loop on error or completed events to avoid unnecessary processing.
3. Implement Error Recovery
Handle errors gracefully and clean up resources properly when errors occur.
4. Process Events Efficiently
Handle events as they arrive and avoid blocking operations in the event loop.