Home/Agentic AI/State Machines/Guards & Actions

State Machines for Agents

Build reliable, predictable agent behavior with finite state machines

Guards & Actions

Guards are conditions that must be true for a transition to occur, while actions are side effects that execute when entering/exiting states or during transitions. Together, they add conditional logic and behavior to your state machines.

Interactive: Guard & Action Simulator

Toggle the guards on/off and try transitioning between states. Watch how guards block invalid transitions and actions execute when transitions succeed.

GUARD CONDITIONS

CURRENT STATE

IDLE
ACTION LOG:
No actions yet. Try transitioning between states...

Guard Conditions

Boolean Functions
Guards return true/false to allow/block transitions
guard: (context) => context.isReady
Context Access
Guards can check any state data/context
guard: (ctx) => ctx.retries < 3
Pure Functions
Guards should have no side effects
No API calls, no state mutations

Action Types

Entry Actions
Execute when entering a state (initialization)
Exit Actions
Execute when leaving a state (cleanup)
Transition Actions
Execute during specific transitions

Code Example

const taskMachine = {
  initial: 'idle',
  states: {
    idle: {
      on: {
        START: {
          target: 'running',
          guard: (ctx) => ctx.hasAuth && ctx.hasResources,
          actions: ['initializeTask', 'logStart']
        }
      }
    },
    running: {
      entry: ['allocateResources'],
      exit: ['saveProgress'],
      on: {
        COMPLETE: {
          target: 'done',
          actions: ['finalizeTask']
        },
        ERROR: {
          target: 'failed',
          guard: (ctx) => ctx.retries < 3,
          actions: ['logError', 'incrementRetry']
        }
      }
    },
    done: {
      type: 'final',
      entry: ['cleanup', 'notifyCompletion']
    },
    failed: {
      type: 'final',
      entry: ['cleanup', 'notifyFailure']
    }
  }
}

💡 Key Insight

Guards protect state integrity, actions enable behavior. Think of guards as the "bouncers" that decide who gets in, and actions as the "events" that happen when transitions occur. Well-designed guards prevent invalid states, while well-placed actions ensure proper initialization and cleanup. Together, they make state machines powerful enough for real-world agent workflows.