#!/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!")