Module 14 Lesson 2: Finite State Machines (FSMs)
Old school intelligence. Learning how to define states, transitions, and triggers to create unshakeable logic.
Finite State Machines: The Unshakeable Map
Before we had LLMs, we had Finite State Machines (FSMs). An FSM is a mathematical model of computation. It is "Finite" because it has a specific, limited number of states. It can only be in one state at a time.
1. The Components of an FSM
- States: The possible situations (e.g.,
OPEN,CLOSED,PENDING). - Transitions: The paths between states.
- Triggers: The events that cause a transition.
- Actions: What happens during or after a transition.
2. Why FSMs are a Superpower for Agents
In a standard agent loop, the LLM can "forget" where it is. It might try to "Update an Order" before it has "Verified the User."
In an FSM-governed agent, this is physically impossible. The code simply won't allow the transition to the UPDATE state unless the current state is VERIFIED.
3. Visualizing a State Machine
stateDiagram-v2
[*] --> GUEST
GUEST --> LOGGED_IN : provide_credentials
LOGGED_IN --> CHECKOUT : add_to_cart
CHECKOUT --> PAID : process_payment
PAID --> [*]
LOGGED_IN --> GUEST : logout
CHECKOUT --> LOGGED_IN : cancel
Notice:
There is no arrow from GUEST to PAID. The model cannot "Hallucinate" its way into skipping the login or checkout steps.
4. Code Concept (Python transitions library)
You don't have to build FSMs from scratch. Libraries like transitions handle the logic for you.
from transitions import Machine
class AgentOrderFlow:
states = ['new', 'authenticated', 'paid']
def __init__(self):
self.machine = Machine(model=self, states=AgentOrderFlow.states, initial='new')
self.machine.add_transition('login', 'new', 'authenticated')
self.machine.add_transition('pay', 'authenticated', 'paid')
flow = AgentOrderFlow()
# flow.pay() -> This will raise an error because we are in 'new' state!
5. FSM vs. LangGraph
You might notice that FSMs look like LangGraph. They are cousins!
- LangGraph: Focused on "Graph" flow where the LLM decides the path.
- FSM: Focused on "Constraint" flow where the Code decides the path.
In a hybrid system, we use an FSM to restrict the LangGraph.
Key Takeaways
- FSMs provide deterministic logic that LLMs cannot break.
- States represent Stages of a process.
- Transitions represent Legal moves between stages.
- Combining FSMs with agents creates Fail-Safe AI systems.