from hopx_ai import Sandbox
import json
import os
from typing import Dict, List, Any
class JupyterNotebookService:
def __init__(self, api_key: str):
self.api_key = api_key
self.sandbox = None
self.cell_state = {} # Store variables between cells
def initialize_notebook(self, notebook_id: str) -> Dict[str, Any]:
"""Initialize a new notebook session"""
try:
self.sandbox = Sandbox.create(
template="code-interpreter",
api_key=self.api_key,
timeout_seconds=3600 # 1 hour session
)
# Set up data science environment
self.sandbox.env.set_all({
"JUPYTER_MODE": "true",
"PYTHONPATH": "/workspace"
})
return {
"success": True,
"notebook_id": notebook_id,
"sandbox_id": self.sandbox.sandbox_id
}
except Exception as e:
return {
"success": False,
"error": str(e)
}
def execute_cell(self, cell_code: str, cell_id: str = None) -> Dict[str, Any]:
"""Execute a notebook cell"""
try:
# Use IPython execution for notebook-like behavior
result = self.sandbox.run_ipython(cell_code)
# Capture outputs
outputs = []
if result.rich_outputs:
for output in result.rich_outputs:
outputs.append({
"type": output.type,
"data": output.data
})
# Store cell state
if cell_id:
self.cell_state[cell_id] = {
"code": cell_code,
"outputs": outputs,
"stdout": result.stdout,
"stderr": result.stderr
}
return {
"success": result.success,
"stdout": result.stdout,
"stderr": result.stderr,
"outputs": outputs,
"output_count": len(outputs),
"execution_time": result.execution_time
}
except Exception as e:
return {
"success": False,
"error": str(e),
"stderr": str(e)
}
def execute_notebook(self, notebook_json: Dict) -> Dict[str, Any]:
"""Execute entire notebook"""
cells = notebook_json.get("cells", [])
results = []
for i, cell in enumerate(cells):
if cell.get("cell_type") != "code":
continue
source = "".join(cell.get("source", []))
cell_result = self.execute_cell(source, cell_id=f"cell_{i}")
results.append({
"cell_index": i,
"result": cell_result
})
return {
"success": True,
"cells_executed": len(results),
"results": results
}
def cleanup(self):
"""Clean up notebook session"""
if self.sandbox:
self.sandbox.kill()
self.sandbox = None
# Usage
service = JupyterNotebookService(api_key=os.getenv("HOPX_API_KEY"))
service.initialize_notebook("my-notebook")
# Execute a cell
result = service.execute_cell("""
import pandas as pd
import numpy as np
df = pd.DataFrame({
'x': np.random.rand(10),
'y': np.random.rand(10)
})
df # Display dataframe
""")
print(f"Captured {result['output_count']} outputs")
print(result)
service.cleanup()