Spaces:
Sleeping
Sleeping
from fastapi import FastAPI, Request, Header, HTTPException | |
from fastapi.responses import JSONResponse, Response | |
import httpx | |
app = FastAPI() | |
# Your internal real API key for TypeGPT (not exposed to users) | |
REAL_API_KEY = "sk-qO9N6kQEEULMWtF4YGVlTTSjIPllEm1h1wfEBzSmnSbxiXwe" | |
BASE_URL = "https://fast.typegpt.net" | |
# Public token users must send in their Authorization header | |
PUBLIC_AUTH_TOKEN = "TypeGPT-Free4ALL" | |
async def proxy(request: Request, path: str, authorization: str = Header(None)): | |
# Validate the Authorization header | |
if not authorization or not authorization.startswith("Bearer "): | |
raise HTTPException(status_code=401, detail="Missing or malformed Authorization header.") | |
token = authorization.replace("Bearer ", "").strip() | |
if token != PUBLIC_AUTH_TOKEN: | |
raise HTTPException(status_code=401, detail="Invalid Authorization token. Use 'TypeGPT-Free4ALL'.") | |
# Construct URL to forward to the real backend | |
target_url = f"{BASE_URL}/{path}" | |
# Prepare headers with real API key | |
headers = dict(request.headers) | |
headers["Authorization"] = f"Bearer {REAL_API_KEY}" | |
headers.pop("host", None) | |
# Forward the request body | |
body = await request.body() | |
async with httpx.AsyncClient() as client: | |
try: | |
response = await client.request( | |
method=request.method, | |
url=target_url, | |
content=body, | |
headers=headers, | |
timeout=60 # prevent hanging | |
) | |
except httpx.RequestError as e: | |
raise HTTPException(status_code=502, detail=f"Request to backend failed: {e}") | |
# Log response for debugging | |
print("TypeGPT Response Status:", response.status_code) | |
print("TypeGPT Response Headers:", response.headers) | |
print("TypeGPT Response Content:", response.text[:200]) # limit output | |
# Try to return JSON response, fallback to raw | |
try: | |
return JSONResponse(content=response.json(), status_code=response.status_code) | |
except Exception: | |
return Response( | |
content=response.content, | |
status_code=response.status_code, | |
media_type=response.headers.get("content-type", "text/plain") | |
) | |