Spaces:
Runtime error
Runtime error
#!/usr/bin/env python3 | |
""" | |
Test script to verify OpenRouter API connectivity | |
""" | |
import os | |
import httpx | |
import json | |
from dotenv import load_dotenv | |
# Load environment variables | |
load_dotenv() | |
def test_openrouter_api(): | |
"""Test OpenRouter API connection""" | |
api_key = os.getenv("OPENROUTER_API_KEY") | |
if not api_key: | |
print("β No OpenRouter API key found in environment variables") | |
return False | |
print(f"π API Key found: {api_key[:10]}...{api_key[-4:]}") | |
# Test API endpoint | |
url = "https://openrouter.ai/api/v1/chat/completions" | |
headers = { | |
"Authorization": f"Bearer {api_key}", | |
"HTTP-Referer": "http://localhost:3000", | |
"X-Title": "PDF Q&A Chatbot Test", | |
"Content-Type": "application/json" | |
} | |
payload = { | |
"model": "meta-llama/llama-3-70b-instruct", | |
"messages": [ | |
{"role": "user", "content": "Hello! Please respond with 'API test successful' if you can see this message."} | |
], | |
"max_tokens": 50, | |
"temperature": 0.1 | |
} | |
print(f"π Making request to: {url}") | |
print(f"π€ Request payload: {json.dumps(payload, indent=2)}") | |
try: | |
with httpx.Client(timeout=30) as client: | |
response = client.post(url, headers=headers, json=payload) | |
print(f"π₯ Response status: {response.status_code}") | |
print(f"π₯ Response headers: {dict(response.headers)}") | |
# Log raw response | |
response_text = response.text | |
print(f"π₯ Raw response: {response_text}") | |
if not response_text.strip(): | |
print("β Empty response received") | |
return False | |
if response.status_code != 200: | |
print(f"β HTTP error: {response.status_code}") | |
return False | |
# Try to parse JSON | |
try: | |
data = response.json() | |
print(f"β JSON parsed successfully: {json.dumps(data, indent=2)}") | |
if "choices" in data and data["choices"]: | |
answer = data["choices"][0]["message"]["content"] | |
print(f"π€ AI Response: {answer}") | |
return True | |
else: | |
print("β No choices in response") | |
return False | |
except json.JSONDecodeError as e: | |
print(f"β JSON parsing failed: {e}") | |
return False | |
except Exception as e: | |
print(f"β Request failed: {e}") | |
return False | |
if __name__ == "__main__": | |
print("π§ͺ Testing OpenRouter API connectivity...") | |
success = test_openrouter_api() | |
if success: | |
print("β OpenRouter API test successful!") | |
else: | |
print("β OpenRouter API test failed!") |