AI Agent State Machines: Managing Complex Workflows

A state machine lets the model decide inside each step while code decides which step comes next. We mapped one refund workflow onto LangGraph, CrewAI Flows, AutoGen GraphFlow, OpenAI handoffs and Temporal.

Team reviewing an automated workflow together on a laptop

A support agent that can issue refunds should never reach the refund step before it has confirmed who the customer is. A prompt can ask the model to follow that order. A state machine makes the order impossible to skip.

An AI agent state machine is a fixed set of states plus the moves allowed between them. The model still makes decisions, but only inside a state. Code decides which state may come next. That split keeps long, branching workflows on track while the model handles the messy parts.

We studied the graph and flow docs for LangGraph, CrewAI, AutoGen, the OpenAI Agents SDK and Temporal. Then we lined up how each one expresses states, transitions and loops, using one refund workflow as the test case.

What an AI Agent State Machine Controls

Anthropic’s guide on building effective agents draws a line between two designs. Workflows run models and tools through predefined code paths. Agents let the model direct its own process and tool use.

A state machine sits on the workflow side of that line, with room for agent steps inside it. The graph fixes the route. Each node may still call a model that reasons, picks tools and loops on its own.

So a state machine controls three things. It controls which step runs first, which steps may follow each one and when the whole run ends. Everything else stays with the model.

States, Transitions and Guards in Agent Frameworks

Classic state machine terms map neatly onto agent frameworks. The table shows how the main ones name each idea.

State machine termLangGraphCrewAI FlowsAutoGen GraphFlow
State (shared data)State schema with reducersself.state, a dict or Pydantic modelMessages shared by agents
StepNodeA method with @start or @listenAn agent node
Fixed transitionadd_edge@listen on a methodadd_edge
Guarded transitionadd_conditional_edges@router with labelsadd_edge with a condition
StartSTART@start()set_entry_point
EndENDNo explicit end markerNo nodes left to run
Loop caprecursion_limitYour own counterMaxMessageTermination

One idea is missing from older state machines, though. LangGraph and CrewAI can also save state to storage as the run moves. That is what lets a run pause for a person or survive a crash.

A Refund Workflow Drawn as a State Machine

In this design, the model reads the messages and drafts replies, while the graph decides what may happen next.

  1. Intake: the model reads the request and pulls the order number.
  2. Verify identity: a tool checks the email against the order. Failure goes to Escalate.
  3. Check policy: code checks the order date and amount against the refund rules.
  4. Decide: if the amount is under the limit, go to Refund. If it is over, go to Approve.
  5. Approve: the run pauses until a manager approves or rejects.
  6. Refund: a tool issues the refund once, with a guard against repeats.
  7. Confirm: the model writes the reply to the customer, then the run ends.
  8. Escalate: a person takes over, then the run ends.

The guards carry the safety. No edge leads from Intake straight to Refund, so no prompt injection can make the model jump there. That guarantee is the main reason to use a graph for a flow like this.

FromConditionTo
IntakeOrder number foundVerify identity
Verify identityEmail matchesCheck policy
Verify identityNo match after two triesEscalate
Check policyInside policyDecide
DecideUnder the limitRefund
DecideOver the limitApprove
ApproveManager approvesRefund
ApproveManager rejectsConfirm
RefundTool succeedsConfirm

Building the State Machine in LangGraph

LangGraph’s Graph API models a workflow as state, nodes and edges. Its docs sum it up in one line: “nodes do the work, edges tell what to do next.” You build a StateGraph, add nodes and edges, then call .compile() before the graph can run.

docs.langchain.com
LangGraph Graph API Docs website screenshot
LangGraph Graph API Docs

Fixed moves use add_edge, such as add_edge(START, "intake"). Guarded moves use add_conditional_edges with a routing function. A node can also return a Command that updates state and names the next node in one step. However, static edges still run when a node returns Command(goto=...), so pick one routing method per node.

For fan-out, a conditional edge can return several Send objects. Each one runs a node with its own slice of state. That works for jobs where the number of branches is unknown ahead of time, such as checking every item on a long order.

Loops need a ceiling. LangGraph counts super-steps, and the default limit is 1,000 from version 1.0.6. Past that, the graph raises GraphRecursionError.

The Approve state uses an interrupt. Calling interrupt() pauses the graph and hands a value to the caller. To continue, pass Command(resume=...) with the thread_id used before. It needs a checkpointer, and the node restarts from its top on resume. So keep side effects such as the refund call after the interrupt or in a separate node. LangGraph is also listed on our site with its other features.

Read also: How AI Agents Maintain State Across Sessions: Checkpoints, Sessions and Memory Stores

CrewAI Flows and AutoGen GraphFlow Take Other Routes

Not every framework draws an explicit graph. Two popular ones get to a state machine by different paths.

CrewAI Flows Use Decorators and Events

CrewAI Flows build the graph from decorators. @start() marks entry points. @listen() runs a method after another one emits output. @router() picks a branch from a method’s return value, and or_() and and_() join several triggers.

State lives on self.state, either as a dict or a Pydantic model, and each run gets an automatic id. Add @persist and the default backend saves state to a local SQLite database. You can resume a run by passing its id to kickoff. A crew of agents can run inside any step, which is how CrewAI mixes fixed routing with free-form agent work. Also, flow.plot() draws the flow as an interactive HTML page.

AutoGen GraphFlow Directs Agent Turns

AutoGen’s GraphFlow uses DiGraphBuilder to set which agent speaks next. Its docs show a generator and a reviewer in a loop. If the reviewer’s reply contains “APPROVE,” the flow moves to a summarizer. Otherwise it goes back to the generator, with MaxMessageTermination(10) as the cap.

GraphFlow is marked experimental. Also, the AutoGen GitHub repository says the project is in maintenance mode and that new users should begin with Microsoft Agent Framework.

Handoffs as Lightweight State Changes

Sometimes a full graph is more than you need. The OpenAI Agents SDK uses handoffs, where one agent passes the conversation to another. The model sees each handoff as a tool. A handoff to a “Refund Agent” shows up as transfer_to_refund_agent.

Each agent then acts as a state, and each handoff acts as a transition. The difference is who picks the move. Here the model chooses, so the guard is softer than a graph edge. You can tighten it with is_enabled, which turns a handoff on or off at runtime. An input_filter trims the history the next agent sees. Our OpenAI Agents SDK page covers the rest of the framework.

Durable State Machines With Temporal

A refund that waits two days for a manager needs more than an in-memory loop. Temporal is built for that case. Once a Temporal Workflow starts, it runs to completion, even if that takes a year.

Temporal splits code into Workflows and Activities. The Workflow holds the state machine logic and must be deterministic, because Temporal replays it to rebuild state after a failure. Activities do the outside work, such as model calls, database writes and emails. A failed Activity retries with backoff. If a Worker dies, another one replays the Event History and resumes where the run stopped.

Temporal also has an OpenAI Agents SDK integration. It runs the agent loop inside a Workflow and each model call as an Activity. As a result, agents can survive Worker restarts and run for long periods without losing state. Running workflows can also receive Signals, which fits a manager’s approval click.

Workflow State Versus Session Memory

Two kinds of state get mixed up often. Workflow state records where the run stands, such as “waiting for approval” or “refund issued.” Session memory holds what the agent knows about the user or the past, such as a preference or an earlier order.

LangGraph keeps the two apart on purpose. A checkpointer saves graph state per thread. A store holds facts that cross threads. If your question is how an agent remembers a customer next week, see how agents keep state across sessions. This article stays with the workflow side.

Design Rules for AI Agent State Machines

These rules come straight from the framework docs we read and the failure cases they warn about.

  • Keep the state count small: each state should match a step a person would name. Ten named states beat forty tiny ones.
  • Put money and data moves in their own nodes: LangGraph re-runs a node from the top after an interrupt. So code before interrupt() must be safe to repeat.
  • Use one routing method per node: mixing static edges with Command(goto=...) runs both paths.
  • Cap every loop: set a recursion limit, a message cap or your own counter, and route the overflow to a person.
  • Keep model choices inside states: let the model write and classify, but let code own the edges that spend, send or delete.
  • Log every transition: a trace of state changes lets you replay a failed run step by step. Tracing tools such as LangSmith or Langfuse record each step.

When a State Machine Is the Wrong Tool

A state machine pays off when the steps are known and some moves are risky. It is a poor match for open research, where the agent cannot know its next step until it sees results. In that case, a looser loop with a step cap works better. Those designs are covered in dynamic planning for LLM agents.

Many teams land in the middle. A graph runs the process, and one node holds a free-form agent. We compared the trade-offs in autonomous AI agents vs workflow automation. For visual builders that draw the graph for you, browse our workflow automation agents, including the n8n AI Agent.

State Machine Questions From Workflow Teams

Is LangGraph a state machine?

It works like one. You define state, nodes and edges, and the graph moves between nodes in super-steps. Unlike a basic state machine, it can run nodes in parallel and save a checkpoint as it goes.

Do state machines make agents less smart?

They limit where the model can go, but they leave its reasoning alone inside each state. For a refund or a bank change, that limit is the point.

Can one state machine run several agents?

Yes. AutoGen GraphFlow routes between agents, and CrewAI runs whole crews inside flow steps. For the bigger picture, see our multi-agent category and our comparison of CrewAI vs LangGraph.

How do I add a human approval step?

Use an interrupt in LangGraph, @human_feedback in CrewAI Flows from version 1.8.0, or a Signal in Temporal. Review screen design is covered in human-in-the-loop orchestration.

Related AI Agents

Read also: Webhooks vs Polling for AI Agent Workflows

Explore Agent Categories

Related Articles

Joydeep Bhattacharya Avatar

Written by