Spaces:
Runtime error
Runtime error
File size: 6,925 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 | #!/usr/bin/env python3
"""
Example demonstrating the RateLimiter integration with ProviderManager.
This example shows how to:
1. Configure rate limits for different providers
2. Track usage across multiple time windows
3. Handle quota exceeded scenarios
4. Monitor provider availability
"""
import asyncio
import logging
from datetime import datetime, timezone
from voice_control.rate_limiter import RateLimiter
from voice_control.models import ProviderConfig, ProviderType
from voice_control.exceptions import QuotaExceededError, RateLimitExceededError
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
async def main():
"""Demonstrate RateLimiter functionality."""
# Initialize the rate limiter
rate_limiter = RateLimiter(cleanup_interval=60) # Cleanup every minute
await rate_limiter.initialize()
try:
# Configure different providers with various limits
providers = [
ProviderConfig(
name="web_speech_api",
provider_type=ProviderType.WEB_SPEECH_API,
enabled=True,
priority=1,
free_tier_limits={}, # No limits for Web Speech API
rate_limits={"requests_per_minute": 60},
supported_formats=["webm", "wav"],
supported_languages=["en-US"],
cost_per_minute=0.0, # Free
api_credentials={}
),
ProviderConfig(
name="google_speech",
provider_type=ProviderType.GOOGLE_SPEECH,
enabled=True,
priority=2,
free_tier_limits={"audio_minutes_per_month": 60}, # 60 minutes/month free
rate_limits={
"requests_per_minute": 1000,
"requests_per_day": 1000000
},
supported_formats=["webm", "wav", "flac"],
supported_languages=["en-US", "es-ES", "fr-FR"],
cost_per_minute=0.006, # $0.006 per minute after free tier
api_credentials={"api_key": "your-google-api-key"}
),
ProviderConfig(
name="azure_speech",
provider_type=ProviderType.AZURE_SPEECH,
enabled=True,
priority=3,
free_tier_limits={"audio_minutes_per_month": 300}, # 5 hours/month free
rate_limits={
"requests_per_minute": 20,
"requests_per_hour": 1000
},
supported_formats=["webm", "wav"],
supported_languages=["en-US", "en-GB"],
cost_per_minute=0.004, # $0.004 per minute after free tier
api_credentials={
"subscription_key": "your-azure-key",
"region": "eastus"
}
)
]
# Configure all providers
for config in providers:
await rate_limiter.configure_provider(config)
logger.info(f"Configured provider: {config.name}")
# Demonstrate quota checking and consumption
logger.info("\n=== Quota Checking Demo ===")
for provider_name in ["web_speech_api", "google_speech", "azure_speech"]:
# Check quota for a 30-second audio clip
quota_status = await rate_limiter.check_quota(provider_name, 30.0)
logger.info(f"{provider_name}: {quota_status.percentage_used:.1%} used, "
f"limit: {quota_status.limit}, remaining: {quota_status.remaining:.1f}")
# Simulate some usage
logger.info("\n=== Usage Simulation ===")
# Consume some quota for Google Speech (simulate 5 requests of 30 seconds each)
for i in range(5):
try:
success = await rate_limiter.consume_quota("google_speech", 30.0, 1)
logger.info(f"Google Speech request {i+1}: {'Success' if success else 'Failed'}")
except QuotaExceededError as e:
logger.warning(f"Google Speech quota exceeded: {e}")
break
except RateLimitExceededError as e:
logger.warning(f"Google Speech rate limited: {e}")
break
# Check usage statistics
logger.info("\n=== Usage Statistics ===")
for provider_name in ["google_speech", "azure_speech"]:
stats = await rate_limiter.get_usage_stats(provider_name, "minute")
logger.info(f"{provider_name} (last minute): "
f"{stats.requests_count} requests, "
f"{stats.audio_minutes:.1f} minutes, "
f"${stats.estimated_cost:.4f}")
# Demonstrate provider availability checking
logger.info("\n=== Provider Availability ===")
for provider_name in ["web_speech_api", "google_speech", "azure_speech"]:
available = await rate_limiter.is_provider_available(provider_name, 60.0) # 1 minute audio
logger.info(f"{provider_name}: {'Available' if available else 'Not Available'}")
# Demonstrate quota reset
logger.info("\n=== Quota Reset Demo ===")
# Reset Google Speech quota
await rate_limiter.reset_quota("google_speech", "requests_per_minute")
logger.info("Reset Google Speech requests_per_minute quota")
# Check quota after reset
quota_status = await rate_limiter.check_quota("google_speech", 30.0)
logger.info(f"Google Speech after reset: {quota_status.percentage_used:.1%} used")
# Demonstrate hitting limits
logger.info("\n=== Limit Testing ===")
# Try to exceed Azure's monthly limit (simulate 6 hours of audio)
try:
await rate_limiter.consume_quota("azure_speech", 21600.0, 1) # 6 hours in seconds
logger.info("Azure Speech: Unexpectedly succeeded")
except QuotaExceededError as e:
logger.info(f"Azure Speech: Expected quota exceeded - {e}")
# Show quota status for all providers
logger.info("\n=== Final Quota Status ===")
for provider_name in ["web_speech_api", "google_speech", "azure_speech"]:
quota_statuses = await rate_limiter.get_provider_quota_status(provider_name)
logger.info(f"\n{provider_name}:")
for window_name, status in quota_statuses.items():
logger.info(f" {window_name}: {status.percentage_used:.1%} used "
f"({status.current_usage:.1f}/{status.limit:.1f})")
finally:
# Clean up
await rate_limiter.shutdown()
logger.info("\nRateLimiter shutdown complete")
if __name__ == "__main__":
asyncio.run(main()) |