louiecerv commited on
Commit
e6bd973
·
1 Parent(s): 4880a2a

fixed handling of streaming response

Browse files
Files changed (1) hide show
  1. app.py +19 -7
app.py CHANGED
@@ -108,18 +108,30 @@ def main():
108
  )
109
 
110
  if stream:
111
- print(f"response: {response.text}")
112
-
113
  response_container = st.empty()
114
  content = ""
115
  # Efficiently handle streaming response
116
  for chunk in response.iter_lines():
117
-
118
- print(f"chunk: {chunk}")
119
-
120
  if len(chunk) > 0:
121
- content += extract_content(chunk)
122
- response_container.markdown(content)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
 
124
  else:
125
  try:
 
108
  )
109
 
110
  if stream:
 
 
111
  response_container = st.empty()
112
  content = ""
113
  # Efficiently handle streaming response
114
  for chunk in response.iter_lines():
 
 
 
115
  if len(chunk) > 0:
116
+ # Decode the bytes object into a string
117
+ chunk_str = chunk.decode('utf-8')
118
+ # Remove the "data: " prefix
119
+ if chunk_str.startswith("data: "):
120
+ chunk_str = chunk_str[6:]
121
+ if chunk_str.strip() == "[DONE]":
122
+ break
123
+ # Check if the string is not empty
124
+ if chunk_str.strip() != "":
125
+ try:
126
+ # Attempt to parse the string as JSON
127
+ chunk_dict = json.loads(chunk_str)
128
+ # Now you can access the 'choices' key
129
+ content += chunk_dict['choices'][0]['delta']['content']
130
+ response_container.markdown(content)
131
+ except json.JSONDecodeError as e:
132
+ # Handle the error if the string is not valid JSON
133
+ print(f"Error parsing JSON: {e}")
134
+ print(f"Invalid JSON string: {chunk_str}")
135
 
136
  else:
137
  try: