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

              
                <!DOCTYPE html>
<html lang="he" dir="rtl">
    <h1>GPT-3.5-turbo Chat</h1>
    <p>ברוכים הבאים לצ'אט עם המון חוכמה! שאלו שאלות ותקבלו תשובות מ-GPT.</p>
    <label for="user-input">על מה תרצה לדבר?</label>
    <input type="text" id="user-input">
    <button id="ask-button">שלח</button>
    <div id="response-container"></div>
    <script src="https://www.shider.co.il/wp-content/themes/skeleton/page-templates/script.js"></script>
      <div id="loading-container">
        <iframe src="https://giphy.com/embed/3oEjI6SIIHBdRxXI40" width="200" height="200" frameBorder="0" class="giphy-embed" allowFullScreen></iframe>
    </div>
              
            
!

CSS

              
                        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            text-align: center;
          text-size: 20px;

        }
        #response-container {
        	width: 70%;
        	margin: 0 auto; /* Center the response container */
        	text-align: left; /* Align text to the left */
            font-size: 1.2em; /* Adjust the font size for mobile */
 	   }
        h1 {
            color: #333;
        }

        label {
            margin-right: 10px;
        }

        #user-input {
            padding: 5px;
            margin-right: 10px;
        }

        #ask-button {
            padding: 5px 10px;
            cursor: pointer;
        }

        #response-container {
            margin-top: 20px;
            padding: 10px;
            border: 1px solid #ccc;
            background-color: #f9f9f9;
        }
        #loading-container {
            display: none;
            text-align: center;
        }
            @media only screen and (max-width: 600px) {
        #response-container {
            width: 90%; /* Adjust width for smaller screens */
            font-size: 1.5em; /* Increase font size for smaller screens */
        }
    }
              
            
!

JS

              
                // Replace 'YOUR_API_KEY' with your actual OpenAI API key
const apiKey = 'YOUR_API_KEY';

// Function to show a loading indicator
function showLoading() {
  // Display the loading container
  document.getElementById("loading-container").style.display = "block";

  // You can optionally hide other elements or modify the UI based on your design
  document.getElementById("response-container").style.display = "none";
}

// Function to hide the loading indicator
function hideLoading() {
  // Hide the loading container
  document.getElementById("loading-container").style.display = "none";

  // You can optionally show other elements or modify the UI based on your design
  document.getElementById("response-container").style.display = "block";
}

async function sendMessage(message) {
    try {
        const response = await fetch('https://api.openai.com/v1/chat/completions', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`,
            },
            body: JSON.stringify({
                model: 'gpt-3.5-turbo',
                messages: [
                    { role: 'system', content: 'You are a helpful assistant.' },
                    { role: 'user', content: message },
                ],
            }),
        });

        console.log('API Response:', response.status);

        if (!response.ok) {
            throw new Error('Bad response from OpenAI API');
        }

        const result = await response.json();

        if (result.choices && result.choices.length > 0) {
            const fullResponse = result.choices.map(choice => choice.message.content).join(' ');

            document.getElementById('response-container').innerText = fullResponse;

            return fullResponse;
        } else {
            throw new Error('Unexpected response format from OpenAI.');
        }
    } catch (error) {
        console.error('Error sending message to GPT:', error);
        throw error;
    }
}

async function sendMessageWithRetries(message, maxRetries = 3) {
    let retries = 0;
    while (retries < maxRetries) {
        try {
            const gptResponse = await sendMessage(message);
            return gptResponse;
        } catch (error) {
            if (error.status === 429 && error.code === 'insufficient_quota') {
                console.warn('Insufficient quota. Waiting for quota reset...');
                const delay = Math.pow(2, retries) * 1000;
                await new Promise(resolve => setTimeout(resolve, delay));
                retries++;
            } else {
                throw error;
            }
        }
    }
    throw new Error('Exceeded the maximum number of retries.');
}

document.getElementById('ask-button').addEventListener('click', async function () {
    const userInput = document.getElementById('user-input').value;
    if (userInput.trim() !== '') {
        try {
          	// Show loading indicator while waiting for the response
        	showLoading();
            const gptResponse = await sendMessageWithRetries(userInput);
            console.log('GPT says:', gptResponse);
            // Hide loading indicator and display the GPT response
        	hideLoading();
        } catch (error) {
            console.error('Error handling user input:', error);
        }
    } else {
        alert('Please enter a question.');
    }
});
              
            
!
999px

Console