Delete retry_middleware.py
Browse files- retry_middleware.py +0 -112
retry_middleware.py
DELETED
@@ -1,112 +0,0 @@
|
|
1 |
-
from starlette.middleware.base import BaseHTTPMiddleware
|
2 |
-
from fastapi import Request, Response
|
3 |
-
from fastapi.responses import JSONResponse
|
4 |
-
import json
|
5 |
-
import logging
|
6 |
-
|
7 |
-
logging.basicConfig(level=logging.INFO)
|
8 |
-
logger = logging.getLogger(__name__)
|
9 |
-
|
10 |
-
class RetryMiddleware(BaseHTTPMiddleware):
|
11 |
-
def __init__(self, app):
|
12 |
-
super().__init__(app)
|
13 |
-
|
14 |
-
async def should_retry_response(self, response_data):
|
15 |
-
"""检查响应是否需要重试"""
|
16 |
-
try:
|
17 |
-
if isinstance(response_data, dict):
|
18 |
-
# 检查错误信息
|
19 |
-
error = response_data.get('error', '')
|
20 |
-
if isinstance(error, str) and 'content is not safe' in error.lower():
|
21 |
-
return True
|
22 |
-
|
23 |
-
# 检查响应内容
|
24 |
-
choices = response_data.get('choices', [])
|
25 |
-
if choices:
|
26 |
-
content = choices[0].get('message', {}).get('content', '')
|
27 |
-
if not content or 'content is not safe' in content.lower():
|
28 |
-
return True
|
29 |
-
|
30 |
-
# 检查是否有部分内容包含错误信息
|
31 |
-
if isinstance(content, str):
|
32 |
-
lines = content.split('\n')
|
33 |
-
for line in lines:
|
34 |
-
if 'content is not safe' in line.lower():
|
35 |
-
return True
|
36 |
-
|
37 |
-
# 检查是否是不需要的响应
|
38 |
-
if "I'm Claude" in str(response_data) or "Anthropic" in str(response_data):
|
39 |
-
return True
|
40 |
-
if "Hello! How can I assist you today?" in str(response_data):
|
41 |
-
return True
|
42 |
-
|
43 |
-
# 检查响应格式
|
44 |
-
if not choices or not choices[0].get('message', {}).get('content'):
|
45 |
-
return True
|
46 |
-
|
47 |
-
return False
|
48 |
-
except Exception:
|
49 |
-
# 如果解析过程中出现任何错误,建议重试
|
50 |
-
return True
|
51 |
-
|
52 |
-
async def dispatch(self, request: Request, call_next):
|
53 |
-
# 只处理 /api/v1/chat/completions 路径的请求
|
54 |
-
if not request.url.path.endswith('/api/v1/chat/completions'):
|
55 |
-
return await call_next(request)
|
56 |
-
|
57 |
-
# 读取原始请求体
|
58 |
-
body = await request.body()
|
59 |
-
retry_count = 0
|
60 |
-
last_error = None
|
61 |
-
|
62 |
-
while True: # 无限循环,直到获得正确响应
|
63 |
-
try:
|
64 |
-
# 构造请求
|
65 |
-
async def receive():
|
66 |
-
return {
|
67 |
-
"type": "http.request",
|
68 |
-
"body": body,
|
69 |
-
"more_body": False,
|
70 |
-
}
|
71 |
-
|
72 |
-
# 发送请求并获取响应
|
73 |
-
response = await call_next(Request(request.scope, receive))
|
74 |
-
response_body = b""
|
75 |
-
async for chunk in response.body_iterator:
|
76 |
-
response_body += chunk
|
77 |
-
|
78 |
-
try:
|
79 |
-
response_data = json.loads(response_body)
|
80 |
-
|
81 |
-
# 检查响应是否需要重试
|
82 |
-
if await self.should_retry_response(response_data):
|
83 |
-
retry_count += 1
|
84 |
-
continue
|
85 |
-
else:
|
86 |
-
# 如果响应正常,直接返回
|
87 |
-
return Response(
|
88 |
-
content=response_body,
|
89 |
-
status_code=response.status_code,
|
90 |
-
headers=dict(response.headers),
|
91 |
-
media_type=response.media_type
|
92 |
-
)
|
93 |
-
|
94 |
-
except json.JSONDecodeError:
|
95 |
-
# JSON解析错误,需要重试
|
96 |
-
retry_count += 1
|
97 |
-
continue
|
98 |
-
|
99 |
-
except Exception as e:
|
100 |
-
last_error = str(e)
|
101 |
-
retry_count += 1
|
102 |
-
continue
|
103 |
-
|
104 |
-
# 使用方法:
|
105 |
-
"""
|
106 |
-
在 main.py 中添加:
|
107 |
-
from fastapi import FastAPI
|
108 |
-
from retry_middleware import RetryMiddleware
|
109 |
-
|
110 |
-
app = FastAPI()
|
111 |
-
app.add_middleware(RetryMiddleware, max_retries=3, delay=1.0)
|
112 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|