Mehul Patel commited on
Commit
39bcecc
·
1 Parent(s): 71a0008

async generator working

Browse files
Files changed (3) hide show
  1. app.py +24 -28
  2. custom_logging.py +7 -3
  3. rasa_socketio_client.py +17 -29
app.py CHANGED
@@ -79,55 +79,51 @@
79
  # if __name__ == "__main__":
80
  # asyncio.run(demo.launch())
81
 
82
-
83
  import gradio as gr
84
  import asyncio
85
  from rasa_socketio_client import RasaSocketIOClient
86
- import logging
87
- from custom_logging import IMPORTANT_LEVEL_NUM
88
-
89
- logging.basicConfig(level=IMPORTANT_LEVEL_NUM, format='%(asctime)s - %(levelname)s - %(message)s')
90
- logger = logging.getLogger(__name__)
91
 
 
92
  rasa_io_url = "https://clairify.ai/socket.io"
93
  theme = gr.themes.Default(primary_hue="cyan", secondary_hue="violet")
94
 
95
  with gr.Blocks(theme=theme) as demo:
96
 
97
- # Initialize chat history as a gr.State object
98
  chat_history = gr.State([])
99
-
100
- # Instantiate RasaSocketIOClient with the update_chat_history callback
101
- rasa_client = RasaSocketIOClient(rasa_io_url, update_chat_history_callback=update_chat_history)
102
-
103
- # Define the callback function for updating chat history
104
- async def update_chat_history(user_input, bot_response):
105
- global chat_history # Ensure chat_history is accessible and can be updated
106
- new_entry = (user_input, bot_response)
107
- current_history = chat_history.value
108
- updated_history = current_history + [new_entry]
109
- chat_history.value = updated_history # Update the state with the new history
110
- logger.important(f"Chat history updated with new entry: {chat_history.value}")
111
-
112
- async def interact_with_rasa(user_input, chatbot):
113
  logger.important(f"User input received: {user_input}")
 
114
  if not rasa_client.sio.connected:
115
  logger.important("Rasa client not connected, attempting to connect...")
116
  await rasa_client.connect()
117
 
118
  logger.important(f"Sending payload to Rasa: {user_input}")
119
- # Send the user message to Rasa; chat history will be updated via callback
120
- await rasa_client.send_message(user_input)
121
- # No need to manually update chat history here
122
- return "", chatbot # Return an empty string to clear the input field
 
 
 
 
 
 
 
 
 
 
 
 
123
 
124
  chatbot = gr.Chatbot(label="Conversation")
125
  msg = gr.Textbox(placeholder="Say Hi! to wake me up", show_label=False)
126
  clear = gr.ClearButton([msg, chatbot])
127
- msg.submit(interact_with_rasa, inputs=[msg, chatbot], outputs=[msg, chatbot])
 
128
 
129
  if __name__ == "__main__":
130
  logger.important("Launching Gradio demo...")
131
  asyncio.run(demo.launch())
132
-
133
-
 
79
  # if __name__ == "__main__":
80
  # asyncio.run(demo.launch())
81
 
 
82
  import gradio as gr
83
  import asyncio
84
  from rasa_socketio_client import RasaSocketIOClient
85
+ from custom_logging import get_logger
 
 
 
 
86
 
87
+ logger = get_logger(__name__)
88
  rasa_io_url = "https://clairify.ai/socket.io"
89
  theme = gr.themes.Default(primary_hue="cyan", secondary_hue="violet")
90
 
91
  with gr.Blocks(theme=theme) as demo:
92
 
 
93
  chat_history = gr.State([])
94
+ rasa_client = RasaSocketIOClient(rasa_io_url)
95
+
96
+ async def interact_with_rasa(user_input):
 
 
 
 
 
 
 
 
 
 
 
97
  logger.important(f"User input received: {user_input}")
98
+
99
  if not rasa_client.sio.connected:
100
  logger.important("Rasa client not connected, attempting to connect...")
101
  await rasa_client.connect()
102
 
103
  logger.important(f"Sending payload to Rasa: {user_input}")
104
+
105
+ is_first_message = True
106
+
107
+ async for message in rasa_client.send_message(user_input):
108
+
109
+ logger.important(f"Processing messages: {message}")
110
+
111
+ if is_first_message:
112
+ new_entry = (user_input, message.get('text', ''))
113
+ is_first_message = False
114
+ else:
115
+ new_entry = (None, message.get('text', ''))
116
+
117
+ chat_history.value.append(new_entry)
118
+
119
+ yield "", chat_history.value
120
 
121
  chatbot = gr.Chatbot(label="Conversation")
122
  msg = gr.Textbox(placeholder="Say Hi! to wake me up", show_label=False)
123
  clear = gr.ClearButton([msg, chatbot])
124
+
125
+ msg.submit(interact_with_rasa, inputs=[msg], outputs=[msg, chatbot])
126
 
127
  if __name__ == "__main__":
128
  logger.important("Launching Gradio demo...")
129
  asyncio.run(demo.launch())
 
 
custom_logging.py CHANGED
@@ -1,6 +1,5 @@
1
  import logging
2
 
3
- # Step 1: Define a new logging level
4
  IMPORTANT_LEVEL_NUM = 25
5
  logging.addLevelName(IMPORTANT_LEVEL_NUM, "IMPORTANT")
6
 
@@ -8,5 +7,10 @@ def important(self, message, *args, **kws):
8
  if self.isEnabledFor(IMPORTANT_LEVEL_NUM):
9
  self._log(IMPORTANT_LEVEL_NUM, message, args, **kws)
10
 
11
- # Add the custom level to the logging.Logger class
12
- logging.Logger.important = important
 
 
 
 
 
 
1
  import logging
2
 
 
3
  IMPORTANT_LEVEL_NUM = 25
4
  logging.addLevelName(IMPORTANT_LEVEL_NUM, "IMPORTANT")
5
 
 
7
  if self.isEnabledFor(IMPORTANT_LEVEL_NUM):
8
  self._log(IMPORTANT_LEVEL_NUM, message, args, **kws)
9
 
10
+ logging.Logger.important = important
11
+
12
+ logging.basicConfig(level=IMPORTANT_LEVEL_NUM, format='%(asctime)s - %(levelname)s - %(message)s')
13
+
14
+ def get_logger(name):
15
+ return logging.getLogger(name)
16
+
rasa_socketio_client.py CHANGED
@@ -93,25 +93,18 @@
93
 
94
  import asyncio
95
  import socketio
96
- import logging
97
- from custom_logging import IMPORTANT_LEVEL_NUM
98
 
99
- # Configure logging
100
- logging.basicConfig(level=IMPORTANT_LEVEL_NUM)
101
- logger = logging.getLogger(__name__)
102
 
103
  class RasaSocketIOClient:
104
  def __init__(self, uri, update_chat_history_callback=None):
105
- self.sio = socketio.AsyncClient(logger=False, engineio_logger=False)
106
- self.response_event = asyncio.Event()
107
  self.uri = uri
108
- self.response = None
109
- self.update_chat_history_callback = update_chat_history_callback
110
- self.last_user_message = None
111
  self.register_event_handlers()
112
 
113
  def register_event_handlers(self):
114
- # Use a method to define event handlers where 'self' is properly defined
115
  @self.sio.event
116
  async def connect():
117
  logger.important("Connected to the server.")
@@ -120,18 +113,10 @@ class RasaSocketIOClient:
120
  async def disconnect():
121
  logger.important("Disconnected from the server.")
122
 
123
- self.sio.on('bot_uttered', self.on_message)
124
-
125
- async def on_message(self, data):
126
- logger.important(f"Socket ID: {self.sio.sid} Received response: {data}")
127
- # Check if there is a callback function defined and last user message is stored
128
- if self.update_chat_history_callback and self.last_user_message is not None:
129
- # Call the callback function with the last user message and bot's response
130
- asyncio.create_task(self.update_chat_history_callback(self.last_user_message, data['text']))
131
- logger.important("Callback task created for update_chat_history_callback.")
132
- self.response = data
133
- self.last_user_message = None # Clear the last user message after handling
134
- self.response_event.set()
135
 
136
  async def connect(self):
137
  try:
@@ -141,14 +126,16 @@ class RasaSocketIOClient:
141
  logger.error(f"Failed to connect to the server: {e}")
142
 
143
  async def send_message(self, user_message):
144
- # Store the user's message to use it later in the callback
145
- self.last_user_message = user_message
146
- self.response = None # Reset previous response
147
- self.response_event.clear() # Reset the event for a new message
148
  try:
149
- await self.sio.emit('user_uttered', {'message': user_message}) # Adjust as per your setup
150
  logger.important(f"Message sent: {user_message}")
151
- await self.response_event.wait() # Wait here until the response has been received
 
 
 
 
 
 
152
  except Exception as e:
153
  logger.error(f"Failed to send message: {e}")
154
 
@@ -159,4 +146,5 @@ class RasaSocketIOClient:
159
  except Exception as e:
160
  logger.error(f"Failed to disconnect: {e}")
161
 
 
162
 
 
93
 
94
  import asyncio
95
  import socketio
96
+ from custom_logging import get_logger
 
97
 
98
+ logger = get_logger(__name__)
 
 
99
 
100
  class RasaSocketIOClient:
101
  def __init__(self, uri, update_chat_history_callback=None):
102
+ self.sio = socketio.AsyncClient(logger=True, engineio_logger=True)
 
103
  self.uri = uri
104
+ self.message_queue = asyncio.Queue()
 
 
105
  self.register_event_handlers()
106
 
107
  def register_event_handlers(self):
 
108
  @self.sio.event
109
  async def connect():
110
  logger.important("Connected to the server.")
 
113
  async def disconnect():
114
  logger.important("Disconnected from the server.")
115
 
116
+ @self.sio.on('bot_uttered')
117
+ async def on_message(data):
118
+ logger.debug(f"Socket ID: {self.sio.sid} Received response: {data}")
119
+ await self.message_queue.put(data) # Put received message into the queue
 
 
 
 
 
 
 
 
120
 
121
  async def connect(self):
122
  try:
 
126
  logger.error(f"Failed to connect to the server: {e}")
127
 
128
  async def send_message(self, user_message):
 
 
 
 
129
  try:
130
+ await self.sio.emit('user_uttered', {'message': user_message})
131
  logger.important(f"Message sent: {user_message}")
132
+ timeout = 1800 / 1000 # Timeout in seconds after the last message is received
133
+ while True:
134
+ try:
135
+ data = await asyncio.wait_for(self.message_queue.get(), timeout)
136
+ yield data
137
+ except asyncio.TimeoutError:
138
+ break
139
  except Exception as e:
140
  logger.error(f"Failed to send message: {e}")
141
 
 
146
  except Exception as e:
147
  logger.error(f"Failed to disconnect: {e}")
148
 
149
+
150