Update app.py
Browse files
app.py
CHANGED
|
@@ -1,12 +1,13 @@
|
|
| 1 |
-
from fastapi import FastAPI, Request
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
from fastapi.responses import StreamingResponse, JSONResponse
|
| 4 |
from pydantic import BaseModel
|
| 5 |
from typing import List, Optional
|
|
|
|
| 6 |
import asyncio
|
| 7 |
import json
|
| 8 |
-
import time
|
| 9 |
import uuid
|
|
|
|
| 10 |
import logging
|
| 11 |
|
| 12 |
import g4f
|
|
@@ -18,22 +19,15 @@ from g4f.client import Client
|
|
| 18 |
# =====================================================
|
| 19 |
|
| 20 |
logging.basicConfig(level=logging.INFO)
|
| 21 |
-
|
| 22 |
logger = logging.getLogger(__name__)
|
| 23 |
|
| 24 |
-
# =====================================================
|
| 25 |
-
# CONFIG
|
| 26 |
-
# =====================================================
|
| 27 |
-
|
| 28 |
-
API_KEY = "sk-your-secret-key"
|
| 29 |
-
|
| 30 |
# =====================================================
|
| 31 |
# FASTAPI
|
| 32 |
# =====================================================
|
| 33 |
|
| 34 |
app = FastAPI(
|
| 35 |
title="Universal AI Gateway",
|
| 36 |
-
version="
|
| 37 |
)
|
| 38 |
|
| 39 |
# =====================================================
|
|
@@ -56,7 +50,6 @@ class Message(BaseModel):
|
|
| 56 |
role: str
|
| 57 |
content: str
|
| 58 |
|
| 59 |
-
|
| 60 |
class ChatRequest(BaseModel):
|
| 61 |
model: str
|
| 62 |
messages: List[Message]
|
|
@@ -64,36 +57,6 @@ class ChatRequest(BaseModel):
|
|
| 64 |
temperature: Optional[float] = 0.7
|
| 65 |
max_tokens: Optional[int] = 4096
|
| 66 |
|
| 67 |
-
|
| 68 |
-
# =====================================================
|
| 69 |
-
# AUTH
|
| 70 |
-
# =====================================================
|
| 71 |
-
|
| 72 |
-
def verify_api_key(req: Request):
|
| 73 |
-
|
| 74 |
-
auth = req.headers.get("Authorization")
|
| 75 |
-
|
| 76 |
-
if not auth:
|
| 77 |
-
raise HTTPException(
|
| 78 |
-
status_code=401,
|
| 79 |
-
detail="Missing Authorization Header"
|
| 80 |
-
)
|
| 81 |
-
|
| 82 |
-
if not auth.startswith("Bearer "):
|
| 83 |
-
raise HTTPException(
|
| 84 |
-
status_code=401,
|
| 85 |
-
detail="Invalid Authorization Format"
|
| 86 |
-
)
|
| 87 |
-
|
| 88 |
-
token = auth.replace("Bearer ", "")
|
| 89 |
-
|
| 90 |
-
if token != API_KEY:
|
| 91 |
-
raise HTTPException(
|
| 92 |
-
status_code=403,
|
| 93 |
-
detail="Invalid API Key"
|
| 94 |
-
)
|
| 95 |
-
|
| 96 |
-
|
| 97 |
# =====================================================
|
| 98 |
# ROOT
|
| 99 |
# =====================================================
|
|
@@ -104,10 +67,9 @@ async def root():
|
|
| 104 |
return {
|
| 105 |
"status": "online",
|
| 106 |
"service": "Universal AI Gateway",
|
| 107 |
-
"version": "
|
| 108 |
}
|
| 109 |
|
| 110 |
-
|
| 111 |
# =====================================================
|
| 112 |
# AUTO MODELS IMPORT
|
| 113 |
# =====================================================
|
|
@@ -124,9 +86,6 @@ async def get_models():
|
|
| 124 |
if hasattr(g4f.models, "_all_models"):
|
| 125 |
all_models = list(g4f.models._all_models)
|
| 126 |
|
| 127 |
-
elif hasattr(g4f.models, "__models__"):
|
| 128 |
-
all_models = list(g4f.models.__models__)
|
| 129 |
-
|
| 130 |
unique_models = set()
|
| 131 |
|
| 132 |
for model in all_models:
|
|
@@ -144,60 +103,45 @@ async def get_models():
|
|
| 144 |
"owned_by": "g4f"
|
| 145 |
})
|
| 146 |
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
fallback_models = [
|
| 150 |
-
"gpt-4o-mini",
|
| 151 |
-
"gpt-4o",
|
| 152 |
-
"gpt-4",
|
| 153 |
-
"gpt-3.5-turbo",
|
| 154 |
-
"claude-3-haiku",
|
| 155 |
-
"claude-3-opus",
|
| 156 |
-
"gemini-pro",
|
| 157 |
-
"llama-3.1-70b",
|
| 158 |
-
"mixtral-8x7b"
|
| 159 |
-
]
|
| 160 |
|
| 161 |
-
|
| 162 |
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
"object": "model",
|
| 166 |
-
"created": int(time.time()),
|
| 167 |
-
"owned_by": "g4f"
|
| 168 |
-
})
|
| 169 |
|
| 170 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
-
|
| 173 |
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
"id": "gpt-4o-mini",
|
| 177 |
"object": "model",
|
| 178 |
"created": int(time.time()),
|
| 179 |
"owned_by": "g4f"
|
| 180 |
-
}
|
| 181 |
-
]
|
| 182 |
|
| 183 |
return {
|
| 184 |
"object": "list",
|
| 185 |
"data": models_data
|
| 186 |
}
|
| 187 |
|
| 188 |
-
|
| 189 |
# =====================================================
|
| 190 |
# CHAT COMPLETIONS
|
| 191 |
# =====================================================
|
| 192 |
|
| 193 |
@app.post("/v1/chat/completions")
|
| 194 |
async def chat_completions(
|
| 195 |
-
req: Request,
|
| 196 |
body: ChatRequest
|
| 197 |
):
|
| 198 |
|
| 199 |
-
verify_api_key(req)
|
| 200 |
-
|
| 201 |
messages = [
|
| 202 |
{
|
| 203 |
"role": m.role,
|
|
@@ -206,10 +150,10 @@ async def chat_completions(
|
|
| 206 |
for m in body.messages
|
| 207 |
]
|
| 208 |
|
| 209 |
-
logger.info(f"
|
| 210 |
|
| 211 |
# =================================================
|
| 212 |
-
# STREAM
|
| 213 |
# =================================================
|
| 214 |
|
| 215 |
if body.stream:
|
|
@@ -263,11 +207,10 @@ async def chat_completions(
|
|
| 263 |
|
| 264 |
await asyncio.sleep(0)
|
| 265 |
|
| 266 |
-
except Exception as
|
|
|
|
| 267 |
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
final_payload = {
|
| 271 |
"id": chunk_id,
|
| 272 |
"object": "chat.completion.chunk",
|
| 273 |
"created": int(time.time()),
|
|
@@ -281,13 +224,12 @@ async def chat_completions(
|
|
| 281 |
]
|
| 282 |
}
|
| 283 |
|
| 284 |
-
yield f"data: {json.dumps(
|
| 285 |
-
|
| 286 |
yield "data: [DONE]\n\n"
|
| 287 |
|
| 288 |
except Exception as e:
|
| 289 |
|
| 290 |
-
logger.error(
|
| 291 |
|
| 292 |
error_payload = {
|
| 293 |
"error": {
|
|
@@ -353,26 +295,15 @@ async def chat_completions(
|
|
| 353 |
|
| 354 |
except Exception as e:
|
| 355 |
|
| 356 |
-
logger.error(
|
| 357 |
|
| 358 |
-
|
| 359 |
status_code=500,
|
| 360 |
-
|
|
|
|
|
|
|
| 361 |
)
|
| 362 |
|
| 363 |
-
|
| 364 |
-
# =====================================================
|
| 365 |
-
# TEST UI
|
| 366 |
-
# =====================================================
|
| 367 |
-
|
| 368 |
-
@app.get("/test")
|
| 369 |
-
async def test():
|
| 370 |
-
|
| 371 |
-
return {
|
| 372 |
-
"message": "Server is working"
|
| 373 |
-
}
|
| 374 |
-
|
| 375 |
-
|
| 376 |
# =====================================================
|
| 377 |
# RUN
|
| 378 |
# =====================================================
|
|
@@ -381,8 +312,6 @@ if __name__ == "__main__":
|
|
| 381 |
|
| 382 |
import uvicorn
|
| 383 |
|
| 384 |
-
print("Server running on port 7860")
|
| 385 |
-
|
| 386 |
uvicorn.run(
|
| 387 |
app,
|
| 388 |
host="0.0.0.0",
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
from fastapi.responses import StreamingResponse, JSONResponse
|
| 4 |
from pydantic import BaseModel
|
| 5 |
from typing import List, Optional
|
| 6 |
+
|
| 7 |
import asyncio
|
| 8 |
import json
|
|
|
|
| 9 |
import uuid
|
| 10 |
+
import time
|
| 11 |
import logging
|
| 12 |
|
| 13 |
import g4f
|
|
|
|
| 19 |
# =====================================================
|
| 20 |
|
| 21 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 22 |
logger = logging.getLogger(__name__)
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
# =====================================================
|
| 25 |
# FASTAPI
|
| 26 |
# =====================================================
|
| 27 |
|
| 28 |
app = FastAPI(
|
| 29 |
title="Universal AI Gateway",
|
| 30 |
+
version="5.0.0"
|
| 31 |
)
|
| 32 |
|
| 33 |
# =====================================================
|
|
|
|
| 50 |
role: str
|
| 51 |
content: str
|
| 52 |
|
|
|
|
| 53 |
class ChatRequest(BaseModel):
|
| 54 |
model: str
|
| 55 |
messages: List[Message]
|
|
|
|
| 57 |
temperature: Optional[float] = 0.7
|
| 58 |
max_tokens: Optional[int] = 4096
|
| 59 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
# =====================================================
|
| 61 |
# ROOT
|
| 62 |
# =====================================================
|
|
|
|
| 67 |
return {
|
| 68 |
"status": "online",
|
| 69 |
"service": "Universal AI Gateway",
|
| 70 |
+
"version": "5.0.0"
|
| 71 |
}
|
| 72 |
|
|
|
|
| 73 |
# =====================================================
|
| 74 |
# AUTO MODELS IMPORT
|
| 75 |
# =====================================================
|
|
|
|
| 86 |
if hasattr(g4f.models, "_all_models"):
|
| 87 |
all_models = list(g4f.models._all_models)
|
| 88 |
|
|
|
|
|
|
|
|
|
|
| 89 |
unique_models = set()
|
| 90 |
|
| 91 |
for model in all_models:
|
|
|
|
| 103 |
"owned_by": "g4f"
|
| 104 |
})
|
| 105 |
|
| 106 |
+
except Exception as e:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
+
logger.error(f"Models error: {e}")
|
| 109 |
|
| 110 |
+
# fallback
|
| 111 |
+
if not models_data:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
+
fallback = [
|
| 114 |
+
"gpt-4o-mini",
|
| 115 |
+
"gpt-4o",
|
| 116 |
+
"gpt-4",
|
| 117 |
+
"claude-3-haiku",
|
| 118 |
+
"gemini-pro",
|
| 119 |
+
"llama-3.1-70b"
|
| 120 |
+
]
|
| 121 |
|
| 122 |
+
for m in fallback:
|
| 123 |
|
| 124 |
+
models_data.append({
|
| 125 |
+
"id": m,
|
|
|
|
| 126 |
"object": "model",
|
| 127 |
"created": int(time.time()),
|
| 128 |
"owned_by": "g4f"
|
| 129 |
+
})
|
|
|
|
| 130 |
|
| 131 |
return {
|
| 132 |
"object": "list",
|
| 133 |
"data": models_data
|
| 134 |
}
|
| 135 |
|
|
|
|
| 136 |
# =====================================================
|
| 137 |
# CHAT COMPLETIONS
|
| 138 |
# =====================================================
|
| 139 |
|
| 140 |
@app.post("/v1/chat/completions")
|
| 141 |
async def chat_completions(
|
|
|
|
| 142 |
body: ChatRequest
|
| 143 |
):
|
| 144 |
|
|
|
|
|
|
|
| 145 |
messages = [
|
| 146 |
{
|
| 147 |
"role": m.role,
|
|
|
|
| 150 |
for m in body.messages
|
| 151 |
]
|
| 152 |
|
| 153 |
+
logger.info(f"Model: {body.model}")
|
| 154 |
|
| 155 |
# =================================================
|
| 156 |
+
# STREAM
|
| 157 |
# =================================================
|
| 158 |
|
| 159 |
if body.stream:
|
|
|
|
| 207 |
|
| 208 |
await asyncio.sleep(0)
|
| 209 |
|
| 210 |
+
except Exception as e:
|
| 211 |
+
logger.error(e)
|
| 212 |
|
| 213 |
+
done_payload = {
|
|
|
|
|
|
|
| 214 |
"id": chunk_id,
|
| 215 |
"object": "chat.completion.chunk",
|
| 216 |
"created": int(time.time()),
|
|
|
|
| 224 |
]
|
| 225 |
}
|
| 226 |
|
| 227 |
+
yield f"data: {json.dumps(done_payload)}\n\n"
|
|
|
|
| 228 |
yield "data: [DONE]\n\n"
|
| 229 |
|
| 230 |
except Exception as e:
|
| 231 |
|
| 232 |
+
logger.error(e)
|
| 233 |
|
| 234 |
error_payload = {
|
| 235 |
"error": {
|
|
|
|
| 295 |
|
| 296 |
except Exception as e:
|
| 297 |
|
| 298 |
+
logger.error(e)
|
| 299 |
|
| 300 |
+
return JSONResponse(
|
| 301 |
status_code=500,
|
| 302 |
+
content={
|
| 303 |
+
"error": str(e)
|
| 304 |
+
}
|
| 305 |
)
|
| 306 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
# =====================================================
|
| 308 |
# RUN
|
| 309 |
# =====================================================
|
|
|
|
| 312 |
|
| 313 |
import uvicorn
|
| 314 |
|
|
|
|
|
|
|
| 315 |
uvicorn.run(
|
| 316 |
app,
|
| 317 |
host="0.0.0.0",
|