File size: 913 Bytes
afd7056
64c0edc
afd7056
64c0edc
afd7056
 
 
64c0edc
 
 
 
 
afd7056
64c0edc
 
 
afd7056
64c0edc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
afd7056
 
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
from fastapi import FastAPI, Body
import subprocess

app = FastAPI(title="Agent Sandbox API")

@app.post("/run")
def run_code(payload: dict = Body(...)):
    """
    Execute Python code in a sandboxed subprocess.
    Input JSON: {"code": "print(2+2)"}
    Output JSON: {"output": "4\n"} or {"error": "..."}
    """
    code = payload.get("code", "")
    if not code:
        return {"error": "No code provided"}

    try:
        # Run the code in a subprocess with a 5s timeout
        proc = subprocess.run(
            ["python3", "-c", code],
            capture_output=True,
            text=True,
            timeout=5
        )

        if proc.returncode != 0:
            return {"error": proc.stderr.strip()}

        return {"output": proc.stdout.strip()}

    except subprocess.TimeoutExpired:
        return {"error": "Execution timed out"}
    except Exception as e:
        return {"error": str(e)}