-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
89 lines (75 loc) · 2.31 KB
/
index.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
87
88
89
require("dotenv").config();
const express = require("express");
const { Configuration, OpenAIApi } = require("openai");
const path = require('path');
const app = express();
app.use(express.json());
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const port = process.env.PORT || 5000;
app.use(express.static(__dirname + "/views"))
// app.set('views', __dirname + 'views')
app.set('view engine', 'ejs')
app.get("/", (req, res) => {
res.render("index");
})
app.post("/ask", async (req, res) => {
const prompt = req.body.prompt;
try {
if (prompt == null) {
throw new Error("Uh oh, no prompt was provided");
}
const response = await openai.createCompletion({
model: "text-davinci-003",
prompt,
max_tokens: 1000
});
const completion = response.data.choices[0].text;
return res.status(200).json({
success: true,
message: completion,
});
} catch (error) {
console.log(error.message);
}
});
app.post("/generate", async (req, res) => {
const prompt = req.body.prompt;
const size = req.body.size;
try {
if (prompt == null) {
throw new Error("Uh oh, no prompt was provided");
}
console.log(prompt, size);
const response = await openai.createImage({
prompt,
n: 1,
size
});
image_url = response.data.data[0].url;
// console.log(image_url);
// const completion = response.data.choices[0].text;
return res.status(200).json({
success: true,
image_url: image_url
})
} catch (error) {
if (error.response) {
console.log(error.response.status);
console.log(error.response.data);
return res.status(400).json({
success: false,
message: "Ughh ohh, something went wrong",
});
} else {
console.log(error.message);
return res.status(400).json({
success: false,
message: "Ughh ohh, something went wrong",
});
}
}
});
app.listen(port, () => console.log(`Server is running on port ${port}!!`));