Multiple await expression blocking the execution
I am using django channels for a chatbot implementation and i am using ayncwebsocketconsumer
# Receive message from WebSocket
async def receive(self, text_data):
text_data_json = json.loads(text_data)
event_type = text_data_json.get('event_type', '-')
if event_type not in EventTypeChoicesChat.choices[0]:
logger.error(f"{event_type} is not a valid EventType")
else:
# NOTE: we need to refresh session and set (user_type ,user) on every message
await self.refresh_session()
self.user = self.scope['user'] if not self.scope['user'].is_anonymous else None
self.user_type = text_data_json['user_type']
chat_data = text_data_json['chat_data']
# save the message first(SessionMessage model)
saved_msg = await self.save_message({
"session": self.session,
"sender": self.user if self.user else None,
"user_type": self.user_type,
"chat_data": chat_data
})
# prepare the message_response to be sent
response = {
"event_type": event_type,
"user_type": self.user_type,
"sender_icon": await self.set_sender_icon(self.user_type),
"id": saved_msg.id,
"created_at": str(saved_msg.created_at),
"chat_data": chat_data
}
# Send message to room group
await self.channel_layer.group_send(
self.room_group_name, {"type": 'send_chat_message', "data": response}
)
# update last message received time on session
self.session.last_chat_received_time = datetime.now(timezone.utc).isoformat()
await database_sync_to_async(self.session.save)()
# If AI is active and the user is not AI, send the message to AI
if self.session.is_ai_active and self.user_type != SessionUserTypeChoices.AI:
session_id = self.room_name
bot_id = await database_sync_to_async(lambda: self.session.bot.id)()
org_id = await database_sync_to_async(lambda: self.session.bot.org.id)()
goal = 'you are intelligent customer service agent'
ai_response_url = settings.AI_BASE_URL + f'/api/v1.0/ai/conversion/{bot_id}/{org_id}'
query_params = f"query={chat_data['msg']}&user_session_id={session_id}&goal={goal}"
ai_response_url_with_query = ai_response_url + '?' + query_params
async with aiohttp.ClientSession() as session:
async with session.post(ai_response_url_with_query) as response:
if response.status == 200:
ai_response = {
"event_type": "message",
"user_type": SessionUserTypeChoices.AI,
"chat_data": await response.json()
}
# Send AI response to room group
await self.channel_layer.group_send(
self.room_group_name, {"type": 'send_chat_message', "data": ai_response}
)
when i send a message the code should have first send the message to the websocket and then pass it to the ai but when i see on the frontend the first message does not arrives first , it waits for the ai message and then both mnessages are sent to the frontend at same time but i want to send the first message first and then other tasks
is it because i used await on them ?