Spaces:
Sleeping
Sleeping
File size: 2,264 Bytes
06281e0 cfc9386 06281e0 cb9e12d 562adbd 06281e0 cb9e12d 06281e0 cfc9386 06281e0 cfc9386 | 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 | import os
import time
from google import genai
from google.genai import types
class GeminiAgent:
def __init__(self, api_key=None, system_instruction=None):
key = api_key or os.environ.get("GEMINI_API_KEY")
if not key:
raise ValueError("GEMINI_API_KEY is not set.")
self.client = genai.Client(api_key=key)
self.system_instruction = system_instruction
self.models = [
"gemini-2.5-flash",
"gemini-2.5-pro",
"gemini-2.0-flash",
"gemini-2.0-flash-lite",
"gemini-2.0-pro",
"gemini-1.5-pro",
"gemini-1.5-flash"
]
def generate_content(self, prompt):
config = types.GenerateContentConfig(
system_instruction=self.system_instruction,
)
errors = {}
for model in self.models:
retries = 3
for attempt in range(retries):
try:
response = self.client.models.generate_content(
model=model,
contents=prompt,
config=config
)
return response.text
except Exception as e:
error_msg = str(e)
# Nếu lỗi 429 (vượt quá quota), sẽ chờ một khoảng thời gian rồi gọi lại
if "429" in error_msg or "RESOURCE_EXHAUSTED" in error_msg:
wait_time = 15 * (attempt + 1)
print(f"[Warning] Model {model} hit Quota Limit (429). Retrying in {wait_time}s...")
time.sleep(wait_time)
errors[model] = f"429 Quota Exceeded (retried {attempt+1} times)"
continue
else:
# Các lỗi khác như 404 sẽ chuyển ngay sang model dự phòng
print(f"[Warning] Model {model} failed: {e}. Trying next model...")
errors[model] = error_msg
break
raise RuntimeError(f"Tất cả model đều thất bại. Hãy kiểm tra lại Quota API của bạn. Chi tiết lỗi: {errors}")
|