Spaces:
Running
Running
from fastapi import APIRouter, HTTPException, Depends, Request | |
from sqlalchemy.orm import Session | |
from app.database import SessionLocal | |
from app.models import APIKey | |
import requests | |
router = APIRouter() | |
TYPEGPT_API_URL = "https://api.typegpt.net/v1/chat/completions" | |
TYPEGPT_API_KEY = "sk-ciH62IRAfuzg288E12QFVwuND0Og1GCZFc0fiJ2Sk37AElEA" | |
def get_db(): | |
db = SessionLocal() | |
try: | |
yield db | |
finally: | |
db.close() | |
def proxy_request(request: Request, db: Session = Depends(get_db)): | |
user_key = request.headers.get("X-API-KEY") | |
if not user_key: | |
raise HTTPException(status_code=401, detail="API key required") | |
api_key = db.query(APIKey).filter(APIKey.key == user_key).first() | |
if not api_key: | |
raise HTTPException(status_code=403, detail="Invalid API key") | |
response = requests.post( | |
TYPEGPT_API_URL, headers={"Authorization": f"Bearer {TYPEGPT_API_KEY}"}, | |
json=request.json() | |
) | |
return response.json() | |