|
|
from fastapi import FastAPI, Request, HTTPException |
|
|
from fastapi.responses import JSONResponse |
|
|
from pydantic import BaseModel |
|
|
import os |
|
|
import httpx |
|
|
|
|
|
app = FastAPI() |
|
|
|
|
|
|
|
|
OMNI_API_KEY = os.getenv("OMNI_API_KEY") |
|
|
OMNI_BASE_URL = "https://user669-omniapi.hf.space" |
|
|
CHAT_COMPLETIONS_PATH = "/chat/completions" |
|
|
DEFAULT_MODEL = "gpt-4o" |
|
|
|
|
|
|
|
|
class ChatRequest(BaseModel): |
|
|
messages: list[dict] |
|
|
model: str = DEFAULT_MODEL |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.on_event("startup") |
|
|
async def startup_event(): |
|
|
|
|
|
if not OMNI_API_KEY: |
|
|
print("CRITICAL ERROR: OMNI_API_KEY not found in environment variables.") |
|
|
|
|
|
|
|
|
|
|
|
@app.post("/chat") |
|
|
async def chat_proxy(request: ChatRequest): |
|
|
if not OMNI_API_KEY: |
|
|
raise HTTPException(status_code=500, detail="API key not configured.") |
|
|
|
|
|
headers = { |
|
|
"Authorization": f"Bearer {OMNI_API_KEY}", |
|
|
"Content-Type": "application/json" |
|
|
} |
|
|
|
|
|
payload = { |
|
|
"model": request.model, |
|
|
"messages": request.messages, |
|
|
|
|
|
|
|
|
|
|
|
} |
|
|
|
|
|
full_url = f"{OMNI_BASE_URL}{CHAT_COMPLETIONS_PATH}" |
|
|
|
|
|
async with httpx.AsyncClient() as client: |
|
|
try: |
|
|
response = await client.post(full_url, json=payload, headers=headers, timeout=60.0) |
|
|
response.raise_for_status() |
|
|
return JSONResponse(content=response.json()) |
|
|
except httpx.RequestError as exc: |
|
|
raise HTTPException(status_code=500, detail=f"An error occurred while requesting: {exc.request.url!r}.") |
|
|
except httpx.HTTPStatusError as exc: |
|
|
raise HTTPException(status_code=exc.response.status_code, detail=f"Error response {exc.response.status_code} from {exc.request.url!r}: {exc.response.text}") |
|
|
except Exception as e: |
|
|
|
|
|
raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {str(e)}") |
|
|
|
|
|
|
|
|
@app.get("/health") |
|
|
def health_check(): |
|
|
return {"status": "ok"} |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
import uvicorn |
|
|
uvicorn.run(app, host="0.0.0.0", port=7860) |