File size: 10,758 Bytes
09801ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
"""
Groq Multi-API-Key Load Balancer with Auto-Fallback
Production-grade load balancer for Groq API with:
- 3-key rotation (round-robin)
- Automatic fallback on errors
- Retry logic with exponential backoff
- Temporary blacklisting for failed keys
- Usage statistics tracking
"""

import os
import time
import asyncio
import logging
from typing import Dict, List, Optional, Any
from datetime import datetime, timedelta
from groq import Groq, AsyncGroq
from groq.types.chat import ChatCompletion

logger = logging.getLogger(__name__)

# ============================================================================
# CONFIGURATION
# ============================================================================

API_KEYS = [
    os.getenv("GROQ_API_KEY"),  # Primary key
    os.getenv("GROQ_KEY_1"),     # Fallback 1
    os.getenv("GROQ_KEY_2"),     # Fallback 2
]

# Filter out None values if environment variables are not set
API_KEYS = [key for key in API_KEYS if key]

if not API_KEYS:
    logger.warning("No Groq API keys configured. Load balancer will not work.")

# Default model
DEFAULT_MODEL = "openai/gpt-oss-20b"

# Configuration
MAX_RETRIES_PER_KEY = 3
RETRY_DELAY_MS = 200  # Base delay between retries
BLACKLIST_DURATION_SECONDS = 60
RECOVERABLE_ERRORS = {
    "ECONNRESET",
    "ETIMEDOUT",
    "429",  # Rate limit
    "500", "502", "503", "504",  # Server errors
}


# ============================================================================
# STATE MANAGEMENT
# ============================================================================

class KeyState:
    """Track state for each API key"""
    def __init__(self, key: str):
        self.key = key
        self.usage_count = 0
        self.fail_count = 0
        self.consecutive_fails = 0
        self.last_success: Optional[datetime] = None
        self.last_failure: Optional[datetime] = None
        self.blacklisted_until: Optional[datetime] = None
    
    def is_blacklisted(self) -> bool:
        """Check if key is currently blacklisted"""
        if self.blacklisted_until is None:
            return False
        if datetime.now() > self.blacklisted_until:
            self.blacklisted_until = None
            self.consecutive_fails = 0
            return False
        return True
    
    def blacklist(self):
        """Blacklist this key temporarily"""
        self.blacklisted_until = datetime.now() + timedelta(seconds=BLACKLIST_DURATION_SECONDS)
        logger.warning(f"Key {self.key[:8]}... blacklisted until {self.blacklisted_until}")
    
    def record_success(self):
        """Record successful request"""
        self.usage_count += 1
        self.consecutive_fails = 0
        self.last_success = datetime.now()
    
    def record_failure(self):
        """Record failed request"""
        self.fail_count += 1
        self.consecutive_fails += 1
        self.last_failure = datetime.now()
        
        # Blacklist after 3 consecutive failures
        if self.consecutive_fails >= MAX_RETRIES_PER_KEY:
            self.blacklist()


# Initialize key states
key_states: Dict[str, KeyState] = {
    key: KeyState(key) for key in API_KEYS
}

# Current key index for round-robin
current_key_index = 0


# ============================================================================
# HELPER FUNCTIONS
# ============================================================================

def get_current_key() -> Optional[str]:
    """Get current API key, skipping blacklisted ones"""
    global current_key_index
    
    if not API_KEYS:
        return None
    
    attempts = 0
    max_attempts = len(API_KEYS)
    
    while attempts < max_attempts:
        key = API_KEYS[current_key_index]
        state = key_states[key]
        
        if not state.is_blacklisted():
            return key
        
        # Try next key
        rotate_key()
        attempts += 1
    
    # All keys blacklisted
    logger.error("All Groq API keys are blacklisted!")
    return None


def rotate_key():
    """Rotate to next key in round-robin fashion"""
    global current_key_index
    current_key_index = (current_key_index + 1) % len(API_KEYS)


async def sleep_with_backoff(attempt: int):
    """Sleep with exponential backoff"""
    delay_ms = RETRY_DELAY_MS * (2 ** attempt)
    await asyncio.sleep(delay_ms / 1000)


def is_recoverable_error(error: Exception) -> bool:
    """Check if error is recoverable (should retry)"""
    error_str = str(error).upper()
    
    for recoverable in RECOVERABLE_ERRORS:
        if recoverable in error_str:
            return True
    
    return False


# ============================================================================
# MAIN LOAD BALANCER FUNCTION
# ============================================================================

async def groq_request(
    messages: List[Dict[str, str]],
    model: str = DEFAULT_MODEL,
    temperature: float = 0.7,
    max_tokens: int = 2000,
    **kwargs
) -> ChatCompletion:
    """
    Make a Groq API request with automatic load balancing and fallback.
    
    Args:
        messages: List of chat messages
        model: Model to use
        temperature: Sampling temperature
        max_tokens: Maximum tokens to generate
        **kwargs: Additional arguments to pass to Groq API
    
    Returns:
        ChatCompletion response
    
    Raises:
        Exception: If all keys fail
    """
    if not API_KEYS:
        raise Exception("No Groq API keys configured")
    
    max_attempts = len(API_KEYS) * MAX_RETRIES_PER_KEY
    attempt = 0
    last_error = None
    
    while attempt < max_attempts:
        # Get current key
        current_key = get_current_key()
        if current_key is None:
            # All keys blacklisted, wait and retry
            logger.warning("All keys blacklisted, waiting before retry...")
            await asyncio.sleep(5)
            continue
        
        state = key_states[current_key]
        
        try:
            # Create client with current key
            client = AsyncGroq(api_key=current_key)
            
            # Make request
            logger.info(f"Groq request using key {current_key[:8]}... (attempt {attempt + 1}/{max_attempts})")
            
            response = await client.chat.completions.create(
                model=model,
                messages=messages,
                temperature=temperature,
                max_tokens=max_tokens,
                **kwargs
            )
            
            # Success!
            state.record_success()
            logger.info(f"✓ Groq request succeeded with key {current_key[:8]}...")
            
            return response
        
        except Exception as e:
            last_error = e
            state.record_failure()
            
            logger.error(f"✗ Groq request failed with key {current_key[:8]}...: {str(e)}")
            
            # Check if error is recoverable
            if is_recoverable_error(e):
                # Rotate to next key
                rotate_key()
                
                # Sleep with backoff
                await sleep_with_backoff(attempt)
                
                attempt += 1
            else:
                # Non-recoverable error, raise immediately
                raise e
    
    # All attempts failed
    raise Exception(f"All Groq API keys failed after {max_attempts} attempts. Last error: {str(last_error)}")


# ============================================================================
# STATISTICS AND DEBUGGING
# ============================================================================

def get_key_stats() -> Dict[str, Any]:
    """Get usage statistics for all keys"""
    stats = {}
    
    for key, state in key_states.items():
        key_preview = f"{key[:8]}..." if key else "None"
        stats[key_preview] = {
            "usage_count": state.usage_count,
            "fail_count": state.fail_count,
            "consecutive_fails": state.consecutive_fails,
            "last_success": state.last_success.isoformat() if state.last_success else None,
            "last_failure": state.last_failure.isoformat() if state.last_failure else None,
            "is_blacklisted": state.is_blacklisted(),
            "blacklisted_until": state.blacklisted_until.isoformat() if state.blacklisted_until else None,
        }
    
    stats["current_key_index"] = current_key_index
    stats["total_keys"] = len(API_KEYS)
    
    return stats


def reset_stats():
    """Reset all statistics (useful for testing)"""
    global key_states, current_key_index
    
    key_states = {
        key: KeyState(key) for key in API_KEYS
    }
    current_key_index = 0
    
    logger.info("Groq load balancer stats reset")


# ============================================================================
# CONVENIENCE FUNCTIONS
# ============================================================================

async def groq_chat(
    prompt: str,
    system_message: Optional[str] = None,
    model: str = DEFAULT_MODEL,
    **kwargs
) -> str:
    """
    Simplified chat function for single-turn conversations.
    
    Args:
        prompt: User prompt
        system_message: Optional system message
        model: Model to use
        **kwargs: Additional arguments
    
    Returns:
        Generated text response
    """
    messages = []
    
    if system_message:
        messages.append({"role": "system", "content": system_message})
    
    messages.append({"role": "user", "content": prompt})
    
    response = await groq_request(messages=messages, model=model, **kwargs)
    
    return response.choices[0].message.content


# ============================================================================
# EXAMPLE USAGE
# ============================================================================

if __name__ == "__main__":
    async def test():
        """Test the load balancer"""
        
        # Example 1: Simple chat
        response = await groq_chat(
            prompt="What is the capital of France?",
            system_message="You are a helpful assistant."
        )
        print("Response:", response)
        
        # Example 2: Multi-turn conversation
        messages = [
            {"role": "system", "content": "You are a business analyst."},
            {"role": "user", "content": "Analyze this revenue data: Q1: $100k, Q2: $150k, Q3: $180k"},
        ]
        
        response = await groq_request(messages=messages)
        print("Analysis:", response.choices[0].message.content)
        
        # Example 3: Check statistics
        stats = get_key_stats()
        print("\nKey Statistics:")
        import json
        print(json.dumps(stats, indent=2))
    
    # Run test
    asyncio.run(test())