-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
86 lines (71 loc) · 2.08 KB
/
server.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const { Configuration, OpenAIApi } = require('openai');
const multer = require('multer');
const { Readable } = require('stream');
require('dotenv').config();
const PORT = process.env.PORT || 3000;
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// print the request endpoint and req method in console
// app.use((req, _res, next) => {
// console.log(req.method, req.url);
// next();
// });
app.get('/', (_req, res) => {
res.send('Hello World!');
});
// Handle POST requests to /api/record
app.post('/api/record', upload.single('audioData'), async (req, res) => {
const buffer = req.file.buffer;
const audioStream = Readable.from(buffer);
audioStream.path = req.file.originalname;
let transcript;
try {
transcript = await openai.createTranscription(
audioStream,
'whisper-1',
'',
'json',
0,
'en'
);
} catch (e) {
console.log(e);
}
res.json({ transcript: transcript.data.text });
});
// chatcompletion endpoint
app.post('/api/complete', async (req, res) => {
const messages = [{role: 'system', content: 'You are helpful assistant.'}];
messages.push(...req.body.messages);
// Generate response using the OpenAI chatcompletion endpoint
let response;
try {
response = await openai.createChatCompletion({
model: 'gpt-3.5-turbo',
messages: messages,
});
} catch (e) {
console.log('error from completion',e);
}
res.json({ response: response.data.choices[0].message.content });
});
// return 404 if no route is matched
app.use('*',(_req, res) => {
res.status(404).send('404 Not Found');
});
// Start the server
app.listen(PORT, () => {
// console.log(`Server listening on port ${PORT}.`);
});
module.exports = app;