-
Notifications
You must be signed in to change notification settings - Fork 1
/
webserver.ts
54 lines (44 loc) · 1.37 KB
/
webserver.ts
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
import express from 'express';
import {Server} from 'socket.io';
import chat from './chat';
import * as Buffer from "buffer";
import bodyParser from "body-parser";
import cors from 'cors';
const port:number = process.env?.PORT ? +process.env.PORT : 8080;
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.post('/chat', async (req: express.Request, res: express.Response) => {
const {prompt} = req.body;
if (!prompt || typeof prompt !== 'string') {
return res.status(400).json({message: "Invalid Prompt!"});
}
const response = await chat.asyncAsk(prompt);
res.json({response});
});
const server = app.listen(port, () => console.log(`Chatbot Listening on port ${port}`));
const io = new Server(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
io.on('connection', (socket) => {
socket.on('chat', ({prompt, id}) => {
if (typeof prompt != 'string') {
return socket.emit('error', `Invalid Prompt Type: ${typeof prompt}`);
}
const chatstream = chat.ask(prompt);
chatstream.on('data', (chunk: Buffer) => {
socket.emit('response', {
chunk: chunk.toString(),
id
});
});
chatstream.on('end', () => {
socket.emit('endResponse', {
id
});
});
});
});