pdf-qa-chatbot / backend /test_openrouter.py
Amin23's picture
Iniital commit
e22dcc4
#!/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!")