Update app.py
Browse files
app.py
CHANGED
|
@@ -1,37 +1,72 @@
|
|
| 1 |
-
from fastapi import FastAPI
|
|
|
|
| 2 |
from pydantic import BaseModel
|
| 3 |
import os
|
|
|
|
| 4 |
|
| 5 |
app = FastAPI()
|
| 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 |
if __name__ == "__main__":
|
| 36 |
import uvicorn
|
| 37 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request, HTTPException
|
| 2 |
+
from fastapi.responses import JSONResponse
|
| 3 |
from pydantic import BaseModel
|
| 4 |
import os
|
| 5 |
+
import httpx # A modern, async HTTP client
|
| 6 |
|
| 7 |
app = FastAPI()
|
| 8 |
|
| 9 |
+
# Configuration from environment variables/secrets
|
| 10 |
+
OMNI_API_KEY = os.getenv("OMNI_API_KEY")
|
| 11 |
+
OMNI_BASE_URL = "https://user669-omniapi.hf.space" # The base URL for the external API
|
| 12 |
+
CHAT_COMPLETIONS_PATH = "/chat/completions" # The specific endpoint path
|
| 13 |
+
DEFAULT_MODEL = "gpt-4o" # The default model you want to use
|
| 14 |
+
|
| 15 |
+
# Basic input model for the chat completions request
|
| 16 |
+
class ChatRequest(BaseModel):
|
| 17 |
+
messages: list[dict]
|
| 18 |
+
model: str = DEFAULT_MODEL
|
| 19 |
+
# You can add other parameters here if your API supports them, e.g., temperature, max_tokens
|
| 20 |
+
# temperature: float = 0.7
|
| 21 |
+
# max_tokens: int = 150
|
| 22 |
+
|
| 23 |
+
@app.on_event("startup")
|
| 24 |
+
async def startup_event():
|
| 25 |
+
# Check if API key is loaded
|
| 26 |
+
if not OMNI_API_KEY:
|
| 27 |
+
print("CRITICAL ERROR: OMNI_API_KEY not found in environment variables.")
|
| 28 |
+
# In a production app, you might want to stop the service or log more aggressively
|
| 29 |
+
# For Spaces, it will just start but requests to /chat will fail.
|
| 30 |
+
|
| 31 |
+
@app.post("/chat")
|
| 32 |
+
async def chat_proxy(request: ChatRequest):
|
| 33 |
+
if not OMNI_API_KEY:
|
| 34 |
+
raise HTTPException(status_code=500, detail="API key not configured.")
|
| 35 |
+
|
| 36 |
+
headers = {
|
| 37 |
+
"Authorization": f"Bearer {OMNI_API_KEY}",
|
| 38 |
+
"Content-Type": "application/json"
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
payload = {
|
| 42 |
+
"model": request.model,
|
| 43 |
+
"messages": request.messages,
|
| 44 |
+
# Add any other parameters from ChatRequest here if they are part of the payload
|
| 45 |
+
# "temperature": request.temperature,
|
| 46 |
+
# "max_tokens": request.max_tokens,
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
full_url = f"{OMNI_BASE_URL}{CHAT_COMPLETIONS_PATH}"
|
| 50 |
+
|
| 51 |
+
async with httpx.AsyncClient() as client:
|
| 52 |
+
try:
|
| 53 |
+
response = await client.post(full_url, json=payload, headers=headers, timeout=60.0) # Add a timeout
|
| 54 |
+
response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)
|
| 55 |
+
return JSONResponse(content=response.json())
|
| 56 |
+
except httpx.RequestError as exc:
|
| 57 |
+
raise HTTPException(status_code=500, detail=f"An error occurred while requesting: {exc.request.url!r}.")
|
| 58 |
+
except httpx.HTTPStatusError as exc:
|
| 59 |
+
raise HTTPException(status_code=exc.response.status_code, detail=f"Error response {exc.response.status_code} from {exc.request.url!r}: {exc.response.text}")
|
| 60 |
+
except Exception as e:
|
| 61 |
+
# Catch any other unexpected errors
|
| 62 |
+
raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {str(e)}")
|
| 63 |
+
|
| 64 |
+
# Health check endpoint (optional but good practice)
|
| 65 |
+
@app.get("/health")
|
| 66 |
+
def health_check():
|
| 67 |
+
return {"status": "ok"}
|
| 68 |
+
|
| 69 |
+
# Ensure the app listens on port 7860 for Hugging Face Spaces
|
| 70 |
if __name__ == "__main__":
|
| 71 |
import uvicorn
|
| 72 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|