Skip to main content

Action Decorator

The @action decorator is used to mark functions or classes as actions that can be called from Colang flows.

action

def action(
    is_system_action: bool = False,
    name: Optional[str] = None,
    execute_async: bool = False,
    output_mapping: Optional[Callable[[Any], bool]] = None
) -> Callable[[T], T]
is_system_action
bool
default:"False"
Flag indicating if the action is a system action.
name
Optional[str]
The name to associate with the action. If not provided, uses the function name.
execute_async
bool
default:"False"
Whether the function should be executed in async mode.
output_mapping
Optional[Callable[[Any], bool]]
A function to interpret the action’s result. It accepts the return value and returns True if the output is not safe.
from nemoguardrails.actions import action

@action()
def get_weather(city: str) -> str:
    """Get weather information for a city."""
    return f"The weather in {city} is sunny."

ActionResult

Data class representing the result of an action execution.
@dataclass
class ActionResult:
    return_value: Optional[Any] = None
    events: Optional[List[dict]] = None
    context_updates: Optional[dict] = field(default_factory=dict)
return_value
Optional[Any]
The value returned by the action.
events
Optional[List[dict]]
The events that should be added to the event stream.
context_updates
Optional[dict]
Updates made to the context by this action.
from nemoguardrails.actions import action, ActionResult

@action()
def process_order(order_id: str) -> ActionResult:
    """Process an order and update context."""
    # Process the order
    status = "completed"
    
    return ActionResult(
        return_value={"order_id": order_id, "status": status},
        events=[{"type": "OrderProcessed", "order_id": order_id}],
        context_updates={"last_order_id": order_id}
    )

Action Parameters

Actions can access various parameters automatically injected by the runtime:
context
dict
The current context dictionary containing variables.
llm
BaseLLM
The main LLM instance.
config
RailsConfig
The rails configuration object.
kb
KnowledgeBase
The knowledge base instance (if configured).
from nemoguardrails.actions import action
from nemoguardrails import RailsConfig

@action()
def custom_search(query: str, context: dict, kb, config: RailsConfig) -> str:
    """Search knowledge base with context awareness."""
    user_name = context.get("user_name", "User")
    
    # Search the knowledge base
    results = kb.search(query, max_results=config.custom_data.get("max_results", 5))
    
    return f"Hello {user_name}, here are the results: {results}"

Registering Actions

Actions can be registered with the LLMRails instance:
from nemoguardrails import RailsConfig, LLMRails
from nemoguardrails.actions import action

@action()
def my_custom_action(param: str) -> str:
    return f"Processed: {param}"

config = RailsConfig.from_path("config")
rails = LLMRails(config)

rails.register_action(my_custom_action)

Using Actions in Colang

Once registered, actions can be called from Colang flows:
define flow handle weather query
  user expressed interest in weather
  $city = "New York"
  $weather = execute get_weather(city=$city)
  bot $weather

Best Practices

  1. Use Type Hints: Always use type hints for action parameters and return values
  2. Handle Errors: Use try-except blocks to handle potential errors gracefully
  3. Return ActionResult: Use ActionResult when you need to update context or emit events
  4. Async When Needed: Use execute_async=True for I/O-bound operations
  5. Document Actions: Provide clear docstrings explaining what the action does

Build docs developers (and LLMs) love