def _predict_next_with_tracker( self, tracker: DialogueStateTracker) -> PolicyPrediction: """Collect predictions from ensemble and return action and predictions.""" followup_action = tracker.followup_action if followup_action: tracker.clear_followup_action() if followup_action in self.domain.action_names_or_texts: prediction = PolicyPrediction.for_action_name( self.domain, followup_action, FOLLOWUP_ACTION) return prediction logger.error( f"Trying to run unknown follow-up action '{followup_action}'. " "Instead of running that, Rasa Open Source will ignore the action " "and predict the next action.") target = self.model_metadata.core_target if not target: raise ValueError( "Cannot predict next action if there is no core target.") results = self.graph_runner.run( inputs={PLACEHOLDER_TRACKER: tracker}, targets=[target], ) policy_prediction = results[target] return policy_prediction
async def _update_tracker_session( self, tracker: DialogueStateTracker, output_channel: OutputChannel, metadata: Optional[Dict] = None, ) -> None: """Check the current session in `tracker` and update it if expired. An 'action_session_start' is run if the latest tracker session has expired, or if the tracker does not yet contain any events (only those after the last restart are considered). Args: metadata: Data sent from client associated with the incoming user message. tracker: Tracker to inspect. output_channel: Output channel for potential utterances in a custom `ActionSessionStart`. """ if not tracker.applied_events() or self._has_session_expired(tracker): logger.debug( f"Starting a new session for conversation ID '{tracker.sender_id}'." ) await self._run_action( action=self._get_action(ACTION_SESSION_START_NAME), tracker=tracker, output_channel=output_channel, nlg=self.nlg, metadata=metadata, prediction=PolicyPrediction.for_action_name( self.domain, ACTION_SESSION_START_NAME), )
def _get_next_action_probabilities( self, tracker: DialogueStateTracker) -> PolicyPrediction: """Collect predictions from ensemble and return action and predictions.""" followup_action = tracker.followup_action if followup_action: tracker.clear_followup_action() if followup_action in self.domain.action_names: return PolicyPrediction.for_action_name( self.domain, followup_action, FOLLOWUP_ACTION) logger.error( f"Trying to run unknown follow-up action '{followup_action}'. " "Instead of running that, Rasa Open Source will ignore the action " "and predict the next action.") prediction = self.policy_ensemble.probabilities_using_best_policy( tracker, self.domain, self.interpreter) if isinstance(prediction, PolicyPrediction): return prediction rasa.shared.utils.io.raise_deprecation_warning( f"Returning a tuple of probabilities and policy name for " f"`{PolicyEnsemble.probabilities_using_best_policy.__name__}` is " f"deprecated and will be removed in Rasa Open Source 3.0.0. Please return " f"a `{PolicyPrediction.__name__}` object instead.") probabilities, policy_name = prediction return PolicyPrediction(probabilities, policy_name)
def probabilities_using_best_policy( self, tracker: DialogueStateTracker, domain: Domain, interpreter: NaturalLanguageInterpreter, **kwargs: Any, ) -> PolicyPrediction: if self.number_of_calls == 0: prediction = PolicyPrediction.for_action_name( domain, end_to_end_action, "some policy" ) prediction.is_end_to_end_prediction = True self.number_of_calls += 1 return prediction else: return PolicyPrediction.for_action_name(domain, ACTION_LISTEN_NAME)
def probabilities_using_best_policy( self, tracker: DialogueStateTracker, domain: Domain, interpreter: RegexInterpreter, **kwargs: Any, ) -> PolicyPrediction: latest_event = tracker.events[-1] if (isinstance(latest_event, UserUttered) and latest_event.parse_data["intent"]["name"] in intent_names): intent_name = latest_event.parse_data["intent"]["name"] # Here we return `action_unlikely_intent` if the name of the # latest intent is present in `intent_names`. Accompanying # metadata is fetched from `metadata_for_intent` if it is present. # We need to do it because every time the tests are run, # training will result in different model weights which might # result in different predictions of `action_unlikely_intent`. # Because we're not testing `UnexpecTEDIntentPolicy`, # here we simply trigger it by # predicting `action_unlikely_intent` in a specified moment # to make the tests deterministic. return PolicyPrediction.for_action_name( domain, ACTION_UNLIKELY_INTENT_NAME, action_metadata=metadata_for_intent.get(intent_name) if metadata_for_intent else None, ) return _original(self, tracker, domain, interpreter, **kwargs)
def probabilities_using_best_policy( self, tracker: DialogueStateTracker, domain: Domain, interpreter: NaturalLanguageInterpreter, **kwargs: Any, ) -> PolicyPrediction: prediction = PolicyPrediction.for_action_name( default_processor.domain, expected_action, "some policy") prediction.events = expected_events return prediction
def predict_action_probabilities( self, tracker, domain, interpreter, **kwargs, ) -> PolicyPrediction: latest_event = tracker.events[-1] if (isinstance(latest_event, UserUttered) and latest_event.parse_data["intent"]["name"] == intent_name): return PolicyPrediction.for_action_name( domain, ACTION_UNLIKELY_INTENT_NAME) return _original(self, tracker, domain, interpreter, **kwargs)
async def execute_action( self, sender_id: Text, action: Text, output_channel: OutputChannel, policy: Optional[Text], confidence: Optional[float], ) -> Optional[DialogueStateTracker]: """Executes an action.""" prediction = PolicyPrediction.for_action_name(self.domain, action, policy, confidence or 0.0) return await self.processor.execute_action( # type: ignore[union-attr] sender_id, action, output_channel, self.nlg, prediction)
async def execute_action( self, sender_id: Text, action: Text, output_channel: OutputChannel, policy: Optional[Text], confidence: Optional[float], ) -> Optional[DialogueStateTracker]: """Handle a single message.""" processor = self.create_processor() prediction = PolicyPrediction.for_action_name(self.domain, action, policy, confidence or 0.0) return await processor.execute_action(sender_id, action, output_channel, self.nlg, prediction)
async def _update_tracker_session( self, tracker: DialogueStateTracker, output_channel: OutputChannel, metadata: Optional[Dict] = None, ) -> None: """Check the current session in `tracker` and update it if expired. An 'action_session_start' is run if the latest tracker session has expired, or if the tracker does not yet contain any events (only those after the last restart are considered). Args: metadata: Data sent from client associated with the incoming user message. tracker: Tracker to inspect. output_channel: Output channel for potential utterances in a custom `ActionSessionStart`. """ if not tracker.applied_events() or self._has_session_expired(tracker): logger.debug( f"Starting a new session for conversation ID '{tracker.sender_id}'." ) action_session_start = self._get_action(ACTION_SESSION_START_NAME) # TODO: Remove in 3.0.0 and describe migration to `session_start_metadata` # slot in migration guide. if isinstance( action_session_start, rasa.core.actions.action.ActionSessionStart ): # Here we set optional metadata to the ActionSessionStart, which will # then be passed to the SessionStart event. action_session_start.metadata = metadata if metadata: tracker.update( SlotSet(SESSION_START_METADATA_SLOT, metadata), self.domain ) await self._run_action( action=action_session_start, tracker=tracker, output_channel=output_channel, nlg=self.nlg, prediction=PolicyPrediction.for_action_name( self.domain, ACTION_SESSION_START_NAME ), )
def _get_next_action_probabilities( self, tracker: DialogueStateTracker) -> PolicyPrediction: """Collect predictions from ensemble and return action and predictions.""" followup_action = tracker.followup_action if followup_action: tracker.clear_followup_action() if followup_action in self.domain.action_names_or_texts: return PolicyPrediction.for_action_name( self.domain, followup_action, FOLLOWUP_ACTION) logger.error( f"Trying to run unknown follow-up action '{followup_action}'. " "Instead of running that, Rasa Open Source will ignore the action " "and predict the next action.") return self.policy_ensemble.probabilities_using_best_policy( tracker, self.domain, self.interpreter)