Skip to content

Instantly share code, notes, and snippets.

@ehzawad
Created February 4, 2024 05:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ehzawad/f1d7b4086a4a8b36bd44894234c8079b to your computer and use it in GitHub Desktop.
Save ehzawad/f1d7b4086a4a8b36bd44894234c8079b to your computer and use it in GitHub Desktop.
actions.py
class ActionAnalyzePreviousMessages(Action):
def name(self) -> Text:
return "action_analyze_previous_messages"
def run(self, dispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[EventType]:
# Your predefined list or dictionary of keywords
keywords = ["খতিয়ান", "পর্চা", "পর্চার", "খাজনা"]
# Get the list of events
events = tracker.events
# Function to find message events
def find_message_events(events):
return [event for event in events if event["event"] == "user"]
# Extracting the last two user messages
message_events = find_message_events(events)
previous_message = message_events[-2]["text"] if len(message_events) > 1 else ""
previous_of_previous_message = message_events[-3]["text"] if len(message_events) > 2 else ""
# Check for keywords in messages
keyword_in_previous = any(keyword in previous_message for keyword in keywords)
keyword_in_previous_of_previous = any(keyword in previous_of_previous_message for keyword in keywords)
# Logic based on keyword findings
if keyword_in_previous:
# Handle scenario for keyword found in previous message
# pass
print("previous")
elif keyword_in_previous_of_previous:
# Handle scenario for keyword found in previous of previous message
# pass
print("previous of previous")
else:
# Handle scenario if no relevant keyword is found
# pass
print("no relevant word found")
# Return an empty list if no events are to be triggered
return []
You, Thu 6:01 PM
```- rule: Ask the user to rephrase whenever they send a message with low NLU confidence
steps:
- intent: nlu_fallback
- action: action_analyze_previous_messages
- rule: Ask the user to rephrase whenever they send a message with low NLU confidence out of scope
steps:
- intent: out_of_scope
- action: action_analyze_previous_messages```
class ActionAnalyzePreviousMessages(Action):
def name(self) -> Text:
return "action_analyze_previous_messages"
def run(self, dispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[EventType]:
# Defining keywords and their corresponding Rasa intents
keyword_intent_mapping = {
"নামজারি": "ApplyNamzari",
"Namzari fee": "NamzariFee",
# Add other keywords and their corresponding intents here
}
# Get the list of events
events = tracker.events
# Function to find message events
def find_message_events(events):
return [event for event in events if event["event"] == "user"]
# Extracting the last two user messages
message_events = find_message_events(events)
previous_message = message_events[-2]["text"] if len(message_events) > 1 else ""
previous_of_previous_message = message_events[-3]["text"] if len(message_events) > 2 else ""
# Check for keywords in messages and map to corresponding intent
for keyword, intent in keyword_intent_mapping.items():
if keyword in previous_message or keyword in previous_of_previous_message:
# Dispatch a custom action or message based on the identified intent
dispatcher.utter_message(text=f"Found keyword related to {intent}. Redirecting to the appropriate action.")
# Here you would typically return a FollowupAction with the name of the action corresponding to the intent
# For illustration, we'll just return an empty list
return [FollowupAction(name=f"action_for_{intent}")]
# Handle scenario if no relevant keyword is found
dispatcher.utter_message(text="No relevant keyword found. Please rephrase or ask another question.")
return []
@ehzawad
Copy link
Author

ehzawad commented Feb 4, 2024

from typing import Any, Dict, List, Text
from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher
from rasa_sdk.events import FollowupAction

class ActionAnalyzePreviousMessages(Action):
    def name(self) -> Text:
        return "action_analyze_previous_messages"

    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        keyword_action_mapping = {
            "নামজারি আবেদন": "action_ApplyNamzari",
            "নামজারি বাতিল": "action_ApplyNamzariCancel",
            "নামজারি সময়": "action_NamzariTime",
            "নামজারি ফি": "action_NamzariFee",
        }

        # Extracting the last two user messages for keyword scanning
        message_events = [event for event in tracker.events if event["event"] == "user"]
        recent_messages = message_events[-2:]  # Getting the last two messages

        for message in recent_messages:
            text = message.get("text", "")
            for keyword, action in keyword_action_mapping.items():
                if keyword in text:
                    dispatcher.utter_message(text=f"Found keyword for {action}. Redirecting...")
                    return [FollowupAction(name=action)]

        dispatcher.utter_message(text="No relevant keyword found. Please rephrase or ask another question.")
        return []

@ehzawad
Copy link
Author

ehzawad commented Feb 4, 2024


from itertools import combinations
import unicodedata
from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher
from rasa_sdk.events import FollowupAction

# Define the function to normalize text using NFC
def normalize_text(text):
    return unicodedata.normalize('NFC', text)

class ActionAnalyzePreviousMessages(Action):
    def name(self) -> Text:
        return "action_analyze_previous_messages"

    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        print("Starting to analyze previous messages...")

        # Original keywords intent mapping with normalization applied
        keywords_intent_mapping = {
            (normalize_text('নামজারি'), normalize_text('সময়')): "NamzariTime",
            (normalize_text('নামজারির'), normalize_text('সময়')): "NamzariTime",
            (normalize_text('সময়'), normalize_text('নামজারি')): "NamzariTime",
            (normalize_text('সময়'), normalize_text('নামজারির')): "NamzariTime",
        }

        messages = [event.get("text", "") for event in tracker.events if event.get("event") == "user"][-2:]
        normalized_messages = [normalize_text(msg) for msg in messages]
        print(f"Last two normalized messages: {normalized_messages}")

        combined_keywords_list = " ".join(normalized_messages).split()
        normalized_keyword_pairs = list(combinations(combined_keywords_list, 2))

        print("Generated normalized keyword pairs:")
        for pair in normalized_keyword_pairs:
            print(pair)

        found = False
        for pair in normalized_keyword_pairs:
            normalized_pair = (normalize_text(pair[0]), normalize_text(pair[1]))
            if normalized_pair in keywords_intent_mapping:
                intent = keywords_intent_mapping[normalized_pair]
                print(f"Match found for intent {intent} with normalized keywords {normalized_pair}")
                found = True
                return self.trigger_response(intent, domain, dispatcher)

        if not found:
            print("No match found for any intent based on the provided normalized keywords.")
            dispatcher.utter_message(text="Could not deduce intent from the messages. Please provide more information.")
            return []

    def trigger_response(self, intent: Text, domain: Dict[Text, Any], dispatcher: CollectingDispatcher) -> List[Dict[Text, Any]]:
        if f"utter_{intent}" in domain.get("responses", {}):
            dispatcher.utter_message(response=f"utter_{intent}")
        elif f"action_{intent}" in domain.get("actions", []):
            return [FollowupAction(name=f"action_{intent}")]
        else:
            dispatcher.utter_message(text=f"Recognized intent: {intent}, but no specific action or utterance is configured.")
        return []

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment