MagicMeWizard commited on
Commit
4543176
Β·
verified Β·
1 Parent(s): 29eba28

Create test_api_key.py

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