mimipynb commited on
Commit
64c0edc
·
verified ·
1 Parent(s): 379d223

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -4
app.py CHANGED
@@ -1,13 +1,34 @@
1
- # agent_server.py
2
  from fastapi import FastAPI, Body
 
3
 
4
- app = FastAPI()
5
 
6
  @app.post("/run")
7
  def run_code(payload: dict = Body(...)):
 
 
 
 
 
8
  code = payload.get("code", "")
 
 
 
9
  try:
10
- result = eval(code)
11
- return {"output": result}
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  except Exception as e:
13
  return {"error": str(e)}
 
 
1
  from fastapi import FastAPI, Body
2
+ import subprocess
3
 
4
+ app = FastAPI(title="Agent Sandbox API")
5
 
6
  @app.post("/run")
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\n"} or {"error": "..."}
12
+ """
13
  code = payload.get("code", "")
14
+ if not code:
15
+ return {"error": "No code provided"}
16
+
17
  try:
18
+ # Run the code in a subprocess with a 5s timeout
19
+ proc = subprocess.run(
20
+ ["python3", "-c", code],
21
+ capture_output=True,
22
+ text=True,
23
+ timeout=5
24
+ )
25
+
26
+ if proc.returncode != 0:
27
+ return {"error": proc.stderr.strip()}
28
+
29
+ return {"output": proc.stdout.strip()}
30
+
31
+ except subprocess.TimeoutExpired:
32
+ return {"error": "Execution timed out"}
33
  except Exception as e:
34
  return {"error": str(e)}