Home -> How to Fix Lag in Google AI Studio

How to Fix Lag and Slowdowns in Google AI Studio

This is a workaround for when chat histories in Code and Chat mode become too long, causing extremely sluggish typing responses or delayed output displays.
You can open the Developer Tools by pressing Ctrl+Shift+I (or right-clicking and selecting "Inspect"), navigate to the Console tab, paste the code below, and press Enter. This should help reduce the lag.
Once executed, this script will keep automatically removing older chat turns from the screen (excluding the 2 most recent ones) until you refresh the page.
* Note: This script only removes elements from the screen (DOM) to free up memory; your actual chat history is safe and remains intact. Refreshing the page will restore all temporarily removed elements.
* Note: This script may stop working if future updates to Google AI Studio change the page structure.


(function() {
    console.log("Starting automatic chat cleanup...");

    // Configuration to keep the most recent chat turns and remove older ones
    const keepChatCount = 2; // Number of recent chat interactions to keep
    const groupCount = 3; // Each turn consists of 3 elements: user query, thought process, and response
    function cleanOldTurns() {
        const turns = document.querySelectorAll('ms-chat-turn');
        const keepCount = keepChatCount * groupCount; // Calculate the number of DOM elements to keep

        // Remove the excess elements
        if (turns.length > keepCount) {
            let deletedCount = 0;
            for (let i = 0; i < turns.length - keepCount; i++) {
                turns[i].remove(); // Remove element
                deletedCount++;
            }
            console.log(`Removed ${deletedCount} old chat elements from the DOM.`);
        }
    }

    // Monitor screen changes (addition of new messages) using MutationObserver
    const observer = new MutationObserver((mutations) => {
        // Run cleanup upon detecting page changes
        cleanOldTurns();
    });

    // Locate the chat container and start observing
    const chatContainer = document.querySelector('ms-virtual-scroll-container') || document.body;
    observer.observe(chatContainer, { childList: true, subtree: true });

    // Run the initial cleanup once
    cleanOldTurns();
})();