Stateful Agentic Graph Tutorial: Construct an autonomous code generator agent that compiles Python snippets, captures execution errors, and reflects to self-correct code bug loops.
Step 1: Define Agent Execution Graph State
from pydantic import BaseModel, Field
from typing import List, Optional
class CodeAgentState(BaseModel):
user_prompt: str
generated_code: Optional[str] = None
compiler_error: Optional[str] = None
retry_count: int = 0
max_retries: int = 3
is_success: bool = False
Step 2: Write Code Execution & Sandbox Verification Node
import subprocess, sys
def execute_code_node(state: CodeAgentState) -> CodeAgentState:
try:
res = subprocess.run([sys.executable, "-c", state.generated_code], capture_output=True, text=True, timeout=5)
if res.returncode == 0:
state.is_success = True
else:
state.compiler_error = res.stderr
state.retry_count += 1
except Exception as err:
state.compiler_error = str(err)
state.retry_count += 1
return state
COMMENTS (0)
Join the discussion on AI engineering and technical research.