How to solve json response from Vue to rasa custom action

32 views Asked by At

Ok, so everything works out fine in during rasa shell but when connecting it to the frontend (Vuejs), it keeps giving the error message that i set up when the rasa action server fails to responds. i think it might be the json response part from Vue to rasa action server since it provided this response in the console: Response received: {message: 'Sorry, something went wrong.'}

this is my frontend:

  methods: {
    sendMessage() {
      console.log('sendMessage method started');
      axios.post('http://127.0.0.1:5000/webhook', {
        sender:'user',
        message: this.userMessage
      })
      .then(response => {
        console.log('Response received:', response.data);
        const botResponse = response.data; // Access the full JSON response

        // Construct the displayed response with additional fields
        let displayedResponse = botResponse.message;
        if (botResponse.syn) {
          displayedResponse += "\nSynonyms: ${botResponse.syn}"
        }
        if (botResponse.exp) {
          displayedResponse += "\nExplanation: ${botResponse.exp}"
        }
        if (botResponse.ant) {
          displayedResponse += "\nAntonyms: ${botResponse.ant}";
        }

        // Update the UI with the displayed response
        this.messages.push({ content: this.userMessage, sender: 'user' });
        this.messages.push({ content: displayedResponse, sender: 'bot' });
        this.userMessage = '';
      })
      .catch(error => {
        console.log('Error sending message:', error);
      })
      .finally(()=>{
        console.log('sendMessage method completed');
      })
    },
  },

this is my backend:

def webhook():
    data = request.get_json()   
    # Forward the incoming message to Rasa server
    rasa_response = requests.post('http://localhost:5055/webhook', json=data)
    if rasa_response.status_code == 200:
        rasa_data = rasa_response.json()
        if rasa_data:
            reply_text = rasa_data[0].get('text', 'Sorry, I didn\'t understand.')
            input_text = rasa_data[0].get('input')
            synonyms = rasa_data[0].get('syn')
            explanation = rasa_data[0].get('exp')
            antonyms = rasa_data[0].get('ant')
            return jsonify({
                'message': reply_text,
                'input': input_text,
                'syn': synonyms,
                'exp': explanation,
                'ant': antonyms
            })
    return jsonify({'message': 'Sorry, something went wrong.'})

this is some of my rasa custom action:

class MalayaExpAction(Action):
  
  def name(self) -> Text:
    return "ms_explanation_action"
  
  def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, dialogue) -> List[Dict[Text, Any]]:
    user_input=tracker.get_latest_input_channel()
    
    try:
      model = malaya.summarization.abstractive.huggingface(model = 'mesolitica/finetune-summarization-ms-t5-small-standard-bahasa-cased')
      summary = model.generate([user_input],do_sample=True,max_length=256,top_p=0.92,top_k=0,num_return_sequences=3,threshold = 0.0)
      dispatcher.utter_message(response="utter_ms_explanation_action",exp=f"{summary}")
      return []
    
    except Exception as e:
      dispatcher.utter_message(f"An Error Occured: {e}")
      return []
class SpacyAntAction(Action):
    def name(self) -> Text:
        return "en_antonym_action"

    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Text]:
        user_input=tracker.get_latest_input_channel()
        explanation, synonyms, antonyms = self.analyze_text(user_input.text)
        dispatcher.utter_message(response="utter_en_antonym_action",text=user_input,ant=f"Antonyms: {', '.join(antonyms)}")
        return []

    def analyze_text(self, text: Text) -> Tuple[Text, List[Text], List[Text]]:
        nlp = spacy.load("en_core_web_md")
        doc = nlp(text)

        # Sentence segmentation
        sent = list(doc.sents)[0]

        # Coreference resolution
        clusters = list(doc._.coref_clusters)

        # Contextualized word embeddings
        word_vectors = nlp.vocab.vectors

        # Explanation
        explanation = ""
        for token in sent:
            if token.pos_ == "NOUN":
                explanation += f"{token.text} is the {token._.dep_} of {token.head.text}"
                # Identify related entities
                for cluster in clusters:
                    if token in cluster:
                        for co_ref in cluster:
                            if co_ref != token:
                                explanation += f"It is also referred to as {co_ref.text}."
                                break
                # Analyze sentiment
                if token._.sentiment != 0:
                    sentiment = "positive" if token._.sentiment > 0 else "negative"
                    explanation += f" It has a {sentiment} sentiment."
                break

        # Synonyms and antonyms
        synonyms = []
        antonyms = []
        for token in sent:
            if token.pos_ == "NOUN":
                # Use contextualized word vectors
                similar_words = nlp(token.text).vector._.most_similar(n=5, vectors=word_vectors)
                for word, sim in similar_words:
                    if token.head != doc[word]: 
                        synonyms.append(word)
                for word, sim in similar_words:
                    if token.head != doc[word]:
                        antonyms.append(word)

        return explanation, synonyms, antonyms

, i have tried a lot of ways through youtube and other blogs and reached a deadend which are the code above and error below, it produced this error that originates from the rasa custom action server that i ran using rasa run action:

Registered function for 'en_antonym_action'.
Registered function for 'en_explanation_action'.
Registered function for 'en_synoynm_action'.
Registered function for 'en_translation_action'.
Registered function for 'ms_antonym_action'.
Registered function for 'ms_explanation_action'.
Registered function for 'ms_synonym_action'.
Registered function for 'ms_translation_action'.
Starting plugins...
Action endpoint is up and running on http://0.0.0.0:5055
Received an action call without an action.

Side Notes: rasa run --enable-api produced no problem, it runs the server and just does nothing. Also my custom actions code is in their own file like en_antonym.py and is within the actions folder which is in the same level as the actions.py file

0

There are 0 answers