T-K-O-H commited on
Commit
373c86e
·
1 Parent(s): ce330ae

Fix WebSocket connection and add error handling

Browse files
Files changed (2) hide show
  1. app.py +9 -4
  2. index.html +36 -8
app.py CHANGED
@@ -100,7 +100,6 @@ def get_stock_history(symbol: str, period: str = "1mo") -> str:
100
  logger.error(f"Error getting stock history: {str(e)}")
101
  return f"Error getting stock history: {str(e)}"
102
 
103
- # Create tools list
104
  logger.info("Creating tools list...")
105
  tools = [get_stock_price, get_stock_info, get_stock_history]
106
 
@@ -178,9 +177,10 @@ async def websocket_endpoint(websocket: WebSocket):
178
  chat_history = [] # Initialize chat history
179
  try:
180
  while True:
181
- data = await websocket.receive_text()
182
- logger.info(f"Received message: {data}")
183
  try:
 
 
 
184
  # Add user message to chat history
185
  chat_history.append(HumanMessage(content=data))
186
 
@@ -198,9 +198,14 @@ async def websocket_endpoint(websocket: WebSocket):
198
  except Exception as e:
199
  logger.error(f"Error processing message: {str(e)}")
200
  await websocket.send_json({"type": "error", "content": f"Error processing message: {str(e)}"})
 
 
201
  except Exception as e:
202
  logger.error(f"WebSocket error: {str(e)}")
203
- await websocket.close()
 
 
 
204
 
205
 
206
  # Serve the HTML frontend
 
100
  logger.error(f"Error getting stock history: {str(e)}")
101
  return f"Error getting stock history: {str(e)}"
102
 
 
103
  logger.info("Creating tools list...")
104
  tools = [get_stock_price, get_stock_info, get_stock_history]
105
 
 
177
  chat_history = [] # Initialize chat history
178
  try:
179
  while True:
 
 
180
  try:
181
+ data = await websocket.receive_text()
182
+ logger.info(f"Received message: {data}")
183
+
184
  # Add user message to chat history
185
  chat_history.append(HumanMessage(content=data))
186
 
 
198
  except Exception as e:
199
  logger.error(f"Error processing message: {str(e)}")
200
  await websocket.send_json({"type": "error", "content": f"Error processing message: {str(e)}"})
201
+ except WebSocketDisconnect:
202
+ logger.info("Client disconnected")
203
  except Exception as e:
204
  logger.error(f"WebSocket error: {str(e)}")
205
+ try:
206
+ await websocket.close()
207
+ except:
208
+ pass
209
 
210
 
211
  # Serve the HTML frontend
index.html CHANGED
@@ -104,11 +104,32 @@
104
  </div>
105
 
106
  <script>
107
- const ws = new WebSocket('ws://' + window.location.host + '/ws');
108
  const chatContainer = document.getElementById('chatContainer');
109
  const userInput = document.getElementById('userInput');
110
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  ws.onmessage = function(event) {
 
112
  const data = JSON.parse(event.data);
113
  const messageDiv = document.createElement('div');
114
  messageDiv.className = 'message ' + (data.type === 'ai_message' ? 'ai-message' : 'error-message');
@@ -120,14 +141,21 @@
120
  function sendMessage() {
121
  const message = userInput.value.trim();
122
  if (message) {
123
- const messageDiv = document.createElement('div');
124
- messageDiv.className = 'message user-message';
125
- messageDiv.textContent = message;
126
- chatContainer.appendChild(messageDiv);
127
- chatContainer.scrollTop = chatContainer.scrollHeight;
 
128
 
129
- ws.send(message);
130
- userInput.value = '';
 
 
 
 
 
 
131
  }
132
  }
133
 
 
104
  </div>
105
 
106
  <script>
107
+ const ws = new WebSocket('wss://' + window.location.host + '/ws');
108
  const chatContainer = document.getElementById('chatContainer');
109
  const userInput = document.getElementById('userInput');
110
 
111
+ ws.onopen = function() {
112
+ console.log('WebSocket connection established');
113
+ };
114
+
115
+ ws.onerror = function(error) {
116
+ console.error('WebSocket error:', error);
117
+ const messageDiv = document.createElement('div');
118
+ messageDiv.className = 'message error-message';
119
+ messageDiv.textContent = 'Connection error. Please refresh the page.';
120
+ chatContainer.appendChild(messageDiv);
121
+ };
122
+
123
+ ws.onclose = function() {
124
+ console.log('WebSocket connection closed');
125
+ const messageDiv = document.createElement('div');
126
+ messageDiv.className = 'message error-message';
127
+ messageDiv.textContent = 'Connection closed. Please refresh the page.';
128
+ chatContainer.appendChild(messageDiv);
129
+ };
130
+
131
  ws.onmessage = function(event) {
132
+ console.log('Received message:', event.data);
133
  const data = JSON.parse(event.data);
134
  const messageDiv = document.createElement('div');
135
  messageDiv.className = 'message ' + (data.type === 'ai_message' ? 'ai-message' : 'error-message');
 
141
  function sendMessage() {
142
  const message = userInput.value.trim();
143
  if (message) {
144
+ if (ws.readyState === WebSocket.OPEN) {
145
+ const messageDiv = document.createElement('div');
146
+ messageDiv.className = 'message user-message';
147
+ messageDiv.textContent = message;
148
+ chatContainer.appendChild(messageDiv);
149
+ chatContainer.scrollTop = chatContainer.scrollHeight;
150
 
151
+ ws.send(message);
152
+ userInput.value = '';
153
+ } else {
154
+ const messageDiv = document.createElement('div');
155
+ messageDiv.className = 'message error-message';
156
+ messageDiv.textContent = 'Not connected. Please refresh the page.';
157
+ chatContainer.appendChild(messageDiv);
158
+ }
159
  }
160
  }
161