Update app.py
Browse files
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 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
if
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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"
|