File size: 1,274 Bytes
053ee0d
 
 
 
 
 
cd451e7
053ee0d
 
 
 
 
 
 
f1440ce
053ee0d
 
 
 
 
 
 
 
 
 
cd451e7
 
 
 
053ee0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1440ce
053ee0d
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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