jostlebot commited on
Commit
81d2f14
·
1 Parent(s): 6b0f9b9

Better API key debugging - show key preview and specific error

Browse files
Files changed (1) hide show
  1. app.py +14 -7
app.py CHANGED
@@ -241,10 +241,17 @@ def test_api_key(api_key_input):
241
  source = f"env:{found_name}" if found_name else "none"
242
 
243
  if not key_to_use:
244
- # List what env vars exist (for debugging)
245
- env_keys = [k for k in os.environ.keys() if 'KEY' in k.upper() or 'ANTHROPIC' in k.upper()]
246
- hint = f" Found env vars with KEY/ANTHROPIC: {env_keys}" if env_keys else " No matching env vars found."
247
- return f"No API key found.{hint} Add ANTHROPIC_API_KEY to Space Settings > Repository secrets."
 
 
 
 
 
 
 
248
 
249
  try:
250
  client = anthropic.Anthropic(api_key=key_to_use)
@@ -254,9 +261,9 @@ def test_api_key(api_key_input):
254
  max_tokens=10,
255
  messages=[{"role": "user", "content": "Say 'OK'"}]
256
  )
257
- return f"API key valid (source: {source})"
258
  except anthropic.AuthenticationError:
259
- return f"Invalid API key (source: {source}). Please check your key."
260
  except Exception as e:
261
  return f"Error: {str(e)}"
262
 
@@ -277,7 +284,7 @@ with gr.Blocks(title="PromptWork", theme=gr.themes.Soft()) as app:
277
  )
278
  test_key_btn = gr.Button("Test Key", scale=1)
279
  key_status = gr.Textbox(label="Status", scale=2, interactive=False,
280
- value="Key loaded from environment" if default_key else "No key set")
281
 
282
  with gr.Tabs():
283
 
 
241
  source = f"env:{found_name}" if found_name else "none"
242
 
243
  if not key_to_use:
244
+ # Check if the env var exists but is empty
245
+ raw_key = os.environ.get("ANTHROPIC_API_KEY", "NOT_SET")
246
+ if raw_key == "NOT_SET":
247
+ return "ANTHROPIC_API_KEY not set. Add it in Space Settings > Repository secrets."
248
+ elif raw_key == "":
249
+ return "ANTHROPIC_API_KEY is set but EMPTY. Re-enter the key in Space secrets."
250
+ else:
251
+ return f"Key found but empty after strip. Raw length: {len(raw_key)}"
252
+
253
+ # Show key info (without revealing the key)
254
+ key_preview = f"{key_to_use[:7]}...{key_to_use[-4:]}" if len(key_to_use) > 15 else f"(length: {len(key_to_use)})"
255
 
256
  try:
257
  client = anthropic.Anthropic(api_key=key_to_use)
 
261
  max_tokens=10,
262
  messages=[{"role": "user", "content": "Say 'OK'"}]
263
  )
264
+ return f"API key valid! ({key_preview})"
265
  except anthropic.AuthenticationError:
266
+ return f"Invalid key ({key_preview}). Check the key in your Anthropic dashboard."
267
  except Exception as e:
268
  return f"Error: {str(e)}"
269
 
 
284
  )
285
  test_key_btn = gr.Button("Test Key", scale=1)
286
  key_status = gr.Textbox(label="Status", scale=2, interactive=False,
287
+ value="Click 'Test Key' to verify" if default_key else "Enter key or click Test Key")
288
 
289
  with gr.Tabs():
290