Handling API exceptions in Rasa action server

I have to handle API call exceptions in Rasa action server. For Example, I have a list of restaurant databases, which I will host it in a local server. In rasa action server, I would host this local server and access information from the database.

If wrong database has hosted, it throws 501 http error. When this error occurs, I can now log this error,but I would like to send a message as a response to user.

If 501 error occurs,

For,
User Input: Can you look for cheap restaurant in centre of town
system output: I am sorry for the inconvenience, I have encountered an Internal service error. Could you please try again later

How can I handle this in Rasa action server? Could I get any information regarding this?

How are you making API calls from actions.py ? If you are using requests package, then it should be quite easy.

Inside the run method of your Action class, you can use requests to make API call like this:

    try:
       log.debug(f'URL for API: {_url}')
       resp = requests.get(_url)
   except requests.exceptions.RequestException as e:
            s = getattr(e,'message', str(e))
            log.error(f'Unable to get data due to {s}.')
  message = 'I am sorry for the inconvenience, I have encountered an Internal service error. Could you please try again later'
  dispatcher.utter_button_message(message)

Hi @tonysinghmss Thanks for the reply. I have tried it, but still it throws me an exception instead of an error message

In run() method of my action class, I have defined as follows,

class RestaurantInform(Action): def name(self): return “Restaurant-Inform”

def run(self, dispatcher, tracker, domain):        
    try:
        count, specific_data, name, addr, ph_no, post_code= ActionSearchRestaurants.entity_extract(self, dispatcher, tracker, domain)
        
        if len(specific_data) != 0:
            message = dispatcher.utter_message(f"There are {count} options available. The list of Restaurant names are {specific_data}. Could you tell me which one do you prefer?")
            return message
        elif len(addr)!=0 and len(ph_no)!=0 and len(post_code)!=0:
            message_1 = dispatcher.utter_message(f"The restaurant {name} is located at {addr} and their phone number is {ph_no}. The post code of the restaurant is {post_code}")  
            return message_1
        else:
            pass
    except requests.exceptions.RequestException as e:
        s = getattr(e,'message', str(e))
        logger.info(f'Unable to get data due to {s}.')
        message = 'I am sorry for the inconvenience, I have encountered an Internal service error. Could you please try again later'
        dispatcher.utter_message(message)

Instead of giving me the message

 message = 'I am sorry for the inconvenience, I have encountered an Internal service error. Could you please try again later'

I get the following exception,

Your input → can you look for cheap restaurants in centre of town?
Could you give me some other suggestion?

2019-11-06 11:09:56 ERROR rasa.core.processor - Encountered an exception while running action ‘Action-Search’. Bot will continue, but the actions events are lost. Please check the logs of your action server for more information.

2019-11-06 11:09:57 ERROR rasa.core.processor - Encountered an exception while running action ‘Restaurant-Inform’. Bot will continue, but the actions events are lost. Please check the logs of your action server for more information.

Can you put log of your actions.py? That will help in better understanding of your issue.

This is the information, which I have received,

2019-11-06 11:52:16 INFO rasa_sdk.endpoint - Action endpoint is up and running. on (‘0.0.0.0’, 5055)

2019-11-06 11:52:35 WARNING rasa_sdk.endpoint - Your versions of rasa and rasa_sdk might not be compatible. You are currently running rasa version 1.4.0a1 and rasa_sdk version 1.3.2.

To ensure compatibility use the same version for both, modulo the last number, i.e. using version A.B.x the numbers A and B should be identical for both rasa and rasa_sdk.

2019-11-06 11:52:35 DEBUG rasa_sdk.executor - Received request to run ‘Restaurant-Request’

2019-11-06 11:52:35 DEBUG rasa_sdk.executor - Finished running ‘Restaurant-Request’

127.0.0.1 - - [2019-11-06 11:52:35] “POST /webhook HTTP/1.1” 200 220 0.000000

2019-11-06 11:52:36 WARNING rasa_sdk.endpoint - Your versions of rasa and rasa_sdk might not be compatible. You are currently running rasa version 1.4.0a1 and rasa_sdk version 1.3.2.

To ensure compatibility use the same version for both, modulo the last number, i.e. using version A.B.x the numbers A and B should be identical for both rasa and rasa_sdk.

2019-11-06 11:52:36 DEBUG rasa_sdk.executor - Received request to run ‘Action-Search’

2019-11-06 11:52:36 DEBUG urllib3.connectionpool - Starting new HTTP connection (1): 127.0.0.1:3128

2019-11-06 11:52:36 DEBUG urllib3.connectionpool - http://127.0.0.1:3128 “GET http://localhost:5000/restaurant HTTP/1.1” 404 447

2019-11-06 11:52:36 DEBUG error-info.log - The requested URL could not be found. I could not disclose whether it is temporary or permanent

2019-11-06 11:52:36 ERROR flask.app - Exception on /webhook [POST]

Traceback (most recent call last):

File “c:\apps\sa2446\lib\site-packages\flask\app.py”, line 2292, in wsgi_app response = self.full_dispatch_request()

File “c:\apps\sa2446\lib\site-packages\flask\app.py”, line 1815, in full_dispatch_request rv = self.handle_user_exception(e)

File “c:\apps\sa2446\lib\site-packages\flask_cors\extension.py”, line 161, in wrapped_function return cors_after_request(app.make_response(f(*args, **kwargs)))

File “c:\apps\sa2446\lib\site-packages\flask\app.py”, line 1718, in handle_user_exception reraise(exc_type, exc_value, tb)

File “c:\apps\sa2446\lib\site-packages\flask_compat.py”, line 35, in reraise raise value

File “c:\apps\sa2446\lib\site-packages\flask\app.py”, line 1813, in full_dispatch_request rv = self.dispatch_request()

File “c:\apps\sa2446\lib\site-packages\flask\app.py”, line 1799, in dispatch_request return self.view_functionsrule.endpoint

File “c:\apps\sa2446\lib\site-packages\flask_cors\decorator.py”, line 128, in wrapped_function resp = make_response(f(*args, **kwargs))

File “c:\apps\sa2446\lib\site-packages\rasa_sdk\endpoint.py”, line 59, in webhook response = executor.run(action_call)

File “c:\apps\sa2446\lib\site-packages\rasa_sdk\executor.py”, line 259, in run validated_events = self.validate_events(events, action_name)

File “c:\apps\sa2446\lib\site-packages\rasa_sdk\executor.py”, line 209, in validate_events for e in events:

TypeError: ‘HTTPError’ object is not iterable 127.0.0.1 - - [2019-11-06 12:36:30] “POST /webhook HTTP/1.1” 500 411 0.015621

Hi,

Could you please suggest, how to track information, errors in a logger? I a using the below codes in my action file but it’s not capturing anything, neither any log files created as of now. (its also not showing any error.

import logging
logging.basicConfig(filename='logfile.log', format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logger = logging.getLogger(__name__)


def submit(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict]:
	
	 try:
	........
	........
	........

except Exception as e:
            msg = 'Unfortunately I am not able to extract requested information! <br>You can still contact us via email 🙂'
            dispatcher.utter_message(text= msg)
            logger.error(e)
            # logger.exception()
            logger.exception("Failed to extract data for " + project + "(" + query + ")")
            return []

Will appreciate your response.