Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -10,7 +10,7 @@ from fastapi.responses import StreamingResponse
|
|
10 |
from httpx import AsyncClient, RequestError, Timeout
|
11 |
from starlette.types import Receive, Scope, Send
|
12 |
|
13 |
-
API_KEYS = [line for line in environ['API_KEYS'].strip().split('\n') if line and line.startswith('sk-')]
|
14 |
COMPLETIONS_URL = 'https://openrouter.ai/api/v1/chat/completions'
|
15 |
app = FastAPI(title='reverse-proxy')
|
16 |
|
@@ -120,27 +120,31 @@ async def proxy_openai_api(request: Request):
|
|
120 |
raise AuthError('ключ API недействителен или превышен лимит отправки запросов')
|
121 |
if stream_response.status_code == 403:
|
122 |
raise CensoredError('отклонено по цензуре') # это специфичная ошибка именно для опенроутера!
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
|
|
|
|
127 |
if chunk.strip():
|
128 |
yield chunk.strip()
|
129 |
-
|
130 |
-
|
131 |
except RequestError as exc:
|
132 |
raise HTTPException(status_code=500, detail=f'произошла ошибка при запросе: {exc}')
|
133 |
|
|
|
134 |
async def try_api_keys():
|
135 |
for api_key in API_KEYS:
|
136 |
try:
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
except AuthError:
|
141 |
print(f'ключ API {api_key} недействителен или превышен лимит отправки запросов')
|
142 |
continue
|
143 |
-
|
|
|
|
|
144 |
|
145 |
return await try_api_keys()
|
146 |
|
|
|
10 |
from httpx import AsyncClient, RequestError, Timeout
|
11 |
from starlette.types import Receive, Scope, Send
|
12 |
|
13 |
+
API_KEYS = ['bad_key'] + [line for line in environ['API_KEYS'].strip().split('\n') if line and line.startswith('sk-')]
|
14 |
COMPLETIONS_URL = 'https://openrouter.ai/api/v1/chat/completions'
|
15 |
app = FastAPI(title='reverse-proxy')
|
16 |
|
|
|
120 |
raise AuthError('ключ API недействителен или превышен лимит отправки запросов')
|
121 |
if stream_response.status_code == 403:
|
122 |
raise CensoredError('отклонено по цензуре') # это специфичная ошибка именно для опенроутера!
|
123 |
+
|
124 |
+
# Инициализация заголовков должна быть здесь, используя объект stream_response
|
125 |
+
headers_to_send = {k: v for k, v in stream_response.headers.items() if k not in {'content-length', 'content-encoding', 'alt-svc'}}
|
126 |
+
response = OverrideStreamResponse(stream_response.aiter_bytes(), headers=headers_to_send)
|
127 |
+
|
128 |
+
async for chunk in response.body_iterator:
|
129 |
if chunk.strip():
|
130 |
yield chunk.strip()
|
131 |
+
|
|
|
132 |
except RequestError as exc:
|
133 |
raise HTTPException(status_code=500, detail=f'произошла ошибка при запросе: {exc}')
|
134 |
|
135 |
+
|
136 |
async def try_api_keys():
|
137 |
for api_key in API_KEYS:
|
138 |
try:
|
139 |
+
async for chunk in stream_api_response(api_key):
|
140 |
+
yield chunk
|
141 |
+
break # Если получили данные, выходим из цикла
|
142 |
except AuthError:
|
143 |
print(f'ключ API {api_key} недействителен или превышен лимит отправки запросов')
|
144 |
continue
|
145 |
+
else:
|
146 |
+
raise HTTPException(status_code=401, detail='все ключи API использованы, доступ запрещен.')
|
147 |
+
|
148 |
|
149 |
return await try_api_keys()
|
150 |
|