pauladeeptech commited on
Commit
6322133
Β·
verified Β·
1 Parent(s): 4ab487d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -22
app.py CHANGED
@@ -154,7 +154,6 @@ def extract_text_from_history_item(content: str) -> str:
154
  # Fallback: just strip HTML
155
  return re.sub(r"<[^>]+>", " ", content).strip()
156
 
157
-
158
  # -----------------------------
159
  # Chat function
160
  # -----------------------------
@@ -166,28 +165,53 @@ def chat(user_message, history):
166
 
167
  messages = [{"role": "system", "content": SYSTEM_PROMPT}]
168
 
169
- # βœ… KEY FIX 1: Only keep last 3 exchanges (6 messages)
170
  recent_history = history[-3:] if len(history) > 3 else history
171
 
172
  print(f"πŸ“Š Processing request. History items: {len(history)}, keeping: {len(recent_history)}")
173
 
 
174
  for item in recent_history:
175
- if isinstance(item, dict):
176
- role = item.get("role", "")
177
- content = item.get("content", "")
178
- # βœ… Extract plain text properly
179
- clean = extract_text_from_history_item(content)
180
- messages.append({"role": role, "content": clean})
181
- elif isinstance(item, (list, tuple)) and len(item) == 2:
182
- u, a = item
183
- # βœ… Extract plain text from assistant response
184
- clean_a = extract_text_from_history_item(str(a))
185
- messages.append({"role": "user", "content": u})
186
- messages.append({"role": "assistant", "content": clean_a})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
 
188
  messages.append({"role": "user", "content": user_message})
189
 
190
- # βœ… Debug: Show message count
191
  print(f"πŸ“ Total messages being sent: {len(messages)}")
192
 
193
  headers = {
@@ -202,7 +226,7 @@ def chat(user_message, history):
202
  "stream": True,
203
  }
204
 
205
- # βœ… KEY FIX 2: Add retry logic
206
  max_retries = 2
207
  for attempt in range(max_retries):
208
  try:
@@ -212,11 +236,10 @@ def chat(user_message, history):
212
  r.encoding = "utf-8"
213
 
214
  if r.status_code != 200:
215
- print(f"❌ HF error (attempt {attempt+1}): {r.status_code} {r.text}")
216
 
217
- # βœ… Retry on rate limit
218
  if r.status_code == 429 and attempt < max_retries - 1:
219
- wait_time = 2 ** attempt # 1s, 2s
220
  print(f"⏰ Rate limited. Waiting {wait_time}s...")
221
  time.sleep(wait_time)
222
  continue
@@ -250,7 +273,6 @@ def chat(user_message, history):
250
  else:
251
  yield fallback_html(response_raw)
252
 
253
- # Success - exit retry loop
254
  return
255
 
256
  except requests.exceptions.Timeout:
@@ -263,7 +285,7 @@ def chat(user_message, history):
263
  return
264
 
265
  except Exception as e:
266
- print(f"❌ Request failed (attempt {attempt+1}):", repr(e))
267
  if attempt < max_retries - 1:
268
  time.sleep(2)
269
  continue
@@ -271,7 +293,6 @@ def chat(user_message, history):
271
  yield "Upsi β€” gerade klappt die Verbindung nicht. πŸ“š Probier es bitte gleich nochmal!"
272
  return
273
 
274
- # Should not reach here, but just in case
275
  yield "Upsi β€” gerade klappt die Verbindung nicht. πŸ“š Probier es bitte gleich nochmal!"
276
 
277
 
 
154
  # Fallback: just strip HTML
155
  return re.sub(r"<[^>]+>", " ", content).strip()
156
 
 
157
  # -----------------------------
158
  # Chat function
159
  # -----------------------------
 
165
 
166
  messages = [{"role": "system", "content": SYSTEM_PROMPT}]
167
 
168
+ # Keep last 3 exchanges
169
  recent_history = history[-3:] if len(history) > 3 else history
170
 
171
  print(f"πŸ“Š Processing request. History items: {len(history)}, keeping: {len(recent_history)}")
172
 
173
+ # Process history safely
174
  for item in recent_history:
175
+ try:
176
+ # Handle dict format
177
+ if isinstance(item, dict):
178
+ role = item.get("role", "")
179
+ content = item.get("content", "")
180
+
181
+ # Handle list content
182
+ if isinstance(content, list):
183
+ content = str(content[0]) if content and content[0] else ""
184
+ else:
185
+ content = str(content) if content else ""
186
+
187
+ clean = extract_text_from_history_item(content)
188
+ if clean:
189
+ messages.append({"role": role, "content": clean})
190
+
191
+ # Handle tuple/list format
192
+ elif isinstance(item, (list, tuple)) and len(item) >= 2:
193
+ u = str(item[0]) if item[0] else ""
194
+ a = item[1] if len(item) > 1 else ""
195
+
196
+ # Handle list in assistant response
197
+ if isinstance(a, list):
198
+ a = str(a[0]) if a and a[0] else ""
199
+ else:
200
+ a = str(a) if a else ""
201
+
202
+ clean_a = extract_text_from_history_item(a)
203
+
204
+ if u:
205
+ messages.append({"role": "user", "content": u})
206
+ if clean_a:
207
+ messages.append({"role": "assistant", "content": clean_a})
208
+
209
+ except Exception as e:
210
+ print(f"⚠️ Skipped history item: {e}")
211
+ continue
212
 
213
  messages.append({"role": "user", "content": user_message})
214
 
 
215
  print(f"πŸ“ Total messages being sent: {len(messages)}")
216
 
217
  headers = {
 
226
  "stream": True,
227
  }
228
 
229
+ # Retry logic
230
  max_retries = 2
231
  for attempt in range(max_retries):
232
  try:
 
236
  r.encoding = "utf-8"
237
 
238
  if r.status_code != 200:
239
+ print(f"❌ HF error (attempt {attempt+1}): {r.status_code}")
240
 
 
241
  if r.status_code == 429 and attempt < max_retries - 1:
242
+ wait_time = 2 ** attempt
243
  print(f"⏰ Rate limited. Waiting {wait_time}s...")
244
  time.sleep(wait_time)
245
  continue
 
273
  else:
274
  yield fallback_html(response_raw)
275
 
 
276
  return
277
 
278
  except requests.exceptions.Timeout:
 
285
  return
286
 
287
  except Exception as e:
288
+ print(f"❌ Request failed (attempt {attempt+1}): {repr(e)}")
289
  if attempt < max_retries - 1:
290
  time.sleep(2)
291
  continue
 
293
  yield "Upsi β€” gerade klappt die Verbindung nicht. πŸ“š Probier es bitte gleich nochmal!"
294
  return
295
 
 
296
  yield "Upsi β€” gerade klappt die Verbindung nicht. πŸ“š Probier es bitte gleich nochmal!"
297
 
298