-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.js
83 lines (69 loc) · 2.35 KB
/
main.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
// Chave de API do OpenAI
const apiKey = 'sua_api_key'
function sendMessage(){
var message = document.getElementById('message-input')
if(!message.value)
{
message.style.border = '1px solid red'
return;
}
message.style.border = 'none'
var status = document.getElementById('status')
var btnSubmit = document.getElementById('btn-submit')
status.style.display = 'block'
status.innerHTML = 'Carregando...'
btnSubmit.disabled = true
btnSubmit.style.cursor = 'not-allowed'
message.disabled = true
fetch("https://api.openai.com/v1/completions",{
method: 'POST',
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: "text-davinci-003",
prompt: message.value,
max_tokens: 2048, // tamanho da resposta
temperature: 0.5 // criatividade na resposta
})
})
.then((response) => response.json())
.then((response) => {
let r = response.choices[0]['text']
status.style.display = 'none'
showHistory(message.value,r)
})
.catch((e) => {
console.log(`Error -> ${e}`)
status.innerHTML = 'Erro, tente novamente mais tarde...'
})
.finally(() => {
btnSubmit.disabled = false
btnSubmit.style.cursor = 'pointer'
message.disabled = false
message.value = ''
})
}
function showHistory(message,response){
var historyBox = document.getElementById('history')
// My message
var boxMyMessage = document.createElement('div')
boxMyMessage.className = 'box-my-message'
var myMessage = document.createElement('p')
myMessage.className = 'my-message'
myMessage.innerHTML = message
boxMyMessage.appendChild(myMessage)
historyBox.appendChild(boxMyMessage)
// Response message
var boxResponseMessage = document.createElement('div')
boxResponseMessage.className = 'box-response-message'
var chatResponse = document.createElement('p')
chatResponse.className = 'response-message'
chatResponse.innerHTML = response
boxResponseMessage.appendChild(chatResponse)
historyBox.appendChild(boxResponseMessage)
// Levar scroll para o final
historyBox.scrollTop = historyBox.scrollHeight
}