Python Actions#

使用 Action 部分,您已经了解了如何在 UMIM 事件的上下文中使用 Action。此外,您还可以使用 Action 概念来调用自定义 Python 函数,这些函数在 actions.py 文件或 action 子文件夹中的任何 Python 文件中被装饰为 Action。如果您需要 Colang 无法实现的更复杂的功能,这将特别有用。请注意,所有 Python Action 都将在 Colang 解释器的上下文中运行。

这是一个 Python Action 定义的示例

from nemoguardrails.actions import action

@action(name="CustomTestAction")
async def custom_test(value: int):
    # Complicated calculation based on parameter value
    return result

以下是如何从 Colang flow 中调用它

flow main
    $result = await CustomTestAction(value=5)
    bot say "The result is: {$result}"

请注意,Python Action 默认是阻塞的。这意味着如果 Action 实现了长时间运行的任务(例如 REST API 请求),您将需要使 Python Action 异步。您可以通过将参数 execute_async=True 添加到函数装饰器来实现这一点

from nemoguardrails.actions import action

@action(name="CustomAsyncTestAction", execute_async=True)
async def custom_test(value: int):
    # Something that takes time, e.g. a REST API request
    return value

以下是如何从 Colang flow 中调用它

flow main
    # Option 1 start the action and let your flow continue until you really need the result from the action
    start CustomTestAction(value=5) as $action_ref
    # Some other statements ...
    match $action_ref.Finished() as $event_ref
    bot say "The result is: {$event_ref.return_value}" # Access the function return value via the event reference

    # Option 2: You can still use async Python actions like you would use any other action (the same as for non async Python actions)
    $result = await CustomTestAction(value=5)
    bot say "The result is: {$result}"

注意

所有 Python Action 名称都需要以 Action 结尾。

除了所有自定义用户定义的参数外,Python Action 中还提供以下列出的参数。要在您的 Python Action 实现中使用这些参数,请将该参数添加到您的函数签名中。

events: list # Recent history of events
context: dict # Contains all global variables and can be updated via ContextUpdate event
config: dict # All configurations from the `config.yml` file
llm_task_manager: LLMTaskManager # The llm task manage object of type LLMTaskManager
state: State # The state machine state object