Python Actions

使用 Actions 章节中,您已经了解了如何在 UMIM 事件的上下文中使用 actions。此外,您还可以使用 action 概念来调用自定义 python 函数,这些函数在文件 actions.py 或子文件夹 action 中的任何 python 文件中被装饰为 actions。如果您需要 Colang 无法完成的更复杂的功能,这将特别有用。请注意,所有 python actions 都将在 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}"

或者,如果您需要异步函数,您可以像这样定义它

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
    start CustomTestAction(value=5) as $action_ref
    # Some other statements ...
    await $action_ref.Finished() as $event_ref
    bot say "The result is: {$event_ref.return_value}" # Access the function return value via the event reference

注意

所有 Python action 名称都需要以 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