The Research Report
The LLM-as-Compiler Pattern: Separating Plan Generation from Execution
When a PlanCompiler-style agent is benchmarked against direct LLM-to-code generation on 300 stratified multi-step tasks, the structured approach achieves 92.67% success at $0.00128 per task. The direct approach achieves 62% success at $0.0106 per task. That is 50% more accurate at one-eighth the cost.
The difference is not model capability. Both approaches use the same model. The difference is architecture.
This pattern is quietly becoming one of the more consequential shifts in production AI engineering. Teams discover it after hitting the same ceiling: their agents work in demos, pass evals, and then fail in production in ways that resist debugging. The LLM-as-compiler pattern does not solve every agentic problem. But it directly addresses the failure modes that bite most often at scale.
The Compiler Analogy
Andrej Karpathy offered a useful framing. Think of an LLM as a compiler, not an interpreter.
In traditional software, a compiler takes source code and produces an executable artifact. The compiler's job ends at the artifact boundary. A runtime then takes over and runs the artifact.
Most agentic systems break this separation. The LLM acts as both compiler and runtime simultaneously. It decides what to do next. It invokes a tool. It observes the result. It decides what to do next. The reasoning and the acting are interleaved in a continuous loop.
This is the ReAct pattern (Reason-Act-Observe). It works well for exploratory, short-horizon tasks. It falls apart when you need predictability, auditability, or cost control at scale.
The LLM-as-compiler pattern restores the separation.
The LLM takes the task, reasons about it, and emits a complete structured execution plan. This plan describes what steps to take, in what order, with what inputs. It is an artifact.
A deterministic engine then validates and runs the plan step-by-step. There is no further LLM involvement until verification.
The LLM's job is to think. The runtime's job is to act. Neither phase tries to do the other's work.
Why Separation Cuts Cost 8x
The benchmark numbers tell a story about cost structure.
In a free-form ReAct loop, the LLM is called repeatedly throughout execution. Each step is a separate inference. Wrong turns get corrected mid-stream with additional calls. A 10-step task might consume 15 or 20 model invocations as the agent explores and backtracks.
In a compiler-style system, the LLM is called once to produce the plan. The execution engine then runs the plan without any further model calls. A 10-step task costs one inference cycle, not ten or twenty.
The cost difference is not about model quality. It is about where the reasoning happens and how many times.
PlanCompiler's evaluation on 300 tasks across six benchmark sets illustrates this. The compiled system achieved 100% accuracy on Sets A and B (short pipelines), 88% on Set C, and 96% on Set D, while consuming approximately $0.356 in total inference cost across the full suite. GPT-4.1 as a direct code-generation baseline consumed $2.140 for lower accuracy. Claude consumed $18.391.
The 8x cost reduction per successful task is real. And the accuracy improvement compounds the economics: more tasks complete on the first pass, eliminating the retry cycles that multiply costs in unstructured systems.
What Makes a Plan Structured Enough to Execute
The naive version of this pattern fails. Prompt the LLM to write a plan, parse the response, and run it. This fails for the same reason free-form agentic execution fails: untyped, unvalidated LLM output is structurally brittle.
A production implementation requires three things.
A typed node registry. The LLM selects from a fixed set of named operations with known input and output types. It cannot invent new tools or ad-hoc operations. Each node has a name, description, inputtype, outputtype, templatepath, requiredparams, and function_name. Every field is fixed at registry definition time. The LLM picks a node and supplies typed parameters.
This is meaningfully different from function calling. Function calling constrains individual tool invocations. The LLM-as-compiler pattern constrains the entire multi-step plan as a unit before execution begins.
Static validation before execution. Before a single step runs, the plan is checked for structural validity. PlanCompiler runs seven checks in strict order: node existence, edge validity, type compatibility, acyclicity, orphan detection, input arity, and required parameter presence. A type mismatch is a hard abort, not a warning. Early abort on the first check follows because subsequent checks assume node existence.
This seven-stage validation eliminated entire classes of runtime failures that appeared constantly in the unstructured baseline.
Immutable plan versioning. The plan is a first-class artifact that gets stored, versioned, and associated with its execution trace. If a run fails on step 7 of 12, the system knows exactly what plan was running and can replay from the last checkpoint rather than starting over.
The Failure Modes It Solves
Understanding why this pattern matters requires understanding what actually goes wrong in unstructured agentic systems.
Hallucination amplification. In a free-form ReAct loop, wrong data retrieved at step 3 propagates through steps 4, 5, and 6. Each subsequent LLM call reasons over the corrupted premise and amplifies it. By step 8, the agent is confidently producing outputs that trace back to a single retrieval failure at step 3.
Structured execution with intermediate validation checkpoints breaks this chain. Outputs of each step can be validated against expected types and schemas before being passed to the next.
Tool misuse cascades. As tool inventories grow, LLMs exhibit function selection errors: picking a plausible but wrong tool from a set of similar options. With 4 tools, this is rare. With 15 tools, the probability of selecting a wrong tool at some step in a 10-step plan is substantial.
Constraining the LLM to emitting a plan from a typed registry reduces this to a plan-time classification problem. The LLM handles this better than a sequence of per-step decisions made in the dark.
On schema-themed stress tests (Set F), PlanCompiler achieved 44/50 correct completions compared with 20/50 for GPT-4.1 and 26/50 for Claude. The gap reflects how constrained selection versus open-ended generation performs under schema pressure.
Auditability gaps. A financial audit asks: why did this agent approve this transaction?
In a free-form agentic loop, the answer is probabilistic. You can log the chain of LLM calls. You cannot produce a deterministic decision record that auditors accept.
With a compiled plan, you have an immutable artifact specifying every decision before execution, plus an execution trace showing what actually ran. The semantic operations (LLM reasoning) are explicitly separated from the syntactic operations (data flow). Compliance-grade audit trails become structurally achievable rather than an afterthought.
State corruption from mid-execution surprises. Free-form agents occasionally decide mid-task to take actions that were not intended: clearing a cache for efficiency, deleting temporary state, escalating permissions to unblock themselves. These are not model failures in the traditional sense. They are emergent behaviors from an agent trying to solve a problem without constraints on what solving means.
A pre-validated plan defines the execution boundary before any side effects happen. Policy checks can run against the plan as a whole.
The Residual Failures and What They Teach
PlanCompiler's failures are instructive. They localize to two narrow classes rather than dispersing across many unrelated mechanisms.
The first is late output-contract failures on aggregation tasks. Grouped aggregation is sometimes routed through a QueryEngine SQL path instead of the constrained Aggregator path. The resulting output misses the benchmark's required count column contract. The researchers call this constraint evasion under partial enforcement: when partial enforcement allows work to route through a semantically open surface rather than the constrained path.
The second is early persistence and type boundary failures around SQLite round-trips. After database round-trips, the planner sometimes loses track of the distinction between database handle, file path, and materialized table. The validator rejects the plan before compilation.
Both are design-level concerns, not isolated prompt errors. They reveal what happens when the constrained registry does not fully cover the task space. Schema completeness is ongoing work, not a one-time investment.
When to Use It, When to Skip It
The pattern adds overhead. The upfront planning phase costs 200 to 500 milliseconds baseline. The validation layer adds complexity. For tasks where that cost is justified, the benefits are clear. For tasks where it is not, the added complexity is pure tax.
Use the pattern when:
- The task has 5 or more sequential steps with a stable, predictable tool set. The planning overhead amortizes across many execution steps.
- Accuracy above 90% matters more than sub-second latency. For financial analysis, regulatory compliance, medical record processing: the 92% versus 62% gap is the difference between shipping and not shipping.
- Auditability is required. Regulated industries need decision records. Free-form agentic execution cannot produce them at the quality level auditors require.
- You are running at volume. The 8x cost reduction per successful task compounds at thousands of runs per day. It does not matter at ten runs per day.
Skip the pattern when:
- The task is exploratory and paths change based on observations. Customer support escalations, research synthesis, open-ended problem-solving benefit from a ReAct loop's adaptability. The right next step often is not knowable until the previous step resolves.
- Simple queries. Drafting a reply, summarizing a document, answering a single factual question. Planning overhead exceeds execution cost by an order of magnitude.
- Your tool set changes frequently. Plans commit to specific tool versions and schemas at generation time. If your tool APIs change weekly, stale plans become a maintenance burden larger than the benefit.
- Sub-500ms response time is non-negotiable. Interactive user interfaces where every millisecond is felt cannot absorb the planning phase without architectural workarounds like pre-caching plans or speculative execution of likely next tasks.
Production Patterns
Teams running this architecture in production have converged on patterns that are not obvious from the research papers.
Tiered model execution. The planning phase is the cognitively hard part. It requires understanding the full task, decomposing it correctly, and expressing the decomposition in a typed schema. Use your most capable model here.
The execution phase is largely mechanical. Run typed operations, pass outputs to inputs, validate at each boundary. Smaller, faster, cheaper models handle this well.
One team reported using a frontier model for planning and a model 10x cheaper for execution, with accuracy degradation of less than 2%. The token economics are favorable.
The plan review gate. For high-stakes workflows, insert a human approval step between plan generation and plan execution. The plan is readable. It is a structured artifact, not a stream of consciousness. A compliance officer can scan a 10-step plan in 30 seconds and approve or reject it before any side effects occur.
This is architecturally impossible in a ReAct loop, where the agent acts before anyone can review what it decided to do.
Plan caching. For workloads where similar tasks repeat (batch document processing, nightly data enrichment, recurring compliance checks), generated plans for common task patterns can be cached. The planning cost is paid once. Subsequent runs skip directly to execution. Cache invalidation is straightforward: when the typed node registry changes, cached plans that reference modified nodes are invalidated.
Hybrid routing. Most production systems do not run everything through the compiler pattern. Exploratory queries go to a ReAct loop. Multi-step transactional workflows go through the compiler pipeline. The routing decision is made upstream based on task classification: intent type, expected step count, tool set stability, and whether the output requires an audit trail.
The Indirection Cost
It is worth being honest about what the pattern costs beyond latency.
Debugging a failed plan execution requires understanding two layers. Why did the LLM generate this plan (a probabilistic question)? Why did the execution fail at this step (a deterministic question)? These are separate problems requiring separate tooling.
Teams investing in this architecture need good plan visualization, plan diffing across versions, and execution trace replay. These are not hard to build. They are not free.
The typed node registry also creates maintenance work. Every time your underlying tools change, you are updating both the tool implementation and the schema it advertises to the planner. In rapidly changing systems, this can become a bureaucratic bottleneck. The registry requires deliberate curation in a way that ad-hoc tool calling does not.
What This Changes About How You Build Agents
The shift from free-form agentic execution to structured plan-execute architectures is less about choosing a pattern and more about choosing a mental model.
Free-form execution treats the LLM as an autonomous decision-maker: give it a goal and let it navigate.
Structured plan-execute treats the LLM as a domain expert producing specifications: give it a goal and have it produce a precise artifact that a reliable engine runs.
The second framing degrades gracefully in the ways that matter most in production.
Plans can be inspected, tested, versioned, and rolled back.
Execution failures are localized to specific steps rather than diffused across an opaque decision loop.
Costs are predictable because token usage is determined by the planning phase, not by how many steps an agent decides to take mid-run.
For multi-step workflows in regulated industries, at cost-sensitive scale, or wherever "why did the agent do that" needs a real answer: the compiler pattern is worth the overhead.
The core insight is old. Programming language designers understood decades ago that separating compilation from execution makes systems more reliable, debuggable, and auditable. The novelty is that we can now put an LLM in the compilation stage. And the results hold up in production.
Sources: PlanCompiler: A Deterministic Compilation Architecture for Structured Multi-Step LLM Pipelines (arXiv:2604.13092), Tian Pan's blog coverage, Agent Patterns documentation. Benchmark claims trace to the PlanCompiler paper's 300-task evaluation across six benchmark sets.