""" Simple script to test if your Gemini API key is working. Run this to verify your API key before using it in the FastAPI service. """ import os from dotenv import load_dotenv from google import genai # Load .env load_dotenv() # Get API key api_key = os.getenv("GEMINI_API_KEY") if not api_key: print("[ERROR] GEMINI_API_KEY not found in .env file or environment") print("\nMake sure you have a .env file with:") print("GEMINI_API_KEY=your_key_here") exit(1) # Strip whitespace api_key = api_key.strip() print(f"[OK] API Key found: {api_key[:10]}... (length: {len(api_key)})") # Validate format if not api_key.startswith("AIza"): print("[WARNING] API key doesn't start with 'AIza' - this might be incorrect") # Test the API key print("\nTesting API key with Gemini...") try: client = genai.Client(api_key=api_key) # Try a simple test call print("Making test API call...") response = client.models.generate_content( model="gemini-2.5-flash-image", contents=["Generate a simple test image of a red circle."], ) print("\n[SUCCESS] API key is valid and working!") print("You can now use this key in your FastAPI service.") except Exception as e: error_msg = str(e) print(f"\n[ERROR] API key test failed") print(f"Error: {error_msg}") if "API key" in error_msg or "INVALID_ARGUMENT" in error_msg: print("\n[TROUBLESHOOTING]") print("1. Check that your API key is correct (no typos)") print("2. Verify the key in your .env file has no spaces or quotes") print("3. Make sure the key is from Google AI Studio: https://aistudio.google.com/app/apikey") print("4. Try regenerating a new API key") print("5. Check if the API key has expired or been revoked") else: print(f"\nUnexpected error: {e}")