AIMaster7 commited on
Commit
6aea54c
Β·
verified Β·
1 Parent(s): acd26ba

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +25 -25
main.py CHANGED
@@ -1,18 +1,15 @@
1
  from fastapi import FastAPI, Request, Header, HTTPException
2
- from fastapi.responses import JSONResponse, Response
3
  import httpx
4
  import socket
 
5
 
6
  app = FastAPI()
7
 
8
- # Real secret API key (used internally, never exposed)
9
- REAL_API_KEY = "sk-94NDKhKQkhKoYnY65mg4NAIFK5BqNiCtxo8u3PsDpb0IucZt"
10
  BASE_URL = "https://fast.typegpt.net"
11
-
12
- # Public key that users must use in Authorization header
13
  PUBLIC_AUTH_TOKEN = "TypeGPT-Free4ALL"
14
 
15
- # Show server IP at startup
16
  @app.on_event("startup")
17
  async def startup_event():
18
  try:
@@ -25,7 +22,6 @@ async def startup_event():
25
 
26
  @app.api_route("/{path:path}", methods=["GET", "POST"])
27
  async def proxy(request: Request, path: str, authorization: str = Header(None)):
28
- # Validate Authorization token
29
  if not authorization or not authorization.startswith("Bearer "):
30
  raise HTTPException(status_code=401, detail="Missing or malformed Authorization header.")
31
 
@@ -33,10 +29,8 @@ async def proxy(request: Request, path: str, authorization: str = Header(None)):
33
  if token != PUBLIC_AUTH_TOKEN:
34
  raise HTTPException(status_code=401, detail="Invalid Authorization token. Use 'TypeGPT-Free4ALL'.")
35
 
36
- # Rebuild the target URL
37
  target_url = f"{BASE_URL}/{path}"
38
 
39
- # Use clean headers to avoid Cloudflare issues
40
  headers = {
41
  "Authorization": f"Bearer {REAL_API_KEY}",
42
  "Content-Type": request.headers.get("content-type", "application/json"),
@@ -44,34 +38,40 @@ async def proxy(request: Request, path: str, authorization: str = Header(None)):
44
  "User-Agent": "FastAPI-Proxy"
45
  }
46
 
47
- # Read the body
48
  body = await request.body()
49
 
50
- # Log for debugging
 
 
51
  print(f"πŸ”„ Forwarding to: {target_url}")
52
  print(f"πŸ“¦ Request Body (first 200 chars): {body[:200]}")
 
53
 
54
- async with httpx.AsyncClient() as client:
55
  try:
56
  response = await client.request(
57
  method=request.method,
58
  url=target_url,
59
  headers=headers,
60
  content=body,
61
- timeout=60
62
  )
63
  except httpx.RequestError as e:
64
- raise HTTPException(status_code=502, detail=f"Failed to reach backend: {e}")
65
 
66
- print(f"↩️ TypeGPT Status: {response.status_code}")
67
- print(f"🧾 Response Snippet: {response.text[:200]}")
 
 
68
 
69
- # Return JSON if possible, else fallback
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
- )
 
 
 
1
  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
 
 
13
  @app.on_event("startup")
14
  async def startup_event():
15
  try:
 
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
 
 
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
 
 
34
  headers = {
35
  "Authorization": f"Bearer {REAL_API_KEY}",
36
  "Content-Type": request.headers.get("content-type", "application/json"),
 
38
  "User-Agent": "FastAPI-Proxy"
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}")
47
  print(f"πŸ“¦ Request Body (first 200 chars): {body[:200]}")
48
+ print(f"πŸ” Stream mode: {is_stream}")
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
+ )