Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,18 +3,16 @@ import httpx
|
|
| 3 |
from fastapi import FastAPI, Request, Response
|
| 4 |
|
| 5 |
app = FastAPI(
|
| 6 |
-
title="
|
| 7 |
-
description="A non-streaming proxy that
|
| 8 |
)
|
| 9 |
|
| 10 |
OR_BASE_URL = "https://api.openai.com/v1"
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
# Увеличим таймаут по умолчанию, т.к. генерация может быть долгой
|
| 14 |
client = httpx.AsyncClient(base_url=OR_BASE_URL, timeout=120.0)
|
| 15 |
|
| 16 |
-
# "Hop-by-hop" заголовки, которые не должны
|
| 17 |
-
# Они относятся к конкретному соединению, а не к сообщению в целом.
|
| 18 |
HOP_BY_HOP_HEADERS = {
|
| 19 |
"connection", "keep-alive", "proxy-authenticate", "proxy-authorization",
|
| 20 |
"te", "trailers", "transfer-encoding", "upgrade",
|
|
@@ -22,21 +20,20 @@ HOP_BY_HOP_HEADERS = {
|
|
| 22 |
|
| 23 |
@app.get("/")
|
| 24 |
async def home():
|
| 25 |
-
return {"status": "ok", "message": "
|
| 26 |
|
| 27 |
|
| 28 |
@app.api_route("/{endpoint:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE"])
|
| 29 |
async def proxy(endpoint: str, request: Request):
|
| 30 |
try:
|
| 31 |
-
# 1. Формируем URL для запроса к OpenAI
|
| 32 |
url = httpx.URL(path=f"/{endpoint}", query=request.url.query.encode("utf-8"))
|
| 33 |
|
| 34 |
-
#
|
| 35 |
headers = {k: v for k, v in request.headers.items() if k.lower() != "host"}
|
|
|
|
| 36 |
body = await request.body()
|
| 37 |
|
| 38 |
-
#
|
| 39 |
-
# Никакого stream=True. Мы ждем, пока `httpx` полностью загрузит ответ.
|
| 40 |
resp_openai = await client.request(
|
| 41 |
method=request.method,
|
| 42 |
url=url,
|
|
@@ -44,15 +41,13 @@ async def proxy(endpoint: str, request: Request):
|
|
| 44 |
content=body
|
| 45 |
)
|
| 46 |
|
| 47 |
-
#
|
| 48 |
-
# Все остальные заголовки (Content-Type, openai-*, и т.д.) будут сохранены
|
| 49 |
response_headers = {
|
| 50 |
k: v for k, v in resp_openai.headers.items()
|
| 51 |
if k.lower() not in HOP_BY_HOP_HEADERS
|
| 52 |
}
|
| 53 |
|
| 54 |
-
#
|
| 55 |
-
# Это не стриминг. Мы возвращаем готовый, полный ответ.
|
| 56 |
return Response(
|
| 57 |
content=resp_openai.content,
|
| 58 |
status_code=resp_openai.status_code,
|
|
@@ -60,8 +55,6 @@ async def proxy(endpoint: str, request: Request):
|
|
| 60 |
)
|
| 61 |
|
| 62 |
except httpx.RequestError as e:
|
| 63 |
-
|
| 64 |
-
return Response(content=f"Error connecting to OpenAI API: {e}", status_code=502) # 502 Bad Gateway
|
| 65 |
except Exception as e:
|
| 66 |
-
# Внутренняя ошибка в самом прокси-сервере
|
| 67 |
return Response(content=f"Internal proxy error: {e}", status_code=500)
|
|
|
|
| 3 |
from fastapi import FastAPI, Request, Response
|
| 4 |
|
| 5 |
app = FastAPI(
|
| 6 |
+
title="Transparent OpenAI Proxy",
|
| 7 |
+
description="A non-streaming proxy that forwards requests as-is."
|
| 8 |
)
|
| 9 |
|
| 10 |
OR_BASE_URL = "https://api.openai.com/v1"
|
| 11 |
|
| 12 |
+
# Увеличим таймаут, т.к. генерация может быть долгой
|
|
|
|
| 13 |
client = httpx.AsyncClient(base_url=OR_BASE_URL, timeout=120.0)
|
| 14 |
|
| 15 |
+
# "Hop-by-hop" заголовки, которые не должны проксироваться
|
|
|
|
| 16 |
HOP_BY_HOP_HEADERS = {
|
| 17 |
"connection", "keep-alive", "proxy-authenticate", "proxy-authorization",
|
| 18 |
"te", "trailers", "transfer-encoding", "upgrade",
|
|
|
|
| 20 |
|
| 21 |
@app.get("/")
|
| 22 |
async def home():
|
| 23 |
+
return {"status": "ok", "message": "Transparent, non-streaming OpenAI proxy is working."}
|
| 24 |
|
| 25 |
|
| 26 |
@app.api_route("/{endpoint:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE"])
|
| 27 |
async def proxy(endpoint: str, request: Request):
|
| 28 |
try:
|
|
|
|
| 29 |
url = httpx.URL(path=f"/{endpoint}", query=request.url.query.encode("utf-8"))
|
| 30 |
|
| 31 |
+
# Копируем все заголовки из входящего запроса, кроме 'host'
|
| 32 |
headers = {k: v for k, v in request.headers.items() if k.lower() != "host"}
|
| 33 |
+
|
| 34 |
body = await request.body()
|
| 35 |
|
| 36 |
+
# Отправляем запрос и ждем полного ответа
|
|
|
|
| 37 |
resp_openai = await client.request(
|
| 38 |
method=request.method,
|
| 39 |
url=url,
|
|
|
|
| 41 |
content=body
|
| 42 |
)
|
| 43 |
|
| 44 |
+
# Фильтруем "hop-by-hop" заголовки из ответа
|
|
|
|
| 45 |
response_headers = {
|
| 46 |
k: v for k, v in resp_openai.headers.items()
|
| 47 |
if k.lower() not in HOP_BY_HOP_HEADERS
|
| 48 |
}
|
| 49 |
|
| 50 |
+
# Возвращаем полный ответ (статус, заголовки, тело) от OpenAI
|
|
|
|
| 51 |
return Response(
|
| 52 |
content=resp_openai.content,
|
| 53 |
status_code=resp_openai.status_code,
|
|
|
|
| 55 |
)
|
| 56 |
|
| 57 |
except httpx.RequestError as e:
|
| 58 |
+
return Response(content=f"Error connecting to OpenAI API: {e}", status_code=502) # Bad Gateway
|
|
|
|
| 59 |
except Exception as e:
|
|
|
|
| 60 |
return Response(content=f"Internal proxy error: {e}", status_code=500)
|