The “Demo-Ware” Problem
Published: 2026-03-17
URL: https://theagenticstack.substack.com/p/dags-vs-state-machines-architecting
If you look at 90% of the AI tutorials on GitHub today, they follow the exact same architectural pattern: The Directed Acyclic Graph (DAG). A developer uses standard LangChain or LlamaIndex to chain a sequence of events. Prompt -> LLM -> Output Parser -> Database Query -> Final LLM -> Return. Thanks for reading! Subscribe for free to receive new posts and support my work.
In a local Jupyter notebook, this looks like magic. In a production enterprise environment, this architecture is fragile, brittle, and essentially “demo-ware.” Why? Because a DAG is, by definition, acyclic.
It flows in one direction. It assumes that every node in the chain will execute perfectly, that the LLM will never hallucinate a malformed JSON payload, and that the external APIs will never time out. But enterprise systems are inherently messy.
When a step fails in a strict DAG, the entire chain breaks. If you want an AI agent to actually operate autonomously—meaning it can encounter an error, realize it made a mistake, adjust its reasoning, and try again—a one-way graph is mathematically incapable of supporting that behavior. To build true enterprise swarms, we have to abandon the DAG. We must architect our orchestrators as Cyclic State Machines. Today, we are going deep into the Python architecture of State Machines, looking at how to build fault-tolerant, looping agentic orchestrators using frameworks like LangGraph.
- The Anatomy of an Agentic State Machine
A State Machine operates on a completely different paradigm than a standard script. Instead of passing a string of text from one function to the next, a State Machine passes a centralized, strongly-typed State Object.
Every node in your system (the LLM, the Database query tool, the Python interpreter) reads from this central state, performs its action, and then returns an update to that state. Crucially, the orchestrator allows for Conditional Edges (cycles). If the LLM generates a bad SQL query and the Database node throws an exception, the Database node doesn’t crash the application.
It writes the error message to the State Object, and routes the flow backward to the LLM node, saying: “Here is the error you caused. Fix your SQL and try again.” This is the foundation of the ReAct (Reasoning and Acting) loop. Let’s look at how to code it.
- Defining the Strongly-Typed State
Before we define our nodes, we must define the state that flows between them. In an enterprise system, you cannot rely on loose dictionaries. You must use TypedDict or Pydantic models to guarantee structural integrity. Python from typing import TypedDict, Annotated, Sequence from langchaincore.messages import BaseMessage from defaultimport import add
1. Define the Global State
class AgentState(TypedDict):
'messages' will hold the entire conversation and tool history.
The 'add' reducer ensures we append new messages rather than overwriting.
messages: Annotated[Sequence[BaseMessage], add]
Track deterministic workflow variables
currentintent: str retrycount: int validation_error: str | None This AgentState is the lifeblood of our State Machine. When our graph executes, this exact object is passed from node to node.
- Architecting the Nodes (The “Doers”)
In a State Machine, a “Node” is just a standard Python function. It takes the AgentState as its input, executes its internal logic, and returns a dictionary that represents how the state should be updated. We need two primary nodes for a fault-tolerant system: The Reasoning Node: Calls the LLM to decide the next action. The Execution Node: Actually executes the tool (e.g., querying the database). Python from langchainopenai import ChatOpenAI from langchaincore.messages import ToolMessage
Initialize our frontier model
llm = ChatOpenAI(model="gpt-4o", temperature=0)
Bind our internal enterprise tools to the model
(Assuming getvendordata and updateerprecord are pre-defined tools)
tools = [getvendordata, updateerprecord] llmwithtools = llm.bindtools(tools) def reasoningnode(state: AgentState): """The brain of the graph. Decides what to do next."""
If the system previously hit an error, we inject it into the prompt
if state.get("validationerror"): print(f"[REASONING] Correcting previous error: {state['validationerror']}")
The LLM reads the entire message history and decides the next move
response = llmwithtools.invoke(state["messages"])
Return the new message to be appended to the state
return {"messages": [response]} def executionnode(state: AgentState): """Executes the tool requested by the LLM and handles exceptions.""" lastmessage = state["messages"][-1]
If the LLM didn't call a tool, we do nothing.
if not lastmessage.toolcalls: return {} toolcall = lastmessage.toolcalls[0] action = toolregistry.get(tool_call["name"]) try:
Attempt to execute the enterprise API
result = action.invoke(tool_call["args"])
Success: Return the result as a ToolMessage
return { "messages": [ToolMessage(toolcallid=toolcall["id"], content=str(result))], "validationerror": None # Clear any previous errors } except Exception as e:
FAILURE HANDLING: The API rejected the LLM's payload
print(f"[EXECUTION ERROR] Tool failed: {str(e)}")
We don't crash. We return the error as a ToolMessage so the LLM can read it.
return { "messages": [ToolMessage( toolcallid=toolcall["id"], content=f"Error executing tool: {str(e)}. Please correct your parameters and try again." )], "validationerror": str(e), "retrycount": state.get("retrycount", 0) + 1 } Notice the critical difference in the execution_node‘s except block. In a standard DAG, this exception would terminate the script. In our State Machine, we simply package the error string into a ToolMessage and write it back to the state.
- The Conditional Routing Logic (The Cyclic Edges)
Now that we have our State and our Nodes, we must wire them together. This is where the graph becomes “Cyclic.” After the reasoningnode finishes, the graph must make a decision: Did the LLM output a final answer, or did it request a tool call? After the executionnode finishes, the graph must automatically route backward to the reasoningnode so the LLM can evaluate the result of the tool it just ran. Python from langgraph.graph import StateGraph, END def shouldcontinue(state: AgentState) -> str: """The conditional routing logic.""" last_message = state["messages"][-1]
CIRCUIT BREAKER: Prevent infinite looping
if state.get("retry_count", 0) > 3: print("[ROUTER] Max retries hit. Terminating graph.") return "end"
If the LLM requested a tool, route to the execution node
if lastmessage.toolcalls: return "continue"
If there are no tool calls, the LLM is finished reasoning
return "end"
--- COMPILE THE STATE MACHINE ---
1. Initialize the Graph with our strict schema
workflow = StateGraph(AgentState)
2. Add the nodes
workflow.addnode("reason", reasoningnode) workflow.addnode("execute", executionnode)
3. Define the Entry Point
workflow.setentrypoint("reason")
4. Add the Conditional Edges (The Cycles)
workflow.addconditionaledges( "reason", # Source node should_continue, # The routing function { "continue": "execute", # If true, go to tool execution "end": END # If false, terminate workflow } )
5. Add the Loop Edge (Tool Execution always goes back to Reasoning)
workflow.add_edge("execute", "reason")
Compile into a runnable application
app = workflow.compile()
- Why This Changes Everything for Enterprise Infrastructure
When you compile this graph, you have built something profoundly resilient. Let’s look at a real-world scenario: The agent is tasked with pulling a vendor’s tax ID. The LLM hallucinates and passes "vendorname": "Acme Corp" to your internal API, but your API strictly requires "vendorid": "V-1234". Cycle 1: The reasoning_node generates the bad payload.
The graph routes to the executionnode. The API throws a 400 Bad Request: Missing vendorid. The executionnode catches the 400 error, writes it to the AgentState, and increments the retrycount. The Graph Loops: The edge workflow.add_edge("execute", "reason") forces the state back to the LLM. Cycle 2: The LLM reads the history.
It sees its previous attempt, and it sees the 400 error message. It says, “Ah, my mistake. I need to query the vendor index to find the ID first.” It calls the searchvendorindex tool. The graph routes back to the execution_node.
The index query succeeds. The Graph Loops Again: Back to the LLM, which now has the correct ID, makes the correct API call, and exits the graph cleanly. This is true autonomy. Conclusion: Escaping the Demo Trap The transition from DAGs to State Machines is the hardest conceptual hurdle for engineering teams adopting AI.
It requires moving away from imperative scripting (telling the code exactly what to do) and toward declarative orchestration (giving the code an objective, a set of tools, and a boundary of state). If you are building your orchestrator with standard chains, you are building technical debt. You are building systems that require pristine inputs and perfect LLM behavior—neither of which exist in the real world.
By defining strict Pydantic states, implementing self-healing execution nodes, and wiring cyclic conditional edges via LangGraph, you stop building brittle scripts. You start building resilient enterprise swarms. Thanks for reading! Subscribe for free to receive new posts and support my work.