async def run(self, output_channel, nlg, tracker, domain): from rasa.core.events import Restarted # only utter the template if it is available evts = await super(ActionRestart, self).run( output_channel, nlg, tracker, domain ) return evts + [Restarted()]
async def test_action_restart(default_channel, template_nlg, template_sender_tracker, default_domain): events = await ActionRestart().run(default_channel, template_nlg, template_sender_tracker, default_domain) assert events == [ BotUttered("congrats, you've restarted me!"), Restarted() ]
async def update_events(self, conversation_id: Text, events: List[Dict[Text, Any]]) -> Any: """Update events in the tracker of a conversation.""" # don't overwrite existing events but rather restart the conversation # and append the updated events. events = [Restarted().as_dict()] + events return await self.append_events_to_tracker(conversation_id, events)
async def run( self, output_channel: "OutputChannel", nlg: "NaturalLanguageGenerator", tracker: "DialogueStateTracker", domain: "Domain", ) -> List[Event]: # only utter the response if it is available evts = await super().run(output_channel, nlg, tracker, domain) return evts + [Restarted()]
def test_restart_after_retrieval_from_tracker_store(default_domain: Domain): store = InMemoryTrackerStore(default_domain) tr = store.get_or_create_tracker("myuser") synth = [ActionExecuted("action_listen") for _ in range(4)] for e in synth: tr.update(e) tr.update(Restarted()) latest_restart = tr.idx_after_latest_restart() store.save(tr) tr2 = store.retrieve("myuser") latest_restart_after_loading = tr2.idx_after_latest_restart() assert latest_restart == latest_restart_after_loading
async def test_reminder_restart(default_processor: MessageProcessor): out = CollectingOutputChannel() sender_id = uuid.uuid4().hex d = Dispatcher(sender_id, out, default_processor.nlg) r = ReminderScheduled("utter_greet", datetime.datetime.now(), kill_on_user_message=False) t = default_processor.tracker_store.get_or_create_tracker(sender_id) t.update(r) t.update(Restarted()) # cancels the reminder t.update(UserUttered("test")) default_processor.tracker_store.save(t) await default_processor.handle_reminder(r, d) # retrieve the updated tracker t = default_processor.tracker_store.retrieve(sender_id) assert len(t.events) == 4 # nothing should have been executed
def test_temporary_tracker(): extra_slot = "some_slot" sender_id = "test" domain = Domain.from_yaml(f""" slots: {extra_slot}: type: unfeaturized """) previous_events = [ActionExecuted(ACTION_LISTEN_NAME)] old_tracker = DialogueStateTracker.from_events(sender_id, previous_events, slots=domain.slots) new_events = [Restarted()] form_action = FormAction("some name", None) temp_tracker = form_action._temporary_tracker(old_tracker, new_events, domain) assert extra_slot in temp_tracker.slots.keys() assert list(temp_tracker.events) == [ *previous_events, ActionExecuted(form_action.name()), *new_events, ]
async def test_restart(default_dispatcher_collecting, default_domain): tracker = DialogueStateTracker("default", default_domain.slots) events = await ActionRestart().run(default_dispatcher_collecting, tracker, default_domain) assert events == [Restarted()]
def run(self, dispatcher, tracker, domain): return [Restarted()]
import json from rasa.core import broker from rasa.core.broker import FileProducer, PikaProducer, KafkaProducer from rasa.core.events import Event, Restarted, SlotSet, UserUttered from rasa.utils.endpoints import EndpointConfig, read_endpoint_config from tests.core.conftest import DEFAULT_ENDPOINTS_FILE TEST_EVENTS = [ UserUttered("/greet", { "name": "greet", "confidence": 1.0 }, []), SlotSet("name", "rasa"), Restarted() ] def test_pika_broker_from_config(): cfg = read_endpoint_config( 'data/test_endpoints/event_brokers/' 'pika_endpoint.yml', "event_broker") actual = broker.from_endpoint_config(cfg) assert isinstance(actual, PikaProducer) assert actual.host == "localhost" assert actual.credentials.username == "username" assert actual.queue == "queue" def test_no_broker_in_config():
def test_json_parse_restarted(): # DOCS MARKER Restarted evt = {"event": "restart"} # DOCS END assert Event.from_parameters(evt) == Restarted()
@pytest.mark.parametrize( "one_event,another_event", [ ( UserUttered("/greet", { "name": "greet", "confidence": 1.0 }, []), UserUttered("/goodbye", { "name": "goodbye", "confidence": 1.0 }, []), ), (SlotSet("my_slot", "value"), SlotSet("my__other_slot", "value")), (Restarted(), None), (AllSlotsReset(), None), (ConversationPaused(), None), (ConversationResumed(), None), (StoryExported(), None), (ActionReverted(), None), (UserUtteranceReverted(), None), (ActionExecuted("my_action"), ActionExecuted("my_other_action")), (FollowupAction("my_action"), FollowupAction("my_other_action")), ( BotUttered("my_text", {"my_data": 1}), BotUttered("my_other_test", {"my_other_data": 1}), ), ( AgentUttered("my_text", "my_data"), AgentUttered("my_other_test", "my_other_data"),
async def record_messages(endpoint: EndpointConfig, sender_id: Text = UserMessage.DEFAULT_SENDER_ID, max_message_limit: Optional[int] = None, finetune: bool = False, stories: Optional[Text] = None, skip_visualization: bool = False ): """Read messages from the command line and print bot responses.""" from rasa.core import training try: _print_help(skip_visualization) try: domain = await retrieve_domain(endpoint) except ClientError: logger.exception("Failed to connect to Rasa Core server at '{}'. " "Is the server running?".format(endpoint.url)) return trackers = await training.load_data(stories, Domain.from_dict(domain), augmentation_factor=0, use_story_concatenation=False, ) intents = [next(iter(i)) for i in (domain.get("intents") or [])] num_messages = 0 sender_ids = [t.events for t in trackers] + [sender_id] if not skip_visualization: plot_file = "story_graph.dot" await _plot_trackers(sender_ids, plot_file, endpoint) else: plot_file = None while not utils.is_limit_reached(num_messages, max_message_limit): try: if await is_listening_for_message(sender_id, endpoint): await _enter_user_message(sender_id, endpoint) await _validate_nlu(intents, endpoint, sender_id) await _predict_till_next_listen(endpoint, sender_id, finetune, sender_ids, plot_file) num_messages += 1 except RestartConversation: await send_event(endpoint, sender_id, Restarted().as_dict()) await send_event(endpoint, sender_id, ActionExecuted(ACTION_LISTEN_NAME).as_dict()) logger.info("Restarted conversation, starting a new one.") except UndoLastStep: await _undo_latest(sender_id, endpoint) await _print_history(sender_id, endpoint) except ForkTracker: await _print_history(sender_id, endpoint) evts_fork = await _request_fork_from_user(sender_id, endpoint) await send_event(endpoint, sender_id, Restarted().as_dict()) if evts_fork: for evt in evts_fork: await send_event(endpoint, sender_id, evt) logger.info("Restarted conversation at fork.") await _print_history(sender_id, endpoint) await _plot_trackers(sender_ids, plot_file, endpoint) except Abort: return except Exception: logger.exception("An exception occurred while recording messages.") raise
def test_json_parse_restarted(): evt = {"event": "restart"} assert Event.from_parameters(evt) == Restarted()