agent-sandbox / app.py
mimipynb's picture
Update app.py
64c0edc verified
raw
history blame
913 Bytes
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)}