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

working callback function

Browse files
Files changed (2) hide show
  1. app.py +31 -30
  2. rasa_socketio_client.py +36 -15
app.py CHANGED
@@ -86,47 +86,48 @@ from rasa_socketio_client import RasaSocketIOClient
86
  import logging
87
  from custom_logging import IMPORTANT_LEVEL_NUM
88
 
89
- # Assuming custom_logging.py defines the IMPORTANT_LEVEL_NUM and extends the Logger class
90
- # Enable logging for the whole app
91
- logging.basicConfig(level=IMPORTANT_LEVEL_NUM, format='%(asctime)s - %(levelname)s - %(name)s - %(message)s')
92
  logger = logging.getLogger(__name__)
93
 
94
  rasa_io_url = "https://clairify.ai/socket.io"
95
- rasa_client = RasaSocketIOClient(rasa_io_url)
96
-
97
  theme = gr.themes.Default(primary_hue="cyan", secondary_hue="violet")
98
 
99
- async def interact_with_rasa(user_input, chat_history):
100
- logger.important(f"User input received: {user_input}")
101
- if not rasa_client.sio.connected:
102
- logger.important("Rasa client not connected, attempting to connect...")
103
- await rasa_client.connect()
104
- if rasa_client.sio.connected:
105
- logger.important("Rasa client successfully connected.")
106
- else:
107
- logger.important("Failed to connect to Rasa client.")
108
- return "Error connecting to chat service, please try again later.", chat_history
109
-
110
- payload = {"message": user_input}
111
- logger.important(f"Sending payload to Rasa: {payload}")
112
- rasa_response = await rasa_client.send_message(payload)
113
-
114
- if rasa_response is None or "text" not in rasa_response:
115
- logger.important(f"Invalid or None response from Rasa: {rasa_response}")
116
- return "Received an invalid response from the chat service.", chat_history
117
-
118
- logger.important(f"Rasa response: {rasa_response}")
119
- chat_history.append((user_input, rasa_response["text"]))
120
- return "", chat_history
121
-
122
  with gr.Blocks(theme=theme) as demo:
123
- chatbot = gr.Chatbot()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  msg = gr.Textbox(placeholder="Say Hi! to wake me up", show_label=False)
125
  clear = gr.ClearButton([msg, chatbot])
126
-
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
 
 
 
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
+
rasa_socketio_client.py CHANGED
@@ -101,41 +101,62 @@ logging.basicConfig(level=IMPORTANT_LEVEL_NUM)
101
  logger = logging.getLogger(__name__)
102
 
103
  class RasaSocketIOClient:
104
- def __init__(self, uri):
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
 
110
- @self.sio.on('bot_uttered') # Adjust the event name as per your Rasa setup
111
- async def on_message(data):
112
- # Use the new logging level
113
- logger.important("Socket ID: %s Received response: %s", self.sio.sid, data)
114
- self.response = data # Store the latest response
115
- self.response_event.set() # Signal that response has been received
 
 
 
 
116
 
117
  async def connect(self):
118
  try:
119
  await self.sio.connect(self.uri)
120
  logger.important("Successfully connected to the server.")
121
  except Exception as e:
122
- logger.important("Failed to connect to the server: %s", e)
123
- return "Failed to connect to the server."
124
 
125
- async def send_message(self, message):
 
 
126
  self.response = None # Reset previous response
127
  self.response_event.clear() # Reset the event for a new message
128
  try:
129
- await self.sio.emit('user_uttered', message) # Adjust the event name as per your Rasa setup
130
- logger.important("Message sent: %s", message)
131
  await self.response_event.wait() # Wait here until the response has been received
132
  except Exception as e:
133
- logger.important("Failed to send message: %s", e)
134
- return self.response
135
 
136
  async def disconnect(self):
137
  try:
138
  await self.sio.disconnect()
139
  logger.important("Disconnected from the server.")
140
  except Exception as e:
141
- logger.important("Failed to disconnect: %s", e)
 
 
 
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.")
118
+
119
+ @self.sio.event
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:
138
  await self.sio.connect(self.uri)
139
  logger.important("Successfully connected to the server.")
140
  except Exception as e:
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
 
155
  async def disconnect(self):
156
  try:
157
  await self.sio.disconnect()
158
  logger.important("Disconnected from the server.")
159
  except Exception as e:
160
+ logger.error(f"Failed to disconnect: {e}")
161
+
162
+