SHL / script /test_gemini.py
kshitiz14's picture
file destination changed
bd16b71
Raw History Blame Contribute Delete
2.22 kB
"""
Standalone Gemini connectivity test — run this directly to see the REAL
error behind "I'm having trouble reaching the recommendation engine".
Usage:
python script/test_gemini.py
"""
import os
import sys
from dotenv import load_dotenv
load_dotenv()
key = os.getenv("GEMINI_API_KEY")
print("=" * 60)
print("GEMINI_API_KEY loaded:", "YES" if key else "NO (missing!)")
if key:
print("Key preview:", key[:6] + "..." + key[-4:] if len(key) > 10 else "(too short, looks wrong)")
print("=" * 60)
if not key:
print("\n>>> Fix: open your .env file (NOT .env.example) and make sure it has:")
print(">>> GEMINI_API_KEY=your_real_key_here")
print(">>> Get a free key at: https://aistudio.google.com/apikey")
sys.exit(1)
try:
import google.generativeai as genai
except ImportError:
print("\n>>> google-generativeai is not installed. Run: pip install google-generativeai")
sys.exit(1)
genai.configure(api_key=key)
print("\nListing models available to this key...")
try:
models = list(genai.list_models())
flash_models = [m.name for m in models if "flash" in m.name.lower()]
print(f"Found {len(models)} total models. Flash models available:")
for m in flash_models:
print(" -", m)
except Exception as e:
print("FAILED to list models — this usually means the API key itself is invalid:")
print(f" {type(e).__name__}: {e}")
sys.exit(1)
print("\nTrying a real generate_content call with 'gemini-2.0-flash'...")
try:
model = genai.GenerativeModel("gemini-2.0-flash")
response = model.generate_content("Say OK if you can hear me.")
print("SUCCESS. Model replied:", response.text.strip())
except Exception as e:
print("FAILED to call gemini-2.0-flash:")
print(f" {type(e).__name__}: {e}")
print("\n>>> Try swapping the model name in app/agent.py (_MODEL) for one of the")
print(">>> 'Flash models available' listed above, then re-run this script.")
sys.exit(1)
print("\n" + "=" * 60)
print("Gemini is working correctly. If /chat is still failing, the bug")
print("is elsewhere (e.g. the FastAPI process isn't picking up the .env")
print("file, or a different working directory is being used at runtime).")
print("=" * 60)