demo / test_gemini.py
samiee2213's picture
Upload 55 files
65a8bf3 verified
Raw
History Blame Contribute Delete
1.62 kB
import os
import json
import urllib.request
import urllib.error
def load_env_keys():
backend_env = ".env"
if os.path.exists(backend_env):
with open(backend_env, "r", encoding="utf-8") as f:
for line in f:
line_str = line.strip()
if line_str.startswith("GEMINI_API_KEY="):
return line_str.split("=", 1)[1].strip('"').strip("'")
return ""
api_key = load_env_keys()
print(f"Loaded API key prefix: {api_key[:8]}...")
payload = {
"contents": [{"parts": [{"text": "Say 'Gemini is working!'"}]}],
"generationConfig": {"temperature": 0.2}
}
models = ["gemini-2.0-flash", "gemini-1.5-flash", "gemini-1.5-flash-latest", "gemini-1.5-pro"]
for model in models:
url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={api_key}"
print(f"\nTrying model: {model} at url: {url[:60]}...")
try:
req = urllib.request.Request(
url,
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"}
)
with urllib.request.urlopen(req, timeout=10) as response:
res_data = json.loads(response.read().decode("utf-8"))
print(f"Success! Response: {res_data['candidates'][0]['content']['parts'][0]['text'].strip()}")
except urllib.error.HTTPError as e:
print(f"HTTPError for {model}: {e.code} {e.reason}")
try:
print(f"Error details: {e.read().decode('utf-8')}")
except:
pass
except Exception as e:
print(f"Error for {model}: {str(e)}")