| 1 | import { ModelConfig } from "@continuedev/config-yaml"; |
| 2 | import { BaseLlmApi } from "@continuedev/openai-adapters"; |
| 3 | import { ChatCompletionMessageParam } from "openai/resources.mjs"; |
| 4 | |
| 5 | import { streamChatResponse } from "./streamChatResponse.js"; |
| 6 | import { StreamCallbacks } from "./streamChatResponse.types.js"; |
| 7 | import { logger } from "./util/logger.js"; |
| 8 | import { |
| 9 | countChatHistoryTokens, |
| 10 | getModelContextLimit, |
| 11 | } from "./util/tokenizer.js"; |
| 12 | |
| 13 | export const COMPACTION_MARKER = "[COMPACTED HISTORY]"; |
| 14 | |
| 15 | export interface CompactionResult { |
| 16 | compactedHistory: ChatCompletionMessageParam[]; |
| 17 | compactionIndex: number; |
| 18 | compactionContent: string; |
| 19 | } |
| 20 | |
| 21 | export interface CompactionCallbacks { |
| 22 | onStreamContent?: (content: string) => void; |
| 23 | onStreamComplete?: () => void; |
| 24 | onError?: (error: Error) => void; |
| 25 | } |
| 26 | |
| 27 | /** |
| 28 | * Compacts a chat history into a summarized form |
| 29 | * @param chatHistory The current chat history to compact |
| 30 | * @param model The model configuration |
| 31 | * @param llmApi The LLM API instance |
| 32 | * @param callbacks Optional callbacks for streaming updates |
| 33 | * @returns The compacted history with compaction index |
| 34 | */ |
| 35 | export async function compactChatHistory( |
| 36 | chatHistory: ChatCompletionMessageParam[], |
| 37 | model: ModelConfig, |
| 38 | llmApi: BaseLlmApi, |
| 39 | callbacks?: CompactionCallbacks, |
| 40 | ): Promise<CompactionResult> { |
| 41 | // Create a prompt to summarize the conversation |
| 42 | const compactionPrompt: ChatCompletionMessageParam = { |
| 43 | role: "user", |
| 44 | content: |
| 45 | "Please provide a concise summary of our conversation so far, capturing the key context, decisions made, and current state. Format this as a single comprehensive message that preserves all important information needed to continue our work. You do not need to recap the system message, as this will remain.", |
| 46 | }; |
| 47 | |
| 48 | // Check if the history with compaction prompt is too long, prune if necessary |
| 49 | let historyToUse = chatHistory; |
| 50 | let historyForCompaction = [...historyToUse, compactionPrompt]; |
| 51 | |
| 52 | const contextLimit = getModelContextLimit(model); |
| 53 | const maxTokens = model.defaultCompletionOptions?.maxTokens || 0; |
| 54 | const reservedForOutput = |
| 55 | maxTokens > 0 ? maxTokens : Math.ceil(contextLimit * 0.35); |
| 56 | const availableForInput = contextLimit - reservedForOutput; |
| 57 | |
| 58 | // Check if we need to prune to fit within context |
| 59 | while ( |
| 60 | countChatHistoryTokens(historyForCompaction) > availableForInput && |
| 61 | historyToUse.length > 0 |
| 62 | ) { |
| 63 | logger.debug("Compaction history too long, pruning last message", { |
| 64 | tokenCount: countChatHistoryTokens(historyForCompaction), |
| 65 | availableForInput, |
| 66 | historyLength: historyToUse.length, |
| 67 | }); |
| 68 | const prunedHistory = pruneLastMessage(historyToUse); |
| 69 | |
| 70 | // Break if pruning didn't change the history (prevents infinite loop) |
| 71 | if (prunedHistory.length === historyToUse.length) { |
| 72 | logger.warn( |
| 73 | "Cannot prune history further while maintaining valid conversation structure", |
| 74 | ); |
| 75 | break; |
| 76 | } |
| 77 | |
| 78 | historyToUse = prunedHistory; |
| 79 | historyForCompaction = [...historyToUse, compactionPrompt]; |
| 80 | } |
| 81 | |
| 82 | // Stream the compaction response |
| 83 | const controller = new AbortController(); |
| 84 | |
| 85 | let compactionContent = ""; |
| 86 | const streamCallbacks: StreamCallbacks = { |
| 87 | onContent: (content: string) => { |
| 88 | compactionContent += content; |
| 89 | callbacks?.onStreamContent?.(content); |
| 90 | }, |
| 91 | onContentComplete: () => { |
| 92 | callbacks?.onStreamComplete?.(); |
| 93 | }, |
| 94 | }; |
| 95 | |
| 96 | try { |
| 97 | await streamChatResponse( |
| 98 | historyForCompaction, |
| 99 | model, |
| 100 | llmApi, |
| 101 | controller, |
| 102 | streamCallbacks, |
| 103 | ); |
| 104 | |
| 105 | // Create the compacted history with a special marker |
| 106 | const systemMessage = chatHistory.find((msg) => msg.role === "system"); |
| 107 | const compactedMessage: ChatCompletionMessageParam = { |
| 108 | role: "assistant", |
| 109 | content: `${COMPACTION_MARKER}\n${compactionContent}`, |
| 110 | }; |
| 111 | |
| 112 | // Set new chat history with only system message and compaction |
| 113 | const compactedHistory = systemMessage |
| 114 | ? [systemMessage, compactedMessage] |
| 115 | : [compactedMessage]; |
| 116 | const compactionIndex = compactedHistory.length - 1; |
| 117 | |
| 118 | logger.debug("Chat history compacted", { |
| 119 | originalLength: chatHistory.length, |
| 120 | compactedLength: compactedHistory.length, |
| 121 | compactionIndex, |
| 122 | }); |
| 123 | |
| 124 | return { |
| 125 | compactedHistory, |
| 126 | compactionIndex, |
| 127 | compactionContent, |
| 128 | }; |
| 129 | } catch (error) { |
| 130 | logger.error("Compaction failed", error); |
| 131 | callbacks?.onError?.(error as Error); |
| 132 | throw error; |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | /** |
| 137 | * Finds the compaction index in a chat history |
| 138 | * @param chatHistory The chat history to search |
| 139 | * @returns The index of the compaction message, or null if not found |
| 140 | */ |
| 141 | export function findCompactionIndex( |
| 142 | chatHistory: ChatCompletionMessageParam[], |
| 143 | ): number | null { |
| 144 | const compactedIndex = chatHistory.findIndex( |
| 145 | (msg) => |
| 146 | msg.role === "assistant" && |
| 147 | typeof msg.content === "string" && |
| 148 | msg.content.startsWith(COMPACTION_MARKER), |
| 149 | ); |
| 150 | return compactedIndex === -1 ? null : compactedIndex; |
| 151 | } |
| 152 | |
| 153 | /** |
| 154 | * Gets the history to send to the LLM, taking compaction into account |
| 155 | * @param fullHistory The complete chat history |
| 156 | * @param compactionIndex The index of the compaction message, if any |
| 157 | * @returns The history to send to the LLM |
| 158 | */ |
| 159 | /** |
| 160 | * Prunes chat history by removing messages from the end while ensuring |
| 161 | * the history ends with either an assistant message or a tool result message |
| 162 | * @param chatHistory The chat history to prune |
| 163 | * @returns The pruned chat history ending with assistant or tool message |
| 164 | */ |
| 165 | export function pruneLastMessage( |
| 166 | chatHistory: ChatCompletionMessageParam[], |
| 167 | ): ChatCompletionMessageParam[] { |
| 168 | if (chatHistory.length === 0) { |
| 169 | return chatHistory; |
| 170 | } |
| 171 | |
| 172 | if (chatHistory.length === 1) { |
| 173 | // Only one message - always return empty array |
| 174 | return []; |
| 175 | } |
| 176 | |
| 177 | const secondToLastIndex = chatHistory.length - 2; |
| 178 | const secondToLastMessage = chatHistory[secondToLastIndex]; |
| 179 | |
| 180 | if ( |
| 181 | secondToLastMessage.role === "assistant" && |
| 182 | secondToLastMessage.tool_calls?.length |
| 183 | ) { |
| 184 | return chatHistory.slice(0, -2); |
| 185 | } else if (secondToLastMessage.role === "user") { |
| 186 | return chatHistory.slice(0, -2); |
| 187 | } |
| 188 | |
| 189 | return chatHistory.slice(0, -1); |
| 190 | } |
| 191 | |
| 192 | export function getHistoryForLLM( |
| 193 | fullHistory: ChatCompletionMessageParam[], |
| 194 | compactionIndex: number | null, |
| 195 | ): ChatCompletionMessageParam[] { |
| 196 | if (compactionIndex === null || compactionIndex >= fullHistory.length) { |
| 197 | return fullHistory; |
| 198 | } |
| 199 | |
| 200 | // Include system message (if at index 0) and everything from compaction index forward |
| 201 | const systemMessage = |
| 202 | fullHistory[0]?.role === "system" ? fullHistory[0] : null; |
| 203 | const messagesFromCompaction = fullHistory.slice(compactionIndex); |
| 204 | |
| 205 | return systemMessage && compactionIndex > 0 |
| 206 | ? [systemMessage, ...messagesFromCompaction] |
| 207 | : messagesFromCompaction; |
| 208 | } |