Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div class="fixedhead">
<nav>
<div class="name"><h1>FreeGPT Online</h1></div>
  <div class="instructions"> Place your OpenAI API key in the Javascript section to use this Chatbot.<br><b>If you fork it, please give me credit</b> and leave a 'heart' or comment. Enjoy!
  </div>
</nav>
<section class="userinput">        
    <input type="text" id="user-input" placeholder="Enter message..." onkeydown="verifyEnter(event)" />
    <button onclick="sendMessage()">Send</button>
</section>
</div>

<section class="chathistory">
<div id="chat-container"></div>
</section>
<footer>
  <div>Now with context memory!
    Courtesy of <a href="http://www.vivacitydesign.net" target="_blank">Vivacity Design</a>, June, 2023
</div> 
   Try our customized <a href="http://www.vivacitydesign.net/vdgpt/index.html" target="_blank">VivacityGPT</a> with context memory, chat saving, and text-to-speech.
</footer>
<script>

</script>
              
            
!

CSS

              
                    * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    }
    
     
    .message {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  margin-bottom: 10px;
  font-family: Arial, sans-serif;
}

.user-message {
  background-color: #42adf5;
  padding: 10px;
  border: 1px solid black;
  color: white;
  font-size: 1rem;
  border-radius: 5px;
  margin-bottom: 4px;
}

.chatgpt-message {
  background-color: #4281f5;
  padding: 15px;
  color: white;
  font-size: 1rem;
  border: 1px solid black;
  border-radius: 5px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: start;
}
nav {
display: flex;
justify-content: space-between;
align-items: center;
}
.fixedhead {
position: absolute;
        top: 0;
        left: 0;
        height: 28%;
        width: 100%;
        display: flex;
        flex-direction: column;
            }   
.instructions {
  width: 30%;
  font-size: .9rem;
  text-align: justify;
  color: blue;
  border-radius: 8px;
  box-shadow: 0 4px 10px lightgrey;
  padding: 10px;
}
            
.userinput {
  background-color: white;
  padding: 10px;
  z-index: 9999;
  width: 100%;
  height: auto;      
  box-shadow: 0 4px 10px lightgrey;
}

.chathistory {
  position: absolute;
  top: 150px;
  padding: 10px;
  width: 100%;
  height: 70%;
  overflow-y: auto;
  box-shadow: 0 4px 10px lightgrey;
}

#chat-container {
height: 100%;
width: 100%;
padding: 10px;
}
.name {
  width: 50%;
  font-size: 1.8rem;
  color: blue;
   box-shadow: 0 2px 10px lightgrey;
   border-bottom: 1px solid lightgrey;
  padding: 10px;
}
.paddedheader {
margin: 10px 10px 10px 0;
font-size: 2.2rem;
  box-shadow: 0 4px 10px lightgrey;
   width: 80%;
}

input {
font-size: 1.2rem;
color: black;
border-radius: 10px;
box-shadow: 0px 4px 10px grey;
padding: 8px;
width: 80%;
margin: 0 auto;
}

button {
background-color: #42adf5;
color: white;
cursor: pointer;
padding: 8px 14px;
font-size: 1.2rem;
border-radius: 8px;
border: 1px solid black;
}
footer{
        position: absolute;
        bottom: 10px;
  padding: 10px;
        width: 100%;

        font-size: .9rem;
color: black;

}

           

@media only screen and (max-width:610px) { 
h1{
  font-size: 1.4rem;
  text-align: center;
  }
nav {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
input {
font-size: 1rem;
color: black;
border-radius: 10px;
box-shadow: 0px 4px 8px grey;
padding: 8px;
width: 60%;
margin: .5rem auto;
}

button {
background-color: #42adf5;
color: white;
cursor: pointer;
padding: 8px 14px;
font-size: 1.1rem;
border-radius: 8px;
border: 1px solid black;
}
.paddedheader {
margin: 8px;
font-size: 1.6rem;

}
  .userinput {
    margin: .5rem;
  }
img {
width: 200px;
height: auto;
}
footer{
       display:none;
  }       
  
  .instructions {

  width: 90%;

  font-size: .9rem;

  text-align: justify;

  color: blue;

  border-radius: 8px;

  box-shadow: 0 4px 10px lightgrey;

  padding: 10px;

}

}


              
            
!

JS

              
                function verifyEnter(event) {
  if (event.keyCode === 13) {
    event.preventDefault(); 

    sendMessage();
  }
}

// Start AI procedure

// 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' //put your api key here besides the word 'bearer'
            },
            body: JSON.stringify({
                "model": "gpt-3.5-16k", //update with last available model if necessary
                "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." }
]);




              
            
!
999px

Console