-
Notifications
You must be signed in to change notification settings - Fork 2
/
script.js
125 lines (101 loc) · 4.25 KB
/
script.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// Create context memory
function createMemory(messages) {
const memory = [];
for (const msg of messages) {
memory.push({ role: msg.role, content: msg.content });
}
return memory;
}
// send messages
async function sendMessage() {
const inputElement = document.getElementById('user-input');
const userInput = inputElement.value.trim();
if (userInput !== '') {
showMessage("Guest", userInput);
chatMemory = await getChatGPTResponse(userInput, chatMemory);
inputElement.value = '';
}
}
// show messages in chat div
function showMessage(sender, message) {
const chatContainer = document.getElementById('chat-container');
const chatSection = document.querySelector('.chathistory');
const typingIndicator = document.getElementById('typing-indicator');
// Remove "typing..." on answer arrival
if (typingIndicator && sender === 'GPT') {
chatContainer.removeChild(typingIndicator);
}
// create new message
const messageElement = document.createElement('div');
messageElement.innerText = `${sender}: ${message}`;
// ads a class according to the sender
if (sender === 'Guest') {
messageElement.classList.add('user-message');
} else if (sender === 'GPT') {
messageElement.classList.add('chatgpt-message');
// message copy
const copyLink = document.createElement('button');
copyLink.innerText = 'Copy';
copyLink.style.float = 'right';
copyLink.addEventListener('click', function (event) {
event.preventDefault();
const text = message;
const input = document.createElement('input');
input.value = text;
document.body.appendChild(input);
input.select();
document.execCommand('copy');
document.body.removeChild(input);
});
messageElement.appendChild(copyLink);
}
chatContainer.appendChild(messageElement);
chatSection.scrollTop = chatSection.scrollHeight;
}
// fetches the answer
async function getChatGPTResponse(userInput, chatMemory = []) {
const chatContainer = document.getElementById('chat-container');
const typingIndicator = document.createElement('p');
typingIndicator.id = 'typing-indicator';
typingIndicator.textContent = 'Typing...';
chatContainer.appendChild(typingIndicator);
try {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer yourapikeyhere'
},
body: JSON.stringify({
"model": "gpt-3.5-turbo-1106",
"messages": [
...chatMemory,
{"role": "user", "content": userInput}
]
})
});
if (!response.ok) {
throw new Error('Error in the request to\'API');
}
const data = await response.json();
if (!data.choices || !data.choices.length || !data.choices[0].message || !data.choices[0].message.content) {
throw new Error('Invalid API request');
}
const chatGPTResponse = data.choices[0].message.content.trim();
var cleanResponse = chatGPTResponse.replace(/(```html|```css|```javascript|```php|```python)(.*?)/gs, '$2');
cleanResponse = cleanResponse.replace(/```/g, "");
showMessage("GPT", cleanResponse);
// pushes the answer into context memory array
chatMemory.push({ role: 'user', content: userInput });
chatMemory.push({ role: 'assistant', content: cleanResponse });
// returns updated context memory array
return chatMemory;
} catch (error) {
console.error(error);
// .
}
}
// initialization
let chatMemory = createMemory([
{ role: 'system', content: "You are a full stack developer working for a Web Agency. You are specialized in producing code for websites and you will always provide clean and effective code. When asked for some code, you will also provide the description for different approaches to achieve the same goal. You will always end your answers with a greeting and thanking for the question received." }
]);