State Machines for Agents
Build reliable, predictable agent behavior with finite state machines
Your Progress
0 / 5 completedGuards & 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
Guard Conditions
Action Types
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.