zenex-ai-project / agent /tools /executor.py
shashankmacherla's picture
Upload full llm_project
6d5c79f verified
Raw History Blame Contribute Delete
5.98 kB
"""Code execution tool — wraps the existing DockerSandbox for agent use.
The agent uses this to:
- Run generated code and read actual output (not predicted output)
- Fix bugs through real execution feedback
- Validate implementations before declaring tasks done
Design reference:
- GPT Codex: tight write→execute→observe→fix loop
"""
from __future__ import annotations
import logging
import os
import subprocess
import tempfile
import time
from pathlib import Path
from typing import Any
from agent.tools.base import BaseTool
LOGGER = logging.getLogger(__name__)
SUPPORTED_LANGUAGES = {"python", "javascript", "typescript", "bash", "go", "rust", "java"}
class CodeExecutorTool(BaseTool):
"""Execute arbitrary code in an isolated sandbox.
Tries Docker sandbox first (full isolation), falls back to local
subprocess for Python/Bash in dev mode.
"""
name = "executor"
description = "Execute code in any language and return actual stdout/stderr."
def __init__(self, use_docker: bool = True, timeout: int = 60) -> None:
self._use_docker = use_docker
self._timeout = timeout
self._mode = os.environ.get("ZENEX_EXECUTOR_MODE", "development").lower()
self._allow_local_fallback = os.environ.get("ZENEX_ALLOW_LOCAL_EXEC", "1") == "1"
self._sandbox = self._init_sandbox()
def _init_sandbox(self):
if not self._use_docker:
return None
try:
from finetuning.docker_sandbox import DockerSandbox
return DockerSandbox(timeout_seconds=self._timeout)
except Exception as exc:
LOGGER.warning("DockerSandbox unavailable: %s. Will use local subprocess fallback.", exc)
return None
def run(self, args: dict[str, Any]) -> dict[str, Any]:
code = args.get("code", "")
language = args.get("language", "python").lower()
file_path = args.get("file_path") # run an existing file instead of inline code
should_cancel = args.get("_should_cancel")
if file_path:
try:
code = Path(file_path).read_text(encoding="utf-8")
except Exception as exc:
return self._fail(f"Cannot read file {file_path}: {exc}")
if not code.strip():
return self._fail("No code provided to execute.")
if language not in SUPPORTED_LANGUAGES:
return self._fail(f"Unsupported language: {language}. Supported: {SUPPORTED_LANGUAGES}")
if self._mode == "production" and not self._sandbox:
return self._fail("Execution blocked: production mode requires Docker sandbox.")
# Try Docker first
if self._sandbox:
try:
if callable(should_cancel) and should_cancel():
return self._fail("Execution cancelled before start.")
result = self._sandbox.execute(language, code)
return {
"success": result.exit_code == 0,
"stdout": result.stdout,
"stderr": result.stderr,
"exit_code": result.exit_code,
"elapsed": result.elapsed_seconds,
"error": result.stderr if result.exit_code != 0 else "",
}
except Exception as exc:
LOGGER.warning("Docker execution failed: %s. Falling back to local.", exc)
# Local subprocess fallback (Python/Bash only)
if not self._allow_local_fallback:
return self._fail("Local execution fallback disabled by policy (ZENEX_ALLOW_LOCAL_EXEC=0).")
return self._local_run(code, language, should_cancel=should_cancel)
def _local_run(self, code: str, language: str, should_cancel=None) -> dict:
if language not in ("python", "bash"):
return self._fail(f"Local fallback only supports python/bash, not {language}.")
with tempfile.NamedTemporaryFile(
mode="w",
suffix=".py" if language == "python" else ".sh",
delete=False,
encoding="utf-8",
) as f:
f.write(code)
tmp_path = f.name
cmd = ["python3", tmp_path] if language == "python" else ["bash", tmp_path]
start = time.time()
try:
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
while proc.poll() is None:
if callable(should_cancel) and should_cancel():
proc.kill()
stdout, stderr = proc.communicate(timeout=2)
return {
"success": False,
"stdout": stdout,
"stderr": stderr,
"exit_code": 130,
"elapsed": time.time() - start,
"error": "Execution cancelled.",
}
if time.time() - start > self._timeout:
proc.kill()
stdout, stderr = proc.communicate(timeout=2)
return {
"success": False,
"stdout": stdout,
"stderr": stderr,
"exit_code": 124,
"elapsed": self._timeout,
"error": f"Execution timed out after {self._timeout}s.",
}
time.sleep(0.1)
stdout, stderr = proc.communicate(timeout=2)
return {
"success": proc.returncode == 0,
"stdout": stdout,
"stderr": stderr,
"exit_code": proc.returncode,
"elapsed": time.time() - start,
"error": stderr if proc.returncode != 0 else "",
}
except Exception as exc:
return self._fail(str(exc))
finally:
Path(tmp_path).unlink(missing_ok=True)