fixed handling of streaming response
Browse files
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 |
-
|
122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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:
|