2024-05-02 08:48:26 +02:00
const { v4 : uuidv4 } = require ( 'uuid' ) ;
2025-09-09 13:51:26 -04:00
const { logger } = require ( '@librechat/data-schemas' ) ;
2024-05-29 09:15:05 -04:00
const { EModelEndpoint , Constants , openAISettings , CacheKeys } = require ( 'librechat-data-provider' ) ;
2024-05-02 08:48:26 +02:00
const { createImportBatchBuilder } = require ( './importBatchBuilder' ) ;
2025-07-05 12:44:19 -04:00
const { cloneMessagesWithTimestamps } = require ( './fork' ) ;
2024-05-29 09:15:05 -04:00
const getLogStores = require ( '~/cache/getLogStores' ) ;
2024-05-02 08:48:26 +02:00
/ * *
* Returns the appropriate importer function based on the provided JSON data .
*
* @ param { Object } jsonData - The JSON data to import .
* @ returns { Function } - The importer function .
* @ throws { Error } - If the import type is not supported .
* /
function getImporter ( jsonData ) {
2025-12-30 03:37:52 +01:00
// For array-based formats (ChatGPT or Claude)
2024-05-02 08:48:26 +02:00
if ( Array . isArray ( jsonData ) ) {
2025-12-30 03:37:52 +01:00
// Claude format has chat_messages array in each conversation
if ( jsonData . length > 0 && jsonData [ 0 ] ? . chat _messages ) {
logger . info ( 'Importing Claude conversation' ) ;
return importClaudeConvo ;
}
// ChatGPT format has mapping object in each conversation
2024-05-02 08:48:26 +02:00
logger . info ( 'Importing ChatGPT conversation' ) ;
return importChatGptConvo ;
}
// For ChatbotUI
if ( jsonData . version && Array . isArray ( jsonData . history ) ) {
logger . info ( 'Importing ChatbotUI conversation' ) ;
return importChatBotUiConvo ;
}
// For LibreChat
2024-05-29 09:15:05 -04:00
if ( jsonData . conversationId && ( jsonData . messagesTree || jsonData . messages ) ) {
2024-05-02 08:48:26 +02:00
logger . info ( 'Importing LibreChat conversation' ) ;
return importLibreChatConvo ;
}
throw new Error ( 'Unsupported import type' ) ;
}
/ * *
* Imports a chatbot - ui V1 conversation from a JSON file and saves it to the database .
*
* @ param { Object } jsonData - The JSON data containing the chatbot conversation .
* @ param { string } requestUserId - The ID of the user making the import request .
* @ param { Function } [ builderFactory = createImportBatchBuilder ] - The factory function to create an import batch builder .
* @ returns { Promise < void > } - A promise that resolves when the import is complete .
* @ throws { Error } - If there is an error creating the conversation from the JSON file .
* /
async function importChatBotUiConvo (
jsonData ,
requestUserId ,
builderFactory = createImportBatchBuilder ,
) {
// this have been tested with chatbot-ui V1 export https://github.com/mckaywrigley/chatbot-ui/tree/b865b0555f53957e96727bc0bbb369c9eaecd83b#legacy-code
try {
🌿 feat: Fork Messages/Conversations (#2617)
* typedef for ImportBatchBuilder
* feat: first pass, fork conversations
* feat: fork - getMessagesUpToTargetLevel
* fix: additional tests and fix getAllMessagesUpToParent
* chore: arrow function return
* refactor: fork 3 options
* chore: remove unused genbuttons
* chore: remove unused hover buttons code
* feat: fork first pass
* wip: fork remember setting
* style: user icon
* chore: move clear chats to data tab
* WIP: fork UI options
* feat: data-provider fork types/services/vars and use generic MutationOptions
* refactor: use single param for fork option, use enum, fix mongo errors, use Date.now(), add records flag for testing, use endpoint from original convo and messages, pass originalConvo to finishConversation
* feat: add fork mutation hook and consolidate type imports
* refactor: use enum
* feat: first pass, fork mutation
* chore: add enum for target level fork option
* chore: add enum for target level fork option
* show toast when checking remember selection
* feat: splitAtTarget
* feat: split at target option
* feat: navigate to new fork, show toasts, set result query data
* feat: hover info for all fork options
* refactor: add Messages settings tab
* fix(Fork): remember text info
* ci: test for single message and is target edge case
* feat: additional tests for getAllMessagesUpToParent
* ci: additional tests and cycle detection for getMessagesUpToTargetLevel
* feat: circular dependency checks for getAllMessagesUpToParent
* fix: getMessagesUpToTargetLevel circular dep. check
* ci: more tests for getMessagesForConversation
* style: hover text for checkbox fork items
* refactor: add statefulness to conversation import
2024-05-05 11:48:20 -04:00
/** @type {ImportBatchBuilder} */
2024-05-02 08:48:26 +02:00
const importBatchBuilder = builderFactory ( requestUserId ) ;
for ( const historyItem of jsonData . history ) {
importBatchBuilder . startConversation ( EModelEndpoint . openAI ) ;
for ( const message of historyItem . messages ) {
if ( message . role === 'assistant' ) {
importBatchBuilder . addGptMessage ( message . content , historyItem . model . id ) ;
} else if ( message . role === 'user' ) {
importBatchBuilder . addUserMessage ( message . content ) ;
}
}
importBatchBuilder . finishConversation ( historyItem . name , new Date ( ) ) ;
}
await importBatchBuilder . saveBatch ( ) ;
logger . info ( ` user: ${ requestUserId } | ChatbotUI conversation imported ` ) ;
} catch ( error ) {
logger . error ( ` user: ${ requestUserId } | Error creating conversation from ChatbotUI file ` , error ) ;
}
}
2025-12-30 03:37:52 +01:00
/ * *
* Extracts text and thinking content from a Claude message .
* @ param { Object } msg - Claude message object with content array and optional text field .
* @ returns { { textContent : string , thinkingContent : string } } Extracted text and thinking content .
* /
function extractClaudeContent ( msg ) {
let textContent = '' ;
let thinkingContent = '' ;
for ( const part of msg . content || [ ] ) {
if ( part . type === 'text' && part . text ) {
textContent += part . text ;
} else if ( part . type === 'thinking' && part . thinking ) {
thinkingContent += part . thinking ;
}
}
// Use the text field as fallback if content array is empty
if ( ! textContent && msg . text ) {
textContent = msg . text ;
}
return { textContent , thinkingContent } ;
}
/ * *
* Imports Claude conversations from provided JSON data .
* Claude export format : array of conversations with chat _messages array .
*
* @ param { Array } jsonData - Array of Claude conversation objects to be imported .
* @ param { string } requestUserId - The ID of the user who initiated the import process .
* @ param { Function } builderFactory - Factory function to create a new import batch builder instance .
* @ returns { Promise < void > } Promise that resolves when all conversations have been imported .
* /
async function importClaudeConvo (
jsonData ,
requestUserId ,
builderFactory = createImportBatchBuilder ,
) {
try {
const importBatchBuilder = builderFactory ( requestUserId ) ;
for ( const conv of jsonData ) {
importBatchBuilder . startConversation ( EModelEndpoint . anthropic ) ;
let lastMessageId = Constants . NO _PARENT ;
let lastTimestamp = null ;
for ( const msg of conv . chat _messages || [ ] ) {
const isCreatedByUser = msg . sender === 'human' ;
const messageId = uuidv4 ( ) ;
const { textContent , thinkingContent } = extractClaudeContent ( msg ) ;
// Skip empty messages
if ( ! textContent && ! thinkingContent ) {
continue ;
}
// Parse timestamp, fallback to conversation create_time or current time
const messageTime = msg . created _at || conv . created _at ;
let createdAt = messageTime ? new Date ( messageTime ) : new Date ( ) ;
// Ensure timestamp is after the previous message.
// Messages are sorted by createdAt and buildTree expects parents to appear before children.
// This guards against any potential ordering issues in exports.
if ( lastTimestamp && createdAt <= lastTimestamp ) {
createdAt = new Date ( lastTimestamp . getTime ( ) + 1 ) ;
}
lastTimestamp = createdAt ;
const message = {
messageId ,
parentMessageId : lastMessageId ,
text : textContent ,
sender : isCreatedByUser ? 'user' : 'Claude' ,
isCreatedByUser ,
user : requestUserId ,
endpoint : EModelEndpoint . anthropic ,
createdAt ,
} ;
// Add content array with thinking if present
if ( thinkingContent && ! isCreatedByUser ) {
message . content = [
{ type : 'think' , think : thinkingContent } ,
{ type : 'text' , text : textContent } ,
] ;
}
importBatchBuilder . saveMessage ( message ) ;
lastMessageId = messageId ;
}
const createdAt = conv . created _at ? new Date ( conv . created _at ) : new Date ( ) ;
importBatchBuilder . finishConversation ( conv . name || 'Imported Claude Chat' , createdAt ) ;
}
await importBatchBuilder . saveBatch ( ) ;
logger . info ( ` user: ${ requestUserId } | Claude conversation imported ` ) ;
} catch ( error ) {
logger . error ( ` user: ${ requestUserId } | Error creating conversation from Claude file ` , error ) ;
}
}
2024-05-02 08:48:26 +02:00
/ * *
* Imports a LibreChat conversation from JSON .
*
* @ param { Object } jsonData - The JSON data representing the conversation .
* @ param { string } requestUserId - The ID of the user making the import request .
* @ param { Function } [ builderFactory = createImportBatchBuilder ] - The factory function to create an import batch builder .
* @ returns { Promise < void > } - A promise that resolves when the import is complete .
* /
async function importLibreChatConvo (
jsonData ,
requestUserId ,
builderFactory = createImportBatchBuilder ,
) {
try {
🌿 feat: Fork Messages/Conversations (#2617)
* typedef for ImportBatchBuilder
* feat: first pass, fork conversations
* feat: fork - getMessagesUpToTargetLevel
* fix: additional tests and fix getAllMessagesUpToParent
* chore: arrow function return
* refactor: fork 3 options
* chore: remove unused genbuttons
* chore: remove unused hover buttons code
* feat: fork first pass
* wip: fork remember setting
* style: user icon
* chore: move clear chats to data tab
* WIP: fork UI options
* feat: data-provider fork types/services/vars and use generic MutationOptions
* refactor: use single param for fork option, use enum, fix mongo errors, use Date.now(), add records flag for testing, use endpoint from original convo and messages, pass originalConvo to finishConversation
* feat: add fork mutation hook and consolidate type imports
* refactor: use enum
* feat: first pass, fork mutation
* chore: add enum for target level fork option
* chore: add enum for target level fork option
* show toast when checking remember selection
* feat: splitAtTarget
* feat: split at target option
* feat: navigate to new fork, show toasts, set result query data
* feat: hover info for all fork options
* refactor: add Messages settings tab
* fix(Fork): remember text info
* ci: test for single message and is target edge case
* feat: additional tests for getAllMessagesUpToParent
* ci: additional tests and cycle detection for getMessagesUpToTargetLevel
* feat: circular dependency checks for getAllMessagesUpToParent
* fix: getMessagesUpToTargetLevel circular dep. check
* ci: more tests for getMessagesForConversation
* style: hover text for checkbox fork items
* refactor: add statefulness to conversation import
2024-05-05 11:48:20 -04:00
/** @type {ImportBatchBuilder} */
2024-05-02 08:48:26 +02:00
const importBatchBuilder = builderFactory ( requestUserId ) ;
2024-05-29 09:15:05 -04:00
const options = jsonData . options || { } ;
/* Endpoint configuration */
let endpoint = jsonData . endpoint ? ? options . endpoint ? ? EModelEndpoint . openAI ;
const cache = getLogStores ( CacheKeys . CONFIG _STORE ) ;
const endpointsConfig = await cache . get ( CacheKeys . ENDPOINT _CONFIG ) ;
const endpointConfig = endpointsConfig ? . [ endpoint ] ;
if ( ! endpointConfig && endpointsConfig ) {
endpoint = Object . keys ( endpointsConfig ) [ 0 ] ;
} else if ( ! endpointConfig ) {
endpoint = EModelEndpoint . openAI ;
}
importBatchBuilder . startConversation ( endpoint ) ;
2024-05-02 08:48:26 +02:00
let firstMessageDate = null ;
2024-05-29 09:15:05 -04:00
const messagesToImport = jsonData . messagesTree || jsonData . messages ;
if ( jsonData . recursive ) {
/ * *
2025-07-05 12:44:19 -04:00
* Flatten the recursive message tree into a flat array
2024-05-29 09:15:05 -04:00
* @ param { TMessage [ ] } messages
* @ param { string } parentMessageId
2025-07-05 12:44:19 -04:00
* @ param { TMessage [ ] } flatMessages
2024-05-29 09:15:05 -04:00
* /
2025-07-05 12:44:19 -04:00
const flattenMessages = (
messages ,
parentMessageId = Constants . NO _PARENT ,
flatMessages = [ ] ,
) => {
2024-05-29 09:15:05 -04:00
for ( const message of messages ) {
2024-12-30 13:01:47 -05:00
if ( ! message . text && ! message . content ) {
2024-05-29 09:15:05 -04:00
continue ;
}
2025-07-05 12:44:19 -04:00
const flatMessage = {
... message ,
parentMessageId : parentMessageId ,
children : undefined , // Remove children from flat structure
} ;
flatMessages . push ( flatMessage ) ;
2024-05-02 08:48:26 +02:00
2024-06-07 21:06:47 +02:00
if ( ! firstMessageDate && message . createdAt ) {
2024-05-29 09:15:05 -04:00
firstMessageDate = new Date ( message . createdAt ) ;
}
if ( message . children && message . children . length > 0 ) {
2025-07-05 12:44:19 -04:00
flattenMessages ( message . children , message . messageId , flatMessages ) ;
2024-05-29 09:15:05 -04:00
}
2024-05-02 08:48:26 +02:00
}
2025-07-05 12:44:19 -04:00
return flatMessages ;
2024-05-29 09:15:05 -04:00
} ;
2025-07-05 12:44:19 -04:00
const flatMessages = flattenMessages ( messagesToImport ) ;
cloneMessagesWithTimestamps ( flatMessages , importBatchBuilder ) ;
2024-05-29 09:15:05 -04:00
} else if ( messagesToImport ) {
2025-07-05 12:44:19 -04:00
cloneMessagesWithTimestamps ( messagesToImport , importBatchBuilder ) ;
2024-05-29 09:15:05 -04:00
for ( const message of messagesToImport ) {
2024-06-07 21:06:47 +02:00
if ( ! firstMessageDate && message . createdAt ) {
2024-05-02 08:48:26 +02:00
firstMessageDate = new Date ( message . createdAt ) ;
}
2024-05-29 09:15:05 -04:00
}
} else {
throw new Error ( 'Invalid LibreChat file format' ) ;
}
2024-05-02 08:48:26 +02:00
2024-06-07 21:06:47 +02:00
if ( firstMessageDate === 'Invalid Date' ) {
firstMessageDate = null ;
}
2024-05-29 09:15:05 -04:00
importBatchBuilder . finishConversation ( jsonData . title , firstMessageDate ? ? new Date ( ) , options ) ;
2024-05-02 08:48:26 +02:00
await importBatchBuilder . saveBatch ( ) ;
logger . debug ( ` user: ${ requestUserId } | Conversation " ${ jsonData . title } " imported ` ) ;
} catch ( error ) {
logger . error ( ` user: ${ requestUserId } | Error creating conversation from LibreChat file ` , error ) ;
}
}
/ * *
* Imports ChatGPT conversations from provided JSON data .
* Initializes the import process by creating a batch builder and processing each conversation in the data .
*
* @ param { ChatGPTConvo [ ] } jsonData - Array of conversation objects to be imported .
* @ param { string } requestUserId - The ID of the user who initiated the import process .
* @ param { Function } builderFactory - Factory function to create a new import batch builder instance , defaults to createImportBatchBuilder .
* @ returns { Promise < void > } Promise that resolves when all conversations have been imported .
* /
async function importChatGptConvo (
jsonData ,
requestUserId ,
builderFactory = createImportBatchBuilder ,
) {
try {
const importBatchBuilder = builderFactory ( requestUserId ) ;
for ( const conv of jsonData ) {
processConversation ( conv , importBatchBuilder , requestUserId ) ;
}
await importBatchBuilder . saveBatch ( ) ;
} catch ( error ) {
logger . error ( ` user: ${ requestUserId } | Error creating conversation from imported file ` , error ) ;
}
}
/ * *
* Processes a single conversation , adding messages to the batch builder based on author roles and handling text content .
* It directly manages the addition of messages for different roles and handles citations for assistant messages .
*
* @ param { ChatGPTConvo } conv - A single conversation object that contains multiple messages and other details .
🌿 feat: Fork Messages/Conversations (#2617)
* typedef for ImportBatchBuilder
* feat: first pass, fork conversations
* feat: fork - getMessagesUpToTargetLevel
* fix: additional tests and fix getAllMessagesUpToParent
* chore: arrow function return
* refactor: fork 3 options
* chore: remove unused genbuttons
* chore: remove unused hover buttons code
* feat: fork first pass
* wip: fork remember setting
* style: user icon
* chore: move clear chats to data tab
* WIP: fork UI options
* feat: data-provider fork types/services/vars and use generic MutationOptions
* refactor: use single param for fork option, use enum, fix mongo errors, use Date.now(), add records flag for testing, use endpoint from original convo and messages, pass originalConvo to finishConversation
* feat: add fork mutation hook and consolidate type imports
* refactor: use enum
* feat: first pass, fork mutation
* chore: add enum for target level fork option
* chore: add enum for target level fork option
* show toast when checking remember selection
* feat: splitAtTarget
* feat: split at target option
* feat: navigate to new fork, show toasts, set result query data
* feat: hover info for all fork options
* refactor: add Messages settings tab
* fix(Fork): remember text info
* ci: test for single message and is target edge case
* feat: additional tests for getAllMessagesUpToParent
* ci: additional tests and cycle detection for getMessagesUpToTargetLevel
* feat: circular dependency checks for getAllMessagesUpToParent
* fix: getMessagesUpToTargetLevel circular dep. check
* ci: more tests for getMessagesForConversation
* style: hover text for checkbox fork items
* refactor: add statefulness to conversation import
2024-05-05 11:48:20 -04:00
* @ param { ImportBatchBuilder } importBatchBuilder - The batch builder instance used to manage and batch conversation data .
2024-05-02 08:48:26 +02:00
* @ param { string } requestUserId - The ID of the user who initiated the import process .
* @ returns { void }
* /
function processConversation ( conv , importBatchBuilder , requestUserId ) {
importBatchBuilder . startConversation ( EModelEndpoint . openAI ) ;
// Map all message IDs to new UUIDs
const messageMap = new Map ( ) ;
for ( const [ id , mapping ] of Object . entries ( conv . mapping ) ) {
if ( mapping . message && mapping . message . content . content _type ) {
const newMessageId = uuidv4 ( ) ;
messageMap . set ( id , newMessageId ) ;
}
}
2025-09-09 13:51:26 -04:00
/ * *
2025-12-30 03:31:18 +01:00
* Helper function to find the nearest valid parent ( skips system , reasoning _recap , and thoughts messages )
2025-09-09 13:51:26 -04:00
* @ param { string } parentId - The ID of the parent message .
2025-12-30 03:31:18 +01:00
* @ returns { string } The ID of the nearest valid parent message .
2025-09-09 13:51:26 -04:00
* /
2025-12-30 03:31:18 +01:00
const findValidParent = ( parentId ) => {
2025-09-09 13:51:26 -04:00
if ( ! parentId || ! messageMap . has ( parentId ) ) {
return Constants . NO _PARENT ;
}
const parentMapping = conv . mapping [ parentId ] ;
if ( ! parentMapping ? . message ) {
return Constants . NO _PARENT ;
}
2025-12-30 03:31:18 +01:00
/* If parent is a system message, reasoning_recap, or thoughts, traverse up to find the nearest valid parent */
const contentType = parentMapping . message . content ? . content _type ;
const shouldSkip =
parentMapping . message . author ? . role === 'system' ||
contentType === 'reasoning_recap' ||
contentType === 'thoughts' ;
if ( shouldSkip ) {
return findValidParent ( parentMapping . parent ) ;
2025-09-09 13:51:26 -04:00
}
return messageMap . get ( parentId ) ;
} ;
2025-12-30 03:31:18 +01:00
/ * *
* Helper function to find thinking content from parent chain ( thoughts messages )
* @ param { string } parentId - The ID of the parent message .
* @ param { Set } visited - Set of already - visited IDs to prevent cycles .
* @ returns { Array } The thinking content array ( empty if not found ) .
* /
const findThinkingContent = ( parentId , visited = new Set ( ) ) => {
// Guard against circular references in malformed imports
if ( ! parentId || visited . has ( parentId ) ) {
return [ ] ;
}
visited . add ( parentId ) ;
const parentMapping = conv . mapping [ parentId ] ;
if ( ! parentMapping ? . message ) {
return [ ] ;
}
const contentType = parentMapping . message . content ? . content _type ;
// If this is a thoughts message, extract the thinking content
if ( contentType === 'thoughts' ) {
const thoughts = parentMapping . message . content . thoughts || [ ] ;
const thinkingText = thoughts
. map ( ( t ) => t . content || t . summary || '' )
. filter ( Boolean )
. join ( '\n\n' ) ;
if ( thinkingText ) {
return [ { type : 'think' , think : thinkingText } ] ;
}
return [ ] ;
}
// If this is reasoning_recap, look at its parent for thoughts
if ( contentType === 'reasoning_recap' ) {
return findThinkingContent ( parentMapping . parent , visited ) ;
}
return [ ] ;
} ;
2024-05-02 08:48:26 +02:00
// Create and save messages using the mapped IDs
const messages = [ ] ;
for ( const [ id , mapping ] of Object . entries ( conv . mapping ) ) {
const role = mapping . message ? . author ? . role ;
if ( ! mapping . message ) {
messageMap . delete ( id ) ;
continue ;
} else if ( role === 'system' ) {
2025-09-09 13:51:26 -04:00
// Skip system messages but keep their ID in messageMap for parent references
2024-05-02 08:48:26 +02:00
continue ;
}
2025-12-30 03:31:18 +01:00
const contentType = mapping . message . content ? . content _type ;
// Skip thoughts messages - they will be merged into the response message
if ( contentType === 'thoughts' ) {
continue ;
}
// Skip reasoning_recap messages (just summaries like "Thought for 44s")
if ( contentType === 'reasoning_recap' ) {
continue ;
}
2024-05-02 08:48:26 +02:00
const newMessageId = messageMap . get ( id ) ;
2025-12-30 03:31:18 +01:00
const parentMessageId = findValidParent ( mapping . parent ) ;
2024-05-02 08:48:26 +02:00
const messageText = formatMessageText ( mapping . message ) ;
const isCreatedByUser = role === 'user' ;
2025-09-09 13:51:26 -04:00
let sender = isCreatedByUser ? 'user' : 'assistant' ;
2024-05-02 08:48:26 +02:00
const model = mapping . message . metadata . model _slug || openAISettings . model . default ;
2025-09-09 13:51:26 -04:00
if ( ! isCreatedByUser ) {
/** Extracted model name from model slug */
const gptMatch = model . match ( /gpt-(.+)/i ) ;
if ( gptMatch ) {
sender = ` GPT- ${ gptMatch [ 1 ] } ` ;
} else {
sender = model || 'assistant' ;
}
2024-05-02 08:48:26 +02:00
}
2025-12-30 03:31:18 +01:00
// Use create_time from ChatGPT export to ensure proper message ordering
// For null timestamps, use the conversation's create_time as fallback, or current time as last resort
const messageTime = mapping . message . create _time || conv . create _time ;
const createdAt = messageTime ? new Date ( messageTime * 1000 ) : new Date ( ) ;
const message = {
2024-05-02 08:48:26 +02:00
messageId : newMessageId ,
parentMessageId ,
text : messageText ,
sender ,
isCreatedByUser ,
model ,
user : requestUserId ,
endpoint : EModelEndpoint . openAI ,
2025-12-30 03:31:18 +01:00
createdAt ,
} ;
// For assistant messages, check if there's thinking content in the parent chain
if ( ! isCreatedByUser ) {
const thinkingContent = findThinkingContent ( mapping . parent ) ;
if ( thinkingContent . length > 0 ) {
// Combine thinking content with the text response
message . content = [ ... thinkingContent , { type : 'text' , text : messageText } ] ;
}
}
messages . push ( message ) ;
2024-05-02 08:48:26 +02:00
}
2025-12-30 03:31:18 +01:00
adjustTimestampsForOrdering ( messages ) ;
2024-05-02 08:48:26 +02:00
for ( const message of messages ) {
importBatchBuilder . saveMessage ( message ) ;
}
importBatchBuilder . finishConversation ( conv . title , new Date ( conv . create _time * 1000 ) ) ;
}
/ * *
* Processes text content of messages authored by an assistant , inserting citation links as required .
2024-10-24 15:50:48 -04:00
* Uses citation start and end indices to place links at the correct positions .
2024-05-02 08:48:26 +02:00
*
* @ param { ChatGPTMessage } messageData - The message data containing metadata about citations .
* @ param { string } messageText - The original text of the message which may be altered by inserting citation links .
* @ returns { string } - The updated message text after processing for citations .
* /
function processAssistantMessage ( messageData , messageText ) {
2024-10-24 15:50:48 -04:00
if ( ! messageText ) {
return messageText ;
}
const citations = messageData . metadata ? . citations ? ? [ ] ;
const sortedCitations = [ ... citations ] . sort ( ( a , b ) => b . start _ix - a . start _ix ) ;
2024-05-02 08:48:26 +02:00
2024-10-24 15:50:48 -04:00
let result = messageText ;
for ( const citation of sortedCitations ) {
2024-05-02 08:48:26 +02:00
if (
2024-10-24 15:50:48 -04:00
! citation . metadata ? . type ||
citation . metadata . type !== 'webpage' ||
typeof citation . start _ix !== 'number' ||
typeof citation . end _ix !== 'number' ||
citation . start _ix >= citation . end _ix
2024-05-02 08:48:26 +02:00
) {
continue ;
}
const replacement = ` ([ ${ citation . metadata . title } ]( ${ citation . metadata . url } )) ` ;
2024-10-24 15:50:48 -04:00
result = result . slice ( 0 , citation . start _ix ) + replacement + result . slice ( citation . end _ix ) ;
2024-05-02 08:48:26 +02:00
}
2024-10-24 15:50:48 -04:00
return result ;
2024-05-02 08:48:26 +02:00
}
/ * *
* Formats the text content of a message based on its content type and author role .
* @ param { ChatGPTMessage } messageData - The message data .
2025-12-30 03:31:18 +01:00
* @ returns { string } - The formatted message text .
2024-05-02 08:48:26 +02:00
* /
function formatMessageText ( messageData ) {
2025-12-30 03:31:18 +01:00
const contentType = messageData . content . content _type ;
const isText = contentType === 'text' ;
2024-05-02 08:48:26 +02:00
let messageText = '' ;
if ( isText && messageData . content . parts ) {
messageText = messageData . content . parts . join ( ' ' ) ;
2025-12-30 03:31:18 +01:00
} else if ( contentType === 'code' ) {
2024-05-02 08:48:26 +02:00
messageText = ` \` \` \` ${ messageData . content . language } \n ${ messageData . content . text } \n \` \` \` ` ;
2025-12-30 03:31:18 +01:00
} else if ( contentType === 'execution_output' ) {
2024-05-02 08:48:26 +02:00
messageText = ` Execution Output: \n > ${ messageData . content . text } ` ;
} else if ( messageData . content . parts ) {
for ( const part of messageData . content . parts ) {
if ( typeof part === 'string' ) {
messageText += part + ' ' ;
} else if ( typeof part === 'object' ) {
messageText = ` \` \` \` json \n ${ JSON . stringify ( part , null , 2 ) } \n \` \` \` \n ` ;
}
}
messageText = messageText . trim ( ) ;
} else {
messageText = ` \` \` \` json \n ${ JSON . stringify ( messageData . content , null , 2 ) } \n \` \` \` ` ;
}
if ( isText && messageData . author . role !== 'user' ) {
messageText = processAssistantMessage ( messageData , messageText ) ;
}
return messageText ;
}
2025-12-30 03:31:18 +01:00
/ * *
* Adjusts message timestamps to ensure children always come after parents .
* Messages are sorted by createdAt and buildTree expects parents to appear before children .
* ChatGPT exports can have slight timestamp inversions ( e . g . , tool call results
* arriving a few ms before their parent ) . Uses multiple passes to handle cascading adjustments .
*
* @ param { Array } messages - Array of message objects with messageId , parentMessageId , and createdAt .
* /
function adjustTimestampsForOrdering ( messages ) {
const timestampMap = new Map ( ) ;
messages . forEach ( ( msg ) => timestampMap . set ( msg . messageId , msg . createdAt ) ) ;
let hasChanges = true ;
while ( hasChanges ) {
hasChanges = false ;
for ( const message of messages ) {
if ( message . parentMessageId && message . parentMessageId !== Constants . NO _PARENT ) {
const parentTimestamp = timestampMap . get ( message . parentMessageId ) ;
if ( parentTimestamp && message . createdAt <= parentTimestamp ) {
// Bump child timestamp to 1ms after parent
message . createdAt = new Date ( parentTimestamp . getTime ( ) + 1 ) ;
timestampMap . set ( message . messageId , message . createdAt ) ;
hasChanges = true ;
}
}
}
}
}
2024-10-24 15:50:48 -04:00
module . exports = { getImporter , processAssistantMessage } ;