Spaces:
Running
Running
Update api/utils.py
Browse files- api/utils.py +70 -31
api/utils.py
CHANGED
@@ -2,6 +2,7 @@ from datetime import datetime
|
|
2 |
import json
|
3 |
from typing import Any, Dict, Optional
|
4 |
import uuid
|
|
|
5 |
|
6 |
import httpx
|
7 |
from api import validate
|
@@ -71,6 +72,9 @@ def message_to_dict(message):
|
|
71 |
|
72 |
|
73 |
async def process_streaming_response(request: ChatRequest):
|
|
|
|
|
|
|
74 |
json_data = {
|
75 |
"messages": [message_to_dict(msg) for msg in request.messages],
|
76 |
"previewToken": None,
|
@@ -94,47 +98,82 @@ async def process_streaming_response(request: ChatRequest):
|
|
94 |
"validated": validate.getHid()
|
95 |
}
|
96 |
|
97 |
-
|
98 |
try:
|
99 |
-
async with
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
107 |
response.raise_for_status()
|
108 |
async for line in response.aiter_lines():
|
109 |
timestamp = int(datetime.now().timestamp())
|
110 |
if line:
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
|
|
|
|
|
|
|
|
120 |
yield f"data: {json.dumps(create_chat_completion_data(content, request.model, timestamp))}\n\n"
|
|
|
|
|
|
|
121 |
|
122 |
yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
|
123 |
yield "data: [DONE]\n\n"
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
131 |
except httpx.RequestError as e:
|
132 |
-
logger.error(f"
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
138 |
|
139 |
|
140 |
async def process_non_streaming_response(request: ChatRequest):
|
|
|
2 |
import json
|
3 |
from typing import Any, Dict, Optional
|
4 |
import uuid
|
5 |
+
import asyncio
|
6 |
|
7 |
import httpx
|
8 |
from api import validate
|
|
|
72 |
|
73 |
|
74 |
async def process_streaming_response(request: ChatRequest):
|
75 |
+
max_retries = 3
|
76 |
+
retry_delay = 1
|
77 |
+
|
78 |
json_data = {
|
79 |
"messages": [message_to_dict(msg) for msg in request.messages],
|
80 |
"previewToken": None,
|
|
|
98 |
"validated": validate.getHid()
|
99 |
}
|
100 |
|
101 |
+
for attempt in range(max_retries):
|
102 |
try:
|
103 |
+
async with httpx.AsyncClient(timeout=120.0) as client:
|
104 |
+
async with client.stream(
|
105 |
+
"POST",
|
106 |
+
f"{BASE_URL}/api/chat",
|
107 |
+
headers=headers,
|
108 |
+
json=json_data,
|
109 |
+
) as response:
|
110 |
+
if response.status_code == 500:
|
111 |
+
# 如果是500错误,尝试刷新hid
|
112 |
+
validate.getHid(True)
|
113 |
+
# 更新json_data中的validated值
|
114 |
+
json_data["validated"] = validate.getHid()
|
115 |
+
if attempt < max_retries - 1:
|
116 |
+
await asyncio.sleep(retry_delay)
|
117 |
+
continue
|
118 |
+
|
119 |
response.raise_for_status()
|
120 |
async for line in response.aiter_lines():
|
121 |
timestamp = int(datetime.now().timestamp())
|
122 |
if line:
|
123 |
+
try:
|
124 |
+
content = line + "\n"
|
125 |
+
if "https://www.blackbox.ai" in content:
|
126 |
+
validate.getHid(True)
|
127 |
+
content = "正在刷新会话,请重试\n"
|
128 |
+
yield f"data: {json.dumps(create_chat_completion_data(content, request.model, timestamp))}\n\n"
|
129 |
+
yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
|
130 |
+
yield "data: [DONE]\n\n"
|
131 |
+
return
|
132 |
+
|
133 |
+
if content.startswith("$@$v=undefined-rv1$@$"):
|
134 |
+
content = content[21:]
|
135 |
+
|
136 |
yield f"data: {json.dumps(create_chat_completion_data(content, request.model, timestamp))}\n\n"
|
137 |
+
except Exception as e:
|
138 |
+
logger.error(f"Error processing line: {e}")
|
139 |
+
continue
|
140 |
|
141 |
yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
|
142 |
yield "data: [DONE]\n\n"
|
143 |
+
return
|
144 |
+
|
145 |
+
except httpx.HTTPStatusError as e:
|
146 |
+
logger.error(f"HTTP error occurred: {e}")
|
147 |
+
if attempt == max_retries - 1:
|
148 |
+
error_message = "服务暂时不可用,请稍后重试"
|
149 |
+
timestamp = int(datetime.now().timestamp())
|
150 |
+
yield f"data: {json.dumps(create_chat_completion_data(error_message, request.model, timestamp))}\n\n"
|
151 |
+
yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
|
152 |
+
yield "data: [DONE]\n\n"
|
153 |
+
return
|
154 |
+
await asyncio.sleep(retry_delay)
|
155 |
+
|
156 |
except httpx.RequestError as e:
|
157 |
+
logger.error(f"Request error occurred: {e}")
|
158 |
+
if attempt == max_retries - 1:
|
159 |
+
error_message = "网络连接错误,请检查网络后重试"
|
160 |
+
timestamp = int(datetime.now().timestamp())
|
161 |
+
yield f"data: {json.dumps(create_chat_completion_data(error_message, request.model, timestamp))}\n\n"
|
162 |
+
yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
|
163 |
+
yield "data: [DONE]\n\n"
|
164 |
+
return
|
165 |
+
await asyncio.sleep(retry_delay)
|
166 |
+
|
167 |
+
except Exception as e:
|
168 |
+
logger.error(f"Unexpected error: {e}")
|
169 |
+
if attempt == max_retries - 1:
|
170 |
+
error_message = "发生未知错误,请重试"
|
171 |
+
timestamp = int(datetime.now().timestamp())
|
172 |
+
yield f"data: {json.dumps(create_chat_completion_data(error_message, request.model, timestamp))}\n\n"
|
173 |
+
yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
|
174 |
+
yield "data: [DONE]\n\n"
|
175 |
+
return
|
176 |
+
await asyncio.sleep(retry_delay)
|
177 |
|
178 |
|
179 |
async def process_non_streaming_response(request: ChatRequest):
|