Fix the bug where the end of the GPT format response does not have a newline
Browse files- main.py +12 -6
- response.py +28 -24
main.py
CHANGED
|
@@ -62,13 +62,18 @@ config, api_keys_db, api_list = load_config()
|
|
| 62 |
async def error_handling_wrapper(generator, status_code=200):
|
| 63 |
try:
|
| 64 |
first_item = await generator.__anext__()
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
# 如果第一个 yield 的项是错误信息,抛出 HTTPException
|
| 71 |
-
raise HTTPException(status_code=status_code, detail=
|
| 72 |
|
| 73 |
# 如果不是错误,创建一个新的生成器,首先yield第一个项,然后yield剩余的项
|
| 74 |
async def new_generator():
|
|
@@ -183,6 +188,7 @@ class ModelRequestHandler:
|
|
| 183 |
except Exception as e:
|
| 184 |
print('\033[31m')
|
| 185 |
print(f"Error with provider {provider['provider']}: {str(e)}")
|
|
|
|
| 186 |
print('\033[0m')
|
| 187 |
if use_round_robin:
|
| 188 |
continue
|
|
|
|
| 62 |
async def error_handling_wrapper(generator, status_code=200):
|
| 63 |
try:
|
| 64 |
first_item = await generator.__anext__()
|
| 65 |
+
first_item_str = first_item
|
| 66 |
+
if isinstance(first_item_str, (bytes, bytearray)):
|
| 67 |
+
first_item_str = first_item_str.decode("utf-8")
|
| 68 |
+
if isinstance(first_item_str, str):
|
| 69 |
+
if first_item_str.startswith("data: "):
|
| 70 |
+
first_item_str = first_item_str[6:]
|
| 71 |
+
elif first_item_str.startswith("data:"):
|
| 72 |
+
first_item_str = first_item_str[5:]
|
| 73 |
+
first_item_str = json.loads(first_item_str)
|
| 74 |
+
if isinstance(first_item_str, dict) and 'error' in first_item_str:
|
| 75 |
# 如果第一个 yield 的项是错误信息,抛出 HTTPException
|
| 76 |
+
raise HTTPException(status_code=status_code, detail=first_item_str)
|
| 77 |
|
| 78 |
# 如果不是错误,创建一个新的生成器,首先yield第一个项,然后yield剩余的项
|
| 79 |
async def new_generator():
|
|
|
|
| 188 |
except Exception as e:
|
| 189 |
print('\033[31m')
|
| 190 |
print(f"Error with provider {provider['provider']}: {str(e)}")
|
| 191 |
+
traceback.print_exc()
|
| 192 |
print('\033[0m')
|
| 193 |
if use_round_robin:
|
| 194 |
continue
|
response.py
CHANGED
|
@@ -53,34 +53,42 @@ async def fetch_gemini_response_stream(client, url, headers, payload, model):
|
|
| 53 |
except json.JSONDecodeError:
|
| 54 |
print(f"无法解析JSON: {line}")
|
| 55 |
|
| 56 |
-
# 处理缓冲区中剩余的内容
|
| 57 |
-
if buffer:
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
# yield "data: [DONE]\n\n"
|
| 70 |
|
| 71 |
async def fetch_gpt_response_stream(client, url, headers, payload):
|
| 72 |
async with client.stream('POST', url, headers=headers, json=payload) as response:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
async for chunk in response.aiter_bytes():
|
| 74 |
-
print(chunk.decode('utf-8'))
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
async def fetch_claude_response_stream(client, url, headers, payload, model):
|
| 78 |
timestamp = datetime.timestamp(datetime.now())
|
| 79 |
async with client.stream('POST', url, headers=headers, json=payload) as response:
|
| 80 |
-
|
| 81 |
-
if response.status_code == 200:
|
| 82 |
-
print("请求成功,状态码是200")
|
| 83 |
-
else:
|
| 84 |
print('\033[31m')
|
| 85 |
print(f"请求失败,状态码是{response.status_code},错误信息:")
|
| 86 |
error_message = await response.aread()
|
|
@@ -89,8 +97,6 @@ async def fetch_claude_response_stream(client, url, headers, payload, model):
|
|
| 89 |
print(json.dumps(error_json, indent=4, ensure_ascii=False))
|
| 90 |
print('\033[0m')
|
| 91 |
yield {"error": f"HTTP Error {response.status_code}", "details": error_json}
|
| 92 |
-
# raise HTTPStatusError(f"HTTP Error {response.status_code}", request=response.request, response=response)
|
| 93 |
-
# raise HTTPException(status_code=response.status_code, detail=error_json)
|
| 94 |
buffer = ""
|
| 95 |
async for chunk in response.aiter_bytes():
|
| 96 |
buffer += chunk.decode('utf-8')
|
|
@@ -136,8 +142,6 @@ async def fetch_claude_response_stream(client, url, headers, payload, model):
|
|
| 136 |
sse_string = await generate_sse_response(timestamp, model, None, None, None, function_call_content)
|
| 137 |
yield sse_string
|
| 138 |
|
| 139 |
-
# yield "data: [DONE]\n\n"
|
| 140 |
-
|
| 141 |
async def fetch_response(client, url, headers, payload):
|
| 142 |
response = await client.post(url, headers=headers, json=payload)
|
| 143 |
return response.json()
|
|
|
|
| 53 |
except json.JSONDecodeError:
|
| 54 |
print(f"无法解析JSON: {line}")
|
| 55 |
|
| 56 |
+
# # 处理缓冲区中剩余的内容
|
| 57 |
+
# if buffer:
|
| 58 |
+
# # print(buffer)
|
| 59 |
+
# if '\"text\": \"' in buffer:
|
| 60 |
+
# try:
|
| 61 |
+
# json_data = json.loads(buffer)
|
| 62 |
+
# content = json_data.get('text', '')
|
| 63 |
+
# content = "\n".join(content.split("\\n"))
|
| 64 |
+
# sse_string = await generate_sse_response(timestamp, model, content)
|
| 65 |
+
# yield sse_string
|
| 66 |
+
# except json.JSONDecodeError:
|
| 67 |
+
# print(f"无法解析JSON: {buffer}")
|
|
|
|
|
|
|
| 68 |
|
| 69 |
async def fetch_gpt_response_stream(client, url, headers, payload):
|
| 70 |
async with client.stream('POST', url, headers=headers, json=payload) as response:
|
| 71 |
+
# print("response.status_code", response.status_code)
|
| 72 |
+
if response.status_code != 200:
|
| 73 |
+
print("请求失败,状态码是", response.status_code)
|
| 74 |
+
error_message = await response.aread()
|
| 75 |
+
error_str = error_message.decode('utf-8', errors='replace')
|
| 76 |
+
error_json = json.loads(error_str)
|
| 77 |
+
print(json.dumps(error_json, indent=4, ensure_ascii=False))
|
| 78 |
+
yield {"error": f"HTTP Error {response.status_code}", "details": error_json}
|
| 79 |
+
buffer = ""
|
| 80 |
async for chunk in response.aiter_bytes():
|
| 81 |
+
# print("chunk.decode('utf-8')", chunk.decode('utf-8'))
|
| 82 |
+
buffer += chunk.decode('utf-8')
|
| 83 |
+
while "\n" in buffer:
|
| 84 |
+
line, buffer = buffer.split("\n", 1)
|
| 85 |
+
print(line)
|
| 86 |
+
yield line + "\n"
|
| 87 |
|
| 88 |
async def fetch_claude_response_stream(client, url, headers, payload, model):
|
| 89 |
timestamp = datetime.timestamp(datetime.now())
|
| 90 |
async with client.stream('POST', url, headers=headers, json=payload) as response:
|
| 91 |
+
if response.status_code != 200:
|
|
|
|
|
|
|
|
|
|
| 92 |
print('\033[31m')
|
| 93 |
print(f"请求失败,状态码是{response.status_code},错误信息:")
|
| 94 |
error_message = await response.aread()
|
|
|
|
| 97 |
print(json.dumps(error_json, indent=4, ensure_ascii=False))
|
| 98 |
print('\033[0m')
|
| 99 |
yield {"error": f"HTTP Error {response.status_code}", "details": error_json}
|
|
|
|
|
|
|
| 100 |
buffer = ""
|
| 101 |
async for chunk in response.aiter_bytes():
|
| 102 |
buffer += chunk.decode('utf-8')
|
|
|
|
| 142 |
sse_string = await generate_sse_response(timestamp, model, None, None, None, function_call_content)
|
| 143 |
yield sse_string
|
| 144 |
|
|
|
|
|
|
|
| 145 |
async def fetch_response(client, url, headers, payload):
|
| 146 |
response = await client.post(url, headers=headers, json=payload)
|
| 147 |
return response.json()
|