-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
54 lines (50 loc) · 1.59 KB
/
app.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
const SECRET_KEY = ''
const submitButton = document.querySelector('#submit')
const outPutElement = document.querySelector('#output')
const inputElement = document.querySelector('input')
const historyElement = document.querySelector('.history')
const buttonElement = document.querySelector('button')
function changeInput(value) {
const inputElement = document.querySelector('input')
inputElement.value = value
}
async function getMessage() {
console.log('clicked')
const options = {
method: 'POST',
headers: {
'Authorization': `Bearer ${SECRET_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: inputElement.value }],
max_tokens: 100
})
}
try {
const response = await fetch('https://api.openai.com/v1/chat/completions', options)
const data = await response.json()
console.log(data)
outPutElement.textContent = data.choices[0].message.content
if (data.choices[0].message.content && inputElement.value) {
const pElement = document.createElement('p')
pElement.textContent = inputElement.value
pElement.addEventListener('click', () => changeInput(pElement.textContent))
historyElement.append(pElement)
}
} catch (error) {
console.error(error)
}
inputElement.value = ''
}
submitButton.addEventListener('click', getMessage)
inputElement.addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
getMessage();
}
});
function clearInput() {
inputElement.value = ''
}
buttonElement.addEventListener('click', clearInput)