Spaces:
Runtime error
Runtime error
File size: 2,321 Bytes
a3e25fc | 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 | import os
from typing import Optional
import google.generativeai as genai
class APIManager:
def __init__(self):
self.api_keys = []
self.current_index = 0
self.error_count = {}
# μ¬μ© κ°λ₯ν API ν€λ€ λ‘λ
for i in range(1, 4):
key = os.getenv(f"GEMINI_API_KEY_{i}")
if key and len(key) > 10:
self.api_keys.append(key)
self.error_count[key] = 0
print(f"π λ°κ²¬λ API ν€: {len(self.api_keys)}κ°")
def get_next_api_key(self) -> Optional[str]:
"""λΌμ΄λ λ‘λΉ λ°©μμΌλ‘ API ν€ μν"""
if not self.api_keys:
return None
key = self.api_keys[self.current_index]
self.current_index = (self.current_index + 1) % len(self.api_keys)
return key
def get_best_api_key(self) -> Optional[str]:
"""μλ¬κ° κ°μ₯ μ μ API ν€ λ°ν"""
if not self.api_keys:
return None
# μλ¬κ° μ μ ν€λ€λ§ νν°λ§
available_keys = [k for k in self.api_keys if self.error_count[k] < 3]
if not available_keys:
# λͺ¨λ ν€κ° μλ¬κ° λ§μΌλ©΄ μλ¬ μΉ΄μ΄νΈ 리μ
for k in self.api_keys:
self.error_count[k] = 0
available_keys = self.api_keys
# μλ¬κ° κ°μ₯ μ μ ν€ λ°ν
return min(available_keys, key=lambda k: self.error_count[k])
def report_error(self, api_key: str):
"""API ν€μμ μλ¬ λ°μ μ νΈμΆ"""
if api_key in self.error_count:
self.error_count[api_key] += 1
print(f"β API μλ¬ λ°μ: {api_key[:10]}... (μλ¬ νμ: {self.error_count[api_key]})")
def test_api_key(self, api_key: str) -> bool:
"""API ν€κ° μλνλμ§ ν
μ€νΈ"""
try:
genai.configure(api_key=api_key)
model = genai.GenerativeModel('gemini-2.5-flash-preview-05-20')
response = model.generate_content("Hi")
return bool(response.text)
except Exception as e:
print(f"API ν
μ€νΈ μ€ν¨: {e}")
self.report_error(api_key)
return False |