Add HF Spaces deployment files: app.py, Dockerfile, .dockerignore; add subprocess fallback for executor
Browse files- .dockerignore +8 -0
- Dockerfile +15 -0
- app.py +86 -0
- src/config.py +1 -1
- src/sandbox/executor.py +84 -29
.dockerignore
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.env
|
| 2 |
+
.venv
|
| 3 |
+
.git
|
| 4 |
+
__pycache__
|
| 5 |
+
*.pyc
|
| 6 |
+
.DS_Store
|
| 7 |
+
.gitignore
|
| 8 |
+
uv.lock
|
Dockerfile
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.12-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
COPY requirements.txt .
|
| 6 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 7 |
+
|
| 8 |
+
COPY . .
|
| 9 |
+
|
| 10 |
+
EXPOSE 7860
|
| 11 |
+
|
| 12 |
+
ENV STREAMLIT_SERVER_PORT=7860
|
| 13 |
+
ENV STREAMLIT_SERVER_ADDRESS=0.0.0.0
|
| 14 |
+
|
| 15 |
+
CMD ["streamlit", "run", "app.py", "--server.port=7860", "--server.address=0.0.0.0"]
|
app.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from src.main import run_sandbox
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
st.set_page_config(
|
| 6 |
+
page_title="Agentic Coding Sandbox",
|
| 7 |
+
page_icon=":zap:",
|
| 8 |
+
layout="wide",
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
st.title("Self-Correcting Agentic Coding Sandbox")
|
| 12 |
+
st.markdown(
|
| 13 |
+
"Submit a coding task. The system generates, executes, and autonomously debugs "
|
| 14 |
+
"Python code in an isolated sandbox environment."
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
with st.sidebar:
|
| 18 |
+
st.header("About")
|
| 19 |
+
st.markdown(
|
| 20 |
+
"""
|
| 21 |
+
**Architecture:**
|
| 22 |
+
1. **Coder Agent** - generates Python code via LLM
|
| 23 |
+
2. **Sandbox Executor** - runs code in isolated environment
|
| 24 |
+
3. **Critic Agent** - analyzes errors and suggests fixes
|
| 25 |
+
4. **Retry Loop** - up to 3 self-healing attempts
|
| 26 |
+
"""
|
| 27 |
+
)
|
| 28 |
+
st.caption("Running on Hugging Face Spaces")
|
| 29 |
+
|
| 30 |
+
col1, col2 = st.columns([3, 2])
|
| 31 |
+
|
| 32 |
+
with col1:
|
| 33 |
+
prompt = st.text_area(
|
| 34 |
+
"Describe what you want the code to do:",
|
| 35 |
+
height=150,
|
| 36 |
+
placeholder="e.g., Plot a bar chart of the top 5 most frequent words in this text.",
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
if st.button("Run", type="primary", disabled=not prompt):
|
| 40 |
+
with st.spinner("Generating code..."):
|
| 41 |
+
try:
|
| 42 |
+
result = run_sandbox(prompt)
|
| 43 |
+
st.session_state["result"] = result
|
| 44 |
+
except Exception as e:
|
| 45 |
+
st.error(f"Error: {e}")
|
| 46 |
+
|
| 47 |
+
with col2:
|
| 48 |
+
st.subheader("Result")
|
| 49 |
+
|
| 50 |
+
if "result" in st.session_state:
|
| 51 |
+
result = st.session_state["result"]
|
| 52 |
+
retries = result.get("retries_used", 0)
|
| 53 |
+
|
| 54 |
+
if result.get("success"):
|
| 55 |
+
st.success(f"Succeeded ({retries} retries)")
|
| 56 |
+
else:
|
| 57 |
+
st.error(f"Failed ({retries} retries)")
|
| 58 |
+
|
| 59 |
+
files = result.get("files", {})
|
| 60 |
+
if files:
|
| 61 |
+
for name, b64 in files.items():
|
| 62 |
+
st.image(f"data:image/png;base64,{b64}", caption=name, use_container_width=True)
|
| 63 |
+
|
| 64 |
+
output = result.get("output") or result.get("error") or "No output"
|
| 65 |
+
if output.strip():
|
| 66 |
+
st.code(output, language="text", line_numbers=True)
|
| 67 |
+
else:
|
| 68 |
+
st.info("Submit a prompt to see results here.")
|
| 69 |
+
|
| 70 |
+
st.divider()
|
| 71 |
+
|
| 72 |
+
st.subheader("Execution Trace")
|
| 73 |
+
|
| 74 |
+
if "result" in st.session_state:
|
| 75 |
+
trace = st.session_state["result"].get("trace", [])
|
| 76 |
+
if trace:
|
| 77 |
+
for i, entry in enumerate(trace):
|
| 78 |
+
node = entry.get("node", "?")
|
| 79 |
+
retry = entry.get("retry", 0)
|
| 80 |
+
|
| 81 |
+
with st.expander(f"Attempt {retry + 1} - {node}", expanded=True):
|
| 82 |
+
st.json(entry)
|
| 83 |
+
else:
|
| 84 |
+
st.caption("No trace data available.")
|
| 85 |
+
else:
|
| 86 |
+
st.caption("Run a prompt to see the execution trace.")
|
src/config.py
CHANGED
|
@@ -3,7 +3,7 @@ from dotenv import load_dotenv
|
|
| 3 |
|
| 4 |
load_dotenv()
|
| 5 |
|
| 6 |
-
API_KEY = os.
|
| 7 |
BASE_URL = os.getenv("LLM_BASE_URL", "https://opencode.ai/zen/v1")
|
| 8 |
MODEL = os.getenv("LLM_MODEL", "deepseek-v4-flash-free")
|
| 9 |
MAX_RETRIES = int(os.getenv("MAX_RETRIES", "3"))
|
|
|
|
| 3 |
|
| 4 |
load_dotenv()
|
| 5 |
|
| 6 |
+
API_KEY = os.getenv("OPENCODE_ZEN_API_KEY", "")
|
| 7 |
BASE_URL = os.getenv("LLM_BASE_URL", "https://opencode.ai/zen/v1")
|
| 8 |
MODEL = os.getenv("LLM_MODEL", "deepseek-v4-flash-free")
|
| 9 |
MAX_RETRIES = int(os.getenv("MAX_RETRIES", "3"))
|
src/sandbox/executor.py
CHANGED
|
@@ -1,41 +1,42 @@
|
|
| 1 |
import io
|
| 2 |
import os
|
| 3 |
-
import base64
|
| 4 |
import re
|
| 5 |
-
import
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
| 8 |
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
DOCKER_SOCKET = "unix:///Users/zaid/.colima/default/docker.sock"
|
| 11 |
|
| 12 |
_IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp"}
|
| 13 |
-
_client: docker.DockerClient | None = None
|
| 14 |
|
| 15 |
|
| 16 |
-
def
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
|
| 23 |
-
def
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
f"exec(base64.b64decode('{b64_script}').decode())\n"
|
| 28 |
-
"for f in os.listdir('/tmp'):\n"
|
| 29 |
-
" ext = os.path.splitext(f)[1].lower()\n"
|
| 30 |
-
f" if ext in {list(_IMAGE_EXTENSIONS)}:\n"
|
| 31 |
-
" with open(os.path.join('/tmp', f), 'rb') as imgf:\n"
|
| 32 |
-
" b = base64.b64encode(imgf.read()).decode()\n"
|
| 33 |
-
" print(f'__SANDBOX_FILE__{f}__{b}__SANDBOX_ENDFILE__')\n"
|
| 34 |
-
)
|
| 35 |
|
| 36 |
|
| 37 |
-
def
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
| 39 |
container = None
|
| 40 |
try:
|
| 41 |
if requirements:
|
|
@@ -81,10 +82,6 @@ def execute_code(script: str, requirements: list[str] | None = None) -> SandboxR
|
|
| 81 |
success=result.get("StatusCode", 1) == 0,
|
| 82 |
files=files,
|
| 83 |
)
|
| 84 |
-
except docker.errors.APIError as e:
|
| 85 |
-
return SandboxResult(
|
| 86 |
-
stdout="", stderr=str(e), exit_code=-1, success=False
|
| 87 |
-
)
|
| 88 |
except Exception as e:
|
| 89 |
return SandboxResult(
|
| 90 |
stdout="", stderr=str(e), exit_code=-1, success=False
|
|
@@ -97,6 +94,64 @@ def execute_code(script: str, requirements: list[str] | None = None) -> SandboxR
|
|
| 97 |
pass
|
| 98 |
|
| 99 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
def _parse_file_blocks(text: str) -> tuple[str, dict[str, str]]:
|
| 101 |
files = {}
|
| 102 |
pattern = r"__SANDBOX_FILE__(.+?)__(.{10,}?)__SANDBOX_ENDFILE__"
|
|
|
|
| 1 |
import io
|
| 2 |
import os
|
|
|
|
| 3 |
import re
|
| 4 |
+
import base64
|
| 5 |
+
import subprocess
|
| 6 |
+
import sys
|
| 7 |
+
import tempfile
|
| 8 |
+
import textwrap
|
| 9 |
+
from pathlib import Path
|
| 10 |
|
| 11 |
+
from src.models import SandboxResult
|
| 12 |
+
from src.config import SANDBOX_TIMEOUT
|
| 13 |
|
|
|
|
| 14 |
|
| 15 |
_IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp"}
|
|
|
|
| 16 |
|
| 17 |
|
| 18 |
+
def _docker_available() -> bool:
|
| 19 |
+
try:
|
| 20 |
+
import docker
|
| 21 |
+
client = docker.from_env()
|
| 22 |
+
client.ping()
|
| 23 |
+
client.close()
|
| 24 |
+
return True
|
| 25 |
+
except Exception:
|
| 26 |
+
return False
|
| 27 |
|
| 28 |
|
| 29 |
+
def execute_code(script: str, requirements: list[str] | None = None) -> SandboxResult:
|
| 30 |
+
if _docker_available():
|
| 31 |
+
return _execute_docker(script, requirements)
|
| 32 |
+
return _execute_local(script, requirements)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
|
| 35 |
+
def _execute_docker(script: str, requirements: list[str] | None = None) -> SandboxResult:
|
| 36 |
+
import docker
|
| 37 |
+
from src.config import SANDBOX_IMAGE
|
| 38 |
+
|
| 39 |
+
client = docker.from_env()
|
| 40 |
container = None
|
| 41 |
try:
|
| 42 |
if requirements:
|
|
|
|
| 82 |
success=result.get("StatusCode", 1) == 0,
|
| 83 |
files=files,
|
| 84 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
except Exception as e:
|
| 86 |
return SandboxResult(
|
| 87 |
stdout="", stderr=str(e), exit_code=-1, success=False
|
|
|
|
| 94 |
pass
|
| 95 |
|
| 96 |
|
| 97 |
+
def _execute_local(script: str, requirements: list[str] | None = None) -> SandboxResult:
|
| 98 |
+
tmp_dir = Path(tempfile.mkdtemp())
|
| 99 |
+
script_path = tmp_dir / "_script.py"
|
| 100 |
+
script_path.write_text(script, encoding="utf-8")
|
| 101 |
+
|
| 102 |
+
try:
|
| 103 |
+
if requirements:
|
| 104 |
+
subprocess.run(
|
| 105 |
+
[sys.executable, "-m", "pip", "install", "--quiet"] + requirements,
|
| 106 |
+
capture_output=True,
|
| 107 |
+
timeout=60,
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
proc = subprocess.run(
|
| 111 |
+
[sys.executable, str(script_path)],
|
| 112 |
+
capture_output=True,
|
| 113 |
+
text=True,
|
| 114 |
+
timeout=SANDBOX_TIMEOUT,
|
| 115 |
+
cwd=str(tmp_dir),
|
| 116 |
+
env={**os.environ, "MPLCONFIGDIR": str(tmp_dir)},
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
clean_stdout, files = _parse_file_blocks(proc.stdout or "")
|
| 120 |
+
|
| 121 |
+
return SandboxResult(
|
| 122 |
+
stdout=clean_stdout or "",
|
| 123 |
+
stderr=proc.stderr or "",
|
| 124 |
+
exit_code=proc.returncode,
|
| 125 |
+
success=proc.returncode == 0,
|
| 126 |
+
files=files,
|
| 127 |
+
)
|
| 128 |
+
except subprocess.TimeoutExpired:
|
| 129 |
+
return SandboxResult(
|
| 130 |
+
stdout="", stderr="Execution timed out", exit_code=-1, success=False
|
| 131 |
+
)
|
| 132 |
+
except Exception as e:
|
| 133 |
+
return SandboxResult(
|
| 134 |
+
stdout="", stderr=str(e), exit_code=-1, success=False
|
| 135 |
+
)
|
| 136 |
+
finally:
|
| 137 |
+
import shutil
|
| 138 |
+
shutil.rmtree(tmp_dir, ignore_errors=True)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def _wrap_script(script: str) -> str:
|
| 142 |
+
b64_script = base64.b64encode(script.encode("utf-8")).decode("ascii")
|
| 143 |
+
return (
|
| 144 |
+
"import base64, os\n"
|
| 145 |
+
f"exec(base64.b64decode('{b64_script}').decode())\n"
|
| 146 |
+
"for f in os.listdir('/tmp'):\n"
|
| 147 |
+
" ext = os.path.splitext(f)[1].lower()\n"
|
| 148 |
+
f" if ext in {list(_IMAGE_EXTENSIONS)}:\n"
|
| 149 |
+
" with open(os.path.join('/tmp', f), 'rb') as imgf:\n"
|
| 150 |
+
" b = base64.b64encode(imgf.read()).decode()\n"
|
| 151 |
+
" print(f'__SANDBOX_FILE__{f}__{b}__SANDBOX_ENDFILE__')\n"
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
def _parse_file_blocks(text: str) -> tuple[str, dict[str, str]]:
|
| 156 |
files = {}
|
| 157 |
pattern = r"__SANDBOX_FILE__(.+?)__(.{10,}?)__SANDBOX_ENDFILE__"
|