File size: 1,808 Bytes
aa21e8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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)}")