dan92 commited on
Commit
fd49f49
·
verified ·
1 Parent(s): e3c38b5

Update api/utils.py

Browse files
Files changed (1) hide show
  1. 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
- async with httpx.AsyncClient() as client:
98
  try:
99
- async with client.stream(
100
- "POST",
101
- f"{BASE_URL}/api/chat",
102
- headers=headers,
103
- json=json_data,
104
- timeout=100,
105
- ) as response:
106
- try:
 
 
 
 
 
 
 
 
107
  response.raise_for_status()
108
  async for line in response.aiter_lines():
109
  timestamp = int(datetime.now().timestamp())
110
  if line:
111
- content = line + "\n"
112
- if "https://www.blackbox.ai" in content:
113
- validate.getHid(True)
114
- content = "hid已刷新,重新对话即可\n"
115
- yield f"data: {json.dumps(create_chat_completion_data(content, request.model, timestamp))}\n\n"
116
- break
117
- if content.startswith("$@$v=undefined-rv1$@$"):
118
- yield f"data: {json.dumps(create_chat_completion_data(content[21:], request.model, timestamp))}\n\n"
119
- else:
 
 
 
 
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
- except httpx.HTTPStatusError as e:
125
- logger.error(f"HTTP error occurred: {e}")
126
- error_message = "抱歉,服务器暂时无法处理您的请求。请稍后重试。"
127
- timestamp = int(datetime.now().timestamp())
128
- yield f"data: {json.dumps(create_chat_completion_data(error_message, 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
  except httpx.RequestError as e:
132
- logger.error(f"Error occurred during request: {e}")
133
- error_message = "抱歉,连接服务器时出现错误。请检查网络连接并重试。"
134
- timestamp = int(datetime.now().timestamp())
135
- yield f"data: {json.dumps(create_chat_completion_data(error_message, request.model, timestamp))}\n\n"
136
- yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
137
- yield "data: [DONE]\n\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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):