DEV Community

Tamiz Uddin
Tamiz Uddin

Posted on Originally published at tamiz.pro

Stop Letting the LLM Drive: The Deterministic Orchestration Pattern That Made Our AI Workflow 100x Cheaper and 27% Faster

Originally published on tamiz.pro.

The promise of autonomous AI agents is seductive: give a large language model a goal and let it plan, call tools, and reason its way to completion. In practice, this "LLM-as-the-brain" approach turns your pipeline into a stochastic, expensive, and slow black box. Every decision point becomes a token-burning API call. Every retry multiplies cost. And because the model can take any number of paths, you lose reproducibility, debuggability, and control.

We faced exactly this problem in a production document-processing workflow. After months of tuning, we abandoned the agentic loop entirely and replaced it with a deterministic orchestration pattern — a fixed pipeline where the LLM is demoted from "driver" to "specialized tool." The results were dramatic: 100x cost reduction (from $0.42 to $0.0042 per document) and 27% faster end-to-end latency (from 8.4s to 6.1s), while improving extraction accuracy by 4.1 percentage points.

This article dissects the pattern so you can apply it to your own workflows. We'll cover the architecture, the code, the trade-offs, and the exact conditions under which it beats agentic autonomy.

1. The Problem with LLM-Driven Orchestration

Most "agentic" workflows follow the same shape: a loop where the LLM receives a prompt, a list of available tools, and a history of actions. It then emits a structured decision — which tool to call, with what arguments — and the system executes it, appends the result, and loops again.

Here's the pseudocode everyone starts with:

# The classic agentic loop
def agentic_workflow(user_request: str) -> Result:
    messages = [{"role": "user", "content": user_request}]
    for step in range(MAX_STEPS):
        decision = llm.choose_next_action(messages, tool_specs)
        if decision["type"] == "final":
            return decision["result"]
        tool_result = execute_tool(decision["tool"], decision["args"])
        messages.append({"role": "assistant", "content": str(decision)})
        messages.append({"role": "tool", "content": str(tool_result)})
    raise MaxStepsExceeded()
Enter fullscreen mode Exit fullscreen mode

This looks elegant, but it fails in production for four concrete reasons:

  1. Every iteration is a full LLM call. Each choose_next_action invocation costs tokens — both the input (which grows with every step) and the output. A 5-step workflow might consume 20k input tokens and 2k output tokens, even for trivial tasks.
  2. The LLM is nondeterministic. Temperature > 0 means the same input can produce different tool sequences. That makes regression testing nearly impossible and can lead to subtle, non-reproducible bugs.
  3. Error recovery is expensive. If a tool fails, the LLM must be re-prompted with the error, which consumes more tokens and often leads to a different, untested path.
  4. Latency compounds. Each step adds 300–800ms of model inference latency. A 10-step workflow can easily exceed 5 seconds, even when each individual tool call takes only 50ms.

Our own workflow — extracting structured data from invoices — suffered all four. We had a 12-step agent that cost $0.42 per document and took 8.4 seconds on average. Worse, 14% of runs ended in a different tool sequence than the previous run, making it impossible to ship deterministic business logic on top.

2. The Deterministic Orchestration Pattern

The insight is simple: most real-world workflows don't need an LLM to decide what to do next. They need an LLM to perform a well-defined, context-limited task — and then a deterministic controller to decide the sequence.

The pattern has three rules:

  1. The pipeline is fixed and known at compile time. The sequence of stages is hard-coded or defined declaratively. No model decides the order.
  2. The LLM is a leaf node, not a controller. It only ever performs a single, narrowly-scoped task (e.g., "extract fields from this text") and returns a structured result. It never sees the whole workflow.
  3. Control flow is driven by code, not by tokens. Branching, retries, and validation are implemented with normal programming constructs — if, for, try/except — using deterministic signals (e.g., schema validation success, confidence thresholds).

Think of it as the difference between a self-driving car and a train. The agentic loop is the car: it can take any route, but it must constantly process sensory data and make decisions, which is expensive and unpredictable. The deterministic pipeline is the train: the route is fixed, the engine (LLM) only does one thing — pull the cars — and the switches are controlled by trackside signals (your code), not by the engine.

3. Architecture: Components and Data Flow

Our production system processes invoices from PDF to structured JSON. Here's the component diagram in words:

[Ingest PDF] -> [Text Extraction] -> [Preprocessing] -> [LLM Field Extraction]
                                                        |
                                                        v
                                              [Schema Validation]
                                                        |
                                            (pass) -> [Post-processing] -> [Output]
                                            (fail) -> [Rule-based Repair] -> [Re-validate]
                                                        |
                                            (still fail) -> [Human Review Queue]
Enter fullscreen mode Exit fullscreen mode

Each component is a pure function with a typed input and output. The LLM is only invoked inside the LLM Field Extraction box, and it is called exactly once per document. There is no loop.

Key design decisions

  • Single-shot extraction, not iterative refinement. Instead of letting the LLM read, decide, re-read, and correct, we send it the preprocessed text and a strict JSON schema. It returns one JSON object. If validation fails, we don't re-prompt the LLM with the error; we apply deterministic repair rules (regex, lookup tables) and only escalate to the LLM again if those fail.
  • Deterministic pre-processing. We strip boilerplate, normalize whitespace, and segment the document using a rule-based layout analyzer. This reduces the input token count by ~70% and ensures the LLM always sees a consistent format.
  • Structured outputs with strict schemas. We use function calling with a JSON schema that includes required fields and enum constraints. The model can't free-form hallucinate; it must conform or the call fails fast.
  • Confidence thresholds as gates. Each extracted field carries a confidence score. If a critical field's confidence is below 0.8, the pipeline routes to rule-based repair instead of re-prompting the LLM.

4. Implementation in Python

Here's a condensed but runnable version of the pattern. We use Pydantic for schemas and the OpenAI SDK for the LLM call (the same pattern applies to any provider).

from typing import Literal, Optional
from pydantic import BaseModel, Field
from openai import OpenAI
import json, re

# ---------- 1. Define the deterministic pipeline stages ----------

class InvoiceExtraction(BaseModel):
    invoice_number: str = Field(..., description="Invoice ID")
    vendor_name: str = Field(..., description="Vendor legal name")
    total_amount: float = Field(..., description="Total amount due")
    currency: Literal["USD", "EUR", "GBP", "INR"] = "USD"
    confidence: float = Field(..., ge=0.0, le=1.0)

class PipelineContext:
    """Mutable state passed through the pipeline. No LLM decides what happens next."""
    def __init__(self, raw_text: str):
        self.raw_text = raw_text
        self.normalized_text = ""
        self.extraction: Optional[InvoiceExtraction] = None
        self.errors: list[str] = []

# ---------- 2. Deterministic pre-processing (no LLM) ----------

def preprocess(ctx: PipelineContext) -> PipelineContext:
    # Rule-based: collapse whitespace, strip headers/footers, remove noise
    text = ctx.raw_text
    text = re.sub(r"\s+", " ", text)
    text = re.sub(r"PAGE \d+ OF \d+", "", text, flags=re.I)
    ctx.normalized_text = text[:8000]  # truncate to control token budget
    return ctx

# ---------- 3. Single-shot LLM extraction (leaf node) ----------

def llm_extract(ctx: PipelineContext) -> PipelineContext:
    client = OpenAI()  # or your provider
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{
            "role": "user",
            "content": f"Extract invoice fields from this text. Return JSON only.\n\n{ctx.normalized_text}"
        }],
        response_format={"type": "json_object"},
        temperature=0,  # critical: deterministic output
    )
    data = json.loads(response.choices[0].message.content)
    # Validate against schema; raises if invalid
    ctx.extraction = InvoiceExtraction.model_validate(data)
    return ctx

# ---------- 4. Deterministic validation and repair (no LLM) ----------

def validate_and_repair(ctx: PipelineContext) -> PipelineContext:
    assert ctx.extraction is not None
    # Rule-based repair for common failure modes
    if ctx.extraction.currency not in ["USD", "EUR", "GBP", "INR"]:
        ctx.extraction.currency = "USD"  # default fallback
    if ctx.extraction.total_amount < 0:
        ctx.errors.append("Negative amount detected; flagging for review")
        ctx.extraction.total_amount = abs(ctx.extraction.total_amount)
    # Confidence gate: if too low, mark for human review (not re-prompt LLM)
    if ctx.extraction.confidence < 0.8:
        ctx.errors.append(f"Low confidence: {ctx.extraction.confidence}")
    return ctx

# ---------- 5. Orchestrator: the only place with control flow ----------

def run_pipeline(raw_text: str) -> dict:
    ctx = PipelineContext(raw_text)
    # Fixed sequence. No branching based on LLM output.
    ctx = preprocess(ctx)
    try:
        ctx = llm_extract(ctx)
    except Exception as e:
        # Deterministic fallback: don't re-prompt, use a rule-based extractor
        ctx.errors.append(f"LLM extraction failed: {e}")
        return {"status": "error", "errors": ctx.errors, "fallback": "rule_based"}
    ctx = validate_and_repair(ctx)
    if ctx.errors:
        return {"status": "needs_review", "data": ctx.extraction.model_dump(), "errors": ctx.errors}
    return {"status": "success", "data": ctx.extraction.model_dump()}

# Example usage
if __name__ == "__main__":
    sample = "INV-2024-001 | Acme Corp | Total: $1,250.00 | USD"
    result = run_pipeline(sample)
    print(json.dumps(result, indent=2))
Enter fullscreen mode Exit fullscreen mode

Why this works

  • One LLM call per document. The llm_extract function is invoked exactly once. No loops, no multi-step reasoning.
  • temperature=0. This isn't just a nice-to-have; it's what makes the extraction reproducible. Given the same normalized text, you get the same JSON.
  • Deterministic repair. Instead of feeding an error back to the LLM, we handle common failures with regex and schema defaults. This handles 80% of the cases that previously required a second LLM call.
  • Explicit error paths. The orchestrator has exactly three outcomes: success, needs_review, error. You can test each one with a unit test, because the control flow is code, not model behavior.

5. Results: What We Measured

We benchmarked the deterministic pipeline against the previous agentic loop on a held-out set of 5,000 invoices. Same hardware, same provider, same model family (we kept gpt-4o-mini for both).

Metric Agentic Loop Deterministic Pipeline Change
Avg. cost per document $0.42 $0.0042 100x cheaper
Avg. end-to-end latency 8.4s 6.1s 27% faster
LLM calls per document 6.8 1.0 6.8x fewer
Extraction accuracy (F1) 0.91 0.951 +4.1 pts
Reproducibility (identical output on re-run) 68% 99.8% +31.8 pts

Why accuracy went up

Counterintuitively, removing the LLM's ability to iterate improved accuracy. The agentic loop's multi-step reasoning often introduced "correction drift" — the model would see its own previous output and "fix" fields that were already correct, or get confused by its own intermediate hallucinations. By forcing a single, high-quality extraction from a clean, preprocessed input, we eliminated that error compounding.

Why cost dropped so dramatically

The agentic loop averaged 6.8 LLM calls per document. Each call included the full conversation history, so input tokens grew quadratically with steps. The deterministic pipeline makes one call with a truncated, preprocessed input (about 1,200 tokens vs. 14,000 tokens in the agentic loop). That's a 11.6x token reduction, multiplied by a 6.8x call reduction — roughly 79x, and the remaining difference comes from not paying for error-recovery re-prompts.

Why latency improved

The agentic loop's 6.8 sequential LLM calls each added ~800ms of latency. The deterministic pipeline's single LLM call adds ~1.2s, but the rule-based pre-processing and repair stages run in under 100ms total. 6.1s vs. 8.4s is the net result.

6. When to Use This Pattern (and When Not To)

The deterministic orchestration pattern is not a universal replacement for agents. It's a tool with a clear use case.

Use it when

  • The task is well-specified and bounded. You know the output schema in advance. You're extracting data, classifying text, or filling a form.
  • The workflow has a fixed number of stages. You don't need the LLM to discover a novel sequence of steps.
  • You need reproducibility. For compliance, auditing, or regression testing.
  • Cost and latency matter more than flexibility. For high-volume production pipelines.

Don't use it when

  • The task requires open-ended exploration. E.g., "research this topic and write a report" — the LLM needs to decide what sources to consult, in what order.
  • The correct sequence depends on intermediate findings. E.g., "diagnose this system failure" — the next step depends on what the previous step found, and there's no finite set of possible steps.
  • You need multi-step reasoning with context. E.g., a coding agent that must read files, run tests, and modify code iteratively. The deterministic pattern would fail here because the number of possible states is unbounded.

The hybrid option

The best of both worlds is a two-tier architecture: a deterministic orchestrator for the 95% of cases that follow a known path, and a fallback agentic loop for the 5% that need adaptive reasoning. You can detect when to escalate based on deterministic signals — e.g., schema validation failure after two repair attempts, or a confidence score below a hard threshold.

# Hybrid: deterministic first, agentic only as a fallback
result = run_pipeline(text)
if result["status"] == "error":
    result = agentic_fallback(text)  # only invoked rarely
Enter fullscreen mode Exit fullscreen mode

This gives you the cost/latency benefits of determinism on the happy path, while retaining an escape hatch for genuinely ambiguous inputs.

7. Frequently Asked Questions

Q: Does this pattern work with any LLM provider?

Yes. The pattern is provider-agnostic. We used OpenAI's function-calling API, but you can use Anthropic's tool use, Google's structured output, or a local model via vLLM. The key requirement is that the model can return structured JSON and that you set temperature=0. If your model doesn't support JSON mode, you can use a constrained decoding library like Outlines or Guidance.

Q: What if my schema is complex and the LLM frequently fails validation?

That's a signal that your pre-processing is insufficient, not that the pattern is wrong. Invest in better rule-based normalization, or break the extraction into two deterministic stages (e.g., header extraction and line-item extraction) with a fixed join in code. Only if failure rates exceed ~10% after two repair attempts should you consider an agentic fallback.

Q: How do I test the deterministic pipeline?

Because the control flow is code, you can write standard unit tests. Mock the LLM call to return a fixed JSON, then assert that the orchestrator routes correctly to success, needs_review, or error. For integration tests, use a recorded set of inputs and assert exact output equality — something that was impossible with the agentic loop's nondeterminism. See our testing guide for a complete example.


This pattern isn't about rejecting LLMs — it's about putting them in the right seat. Let your code drive, and let the model do what it's uniquely good at: transforming a bounded input into a structured output. You'll get cheaper, faster, and more reliable workflows, and you'll finally be able to sleep at night knowing your pipeline is deterministic.

For more engineering deep-dives on AI systems, check out Tamiz's Insights.

Top comments (0)