pip install openai
function askChatGPT(prompt) {
const apiUrl = "https://api.openai.com/v1/engines/text-davinci-002/completions";
const apiKey = "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";
const data = {
prompt: prompt,
max_tokens: 1024,
temperature: 0.7,
n: 1
};
return fetch(apiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => data.choices[0].text)
.catch(error => console.log(error));
}
const input = document.getElementById("input");
const chatbox = document.getElementById("chatbox");
function handleSubmit(event) {
event.preventDefault();
const prompt = input.value.trim();
if (prompt !== "") {
chatbox.innerHTML += `
${prompt}
`;
askChatGPT(prompt).then(response => {
chatbox.innerHTML += `
${response}
`;
chatbox.scrollTop = chatbox.scrollHeight;
});
input.value = "";
}
}
const form = document.getElementById("form");
form.addEventListener("submit", handleSubmit);
No comments:
Post a Comment