background.js
const models = {
  en: [
    'facebook/blenderbot-400M-distill',
    'microsoft/DialoGPT-medium',
    'EleutherAI/gpt-neo-125M'
  ],
  de: [
    'deutsche-telekom/gbert-large',
    'bert-base-german-cased',
    'dbmdz/german-gpt2'
  ],
  es: [
    'dccuchile/bert-base-spanish-wwm-cased',
    'BSC-TeMU/roberta-base-bne',
    'bertin-project/bertin-roberta-base-spanish'
  ]
};

const apiToken = '<TRUFFLEHOG_REDACTED_HUGGINGFACE>';

async function getAIResponse(text, modelName) {
  const apiUrl = `https://api-inference.huggingface.co/models/${modelName}`;
  
  try {
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ inputs: text })
    });
    
    if (!response.ok) {
      throw new Error(`Error: ${response.status}`);
    }
    
    const data = await response.json();
    return data[0].generated_text || 'No response';
  } catch (error) {
    console.error('Error getting AI response:', error);
    return `Error: ${error.message}`;
  }
}

// Language detection function
function detectLanguage(text) {
  const languages = {
    en: ['the', 'is', 'are', 'what', 'when', 'where'],
    de: ['der', 'die', 'das', 'ist', 'sind', 'wenn'],
    es: ['el', 'la', 'los', 'es', 'son', 'cuando']
  };

  text = text.toLowerCase();
  for (const [lang, words] of Object.entries(languages)) {
    if (words.some(word => text.includes(word))) {
      return lang;
    }
  }
  return 'en'; // Default to English
}

// Handle messages from content script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'processMessage') {
    const language = detectLanguage(request.text);

    // Make parallel requests to all models for the detected language
    Promise.all(models[language].map(model =>
      getAIResponse(request.text, model)
    ))
    .then(responses => {
      sendResponse({
        responses: responses,
        language: language
      });
    })
    .catch(error => {
      sendResponse({
        error: error.message
      });
    });
    
    return true; // Required for async response
  }

  if (request.action === 'translate') {
    // Leave translation logic here if needed
    // Skipping real API call for translation due to the example nature
    sendResponse({
      translatedText: request.text // This is a placeholder
    });
  }
});

// Handle extension installation
chrome.runtime.onInstalled.addListener(() => {
  console.log('Extension installed');
});


// content.js
(() => {
  // Create floating chat container
  const createFloatingChat = () => {
    const container = document.createElement('div');
    container.innerHTML = `
      <div id="floating-chat" style="
        position: fixed;
        bottom: 20px;
        right: 20px;
        width: 400px;
        height: 600px;
        background: white;
        border-radius: 10px;
        box-shadow: 0 0 10px rgba(0,0,0,0.1);
        z-index: 10000;
        display: flex;
        flex-direction: column;
        overflow: hidden;
      ">
        <div id="chat-header" style="
          padding: 10px;
          background: #f5f5f5;
          cursor: move;
          display: flex;
          justify-content: space-between;
          align-items: center;
        ">
          <span>AI Chat Assistant</span>
          <div>
            <button id="minimize-chat" style="margin-right: 10px;">_</button>
            <button id="close-chat">×</button>
          </div>
        </div>
        <div id="chat-container" style="
          flex-grow: 1;
          overflow-y: auto;
          padding: 10px;
          background: white;
        "></div>
        <div id="input-container" style="
          padding: 10px;
          border-top: 1px solid #eee;
        ">
          <div style="display: flex; gap: 5px; margin-bottom: 5px;">
            <input type="text" id="message-input" placeholder="Type your message..." style="
              flex-grow: 1;
              padding: 5px;
              border: 1px solid #ddd;
              border-radius: 4px;
            ">
            <button id="send-button">Send</button>
          </div>
          <div style="display: flex; gap: 5px;">
            <button id="next-response">Next Response</button>
            <select id="translate-to">
              <option value="en">English</option>
              <option value="de">German</option>
              <option value="es">Spanish</option>
            </select>
            <button id="translate-button">Translate</button>
          </div>
        </div>
        <div id="model-info" style="
          padding: 5px;
          font-size: 12px;
          color: #666;
          background: #f5f5f5;
        "></div>
      </div>
    `;
    document.body.appendChild(container);
    
    // Make the chat draggable
    const chatWindow = document.getElementById('floating-chat');
    const header = document.getElementById('chat-header');
    let isDragging = false;
    let currentX;
    let currentY;
    let initialX;
    let initialY;
    let xOffset = 0;
    let yOffset = 0;

    header.addEventListener('mousedown', dragStart);
    document.addEventListener('mousemove', drag);
    document.addEventListener('mouseup', dragEnd);

    function dragStart(e) {
      initialX = e.clientX - xOffset;
      initialY = e.clientY - yOffset;
      if (e.target === header) {
        isDragging = true;
      }
    }

    function drag(e) {
      if (isDragging) {
        e.preventDefault();
        currentX = e.clientX - initialX;
        currentY = e.clientY - initialY;
        xOffset = currentX;
        yOffset = currentY;
        setTranslate(currentX, currentY, chatWindow);
      }
    }

    function setTranslate(xPos, yPos, el) {
      el.style.transform = `translate3d(${xPos}px, ${yPos}px, 0)`;
    }

    function dragEnd() {
      isDragging = false;
    }

    // Minimize/Maximize functionality
    let isMinimized = false;
    const chatContent = document.getElementById('chat-container');
    const inputContainer = document.getElementById('input-container');
    const modelInfo = document.getElementById('model-info');
    const minimizeBtn = document.getElementById('minimize-chat');

    minimizeBtn.addEventListener('click', () => {
      isMinimized = !isMinimized;
      chatContent.style.display = isMinimized ? 'none' : 'block';
      inputContainer.style.display = isMinimized ? 'none' : 'block';
      modelInfo.style.display = isMinimized ? 'none' : 'block';
      chatWindow.style.height = isMinimized ? '40px' : '600px';
      minimizeBtn.textContent = isMinimized ? '□' : '_';
    });

    // Close functionality
    document.getElementById('close-chat').addEventListener('click', () => {
      container.remove();
    });

    return container;
  };

  // Initialize chat functionality
  const initializeChat = () => {
    const container = createFloatingChat();
    
    let currentModelIndex = 0;
    let currentResponses = [];
    let currentLanguage = 'en';

    // Add message to chat
    function addMessage(text, isUser = false) {
      const chatContainer = document.getElementById('chat-container');
      const messageDiv = document.createElement('div');
      messageDiv.className = `message ${isUser ? 'user-message' : 'ai-message'}`;
      messageDiv.style.cssText = `
        margin-bottom: 10px;
        padding: 8px;
        border-radius: 5px;
        ${isUser ? 
          'background-color: #e3f2fd; margin-left: 20px;' : 
          'background-color: #f5f5f5; margin-right: 20px;'}
      `;
      messageDiv.textContent = text;
      chatContainer.appendChild(messageDiv);
      chatContainer.scrollTop = chatContainer.scrollHeight;
    }

    // Handle send message
    async function handleSend() {
      const input = document.getElementById('message-input');
      const text = input.value.trim();
      
      if (!text) return;
      
      addMessage(text, true);
      input.value = '';
      
      // Send message to background script for processing
      chrome.runtime.sendMessage({
        action: 'processMessage',
        text: text
      }, response => {
        if (response.error) {
          addMessage('Error: ' + response.error);
        } else {
          currentResponses = response.responses;
          currentLanguage = response.language;
          currentModelIndex = 0;
          addMessage(currentResponses[0]);
          updateModelInfo();
        }
      });
    }

    // Update model info display
    function updateModelInfo() {
      const modelInfo = document.getElementById('model-info');
      modelInfo.textContent = `Model ${currentModelIndex + 1}/3: Using ${currentLanguage} model`;
    }

    // Event listeners
    document.getElementById('send-button').addEventListener('click', handleSend);
    document.getElementById('message-input').addEventListener('keypress', (e) => {
      if (e.key === 'Enter') handleSend();
    });

    document.getElementById('next-response').addEventListener('click', () => {
      if (currentResponses.length === 0) return;
      
      currentModelIndex = (currentModelIndex + 1) % 3;
      const lastMessage = document.querySelector('.ai-message:last-child');
      if (lastMessage) {
        lastMessage.textContent = currentResponses[currentModelIndex];
      }
      updateModelInfo();
    });

    document.getElementById('translate-button').addEventListener('click', () => {
      const targetLang = document.getElementById('translate-to').value;
      const lastMessage = document.querySelector('.ai-message:last-child');
      
      if (!lastMessage) return;
      
      chrome.runtime.sendMessage({
        action: 'translate',
        text: lastMessage.textContent,
        targetLang: targetLang
      }, response => {
        if (response.error) {
          addMessage('Translation error: ' + response.error);
        } else {
          lastMessage.textContent = response.translatedText;
        }
      });
    });
  };

  // Initialize the chat when the content script loads
  initializeChat();
})();

popup.js
const models = {
  en: [
    'Undi95/Unholy-v2-13B',
    'CultriX/flux-nsfw-highress', //image model
    'UnfilteredAI/NSFW-6B'  //Oters mzwing/NSFW_13B_sft-GGUF, 
  ],
  de: [
    'deutsche-telekom/gbert-large',
    'bert-base-german-cased',
    'dbmdz/german-gpt2'
  ],
  es: [
    'dccuchile/bert-base-spanish-wwm-cased',
    'BSC-TeMU/roberta-base-bne',
    'bertin-project/bertin-roberta-base-spanish'
  ]
};

const apiToken = '<TRUFFLEHOG_REDACTED_HUGGINGFACE>';

async function getAIResponse(text, modelName) {
  const apiUrl = `https://api-inference.huggingface.co/models/${modelName}`;
  
  try {
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ inputs: text })
    });
    
    if (!response.ok) {
      throw new Error(`Error: ${response.status}`);
    }
    
    const data = await response.json();
    return data[0].generated_text || 'No response';
  } catch (error) {
    console.error('Error getting AI response:', error);
    return `Error: ${error.message}`;
  }
}

function detectLanguage(text) {
  const languages = {
    en: ['the', 'is', 'are', 'what', 'when', 'where'],
    de: ['der', 'die', 'das', 'ist', 'sind', 'wenn'],
    es: ['el', 'la', 'los', 'es', 'son', 'cuando']
  };

  text = text.toLowerCase();
  for (const [lang, words] of Object.entries(languages)) {
    if (words.some(word => text.includes(word))) {
      return lang;
    }
  }
  return 'en'; // Default to English
}

function addMessage(text, isUser = false) {
  const chatContainer = document.getElementById('chat-container');
  const messageDiv = document.createElement('div');
  messageDiv.className = `message ${isUser ? 'user-message' : 'ai-message'}`;
  messageDiv.textContent = text;
  chatContainer.appendChild(messageDiv);
  chatContainer.scrollTop = chatContainer.scrollHeight;
}

async function handleSend() {
  const input = document.getElementById('message-input');
  const text = input.value.trim();
  
  if (!text) return;
  
  addMessage(text, true);
  input.value = '';
  
  const detectedLang = detectLanguage(text);
  let currentResponses = [];
  document.getElementById('model-info').textContent = 'Loading responses...';

  for (const model of models[detectedLang]) {
    const response = await getAIResponse(text, model);
    currentResponses.push(response);
  }
  
  addMessage(currentResponses[0]);
  document.getElementById('model-info').textContent = 
    `Model 1/3: ${models[detectedLang][0]}`;

  currentModelIndex = 0;
  currentResponses = currentResponses;
  currentLanguage = detectedLang;
}

document.getElementById('send-button').addEventListener('click', handleSend);
document.getElementById('message-input').addEventListener('keypress', (e) => {
  if (e.key === 'Enter') handleSend();
});

document.getElementById('next-response').addEventListener('click', () => {
  if (currentResponses.length === 0) return;
  
  currentModelIndex = (currentModelIndex + 1) % 3;
  const lastMessage = document.querySelector('.ai-message:last-child');
  if (lastMessage) {
    lastMessage.textContent = currentResponses[currentModelIndex];
  }

  document.getElementById('model-info').textContent = 
    `Model ${currentModelIndex + 1}/3: ${models[currentLanguage][currentModelIndex]}`;
});

document.getElementById('translate-button').addEventListener('click', async () => {
  const targetLang = document.getElementById('translate-to').value;
  const lastMessage = document.querySelector('.ai-message:last-child');
  
  if (!lastMessage) return;
  
  lastMessage.textContent = 'Translating...';
  // Replace with actual translation logic if needed
  lastMessage.textContent = lastMessage.textContent; // Placeholder
});

This is code for my browser extension that uses hugghuggingface models to chat. When I send a message I see
1. Error getting AI response: Error: Error: 503 and it points to     console.error('Error getting AI response:', error); in popup.js
2. Error getting AI response: Error: Error: 400

I think the problem is it is using a different model than the language it supports. example, using en model to respond in de

Please modify above code so that
1. Input validation: Ensure the text input is properly formatted and doesn't contain any special characters or symbols that could cause the API to return a 400 error.
2. Expand output to also accept images as output for models that can generate images.
3. Retry the request: Implement an advanced retry mechanism in your code to handle occasional 503 errors due to temporary server overloads or maintenance.
4. Batching requests: Instead of sending individual requests for each model, you can consider sending multiple requests in a single API call using the inputs parameter to send a list of inputs. This could help reduce the number of API calls and prevent rate limiting issues.
Write the whole code. I want complete code that is production ready so that I can copy and paste and then test the extension if it actually works.