Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,8 +7,8 @@ app = FastAPI(title="Agent Sandbox API")
|
|
| 7 |
def run_code(payload: dict = Body(...)):
|
| 8 |
"""
|
| 9 |
Execute Python code in a sandboxed subprocess.
|
| 10 |
-
Input JSON: {"code": "print(2+2)"}
|
| 11 |
-
Output JSON: {"output": "4
|
| 12 |
"""
|
| 13 |
code = payload.get("code", "")
|
| 14 |
if not code:
|
|
@@ -24,9 +24,19 @@ def run_code(payload: dict = Body(...)):
|
|
| 24 |
)
|
| 25 |
|
| 26 |
if proc.returncode != 0:
|
| 27 |
-
return {"error": proc.stderr.strip()}
|
| 28 |
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
except subprocess.TimeoutExpired:
|
| 32 |
return {"error": "Execution timed out"}
|
|
|
|
| 7 |
def run_code(payload: dict = Body(...)):
|
| 8 |
"""
|
| 9 |
Execute Python code in a sandboxed subprocess.
|
| 10 |
+
Input JSON: {"code": "print(2+2)"} or {"code": "2+2"}
|
| 11 |
+
Output JSON: {"output": "4"} or {"error": "..."}
|
| 12 |
"""
|
| 13 |
code = payload.get("code", "")
|
| 14 |
if not code:
|
|
|
|
| 24 |
)
|
| 25 |
|
| 26 |
if proc.returncode != 0:
|
| 27 |
+
return {"error": proc.stderr.strip() or "Unknown error"}
|
| 28 |
|
| 29 |
+
output = proc.stdout.strip()
|
| 30 |
+
|
| 31 |
+
# If nothing printed, try evaluating expression directly
|
| 32 |
+
if not output:
|
| 33 |
+
try:
|
| 34 |
+
result = eval(code, {})
|
| 35 |
+
output = str(result)
|
| 36 |
+
except Exception:
|
| 37 |
+
output = "<no output>"
|
| 38 |
+
|
| 39 |
+
return {"output": output}
|
| 40 |
|
| 41 |
except subprocess.TimeoutExpired:
|
| 42 |
return {"error": "Execution timed out"}
|