The @action Decorator
Use the@action decorator to mark a function as an action that can be called from Colang flows.
Basic Action
Fromnemoguardrails/actions/core.py:
Action Decorator Parameters
boolean
default:"False"
Flag indicating if the action is a system action (internal to NeMo Guardrails)
string
Custom name for the action. If not provided, uses the function name
boolean
default:"False"
Whether the function should be executed in async mode
function
A function to interpret the action’s result. Accepts the return value and returns True if the output is not safe
ActionResult Class
Actions can return anActionResult object to provide more control over the execution flow.
any
The value returned by the action
list[dict]
Events to be added to the event stream
dict
Updates made to the context by this action
Example: Wolfram Alpha Integration
Fromnemoguardrails/actions/math.py:
Creating Custom Actions
1
Create actions.py
Create an
actions.py file in your configuration directory:2
Define Your Action
3
Call from Colang
Reference the action in your
.co files:Action Patterns
- Simple Return Value
- With Context Updates
- With Events
- External API Call
Accessing Context
Thecontext parameter provides access to the conversation state:
Error Handling
Best Practices
1
Use Async Functions
Always use
async def for actions, even if they don’t make async calls2
Include Type Hints
Use type hints for better code clarity and IDE support
3
Document Your Actions
Include docstrings explaining parameters and return values
4
Handle None Context
Always check if context is None before accessing it
Registering Actions
Actions inactions.py are automatically registered when the configuration is loaded. No additional registration is needed.
Testing Actions
- Direct Testing
- Integration Testing
Next Steps
Rails Definition
Learn how to call actions from Colang flows
Guardrails Library
Explore built-in actions and rails