Commit ·
211214e
1
Parent(s): de69835
Added 3 retries for the AI explanation
Browse files
utils.py
CHANGED
|
@@ -8,6 +8,7 @@ import py3Dmol
|
|
| 8 |
from jinja2 import Environment, FileSystemLoader
|
| 9 |
from google import genai
|
| 10 |
from decouple import config
|
|
|
|
| 11 |
|
| 12 |
GEMINI_API_KEY = config("GEMINI_API_KEY")
|
| 13 |
|
|
@@ -230,11 +231,26 @@ def get_gemini_explanation(
|
|
| 230 |
4. **Conclusion:** Verdict on whether to proceed with this molecule.
|
| 231 |
Keep it relatively short (max 150 words). Do not include markdown code blocks (```html), just return the raw HTML tags.
|
| 232 |
"""
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
from jinja2 import Environment, FileSystemLoader
|
| 9 |
from google import genai
|
| 10 |
from decouple import config
|
| 11 |
+
import time
|
| 12 |
|
| 13 |
GEMINI_API_KEY = config("GEMINI_API_KEY")
|
| 14 |
|
|
|
|
| 231 |
4. **Conclusion:** Verdict on whether to proceed with this molecule.
|
| 232 |
Keep it relatively short (max 150 words). Do not include markdown code blocks (```html), just return the raw HTML tags.
|
| 233 |
"""
|
| 234 |
+
max_retries = 3
|
| 235 |
+
client = genai.Client(api_key=GEMINI_API_KEY)
|
| 236 |
+
for attempt in range(max_retries):
|
| 237 |
+
try:
|
| 238 |
+
response = client.models.generate_content(
|
| 239 |
+
model="gemini-2.5-flash", contents=prompt
|
| 240 |
+
)
|
| 241 |
+
return response.text
|
| 242 |
+
|
| 243 |
+
except Exception as e:
|
| 244 |
+
error_msg = str(e).lower()
|
| 245 |
+
|
| 246 |
+
if "503" in error_msg or "overloaded" in error_msg or "429" in error_msg:
|
| 247 |
+
if attempt < max_retries - 1:
|
| 248 |
+
wait_time = 2 * (attempt + 1)
|
| 249 |
+
print(f"Gemini overloaded, retrying in {wait_time}s...")
|
| 250 |
+
time.sleep(wait_time)
|
| 251 |
+
continue
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
return f"<p class='text-danger'>Error generating explanation: {str(e)}</p>"
|
| 255 |
+
|
| 256 |
+
return "<p class='text-danger'>Error: Gemini unavailable after retries.</p>"
|