Update app.py
Browse files
app.py
CHANGED
|
@@ -12,7 +12,7 @@ logging.basicConfig(level=logging.INFO)
|
|
| 12 |
logger = logging.getLogger("g4f-smart-router")
|
| 13 |
|
| 14 |
# =====================================================
|
| 15 |
-
# COOKIES
|
| 16 |
# =====================================================
|
| 17 |
def _load_cookies_raw() -> Dict[str, Any]:
|
| 18 |
raw_env = (os.getenv("COOKIES_JSON") or "").strip()
|
|
@@ -65,7 +65,7 @@ def load_cookies() -> str:
|
|
| 65 |
COOKIE_STATUS = load_cookies()
|
| 66 |
|
| 67 |
# =====================================================
|
| 68 |
-
# PROVIDERS
|
| 69 |
# =====================================================
|
| 70 |
def get_provider(name: str):
|
| 71 |
try:
|
|
@@ -88,7 +88,7 @@ REAL_PROVIDERS: Dict[str, Any] = {
|
|
| 88 |
REAL_PROVIDERS = {k: v for k, v in REAL_PROVIDERS.items() if v}
|
| 89 |
|
| 90 |
# =====================================================
|
| 91 |
-
# MODELS
|
| 92 |
# =====================================================
|
| 93 |
PROVIDER_MODELS_FALLBACK: Dict[str, List[str]] = {
|
| 94 |
"Perplexity": ["sonar", "sonar-pro", "gpt-4o", "llama-3"],
|
|
@@ -103,7 +103,7 @@ PROVIDER_MODELS_FALLBACK: Dict[str, List[str]] = {
|
|
| 103 |
}
|
| 104 |
|
| 105 |
# =====================================================
|
| 106 |
-
# MODEL DISCOVERY
|
| 107 |
# =====================================================
|
| 108 |
def _normalize_model_list(x: Any) -> List[str]:
|
| 109 |
out: List[str] = []
|
|
@@ -175,7 +175,7 @@ def discover_provider_models(provider_obj: Any, provider_name: str) -> List[str]
|
|
| 175 |
return uniq
|
| 176 |
|
| 177 |
# =====================================================
|
| 178 |
-
# STREAM CLEANER
|
| 179 |
# =====================================================
|
| 180 |
def clean_stream(chunk):
|
| 181 |
try:
|
|
@@ -217,7 +217,7 @@ def clean_stream(chunk):
|
|
| 217 |
return ""
|
| 218 |
|
| 219 |
# =====================================================
|
| 220 |
-
# CACHE
|
| 221 |
# =====================================================
|
| 222 |
CACHE = {}
|
| 223 |
CACHE_TS = {}
|
|
@@ -232,7 +232,7 @@ def _cache_set(key, val):
|
|
| 232 |
CACHE_TS[key] = time.time()
|
| 233 |
|
| 234 |
# =====================================================
|
| 235 |
-
# CHAT LOGIC
|
| 236 |
# =====================================================
|
| 237 |
_PROVIDER_MODEL_CACHE = {}
|
| 238 |
|
|
@@ -354,22 +354,19 @@ def ask(message: str, history, provider_name: str, model_name: str):
|
|
| 354 |
yield "❌ Failed with all providers."
|
| 355 |
|
| 356 |
# =====================================================
|
| 357 |
-
# FASTAPI
|
| 358 |
# =====================================================
|
| 359 |
|
| 360 |
app = FastAPI(title="G4F API", description="G4F Smart Router API")
|
| 361 |
|
| 362 |
-
# المفتاح السري
|
| 363 |
API_KEY = os.getenv("API_KEY", "mysecretkey123")
|
| 364 |
|
| 365 |
-
# نموذج البيانات للطلب
|
| 366 |
class ChatRequest(BaseModel):
|
| 367 |
message: str
|
| 368 |
provider: str = "Perplexity"
|
| 369 |
model: str = "sonar"
|
| 370 |
history: List[Any] = []
|
| 371 |
|
| 372 |
-
# التحقق من المفتاح
|
| 373 |
def verify_api_key(request: Request):
|
| 374 |
auth = request.headers.get("Authorization")
|
| 375 |
if not auth or not auth.startswith("Bearer "):
|
|
@@ -378,12 +375,26 @@ def verify_api_key(request: Request):
|
|
| 378 |
if key != API_KEY:
|
| 379 |
raise HTTPException(status_code=403, detail="Invalid API key")
|
| 380 |
|
| 381 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 382 |
@app.get("/health")
|
| 383 |
async def health():
|
| 384 |
return {"status": "ok", "cookies": COOKIE_STATUS, "providers": list(REAL_PROVIDERS.keys())}
|
| 385 |
|
| 386 |
-
# نقطة الدردشة (غير متدفق)
|
| 387 |
@app.post("/chat")
|
| 388 |
async def chat(request: Request, chat_req: ChatRequest):
|
| 389 |
verify_api_key(request)
|
|
@@ -394,7 +405,6 @@ async def chat(request: Request, chat_req: ChatRequest):
|
|
| 394 |
|
| 395 |
return JSONResponse(content={"response": full_response})
|
| 396 |
|
| 397 |
-
# نقطة الدردشة (متتدفق - Stream)
|
| 398 |
@app.post("/chat/stream")
|
| 399 |
async def chat_stream(request: Request, chat_req: ChatRequest):
|
| 400 |
verify_api_key(request)
|
|
@@ -406,7 +416,6 @@ async def chat_stream(request: Request, chat_req: ChatRequest):
|
|
| 406 |
|
| 407 |
return StreamingResponse(generate(), media_type="text/event-stream")
|
| 408 |
|
| 409 |
-
# نقطة الحصول على المزودين والنماذج
|
| 410 |
@app.get("/providers")
|
| 411 |
async def get_providers(request: Request):
|
| 412 |
verify_api_key(request)
|
|
|
|
| 12 |
logger = logging.getLogger("g4f-smart-router")
|
| 13 |
|
| 14 |
# =====================================================
|
| 15 |
+
# COOKIES
|
| 16 |
# =====================================================
|
| 17 |
def _load_cookies_raw() -> Dict[str, Any]:
|
| 18 |
raw_env = (os.getenv("COOKIES_JSON") or "").strip()
|
|
|
|
| 65 |
COOKIE_STATUS = load_cookies()
|
| 66 |
|
| 67 |
# =====================================================
|
| 68 |
+
# PROVIDERS
|
| 69 |
# =====================================================
|
| 70 |
def get_provider(name: str):
|
| 71 |
try:
|
|
|
|
| 88 |
REAL_PROVIDERS = {k: v for k, v in REAL_PROVIDERS.items() if v}
|
| 89 |
|
| 90 |
# =====================================================
|
| 91 |
+
# MODELS
|
| 92 |
# =====================================================
|
| 93 |
PROVIDER_MODELS_FALLBACK: Dict[str, List[str]] = {
|
| 94 |
"Perplexity": ["sonar", "sonar-pro", "gpt-4o", "llama-3"],
|
|
|
|
| 103 |
}
|
| 104 |
|
| 105 |
# =====================================================
|
| 106 |
+
# MODEL DISCOVERY
|
| 107 |
# =====================================================
|
| 108 |
def _normalize_model_list(x: Any) -> List[str]:
|
| 109 |
out: List[str] = []
|
|
|
|
| 175 |
return uniq
|
| 176 |
|
| 177 |
# =====================================================
|
| 178 |
+
# STREAM CLEANER
|
| 179 |
# =====================================================
|
| 180 |
def clean_stream(chunk):
|
| 181 |
try:
|
|
|
|
| 217 |
return ""
|
| 218 |
|
| 219 |
# =====================================================
|
| 220 |
+
# CACHE
|
| 221 |
# =====================================================
|
| 222 |
CACHE = {}
|
| 223 |
CACHE_TS = {}
|
|
|
|
| 232 |
CACHE_TS[key] = time.time()
|
| 233 |
|
| 234 |
# =====================================================
|
| 235 |
+
# CHAT LOGIC
|
| 236 |
# =====================================================
|
| 237 |
_PROVIDER_MODEL_CACHE = {}
|
| 238 |
|
|
|
|
| 354 |
yield "❌ Failed with all providers."
|
| 355 |
|
| 356 |
# =====================================================
|
| 357 |
+
# FASTAPI
|
| 358 |
# =====================================================
|
| 359 |
|
| 360 |
app = FastAPI(title="G4F API", description="G4F Smart Router API")
|
| 361 |
|
|
|
|
| 362 |
API_KEY = os.getenv("API_KEY", "mysecretkey123")
|
| 363 |
|
|
|
|
| 364 |
class ChatRequest(BaseModel):
|
| 365 |
message: str
|
| 366 |
provider: str = "Perplexity"
|
| 367 |
model: str = "sonar"
|
| 368 |
history: List[Any] = []
|
| 369 |
|
|
|
|
| 370 |
def verify_api_key(request: Request):
|
| 371 |
auth = request.headers.get("Authorization")
|
| 372 |
if not auth or not auth.startswith("Bearer "):
|
|
|
|
| 375 |
if key != API_KEY:
|
| 376 |
raise HTTPException(status_code=403, detail="Invalid API key")
|
| 377 |
|
| 378 |
+
# ========== المسار الرئيسي (تمت الإضافة هنا) ==========
|
| 379 |
+
@app.get("/")
|
| 380 |
+
async def root():
|
| 381 |
+
return {
|
| 382 |
+
"message": "G4F API is running",
|
| 383 |
+
"endpoints": {
|
| 384 |
+
"GET /": "هذه الصفحة",
|
| 385 |
+
"GET /health": "التحقق من صحة الخادم",
|
| 386 |
+
"GET /providers": "قائمة المزودين والنماذج (يتطلب مفتاح)",
|
| 387 |
+
"POST /chat": "إرسال رسالة والحصول على رد (يتطلب مفتاح)",
|
| 388 |
+
"POST /chat/stream": "إرسال رسالة والحصول على رد متدفق (يتطلب مفتاح)"
|
| 389 |
+
},
|
| 390 |
+
"authentication": "Bearer YOUR_API_KEY",
|
| 391 |
+
"status": "✅ Server is working"
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
@app.get("/health")
|
| 395 |
async def health():
|
| 396 |
return {"status": "ok", "cookies": COOKIE_STATUS, "providers": list(REAL_PROVIDERS.keys())}
|
| 397 |
|
|
|
|
| 398 |
@app.post("/chat")
|
| 399 |
async def chat(request: Request, chat_req: ChatRequest):
|
| 400 |
verify_api_key(request)
|
|
|
|
| 405 |
|
| 406 |
return JSONResponse(content={"response": full_response})
|
| 407 |
|
|
|
|
| 408 |
@app.post("/chat/stream")
|
| 409 |
async def chat_stream(request: Request, chat_req: ChatRequest):
|
| 410 |
verify_api_key(request)
|
|
|
|
| 416 |
|
| 417 |
return StreamingResponse(generate(), media_type="text/event-stream")
|
| 418 |
|
|
|
|
| 419 |
@app.get("/providers")
|
| 420 |
async def get_providers(request: Request):
|
| 421 |
verify_api_key(request)
|