-
Notifications
You must be signed in to change notification settings - Fork 0
/
single-response.js
82 lines (72 loc) · 2.57 KB
/
single-response.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
/**
* This code demonstrates how to use the OpenAI API to generate chat completions.
* The generated completions are received as a single response from the API and the
* code includes functionality to handle errors and abort requests using an AbortController.
* The API_KEY variable needs to be updated with the appropriate value from OpenAI for successful API communication.
*/
const API_URL = "https://api.openai.com/v1/chat/completions";
const API_KEY = "YOUR_API_KEY";
const promptInput = document.getElementById("promptInput");
const generateBtn = document.getElementById("generateBtn");
const stopBtn = document.getElementById("stopBtn");
const resultText = document.getElementById("resultText");
let controller = null; // Store the AbortController instance
const generate = async () => {
// Alert the user if no prompt value
if (!promptInput.value) {
alert("Please enter a prompt.");
return;
}
// Disable the generate button and enable the stop button
generateBtn.disabled = true;
stopBtn.disabled = false;
resultText.innerText = "Generating...";
// Create a new AbortController instance
controller = new AbortController();
const signal = controller.signal;
try {
// Fetch the response from the OpenAI API with the signal from AbortController
const response = await fetch(API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${API_KEY}`,
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: promptInput.value }],
max_tokens: 100,
}),
signal, // Pass the signal to the fetch request
});
const data = await response.json();
resultText.innerText = data.choices[0].message.content;
} catch (error) {
// Handle fetch request errors
if (signal.aborted) {
resultText.innerText = "Request aborted.";
} else {
console.error("Error:", error);
resultText.innerText = "Error occurred while generating.";
}
} finally {
// Enable the generate button and disable the stop button
generateBtn.disabled = false;
stopBtn.disabled = true;
controller = null; // Reset the AbortController instance
}
};
const stop = () => {
// Abort the fetch request by calling abort() on the AbortController instance
if (controller) {
controller.abort();
controller = null;
}
};
promptInput.addEventListener("keyup", (event) => {
if (event.key === "Enter") {
generate();
}
});
generateBtn.addEventListener("click", generate);
stopBtn.addEventListener("click", stop);