Asyncio error when sending multiple consecutive requests

Hello,

I’m using Django to interface the chat UI with Rasa bot.

If the user sends 1 message each time after the bot responses, it works fine.

If the user sends multiple messages (multiple requests) before the bot can response to the first message, it encountered some errors.

RuntimeError: Task <Task pending coro=<RasaAgent.handle_user_msg() running at D:\Project\LA-     Docker\SourceCode\AppChat\Browser\luvina_assistant\rasa_models\rasa_agent.py:30> cb=[_run_until_complete_cb() at e:\program and tool\python 3.7\Lib\asyncio\base_events.py:150]> got Future <Future pending> attached to a different loop

This is the code from Django view:

    def bot_response(request):
        user_id = request.session['user_id']
        if request.is_ajax():
            message = request.POST['message']
            message_id = request.POST['message_id']
        
        response = asyncio.run(RasaAgent.handle_user_msg(message, user_id))
        response = {'message_id': message_id, 'response': response}

    return JsonResponse(response)
    async def handle_user_msg(message, user_id):
            """
                Handle user message and return the bot's response
            """
            if RasaAgent.agent != None:
                response = await RasaAgent.agent.handle_text(message, sender_id=user_id)

            return response

I want the bot to handle 1 request at a time in the mentioned situation.

Hi @fuih, could you try replacing asyncio.run(RasaAgent.handle_user_msg(message, user_id)) with await RasaAgent.handle_user_msg(message, user_id)? The Python documentation mentions that asyncio.run always creates a new event loop, which is not what we want since there is already another one running.

Hello @fede,

I don’t think i can use await RasaAgent.handle_user_msg(message, user_id) cause the Django view, which is the function bot_response gave error when i give it the key word async. But i’m using the HTTP API now so this is not a problem anymore.

Although, i’m having a problem after i send a request to tell Rasa to execute an action. Rasa executed the action correctly, but somehow ignore the next user message. If i send the message again, the bot handled it normally (so 2 total messages after executing action, only the latter got handled). If you want i can create another topic about this.