File size: 5,897 Bytes
4543176 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 |
"""
π Quick Perplexity API Key Test
Run this to verify your API key is working correctly
"""
import os
import requests
def test_perplexity_api_key():
"""Test if Perplexity API key is working"""
print("π Testing Perplexity API Key...")
print("=" * 40)
# Check if API key exists
api_key = os.getenv('PERPLEXITY_API_KEY')
if not api_key:
print("β PERPLEXITY_API_KEY environment variable not found")
print("\nπ‘ To fix this:")
print("1. Go to your HuggingFace Space Settings")
print("2. Add Repository secret:")
print(" Name: PERPLEXITY_API_KEY")
print(" Value: your_api_key_here")
print("3. Restart your Space")
return False
print(f"β
API key found: {api_key[:12]}...{api_key[-4:]}")
# Test API connection
print("\nπ§ͺ Testing API connection...")
try:
headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
payload = {
"model": "llama-3.1-sonar-large-128k-online",
"messages": [
{
"role": "user",
"content": "Test API connection - respond with 'API working' if you receive this."
}
],
"max_tokens": 50,
"temperature": 0.1
}
response = requests.post(
'https://api.perplexity.ai/chat/completions',
headers=headers,
json=payload,
timeout=30
)
if response.status_code == 200:
print("β
API connection successful!")
# Parse response
try:
result = response.json()
content = result['choices'][0]['message']['content']
print(f"π API Response: {content}")
print("\nπ Your Perplexity API integration is working correctly!")
return True
except Exception as e:
print(f"β οΈ Response parsing issue: {e}")
print("β
But API connection works!")
return True
elif response.status_code == 401:
print("β API key is invalid or expired")
print("\nπ‘ To fix this:")
print("1. Check your API key at https://www.perplexity.ai/")
print("2. Generate a new key if needed")
print("3. Update the PERPLEXITY_API_KEY secret in your Space")
return False
elif response.status_code == 429:
print("β οΈ API rate limit reached")
print("β
But API key is valid!")
return True
else:
print(f"β API error: {response.status_code}")
print(f"Response: {response.text}")
return False
except requests.exceptions.Timeout:
print("β° API request timed out")
print("β οΈ This might be a temporary network issue")
return False
except requests.exceptions.RequestException as e:
print(f"π Connection error: {e}")
return False
def test_ai_dataset_studio_integration():
"""Test the full AI Dataset Studio integration"""
print("\nπ Testing AI Dataset Studio Integration...")
print("=" * 40)
try:
# Try to import our Perplexity client
from perplexity_client import PerplexityClient, SearchType
print("β
Perplexity client module imported")
# Initialize client
client = PerplexityClient()
print("β
Perplexity client initialized")
# Test API key validation
if client._validate_api_key():
print("β
API key validation successful")
else:
print("β API key validation failed")
return False
# Test source discovery
print("\nπ Testing source discovery...")
results = client.discover_sources(
project_description="Test query for API integration verification",
search_type=SearchType.GENERAL,
max_sources=3
)
if results.sources:
print(f"β
Source discovery working! Found {len(results.sources)} sources")
print(f" Example: {results.sources[0].title}")
else:
print("β οΈ Source discovery returned no results (but API is working)")
print("\nπ AI Dataset Studio integration is fully functional!")
return True
except ImportError as e:
print(f"β Import error: {e}")
print("π‘ Make sure perplexity_client.py is uploaded to your Space")
return False
except Exception as e:
print(f"β Integration test failed: {e}")
return False
if __name__ == "__main__":
print("π§ͺ Perplexity API Integration Test")
print("=" * 50)
# Test 1: Basic API key
api_test = test_perplexity_api_key()
# Test 2: Full integration (only if basic test passes)
if api_test:
integration_test = test_ai_dataset_studio_integration()
if api_test and integration_test:
print("\n" + "=" * 50)
print("π ALL TESTS PASSED!")
print("Your AI Dataset Studio is ready to use!")
print("π Start creating amazing datasets with AI-powered source discovery!")
else:
print("\n" + "=" * 50)
print("β οΈ Some tests failed, but basic API connectivity works")
print("Check the error messages above for specific issues")
else:
print("\n" + "=" * 50)
print("β API key test failed")
print("Please fix the API key configuration before proceeding") |