Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Llm workflow orchestration when a state machine beats just let the llm handle it?

· 5 min read · Home Tech

In this article
  1. Background: Why This Question Matters
  2. What a State Machine Brings to LLM Workflows
  3. When to Let the LLM Handle It (and When Not To)
  4. How to Design a Hybrid: State Machine + LLM
  5. Common Problems and How to Avoid Them
  6. Comparison: State Machine vs. LLM-Only vs. Full Agent
  7. Costs and Safety Considerations
  8. Frequently Asked Questions

State machines beat letting the LLM handle everything when the task has a fixed, predictable set of steps, requires strict validation or rollback, or must guarantee a specific output format—LLMs excel at open-ended generation but struggle with consistency, cost, and error recovery. For workflows with clear stages (like data entry, approval, or multi-step tool use), a state machine provides deterministic control, while the LLM handles only the fuzzy parts like understanding user intent or generating text.

Background: Why This Question Matters

As LLMs became capable of following instructions and calling tools, developers started building "agentic" systems where the model decides each next step. This is powerful for open-ended tasks like research or creative writing. But for production workflows—order processing, customer support ticketing, document generation—letting the LLM drive the entire process creates problems: unpredictable costs, hallucinated steps, and difficulty debugging. The industry is now realizing that a hybrid approach is often better: use a state machine to define the workflow's skeleton, and let the LLM fill in the content at each step.

What a State Machine Brings to LLM Workflows

A state machine is a model of computation with a finite set of states, transitions between them, and rules for when transitions occur. In an LLM workflow, you define states like awaiting_user_input, validating_data, generating_response, and escalating. Transitions happen based on events (user message, tool result, timeout) or conditions (validation passed). This gives you:

  • Determinism: The path through the workflow is predictable, so you can test it thoroughly.
  • Error handling: You can define fallback states (e.g., retry, human handoff) explicitly.
  • Auditability: Every state change can be logged, making it easy to trace what happened.
  • Cost control: You call the LLM only when needed, not for every decision.

When to Let the LLM Handle It (and When Not To)

Letting the LLM handle the entire workflow is suitable for tasks that are genuinely open-ended and where the user expects a conversational, adaptive experience. Examples include brainstorming, drafting emails, or answering follow-up questions in a chat. In these cases, a rigid state machine would feel clunky and limit the model's usefulness.

However, you should use a state machine when:

  • The workflow has a fixed number of steps that must happen in order (e.g., collect shipping address → validate → confirm → pay).
  • There are strict business rules (e.g., a refund can only be issued after approval from a manager).
  • The output must be structured (e.g., a JSON object with specific fields) and validated before proceeding.
  • You need to handle interruptions or timeouts gracefully (e.g., a user stops responding mid-checkout).
  • You need to rollback to a previous state if something goes wrong (e.g., payment fails).

How to Design a Hybrid: State Machine + LLM

The key is to separate control flow from content generation. Here's a practical approach:

  1. Map the workflow steps: Write down every step from start to finish, including decision points and error branches.
  2. Identify the fuzzy parts: Which steps require understanding natural language, generating text, or extracting unstructured info? Those are where the LLM goes.
  3. Define states and transitions: For each step, define what triggers the next step. Use a library like XState (JavaScript) or a simple enum in Python to implement it.
  4. Call the LLM only within a state: For example, in the extract_details state, you call the LLM to turn a user's free-text answer into structured fields. The state machine then validates those fields and moves on.
  5. Add fallback states: If the LLM output fails validation, transition to a clarify state where the LLM asks the user a follow-up question.

Common Problems and How to Avoid Them

  • Over-engineering: Don't create a state machine for a simple Q&A bot. If your workflow is just "user asks, LLM answers," a state machine adds complexity without benefit.
  • Ignoring validation: Even with a state machine, you must validate LLM outputs. Use JSON schema validation or custom checks to ensure the model didn't invent a product ID or use an invalid date.
  • State explosion: Too many states make the system hard to maintain. Keep it coarse-grained; let the LLM handle sub-steps within a state.
  • Latency: Each LLM call adds seconds. If a state transition requires an LLM call, consider caching or using a faster model for simple classifications.

Comparison: State Machine vs. LLM-Only vs. Full Agent

ApproachProsCons
State Machine OnlyFast, cheap, deterministicInflexible, can't handle unexpected input
LLM-Only (prompt-driven)Flexible, adaptiveUnpredictable, costly, can hallucinate steps
State Machine + LLMBalanced control and flexibilityMore complex to build
Full Agent (LLM decides all)Handles complex, novel tasksHard to debug, requires guardrails

In practice, many production systems use the hybrid. For example, a customer service bot might use a state machine to handle authentication, order lookup, and refund processing, while using the LLM to interpret the user's issue and generate the final response.

Costs and Safety Considerations

Cost is a major driver. LLM calls are metered per token. A state machine reduces the number of calls by not asking the model to "decide" what to do next at every step. For a high-volume workflow, this can cut costs by 50-80% compared to a fully agentic approach.

Safety is another concern. If an LLM is allowed to perform actions (like sending emails or making API calls), a state machine can enforce permissions. For instance, you can define a state awaiting_approval that requires a human to click "approve" before transitioning to send_email. This prevents the model from taking irreversible actions without oversight.

Frequently Asked Questions

Is a state machine always better than letting the LLM handle it?

No. For open-ended, low-risk tasks like a casual chat, letting the LLM handle it is simpler and more natural. State machines shine when you need reliability, auditability, and cost control—typical in business workflows.

Can I use a state machine with any LLM provider?

Yes. The state machine is just code that calls an LLM API. It works with any provider (OpenAI, Anthropic, open-source models) as long as you can make HTTP requests.

How do I handle unexpected user input in a state machine?

Add a fallback state that uses the LLM to understand the input. For example, if the user says something that doesn't match any expected transition, the LLM can ask clarifying questions or route to a human.

What if the LLM produces invalid output in a state?

Validate the output immediately after the LLM call. If it fails, transition to a retry state (with a limited number of attempts) or a human_handoff state.

Is this approach only for text-based workflows?

No. It works for any workflow where an LLM is used, including image generation, code generation, or data transformation. The state machine manages the process; the LLM handles the content.