← Back to File Tree
test_api_key.py
Language: python |
Path: test_api_key.py |
Lines: 77
#!/usr/bin/env python3
"""Quick test script to verify Anthropic API key."""
import os
from anthropic import Anthropic
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
api_key = os.getenv("ANTHROPIC_API_KEY")
print("=" * 70)
print("🔑 TESTING ANTHROPIC API KEY")
print("=" * 70)
print()
# Check if key exists
if not api_key:
print("❌ ERROR: ANTHROPIC_API_KEY not found in .env file")
print(" Please set your API key in .env")
exit(1)
# Check key format
if not api_key.startswith("sk-ant-"):
print("⚠️ WARNING: API key doesn't start with 'sk-ant-'")
print(f" Current key starts with: {api_key[:10]}...")
print()
print(f"✓ API Key found: {api_key[:20]}...{api_key[-10:]}")
print(f"✓ Key length: {len(api_key)} characters")
print()
# Test API call
print("Testing API connection...")
print("-" * 70)
try:
client = Anthropic(api_key=api_key)
response = client.messages.create(
model="claude-3-haiku-20240307",
max_tokens=50,
messages=[
{
"role": "user",
"content": "Reply with just the word 'Hello'"
}
]
)
print("✅ SUCCESS! API key is valid")
print()
print(f"Response: {response.content[0].text}")
print()
print(f"Tokens used: {response.usage.input_tokens} input, {response.usage.output_tokens} output")
print(f"Estimated cost: $0.{str(response.usage.input_tokens * 25 + response.usage.output_tokens * 125).zfill(5)}")
print()
print("=" * 70)
print("🎉 Your API key is working! You can now start the API server.")
print("=" * 70)
except Exception as e:
print("❌ FAILED! API key is invalid or there's an issue")
print()
print(f"Error: {str(e)}")
print()
print("=" * 70)
print("📋 NEXT STEPS:")
print("=" * 70)
print("1. Visit: https://console.anthropic.com/settings/keys")
print("2. Check if your key is 'Active'")
print("3. Verify you have credits remaining")
print("4. Generate a new key if needed")
print("5. Update .env with the new key")
print("6. Run this script again to verify")
print()
exit(1)