Guards and Conditional Transitions
What You'll Learn
You'll learn how to implement guards that inspect LLM outputs, context conditions, or external signals to control when state machines allow or block transitions—making your AI agents smarter and safer.
Why Guards Matter
In a state machine, a guard is a boolean condition that must be satisfied before a transition fires. Think of guards as security checkpoints: even if an event occurs, the state won't change unless the guard "approves" it.
Without guards, your AI agent might transition from "researching" to "responding" even if the LLM hallucinated, the context is incomplete, or an external API failed. Guards prevent these premature or unsafe transitions.
How Guards Work
When an event triggers a potential transition, the state machine evaluates the guard function first:
- If the guard returns
true: transition proceeds - If the guard returns
false: transition is blocked; the system stays in the current state
Guards can inspect:
- LLM outputs: check for confidence scores, length, or presence of key information
- Context conditions: verify user authentication, token budget, or conversation history
- External signals: confirm API success, database availability, or rate limits
Common Guard Patterns
- Quality gates: Only transition if LLM response meets quality thresholds (e.g., no hallucination markers, sufficient detail)
- Budget checks: Block transitions if token count exceeds limits
- Validation guards: Ensure structured outputs match expected schemas
- Safety filters: Prevent transitions if content moderation flags appear
- External readiness: Verify third-party services are available before proceeding
Practical Example (Conceptual)
Imagine an agent in state "awaiting_user_input". An event "user_message_received" arrives. Before transitioning to "generating_response", a guard checks:
- Is the message non-empty?
- Does the user have remaining credits?
- Is the content safe?
Only if all checks pass does the transition occur.
Key Takeaway: Guards transform state machines from rigid flowcharts into intelligent control structures that adapt to real-world conditions, making your AI workflows more robust and production-ready.