Spaces:
Sleeping
Sleeping
Download src/utils/rate_limiter.py from faseehsandhu/Digitalytics: direct link, hf CLI and curl.
- Browser
- Download file 7.22 kB
-
https://huggingface.co/spaces/faseehsandhu/Digitalytics/resolve/main/src/utils/rate_limiter.py
- Command line
-
hf download hf://spaces/faseehsandhu/Digitalytics/src/utils/rate_limiter.py
-
curl -L -o rate_limiter.py https://huggingface.co/spaces/faseehsandhu/Digitalytics/resolve/main/src/utils/rate_limiter.py
7.22 kB
| """ | |
| Rate limiter for API calls to prevent abuse and control costs. | |
| Implements per-user rate limiting with token bucket algorithm. | |
| """ | |
| import time | |
| from collections import defaultdict | |
| from typing import Dict, Tuple | |
| class RateLimiter: | |
| """Rate limiter using token bucket algorithm.""" | |
| def __init__(self, max_requests_per_minute: int = 60, user_key: str = "default"): | |
| """ | |
| Initialize rate limiter. | |
| Args: | |
| max_requests_per_minute: Maximum requests allowed per minute | |
| user_key: Key to identify user (can be session ID, IP, etc) | |
| """ | |
| self.max_requests = max_requests_per_minute | |
| self.window_seconds = 60 | |
| self.user_key = user_key | |
| # Track requests per user: user_id -> list of timestamps | |
| self.requests: Dict[str, list] = defaultdict(list) | |
| # Optionally track request details for analytics | |
| self.request_details: Dict[str, list] = defaultdict(list) | |
| def is_allowed(self, user_id: str = None) -> bool: | |
| """ | |
| Check if user has exceeded rate limit. | |
| Args: | |
| user_id: User identifier (defaults to self.user_key) | |
| Returns: | |
| True if request is allowed, False if rate limit exceeded | |
| """ | |
| if user_id is None: | |
| user_id = self.user_key | |
| now = time.time() | |
| cutoff = now - self.window_seconds # Only count recent requests | |
| # Clean up old requests (outside the window) | |
| self.requests[user_id] = [ | |
| ts for ts in self.requests[user_id] if ts > cutoff | |
| ] | |
| # Check if limit exceeded | |
| if len(self.requests[user_id]) >= self.max_requests: | |
| return False | |
| # Record this request | |
| self.requests[user_id].append(now) | |
| return True | |
| def get_remaining(self, user_id: str = None) -> int: | |
| """ | |
| Get remaining requests for user in current minute. | |
| Args: | |
| user_id: User identifier | |
| Returns: | |
| Number of remaining requests this minute | |
| """ | |
| if user_id is None: | |
| user_id = self.user_key | |
| now = time.time() | |
| cutoff = now - self.window_seconds | |
| valid_requests = [ | |
| ts for ts in self.requests[user_id] if ts > cutoff | |
| ] | |
| remaining = max(0, self.max_requests - len(valid_requests)) | |
| return remaining | |
| def get_reset_time(self, user_id: str = None) -> float: | |
| """ | |
| Get time until rate limit resets (in seconds). | |
| Args: | |
| user_id: User identifier | |
| Returns: | |
| Seconds until next request allowed (0 if allowed now) | |
| """ | |
| if user_id is None: | |
| user_id = self.user_key | |
| if not self.requests[user_id]: | |
| return 0 | |
| oldest_request = min(self.requests[user_id]) | |
| reset_time = (oldest_request + self.window_seconds) - time.time() | |
| return max(0, reset_time) | |
| def log_request(self, user_id: str, request_type: str, cost: float = 0.0): | |
| """ | |
| Log detailed information about a request. | |
| Args: | |
| user_id: User identifier | |
| request_type: Type of request (e.g., "embedding", "chat") | |
| cost: Estimated cost of the request | |
| """ | |
| self.request_details[user_id].append({ | |
| "timestamp": time.time(), | |
| "type": request_type, | |
| "cost": cost | |
| }) | |
| def get_user_cost(self, user_id: str = None, minutes: int = 60) -> float: | |
| """ | |
| Calculate total API cost for user in last N minutes. | |
| Args: | |
| user_id: User identifier | |
| minutes: Time window in minutes | |
| Returns: | |
| Total estimated cost | |
| """ | |
| if user_id is None: | |
| user_id = self.user_key | |
| if user_id not in self.request_details: | |
| return 0.0 | |
| now = time.time() | |
| cutoff = now - (minutes * 60) | |
| total_cost = sum( | |
| detail["cost"] | |
| for detail in self.request_details[user_id] | |
| if detail["timestamp"] > cutoff | |
| ) | |
| return total_cost | |
| def reset_user(self, user_id: str = None): | |
| """ | |
| Reset rate limit for specific user (admin function). | |
| Args: | |
| user_id: User identifier to reset | |
| """ | |
| if user_id is None: | |
| user_id = self.user_key | |
| self.requests[user_id] = [] | |
| if user_id in self.request_details: | |
| self.request_details[user_id] = [] | |
| class CostTracker: | |
| """Track API costs for monitoring and billing.""" | |
| # Pricing as of 2024 (update as needed) | |
| EMBEDDING_COST_PER_M_TOKENS = 0.02 # $ per 1M tokens | |
| CHAT_INPUT_COST_PER_M_TOKENS = 0.15 # $ per 1M tokens | |
| CHAT_OUTPUT_COST_PER_M_TOKENS = 0.60 # $ per 1M tokens | |
| def __init__(self): | |
| """Initialize cost tracker.""" | |
| self.costs: Dict[str, float] = defaultdict(float) | |
| self.token_counts: Dict[str, int] = defaultdict(int) | |
| self.call_counts: Dict[str, int] = defaultdict(int) | |
| def add_embedding_cost(self, num_tokens: int, user_id: str = "default"): | |
| """ | |
| Record embedding API call cost. | |
| Args: | |
| num_tokens: Number of tokens used | |
| user_id: User identifier | |
| """ | |
| cost = (num_tokens / 1_000_000) * self.EMBEDDING_COST_PER_M_TOKENS | |
| self.costs[user_id] += cost | |
| self.token_counts[user_id] += num_tokens | |
| self.call_counts[f"{user_id}:embedding"] += 1 | |
| def add_chat_cost(self, input_tokens: int, output_tokens: int, user_id: str = "default"): | |
| """ | |
| Record chat API call cost. | |
| Args: | |
| input_tokens: Number of input tokens | |
| output_tokens: Number of output tokens | |
| user_id: User identifier | |
| """ | |
| in_cost = (input_tokens / 1_000_000) * self.CHAT_INPUT_COST_PER_M_TOKENS | |
| out_cost = (output_tokens / 1_000_000) * self.CHAT_OUTPUT_COST_PER_M_TOKENS | |
| total_cost = in_cost + out_cost | |
| self.costs[user_id] += total_cost | |
| self.token_counts[user_id] += input_tokens + output_tokens | |
| self.call_counts[f"{user_id}:chat"] += 1 | |
| def get_user_cost(self, user_id: str = "default") -> float: | |
| """Get total cost for user.""" | |
| return self.costs[user_id] | |
| def get_stats(self, user_id: str = "default") -> Dict: | |
| """ | |
| Get detailed cost statistics for user. | |
| Returns: | |
| Dictionary with tokens, calls, and total cost | |
| """ | |
| return { | |
| "total_cost": self.costs[user_id], | |
| "total_tokens": self.token_counts[user_id], | |
| "embedding_calls": self.call_counts.get(f"{user_id}:embedding", 0), | |
| "chat_calls": self.call_counts.get(f"{user_id}:chat", 0), | |
| } | |
| def get_all_costs(self) -> Dict: | |
| """Get costs for all users (for dashboard).""" | |
| return dict(self.costs) | |