feat: implement 429 auto-retry exponential backoff to handle free tier Gemini rate limits

This commit is contained in:
Rui
2026-05-17 03:13:45 +02:00
parent 985c6e9e0a
commit 6a60d1cd2a
+10
View File
@@ -133,9 +133,19 @@ class SwarmAgent:
"tools": tools "tools": tools
} }
for attempt in range(5):
try:
req = urllib.request.Request(url, data=json.dumps(payload).encode('utf-8'), headers=headers, method='POST') req = urllib.request.Request(url, data=json.dumps(payload).encode('utf-8'), headers=headers, method='POST')
with urllib.request.urlopen(req) as res: with urllib.request.urlopen(req) as res:
return json.loads(res.read().decode('utf-8')) return json.loads(res.read().decode('utf-8'))
except urllib.error.HTTPError as e:
if e.code == 429:
wait_time = (attempt + 1) * 8
print(f" [W] Rate Limit (429) detectado. Aguardando {wait_time} segundos antes de tentar novamente (tentativa {attempt + 1}/5)...")
time.sleep(wait_time)
else:
raise e
raise Exception("Falha após 5 tentativas devido a limite de requisições (429).")
def execute(self): def execute(self):
self.setup_workspace() self.setup_workspace()