| 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 | |
| 9 | export const COMPACTION_MARKER = "[COMPACTED HISTORY]"; |
| 10 | |
| 11 | export interface CompactionResult { |
| 12 | compactedHistory: ChatCompletionMessageParam[]; |
| 13 | compactionIndex: number; |
| 14 | compactionContent: string; |
| 15 | } |
| 16 | |
| 17 | export interface CompactionCallbacks { |
| 18 | onStreamContent?: (content: string) => void; |
| 19 | onStreamComplete?: () => void; |
| 20 | onError?: (error: Error) => void; |
| 21 | } |
| 22 | |
| 23 | /** |
| 24 | * Compacts a chat history into a summarized form |
| 25 | * @param chatHistory The current chat history to compact |
| 26 | * @param model The model configuration |
| 27 | * @param llmApi The LLM API instance |
| 28 | * @param callbacks Optional callbacks for streaming updates |
| 29 | * @returns The compacted history with compaction index |
| 30 | */ |
| 31 | export async function compactChatHistory( |
| 32 | chatHistory: ChatCompletionMessageParam[], |
| 33 | model: ModelConfig, |
| 34 | llmApi: BaseLlmApi, |
| 35 | callbacks?: CompactionCallbacks, |
| 36 | ): Promise<CompactionResult> { |
| 37 | // Create a prompt to summarize the conversation |
| 38 | const compactionPrompt: ChatCompletionMessageParam = { |
| 39 | role: "user", |
| 40 | content: |
| 41 | "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.", |
| 42 | }; |
| 43 | |
| 44 | // Get the current history for compaction |
| 45 | const historyForCompaction = [...chatHistory, compactionPrompt]; |
| 46 | |
| 47 | // Stream the compaction response |
| 48 | const controller = new AbortController(); |
| 49 | |
| 50 | let compactionContent = ""; |
| 51 | const streamCallbacks: StreamCallbacks = { |
| 52 | onContent: (content: string) => { |
| 53 | compactionContent += content; |
| 54 | callbacks?.onStreamContent?.(content); |
| 55 | }, |
| 56 | onContentComplete: () => { |
| 57 | callbacks?.onStreamComplete?.(); |
| 58 | }, |
| 59 | }; |
| 60 | |
| 61 | try { |
| 62 | await streamChatResponse( |
| 63 | historyForCompaction, |
| 64 | model, |
| 65 | llmApi, |
| 66 | controller, |
| 67 | streamCallbacks, |
| 68 | ); |
| 69 | |
| 70 | // Create the compacted history with a special marker |
| 71 | const systemMessage = chatHistory.find((msg) => msg.role === "system"); |
| 72 | const compactedMessage: ChatCompletionMessageParam = { |
| 73 | role: "assistant", |
| 74 | content: `${COMPACTION_MARKER}\n${compactionContent}`, |
| 75 | }; |
| 76 | |
| 77 | // Set new chat history with only system message and compaction |
| 78 | const compactedHistory = systemMessage |
| 79 | ? [systemMessage, compactedMessage] |
| 80 | : [compactedMessage]; |
| 81 | const compactionIndex = compactedHistory.length - 1; |
| 82 | |
| 83 | logger.debug("Chat history compacted", { |
| 84 | originalLength: chatHistory.length, |
| 85 | compactedLength: compactedHistory.length, |
| 86 | compactionIndex, |
| 87 | }); |
| 88 | |
| 89 | return { |
| 90 | compactedHistory, |
| 91 | compactionIndex, |
| 92 | compactionContent, |
| 93 | }; |
| 94 | } catch (error) { |
| 95 | logger.error("Compaction failed", error); |
| 96 | callbacks?.onError?.(error as Error); |
| 97 | throw error; |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | /** |
| 102 | * Finds the compaction index in a chat history |
| 103 | * @param chatHistory The chat history to search |
| 104 | * @returns The index of the compaction message, or null if not found |
| 105 | */ |
| 106 | export function findCompactionIndex( |
| 107 | chatHistory: ChatCompletionMessageParam[], |
| 108 | ): number | null { |
| 109 | const compactedIndex = chatHistory.findIndex( |
| 110 | (msg) => |
| 111 | msg.role === "assistant" && |
| 112 | typeof msg.content === "string" && |
| 113 | msg.content.startsWith(COMPACTION_MARKER), |
| 114 | ); |
| 115 | return compactedIndex === -1 ? null : compactedIndex; |
| 116 | } |
| 117 | |
| 118 | /** |
| 119 | * Gets the history to send to the LLM, taking compaction into account |
| 120 | * @param fullHistory The complete chat history |
| 121 | * @param compactionIndex The index of the compaction message, if any |
| 122 | * @returns The history to send to the LLM |
| 123 | */ |
| 124 | export function getHistoryForLLM( |
| 125 | fullHistory: ChatCompletionMessageParam[], |
| 126 | compactionIndex: number | null, |
| 127 | ): ChatCompletionMessageParam[] { |
| 128 | if (compactionIndex === null || compactionIndex >= fullHistory.length) { |
| 129 | return fullHistory; |
| 130 | } |
| 131 | |
| 132 | // Include system message (if at index 0) and everything from compaction index forward |
| 133 | const systemMessage = |
| 134 | fullHistory[0]?.role === "system" ? fullHistory[0] : null; |
| 135 | const messagesFromCompaction = fullHistory.slice(compactionIndex); |
| 136 | |
| 137 | return systemMessage && compactionIndex > 0 |
| 138 | ? [systemMessage, ...messagesFromCompaction] |
| 139 | : messagesFromCompaction; |
| 140 | } |