| import modal |
|
|
|
|
| app = modal.App("split-brain-sandbox") |
|
|
|
|
| @app.function(timeout=20) |
| def execute_python(code: str) -> dict: |
| """Run code in a Modal sandbox and return stdout/stderr.""" |
| sandbox = modal.Sandbox.create( |
| "python3", |
| "-c", |
| code, |
| image=modal.Image.debian_slim().pip_install("numpy"), |
| timeout=10, |
| cpu=0.5, |
| ) |
| sandbox.wait() |
| return { |
| "stdout": sandbox.stdout.read(), |
| "stderr": sandbox.stderr.read(), |
| "returncode": sandbox.returncode, |
| } |
|
|
|
|
| @app.function( |
| image=modal.Image.debian_slim().pip_install("fastapi", "pydantic"), |
| scaledown_window=30, |
| ) |
| @modal.asgi_app() |
| def sandbox_endpoint(): |
| from fastapi import FastAPI |
| from fastapi.middleware.cors import CORSMiddleware |
| from pydantic import BaseModel |
|
|
| web_app = FastAPI() |
| web_app.add_middleware( |
| CORSMiddleware, |
| allow_origins=["*"], |
| allow_methods=["*"], |
| allow_headers=["*"], |
| ) |
|
|
| class ExecuteRequest(BaseModel): |
| code: str |
|
|
| @web_app.post("/execute") |
| async def execute(req: ExecuteRequest): |
| return await execute_python.remote.aio(req.code) |
|
|
| @web_app.get("/health") |
| async def health(): |
| return {"ok": True} |
|
|
| return web_app |
|
|