-
Notifications
You must be signed in to change notification settings - Fork 0
/
openaiUtil.js
80 lines (70 loc) · 2.44 KB
/
openaiUtil.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
require("dotenv").config()
const { Configuration, OpenAIApi } = require("openai")
const axios = require("axios")
const configuration = new Configuration({
organization: process.env.OPENAI_ORGANIZATION,
apiKey: process.env.OPENAI_API_KEY,
})
const openai = new OpenAIApi(configuration)
// async function sendToOpenAI(prompt) {
// try {
// const response = await openai.createCompletion({
// model: "text-davinci-003",
// prompt: prompt,
// max_tokens: 1000, // Max number of tokens to generate
// temperature: 0, // Make the output deterministic
// })
// return response.data.choices[0].text.trim()
// } catch (error) {
// console.error(`OPENAI Error: ${error.message}`)
// }
// }
async function sendToOpenAI(prompt) {
const messages = []
messages.push({ role: "user", content: prompt })
try {
const response = await openai.createChatCompletion({
model: "gpt-4",
messages: messages,
temperature: 0,
})
console.log(response.data.choices[0].message.content)
return response.data.choices[0].message.content
} catch (error) {
if (error.response) {
console.log(error.response.status)
console.log(error.response.data)
} else {
console.error(`OPENAI Error: ${error.message}`)
}
}
}
// async function sendToOpenAI(prompt) {
// const headers = {
// "Content-Type": "application/json",
// Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
// }
// const data = {
// model: "gpt-3.5-turbo",
// messages: [{ role: "user", content: prompt }],
// temperature: 0,
// }
// try {
// const response = await axios.post(
// "https://api.openai.com/v1/chat/completions",
// data,
// { headers }
// )
// return response.data.choices[0].message.content
// } catch (error) {
// if (error.response && error.response.status === 429) {
// // Retry after a random delay between 5 and 20 seconds
// const delay = Math.floor(Math.random() * 16) + 5
// await new Promise((resolve) => setTimeout(resolve, delay * 1000))
// return sendToOpenAI(prompt) // Retry the request
// } else {
// console.error(error)
// }
// }
// }
module.exports = { sendToOpenAI }