Spaces:
Running
Running
#!/usr/bin/env python3 | |
"""Test OpenRouter API key functionality""" | |
import requests | |
import json | |
def test_openrouter_api_key(api_key): | |
"""Test if an OpenRouter API key is valid by making a simple completion request""" | |
url = "https://openrouter.ai/api/v1/chat/completions" | |
headers = { | |
"Authorization": f"Bearer {api_key}", | |
"Content-Type": "application/json", | |
"HTTP-Referer": "https://github.com/test-api-key", # Required by OpenRouter | |
"X-Title": "API Key Test" # Optional but recommended | |
} | |
# Simple test message | |
data = { | |
"model": "openrouter/auto", # Auto-select cheapest available model | |
"messages": [ | |
{"role": "user", "content": "Say 'API key is working!' in exactly 4 words."} | |
], | |
"max_tokens": 10, | |
"temperature": 0.1 | |
} | |
try: | |
print("Testing OpenRouter API key...") | |
response = requests.post(url, headers=headers, json=data, timeout=30) | |
if response.status_code == 200: | |
result = response.json() | |
if "choices" in result and len(result["choices"]) > 0: | |
assistant_message = result["choices"][0]["message"]["content"] | |
print(f"β API key is valid!") | |
print(f"Response: {assistant_message}") | |
print(f"Model used: {result.get('model', 'unknown')}") | |
return True | |
else: | |
print("β Unexpected response format") | |
return False | |
else: | |
error_data = response.json() if response.headers.get('content-type', '').startswith('application/json') else {} | |
print(f"β API key test failed!") | |
print(f"Status code: {response.status_code}") | |
print(f"Error: {error_data.get('error', {}).get('message', response.text)}") | |
# Common error interpretations | |
if response.status_code == 401: | |
print("β The API key is invalid or has been revoked") | |
elif response.status_code == 402: | |
print("β The API key has insufficient credits") | |
elif response.status_code == 429: | |
print("β Rate limit exceeded") | |
return False | |
except requests.exceptions.Timeout: | |
print("β Request timed out") | |
return False | |
except requests.exceptions.RequestException as e: | |
print(f"β Network error: {e}") | |
return False | |
except Exception as e: | |
print(f"β Unexpected error: {e}") | |
return False | |
if __name__ == "__main__": | |
# Test the provided API key | |
api_key = "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" | |
print(f"API Key: {api_key[:20]}...{api_key[-10:]}") | |
print("-" * 50) | |
success = test_openrouter_api_key(api_key) | |
print("-" * 50) | |
if success: | |
print("β The API key is working correctly!") | |
print("You can use this key in your Chat UI Helper application.") | |
else: | |
print("β The API key is not working.") | |
print("Please check that the key is correct and has available credits.") |