The code-interpreter template includes Python 3.11 with data science libraries (NumPy, Pandas, Matplotlib) pre-installed.
No need to pass api_key explicitly - the SDK automatically reads from HOPX_API_KEY environment variable!
Run Your First Code
Execute code and see the results:
Copy
# ...# Run Python code in the sandboxresult = sandbox.run_code('print("The question of whether computers can think is like the question of whether submarines can swim. - Edsger Dijkstra")')# Check if execution succeededif result.success: print("✅ Code executed successfully!") print("\nOutput:") print(result.stdout)else: print("❌ Error:", result.stderr)
Expected Output:
Copy
✅ Code executed successfully!Output:The question of whether computers can think is like the question of whether submarines can swim. - Edsger Dijkstra
Success! You just ran code in a secure, isolated environment 🎉
Cleanup
Always clean up your sandbox when done to avoid unnecessary charges:
from hopx_ai import Sandbox, HopxErrortry: sandbox = Sandbox.create(template="code-interpreter") # This will fail (division by zero) result = sandbox.run_code("print(1/0)") if not result.success: print(f"❌ Code failed: {result.stderr}") print(f"Exit code: {result.exit_code}")except HopxError as e: print(f"❌ Sandbox error: {e.message}") print(f"Request ID: {e.request_id}")finally: sandbox.kill()
Streaming Output
Stream output in real-time for long-running operations:
Copy
import asyncioasync def stream_execution(): sandbox = Sandbox.create(template="code-interpreter") code = """import timefor i in range(5): print(f"Step {i+1}/5") time.sleep(1)print("Done!")""" # Stream output line by line async for message in sandbox.run_code_stream(code): if message['type'] == 'stdout': print(message['data'], end='') elif message['type'] == 'stderr': print(f"[stderr] {message['data']}", end='') elif message['type'] == 'result': print(f"\n✅ Exit code: {message['exit_code']}") elif message['type'] == 'complete': if message['success']: print("\n✅ Execution completed successfully") else: print("\n❌ Execution failed") sandbox.kill()# Run the async functionasyncio.run(stream_execution())