Your LLM agent has generated a brilliant, multi-step natural-language plan to refactor your monolith, scrape a competitor's pricing page, or provision a staging cluster. It reads like poetry: “First, check the database schema, then write the migration script, then run the unit tests, and if they fail, roll back.”
Then you try to execute it.
The moment you hand that plan to a traditional script, everything falls apart. The model hallucinated a step name, swapped an argument order, or looped back onto a resource that no longer exists. A string of text is not an API payload. An LLM's prose is probabilistic, fluid, and notoriously creative; infrastructure is deterministic, rigid, and deeply unforgiving of creativity.
If you are building production-grade agentic systems in 2026, you cannot simply pass raw text between tool calls and hope for the best. You need to compile that natural-language intent into a Validated Execution Graph (VEG)—a directed, acyclic or cyclic graph of typed nodes, atomic operations, and explicit runtime contracts that can be verified before a single production database record is touched or an external API is billed.
Let’s look at how to build a robust pipeline that takes an AI agent’s natural-language stream of consciousness, parses it into an explicit graph structure, validates its semantic and structural integrity, and executes it safely.
📋 Table of Contents
- The Structural Disconnect: Text vs. Topologies
- Step 1: Constraining the Output with Structured Generation and Pydantic
- Step 2: Defining the Graph Schema and Node Types
- Step 3: Building the AST Compiler for Natural-Language Plans
- Step 4: Implementing Topological and Semantic Validation Passes
- Step 5: Handling Cyclic Dependencies and Agentic Loops Safely
- Step 6: Executing the Graph with Concurrency and Checkpointing
- Architectural Trade-Offs and Production Realities
The Structural Disconnect: Text vs. Topologies
Scenario: You ask an agent to audit an AWS account and delete idle resources. It returns a paragraph outlining twelve steps, interspersing descriptive commentary with imperative commands. Your naive parser splits the text by newlines and hands each string to a bash executor. Step four says "Review the logs, or delete the S3 bucket if empty." The parser executes both, ignoring the conditional nature of the prose, and wipes a production bucket because an intermediate variable was undefined.
Why it matters: Natural language is inherently ambiguous, context-dependent, and non-deterministic. Execution engines require absolute clarity: explicit inputs, explicit outputs, deterministic ordering, and defined error-handling policies. Treating an LLM prompt output as an executable script is a production outage waiting to happen.
Solution: Treat the LLM not as an executor, but as a compiler front-end. Just as Clang takes C source code and lowers it into an Abstract Syntax Tree (AST), your agentic framework must take natural language and lower it into a strongly typed execution graph.
+--------------------------+ Structured JSON +------------------------+
| LLM Natural-Language | ---------------------> | Pydantic Schema |
| Plan Generation | | (Nodes & Edges) |
+--------------------------+ +------------------------+
|
v
+------------------------+
| Validated Execution |
| Graph (VEG Engine) |
+------------------------+
Step 1: Constraining the Output with Structured Generation and Pydantic
Scenario:
You prompt GPT-4o or Claude 3.5 Sonnet to output JSON representing a plan. Half the time, it wraps the JSON in markdown code blocks (```json), or includes conversational filler like "Here is your plan!" at the top, crashing your JSON parser.
Why it matters: Standard prompt engineering relying on "please output valid JSON" fails under production load, especially when context windows fill up or smaller models are swapped in for latency reduction.
Solution: Enforce strict schema adherence using native tool/function calling or constrained decoding libraries (such as Instructor, Outlines, or native provider JSON modes) tied directly to a Pydantic model.
from typing import List, Literal, Dict, Any, Optional
from pydantic import BaseModel, Field, field_validator
class PlanNode(BaseModel):
id: str = Field(..., description="Unique snake_case identifier for this step")
tool_name: Literal["sql_query", "http_request", "s3_manager", "code_interpreter"]
description: str = Field(..., description="Human-readable summary of what this step does")
arguments: Dict[str, Any] = Field(default_factory=dict, description="Typed arguments required by the tool")
dependencies: List[str] = Field(default_factory=list, description="IDs of nodes that must execute successfully before this node")
@field_validator('id')
@classmethod
def validate_snake_case(cls, v: str) -> str:
if not v.isidentifier() or not v.islower():
raise ValueError("Node ID must be valid lowercase snake_case identifier")
return v
class ExecutionPlan(BaseModel):
goal: str
nodes: List[PlanNode]
@field_validator('nodes')
@classmethod
def validate_dag_references(cls, nodes: List[PlanNode]) -> List[PlanNode]:
node_ids = {node.id for node in nodes}
for node in nodes:
for dep in node.dependencies:
if dep not in node_ids:
raise ValueError(f"Node '{node.id}' depends on non-existent node ID '{dep}'")
return nodes
Why this works: By leveraging Pydantic's validators alongside structured generation APIs, you catch dangling node references, invalid identifiers, and schema mismatches before the graph is instantiated. The LLM is forced to conform to a strict contract.
💡 Practical note: Even with constrained decoding, LLMs occasionally invent argument names that do not match your tool definitions. Always layer a tool-signature verification pass directly after Pydantic validation.
Step 2: Defining the Graph Schema and Node Types
Scenario: Your plan contains nodes that perform completely different actions—some query a database, some send Slack alerts, and others execute Python code in an isolated sandbox. If your execution engine treats every node as a generic function taking a string, you lose type safety and error granularity.
Why it matters: A failure in a Slack alert shouldn't trigger the same retry-and-rollback policy as a failure in a financial ledger database write. Your graph schema must encode operational semantics, timeouts, retry policies, and compensation logic directly into the nodes.
Solution: Design a rich graph representation using a dedicated graph library (such as NetworkX in Python or graphology in JavaScript) where nodes encapsulate not just data, but execution metadata.
import networkx as nx
from enum import Enum
class FailurePolicy(Enum):
FAIL_FAST = "fail_fast"
IGNORE = "ignore"
RETRY = "retry"
class ExecutableNode:
def __init__(self, plan_node: PlanNode):
self.id = plan_node.id
self.tool_name = plan_node.tool_name
self.description = plan_node.description
self.arguments = plan_node.arguments
self.failure_policy = FailurePolicy.FAIL_FAST
self.max_retries = 3
self.timeout_seconds = 30
self.status = "PENDING"
self.output: Optional[Any] = None
self.error: Optional[str] = None
def build_graph_from_plan(plan: ExecutionPlan) -> nx.DiGraph:
G = nx.DiGraph()
# Add all nodes first
for plan_node in plan.nodes:
exec_node = ExecutableNode(plan_node)
G.add_node(exec_node.id, data=exec_node)
# Add edges based on dependencies
# If Node B depends on Node A, edge goes A -> B (A must run before B)
for plan_node in plan.nodes:
for dep in plan_node.dependencies:
G.add_edge(dep, plan_node.id)
return G
Why this works:
NetworkX provides robust mathematical underpinnings for graph analysis. By reversing the dependency array into directed edges (dep -> node.id), we create a topological layout where incoming edges represent prerequisites.
Step 3: Building the AST Compiler for Natural-Language Plans
Scenario: The LLM generates a plan where Node B depends on Node A, and Node C depends on Node B. However, the model inadvertently outputs the nodes in reverse order in the JSON array, or omits intermediate data-passing bindings.
Why it matters: An execution graph isn't just about when tasks run (control flow), but what data flows between them (data flow). If Node B requires the output of Node A as an argument, but the plan doesn't specify how to map Node A's result into Node B's input, the graph will execute in the right order but fail due to missing variables.
Solution:
Implement a compiler pass that scans the graph and performs variable reference resolution. Allow natural language placeholders like {{step_1.output}} in node arguments and bind them to actual graph state references.
import re
def resolve_data_bindings(G: nx.DiGraph) -> None:
# Regex to find references like {{node_id.output.property}}
pattern = re.compile(r"\{\{([a-zA-Z0-9_]+)\.output(?:\.([a-zA-Z0-9_.]+))?\}\}")
for node_id in G.nodes():
node_data: ExecutableNode = G.nodes[node_id]['data']
# Scan arguments dictionary recursively for template strings
for arg_key, arg_val in node_data.arguments.items():
if isinstance(arg_val, str):
matches = pattern.findall(arg_val)
if matches:
# Validate that referenced nodes actually exist as ancestors
for ref_node_id, prop_path in matches:
if not nx.has_path(G, ref_node_id, node_id):
raise ValueError(
f"Data dependency error: Node '{node_id}' references "
f"'{ref_node_id}', but there is no execution path from '{ref_node_id}' to '{node_id}'."
)
Why this works: This compiler pass bridges the gap between control flow dependencies (Node A runs before Node B) and data flow dependencies (Node B uses data from Node A). If an LLM tries to use data from a node it didn't mark as a dependency, the compiler catches it instantly.
Step 4: Implementing Topological and Semantic Validation Passes
Scenario: An agent generates a complex plan with twenty steps. In its attempt to be thorough, it creates a circular dependency: Step 3 depends on Step 10, and Step 10 depends on Step 3.
Why it matters: If you run a naive runner on a graph containing cycles without explicit loop control, your application will hang indefinitely or crash with a recursion depth error.
Solution: Run a strict validation suite before execution. This suite must check for cycles, disconnected subgraphs, unreachable nodes, and resource contention.
def validate_execution_graph(G: nx.DiGraph) -> None:
# 1. Check for cycles (must be a Directed Acyclic Graph unless explicitly allowed)
if not nx.is_directed_acyclic_graph(G):
try:
cycle = nx.find_cycle(G, orientation="original")
raise ValueError(f"Cyclic dependency detected in execution graph: {cycle}")
except nx.NetworkXNoCycle:
raise ValueError("Cyclic dependency detected, but cycle could not be traced.")
# 2. Check for dead ends / unreachability if there are multiple roots
# Find nodes with in-degree 0 (entry points)
entry_points = [n for n, d in G.in_degree() if d == 0]
if not entry_points:
raise ValueError("Graph has no valid entry points (all nodes have dependencies).")
# 3. Verify graph connectivity (warn or fail on isolated components)
if not nx.is_weakly_connected(G):
raise ValueError("Execution graph contains disconnected subgraphs. All tasks must be part of the primary plan.")
Why this works:
NetworkX's nx.is_directed_acyclic_graph(G) executes in linear time relative to the number of nodes and edges ($O(V + E)$). Catching cycles here prevents infinite execution loops before wasting compute or API tokens on invalid runtime paths.
Step 5: Handling Cyclic Dependencies and Agentic Loops Safely
Scenario: Your agent is writing code, running tests, and fixing bugs iteratively. This is inherently cyclic: Write Code -> Run Tests -> (If Fail) -> Modify Code -> Run Tests. A strict DAG validator will reject this plan immediately.
Why it matters: Pure DAGs are insufficient for true agentic workflows that require iterative refinement, reflection, and feedback loops. You need to support controlled cycles without introducing infinite execution traps.
Solution: Introduce bounded feedback loops where cyclic edges are explicitly annotated with guard conditions, maximum iteration counts, and state transition keys.
class LoopGuard:
def __init__(self, max_iterations: int = 5):
self.max_iterations = max_iterations
self.current_count = 0
def can_proceed(self, test_result: bool) -> bool:
if test_result:
return False # Exit loop on success
self.current_count += 1
if self.current_count >= self.max_iterations:
raise RuntimeError(f"Exceeded maximum iteration limit of {self.max_iterations} in agentic loop.")
return True
When compiling plans that contain iterative agent behavior, use stateful graph orchestrators (like LangGraph or custom state machines) where conditional edges dictate whether execution loops back or proceeds to termination.
Step 6: Executing the Graph with Concurrency and Checkpointing
Scenario: Your validated execution graph has 15 nodes. Steps 2, 3, and 4 all depend only on Step 1 and do not depend on each other. If your executor runs them sequentially, you are wasting valuable seconds waiting on I/O-bound network calls.
Why it matters: LLM-generated plans often imply parallelism because independent tool calls (e.g., fetching user data, checking subscription status, and pinging feature flags) can happen concurrently. Your execution engine must leverage asynchronous task scheduling.
Solution:
Use an asynchronous runner that traverses the topological generations of the graph, executing independent nodes concurrently using asyncio.gather.
import asyncio
from typing import Dict, Any
async def mock_tool_executor(tool_name: str, arguments: Dict[str, Any]) -> Any:
# Simulate async tool execution
await asyncio.sleep(1)
return {"status": "success", "result": f"Executed {tool_name} with {arguments}"}
async def execute_verified_graph(G: nx.DiGraph) -> Dict[str, Any]:
# Get nodes grouped by topological generations (concurrently executable tiers)
generations = list(nx.topological_generations(G))
execution_results = {}
for generation in generations:
tasks = []
for node_id in generation:
node_data: ExecutableNode = G.nodes[node_id]['data']
# Resolve data bindings from previous results
resolved_args = node_data.arguments.copy()
# (In production, replace template variables using execution_results here)
task = execute_node_with_retry(node_data, resolved_args, execution_results)
tasks.append((node_id, task))
# Run all nodes in this generation concurrently
results = await asyncio.gather(*(t[1] for t in tasks), return_exceptions=True)
for (node_id, _), res in zip(tasks, results):
if isinstance(res, Exception):
G.nodes[node_id]['data'].status = "FAILED"
G.nodes[node_id]['data'].error = str(res)
raise RuntimeError(f"Node '{node_id}' failed during execution: {res}")
else:
G.nodes[node_id]['data'].status = "COMPLETED"
G.nodes[node_id]['data'].output = res
execution_results[node_id] = res
return execution_results
async def execute_node_with_retry(node: ExecutableNode, args: dict, context: dict) -> Any:
retries = 0
while retries < node.max_retries:
try:
return await asyncio.wait_for(
mock_tool_executor(node.tool_name, args),
timeout=node.timeout_seconds
)
except Exception as e:
retries += 1
if retries >= node.max_retries:
raise e
await asyncio.sleep(2 ** retries) # Exponential backoff
Why this works:
nx.topological_generations() groups nodes into sets where no node in a set depends on another node in the same set. This allows safe, maximum-concurrency execution without race conditions, while the asynchronous wrapper handles timeouts and exponential backoffs cleanly.
⚠️ Gotcha: Never execute state-mutating operations concurrently in the same generation if they target the same resource lock. If two parallel nodes attempt to write to the same database row, you will hit deadlocks regardless of graph validity. Use resource-level locking keys in your node metadata to serialize conflicting operations.
Architectural Trade-Offs and Production Realities
When deciding how strictly to validate and compile agent plans, architectural choices involve clear trade-offs between rigidity and autonomy.
| Dimension | Unconstrained Agent Execution (Raw Tool Loop) | Fully Compiled & Validated Execution Graph |
|---|---|---|
| Safety & Predictability | Extremely Low (prone to hallucinations & infinite loops) | Extremely High (deterministic structure & strict type checking) |
| Latency Overhead | Low (executes immediately per step) | Higher (requires generation, AST compilation, and validation passes) |
| Flexibility in Ambiguous Tasks | High (agent adapts strategy on the fly) | Lower (bounded by pre-compiled graph topology) |
| Debugging & Observability | Difficult (tracing spaghetti text logs) | Exceptional (node-level states, execution graphs, and checkpoints) |
| Cost (Token Consumption) | Variable (can spiral out of control during loops) | Bounded (predictable structure generation upfront) |
The Production Verdict
If your agent is performing trivial tasks like looking up the weather or summarizing a single document, a reactive ReAct loop is sufficient. But if your agent is touching production databases, modifying cloud infrastructure, executing code, or orchestrating multi-system workflows, compiling natural language into a validated execution graph is non-negotiable.
By enforcing structural schemas via Pydantic, compiling text into NetworkX topologies, resolving data bindings statically, and running generational concurrency with robust error policies, you transform an unpredictable generative model into a reliable enterprise orchestration engine.