Source

helpers/history.js

/**
 * Formats chat history into the OpenAI message format for LLM requests.
 * @category Helpers
 * @param {IChatHistory[]} chatHistory Chat exchanges between the user and assistant.
 * @returns {IFormattedHistory[]} Array of formatted messages ready for LLM consumption.
 */
export function formatHistory(chatHistory) {
    const formattedHistory = [];
    // Filter out hidden messages (they should not be visible in chat UI or used for LLM context)
    const visibleHistory = chatHistory.filter((item) => !item.hidden);
    // Process history in reverse order
    [...visibleHistory].reverse().forEach((item) => {
        // Add assistant message if it exists
        if (item.assistant && item.assistant.content) {
            let content;
            if (item.assistant.content_for_llm) {
                content = item.assistant.content_for_llm;
            }
            else {
                // If metadata is null, use regular content
                content = item.assistant.content;
            }
            formattedHistory.unshift({
                role: "assistant",
                content: content,
            });
        }
        // Add user message if it exists
        if (item.user && item.user.content) {
            formattedHistory.unshift({
                role: "user",
                content: item.user.content,
            });
        }
    });
    return formattedHistory;
}