State machines

State machines bring formal rigor to agent behavior. Your agent has defined states (IDLE, PROCESSING, RESPONDING, ERROR), events that trigger transitions, and clear rules about which transitions are valid. This prevents undefined behavior and makes agents predictable.

Agent state machine

A state machine guarantees that only valid transitions happen. With if/else, it is easy to forget an edge case and end up in an undefined state. The transition table acts as a single source of truth for all allowed behavior.

patterns/26_state_machines.py
python
from enum import Enum

class AgentState(Enum):
    IDLE = "idle"
    LISTENING = "listening"
    PROCESSING = "processing"
    RESPONDING = "responding"
    ERROR = "error"
    SLEEPING = "sleeping"

class Event(Enum):
    USER_INPUT = "user_input"
    PROCESSING_COMPLETE = "processing_complete"
    ERROR_OCCURRED = "error_occurred"
    RESET = "reset"

class StateMachine:
    def __init__(self):
        self.state = AgentState.IDLE
        self.transitions = {
            (AgentState.IDLE, Event.USER_INPUT): AgentState.LISTENING,
            (AgentState.LISTENING, Event.USER_INPUT): AgentState.PROCESSING,
            (AgentState.PROCESSING, Event.PROCESSING_COMPLETE): AgentState.RESPONDING,
            (AgentState.PROCESSING, Event.ERROR_OCCURRED): AgentState.ERROR,
            (AgentState.RESPONDING, Event.PROCESSING_COMPLETE): AgentState.IDLE,
            (AgentState.ERROR, Event.RESET): AgentState.IDLE,
        }

    def transition(self, event):
        key = (self.state, event)
        if key not in self.transitions:
            raise ValueError(f"Invalid transition: {self.state} + {event}")
        self.state = self.transitions[key]
        return self.state

Enum-based states, event-driven transitions with validation.

Quiz: Quiz

Loading practice…

Ordering exercise: Order a typical agent state flow

Loading practice…

Flashcards: Flashcards

Loading practice…

State machines make agent behavior predictable and debuggable. Next, we explore recursive agents that solve complex problems by decomposing them into sub-problems.