Python Action#
在使用 Action一节中,您已经了解了如何在 UMIM 事件的上下文中使用 Action。此外,您还可以使用 Action 概念调用在 actions.py
文件中或 action
子文件夹中的任何 Python 文件中被装饰为 Action 的自定义 Python 函数。如果您需要更复杂的无法在 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 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 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