-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
events.py
1927 lines (1557 loc) 路 61.8 KB
/
events.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 abc
import json
import logging
import re
from abc import ABC
import jsonpickle
import time
import uuid
from dateutil import parser
from datetime import datetime
from typing import (
List,
Dict,
Text,
Any,
Type,
Optional,
TYPE_CHECKING,
Iterable,
cast,
Tuple,
)
import rasa.shared.utils.common
from typing import Union
from rasa.shared.constants import DOCS_URL_TRAINING_DATA
from rasa.shared.core.constants import (
LOOP_NAME,
EXTERNAL_MESSAGE_PREFIX,
ACTION_NAME_SENDER_ID_CONNECTOR_STR,
IS_EXTERNAL,
USE_TEXT_FOR_FEATURIZATION,
LOOP_INTERRUPTED,
ENTITY_LABEL_SEPARATOR,
ACTION_SESSION_START_NAME,
ACTION_LISTEN_NAME,
)
from rasa.shared.exceptions import UnsupportedFeatureException
from rasa.shared.nlu.constants import (
ENTITY_ATTRIBUTE_TYPE,
INTENT,
TEXT,
ENTITIES,
ENTITY_ATTRIBUTE_VALUE,
ACTION_TEXT,
ACTION_NAME,
INTENT_NAME_KEY,
ENTITY_ATTRIBUTE_ROLE,
ENTITY_ATTRIBUTE_GROUP,
PREDICTED_CONFIDENCE_KEY,
INTENT_RANKING_KEY,
ENTITY_ATTRIBUTE_TEXT,
ENTITY_ATTRIBUTE_START,
ENTITY_ATTRIBUTE_CONFIDENCE,
ENTITY_ATTRIBUTE_END,
)
if TYPE_CHECKING:
from typing_extensions import TypedDict
from rasa.shared.core.trackers import DialogueStateTracker
EntityPrediction = TypedDict(
"EntityPrediction",
{
ENTITY_ATTRIBUTE_TEXT: Text,
ENTITY_ATTRIBUTE_START: Optional[float],
ENTITY_ATTRIBUTE_END: Optional[float],
ENTITY_ATTRIBUTE_VALUE: Text,
ENTITY_ATTRIBUTE_CONFIDENCE: float,
ENTITY_ATTRIBUTE_TYPE: Text,
ENTITY_ATTRIBUTE_GROUP: Optional[Text],
ENTITY_ATTRIBUTE_ROLE: Optional[Text],
"additional_info": Any,
},
total=False,
)
IntentPrediction = TypedDict(
"IntentPrediction", {INTENT_NAME_KEY: Text, PREDICTED_CONFIDENCE_KEY: float,},
)
NLUPredictionData = TypedDict(
"NLUPredictionData",
{
INTENT: IntentPrediction,
INTENT_RANKING_KEY: List[IntentPrediction],
ENTITIES: List[EntityPrediction],
"message_id": Optional[Text],
"metadata": Dict,
},
total=False,
)
logger = logging.getLogger(__name__)
def deserialise_events(serialized_events: List[Dict[Text, Any]]) -> List["Event"]:
"""Convert a list of dictionaries to a list of corresponding events.
Example format:
[{"event": "slot", "value": 5, "name": "my_slot"}]
"""
deserialised = []
for e in serialized_events:
if "event" in e:
event = Event.from_parameters(e)
if event:
deserialised.append(event)
else:
logger.warning(
f"Unable to parse event '{event}' while deserialising. The event"
" will be ignored."
)
return deserialised
def deserialise_entities(entities: Union[Text, List[Any]]) -> List[Dict[Text, Any]]:
if isinstance(entities, str):
entities = json.loads(entities)
return [e for e in entities if isinstance(e, dict)]
def format_message(
text: Text, intent: Optional[Text], entities: Union[Text, List[Any]]
) -> Text:
"""Uses NLU parser information to generate a message with inline entity annotations.
Arguments:
text: text of the message
intent: intent of the message
entities: entities of the message
Return:
Message with entities annotated inline, e.g.
`I am from [Berlin]{"entity": "city"}`.
"""
from rasa.shared.nlu.training_data.formats.readerwriter import TrainingDataWriter
from rasa.shared.nlu.training_data import entities_parser
message_from_md = entities_parser.parse_training_example(text, intent)
deserialised_entities = deserialise_entities(entities)
return TrainingDataWriter.generate_message(
{"text": message_from_md.get(TEXT), "entities": deserialised_entities}
)
def split_events(
events: Iterable["Event"],
event_type_to_split_on: Type["Event"],
additional_splitting_conditions: Optional[Dict[Text, Any]] = None,
include_splitting_event: bool = True,
) -> List[List["Event"]]:
"""Splits events according to an event type and condition.
Examples:
Splitting events according to the event type `ActionExecuted` and the
`action_name` 'action_session_start' would look as follows:
>> _events = split_events(
events,
ActionExecuted,
{"action_name": "action_session_start"},
True
)
Args:
events: Events to split.
event_type_to_split_on: The event type to split on.
additional_splitting_conditions: Additional event attributes to split on.
include_splitting_event: Whether the events of the type on which the split
is based should be included in the returned events.
Returns:
The split events.
"""
sub_events = []
current = []
def event_fulfills_splitting_condition(evt: "Event") -> bool:
# event does not have the correct type
if not isinstance(evt, event_type_to_split_on):
return False
# the type is correct and there are no further conditions
if not additional_splitting_conditions:
return True
# there are further conditions - check those
return all(
getattr(evt, k, None) == v
for k, v in additional_splitting_conditions.items()
)
for event in events:
if event_fulfills_splitting_condition(event):
if current:
sub_events.append(current)
current = []
if include_splitting_event:
current.append(event)
else:
current.append(event)
if current:
sub_events.append(current)
return sub_events
def do_events_begin_with_session_start(events: List["Event"]) -> bool:
"""Determines whether `events` begins with a session start sequence.
A session start sequence is a sequence of two events: an executed
`action_session_start` as well as a logged `session_started`.
Args:
events: The events to inspect.
Returns:
Whether or not `events` begins with a session start sequence.
"""
return len(events) > 1 and events[:2] == [
ActionExecuted(ACTION_SESSION_START_NAME),
SessionStarted(),
]
class Event(ABC):
"""Describes events in conversation and how the affect the conversation state.
Immutable representation of everything which happened during a conversation of the
user with the assistant. Tells the `rasa.shared.core.trackers.DialogueStateTracker`
how to update its state as the events occur.
"""
type_name = "event"
def __init__(
self,
timestamp: Optional[float] = None,
metadata: Optional[Dict[Text, Any]] = None,
) -> None:
self.timestamp = timestamp or time.time()
self.metadata = metadata or {}
def __ne__(self, other: Any) -> bool:
# Not strictly necessary, but to avoid having both x==y and x!=y
# True at the same time
return not (self == other)
@abc.abstractmethod
def as_story_string(self) -> Optional[Text]:
"""Returns the event as story string.
Returns:
textual representation of the event or None.
"""
# Every class should implement this
raise NotImplementedError
@staticmethod
def from_story_string(
event_name: Text,
parameters: Dict[Text, Any],
default: Optional[Type["Event"]] = None,
) -> Optional[List["Event"]]:
event_class = Event.resolve_by_type(event_name, default)
if not event_class:
return None
return event_class._from_story_string(parameters)
@staticmethod
def from_parameters(
parameters: Dict[Text, Any], default: Optional[Type["Event"]] = None
) -> Optional["Event"]:
event_name = parameters.get("event")
if event_name is None:
return None
event_class: Optional[Type[Event]] = Event.resolve_by_type(event_name, default)
if not event_class:
return None
return event_class._from_parameters(parameters)
@classmethod
def _from_story_string(cls, parameters: Dict[Text, Any]) -> Optional[List["Event"]]:
"""Called to convert a parsed story line into an event."""
return [cls(parameters.get("timestamp"), parameters.get("metadata"))]
def as_dict(self) -> Dict[Text, Any]:
d = {"event": self.type_name, "timestamp": self.timestamp}
if self.metadata:
d["metadata"] = self.metadata
return d
@classmethod
def _from_parameters(cls, parameters: Dict[Text, Any]) -> Optional["Event"]:
"""Called to convert a dictionary of parameters to a single event.
By default uses the same implementation as the story line
conversation ``_from_story_string``. But the subclass might
decide to handle parameters differently if the parsed parameters
don't origin from a story file."""
result = cls._from_story_string(parameters)
if len(result) > 1:
logger.warning(
f"Event from parameters called with parameters "
f"for multiple events. This is not supported, "
f"only the first event will be returned. "
f"Parameters: {parameters}"
)
return result[0] if result else None
@staticmethod
def resolve_by_type(
type_name: Text, default: Optional[Type["Event"]] = None
) -> Optional[Type["Event"]]:
"""Returns a slots class by its type name."""
for cls in rasa.shared.utils.common.all_subclasses(Event):
if cls.type_name == type_name:
return cls
if type_name == "topic":
return None # backwards compatibility to support old TopicSet evts
elif default is not None:
return default
else:
raise ValueError(f"Unknown event name '{type_name}'.")
def apply_to(self, tracker: "DialogueStateTracker") -> None:
"""Applies event to current conversation state.
Args:
tracker: The current conversation state.
"""
pass
@abc.abstractmethod
def __eq__(self, other: Any) -> bool:
"""Compares object with other object."""
# Every class should implement this
raise NotImplementedError()
def __str__(self) -> Text:
"""Returns text representation of event."""
return f"{self.__class__.__name__}()"
class AlwaysEqualEventMixin(Event, ABC):
"""Class to deduplicate common behavior for events without additional attributes."""
def __eq__(self, other: Any) -> bool:
"""Compares object with other object."""
if not isinstance(other, self.__class__):
return NotImplemented
return True
class SkipEventInMDStoryMixin(Event, ABC):
"""Skips the visualization of an event in Markdown stories."""
def as_story_string(self) -> None:
"""Returns the event as story string.
Returns:
None, as this event should not appear inside the story.
"""
return
class UserUttered(Event):
"""The user has said something to the bot.
As a side effect a new `Turn` will be created in the `Tracker`.
"""
type_name = "user"
def __init__(
self,
text: Optional[Text] = None,
intent: Optional[Dict] = None,
entities: Optional[List[Dict]] = None,
parse_data: Optional["NLUPredictionData"] = None,
timestamp: Optional[float] = None,
input_channel: Optional[Text] = None,
message_id: Optional[Text] = None,
metadata: Optional[Dict] = None,
use_text_for_featurization: Optional[bool] = None,
) -> None:
"""Creates event for incoming user message.
Args:
text: Text of user message.
intent: Intent prediction of user message.
entities: Extracted entities.
parse_data: Detailed NLU parsing result for message.
timestamp: When the event was created.
metadata: Additional event metadata.
input_channel: Which channel the user used to send message.
message_id: Unique ID for message.
use_text_for_featurization: `True` if the message's text was used to predict
next action. `False` if the message's intent was used.
"""
self.text = text
self.intent = intent if intent else {}
self.entities = entities if entities else []
self.input_channel = input_channel
self.message_id = message_id
super().__init__(timestamp, metadata)
# The featurization is set by the policies during prediction time using a
# `DefinePrevUserUtteredFeaturization` event.
self.use_text_for_featurization = use_text_for_featurization
# define how this user utterance should be featurized
if self.text and not self.intent_name:
# happens during training
self.use_text_for_featurization = True
elif self.intent_name and not self.text:
# happens during training
self.use_text_for_featurization = False
self.parse_data: "NLUPredictionData" = {
INTENT: self.intent,
# Copy entities so that changes to `self.entities` don't affect
# `self.parse_data` and hence don't get persisted
ENTITIES: self.entities.copy(),
TEXT: self.text,
"message_id": self.message_id,
"metadata": self.metadata,
}
if parse_data:
self.parse_data.update(**parse_data)
@staticmethod
def _from_parse_data(
text: Text,
parse_data: "NLUPredictionData",
timestamp: Optional[float] = None,
input_channel: Optional[Text] = None,
message_id: Optional[Text] = None,
metadata: Optional[Dict] = None,
) -> "UserUttered":
return UserUttered(
text,
parse_data.get(INTENT),
parse_data.get(ENTITIES, []),
parse_data,
timestamp,
input_channel,
message_id,
metadata,
)
def __hash__(self) -> int:
"""Returns unique hash of object."""
return hash(json.dumps(self.as_sub_state()))
@property
def intent_name(self) -> Optional[Text]:
"""Returns intent name or `None` if no intent."""
return self.intent.get(INTENT_NAME_KEY)
def __eq__(self, other: Any) -> bool:
"""Compares object with other object."""
if not isinstance(other, UserUttered):
return NotImplemented
return (
self.text,
self.intent_name,
[jsonpickle.encode(ent) for ent in self.entities],
) == (
other.text,
other.intent_name,
[jsonpickle.encode(ent) for ent in other.entities],
)
def __str__(self) -> Text:
"""Returns text representation of event."""
entities = ""
if self.entities:
entities = [
f"{entity[ENTITY_ATTRIBUTE_VALUE]} "
f"(Type: {entity[ENTITY_ATTRIBUTE_TYPE]}, "
f"Role: {entity.get(ENTITY_ATTRIBUTE_ROLE)}, "
f"Group: {entity.get(ENTITY_ATTRIBUTE_GROUP)})"
for entity in self.entities
]
entities = f", entities: {', '.join(entities)}"
return (
f"UserUttered(text: {self.text}, intent: {self.intent_name}"
f"{entities}"
f", use_text_for_featurization: {self.use_text_for_featurization})"
)
@staticmethod
def empty() -> "UserUttered":
return UserUttered(None)
def is_empty(self) -> bool:
return not self.text and not self.intent_name and not self.entities
def as_dict(self) -> Dict[Text, Any]:
_dict = super().as_dict()
_dict.update(
{
"text": self.text,
"parse_data": self.parse_data,
"input_channel": getattr(self, "input_channel", None),
"message_id": getattr(self, "message_id", None),
"metadata": self.metadata,
}
)
return _dict
def as_sub_state(self,) -> Dict[Text, Union[None, Text, List[Optional[Text]]]]:
"""Turns a UserUttered event into features.
The substate contains information about entities, intent and text of the
`UserUttered` event.
Returns:
a dictionary with intent name, text and entities
"""
entities = [entity.get(ENTITY_ATTRIBUTE_TYPE) for entity in self.entities]
entities.extend(
(
f"{entity.get(ENTITY_ATTRIBUTE_TYPE)}{ENTITY_LABEL_SEPARATOR}"
f"{entity.get(ENTITY_ATTRIBUTE_ROLE)}"
)
for entity in self.entities
if ENTITY_ATTRIBUTE_ROLE in entity
)
entities.extend(
(
f"{entity.get(ENTITY_ATTRIBUTE_TYPE)}{ENTITY_LABEL_SEPARATOR}"
f"{entity.get(ENTITY_ATTRIBUTE_GROUP)}"
)
for entity in self.entities
if ENTITY_ATTRIBUTE_GROUP in entity
)
out: Dict[Text, Union[None, Text, List[Optional[Text]]]] = {}
# During training we expect either intent_name or text to be set.
# During prediction both will be set.
if self.text and (
self.use_text_for_featurization or self.use_text_for_featurization is None
):
out[TEXT] = self.text
if self.intent_name and not self.use_text_for_featurization:
out[INTENT] = self.intent_name
# don't add entities for e2e utterances
if entities and not self.use_text_for_featurization:
out[ENTITIES] = entities
return out
@classmethod
def _from_story_string(cls, parameters: Dict[Text, Any]) -> Optional[List[Event]]:
try:
return [
cls._from_parse_data(
parameters.get("text"),
parameters.get("parse_data"),
parameters.get("timestamp"),
parameters.get("input_channel"),
parameters.get("message_id"),
parameters.get("metadata"),
)
]
except KeyError as e:
raise ValueError(f"Failed to parse bot uttered event. {e}")
def _entity_string(self) -> Text:
if self.entities:
return json.dumps(
{
entity[ENTITY_ATTRIBUTE_TYPE]: entity[ENTITY_ATTRIBUTE_VALUE]
for entity in self.entities
},
ensure_ascii=False,
)
return ""
def as_story_string(self, e2e: bool = False) -> Text:
"""Return event as string for Markdown training format.
Args:
e2e: `True` if the the event should be printed in the format for
end-to-end conversation tests.
Returns:
Event as string.
"""
if self.use_text_for_featurization and not e2e:
raise UnsupportedFeatureException(
f"Printing end-to-end user utterances is not supported in the "
f"Markdown training format. Please use the YAML training data format "
f"instead. Please see {DOCS_URL_TRAINING_DATA} for more information."
)
if e2e:
text_with_entities = format_message(
self.text or "", self.intent_name, self.entities
)
intent_prefix = f"{self.intent_name}: " if self.intent_name else ""
return f"{intent_prefix}{text_with_entities}"
return f"{self.intent_name or ''}{self._entity_string()}"
def apply_to(self, tracker: "DialogueStateTracker") -> None:
"""Applies event to tracker. See docstring of `Event`."""
tracker.latest_message = self
tracker.clear_followup_action()
@staticmethod
def create_external(
intent_name: Text,
entity_list: Optional[List[Dict[Text, Any]]] = None,
input_channel: Optional[Text] = None,
) -> "UserUttered":
return UserUttered(
text=f"{EXTERNAL_MESSAGE_PREFIX}{intent_name}",
intent={INTENT_NAME_KEY: intent_name},
metadata={IS_EXTERNAL: True},
entities=entity_list or [],
input_channel=input_channel,
)
class DefinePrevUserUtteredFeaturization(SkipEventInMDStoryMixin):
"""Stores information whether action was predicted based on text or intent."""
type_name = "user_featurization"
def __init__(
self,
use_text_for_featurization: bool,
timestamp: Optional[float] = None,
metadata: Optional[Dict[Text, Any]] = None,
) -> None:
"""Creates event.
Args:
use_text_for_featurization: `True` if message text was used to predict
action. `False` if intent was used.
timestamp: When the event was created.
metadata: Additional event metadata.
"""
super().__init__(timestamp, metadata)
self.use_text_for_featurization = use_text_for_featurization
def __str__(self) -> Text:
"""Returns text representation of event."""
return f"DefinePrevUserUtteredFeaturization({self.use_text_for_featurization})"
def __hash__(self) -> int:
"""Returns unique hash for event."""
return hash(self.use_text_for_featurization)
@classmethod
def _from_parameters(
cls, parameters: Dict[Text, Any]
) -> "DefinePrevUserUtteredFeaturization":
return DefinePrevUserUtteredFeaturization(
parameters.get(USE_TEXT_FOR_FEATURIZATION),
parameters.get("timestamp"),
parameters.get("metadata"),
)
def as_dict(self) -> Dict[Text, Any]:
"""Returns serialized event."""
d = super().as_dict()
d.update({USE_TEXT_FOR_FEATURIZATION: self.use_text_for_featurization})
return d
def apply_to(self, tracker: "DialogueStateTracker") -> None:
"""Applies event to current conversation state.
Args:
tracker: The current conversation state.
"""
if tracker.latest_action_name != ACTION_LISTEN_NAME:
# featurization belong only to the last user message
# a user message is always followed by action listen
return
# update previous user message's featurization based on this event
tracker.latest_message.use_text_for_featurization = (
self.use_text_for_featurization
)
def __eq__(self, other: Any) -> bool:
"""Compares object with other object."""
if not isinstance(other, DefinePrevUserUtteredFeaturization):
return NotImplemented
return self.use_text_for_featurization == other.use_text_for_featurization
class EntitiesAdded(SkipEventInMDStoryMixin):
"""Event that is used to add extracted entities to the tracker state."""
type_name = "entities"
def __init__(
self,
entities: List[Dict[Text, Any]],
timestamp: Optional[float] = None,
metadata: Optional[Dict[Text, Any]] = None,
) -> None:
"""Initializes event.
Args:
entities: Entities extracted from previous user message. This can either
be done by NLU components or end-to-end policy predictions.
timestamp: the timestamp
metadata: some optional metadata
"""
super().__init__(timestamp, metadata)
self.entities = entities
def __str__(self) -> Text:
"""Returns the string representation of the event."""
entity_str = [e[ENTITY_ATTRIBUTE_TYPE] for e in self.entities]
return f"{self.__class__.__name__}({entity_str})"
def __hash__(self) -> int:
"""Returns the hash value of the event."""
return hash(json.dumps(self.entities))
def __eq__(self, other: Any) -> bool:
"""Compares this event with another event."""
if not isinstance(other, EntitiesAdded):
return NotImplemented
return self.entities == other.entities
@classmethod
def _from_parameters(cls, parameters: Dict[Text, Any]) -> "EntitiesAdded":
return EntitiesAdded(
parameters.get(ENTITIES),
parameters.get("timestamp"),
parameters.get("metadata"),
)
def as_dict(self) -> Dict[Text, Any]:
"""Converts the event into a dict.
Returns:
A dict that represents this event.
"""
d = super().as_dict()
d.update({ENTITIES: self.entities})
return d
def apply_to(self, tracker: "DialogueStateTracker") -> None:
"""Applies event to current conversation state.
Args:
tracker: The current conversation state.
"""
if tracker.latest_action_name != ACTION_LISTEN_NAME:
# entities belong only to the last user message
# a user message always comes after action listen
return
for entity in self.entities:
if entity not in tracker.latest_message.entities:
tracker.latest_message.entities.append(entity)
class BotUttered(SkipEventInMDStoryMixin):
"""The bot has said something to the user.
This class is not used in the story training as it is contained in the
``ActionExecuted`` class. An entry is made in the ``Tracker``.
"""
type_name = "bot"
def __init__(
self,
text: Optional[Text] = None,
data: Optional[Dict] = None,
metadata: Optional[Dict[Text, Any]] = None,
timestamp: Optional[float] = None,
) -> None:
"""Creates event for a bot response.
Args:
text: Plain text which bot responded with.
data: Additional data for more complex utterances (e.g. buttons).
timestamp: When the event was created.
metadata: Additional event metadata.
"""
self.text = text
self.data = data or {}
super().__init__(timestamp, metadata)
def __members(self) -> Tuple[Optional[Text], Text, Text]:
data_no_nones = {k: v for k, v in self.data.items() if v is not None}
meta_no_nones = {k: v for k, v in self.metadata.items() if v is not None}
return (
self.text,
jsonpickle.encode(data_no_nones),
jsonpickle.encode(meta_no_nones),
)
def __hash__(self) -> int:
"""Returns unique hash for event."""
return hash(self.__members())
def __eq__(self, other: Any) -> bool:
"""Compares object with other object."""
if not isinstance(other, BotUttered):
return NotImplemented
return self.__members() == other.__members()
def __str__(self) -> Text:
"""Returns text representation of event."""
return "BotUttered(text: {}, data: {}, metadata: {})".format(
self.text, json.dumps(self.data), json.dumps(self.metadata)
)
def __repr__(self) -> Text:
"""Returns text representation of event for debugging."""
return "BotUttered('{}', {}, {}, {})".format(
self.text, json.dumps(self.data), json.dumps(self.metadata), self.timestamp
)
def apply_to(self, tracker: "DialogueStateTracker") -> None:
"""Applies event to current conversation state."""
tracker.latest_bot_utterance = self
def message(self) -> Dict[Text, Any]:
"""Return the complete message as a dictionary."""
m = self.data.copy()
m["text"] = self.text
m["timestamp"] = self.timestamp
m.update(self.metadata)
if m.get("image") == m.get("attachment"):
# we need this as there is an oddity we introduced a while ago where
# we automatically set the attachment to the image. to not break
# any persisted events we kept that, but we need to make sure that
# the message contains the image only once
m["attachment"] = None
return m
@staticmethod
def empty() -> "BotUttered":
"""Creates an empty bot utterance."""
return BotUttered()
def as_dict(self) -> Dict[Text, Any]:
"""Returns serialized event."""
d = super().as_dict()
d.update({"text": self.text, "data": self.data, "metadata": self.metadata})
return d
@classmethod
def _from_parameters(cls, parameters: Dict[Text, Any]) -> "BotUttered":
try:
return BotUttered(
parameters.get("text"),
parameters.get("data"),
parameters.get("metadata"),
parameters.get("timestamp"),
)
except KeyError as e:
raise ValueError(f"Failed to parse bot uttered event. {e}")
class SlotSet(Event):
"""The user has specified their preference for the value of a `slot`.
Every slot has a name and a value. This event can be used to set a
value for a slot on a conversation.
As a side effect the `Tracker`'s slots will be updated so
that `tracker.slots[key]=value`.
"""
type_name = "slot"
def __init__(
self,
key: Text,
value: Optional[Any] = None,
timestamp: Optional[float] = None,
metadata: Optional[Dict[Text, Any]] = None,
) -> None:
"""Creates event to set slot.
Args:
key: Name of the slot which is set.
value: Value to which slot is set.
timestamp: When the event was created.
metadata: Additional event metadata.
"""
self.key = key
self.value = value
super().__init__(timestamp, metadata)
def __str__(self) -> Text:
"""Returns text representation of event."""
return f"SlotSet(key: {self.key}, value: {self.value})"
def __hash__(self) -> int:
"""Returns unique hash for event."""
return hash((self.key, jsonpickle.encode(self.value)))
def __eq__(self, other: Any) -> bool:
"""Compares object with other object."""
if not isinstance(other, SlotSet):
return NotImplemented
return (self.key, self.value) == (other.key, other.value)
def as_story_string(self) -> Text:
"""Returns text representation of event."""
props = json.dumps({self.key: self.value}, ensure_ascii=False)
return f"{self.type_name}{props}"
@classmethod
def _from_story_string(
cls, parameters: Dict[Text, Any]
) -> Optional[List["SlotSet"]]:
slots = []
for slot_key, slot_val in parameters.items():
slots.append(SlotSet(slot_key, slot_val))
if slots:
return slots
else:
return None
def as_dict(self) -> Dict[Text, Any]:
"""Returns serialized event."""
d = super().as_dict()
d.update({"name": self.key, "value": self.value})
return d
@classmethod
def _from_parameters(cls, parameters: Dict[Text, Any]) -> "SlotSet":
try:
return SlotSet(
parameters.get("name"),
parameters.get("value"),
parameters.get("timestamp"),
parameters.get("metadata"),
)
except KeyError as e:
raise ValueError(f"Failed to parse set slot event. {e}")
def apply_to(self, tracker: "DialogueStateTracker") -> None:
"""Applies event to current conversation state."""
tracker._set_slot(self.key, self.value)
class Restarted(AlwaysEqualEventMixin):
"""Conversation should start over & history wiped.
Instead of deleting all events, this event can be used to reset the
trackers state (e.g. ignoring any past user messages & resetting all
the slots).
"""
type_name = "restart"
def __hash__(self) -> int:
"""Returns unique hash for event."""
return hash(32143124312)
def as_story_string(self) -> Text: