AIMaster7 commited on
Commit
770bf77
·
verified ·
1 Parent(s): 6aea54c

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +33 -27
main.py CHANGED
@@ -2,11 +2,10 @@ from fastapi import FastAPI, Request, Header, HTTPException
2
  from fastapi.responses import JSONResponse, Response, StreamingResponse
3
  import httpx
4
  import socket
5
- import asyncio
6
 
7
  app = FastAPI()
8
 
9
- REAL_API_KEY = "sk-94NDKhKQkhKoYnY65mg4NAIFK5BqNiCtxo8u3PsDpb0IucZt" # Replace this with your actual key
10
  BASE_URL = "https://fast.typegpt.net"
11
  PUBLIC_AUTH_TOKEN = "TypeGPT-Free4ALL"
12
 
@@ -30,7 +29,6 @@ async def proxy(request: Request, path: str, authorization: str = Header(None)):
30
  raise HTTPException(status_code=401, detail="Invalid Authorization token. Use 'TypeGPT-Free4ALL'.")
31
 
32
  target_url = f"{BASE_URL}/{path}"
33
-
34
  headers = {
35
  "Authorization": f"Bearer {REAL_API_KEY}",
36
  "Content-Type": request.headers.get("content-type", "application/json"),
@@ -39,8 +37,6 @@ async def proxy(request: Request, path: str, authorization: str = Header(None)):
39
  }
40
 
41
  body = await request.body()
42
-
43
- # Detect stream mode
44
  is_stream = b'"stream":true' in body or b'"stream": true' in body
45
 
46
  print(f"🔄 Forwarding to: {target_url}")
@@ -49,29 +45,39 @@ async def proxy(request: Request, path: str, authorization: str = Header(None)):
49
 
50
  async with httpx.AsyncClient(timeout=60) as client:
51
  try:
52
- response = await client.request(
53
- method=request.method,
54
- url=target_url,
55
- headers=headers,
56
- content=body,
57
- stream=is_stream,
58
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  except httpx.RequestError as e:
60
  raise HTTPException(status_code=502, detail=f"Backend request failed: {e}")
61
 
62
- if is_stream:
63
- async def event_generator():
64
- async for chunk in response.aiter_bytes():
65
- yield chunk
66
 
67
- return StreamingResponse(event_generator(), status_code=response.status_code, media_type="text/event-stream")
68
-
69
- # For non-streamed response
70
- try:
71
- return JSONResponse(content=response.json(), status_code=response.status_code)
72
- except Exception:
73
- return Response(
74
- content=response.content,
75
- status_code=response.status_code,
76
- media_type=response.headers.get("content-type", "text/plain")
77
- )
 
2
  from fastapi.responses import JSONResponse, Response, StreamingResponse
3
  import httpx
4
  import socket
 
5
 
6
  app = FastAPI()
7
 
8
+ REAL_API_KEY = "sk-94NDKhKQkhKoYnY65mg4NAIFK5BqNiCtxo8u3PsDpb0IucZt"
9
  BASE_URL = "https://fast.typegpt.net"
10
  PUBLIC_AUTH_TOKEN = "TypeGPT-Free4ALL"
11
 
 
29
  raise HTTPException(status_code=401, detail="Invalid Authorization token. Use 'TypeGPT-Free4ALL'.")
30
 
31
  target_url = f"{BASE_URL}/{path}"
 
32
  headers = {
33
  "Authorization": f"Bearer {REAL_API_KEY}",
34
  "Content-Type": request.headers.get("content-type", "application/json"),
 
37
  }
38
 
39
  body = await request.body()
 
 
40
  is_stream = b'"stream":true' in body or b'"stream": true' in body
41
 
42
  print(f"🔄 Forwarding to: {target_url}")
 
45
 
46
  async with httpx.AsyncClient(timeout=60) as client:
47
  try:
48
+ if is_stream:
49
+ # For streaming, use .stream()
50
+ upstream_response = await client.stream(
51
+ method=request.method,
52
+ url=target_url,
53
+ headers=headers,
54
+ content=body
55
+ )
56
+
57
+ async def stream_generator():
58
+ async for chunk in upstream_response.aiter_bytes():
59
+ yield chunk
60
+
61
+ return StreamingResponse(stream_generator(), status_code=upstream_response.status_code, media_type="text/event-stream")
62
+ else:
63
+ # For normal response, use .request()
64
+ response = await client.request(
65
+ method=request.method,
66
+ url=target_url,
67
+ headers=headers,
68
+ content=body
69
+ )
70
  except httpx.RequestError as e:
71
  raise HTTPException(status_code=502, detail=f"Backend request failed: {e}")
72
 
73
+ print(f"↩️ TypeGPT Status: {response.status_code}")
74
+ print(f"🧾 Response Snippet: {response.text[:200]}")
 
 
75
 
76
+ try:
77
+ return JSONResponse(content=response.json(), status_code=response.status_code)
78
+ except Exception:
79
+ return Response(
80
+ content=response.content,
81
+ status_code=response.status_code,
82
+ media_type=response.headers.get("content-type", "text/plain")
83
+ )