Elffuss BraidHub

kikocis/continue public

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