diff --git a/formatMessages.mjs b/formatMessages.mjs new file mode 100644 index 0000000..c8038af --- /dev/null +++ b/formatMessages.mjs @@ -0,0 +1,91 @@ +export function formatMessages(messages) { + // 检查是否存在 "" 标记 + const hasAIRound0 = messages.some(message => message.content.includes('')); + + // 如果没有找到标记,直接返回原始消息数组 + if (!hasAIRound0) { + return messages; + } + + let formattedMessages = []; + let userRoundCounter = 0; + let assistantRoundCounter = 0; + let descriptionPointCounter = 0; + let isFirstUserFound = false; + let isLatestRound = false; + let lastAssistantRound = 0; + + // 查找初始回合数 + let initialRound = 0; + for (let i = 0; i < messages.length; i++) { + if (messages[i].role === 'user') { + const nextMessage = messages[i + 1]; + if (nextMessage && nextMessage.role === 'assistant') { + const match = nextMessage.content.match(//); + if (match) { + initialRound = parseInt(match[1]); + userRoundCounter = initialRound - 1; + assistantRoundCounter = initialRound; + lastAssistantRound = initialRound; + descriptionPointCounter = Math.ceil(initialRound / 2); + break; + } + } + } + } + + for (let i = 0; i < messages.length; i++) { + const message = messages[i]; + + if (message.content.includes('')) { + formattedMessages.push({ + role: message.role, + content: message.content.replace('', '--------------------<一切的开始>--------------------\n') + }); + continue; + } + + if (message.role === 'user') { + if (isFirstUserFound) { + userRoundCounter = lastAssistantRound + 1; + descriptionPointCounter++; + } else { + isFirstUserFound = true; + } + + let roundInfo = ''; + if (i + 1 < messages.length && messages[i + 1].role === 'assistant') { + const nextAssistantRound = userRoundCounter + 1; + roundInfo = `--------------------<历史第 user = 回合${userRoundCounter}|assistant = 回合${nextAssistantRound} 开始,标记描点:[${descriptionPointCounter}]>--------------------\n`; + } else { + isLatestRound = true; + roundInfo = `--------------------<最新user:(${userRoundCounter})回合|assistant:(${userRoundCounter + 1})回合开始,基于上回(${descriptionPointCounter - 1}(user${userRoundCounter - 1}|assistant${userRoundCounter}))中的历史描点内的\`assistant:\`发言末尾衔接,不得无视下方\`user:\`指引内容,根据多个记忆信息来保持思路清晰,不要出现失忆发言:>--------------------\n`; + } + formattedMessages.push({ + role: 'system', + content: roundInfo + }); + } else if (message.role === 'assistant') { + const match = message.content.match(//); + if (match) { + assistantRoundCounter = parseInt(match[1]); + lastAssistantRound = assistantRoundCounter; + } + } + + formattedMessages.push(message); + + if (message.content.includes('') && !isLatestRound) { + formattedMessages.push({ + role: 'system', + content: `--------------------<历史描点[${descriptionPointCounter}]结束>--------------------` + }); + } + + if (message.content.includes('')) { + break; + } + } + + return formattedMessages; +} \ No newline at end of file