自定义 dispatcher
时间: 2024-04-18 22:33:01 浏览: 16
您可以使用Rasa的自定义dispatcher来处理对话中的不同动作。dispatcher是一个用于发送消息和执行动作的对象。
首先,您需要创建一个自定义的dispatcher类。您可以将以下代码添加到您的Rasa项目的`actions.py`文件中:
```python
from rasa_sdk import Action
from rasa_sdk.executor import CollectingDispatcher
class CustomDispatcher(CollectingDispatcher):
def __init__(
self,
sender_id: Text,
output_channel: Optional["OutputChannel"] = None,
nlg: Optional["NaturalLanguageGenerator"] = None,
tracker_store: Optional["TrackerStore"] = None,
domain: Optional["Domain"] = None,
) -> None:
super().__init__(sender_id, output_channel, nlg, tracker_store, domain)
def utter_message(self, text: Text) -> None:
# 在这里自定义消息发送的方式
# 您可以在这里修改消息的格式、发送给不同的渠道等等
# 例如,您可以在这里将消息发送给特定的API,或者将消息存储到数据库中等等
print(f"CustomDispatcher: {text}")
class MyCustomAction(Action):
def name(self) -> Text:
return "action_custom_action"
def run(
self,
dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any],
) -> List[Dict[Text, Any]]:
dispatcher.utter_message("Hello from custom action!")
return []
```
然后,您需要在您的`endpoints.yml`文件中指定自定义dispatcher类。在`action_endpoint`下添加以下配置:
```yaml
action_endpoint:
url: "http://localhost:5055/webhook"
dispatcher: "actions.CustomDispatcher"
```
最后,您可以在您的对话流程中使用自定义的dispatcher。例如,在您的对话流程中使用自定义动作的话,您可以创建一个包含以下内容的故事文件(`stories.yml`):
```yaml
- story: Custom action test
steps:
- intent: greet
- action: action_custom_action
```
当您运行Rasa服务时,您将看到来自自定义dispatcher的输出,例如`CustomDispatcher: Hello from custom action!`。
通过自定义dispatcher,您可以根据自己的需求对消息进行定制化处理。您可以根据需要修改消息格式、发送到不同的渠道或存储到数据库中等等。