Python 操作#

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

这是一个此类 Python 操作定义的示例

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 操作默认是阻塞的。这意味着如果操作实现了一个长时间运行的任务(例如 REST API 请求),您将需要使 Python 操作异步。您可以通过将参数 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 结尾。

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

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