tecuts commited on
Commit
d8153f4
·
verified ·
1 Parent(s): 0d8d241

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -14
app.py CHANGED
@@ -406,20 +406,33 @@ async def chat_endpoint(request: Request, _: None = Depends(verify_origin)):
406
  }
407
 
408
  async with httpx.AsyncClient() as http_client:
409
- response = await http_client.post(f"{LLM_BASE_URL}/chat/completions", headers=headers, json=payload)
410
- async for line in response.aiter_lines():
411
- if line.startswith("data: "):
412
- data = line[len("data: "):]
413
- if data.strip() == "[DONE]":
414
- yield "data: [DONE]\n\n"
415
- break
416
- try:
417
- chunk = json.loads(data)
418
- content = chunk.get("choices", [{}])[0].get("delta", {}).get("content", "")
419
- if content:
420
- yield f"data: {json.dumps({'chunk': content, 'sources': source_links, 'search_used': bool(tool_calls), 'temperature': temperature, 'timestamp': datetime.now().isoformat()})}\n\n"
421
- except json.JSONDecodeError:
422
- continue
 
 
 
 
 
 
 
 
 
 
 
 
 
423
 
424
  # 发送结束信号
425
  yield "data: [DONE]\n\n"
 
406
  }
407
 
408
  async with httpx.AsyncClient() as http_client:
409
+ try:
410
+ response = await http_client.post(f"{LLM_BASE_URL}/chat/completions", headers=headers, json=payload)
411
+ response.raise_for_status() # Raise HTTP errors
412
+ async for line in response.aiter_lines():
413
+ if line.startswith("data: "):
414
+ data = line[len("data: "):]
415
+ if data.strip() == "[DONE]":
416
+ yield "data: [DONE]\n\n"
417
+ break
418
+ try:
419
+ chunk = json.loads(data)
420
+ content = chunk.get("choices", [{}])[0].get("delta", {}).get("content", "")
421
+ if content:
422
+ yield f"data: {json.dumps({'chunk': content, 'sources': source_links, 'search_used': bool(tool_calls), 'temperature': temperature, 'timestamp': datetime.now().isoformat()})}\n\n"
423
+ except json.JSONDecodeError:
424
+ logger.warning(f"Failed to decode JSON chunk: {data}")
425
+ continue
426
+ except httpx.HTTPError as e:
427
+ logger.error(f"HTTP request failed: {str(e)}")
428
+ yield f"data: {json.dumps({'error': 'Failed to generate response', 'details': str(e)})}\n\n"
429
+ yield "data: [DONE]\n\n"
430
+ return
431
+ except Exception as e:
432
+ logger.error(f"Unexpected error in streaming response: {str(e)}")
433
+ yield f"data: {json.dumps({'error': 'An unexpected error occurred', 'details': str(e)})}\n\n"
434
+ yield "data: [DONE]\n\n"
435
+ return
436
 
437
  # 发送结束信号
438
  yield "data: [DONE]\n\n"