Spaces:
Running
Running
Update backend/agents/puzzle_agent.py
Browse files- backend/agents/puzzle_agent.py +34 -13
backend/agents/puzzle_agent.py
CHANGED
|
@@ -44,20 +44,41 @@ MAZE_TOOLBOX_XML = (
|
|
| 44 |
)
|
| 45 |
|
| 46 |
|
| 47 |
-
def _get_best_flash_model() -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
try:
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
except Exception as e:
|
| 60 |
-
print(f"
|
| 61 |
return "gemini-2.0-flash"
|
| 62 |
|
| 63 |
|
|
@@ -108,7 +129,7 @@ class PuzzleAgent:
|
|
| 108 |
self.model = None
|
| 109 |
else:
|
| 110 |
genai.configure(api_key=self.api_key)
|
| 111 |
-
best_model = _get_best_flash_model()
|
| 112 |
print(f"[PuzzleAgent] Selected Model: {best_model}")
|
| 113 |
self.model = genai.GenerativeModel(best_model)
|
| 114 |
|
|
|
|
| 44 |
)
|
| 45 |
|
| 46 |
|
| 47 |
+
def _get_best_flash_model(api_key: Optional[str] = None) -> str:
|
| 48 |
+
"""
|
| 49 |
+
Auto-detects the best available Gemini model.
|
| 50 |
+
Dynamically parses the list of supported models and selects the highest-version Flash model.
|
| 51 |
+
Falls back to a default if query fails or no flash models are found.
|
| 52 |
+
"""
|
| 53 |
+
key = api_key or os.getenv("GEMINI_API_KEY")
|
| 54 |
+
if not key:
|
| 55 |
+
return "gemini-2.0-flash"
|
| 56 |
try:
|
| 57 |
+
import google.generativeai as genai
|
| 58 |
+
import re
|
| 59 |
+
genai.configure(api_key=key)
|
| 60 |
+
|
| 61 |
+
# Get all available models for this key
|
| 62 |
+
models = [m.name for m in genai.list_models()]
|
| 63 |
+
|
| 64 |
+
# Filter for flash models
|
| 65 |
+
flash_candidates = [m for m in models if "flash" in m.lower()]
|
| 66 |
+
|
| 67 |
+
if flash_candidates:
|
| 68 |
+
# Sort by version number extracted from the name
|
| 69 |
+
def _extract_version(name: str) -> float:
|
| 70 |
+
match = re.search(r'(\d+\.\d+)', name)
|
| 71 |
+
return float(match.group(1)) if match else 0.0
|
| 72 |
+
|
| 73 |
+
flash_candidates.sort(key=_extract_version, reverse=True)
|
| 74 |
+
return flash_candidates[0].replace("models/", "")
|
| 75 |
+
|
| 76 |
+
# If no flash models found, fall back to standard candidates list
|
| 77 |
+
for candidate in ["models/gemini-2.0-flash", "models/gemini-1.5-flash", "models/gemini-1.0-pro"]:
|
| 78 |
+
if candidate in models:
|
| 79 |
+
return candidate.replace("models/", "")
|
| 80 |
except Exception as e:
|
| 81 |
+
print(f"[PuzzleAgent] Error listing models: {e}. Defaulting to gemini-2.0-flash.")
|
| 82 |
return "gemini-2.0-flash"
|
| 83 |
|
| 84 |
|
|
|
|
| 129 |
self.model = None
|
| 130 |
else:
|
| 131 |
genai.configure(api_key=self.api_key)
|
| 132 |
+
best_model = _get_best_flash_model(self.api_key)
|
| 133 |
print(f"[PuzzleAgent] Selected Model: {best_model}")
|
| 134 |
self.model = genai.GenerativeModel(best_model)
|
| 135 |
|