AIMaster7 commited on
Commit
719cbf5
·
verified ·
1 Parent(s): aecceec

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +36 -34
main.py CHANGED
@@ -5,7 +5,7 @@ import socket
5
 
6
  app = FastAPI()
7
 
8
- # Replace this with your actual backend API key
9
  REAL_API_KEY = "sk-kwWVUQPDsLemvilLcyzSSWRzo8sctCzxzlbdN0ZC5ZUCCv0m"
10
  BASE_URL = "https://fast.typegpt.net"
11
  PUBLIC_AUTH_TOKEN = "TypeGPT-Free4ALL"
@@ -22,16 +22,14 @@ async def startup_event():
22
 
23
  @app.api_route("/{path:path}", methods=["GET", "POST"])
24
  async def proxy(request: Request, path: str, authorization: str = Header(None)):
25
- # Validate token
26
  if not authorization or not authorization.startswith("Bearer "):
27
  raise HTTPException(status_code=401, detail="Missing or malformed Authorization header.")
28
-
29
  token = authorization.replace("Bearer ", "").strip()
30
  if token != PUBLIC_AUTH_TOKEN:
31
  raise HTTPException(status_code=401, detail="Invalid Authorization token. Use 'TypeGPT-Free4ALL'.")
32
 
33
  target_url = f"{BASE_URL}/{path}"
34
-
35
  headers = {
36
  "Authorization": f"Bearer {REAL_API_KEY}",
37
  "Content-Type": request.headers.get("content-type", "application/json"),
@@ -46,42 +44,46 @@ async def proxy(request: Request, path: str, authorization: str = Header(None)):
46
  print(f"📦 Request Body (first 200 chars): {body[:200]}")
47
  print(f"🔁 Stream mode: {is_stream}")
48
 
49
- async with httpx.AsyncClient(timeout=60) as client:
50
- try:
51
- if is_stream:
52
- async def stream_generator():
53
- async with client.stream(
54
- method=request.method,
55
- url=target_url,
56
- headers=headers,
57
- content=body
58
- ) as upstream_response:
59
- async for chunk in upstream_response.aiter_bytes():
60
- yield chunk
61
 
62
- return StreamingResponse(
63
- stream_generator(),
64
- status_code=200,
65
- media_type="text/event-stream"
66
- )
67
- else:
 
 
 
 
68
  response = await client.request(
69
  method=request.method,
70
  url=target_url,
71
  headers=headers,
72
  content=body
73
  )
74
- except httpx.RequestError as e:
75
- raise HTTPException(status_code=502, detail=f"Backend request failed: {e}")
76
 
77
- print(f"↩️ TypeGPT Status: {response.status_code}")
78
- print(f"🧾 Response Snippet: {response.text[:200]}")
79
 
80
- try:
81
- return JSONResponse(content=response.json(), status_code=response.status_code)
82
- except Exception:
83
- return Response(
84
- content=response.content,
85
- status_code=response.status_code,
86
- media_type=response.headers.get("content-type", "text/plain")
87
- )
 
5
 
6
  app = FastAPI()
7
 
8
+ # Your real backend API key
9
  REAL_API_KEY = "sk-kwWVUQPDsLemvilLcyzSSWRzo8sctCzxzlbdN0ZC5ZUCCv0m"
10
  BASE_URL = "https://fast.typegpt.net"
11
  PUBLIC_AUTH_TOKEN = "TypeGPT-Free4ALL"
 
22
 
23
  @app.api_route("/{path:path}", methods=["GET", "POST"])
24
  async def proxy(request: Request, path: str, authorization: str = Header(None)):
 
25
  if not authorization or not authorization.startswith("Bearer "):
26
  raise HTTPException(status_code=401, detail="Missing or malformed Authorization header.")
27
+
28
  token = authorization.replace("Bearer ", "").strip()
29
  if token != PUBLIC_AUTH_TOKEN:
30
  raise HTTPException(status_code=401, detail="Invalid Authorization token. Use 'TypeGPT-Free4ALL'.")
31
 
32
  target_url = f"{BASE_URL}/{path}"
 
33
  headers = {
34
  "Authorization": f"Bearer {REAL_API_KEY}",
35
  "Content-Type": request.headers.get("content-type", "application/json"),
 
44
  print(f"📦 Request Body (first 200 chars): {body[:200]}")
45
  print(f"🔁 Stream mode: {is_stream}")
46
 
47
+ if is_stream:
48
+ # Move the client and stream both inside the generator
49
+ async def stream_generator():
50
+ async with httpx.AsyncClient(timeout=60) as client:
51
+ async with client.stream(
52
+ method=request.method,
53
+ url=target_url,
54
+ headers=headers,
55
+ content=body
56
+ ) as upstream_response:
57
+ async for chunk in upstream_response.aiter_bytes():
58
+ yield chunk
59
 
60
+ return StreamingResponse(
61
+ stream_generator(),
62
+ status_code=200,
63
+ media_type="text/event-stream"
64
+ )
65
+
66
+ else:
67
+ # Non-stream (normal JSON response)
68
+ async with httpx.AsyncClient(timeout=60) as client:
69
+ try:
70
  response = await client.request(
71
  method=request.method,
72
  url=target_url,
73
  headers=headers,
74
  content=body
75
  )
76
+ except httpx.RequestError as e:
77
+ raise HTTPException(status_code=502, detail=f"Backend request failed: {e}")
78
 
79
+ print(f"↩️ TypeGPT Status: {response.status_code}")
80
+ print(f"🧾 Response Snippet: {response.text[:200]}")
81
 
82
+ try:
83
+ return JSONResponse(content=response.json(), status_code=response.status_code)
84
+ except Exception:
85
+ return Response(
86
+ content=response.content,
87
+ status_code=response.status_code,
88
+ media_type=response.headers.get("content-type", "text/plain")
89
+ )