const messages = [];
const TOKEN = 'ТВОЙ ТОКЕН';
const randomInt = (max) => Math.random() * max;
async function getAnswer(prompt) {
if (!prompt)
return alert('Ошибка, введите текст!');
messages.push({ role: 'user', content: prompt });
const response = await fetch('https://api.openai.com/v1/chat/completions', {
headers: {
Authorization: `Bearer ${TOKEN}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-3.5-turbo',
messages: messages,
temperature: 1,
max_tokens: 256,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0
}),
method: 'POST'
});
const text = await response.text();
const data = JSON.parse(text);
if (response.status != 200)
return alert(data?.error?.message ?? `Unknown error, code ${response.status}\n${text}`);
return data?.choices?.[randomInt(0, data.choices.length - 1)].message.content ?? text;
}
addEventListener('DOMContentLoaded', () => {
const input = document.getElementById('prompt');
const submit = document.getElementById('submit');
const clear = document.getElementById('clear');
const chat = document.getElementById('chat');
submit.addEventListener('click', async () => {
chat.innerHTML += `<p>USER: ${input.value}</p>`;
const result = await getAnswer(input.value);
input.value = '';
chat.innerHTML += `<p>GPT: ${result}</p>`;
});
clear.addEventListener('click', () => {
messages = [];
chat.innerHTML = '';
});
});