AI Engine Adding Context with Javascript

Here’s a tip to easily add dynamic content to your AI Engine context from the client-side with a small amount of code:

const messagePrefix = "Info for future reference, do not mention it unless it is relevant: ";
const messageContinue = "Moving on..";

// Edit this, or set it dynamically on form input change etc.
window.chatbotShouldKnow = "I like oranges";

document.addEventListener("DOMContentLoaded", function() {
    setTimeout(function() {
        // Override the global fetch function
        const originalFetch = window.fetch;
        window.fetch = async (url, options = {}) => {
            const isChatEndpoint = url.endsWith("/wp-json/mwai-ui/v1/chats/submit");

            if (!isChatEndpoint || !window.chatbotShouldKnow || !options.body) {
                return originalFetch(url, options);
            }

            let chatData = JSON.parse(options.body);

            const prefix = messagePrefix + window.chatbotShouldKnow + "\n" + messageContinue + "\n---\n";

            if (chatData.messages.length == 1) {
                chatData.newMessage = prefix + chatData.newMessage;
            } else {
                chatData.messages[1].content = prefix + chatData.messages[1].content;
            }

            options.body = JSON.stringify(chatData);

            return await originalFetch(url, options);
        }
    }, 1000);
});

Because there’s no access to the system prompt from Javascript, this will add the context to the user’s first message.

“Hello!” becomes “Info for future reference, do not mention it unless it is relevant: [your context here] Moving on.. Hello!”

Try it out!


Let’s enhance your business! I can help you develop custom AI engine extensions or broader AI strategies.

Contact me.

Leave a Reply

Your email address will not be published. Required fields are marked *