-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebug_api.py
More file actions
144 lines (122 loc) · 5.17 KB
/
Copy pathdebug_api.py
File metadata and controls
144 lines (122 loc) · 5.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
"""
Gemini API Key Deep Diagnostic & RCA Tool
Run: python debug_api.py
"""
import os
import sys
import json
import time
from pathlib import Path
from dotenv import load_dotenv
load_dotenv(dotenv_path=Path(__file__).parent / ".env")
api_key = os.getenv("GEMINI_API_KEY")
print("=" * 60)
print(" GEMINI API KEY DIAGNOSTIC TOOL")
print("=" * 60)
# --- STEP 1: Key presence ---
print("\n[STEP 1] Checking .env file...")
if not api_key:
print(" FAIL: GEMINI_API_KEY not found in .env")
sys.exit(1)
print(f" PASS: Key found: {api_key[:12]}...{api_key[-6:]}")
print(f" Key length: {len(api_key)} chars")
print(f" Key prefix: {api_key[:5]} (should start with 'AQ.Ab')")
# --- STEP 2: Import library ---
print("\n[STEP 2] Importing google.generativeai...")
try:
import google.generativeai as genai
import warnings
warnings.filterwarnings("ignore") # suppress FutureWarning noise
print(" PASS: Library imported successfully")
except ImportError as e:
print(f" FAIL: Cannot import google.generativeai: {e}")
sys.exit(1)
# --- STEP 3: Configure & list models ---
print("\n[STEP 3] Configuring API key and listing available models...")
try:
genai.configure(api_key=api_key)
models = [m.name for m in genai.list_models() if "generateContent" in m.supported_generation_methods]
print(f" PASS: {len(models)} models available")
for m in models[:5]:
print(f" - {m}")
if len(models) > 5:
print(f" ... and {len(models) - 5} more")
except Exception as e:
print(f" FAIL: Cannot list models: {e}")
# --- STEP 4: Test each model with full error breakdown ---
test_models = [
"gemini-3.5-flash",
"gemini-flash-latest",
"gemini-2.0-flash",
"gemini-2.0-flash-lite",
]
print("\n[STEP 4] Testing content generation across models...")
print("-" * 60)
results = {}
for model_name in test_models:
print(f"\n Testing: {model_name}")
try:
model = genai.GenerativeModel(model_name)
start = time.time()
response = model.generate_content("Say the word: OK")
elapsed = round(time.time() - start, 2)
results[model_name] = "WORKING"
print(f" RESULT: [SUCCESS] Response='{response.text.strip()}' | Time={elapsed}s")
except Exception as e:
error_str = str(e)
results[model_name] = "FAILED"
# Parse quota violation details
if "429" in error_str or "ResourceExhausted" in error_str:
print(f" RESULT: [FAIL] 429 Quota Exceeded")
# Extract exact quota details
if "GenerateRequestsPerDayPerProjectPerModel-FreeTier" in error_str:
print(f" RCA: Daily request limit hit (free tier)")
# Try to find the quota_value
if "quota_value: 20" in error_str:
print(f" Limit: 20 requests/day used up")
elif "limit: 0" in error_str:
print(f" Limit: 0 — This model may be DISABLED for this key's project")
if "GenerateRequestsPerMinutePerProjectPerModel-FreeTier" in error_str:
print(f" RCA: Per-minute rate limit hit")
if "GenerateContentInputTokensPerModelPerMinute-FreeTier" in error_str:
print(f" RCA: Input token per-minute limit hit")
# Retry delay
import re
retry_match = re.search(r"retry_delay \{\s*seconds: (\d+)", error_str)
if retry_match:
print(f" Retry after: {retry_match.group(1)} seconds")
elif "404" in error_str or "not found" in error_str.lower():
print(f" RESULT: [FAIL] Model not found / not available for this key")
elif "403" in error_str or "API_KEY_INVALID" in error_str:
print(f" RESULT: [FAIL] Invalid or revoked API key")
elif "PermissionDenied" in error_str:
print(f" RESULT: [FAIL] Permission denied — billing may be required")
else:
print(f" RESULT: [FAIL] Unknown error:")
print(f" {error_str[:300]}")
# --- STEP 5: RCA Summary ---
print("\n" + "=" * 60)
print(" ROOT CAUSE ANALYSIS (RCA) SUMMARY")
print("=" * 60)
working = [m for m, r in results.items() if r == "WORKING"]
failed = [m for m, r in results.items() if r == "FAILED"]
print(f"\n Working models : {working if working else 'NONE'}")
print(f" Failed models : {failed}")
if not working:
print("\n DIAGNOSIS: All models failed.")
print(" Most likely cause: The Google Cloud project linked to")
print(" this API key has exhausted its FREE TIER daily quota.")
print("")
print(" Even NEW keys from the same Google account share the")
print(" same project quota. Each Google account's AI Studio")
print(" project has a hard cap of 20 req/day for gemini-3.5-flash.")
print("")
print(" ACTION REQUIRED:")
print(" 1. Sign in to a DIFFERENT Google account at:")
print(" https://aistudio.google.com/app/apikey")
print(" 2. Create a new API key there")
print(" 3. Paste into .env and re-run: python test_api_key.py")
else:
print(f"\n DIAGNOSIS: API key is working on {working[0]}.")
print(" Update gemini_client.py to use:", working[0])
print("\n" + "=" * 60)