-
Notifications
You must be signed in to change notification settings - Fork 0
/
api-routes.js
53 lines (43 loc) · 1.55 KB
/
api-routes.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
import express from 'express';
import { getSystemMessage, getUserMessage } from './utilities.js';
import OpenAI from "openai";
export function getRouter() {
const configuration = {
organization: process.env.OPENAI_ORG_ID,
apiKey: process.env.OPENAI_API_KEY,
};
const openai = new OpenAI(configuration);
const router = express.Router();
router.post('/prompt', async (req, res) => {
const { prompt, calendar, preferences } = req.body;
if (!prompt || !calendar) {
res.status(400);
res.send('Please provide prompt and calendar in request body');
return;
}
if (!preferences) {
res.status(400);
res.send('Error retrieving preferences');
return;
}
const messages = [
{ role: 'system', content: getSystemMessage(preferences) },
{ role: 'user', content: getUserMessage(calendar, prompt) }
];
const completion = await openai.chat.completions.create({
model: process.env.OPENAI_MODEL,
messages: messages,
temperature: 1,
});
const openaiResponse = completion.choices[0].message.content;
// Extract the ICalendar from the response, by finding the <ICAL> tags
const regex = /.*?<ical>([\s\S]*?)<\/ical>.*?/i;
const matches = openaiResponse.match(regex);
const calendarResp = matches[1];
res.status(200);
res.json({
response: calendarResp,
});
});
return router;
}