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")