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