Hello,
I’m using GPT API to create a chatbot but I got this error: openai.createChatCompletion is not a function.
I’ve looked at every topic here about this but none of the solutions worked (unninstall and install again the openai lib, update the openai lib etc.)
Can I get some help please?
Codes:
server.js
const OpenAIApi = require('openai')
const Configuration = require('openai')
const express = require('express')
const app = express()
const cors = require('cors')
app.use(express.static('public'))
app.use(express.json())
app.use(cors());
const openai = new OpenAIApi(new Configuration({
apiKey: 'myKey'
}))
app.post('/chat', async (req, res)=> {
try {
const resp = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
messages: [
{ role: "user", content: req.body.question }
]
});
res.status(200).json({message: resp.data.choices[0].message.content})
} catch(e) {
res.status(400).json({message: e.message})
}
})
app.listen(5000, ()=> {
console.log("Server is active")
})
and index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="chat-area">
</div>
<div class="submit-form">
<div class="input">
<textarea name="input" id="input" cols="40" rows="3"></textarea>
<button id="btn">Submit</button>
</div>
</div>
<script>
const btn = document.getElementById("btn")
btn.addEventListener('click', getResponse)
async function getResponse() {
var inputText = document.getElementById("input").value
const parentDiv = document.getElementById("chat-area")
if(inputText === '') {
return
}
const question = document.createElement('div')
question.innerHTML = inputText
question.classList.add("box")
parentDiv.appendChild(question)
document.getElementById("input").value = ''
let res = await fetch('http://localhost:5000/chat',
{
method: 'POST',
headers: {
"Content-Type": 'application/json'
},
body: JSON.stringify({
question: inputText
})
}
)
const data = await res.json()
if(data.message) {
const answer = document.createElement('div')
answer.innerHTML = data.message
answer.classList.add("box", "answer")
parentDiv.appendChild(answer)
}
}
</script>
</body>
</html>