ZENLLC commited on
Commit
27d3e61
·
verified ·
1 Parent(s): 24761a4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -1
app.py CHANGED
@@ -353,6 +353,47 @@ def build_knowledge_base(
353
  return status, kb
354
 
355
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
  def chat_with_rag(
357
  user_message: str,
358
  api_key: str,
@@ -417,7 +458,10 @@ def chat_with_rag(
417
  messages=messages,
418
  max_completion_tokens=900, # GPT-5-compatible param
419
  )
420
- answer = resp.choices[0].message.content or ""
 
 
 
421
  except Exception as e:
422
  answer = f"⚠️ OpenAI API error: {e}"
423
 
 
353
  return status, kb
354
 
355
 
356
+ def normalize_openai_content(raw_content: Any) -> str:
357
+ """
358
+ Normalize OpenAI message.content into a plain string.
359
+ Handles cases where content is:
360
+ - string
361
+ - list of parts (with .text or ['text'])
362
+ - dict
363
+ - None
364
+ """
365
+ if raw_content is None:
366
+ return ""
367
+
368
+ # Simple string
369
+ if isinstance(raw_content, str):
370
+ return raw_content.strip()
371
+
372
+ # List of parts
373
+ if isinstance(raw_content, list):
374
+ parts: List[str] = []
375
+ for p in raw_content:
376
+ text_piece = ""
377
+ if isinstance(p, dict):
378
+ text_piece = p.get("text") or ""
379
+ else:
380
+ # object with .text or fallback to str
381
+ text_piece = getattr(p, "text", "") or ""
382
+ if not text_piece:
383
+ text_piece = str(p)
384
+ parts.append(text_piece)
385
+ return "\n".join(parts).strip()
386
+
387
+ # Dict or something else: best-effort stringify
388
+ if isinstance(raw_content, dict):
389
+ text_piece = raw_content.get("text")
390
+ if isinstance(text_piece, str):
391
+ return text_piece.strip()
392
+ return str(raw_content)
393
+
394
+ return str(raw_content).strip()
395
+
396
+
397
  def chat_with_rag(
398
  user_message: str,
399
  api_key: str,
 
458
  messages=messages,
459
  max_completion_tokens=900, # GPT-5-compatible param
460
  )
461
+ raw_content = resp.choices[0].message.content
462
+ answer = normalize_openai_content(raw_content)
463
+ if not answer:
464
+ answer = "⚠️ Model returned an empty response. This may be a transient issue with the API."
465
  except Exception as e:
466
  answer = f"⚠️ OpenAI API error: {e}"
467