File size: 1,021 Bytes
ba18317
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import threading
from typing import List


class KeyRotationManager:
    def __init__(self):
        keys_str = os.getenv("GROQ_API_KEYS", "")
        if not keys_str:
            keys_str = os.getenv("GROQ_API_KEY", "")

        self.keys = [k.strip() for k in keys_str.split(",") if k.strip()]
        print(f"[KeyManager] Initialized with {len(self.keys)} key(s).")
        if not self.keys:
            print("[KeyManager] WARNING: No GROQ_API_KEYS or GROQ_API_KEY found in environment!")

        self.current_index = 0
        self.lock = threading.Lock()

    def get_next_key(self) -> str:
        with self.lock:
            if not self.keys:
                raise ValueError("No GROQ API keys found. Set GROQ_API_KEYS or GROQ_API_KEY in your .env file.")
            key = self.keys[self.current_index]
            self.current_index = (self.current_index + 1) % len(self.keys)
            return key

    def key_count(self) -> int:
        return len(self.keys)


key_manager = KeyRotationManager()