Update app.py
Browse files
app.py
CHANGED
|
@@ -4,24 +4,36 @@ import requests
|
|
| 4 |
def check_key_gemini_availability(key):
|
| 5 |
"""
|
| 6 |
Checks the availability of a Gemini API key.
|
| 7 |
-
|
| 8 |
Args:
|
| 9 |
key: The API key to check.
|
| 10 |
-
|
| 11 |
Returns:
|
| 12 |
A tuple containing a boolean indicating whether the key is valid and an error message (or None if the key is valid).
|
| 13 |
"""
|
| 14 |
try:
|
|
|
|
| 15 |
url_getListModel = f"https://generativelanguage.googleapis.com/v1beta/models?key={key}"
|
| 16 |
rq = requests.get(url_getListModel)
|
| 17 |
rq.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
|
| 18 |
result = rq.json()
|
| 19 |
-
if 'models' in result:
|
| 20 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
else:
|
| 22 |
-
|
|
|
|
|
|
|
| 23 |
except requests.exceptions.HTTPError as e:
|
| 24 |
-
return False, f"Invalid key: HTTP {e.response.status_code}"
|
| 25 |
except Exception as e:
|
| 26 |
return False, f"Error key: {e}"
|
| 27 |
|
|
|
|
| 4 |
def check_key_gemini_availability(key):
|
| 5 |
"""
|
| 6 |
Checks the availability of a Gemini API key.
|
|
|
|
| 7 |
Args:
|
| 8 |
key: The API key to check.
|
|
|
|
| 9 |
Returns:
|
| 10 |
A tuple containing a boolean indicating whether the key is valid and an error message (or None if the key is valid).
|
| 11 |
"""
|
| 12 |
try:
|
| 13 |
+
# First, check if the key allows access to the list of models
|
| 14 |
url_getListModel = f"https://generativelanguage.googleapis.com/v1beta/models?key={key}"
|
| 15 |
rq = requests.get(url_getListModel)
|
| 16 |
rq.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
|
| 17 |
result = rq.json()
|
| 18 |
+
if 'models' not in result:
|
| 19 |
+
return False, f"Invalid key: 'models' field not found in response from list models endpoint."
|
| 20 |
+
|
| 21 |
+
# Second, attempt to generate content to further validate the key
|
| 22 |
+
url_generateContent = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={key}"
|
| 23 |
+
# headers = {'Content-Type': 'application/json'}
|
| 24 |
+
data = {"contents": [{"parts": [{"text": "Say \"this is a test\""}]}]}
|
| 25 |
+
rq = requests.post(url_generateContent, headers=headers, json=data) #data=json.dumps(data)
|
| 26 |
+
|
| 27 |
+
if 400 <= rq.status_code < 500:
|
| 28 |
+
return False, f"Invalid key: Generate content returned HTTP {rq.status_code}"
|
| 29 |
+
elif 500 <= rq.status_code < 600:
|
| 30 |
+
return True, None # consider 5xx as valid, could be temporary issue.
|
| 31 |
else:
|
| 32 |
+
rq.raise_for_status() # Raise other errors for other status codes
|
| 33 |
+
return True, None
|
| 34 |
+
|
| 35 |
except requests.exceptions.HTTPError as e:
|
| 36 |
+
return False, f"Invalid key: HTTP {e.response.status_code} - {e}"
|
| 37 |
except Exception as e:
|
| 38 |
return False, f"Error key: {e}"
|
| 39 |
|