[SOLVED] Facing problem executing custom actions

I am not getting entities from a sample text, i.e, entities = None

I am getting below error:

Rasa Actions server:

> Exception occurred while handling uri: 'http://localhost:5055/webhook'      
> Traceback (most recent call last):    
>   File "c:\users\i0805\anaconda3\envs\rasa\lib\site-packages\rasa_sdk\executor.py", line 398, in run
>     action(dispatcher, tracker, domain)
>   File "C:\Users\i0805\Downloads\project_2\actions\actions.py", line 64, in 
> run
>     months_to_predict = next(tracker.get_latest_entity_values("time", None))StopIteration
> 
> The above exception was the direct cause of the following exception:        
> 
> Traceback (most recent call last):    
>   File "c:\users\i0805\anaconda3\envs\rasa\lib\site-packages\sanic\app.py", 
> line 939, in handle_request
>     response = await response
>   File "c:\users\i0805\anaconda3\envs\rasa\lib\site-packages\rasa_sdk\endpoint.py", line 104, in webhook
>     result = await executor.run(action_call)
> RuntimeError: coroutine raised StopIteration

rasa shell:

2021-11-26 12:45:59 ERROR    rasa.core.processor  - Encountered an exception while running action 'action_forecast_avg_risk'.Bot will continue, but the actions events are lost. Please check the logs of your action server for more information.
Traceback (most recent call last):
  File "c:\users\i0805\anaconda3\envs\rasa\lib\site-packages\rasa\core\actions\action.py", line 686, in run
    json=json_body, method="post", timeout=DEFAULT_REQUEST_TIMEOUT
  File "c:\users\i0805\anaconda3\envs\rasa\lib\site-packages\rasa\utils\endpoints.py", 
line 173, in request
    response.status, response.reason, await response.content.read()
rasa.utils.endpoints.ClientResponseError: 500, Internal Server Error, body='b'<!DOCTYPE html><html lang=en><meta charset=UTF-8><title>\xe2\x9a\xa0\xef\xb8\x8f 500 \xe2\x80\x94 Internal Server Error</title>\n<style>\n        html { font-family: sans-serif }\n   
     h2 { color: #888; }\n        .tb-wrapper p { margin: 0 }\n        .frame-border { 
margin: 1rem }\n        .frame-line > * { padding: 0.3rem 0.6rem }\n        .frame-line { margin-bottom: 0.3rem }\n        .frame-code { font-size: 16px; padding-left: 4ch }\n        .tb-wrapper { border: 1px solid #eee }\n        .tb-header { background: #eee; padding: 0.3rem; font-weight: bold }\n        .frame-descriptor { background: #e2eafb; font-size: 14px }\n    </style>\n<h1>\xe2\x9a\xa0\xef\xb8\x8f 500 \xe2\x80\x94 Internal Server Error</h1><p>The server encountered an internal error and cannot complete your request.\n''

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "c:\users\i0805\anaconda3\envs\rasa\lib\site-packages\rasa\core\processor.py", line 773, in _run_action
    output_channel, nlg, temporary_tracker, self.domain
  File "c:\users\i0805\anaconda3\envs\rasa\lib\site-packages\rasa\core\actions\action.py", line 709, in run
    raise RasaException("Failed to execute custom action.") from e
rasa.shared.exceptions.RasaException: Failed to execute custom action.
> Rasa Version      :         2.8.15
> Minimum Compatible Version: 2.8.9
> Rasa SDK Version  :         2.8.2
> Rasa X Version    :         0.42.6
> Python Version    :         3.6.13
> Operating System  :         Windows-10-10.0.19041-SP0

I have the same problem…Would be great if someone who resolve this problem will come with a solution…

1 Like

Welcome to the forum :slight_smile:

Can you share the output of rasa --version?

Tip: To correctly format code on the forum, please but three backticks (```) a line before and a line after the code

```
like this
```
1 Like

Hi @ChrisRahme I have updated the same in the question.

1 Like

Thanks :slight_smile:

Any events after which this error started appearing (e.g. upgrading Rasa)?

Also try upgrading Python to 3.7 or 3.8.

@ChrisRahme Same error with python 3.8. I get this error when an action is called and it has no entities detected in the user provided sentence. For the example where entity is present and detected, it runs fine.

Ah I see, thanks for clarifying.

Can you send your custom action over here?

# # This files contains your custom actions which can be used to run

# # custom Python code.

# #

# # See this guide on how to implement these action:

# # https://rasa.com/docs/rasa/custom-actions

# # This is a simple example for a custom action which utters "Hello World!"

from typing import Any, Text, Dict, List

from numpy import array

import keras

import pandas as pd

from rasa_sdk import Action, Tracker

from rasa_sdk.executor import CollectingDispatcher

time_mapping = {

    'next': '1',

    'upcoming': '1',

    'one': '1',

    'two': '2',

    'three': '3',

    'four': '4',

    'five': '5',

    'six': '6',

    'seven': '7',

    'eight': '8',

    'nine': '9',

    'ten': '10',

    'eleven': '11',

    'twelve': '12',

    'future': '1'

}

raw_risk_sequence = [1,2,3,4,5,6,7,8,9,10]

class ActionForecastRisk(Action):

       

    def forecastRisk(self, sequence, months):

        model = keras.models.load_model("../forecast_avg_risk_model.h5")

        sequence = [i for i in sequence]

        predictions = []

        pred_date = []

        for next_pred in range(months):

            #Testing the Model

            x_input = array(sequence[-3:])

            x_input = x_input.reshape((1, 3, 1))

            y_pred = model.predict(x_input, verbose=0)

            sequence.append(round(y_pred[0][0],3))

            predictions.append(round(y_pred[0][0],3))

        return predictions

    def name(self) -> Text:

        return "action_forecast_avg_risk"

    def run(self, dispatcher: CollectingDispatcher,

            tracker: Tracker,

            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        try:

            months_to_predict = next(tracker.get_latest_entity_values("time", None))

        except:

            months_to_predict = None

       

        if not months_to_predict:

            forecasted_risk = str(self.forecastRisk(raw_risk_sequence, 1))

            msg =  f"The average risk score for patients for the next one month is {forecasted_risk}."

            dispatcher.utter_message(text=msg)

            return []

       

        elif not str(months_to_predict).isnumeric():

            months_to_predict = time_mapping.get(months_to_predict, '1')

            forecasted_risk = str(self.forecastRisk(raw_risk_sequence, int(months_to_predict))).replace('[','').replace(']','')

            msg =  f"The average risk score for patients for the next {months_to_predict} month is: {forecasted_risk}."

            dispatcher.utter_message(text=msg)

            return []

       

        elif str(months_to_predict).isnumeric():

            forecasted_risk = str(self.forecastRisk(raw_risk_sequence, int(months_to_predict))).replace('[','').replace(']','')

            msg =  f"The average risk score for patients for the next {months_to_predict} month is: {forecasted_risk}."

            dispatcher.utter_message(text=msg)

            return []

       

        msg =  f"Sorry! Didn't get that. Please as again?"

        dispatcher.utter_message(text=msg)

        return []

Does it still give you an error even though you used try/except?

I handled it using try and except, otherwise it was showing error.

Okay so basically no problems anymore, right?

Anyway, you could also do something like that:

def run(self, dispatcher, tracker, domain):
    latest = tracker.latest_message
    months_to_predict = None
        
    if latest['entities']:
        for blob in latest['entities']:
            if blob['entity'] == 'time':
                    months_to_predict = blob['value']
                    break
1 Like