-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi_key.astro
More file actions
471 lines (425 loc) · 19.9 KB
/
api_key.astro
File metadata and controls
471 lines (425 loc) · 19.9 KB
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
---
import { getSession } from 'auth-astro/server';
import PageLayout from "@layouts/PageLayout.astro";
import Container from "@components/Container.astro";
import { SITE } from "@consts";
import { getUserProfile } from '@lib/auth';
import { SignIn } from 'auth-astro/components';
export const prerender = false;
// Detect local development
const isDev = import.meta.env.DEV;
let session;
if (isDev) {
// Dummy session for local development — bypasses Auth0
session = {
user: { name: 'Dev User', email: 'dev@localhost' },
accessToken: 'dev-dummy-token',
};
} else {
// Check if user is authenticated
session = await getSession(Astro.request);
if (!session) {
return Astro.redirect('/');
}
}
// API key will be fetched client-side to avoid exposing it in the HTML
let apiKey = "Loading...";
const apiUrl = process.env.VITE_API_URL || import.meta.env.VITE_API_URL || 'https://api.swissai.svc.cscs.ch';
---
<PageLayout title="API Key" description="Your personal API key for accessing Research Computer services">
<Container>
<div class="space-y-12 py-8">
<!-- Header Section -->
<div class="animate text-center">
<h1 class="text-4xl md:text-5xl font-bold gradient-text mb-4">
Your API Key
</h1>
<p class="text-lg text-slate-600 dark:text-slate-400 max-w-2xl mx-auto">
Access Swiss AI Platform services with your personal API key
</p>
</div>
<!-- Security Information Card -->
<div class="animate card p-8 bg-gradient-to-br from-red-50 to-red-100 dark:from-red-900/20 dark:to-red-800/20 border-red-200 dark:border-red-800">
<div class="flex items-start gap-4">
<div class="w-12 h-12 bg-gradient-to-r from-red-600 to-red-700 rounded-xl flex items-center justify-center flex-shrink-0">
<svg class="w-6 h-6 text-white" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clip-rule="evenodd"/>
</svg>
</div>
<div>
<h2 class="text-xl font-bold text-red-900 dark:text-red-100 mb-3">API Key Security</h2>
<div class="space-y-3 text-red-800 dark:text-red-200">
<p><span class="font-semibold">⚠️ Keep your API key secure</span>. Do not share it publicly or include it in client-side code.</p>
<p>If you believe your API key has been compromised, please contact support to reset it.</p>
</div>
</div>
</div>
</div>
<div class="animate card p-8 bg-gradient-to-br from-red-50 to-red-100 dark:from-red-900/20 dark:to-red-800/20 border-red-200 dark:border-red-800">
<div class="flex items-start gap-4">
<div class="w-12 h-12 bg-gradient-to-r from-red-600 to-red-700 rounded-xl flex items-center justify-center flex-shrink-0">
<svg class="w-6 h-6 text-white" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clip-rule="evenodd"/>
</svg>
</div>
<div>
<h2 class="text-xl font-bold text-red-900 dark:text-red-100 mb-3">Consent to Data Collection</h2>
<div class="space-y-3 text-red-800 dark:text-red-200">
<p>By using this service, you consent to the collection and use of your request metadata. We collect this data in order to facilitate the research in this direction.</p>
<p>If you have any questions or concerns, please contact us.</p>
</div>
</div>
</div>
</div>
<!-- API Documentation Card -->
<div class="animate card p-8">
<div class="flex items-start gap-4">
<div class="w-12 h-12 bg-gradient-to-r from-emerald-600 to-teal-600 rounded-xl flex items-center justify-center flex-shrink-0">
<svg class="w-6 h-6 text-white" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4zm2 6a1 1 0 011-1h6a1 1 0 110 2H7a1 1 0 01-1-1zm1 3a1 1 0 100 2h6a1 1 0 100-2H7z" clip-rule="evenodd"/>
</svg>
</div>
<div>
<h2 class="text-xl font-bold text-slate-900 dark:text-white mb-3">API Documentation</h2>
<p class="text-slate-600 dark:text-slate-400 mb-4">
Explore the full API reference with interactive documentation. Try out endpoints directly from your browser.
</p>
<a
href={`${apiUrl}/docs`}
target="_blank"
rel="noopener noreferrer"
class="inline-flex items-center gap-2 btn-primary px-6 py-3 rounded-xl text-sm font-semibold"
>
<svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
<path d="M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z"/>
<path d="M5 5a2 2 0 00-2 2v8a2 2 0 002 2h8a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z"/>
</svg>
View Swagger API Docs
</a>
</div>
</div>
</div>
<!-- Main API Key Card -->
<div class="animate card p-8">
<div class="mb-6">
<div class="flex items-center gap-3 mb-4">
<div class="w-12 h-12 bg-gradient-to-r from-indigo-600 to-blue-600 rounded-xl flex items-center justify-center">
<svg class="w-6 h-6 text-white" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M18 8a6 6 0 01-7.743 5.743L10 14l-1 1-1 1H6v2H2v-4l4.257-4.257A6 6 0 1118 8zm-6-4a1 1 0 100 2 2 2 0 012 2 1 1 0 102 0 4 4 0 00-4-4z" clip-rule="evenodd"/>
</svg>
</div>
<div>
<p class="text-slate-700 dark:text-slate-300 text-lg">Welcome back, <span class="font-semibold text-slate-900 dark:text-white">{session.user && session.user.name || 'User'}</span>!</p>
<div id="accountStatus" class="flex items-center gap-2">
<span class="text-slate-600 dark:text-slate-400">Account Status:</span>
<span id="statusText" class="font-semibold">Loading...</span>
</div>
</div>
</div>
<p class="text-slate-600 dark:text-slate-300">Below is your personal API key for accessing Swiss AI Platform services:</p>
</div>
<div class="relative mt-6 mb-8">
<div class="flex rounded-xl overflow-hidden shadow-lg">
<input
type="text"
id="apiKeyDisplay"
value="Loading..."
readonly
class="flex-grow px-6 py-4 bg-slate-50 dark:bg-slate-800 text-slate-900 dark:text-white focus:outline-none font-mono text-sm border-r border-slate-200 dark:border-slate-700"
/>
<button
id="copyButton"
class="px-6 py-4 btn-primary"
>
<svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
<path d="M8 3a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1z"/>
<path d="M6 3a2 2 0 00-2 2v11a2 2 0 002 2h8a2 2 0 002-2V5a2 2 0 00-2-2 3 3 0 01-3 3H9a3 3 0 01-3-3z"/>
</svg>
Copy
</button>
</div>
<div id="copyMessage" class="hidden absolute -bottom-8 left-0 text-emerald-600 dark:text-emerald-400 text-sm font-medium">
✓ Copied to clipboard!
</div>
<div id="loadingMessage" class="absolute -bottom-8 left-0 text-indigo-600 dark:text-indigo-400 text-sm">
Loading your API key...
</div>
<div id="errorMessage" class="hidden absolute -bottom-8 left-0 text-red-600 dark:text-red-400 text-sm">
Error loading API key. Please login again.
<SignIn provider="auth0" class="btn-primary ml-2">
Login
</SignIn>
</div>
</div>
</div>
<!-- Usage Instructions Card -->
<div class="animate card p-8">
<div class="space-y-6">
<h2 class="text-2xl font-bold text-slate-900 dark:text-white mb-4">How to use your API key</h2>
<!-- Header Example -->
<div class="space-y-3">
<h3 class="text-lg font-semibold text-slate-800 dark:text-slate-200">Authorization Header</h3>
<p class="text-slate-600 dark:text-slate-400">Include this API key in the header of your requests:</p>
<div class="card p-4 bg-slate-50 dark:bg-slate-800/50">
<pre class="text-sm text-slate-700 dark:text-slate-300 overflow-x-auto"><code>Authorization: Bearer <span id="headerApiKey" class="text-indigo-600 dark:text-indigo-400">your-api-key</span></code></pre>
</div>
</div>
<!-- Export Environment Variable -->
<div class="space-y-3">
<h3 class="text-lg font-semibold text-slate-800 dark:text-slate-200">Set Environment Variable</h3>
<p class="text-slate-600 dark:text-slate-400">Export your API key so you can copy and paste the examples below:</p>
<div class="card p-4 bg-slate-50 dark:bg-slate-800/50">
<pre class="text-sm text-slate-700 dark:text-slate-300 overflow-x-auto"><code>export CSCS_SERVING_API="<span id="exportApiKey" class="text-indigo-600 dark:text-indigo-400">your-api-key</span>"</code></pre>
</div>
</div>
<!-- Code Examples with Tabs -->
<div class="space-y-3">
<h3 class="text-lg font-semibold text-slate-800 dark:text-slate-200">Code Examples</h3>
<p class="text-slate-600 dark:text-slate-400">Choose your preferred method to interact with the API:</p>
<!-- Tab Buttons -->
<div class="flex border-b border-slate-200 dark:border-slate-700">
<button
id="tab-curl"
class="code-tab px-5 py-2.5 text-sm font-medium border-b-2 border-indigo-600 text-indigo-600 dark:text-indigo-400 dark:border-indigo-400"
data-tab="curl"
>
CURL
</button>
<button
id="tab-python"
class="code-tab px-5 py-2.5 text-sm font-medium border-b-2 border-transparent text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300"
data-tab="python"
>
Python (requests)
</button>
<button
id="tab-openai"
class="code-tab px-5 py-2.5 text-sm font-medium border-b-2 border-transparent text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300"
data-tab="openai"
>
Python (OpenAI)
</button>
</div>
<!-- Tab Content -->
<div id="content-curl" class="code-tab-content card p-4 bg-slate-50 dark:bg-slate-800/50">
<pre class="text-sm text-slate-700 dark:text-slate-300 overflow-x-auto"><code id="curlExample">Loading example...</code></pre>
</div>
<div id="content-python" class="code-tab-content card p-4 bg-slate-50 dark:bg-slate-800/50 hidden">
<pre class="text-sm text-slate-700 dark:text-slate-300 overflow-x-auto"><code id="pythonRequestsExample">Loading example...</code></pre>
</div>
<div id="content-openai" class="code-tab-content card p-4 bg-slate-50 dark:bg-slate-800/50 hidden">
<pre class="text-sm text-slate-700 dark:text-slate-300 overflow-x-auto"><code id="pythonApiKey">Loading example...</code></pre>
</div>
</div>
<div class="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-xl p-4 mt-6">
<p class="text-amber-800 dark:text-amber-200 text-sm">
<strong>Note:</strong> If you cannot see your API key, please sign out and sign in again to refresh your session.
</p>
</div>
</div>
</div>
</div>
</Container>
</PageLayout>
<script define:vars={{ session, apiUrl }}>
// Function to get API key from storage
function getApiKey() {
return localStorage.getItem('apiKey');
}
// Function to set API key in storage
function setApiKey(apiKey) {
localStorage.setItem('apiKey', apiKey);
}
// Function to initialize code examples with placeholders
function initializeCodeExamples() {
const curlExample = document.getElementById('curlExample');
const pythonRequestsExample = document.getElementById('pythonRequestsExample');
const pythonApiKey = document.getElementById('pythonApiKey');
// Set CURL example
if (curlExample) {
const curlCode = `curl -X POST ${apiUrl}/v1/chat/completions \\\n` +
' -H "Content-Type: application/json" \\\n' +
' -H "Authorization: Bearer $CSCS_SERVING_API" \\\n' +
' -d \'{\n' +
' "model": "swiss-ai/Apertus-8B-Instruct-2509",\n' +
' "messages": [\n' +
' {\n' +
' "role": "user",\n' +
' "content": "Who is Pablo Picasso?"\n' +
' }\n' +
' ],\n' +
' "stream": false\n' +
' }\'';
curlExample.textContent = curlCode;
}
// Set Python requests example
if (pythonRequestsExample) {
const requestsCode = 'import requests\n' +
'import os\n' +
'\n' +
'response = requests.post(\n' +
` "${apiUrl}/v1/chat/completions",\n` +
' headers={\n' +
' "Authorization": f"Bearer {os.environ.get(\'CSCS_SERVING_API\')}"\n' +
' },\n' +
' json={\n' +
' "model": "swiss-ai/Apertus-8B-Instruct-2509",\n' +
' "messages": [\n' +
' {\n' +
' "role": "user",\n' +
' "content": "Who is Pablo Picasso?"\n' +
' }\n' +
' ],\n' +
' "stream": False\n' +
' }\n' +
')\n' +
'\n' +
'result = response.json()\n' +
'print(result["choices"][0]["message"]["content"])';
pythonRequestsExample.textContent = requestsCode;
}
// Set Python OpenAI example
if (pythonApiKey) {
const pythonCode = 'import openai\n' +
'import os\n' +
'\n' +
'client = openai.Client(\n' +
' api_key=os.environ.get("CSCS_SERVING_API"),\n' +
` base_url="${apiUrl}/v1"\n` +
')\n' +
'res = client.chat.completions.create(\n' +
' model="swiss-ai/Apertus-8B-Instruct-2509",\n' +
' messages=[\n' +
' {\n' +
' "content": "Who is Pablo Picasso?",\n' +
' "role": "user",\n' +
' }\n' +
' ],\n' +
' stream=True,\n' +
')\n' +
'\n' +
'for chunk in res:\n' +
' if len(chunk.choices) > 0 and chunk.choices[0].delta.content:\n' +
' print(chunk.choices[0].delta.content, end="", flush=True)\n';
pythonApiKey.textContent = pythonCode;
}
}
// Tab switching logic
function initializeTabs() {
const tabs = document.querySelectorAll('.code-tab');
const contents = document.querySelectorAll('.code-tab-content');
tabs.forEach(tab => {
tab.addEventListener('click', () => {
const target = tab.getAttribute('data-tab');
// Update tab styles
tabs.forEach(t => {
t.classList.remove('border-indigo-600', 'text-indigo-600', 'dark:text-indigo-400', 'dark:border-indigo-400');
t.classList.add('border-transparent', 'text-slate-500', 'dark:text-slate-400');
});
tab.classList.remove('border-transparent', 'text-slate-500', 'dark:text-slate-400');
tab.classList.add('border-indigo-600', 'text-indigo-600', 'dark:text-indigo-400', 'dark:border-indigo-400');
// Show/hide content
contents.forEach(c => c.classList.add('hidden'));
document.getElementById(`content-${target}`).classList.remove('hidden');
});
});
}
// Function to fetch API key from the server using the access token
async function fetchApiKey() {
try {
const loadingMessage = document.getElementById('loadingMessage');
const errorMessage = document.getElementById('errorMessage');
const apiKeyDisplay = document.getElementById('apiKeyDisplay');
const headerApiKey = document.getElementById('headerApiKey');
const pythonApiKey = document.getElementById('pythonApiKey');
const statusText = document.getElementById('statusText');
// Get user details from session
const userEmail = session?.user?.email || '';
const userName = session?.user?.name || '';
// Try to get API key from storage first
let apiKey = getApiKey();
// If not in storage, fetch from server
if (!apiKey) {
const response = await fetch(`${apiUrl}/v1/profile`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${session.accessToken}`,
}
});
if (!response.ok) {
throw new Error(`Error: ${response.status}`);
}
const data = await response.json();
apiKey = data.api_key;
// Update account status based on budget
if (statusText) {
if (data.budget <= 0) {
statusText.textContent = 'Inactive';
statusText.classList.add('text-red-600', 'dark:text-red-400');
} else {
statusText.textContent = 'Active';
statusText.classList.add('text-green-600', 'dark:text-green-400');
}
}
// Store the API key if we got one
if (apiKey) {
setApiKey(apiKey);
}
}
if (!apiKey) {
throw new Error('No API key available');
}
// Update UI with API key
const exportApiKey = document.getElementById('exportApiKey');
if (apiKeyDisplay) apiKeyDisplay.value = apiKey;
if (headerApiKey) headerApiKey.textContent = apiKey;
if (exportApiKey) exportApiKey.textContent = apiKey;
// Hide loading message
if (loadingMessage) loadingMessage.classList.add('hidden');
} catch (error) {
console.error('Error fetching API key:', error);
const loadingMessage = document.getElementById('loadingMessage');
const errorMessage = document.getElementById('errorMessage');
if (loadingMessage) loadingMessage.classList.add('hidden');
if (errorMessage) {
errorMessage.classList.remove('hidden');
errorMessage.innerHTML = "Error loading API key. Please sign out and sign in again or refresh the page.";
const signInButton = document.createElement('div');
signInButton.innerHTML = `<button onclick="window.location.href='/auth/signin'" class="bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded transition-colors mt-2">Sign In</button>`;
errorMessage.appendChild(signInButton);
}
}
}
// Copy to clipboard functionality
document.addEventListener('DOMContentLoaded', () => {
// Initialize code examples and tabs immediately so they're visible even if auth fails
initializeCodeExamples();
initializeTabs();
// Fetch API key on page load
fetchApiKey();
const copyButton = document.getElementById('copyButton');
const apiKeyDisplay = document.getElementById('apiKeyDisplay');
const copyMessage = document.getElementById('copyMessage');
if (copyButton && apiKeyDisplay && copyMessage) {
copyButton.addEventListener('click', () => {
// Select the text
apiKeyDisplay.select();
// Copy to clipboard
navigator.clipboard.writeText(apiKeyDisplay.value)
.then(() => {
// Show success message
copyMessage.classList.remove('hidden');
// Hide message after 2 seconds
setTimeout(() => {
copyMessage.classList.add('hidden');
}, 2000);
})
.catch(err => {
console.error('Failed to copy: ', err);
alert('Failed to copy API key to clipboard');
});
});
}
});
</script>