-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
Copy pathaction.py
1410 lines (1154 loc) · 47.1 KB
/
action.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import copy
import json
import logging
from typing import (
List,
Text,
Optional,
Dict,
Any,
TYPE_CHECKING,
Tuple,
Set,
cast,
)
import aiohttp
import rasa.core
from rasa.core.actions.constants import DEFAULT_SELECTIVE_DOMAIN, SELECTIVE_DOMAIN
from rasa.core.constants import (
DEFAULT_REQUEST_TIMEOUT,
COMPRESS_ACTION_SERVER_REQUEST_ENV_NAME,
DEFAULT_COMPRESS_ACTION_SERVER_REQUEST,
)
from rasa.core.policies.policy import PolicyPrediction
from rasa.nlu.constants import (
RESPONSE_SELECTOR_DEFAULT_INTENT,
RESPONSE_SELECTOR_PROPERTY_NAME,
RESPONSE_SELECTOR_PREDICTION_KEY,
RESPONSE_SELECTOR_UTTER_ACTION_KEY,
)
from rasa.plugin import plugin_manager
from rasa.shared.constants import (
DOCS_BASE_URL,
DEFAULT_NLU_FALLBACK_INTENT_NAME,
UTTER_PREFIX,
)
from rasa.shared.core import events
from rasa.shared.core.constants import (
USER_INTENT_OUT_OF_SCOPE,
ACTION_LISTEN_NAME,
ACTION_RESTART_NAME,
ACTION_SEND_TEXT_NAME,
ACTION_SESSION_START_NAME,
ACTION_DEFAULT_FALLBACK_NAME,
ACTION_DEACTIVATE_LOOP_NAME,
ACTION_REVERT_FALLBACK_EVENTS_NAME,
ACTION_DEFAULT_ASK_AFFIRMATION_NAME,
ACTION_DEFAULT_ASK_REPHRASE_NAME,
ACTION_UNLIKELY_INTENT_NAME,
ACTION_BACK_NAME,
REQUESTED_SLOT,
ACTION_EXTRACT_SLOTS,
DEFAULT_SLOT_NAMES,
MAPPING_CONDITIONS,
ACTIVE_LOOP,
ACTION_VALIDATE_SLOT_MAPPINGS,
MAPPING_TYPE,
SlotMappingType,
)
from rasa.shared.core.domain import Domain
from rasa.shared.core.events import (
UserUtteranceReverted,
UserUttered,
ActionExecuted,
Event,
BotUttered,
SlotSet,
ActiveLoop,
Restarted,
SessionStarted,
)
from rasa.shared.core.slot_mappings import SlotMapping
from rasa.shared.core.slots import ListSlot
from rasa.shared.core.trackers import DialogueStateTracker
from rasa.shared.exceptions import RasaException
from rasa.shared.nlu.constants import (
INTENT_NAME_KEY,
INTENT_RANKING_KEY,
ENTITY_ATTRIBUTE_TYPE,
ENTITY_ATTRIBUTE_ROLE,
ENTITY_ATTRIBUTE_GROUP,
)
from rasa.shared.utils.schemas.events import EVENTS_SCHEMA
import rasa.shared.utils.io
from rasa.utils.common import get_bool_env_variable
from rasa.utils.endpoints import EndpointConfig, ClientResponseError
if TYPE_CHECKING:
from rasa.core.nlg import NaturalLanguageGenerator
from rasa.core.channels.channel import OutputChannel
from rasa.shared.core.events import IntentPrediction
logger = logging.getLogger(__name__)
def default_actions(action_endpoint: Optional[EndpointConfig] = None) -> List["Action"]:
"""List default actions."""
from rasa.core.actions.two_stage_fallback import TwoStageFallbackAction
return [
ActionListen(),
ActionRestart(),
ActionSessionStart(),
ActionDefaultFallback(),
ActionDeactivateLoop(),
ActionRevertFallbackEvents(),
ActionDefaultAskAffirmation(),
ActionDefaultAskRephrase(),
TwoStageFallbackAction(action_endpoint),
ActionUnlikelyIntent(),
ActionSendText(),
ActionBack(),
ActionExtractSlots(action_endpoint),
]
def action_for_index(
index: int, domain: Domain, action_endpoint: Optional[EndpointConfig]
) -> "Action":
"""Get an action based on its index in the list of available actions.
Args:
index: The index of the action. This is usually used by `Policy`s as they
predict the action index instead of the name.
domain: The `Domain` of the current model. The domain contains the actions
provided by the user + the default actions.
action_endpoint: Can be used to run `custom_actions`
(e.g. using the `rasa-sdk`).
Returns:
The instantiated `Action` or `None` if no `Action` was found for the given
index.
"""
if domain.num_actions <= index or index < 0:
raise IndexError(
f"Cannot access action at index {index}. "
f"Domain has {domain.num_actions} actions."
)
return action_for_name_or_text(
domain.action_names_or_texts[index], domain, action_endpoint
)
def is_retrieval_action(action_name: Text, retrieval_intents: List[Text]) -> bool:
"""Check if an action name is a retrieval action.
The name for a retrieval action has an extra `utter_` prefix added to
the corresponding retrieval intent name.
Args:
action_name: Name of the action.
retrieval_intents: List of retrieval intents defined in the NLU training data.
Returns:
`True` if the resolved intent name is present in the list of retrieval
intents, `False` otherwise.
"""
return (
ActionRetrieveResponse.intent_name_from_action(action_name) in retrieval_intents
)
def action_for_name_or_text(
action_name_or_text: Text, domain: Domain, action_endpoint: Optional[EndpointConfig]
) -> "Action":
"""Retrieves an action by its name or by its text in case it's an end-to-end action.
Args:
action_name_or_text: The name of the action.
domain: The current model domain.
action_endpoint: The endpoint to execute custom actions.
Raises:
ActionNotFoundException: If action not in current domain.
Returns:
The instantiated action.
"""
if action_name_or_text not in domain.action_names_or_texts:
domain.raise_action_not_found_exception(action_name_or_text)
defaults = {a.name(): a for a in default_actions(action_endpoint)}
if (
action_name_or_text in defaults
and action_name_or_text not in domain.user_actions_and_forms
):
return defaults[action_name_or_text]
if action_name_or_text.startswith(UTTER_PREFIX) and is_retrieval_action(
action_name_or_text, domain.retrieval_intents
):
return ActionRetrieveResponse(action_name_or_text)
if action_name_or_text in domain.action_texts:
return ActionEndToEndResponse(action_name_or_text)
if action_name_or_text.startswith(UTTER_PREFIX):
return ActionBotResponse(action_name_or_text)
is_form = action_name_or_text in domain.form_names
# Users can override the form by defining an action with the same name as the form
user_overrode_form_action = is_form and action_name_or_text in domain.user_actions
if is_form and not user_overrode_form_action:
from rasa.core.actions.forms import FormAction
return FormAction(action_name_or_text, action_endpoint)
return RemoteAction(action_name_or_text, action_endpoint)
def create_bot_utterance(message: Dict[Text, Any]) -> BotUttered:
"""Create BotUttered event from message."""
bot_message = BotUttered(
text=message.pop("text", None),
data={
"elements": message.pop("elements", None),
"quick_replies": message.pop("quick_replies", None),
"buttons": message.pop("buttons", None),
# for legacy / compatibility reasons we need to set the image
# to be the attachment if there is no other attachment (the
# `.get` is intentional - no `pop` as we still need the image`
# property to set it in the following line)
"attachment": message.pop("attachment", None) or message.get("image", None),
"image": message.pop("image", None),
"custom": message.pop("custom", None),
},
metadata=message,
)
return bot_message
class Action:
"""Next action to be taken in response to a dialogue state."""
def name(self) -> Text:
"""Unique identifier of this simple action."""
raise NotImplementedError
async def run(
self,
output_channel: "OutputChannel",
nlg: "NaturalLanguageGenerator",
tracker: "DialogueStateTracker",
domain: "Domain",
metadata: Optional[Dict[Text, Any]] = None,
) -> List[Event]:
"""Execute the side effects of this action.
Args:
nlg: which ``nlg`` to use for response generation
output_channel: ``output_channel`` to which to send the resulting message.
tracker (DialogueStateTracker): the state tracker for the current
user. You can access slot values using
``tracker.get_slot(slot_name)`` and the most recent user
message is ``tracker.latest_message.text``.
domain (Domain): the bot's domain
Returns:
A list of :class:`rasa.core.events.Event` instances
"""
raise NotImplementedError
def __str__(self) -> Text:
"""Returns text representation of form."""
return f"{self.__class__.__name__}('{self.name()}')"
def event_for_successful_execution(
self, prediction: PolicyPrediction
) -> ActionExecuted:
"""Event which should be logged for the successful execution of this action.
Args:
prediction: Prediction which led to the execution of this event.
Returns:
Event which should be logged onto the tracker.
"""
return ActionExecuted(
self.name(),
prediction.policy_name,
prediction.max_confidence,
hide_rule_turn=prediction.hide_rule_turn,
metadata=prediction.action_metadata,
)
class ActionBotResponse(Action):
"""An action which only effect is to utter a response when it is run."""
def __init__(self, name: Text, silent_fail: Optional[bool] = False) -> None:
"""Creates action.
Args:
name: Name of the action.
silent_fail: `True` if the action should fail silently in case no response
was defined for this action.
"""
self.utter_action = name
self.silent_fail = silent_fail
async def run(
self,
output_channel: "OutputChannel",
nlg: "NaturalLanguageGenerator",
tracker: "DialogueStateTracker",
domain: "Domain",
metadata: Optional[Dict[Text, Any]] = None,
) -> List[Event]:
"""Simple run implementation uttering a (hopefully defined) response."""
kwargs = {
"domain_responses": domain.responses,
}
message = await nlg.generate(
self.utter_action,
tracker,
output_channel.name(),
**kwargs,
)
if message is None:
if not self.silent_fail:
logger.error(
"Couldn't create message for response '{}'."
"".format(self.utter_action)
)
return []
message["utter_action"] = self.utter_action
return [create_bot_utterance(message)]
def name(self) -> Text:
"""Returns action name."""
return self.utter_action
class ActionEndToEndResponse(Action):
"""Action to utter end-to-end responses to the user."""
def __init__(self, action_text: Text) -> None:
"""Creates action.
Args:
action_text: Text of end-to-end bot response.
"""
self.action_text = action_text
def name(self) -> Text:
"""Returns action name."""
# In case of an end-to-end action there is no label (aka name) for the action.
# We fake a name by returning the text which the bot sends back to the user.
return self.action_text
async def run(
self,
output_channel: "OutputChannel",
nlg: "NaturalLanguageGenerator",
tracker: "DialogueStateTracker",
domain: "Domain",
metadata: Optional[Dict[Text, Any]] = None,
) -> List[Event]:
"""Runs action (see parent class for full docstring)."""
message = {"text": self.action_text}
return [create_bot_utterance(message)]
def event_for_successful_execution(
self, prediction: PolicyPrediction
) -> ActionExecuted:
"""Event which should be logged for the successful execution of this action.
Args:
prediction: Prediction which led to the execution of this event.
Returns:
Event which should be logged onto the tracker.
"""
return ActionExecuted(
policy=prediction.policy_name,
confidence=prediction.max_confidence,
action_text=self.action_text,
hide_rule_turn=prediction.hide_rule_turn,
metadata=prediction.action_metadata,
)
class ActionRetrieveResponse(ActionBotResponse):
"""An action which queries the Response Selector for the appropriate response."""
def __init__(self, name: Text, silent_fail: Optional[bool] = False) -> None:
"""Creates action. See docstring of parent class."""
super().__init__(name, silent_fail)
self.action_name = name
self.silent_fail = silent_fail
@staticmethod
def intent_name_from_action(action_name: Text) -> Text:
"""Resolve the name of the intent from the action name."""
return action_name.split(UTTER_PREFIX)[1]
def get_full_retrieval_name(
self, tracker: "DialogueStateTracker"
) -> Optional[Text]:
"""Returns full retrieval name for the action.
Extracts retrieval intent from response selector and
returns complete action utterance name.
Args:
tracker: Tracker containing past conversation events.
Returns:
Full retrieval name of the action if the last user utterance
contains a response selector output, `None` otherwise.
"""
latest_message = tracker.latest_message
if latest_message is None:
return None
if RESPONSE_SELECTOR_PROPERTY_NAME not in latest_message.parse_data:
return None
response_selector_properties = latest_message.parse_data[
RESPONSE_SELECTOR_PROPERTY_NAME # type: ignore[literal-required]
]
if (
self.intent_name_from_action(self.action_name)
in response_selector_properties
):
query_key = self.intent_name_from_action(self.action_name)
elif RESPONSE_SELECTOR_DEFAULT_INTENT in response_selector_properties:
query_key = RESPONSE_SELECTOR_DEFAULT_INTENT
else:
return None
selected = response_selector_properties[query_key]
full_retrieval_utter_action = selected[RESPONSE_SELECTOR_PREDICTION_KEY][
RESPONSE_SELECTOR_UTTER_ACTION_KEY
]
return full_retrieval_utter_action
async def run(
self,
output_channel: "OutputChannel",
nlg: "NaturalLanguageGenerator",
tracker: "DialogueStateTracker",
domain: "Domain",
metadata: Optional[Dict[Text, Any]] = None,
) -> List[Event]:
"""Query the appropriate response and create a bot utterance with that."""
latest_message = tracker.latest_message
if latest_message is None:
return []
response_selector_properties = latest_message.parse_data[
RESPONSE_SELECTOR_PROPERTY_NAME # type: ignore[literal-required]
]
if (
self.intent_name_from_action(self.action_name)
in response_selector_properties
):
query_key = self.intent_name_from_action(self.action_name)
elif RESPONSE_SELECTOR_DEFAULT_INTENT in response_selector_properties:
query_key = RESPONSE_SELECTOR_DEFAULT_INTENT
else:
if not self.silent_fail:
logger.error(
"Couldn't create message for response action '{}'."
"".format(self.action_name)
)
return []
logger.debug(f"Picking response from selector of type {query_key}")
selected = response_selector_properties[query_key]
# Override utter action of ActionBotResponse
# with the complete utter action retrieved from
# the output of response selector.
self.utter_action = selected[RESPONSE_SELECTOR_PREDICTION_KEY][
RESPONSE_SELECTOR_UTTER_ACTION_KEY
]
return await super().run(output_channel, nlg, tracker, domain)
def name(self) -> Text:
"""Returns action name."""
return self.action_name
class ActionBack(ActionBotResponse):
"""Revert the tracker state by two user utterances."""
def name(self) -> Text:
"""Returns action back name."""
return ACTION_BACK_NAME
def __init__(self) -> None:
"""Initializes action back."""
super().__init__("utter_back", silent_fail=True)
async def run(
self,
output_channel: "OutputChannel",
nlg: "NaturalLanguageGenerator",
tracker: "DialogueStateTracker",
domain: "Domain",
metadata: Optional[Dict[Text, Any]] = None,
) -> List[Event]:
"""Runs action. Please see parent class for the full docstring."""
# only utter the response if it is available
evts = await super().run(output_channel, nlg, tracker, domain)
return evts + [UserUtteranceReverted(), UserUtteranceReverted()]
class ActionListen(Action):
"""The first action in any turn - bot waits for a user message.
The bot should stop taking further actions and wait for the user to say
something.
"""
def name(self) -> Text:
"""Returns action listen name."""
return ACTION_LISTEN_NAME
async def run(
self,
output_channel: "OutputChannel",
nlg: "NaturalLanguageGenerator",
tracker: "DialogueStateTracker",
domain: "Domain",
metadata: Optional[Dict[Text, Any]] = None,
) -> List[Event]:
"""Runs action. Please see parent class for the full docstring."""
return []
class ActionRestart(ActionBotResponse):
"""Resets the tracker to its initial state.
Utters the restart response if available.
"""
def name(self) -> Text:
"""Returns action restart name."""
return ACTION_RESTART_NAME
def __init__(self) -> None:
"""Initializes action restart."""
super().__init__("utter_restart", silent_fail=True)
async def run(
self,
output_channel: "OutputChannel",
nlg: "NaturalLanguageGenerator",
tracker: "DialogueStateTracker",
domain: "Domain",
metadata: Optional[Dict[Text, Any]] = None,
) -> List[Event]:
"""Runs action. Please see parent class for the full docstring."""
# only utter the response if it is available
evts = await super().run(output_channel, nlg, tracker, domain)
return evts + [Restarted()]
class ActionSessionStart(Action):
"""Applies a conversation session start.
Takes all `SlotSet` events from the previous session and applies them to the new
session.
"""
def name(self) -> Text:
"""Returns action start name."""
return ACTION_SESSION_START_NAME
@staticmethod
def _slot_set_events_from_tracker(
tracker: "DialogueStateTracker",
) -> List["SlotSet"]:
"""Fetch SlotSet events from tracker and carry over key, value and metadata."""
return [
SlotSet(key=event.key, value=event.value, metadata=event.metadata)
for event in tracker.applied_events()
if isinstance(event, SlotSet)
]
async def run(
self,
output_channel: "OutputChannel",
nlg: "NaturalLanguageGenerator",
tracker: "DialogueStateTracker",
domain: "Domain",
metadata: Optional[Dict[Text, Any]] = None,
) -> List[Event]:
"""Runs action. Please see parent class for the full docstring."""
_events: List[Event] = [SessionStarted()]
if domain.session_config.carry_over_slots:
_events.extend(self._slot_set_events_from_tracker(tracker))
_events.append(ActionExecuted(ACTION_LISTEN_NAME))
return _events
class ActionDefaultFallback(ActionBotResponse):
"""Executes the fallback action and goes back to the prev state of the dialogue."""
def name(self) -> Text:
"""Returns action default fallback name."""
return ACTION_DEFAULT_FALLBACK_NAME
def __init__(self) -> None:
"""Initializes action default fallback."""
super().__init__("utter_default", silent_fail=True)
async def run(
self,
output_channel: "OutputChannel",
nlg: "NaturalLanguageGenerator",
tracker: "DialogueStateTracker",
domain: "Domain",
metadata: Optional[Dict[Text, Any]] = None,
) -> List[Event]:
"""Runs action. Please see parent class for the full docstring."""
# only utter the response if it is available
evts = await super().run(output_channel, nlg, tracker, domain)
return evts + [UserUtteranceReverted()]
class ActionDeactivateLoop(Action):
"""Deactivates an active loop."""
def name(self) -> Text:
return ACTION_DEACTIVATE_LOOP_NAME
async def run(
self,
output_channel: "OutputChannel",
nlg: "NaturalLanguageGenerator",
tracker: "DialogueStateTracker",
domain: "Domain",
metadata: Optional[Dict[Text, Any]] = None,
) -> List[Event]:
"""Runs action. Please see parent class for the full docstring."""
return [ActiveLoop(None), SlotSet(REQUESTED_SLOT, None)]
class RemoteAction(Action):
def __init__(self, name: Text, action_endpoint: Optional[EndpointConfig]) -> None:
self._name = name
self.action_endpoint = action_endpoint
def _action_call_format(
self,
tracker: "DialogueStateTracker",
domain: "Domain",
) -> Dict[Text, Any]:
"""Create the request json send to the action server."""
from rasa.shared.core.trackers import EventVerbosity
tracker_state = tracker.current_state(EventVerbosity.ALL)
result = {
"next_action": self._name,
"sender_id": tracker.sender_id,
"tracker": tracker_state,
"version": rasa.__version__,
}
if (
not self._is_selective_domain_enabled()
or domain.does_custom_action_explicitly_need_domain(self.name())
):
result["domain"] = domain.as_dict()
return result
def _is_selective_domain_enabled(self) -> bool:
if self.action_endpoint is None:
return False
return bool(
self.action_endpoint.kwargs.get(SELECTIVE_DOMAIN, DEFAULT_SELECTIVE_DOMAIN)
)
@staticmethod
def action_response_format_spec() -> Dict[Text, Any]:
"""Expected response schema for an Action endpoint.
Used for validation of the response returned from the
Action endpoint.
"""
schema = {
"type": "object",
"properties": {
"events": EVENTS_SCHEMA,
"responses": {"type": "array", "items": {"type": "object"}},
},
}
return schema
def _validate_action_result(self, result: Dict[Text, Any]) -> bool:
from jsonschema import validate
from jsonschema import ValidationError
try:
validate(result, self.action_response_format_spec())
return True
except ValidationError as e:
e.message += (
f". Failed to validate Action server response from API, "
f"make sure your response from the Action endpoint is valid. "
f"For more information about the format visit "
f"{DOCS_BASE_URL}/custom-actions"
)
raise e
@staticmethod
async def _utter_responses(
responses: List[Dict[Text, Any]],
output_channel: "OutputChannel",
nlg: "NaturalLanguageGenerator",
tracker: "DialogueStateTracker",
) -> List[BotUttered]:
"""Use the responses generated by the action endpoint and utter them."""
bot_messages = []
for response in responses:
generated_response = response.pop("response", None)
if generated_response:
draft = await nlg.generate(
generated_response, tracker, output_channel.name(), **response
)
if not draft:
continue
draft["utter_action"] = generated_response
else:
draft = {}
buttons = response.pop("buttons", []) or []
if buttons:
draft.setdefault("buttons", [])
draft["buttons"].extend(buttons)
# Avoid overwriting `draft` values with empty values
response = {k: v for k, v in response.items() if v}
draft.update(response)
bot_messages.append(create_bot_utterance(draft))
return bot_messages
async def run(
self,
output_channel: "OutputChannel",
nlg: "NaturalLanguageGenerator",
tracker: "DialogueStateTracker",
domain: "Domain",
metadata: Optional[Dict[Text, Any]] = None,
) -> List[Event]:
"""Runs action. Please see parent class for the full docstring."""
json_body = self._action_call_format(tracker, domain)
if not self.action_endpoint:
raise RasaException(
f"Failed to execute custom action '{self.name()}' "
f"because no endpoint is configured to run this "
f"custom action. Please take a look at "
f"the docs and set an endpoint configuration via the "
f"--endpoints flag. "
f"{DOCS_BASE_URL}/custom-actions"
)
try:
logger.debug(
"Calling action endpoint to run action '{}'.".format(self.name())
)
should_compress = get_bool_env_variable(
COMPRESS_ACTION_SERVER_REQUEST_ENV_NAME,
DEFAULT_COMPRESS_ACTION_SERVER_REQUEST,
)
modified_json = plugin_manager().hook.prefix_stripping_for_custom_actions(
json_body=json_body
)
response: Any = await self.action_endpoint.request(
json=modified_json if modified_json else json_body,
method="post",
timeout=DEFAULT_REQUEST_TIMEOUT,
compress=should_compress,
)
if modified_json:
plugin_manager().hook.prefixing_custom_actions_response(
json_body=json_body, response=response
)
self._validate_action_result(response)
events_json = response.get("events", [])
responses = response.get("responses", [])
bot_messages = await self._utter_responses(
responses, output_channel, nlg, tracker
)
evts = events.deserialise_events(events_json)
return cast(List[Event], bot_messages) + evts
except ClientResponseError as e:
if e.status == 400:
response_data = json.loads(e.text)
exception = ActionExecutionRejection(
response_data["action_name"], response_data.get("error")
)
logger.error(exception.message)
raise exception
else:
raise RasaException(
f"Failed to execute custom action '{self.name()}'"
) from e
except aiohttp.ClientConnectionError as e:
logger.error(
f"Failed to run custom action '{self.name()}'. Couldn't connect "
f"to the server at '{self.action_endpoint.url}'. "
f"Is the server running? "
f"Error: {e}"
)
raise RasaException(
f"Failed to execute custom action '{self.name()}'. Couldn't connect "
f"to the server at '{self.action_endpoint.url}."
)
except aiohttp.ClientError as e:
# not all errors have a status attribute, but
# helpful to log if they got it
# noinspection PyUnresolvedReferences
status = getattr(e, "status", None)
raise RasaException(
"Failed to run custom action '{}'. Action server "
"responded with a non 200 status code of {}. "
"Make sure your action server properly runs actions "
"and returns a 200 once the action is executed. "
"Error: {}".format(self.name(), status, e)
)
def name(self) -> Text:
return self._name
class ActionExecutionRejection(RasaException):
"""Raising this exception will allow other policies
to predict a different action.
"""
def __init__(self, action_name: Text, message: Optional[Text] = None) -> None:
"""Create a new ActionExecutionRejection exception."""
self.action_name = action_name
self.message = message or "Custom action '{}' rejected to run".format(
action_name
)
super(ActionExecutionRejection, self).__init__()
def __str__(self) -> Text:
return self.message
class ActionRevertFallbackEvents(Action):
"""Reverts events which were done during the `TwoStageFallbackPolicy`.
This reverts user messages and bot utterances done during a fallback
of the `TwoStageFallbackPolicy`. By doing so it is not necessary to
write custom stories for the different paths, but only of the happy
path. This is deprecated and can be removed once the
`TwoStageFallbackPolicy` is removed.
"""
def name(self) -> Text:
return ACTION_REVERT_FALLBACK_EVENTS_NAME
async def run(
self,
output_channel: "OutputChannel",
nlg: "NaturalLanguageGenerator",
tracker: "DialogueStateTracker",
domain: "Domain",
metadata: Optional[Dict[Text, Any]] = None,
) -> List[Event]:
"""Runs action. Please see parent class for the full docstring."""
from rasa.core.policies.two_stage_fallback import has_user_rephrased
# User rephrased
if has_user_rephrased(tracker):
return _revert_successful_rephrasing(tracker)
# User affirmed
elif has_user_affirmed(tracker):
return _revert_affirmation_events(tracker)
else:
return []
class ActionUnlikelyIntent(Action):
"""An action that indicates that the intent predicted by NLU is unexpected.
This action can be predicted by `UnexpecTEDIntentPolicy`.
"""
def name(self) -> Text:
"""Returns the name of the action."""
return ACTION_UNLIKELY_INTENT_NAME
async def run(
self,
output_channel: "OutputChannel",
nlg: "NaturalLanguageGenerator",
tracker: "DialogueStateTracker",
domain: "Domain",
metadata: Optional[Dict[Text, Any]] = None,
) -> List[Event]:
"""Runs action. Please see parent class for the full docstring."""
return []
def has_user_affirmed(tracker: "DialogueStateTracker") -> bool:
"""Indicates if the last executed action is `action_default_ask_affirmation`."""
return tracker.last_executed_action_has(ACTION_DEFAULT_ASK_AFFIRMATION_NAME)
def _revert_affirmation_events(tracker: "DialogueStateTracker") -> List[Event]:
revert_events = _revert_single_affirmation_events()
# User affirms the rephrased intent
rephrased_intent = tracker.last_executed_action_has(
name=ACTION_DEFAULT_ASK_REPHRASE_NAME, skip=1
)
if rephrased_intent:
revert_events += _revert_rephrasing_events()
last_user_event = tracker.get_last_event_for(UserUttered)
if not last_user_event:
raise TypeError("Cannot find last event to revert to.")
last_user_event = copy.deepcopy(last_user_event)
# FIXME: better type annotation for `parse_data` would require
# a larger refactoring (e.g. switch to dataclass)
last_user_event.parse_data["intent"]["confidence"] = 1.0 # type: ignore[typeddict-item] # noqa: E501
return revert_events + [last_user_event]
def _revert_single_affirmation_events() -> List[Event]:
return [
UserUtteranceReverted(), # revert affirmation and request
# revert original intent (has to be re-added later)
UserUtteranceReverted(),
# add action listen intent
ActionExecuted(action_name=ACTION_LISTEN_NAME),
]
def _revert_successful_rephrasing(tracker: "DialogueStateTracker") -> List[Event]:
last_user_event = tracker.get_last_event_for(UserUttered)
if not last_user_event:
raise TypeError("Cannot find last event to revert to.")
last_user_event = copy.deepcopy(last_user_event)
return _revert_rephrasing_events() + [last_user_event]
def _revert_rephrasing_events() -> List[Event]:
return [
UserUtteranceReverted(), # remove rephrasing
# remove feedback and rephrase request
UserUtteranceReverted(),
# remove affirmation request and false intent
UserUtteranceReverted(),
# replace action with action listen
ActionExecuted(action_name=ACTION_LISTEN_NAME),
]
class ActionDefaultAskAffirmation(Action):
"""Default implementation which asks the user to affirm his intent.
It is suggested to overwrite this default action with a custom action
to have more meaningful prompts for the affirmations. E.g. have a
description of the intent instead of its identifier name.
"""
def name(self) -> Text:
return ACTION_DEFAULT_ASK_AFFIRMATION_NAME
async def run(
self,