-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
68 lines (58 loc) · 1.79 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const API_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(
`Button clicked: Fetching message from API with input: ${inPutElement.value}`
);
const options = {
method: "POST",
headers: {
Authorization: `Bearer ${API_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(`API response received: `, 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);
console.log(`Added to history: ${inPutElement.value}`);
}
} catch (error) {
console.error(`Error fetching message from API:`, error);
}
}
submitButton.addEventListener("click", getMessage);
function clearInput() {
console.log(`Input cleared.`);
inPutElement.value = "";
}
buttonElement.addEventListener("click", clearInput);