Update app.py
Browse files
app.py
CHANGED
|
@@ -2,6 +2,7 @@ import os
|
|
| 2 |
import re
|
| 3 |
import logging
|
| 4 |
import uuid
|
|
|
|
| 5 |
from datetime import datetime, timezone
|
| 6 |
from typing import Optional, Dict, Any
|
| 7 |
import asyncio
|
|
@@ -58,10 +59,79 @@ class TaskStatusResponse(BaseModel):
|
|
| 58 |
# request_params: Optional[Dict[str, Any]] = None # Optionally return original params
|
| 59 |
|
| 60 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
# --- FastAPI App Initialization ---
|
| 62 |
app = FastAPI(
|
| 63 |
title="Dual Chat & Async Gemini API",
|
| 64 |
-
description="
|
| 65 |
version="2.0.0"
|
| 66 |
)
|
| 67 |
|
|
@@ -162,7 +232,17 @@ async def process_gemini_request_background(
|
|
| 162 |
@app.post("/chat", response_class=StreamingResponse)
|
| 163 |
async def direct_chat(payload: ChatPayload):
|
| 164 |
logger.info(f"Direct chat request received. Temperature: {payload.temperature}, Message: '{payload.message[:50]}...'")
|
|
|
|
| 165 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
custom_api_key_secret = os.getenv("CUSTOM_API_SECRET_KEY")
|
| 167 |
custom_api_base_url = os.getenv("CUSTOM_API_BASE_URL", CUSTOM_API_BASE_URL_DEFAULT)
|
| 168 |
custom_api_model = os.getenv("CUSTOM_API_MODEL", CUSTOM_API_MODEL_DEFAULT)
|
|
|
|
| 2 |
import re
|
| 3 |
import logging
|
| 4 |
import uuid
|
| 5 |
+
import time
|
| 6 |
from datetime import datetime, timezone
|
| 7 |
from typing import Optional, Dict, Any
|
| 8 |
import asyncio
|
|
|
|
| 59 |
# request_params: Optional[Dict[str, Any]] = None # Optionally return original params
|
| 60 |
|
| 61 |
|
| 62 |
+
# Rate limiting dictionary
|
| 63 |
+
class RateLimiter:
|
| 64 |
+
def __init__(self, max_requests: int, time_window: timedelta):
|
| 65 |
+
self.max_requests = max_requests
|
| 66 |
+
self.time_window = time_window
|
| 67 |
+
self.requests: Dict[str, list] = defaultdict(list)
|
| 68 |
+
|
| 69 |
+
def _cleanup_old_requests(self, user_ip: str) -> None:
|
| 70 |
+
"""Remove requests that are outside the time window."""
|
| 71 |
+
current_time = time.time()
|
| 72 |
+
self.requests[user_ip] = [
|
| 73 |
+
timestamp for timestamp in self.requests[user_ip]
|
| 74 |
+
if current_time - timestamp < self.time_window.total_seconds()
|
| 75 |
+
]
|
| 76 |
+
|
| 77 |
+
def is_rate_limited(self, user_ip: str) -> bool:
|
| 78 |
+
"""Check if the user has exceeded their rate limit."""
|
| 79 |
+
self._cleanup_old_requests(user_ip)
|
| 80 |
+
|
| 81 |
+
# Get current count after cleanup
|
| 82 |
+
current_count = len(self.requests[user_ip])
|
| 83 |
+
|
| 84 |
+
# Add current request timestamp (incrementing the count)
|
| 85 |
+
current_time = time.time()
|
| 86 |
+
self.requests[user_ip].append(current_time)
|
| 87 |
+
|
| 88 |
+
# Check if user has exceeded the maximum requests
|
| 89 |
+
return (current_count + 1) > self.max_requests
|
| 90 |
+
|
| 91 |
+
def get_current_count(self, user_ip: str) -> int:
|
| 92 |
+
"""Get the current request count for an IP."""
|
| 93 |
+
self._cleanup_old_requests(user_ip)
|
| 94 |
+
return len(self.requests[user_ip])
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
# Initialize rate limiter with 100 requests per day
|
| 98 |
+
rate_limiter = RateLimiter(
|
| 99 |
+
max_requests=12,
|
| 100 |
+
time_window=timedelta(days=1)
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
def get_user_ip(request: Request) -> str:
|
| 104 |
+
"""Helper function to get user's IP address."""
|
| 105 |
+
forwarded = request.headers.get("X-Forwarded-For")
|
| 106 |
+
if forwarded:
|
| 107 |
+
return forwarded.split(",")[0]
|
| 108 |
+
return request.client.host
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class ApiRotator:
|
| 112 |
+
def __init__(self, apis):
|
| 113 |
+
self.apis = apis
|
| 114 |
+
self.last_successful_index = None
|
| 115 |
+
|
| 116 |
+
def get_prioritized_apis(self):
|
| 117 |
+
if self.last_successful_index is not None:
|
| 118 |
+
# Move the last successful API to the front
|
| 119 |
+
rotated_apis = (
|
| 120 |
+
[self.apis[self.last_successful_index]] +
|
| 121 |
+
self.apis[:self.last_successful_index] +
|
| 122 |
+
self.apis[self.last_successful_index+1:]
|
| 123 |
+
)
|
| 124 |
+
return rotated_apis
|
| 125 |
+
return self.apis
|
| 126 |
+
|
| 127 |
+
def update_last_successful(self, index):
|
| 128 |
+
self.last_successful_index = index
|
| 129 |
+
|
| 130 |
+
|
| 131 |
# --- FastAPI App Initialization ---
|
| 132 |
app = FastAPI(
|
| 133 |
title="Dual Chat & Async Gemini API",
|
| 134 |
+
description="Made by Cody from chrunos.com.",
|
| 135 |
version="2.0.0"
|
| 136 |
)
|
| 137 |
|
|
|
|
| 232 |
@app.post("/chat", response_class=StreamingResponse)
|
| 233 |
async def direct_chat(payload: ChatPayload):
|
| 234 |
logger.info(f"Direct chat request received. Temperature: {payload.temperature}, Message: '{payload.message[:50]}...'")
|
| 235 |
+
user_ip = get_user_ip(request)
|
| 236 |
|
| 237 |
+
if rate_limiter.is_rate_limited(user_ip):
|
| 238 |
+
current_count = rate_limiter.get_current_count(user_ip)
|
| 239 |
+
raise HTTPException(
|
| 240 |
+
status_code=429,
|
| 241 |
+
detail={
|
| 242 |
+
"error": "You have exceeded the maximum number of requests per day. Please try again tomorrow.",
|
| 243 |
+
"url": "https://t.me/chrunoss"
|
| 244 |
+
}
|
| 245 |
+
)
|
| 246 |
custom_api_key_secret = os.getenv("CUSTOM_API_SECRET_KEY")
|
| 247 |
custom_api_base_url = os.getenv("CUSTOM_API_BASE_URL", CUSTOM_API_BASE_URL_DEFAULT)
|
| 248 |
custom_api_model = os.getenv("CUSTOM_API_MODEL", CUSTOM_API_MODEL_DEFAULT)
|