Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexandrosm/b900c8dd80af1669963c5fc626ff023d to your computer and use it in GitHub Desktop.
Save alexandrosm/b900c8dd80af1669963c5fc626ff023d to your computer and use it in GitHub Desktop.
initial code
<!DOCTYPE html>
<html>
<head>
<title>Chat with GPT</title>
<style>
#chatbox {
width: 500px;
height: 500px;
border: 1px solid black;
overflow: auto;
}
#userinput {
width: 500px;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/1.9.1/showdown.min.js"></script>
</head>
<body>
<h1>Chat with GPT</h1>
<input id="apikey" type="password" placeholder="Enter your OpenAI API Key here" onchange="saveAPIKey()"/>
<div id="chatbox"></div>
<textarea id="userinput" placeholder="Type your message here"></textarea>
<button onclick="sendMessage()">Send</button>
<script>
var messages = [];
var converter = new showdown.Converter();
// Function to save API key in localStorage
function saveAPIKey() {
var apikey = document.getElementById("apikey").value;
localStorage.setItem('apikey', apikey);
}
// Load API key from localStorage if it exists
window.onload = function() {
var apikey = localStorage.getItem('apikey');
if (apikey) {
document.getElementById("apikey").value = apikey;
}
}
async function sendMessage() {
var apikey = document.getElementById("apikey").value;
var input = document.getElementById("userinput").value;
var chatbox = document.getElementById("chatbox");
if(input.includes("/source/")){
input = input.replace("/source/", "```html\n" + document.documentElement.outerHTML + "\n```");
}
messages.push({role: 'system', content: 'You are now chatting with GPT-4'});
messages.push({role: 'user', content: input});
chatbox.innerHTML += "<p><b>You:</b> " + converter.makeHtml(input) + "</p>";
var response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + apikey,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-4',
messages: messages
})
});
var data = await response.json();
if (data['choices'] && data['choices'][0] && data['choices'][0]['message']) {
var message = data['choices'][0]['message']['content'];
messages.push({role: 'assistant', content: message});
chatbox.innerHTML += "<p><b>GPT:</b> " + converter.makeHtml(message) + "</p>";
chatbox.scrollTop = chatbox.scrollHeight;
}
document.getElementById("userinput").value = "";
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment