Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix EventSourceResponse chunk splitting causes json loads to fail #3477

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 26 additions & 4 deletions webui_pages/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,22 +129,33 @@ def _httpx_stream2generator(
async def ret_async(response, as_json):
try:
async with response as r:
chunk_cache = ''
async for chunk in r.aiter_text(None):
if not chunk: # fastchat api yield empty bytes on start and end
continue
if as_json:
try:
if chunk.startswith("data: "):
data = json.loads(chunk[6:-2])
data = json.loads(chunk_cache + chunk[6:-2])
elif chunk.startswith(":"): # skip sse comment line
continue
else:
data = json.loads(chunk)
data = json.loads(chunk_cache + chunk)

chunk_cache = ''
yield data
except Exception as e:
msg = f"接口返回json错误: ‘{chunk}’。错误信息是:{e}。"
logger.error(f'{e.__class__.__name__}: {msg}',
exc_info=e if log_verbose else None)

if chunk.startswith("data: "):
chunk_cache += chunk[6:-2]
elif chunk.startswith(":"): # skip sse comment line
continue
else:
chunk_cache += chunk
continue
else:
# print(chunk, end="", flush=True)
yield chunk
Expand All @@ -165,22 +176,33 @@ async def ret_async(response, as_json):
def ret_sync(response, as_json):
try:
with response as r:
chunk_cache = ''
for chunk in r.iter_text(None):
if not chunk: # fastchat api yield empty bytes on start and end
continue
if as_json:
try:
if chunk.startswith("data: "):
data = json.loads(chunk[6:-2])
data = json.loads(chunk_cache + chunk[6:-2])
elif chunk.startswith(":"): # skip sse comment line
continue
else:
data = json.loads(chunk)
data = json.loads(chunk_cache + chunk)

chunk_cache = ''
yield data
except Exception as e:
msg = f"接口返回json错误: ‘{chunk}’。错误信息是:{e}。"
logger.error(f'{e.__class__.__name__}: {msg}',
exc_info=e if log_verbose else None)

if chunk.startswith("data: "):
chunk_cache += chunk[6:-2]
elif chunk.startswith(":"): # skip sse comment line
continue
else:
chunk_cache += chunk
continue
else:
# print(chunk, end="", flush=True)
yield chunk
Expand Down