Spaces:
Runtime error
Runtime error
File size: 7,027 Bytes
8cbe6eb | 1 2 3 4 5 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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | # RateLimiter Implementation
## Overview
The RateLimiter class provides sophisticated rate limiting and quota management for the voice control optimization system. It implements sliding window rate limiting with multi-window tracking, provider-specific limit enforcement, and automatic provider switching capabilities.
## Features
### Multi-Window Tracking
- **Sliding Windows**: Requests per minute/hour with automatic cleanup of old entries
- **Fixed Windows**: Daily and monthly quotas with scheduled resets
- **Audio Duration Limits**: Track audio minutes across different time periods
- **Request Count Limits**: Track number of requests across different time periods
### Provider-Specific Configuration
- **Individual Limits**: Each provider can have different rate limits and quotas
- **Free Tier Management**: Separate tracking for free tier limits vs paid usage
- **Multiple Quota Types**: Support for requests/minute, requests/day, audio minutes/day, audio minutes/month
### Intelligent Quota Management
- **Proactive Checking**: Check if requests would exceed limits before consuming quota
- **Automatic Switching**: Integration with ProviderManager for automatic provider switching
- **Usage Statistics**: Detailed usage tracking and reporting
- **Cost Estimation**: Calculate estimated costs based on usage and provider pricing
### Exponential Backoff
- **Rate Limit Violations**: Implement exponential backoff for repeated quota violations
- **Provider-Specific**: Independent backoff state for each provider and quota type
- **Automatic Recovery**: Reset backoff state on successful requests
## Architecture
```
RateLimiter
βββ Provider Configuration
β βββ Rate Limits (requests/minute, requests/hour, requests/day)
β βββ Free Tier Limits (audio minutes/day, audio minutes/month)
β βββ Cost Per Minute
βββ Multi-Window Tracking
β βββ Sliding Windows (cleanup old entries)
β βββ Fixed Windows (scheduled resets)
β βββ Usage Statistics
βββ Quota Management
β βββ Quota Checking (before consumption)
β βββ Quota Consumption (with validation)
β βββ Quota Reset (manual and automatic)
βββ Backoff Management
βββ Exponential Backoff
βββ Provider-Specific State
βββ Automatic Recovery
```
## Usage
### Basic Setup
```python
from voice_control.rate_limiter import RateLimiter
from voice_control.models import ProviderConfig, ProviderType
# Initialize rate limiter
rate_limiter = RateLimiter()
await rate_limiter.initialize()
# Configure a provider
config = ProviderConfig(
name="google_speech",
provider_type=ProviderType.GOOGLE_SPEECH,
enabled=True,
priority=2,
free_tier_limits={"audio_minutes_per_month": 60},
rate_limits={"requests_per_minute": 1000},
supported_formats=["webm", "wav"],
supported_languages=["en-US"],
cost_per_minute=0.006,
api_credentials={"api_key": "your-key"}
)
await rate_limiter.configure_provider(config)
```
### Quota Management
```python
# Check if request would exceed quota
quota_status = await rate_limiter.check_quota("google_speech", 30.0)
if not quota_status.is_exceeded:
# Consume quota for 30 seconds of audio
success = await rate_limiter.consume_quota("google_speech", 30.0, 1)
```
### Usage Statistics
```python
# Get usage statistics for different time windows
minute_stats = await rate_limiter.get_usage_stats("google_speech", "minute")
daily_stats = await rate_limiter.get_usage_stats("google_speech", "day")
print(f"Requests: {minute_stats.requests_count}")
print(f"Audio minutes: {minute_stats.audio_minutes}")
print(f"Estimated cost: ${minute_stats.estimated_cost:.4f}")
```
### Provider Availability
```python
# Check if provider is available (not rate limited)
available = await rate_limiter.is_provider_available("google_speech", 60.0)
if available:
# Provider can handle a 60-second request
pass
```
## Integration with ProviderManager
The RateLimiter integrates seamlessly with the existing ProviderManager:
```python
# In ProviderManager.transcribe_audio()
if self._rate_limiter:
audio_duration = len(audio_data) / (44100 * 2) # Estimate duration
quota_status = await self._rate_limiter.check_quota(provider_name, audio_duration)
if quota_status.is_exceeded:
continue # Try next provider
# After successful transcription
await self._rate_limiter.consume_quota(provider_name, result.audio_duration)
```
## Configuration Examples
### Web Speech API (Free, No Limits)
```python
ProviderConfig(
name="web_speech_api",
provider_type=ProviderType.WEB_SPEECH_API,
free_tier_limits={}, # No limits
rate_limits={"requests_per_minute": 60}, # Basic rate limiting
cost_per_minute=0.0 # Free
)
```
### Google Speech-to-Text (60 minutes/month free)
```python
ProviderConfig(
name="google_speech",
provider_type=ProviderType.GOOGLE_SPEECH,
free_tier_limits={"audio_minutes_per_month": 60},
rate_limits={
"requests_per_minute": 1000,
"requests_per_day": 1000000
},
cost_per_minute=0.006
)
```
### Azure Speech Services (5 hours/month free)
```python
ProviderConfig(
name="azure_speech",
provider_type=ProviderType.AZURE_SPEECH,
free_tier_limits={"audio_minutes_per_month": 300},
rate_limits={
"requests_per_minute": 20,
"requests_per_hour": 1000
},
cost_per_minute=0.004
)
```
## Error Handling
The RateLimiter raises specific exceptions for different scenarios:
- **QuotaExceededError**: When quota limits would be exceeded
- **RateLimitExceededError**: When rate limits are exceeded with backoff
```python
try:
await rate_limiter.consume_quota("provider", 30.0, 1)
except QuotaExceededError as e:
logger.warning(f"Quota exceeded: {e}")
# Switch to different provider
except RateLimitExceededError as e:
logger.warning(f"Rate limited: {e}")
# Wait for retry_after seconds
```
## Testing
Comprehensive test suite covers:
- **Unit Tests**: Individual method functionality
- **Integration Tests**: Multi-provider scenarios
- **Edge Cases**: Concurrent access, large durations, zero values
- **Error Conditions**: Quota exceeded, rate limiting, backoff
Run tests with:
```bash
python -m pytest voice_control/tests/test_rate_limiter.py -v
```
## Performance Considerations
- **In-Memory Storage**: Default storage for development and testing
- **Redis Support**: Optional Redis backend for distributed rate limiting
- **Cleanup Tasks**: Background cleanup of old sliding window data
- **Async Operations**: All operations are async for non-blocking performance
## Future Enhancements
- **Redis Integration**: Distributed rate limiting across multiple instances
- **Metrics Export**: Integration with monitoring systems (Prometheus, etc.)
- **Dynamic Limits**: Runtime adjustment of rate limits based on provider status
- **Predictive Switching**: Machine learning-based provider selection |