add a place for the user to add a system prompt

<!DOCTYPE html>
<html>
<head>
  <title>G1</title>
  <style>
    body {
      font-family: sans-serif;
    }

    #chat-container {
      display: flex;
      flex-direction: column;
      width: 500px;
      margin: 0 auto;
      border: 1px solid #ccc;
      padding: 10px;
      height: 400px;
      overflow-y: auto;
    }

    .message {
      padding: 10px;
      margin-bottom: 10px;
      border-radius: 5px;
    }

    .user-message {
      background-color: #eee;
      text-align: right;
      white-space: pre-wrap; 
    }

    .bot-message {
      background-color: #f5f5f5;
      white-space: pre-wrap; 
    }

    #input-area {
      display: flex;
      margin-top: 10px;
    }

    #input-box {
      flex-grow: 1;
      padding: 5px;
      border: 1px solid #ccc;
      border-radius: 5px;
    }

    #send-button {
      padding: 5px 10px;
      background-color: #007bff;
      color: #fff;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }

    /* Styles for typing indicator */
    #typing-indicator {
      display: none; /* Initially hidden */
      margin-top: 5px;
      font-style: italic;
      color: #999;
    }
  </style>
</head>

<body>
  <div id="chat-container"></div>
  <div id="input-area">
    <textarea id="input-box" placeholder="Enter your message..." rows="3"></textarea>
    <button id="send-button">Send</button>
  </div>
  <div id="typing-indicator">Gemini is typing...</div> 

  <script>
    // List of API keys. Replace these with your actual API keys.
    const API_KEYS = [
            'AIzaSyBdc_A8VxExwO6-0LY1--r2-Ym73lMg-h4',
            'AIzaSyBydeCpaNOIPSk794CpTGnfKrxbjCgJLu4',
            'AIzaSyCQ7tBHtctxlNs61Zm2Y__7KYeDLfz5dms',
	    'AIzaSyAip_DFfKNC35MFIorEoNK4y6czP9P65-c'
    ];

    const chatContainer = document.getElementById('chat-container');
    const inputBox = document.getElementById('input-box');
    const sendButton = document.getElementById('send-button');
    const typingIndicator = document.getElementById('typing-indicator');
    let messageHistory = ""; // Store the conversation history

    sendButton.addEventListener('click', sendMessage);
    inputBox.addEventListener('keydown', (event) => {
      if (event.key === 'Enter' && !event.shiftKey) {
        event.preventDefault();
        sendMessage();
      }
    });

    /**
     * Attempts to fetch a response using the provided API key.
     * @param {string} apiKey - The API key to use for the request.
     * @param {string} prompt - The user message to send.
     * @returns {Promise<Object>} - The response data from the API.
     */
    async function fetchWithKey(apiKey, prompt) {
      const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro:generateContent?key=${apiKey}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          contents: [
            {
              role: "user",
              parts: [
                { text: prompt } // Include history in the prompt
              ]
            }
          ],
          "generationConfig": {
            "temperature": 1,
            "topK": 64,
            "topP": 0.95,
            "maxOutputTokens": 8192,
            "responseMimeType": "text/plain"
          }
        })
      });

      if (!response.ok) {
        // Extract error message from response
        const errorData = await response.json();
        throw new Error(errorData.error?.message || 'Unknown API error');
      }

      const data = await response.json();
      return data;
    }

    /**
     * Sends the user's message and handles the bot's response using multiple API keys.
     */
    async function sendMessage() {
      const messageText = inputBox.value.trim();
      if (messageText === '') return;

      // Display user's message
      const userMessage = document.createElement('div');
      userMessage.classList.add('message', 'user-message');
      userMessage.textContent = messageText;
      chatContainer.appendChild(userMessage);
      chatContainer.scrollTop = chatContainer.scrollHeight;

      // Update the message history
      messageHistory += `User: ${messageText}\n`; 

      inputBox.value = ''; // Clear the input box
      typingIndicator.style.display = 'block'; // Show typing indicator

      let botMessageText = '';
      let success = false;
      let lastError = '';

      // Iterate through API keys until one succeeds
      for (let i = 0; i < API_KEYS.length; i++) {
        const currentKey = API_KEYS[i];
        try {
          const data = await fetchWithKey(currentKey, messageHistory);

          // Extract and clean the bot's response
          botMessageText = data?.candidates[0].content.parts[0].text.replace(/\*\*(.*?)\*\*/g, '$1');

          // Update the message history with the bot's response 
          messageHistory += `Gemini: ${botMessageText}\n`; 

          // Display bot's message
          const botMessage = document.createElement('div');
          botMessage.classList.add('message', 'bot-message');
          botMessage.textContent = botMessageText;
          chatContainer.appendChild(botMessage);
          chatContainer.scrollTop = chatContainer.scrollHeight;

          success = true;
          break; // Exit the loop upon successful response
        } catch (error) {
          console.error(`Error with API key ${i + 1}:`, error.message);
          lastError = error.message;
          // Optionally, you can provide feedback to the user about switching keys
        }
      }

      if (!success) {
        // All API keys failed
        const errorMessage = document.createElement('div');
        errorMessage.classList.add('message', 'bot-message');
        errorMessage.textContent = "I'm sorry, I'm currently unable to process your request. Please try again later.";
        chatContainer.appendChild(errorMessage);
        chatContainer.scrollTop = chatContainer.scrollHeight;

        console.error('All API keys failed. Last error:', lastError);
      }

      typingIndicator.style.display = 'none'; // Hide typing indicator 
    }
  </script>
</body>
</html>