import os import httpx from fastapi import FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from dotenv import load_dotenv load_dotenv() app = FastAPI(title="NVIDIA API Proxy") # Enable CORS for all domains so the frontend on Vercel can connect seamlessly app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) NVIDIA_API_KEY = os.getenv("NVIDIA_API_KEY") NVIDIA_API_URL = "https://integrate.api.nvidia.com/v1/chat/completions" @app.get("/") def read_root(): return {"status": "ok", "message": "FridgeChef Backend is running!"} @app.post("/api/nvidia/chat/completions") async def proxy_nvidia(request: Request): if not NVIDIA_API_KEY: raise HTTPException(status_code=500, detail="Missing NVIDIA_API_KEY on the backend secure server.") body = await request.json() async with httpx.AsyncClient() as client: try: # We use an extended timeout (120s) because large vision queries or recipe generations can take time response = await client.post( NVIDIA_API_URL, headers={ "Authorization": f"Bearer {NVIDIA_API_KEY}", "Content-Type": "application/json", "Accept": "application/json" }, json=body, timeout=120.0 ) if response.status_code != 200: raise HTTPException(status_code=response.status_code, detail=response.text) return response.json() except httpx.RequestError as exc: raise HTTPException(status_code=500, detail=f"Request to NVIDIA failed: {str(exc)}")