Ganesh Chintalapati commited on
Commit
6e59463
·
1 Parent(s): a64da77

Fix syntax3

Browse files
Files changed (1) hide show
  1. app.py +10 -4
app.py CHANGED
@@ -1,6 +1,7 @@
1
  import os
2
  import logging
3
  import httpx
 
4
  from dotenv import load_dotenv
5
  import gradio as gr
6
  from typing import AsyncGenerator, List, Dict, Tuple
@@ -55,15 +56,20 @@ async def ask_openai(query: str, history: List[Dict[str, str]]) -> AsyncGenerato
55
  data = line[6:] # Remove "data: " prefix
56
  if data == "[DONE]":
57
  break
 
 
58
  try:
59
- json_data = eval(data) # Safely parse JSON
60
  if "choices" in json_data and json_data["choices"]:
61
  delta = json_data["choices"][0].get("delta", {})
62
- if "content" in delta:
63
  yield delta["content"]
64
- except Exception as e:
65
- logger.error(f"Error parsing OpenAI stream chunk: {str(e)}")
66
  yield f"Error parsing stream: {str(e)}"
 
 
 
67
 
68
  except httpx.HTTPStatusError as e:
69
  logger.error(f"OpenAI HTTP Status Error: {e.response.status_code}, {e.response.text}")
 
1
  import os
2
  import logging
3
  import httpx
4
+ import json
5
  from dotenv import load_dotenv
6
  import gradio as gr
7
  from typing import AsyncGenerator, List, Dict, Tuple
 
56
  data = line[6:] # Remove "data: " prefix
57
  if data == "[DONE]":
58
  break
59
+ if not data.strip():
60
+ continue
61
  try:
62
+ json_data = json.loads(data) # Safely parse JSON
63
  if "choices" in json_data and json_data["choices"]:
64
  delta = json_data["choices"][0].get("delta", {})
65
+ if "content" in delta and delta["content"] is not None:
66
  yield delta["content"]
67
+ except json.JSONDecodeError as e:
68
+ logger.error(f"Error parsing OpenAI stream chunk: {str(e)} - Data: {data}")
69
  yield f"Error parsing stream: {str(e)}"
70
+ except Exception as e:
71
+ logger.error(f"Unexpected error in OpenAI stream: {str(e)} - Data: {data}")
72
+ yield f"Error in stream: {str(e)}"
73
 
74
  except httpx.HTTPStatusError as e:
75
  logger.error(f"OpenAI HTTP Status Error: {e.response.status_code}, {e.response.text}")