File size: 9,846 Bytes
c001f24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# API Key Manager Guide

## Overview

The API Key Manager provides automatic failover and rotation across multiple API keys for the same service. If one API key fails due to rate limiting or errors, the system automatically switches to a backup key.

## Features

βœ… **Automatic Failover** - Switches to backup keys when one fails  
βœ… **Load Balancing** - Rotates through keys using round-robin  
βœ… **Failure Tracking** - Blocks keys after consecutive failures  
βœ… **Auto-Recovery** - Unblocks keys after cooldown period  
βœ… **Success Rate Monitoring** - Tracks performance of each key  
βœ… **Thread-Safe** - Can be used in multi-threaded environments  

## Configuration

### Setting Up Multiple API Keys

You can configure multiple API keys for each service using environment variables:

#### Method 1: Numbered Keys (Recommended)
```bash
# Gemini API Keys
export GEMINI_API_KEY_1="your-first-gemini-key"
export GEMINI_API_KEY_2="your-second-gemini-key"
export GEMINI_API_KEY_3="your-third-gemini-key"

# NVIDIA API Keys
export NVIDIA_API_KEY_1="your-first-nvidia-key"
export NVIDIA_API_KEY_2="your-second-nvidia-key"

# OpenRouter API Keys (for Nova)
export OPENROUTER_API_KEY_1="your-first-openrouter-key"
export OPENROUTER_API_KEY_2="your-second-openrouter-key"
```

#### Method 2: Single Key (Backward Compatible)
```bash
export GEMINI_API_KEY="your-gemini-key"
export NVIDIA_API_KEY="your-nvidia-key"
export OPENROUTER_API_KEY="your-openrouter-key"
```

#### Method 3: Mixed (Both Work Together)
```bash
# These will all be combined into the pool
export GEMINI_API_KEY="key-1"
export GEMINI_API_KEY_1="key-2"
export GEMINI_API_KEY_2="key-3"
# Result: 3 keys total (duplicates are automatically removed)
```

### Supported Services

| Service | Environment Variable Pattern | Used For |
|---------|----------------------------|----------|
| `nvidia` | `NVIDIA_API_KEY` or `NVIDIA_API_KEY_1`, `NVIDIA_API_KEY_2`, etc. | OCR processing |
| `gemini` | `GEMINI_API_KEY`, `GOOGLE_API_KEY`, or numbered variants | Question classification, Q&A extraction |
| `openrouter` | `OPENROUTER_API_KEY` or `OPENROUTER_API_KEY_1`, etc. | Amazon Nova classification |

## How It Works

### 1. Key Rotation
Keys are automatically rotated using round-robin:
```
Request 1 β†’ Key 1
Request 2 β†’ Key 2  
Request 3 β†’ Key 3
Request 4 β†’ Key 1 (back to start)
```

### 2. Failure Handling
When a key fails:
- Failure count is incremented
- After **3 consecutive failures**, the key is **blocked for 5 minutes**
- System automatically switches to next available key
- After cooldown period, key is automatically unblocked

### 3. Success Tracking
When a key succeeds:
- Success count is incremented
- Failure count is reset to 0
- Key is marked as available
- System rotates to next key for load balancing

## Usage in Code

### Automatic (Already Integrated)

The API Key Manager is already integrated into:
- βœ… `gemini_classifier.py` - Gemini question classification
- βœ… `nova_classifier.py` - Nova question classification  
- βœ… `processing.py` - NVIDIA OCR API

**No code changes needed!** Just set up multiple API keys and the system handles the rest.

### Manual Usage (Advanced)

If you need to add API key management to other modules:

```python
from api_key_manager import get_api_key_manager

# Get the manager instance
manager = get_api_key_manager()

# Get an API key
api_key, key_index = manager.get_key('gemini')

if api_key:
    try:
        # Make your API call
        response = make_api_call(api_key)
        
        # Mark as successful
        manager.mark_success('gemini', key_index)
        
    except Exception as e:
        # Mark as failed (will block after 3 failures)
        manager.mark_failure('gemini', key_index)
else:
    print("No API keys available!")
```

## Monitoring

### Get Service Status

```python
from api_key_manager import get_api_key_manager

manager = get_api_key_manager()

# Get status for one service
status = manager.get_service_status('gemini')
print(f"Available keys: {status['available_keys']}/{status['total_keys']}")
print(f"Blocked keys: {status['blocked_keys']}")

# Get status for all services
all_status = manager.get_all_services_status()
for service, info in all_status.items():
    print(f"{service}: {info['available_keys']}/{info['total_keys']} keys available")
```

### Example Output
```json
{
  "service": "gemini",
  "available": true,
  "total_keys": 3,
  "available_keys": 2,
  "blocked_keys": 1,
  "keys": [
    {
      "index": 0,
      "is_available": true,
      "is_blocked": false,
      "failure_count": 0,
      "total_requests": 15,
      "success_rate": 100.0,
      "blocked_until": null
    },
    {
      "index": 1,
      "is_available": true,
      "is_blocked": false,
      "failure_count": 0,
      "total_requests": 12,
      "success_rate": 100.0,
      "blocked_until": null
    },
    {
      "index": 2,
      "is_available": false,
      "is_blocked": true,
      "failure_count": 3,
      "total_requests": 8,
      "success_rate": 62.5,
      "blocked_until": "2025-12-08T04:30:00.000000"
    }
  ]
}
```

## Configuration Options

### Block Duration

By default, keys are blocked for **5 minutes** after 3 failures. You can customize this:

```python
# Block for 10 minutes instead
manager.mark_failure('gemini', key_index, block_duration_minutes=10)
```

### Failure Threshold

The failure threshold is currently hardcoded to **3 consecutive failures**. This is defined in `api_key_manager.py` in the `mark_failure()` method:

```python
if self.failure_count >= 3:
    self.is_blocked = True
```

## Troubleshooting

### Problem: "No API keys available"

**Cause:** All keys are blocked or no keys are configured.

**Solution:**
1. Check environment variables are set correctly
2. Wait for cooldown period (5 minutes)
3. Manually reset the service:
   ```python
   manager.reset_service('gemini')
   ```

### Problem: Keys getting blocked frequently

**Cause:** Rate limiting or invalid API keys.

**Solution:**
1. Check API key validity
2. Verify rate limits with your API provider
3. Add more API keys to distribute load
4. Increase block duration to avoid rapid retries

### Problem: Not using multiple keys even though they're configured

**Cause:** Check if keys are being loaded correctly.

**Solution:**
```python
manager = get_api_key_manager()
status = manager.get_service_status('gemini')
print(f"Total keys loaded: {status['total_keys']}")
```

## Best Practices

1. **Use at least 2-3 keys per service** for better reliability
2. **Monitor success rates** to identify problematic keys
3. **Stagger API requests** to avoid hitting rate limits
4. **Keep backup keys from different accounts** if possible
5. **Test keys periodically** to ensure they're still valid

## Logging

The API Key Manager logs important events:

```
INFO: Loaded API keys: NVIDIA=2, Gemini=3, OpenRouter=2
INFO: Registered 3 API key(s) for service: gemini
DEBUG: Using API key 1/3 for gemini
DEBUG: API key 1 for gemini marked as successful
WARNING: API key 2 for gemini marked as failed
WARNING: API key for gemini blocked until 2025-12-08 04:30:00 after 3 failures
INFO: API key for gemini unblocked after cooldown period
```

## Architecture

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    API Key Manager                           β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                                                               β”‚
β”‚  Service: nvidia        Service: gemini    Service: openrouterβ”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚ Key 1 βœ“      β”‚      β”‚ Key 1 βœ“      β”‚   β”‚ Key 1 βœ“      β”‚  β”‚
β”‚  β”‚ Key 2 βœ“      β”‚      β”‚ Key 2 βœ“      β”‚   β”‚ Key 2 βœ“      β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β”‚ Key 3 βœ—      β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚                        β”‚ (blocked)    β”‚                      β”‚
β”‚                        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                      β”‚
β”‚                                                               β”‚
β”‚  Features:                                                    β”‚
β”‚  β€’ Round-robin rotation                                      β”‚
β”‚  β€’ Automatic failover                                        β”‚
β”‚  β€’ Failure tracking                                          β”‚
β”‚  β€’ Auto-recovery after cooldown                              β”‚
β”‚                                                               β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚              β”‚              β”‚
         β–Ό              β–Ό              β–Ό
   processing.py   gemini_classifier.py   nova_classifier.py
   (NVIDIA OCR)    (Gemini AI)           (Amazon Nova)
```

## Future Enhancements

Potential improvements for the API Key Manager:

- [ ] Web dashboard for monitoring key status
- [ ] Configurable failure threshold per service
- [ ] Exponential backoff for blocked keys
- [ ] API key health checks
- [ ] Cost tracking per key
- [ ] Rate limit detection and adaptive throttling
- [ ] Database persistence for key statistics
- [ ] Email alerts when all keys are blocked
- [ ] Integration with settings page for user-visible status