-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
97 lines (89 loc) · 2.57 KB
/
index.js
File metadata and controls
97 lines (89 loc) · 2.57 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
const https = require('https');
function httpsPost({ hostname, path, headers, body }) {
return new Promise((resolve, reject) => {
console.log('Preparing HTTPS POST request...');
const options = {
hostname,
path,
method: 'POST',
headers,
};
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => data += chunk);
res.on('end', () => {
console.log('HTTPS response received. Processing...');
if (res.statusCode >= 200 && res.statusCode < 300) {
console.log('Successful response:', data);
resolve(JSON.parse(data));
} else {
console.log(`Error with response. Status code: ${res.statusCode}`, data);
reject(new Error(`HTTP status code ${res.statusCode}`));
}
});
});
req.on('error', (error) => {
console.log('Request error:', error);
reject(error);
});
req.write(body);
req.end();
});
}
exports.handler = async (event) => {
console.log('Event:', event);
const api_key = process.env.GEMINI_API_KEY;
if (!api_key) {
console.log('Missing GEMINI_API_KEY in environment variables');
return {
headers: {
'Access-Control-Allow-Origin': '*'
},
statusCode: 500,
body: 'Missing GEMINI_API_KEY in environment variables' };
}
const input_text = event["data"];
if (!input_text) {
console.log('Missing text to explain');
return { headers: {
'Access-Control-Allow-Origin': '*'
},
statusCode: 400,
body: 'Missing text to explain' };
}
const gemini_payload = JSON.stringify({
contents: [{
parts: [{
text: `Explain this text: ${input_text}`
}]
}]
});
try {
console.log('Sending request to Gemini API...');
const response = await httpsPost({
hostname: 'generativelanguage.googleapis.com',
path: `/v1beta/models/gemini-pro:generateContent?key=${api_key}`,
headers: {
'Content-Type': 'application/json'
},
body: gemini_payload,
});
console.log('Response from Gemini API:', response.candidates[0]);
return {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*'
},
body: response.candidates[0].content.parts[0].text
};
} catch (error) {
console.log('Error occurred:', error.message);
return {
headers: {
'Access-Control-Allow-Origin': '*'
},
statusCode: 500,
body: JSON.stringify({ message: 'An error occurred', error: error.message })
};
}
};