Code execution

Code execution lets your agent generate and run Python code dynamically. But this is risky, so you need AST-based validation to block dangerous patterns (subprocess, exec, file access), subprocess isolation for sandboxing, and timeouts to prevent infinite loops.

RAG query processing pipeline

How queries get rewritten, checked for relevancy, and used to generate answers

Safe code execution pipeline

Only with proper safeguards. AST validation blocks dangerous patterns before execution, subprocess sandboxing isolates the runtime, and timeouts prevent infinite loops. Without all three layers, it is not production-ready.

patterns/28_code_execution.py
python
class CodeExecutor:
    DANGEROUS_PATTERNS = [
        "subprocess", "os.system", "exec(", "eval(",
        "open(", "__import__", "shutil"
    ]

    def validate_code(self, code):
        """Check syntax and block dangerous patterns."""
        try:
            ast.parse(code)  # Syntax check
        except SyntaxError as e:
            return False, f"Syntax error: {e}"

        for pattern in self.DANGEROUS_PATTERNS:
            if pattern in code:
                return False, f"Blocked: {pattern}"
        return True, "Safe"

    def execute_python_code(self, code, timeout=10):
        """Run code in isolated subprocess with timeout."""
        is_valid, msg = self.validate_code(code)
        if not is_valid:
            return {"success": False, "error": msg}

        result = subprocess.run(
            ["python", "-c", code],
            capture_output=True, text=True, timeout=timeout
        )
        return {
            "success": result.returncode == 0,
            "stdout": result.stdout,
            "stderr": result.stderr,
        }

CodeExecutor with AST validation and subprocess sandboxing.

That is why sandboxing is critical. In production, you run generated code in an isolated environment like Docker containers or services like E2B. Never run LLM-generated code with access to your filesystem or network without strict sandboxing.

Quiz: Quiz

Loading practice…

Ordering exercise: Order the safe code execution steps

Loading practice…

Flashcards: Flashcards

Loading practice…

You now know how to safely execute LLM-generated code with validation and sandboxing. Next, we improve RAG accuracy by rewriting user queries before retrieval.