Creating Custom Actions
This section describes how to create custom actions in the actions.py file.
The @action Decorator
Use the @action decorator from nemoguardrails.actions to define custom actions:
Decorator Parameters
Custom Action Name
Override the default action name:
Call from Colang:
System Actions
When is_system_action=True, the action always runs locally, even when an actions_server_url is configured. This is important for actions that need access to special parameters like context, llm, config, and events, which are only injected for locally-run actions.
When no actions_server_url is configured, all actions run locally and receive special parameters regardless of the is_system_action setting. The flag only affects behavior when an actions server is in use.
Async Execution
When execute_async=True, the event processing loop does not wait for the action to complete before continuing. The action runs in the background and the result is picked up later via polling. This is useful for long-running operations where you don’t need the result immediately.
This flag is only supported in the Colang 2.x runtime. In the Colang 1.0 runtime, it is stored in metadata but has no effect.
Output Mapping
The output_mapping parameter controls how the action’s return value is interpreted to determine if output should be blocked. It accepts a callable that takes the return value and returns True if the output is not safe (should be blocked).
When no output_mapping is provided, the default behavior is:
- Boolean results:
Truemeans allowed,Falsemeans blocked - Numeric results: Values below
0.5are blocked - Other types: Allowed by default
You can also define a custom mapping function for more complex logic:
Function Parameters
Actions can accept parameters of the following types:
Basic Parameters
Call from Colang:
Optional Parameters with Defaults
Return Values
Actions can return various types:
Simple Return
Dictionary Return
Boolean Return (for validation)
Error Handling
Handle errors gracefully within actions:
Example Actions
Input Validation Action
Output Filtering Action
External API Action
Related Topics
- Built-in Actions - Default actions in the library
- Action Parameters - Special parameters provided automatically
- Registering Actions - Different ways to register actions