-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.js
72 lines (72 loc) · 2.88 KB
/
worker.js
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
const apiKey = 'YOUR API KEY';
const models = [
'gemini-pro',
'gemini-1.0-pro',
'gemini-1.0-pro-001',
'gemini-1.5-pro',
'gemini-1.5-pro-001',
'gemini-1.5-pro-002',
'gemini-1.5-pro-latest',
'gemini-1.5-flash',
'gemini-1.5-flash-latest',
'gemini-1.5-flash-001',
'gemini-1.5-flash-001-tuning',
'gemini-1.5-flash-002',
'gemini-1.5-flash-8b',
'gemini-1.5-flash-8b-001',
'gemini-1.5-flash-8b-latest',
'gemini-1.5-flash-8b-exp-0924',
'gemini-2.0-flash-exp',
'gemini-2.0-flash-thinking-exp',
'gemini-2.0-flash-thinking-exp-1219',
'learnlm-1.5-pro-experimental'
];
addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)); });
async function handleRequest(request) {
const url = new URL(request.url);
// Check if the path is '/models'
if (url.pathname === '/models') {
return new Response(JSON.stringify(models, null, 2), {
status: 200,
headers: { 'Content-Type': 'application/json' }
});
}
// Default to handling / with model and prompt parameters
const model = url.searchParams.get('model') || 'gemini-1.5-flash';
const prompt = url.searchParams.get('prompt') || '';
if (request.method === 'POST') {
const body = await request.json();
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ contents: [{ parts: [{ text: body.prompt }] }] })
});
const data = await response.json();
return new Response(JSON.stringify(data, null, 2), {
status: 200,
headers: { 'Content-Type': 'application/json' }
});
} else if (request.method === 'GET') {
if (prompt === '') {
// If no prompt is provided, return a meaningful response
return new Response(JSON.stringify({ error: 'use: /?model={model}&prompt={prompt} view list model: /models ' }, null, 2), {
status: 400,
headers: { 'Content-Type': 'application/json' }
});
}
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ contents: [{ parts: [{ text: prompt }] }] })
});
const data = await response.json();
return new Response(JSON.stringify(data, null, 2), {
status: 200,
headers: { 'Content-Type': 'application/json' }
});
}
return new Response(JSON.stringify({ error: "Invalid request method" }, null, 2), {
status: 405,
headers: { 'Content-Type': 'application/json' }
});
}