Elffuss BraidHub

kikocis/continue public

c657d7bd6e88 · 16.4 KiBRawPermalink
1import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
2
3import {
4 ChatMessage,
5 CompiledMessagesResult,
6 MessageContent,
7 MessagePart,
8 PruningStatus,
9 Tool,
10} from "../index.js";
11import { autodetectTemplateType } from "./autodetect.js";
12import {
13 addSpaceToAnyEmptyMessages,
14 chatMessageIsEmpty,
15 isUserOrToolMsg,
16 messageHasToolCallId,
17} from "./messages.js";
18
19import { renderChatMessage } from "../util/messageContent.js";
20import { AsyncEncoder, LlamaAsyncEncoder } from "./asyncEncoder.js";
21import llamaTokenizer from "./llamaTokenizer.js";
22interface Encoding {
23 encode: Tiktoken["encode"];
24 decode: Tiktoken["decode"];
25}
26
27class LlamaEncoding implements Encoding {
28 encode(text: string): number[] {
29 return llamaTokenizer.encode(text);
30 }
31
32 decode(tokens: number[]): string {
33 return llamaTokenizer.decode(tokens);
34 }
35}
36
37class NonWorkerAsyncEncoder implements AsyncEncoder {
38 constructor(private readonly encoding: Encoding) {}
39
40 async close(): Promise<void> {}
41
42 async encode(text: string): Promise<number[]> {
43 return this.encoding.encode(text);
44 }
45
46 async decode(tokens: number[]): Promise<string> {
47 return this.encoding.decode(tokens);
48 }
49}
50
51let gptEncoding: Encoding | null = null;
52const llamaEncoding = new LlamaEncoding();
53const llamaAsyncEncoder = new LlamaAsyncEncoder();
54
55function asyncEncoderForModel(modelName: string): AsyncEncoder {
56 // Temporary due to issues packaging the worker files
57 if (process.env.IS_BINARY) {
58 const encoding = encodingForModel(modelName);
59 return new NonWorkerAsyncEncoder(encoding);
60 }
61
62 const modelType = autodetectTemplateType(modelName);
63 if (!modelType || modelType === "none") {
64 // Right now there is a problem packaging js-tiktoken in workers. Until then falling back
65 // Cannot find package 'js-tiktoken' imported from /Users/nate/gh/continuedev/continue/extensions/vscode/out/tiktokenWorkerPool.mjs
66 // return gptAsyncEncoder;
67 return llamaAsyncEncoder;
68 }
69 return llamaAsyncEncoder;
70}
71
72function encodingForModel(modelName: string): Encoding {
73 const modelType = autodetectTemplateType(modelName);
74
75 if (!modelType || modelType === "none") {
76 if (!gptEncoding) {
77 gptEncoding = _encodingForModel("gpt-4");
78 }
79
80 return gptEncoding;
81 }
82
83 return llamaEncoding;
84}
85
86function countImageTokens(content: MessagePart): number {
87 if (content.type === "imageUrl") {
88 return 85;
89 }
90 throw new Error("Non-image content type");
91}
92
93async function countTokensAsync(
94 content: MessageContent,
95 // defaults to llama2 because the tokenizer tends to produce more tokens
96 modelName = "llama2",
97): Promise<number> {
98 const encoding = asyncEncoderForModel(modelName);
99 if (Array.isArray(content)) {
100 const promises = content.map(async (part) => {
101 if (part.type === "imageUrl") {
102 return countImageTokens(part);
103 }
104 return (await encoding.encode(part.text ?? "")).length;
105 });
106 return (await Promise.all(promises)).reduce((sum, val) => sum + val, 0);
107 }
108 return (await encoding.encode(content ?? "")).length;
109}
110
111function countTokens(
112 content: MessageContent,
113 // defaults to llama2 because the tokenizer tends to produce more tokens
114 modelName = "llama2",
115): number {
116 const encoding = encodingForModel(modelName);
117 if (Array.isArray(content)) {
118 return content.reduce((acc, part) => {
119 return (
120 acc +
121 (part.type === "text"
122 ? encoding.encode(part.text ?? "", "all", []).length
123 : countImageTokens(part))
124 );
125 }, 0);
126 } else {
127 return encoding.encode(content ?? "", "all", []).length;
128 }
129}
130
131// https://community.openai.com/t/how-to-calculate-the-tokens-when-using-function-call/266573/10
132function countToolsTokens(tools: Tool[], modelName: string): number {
133 const count = (value: string) =>
134 encodingForModel(modelName).encode(value).length;
135
136 let numTokens = 12;
137
138 for (const tool of tools) {
139 let functionTokens = count(tool.function.name);
140 if (tool.function.description) {
141 functionTokens += count(tool.function.description);
142 }
143 const props = tool.function.parameters?.properties;
144 if (props) {
145 for (const key in props) {
146 functionTokens += count(key);
147 const fields = props[key];
148 if (fields) {
149 const fieldType = fields["type"];
150 const fieldDesc = fields["description"];
151 const fieldEnum = fields["enum"];
152 if (fieldType && typeof fieldType === "string") {
153 functionTokens += 2;
154 functionTokens += count(fieldType);
155 }
156 if (fieldDesc && typeof fieldDesc === "string") {
157 functionTokens += 2;
158 functionTokens += count(fieldDesc);
159 }
160 if (fieldEnum && Array.isArray(fieldEnum)) {
161 functionTokens -= 3;
162 for (const e of fieldEnum) {
163 functionTokens += 3;
164 functionTokens += typeof e === "string" ? count(e) : 5;
165 }
166 }
167 }
168 }
169 }
170 numTokens += functionTokens;
171 }
172
173 return numTokens + 12;
174}
175
176function countChatMessageTokens(
177 modelName: string,
178 chatMessage: ChatMessage,
179): number {
180 // Doing simpler, safer version of what is here:
181 // https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb
182 // every message follows <|im_start|>{role/name}\n{content}<|end|>\n
183 const BASE_TOKENS = 4;
184 const TOOL_CALL_EXTRA_TOKENS = 10;
185 const TOOL_OUTPUT_EXTRA_TOKENS = 10;
186 let tokens = BASE_TOKENS;
187
188 if (chatMessage.content) {
189 tokens += countTokens(chatMessage.content, modelName);
190 }
191
192 if ("toolCalls" in chatMessage && chatMessage.toolCalls) {
193 for (const call of chatMessage.toolCalls) {
194 tokens += TOOL_CALL_EXTRA_TOKENS;
195 tokens += countTokens(JSON.stringify(call), modelName); // TODO hone this
196 }
197 }
198
199 if (chatMessage.role === "thinking") {
200 if (chatMessage.redactedThinking) {
201 tokens += countTokens(chatMessage.redactedThinking, modelName);
202 }
203 if (chatMessage.signature) {
204 tokens += countTokens(chatMessage.signature, modelName);
205 }
206 }
207
208 if (chatMessage.role === "tool") {
209 tokens += TOOL_OUTPUT_EXTRA_TOKENS; // safety
210 if (chatMessage.toolCallId) {
211 tokens += countTokens(chatMessage.toolCallId, modelName);
212 }
213 }
214 return tokens;
215}
216
217/**
218 * Extracts and validates the tool call sequence from the end of a message array.
219 * Tool sequences consist of: [assistant_with_tool_calls, tool_response_1, tool_response_2, ...]
220 * or just a single user message.
221 *
222 * @param messages - Array of chat messages (will be modified by popping messages)
223 * @returns Array of messages that form the tool sequence
224 */
225function extractToolSequence(messages: ChatMessage[]): ChatMessage[] {
226 const lastMsg = messages.pop();
227 if (!lastMsg || !isUserOrToolMsg(lastMsg)) {
228 throw new Error("Error parsing chat history: no user/tool message found");
229 }
230
231 const toolSequence: ChatMessage[] = [];
232
233 if (lastMsg.role === "tool") {
234 toolSequence.push(lastMsg);
235
236 // Collect all consecutive tool messages from the end
237 while (
238 messages.length > 0 &&
239 messages[messages.length - 1].role === "tool"
240 ) {
241 toolSequence.unshift(messages.pop()!);
242 }
243
244 // Get the assistant message with tool calls
245 const assistantMsg = messages.pop();
246 if (assistantMsg) {
247 toolSequence.unshift(assistantMsg);
248
249 // Validate that all tool messages have matching tool call IDs
250 for (const toolMsg of toolSequence.slice(1)) {
251 // Skip assistant message
252 if (
253 toolMsg.role === "tool" &&
254 !messageHasToolCallId(assistantMsg, toolMsg.toolCallId)
255 ) {
256 throw new Error(
257 `Error parsing chat history: no tool call found to match tool output for id "${toolMsg.toolCallId}"`,
258 );
259 }
260 }
261 }
262 } else {
263 // Single user message
264 toolSequence.push(lastMsg);
265 }
266
267 return toolSequence;
268}
269
270function pruneLinesFromTop(
271 prompt: string,
272 maxTokens: number,
273 modelName: string,
274): string {
275 const lines = prompt.split("\n");
276 // Preprocess tokens for all lines and cache them.
277 const lineTokens = lines.map((line) => countTokens(line, modelName));
278 let totalTokens = lineTokens.reduce((sum, tokens) => sum + tokens, 0);
279 let start = 0;
280 let currentLines = lines.length;
281
282 // Calculate initial token count including newlines
283 totalTokens += Math.max(0, currentLines - 1); // Add tokens for joining newlines
284
285 // Using indexes instead of array modifications.
286 // Remove lines from the top until the token count is within the limit.
287 while (totalTokens > maxTokens && start < currentLines) {
288 totalTokens -= lineTokens[start];
289 // Decrement token count for the removed line and its preceding/joining newline (if not the last line)
290 if (currentLines - start > 1) {
291 totalTokens--;
292 }
293 start++;
294 }
295
296 return lines.slice(start).join("\n");
297}
298
299function pruneLinesFromBottom(
300 prompt: string,
301 maxTokens: number,
302 modelName: string,
303): string {
304 const lines = prompt.split("\n");
305 const lineTokens = lines.map((line) => countTokens(line, modelName));
306 let totalTokens = lineTokens.reduce((sum, tokens) => sum + tokens, 0);
307 let end = lines.length;
308
309 // Calculate initial token count including newlines
310 totalTokens += Math.max(0, end - 1); // Add tokens for joining newlines
311
312 // Reverse traversal to avoid array modification
313 // Remove lines from the bottom until the token count is within the limit.
314 while (totalTokens > maxTokens && end > 0) {
315 end--;
316 totalTokens -= lineTokens[end];
317 // Decrement token count for the removed line and its following/joining newline (if not the first line)
318 if (end > 0) {
319 totalTokens--;
320 }
321 }
322
323 return lines.slice(0, end).join("\n");
324}
325
326function pruneStringFromBottom(
327 modelName: string,
328 maxTokens: number,
329 prompt: string,
330): string {
331 const encoding = encodingForModel(modelName);
332
333 const tokens = encoding.encode(prompt, "all", []);
334 if (tokens.length <= maxTokens) {
335 return prompt;
336 }
337
338 return encoding.decode(tokens.slice(0, maxTokens));
339}
340
341function pruneStringFromTop(
342 modelName: string,
343 maxTokens: number,
344 prompt: string,
345): string {
346 const encoding = encodingForModel(modelName);
347
348 const tokens = encoding.encode(prompt, "all", []);
349 if (tokens.length <= maxTokens) {
350 return prompt;
351 }
352
353 return encoding.decode(tokens.slice(tokens.length - maxTokens));
354}
355
356const MAX_TOKEN_SAFETY_BUFFER = 1000;
357const TOKEN_SAFETY_PROPORTION = 0.02;
358function getTokenCountingBufferSafety(contextLength: number) {
359 return Math.min(
360 MAX_TOKEN_SAFETY_BUFFER,
361 contextLength * TOKEN_SAFETY_PROPORTION,
362 );
363}
364
365const MIN_RESPONSE_TOKENS = 1000;
366function getMinResponseTokens(maxTokens: number) {
367 return Math.min(MIN_RESPONSE_TOKENS, maxTokens);
368}
369
370function pruneRawPromptFromTop(
371 modelName: string,
372 contextLength: number,
373 prompt: string,
374 tokensForCompletion: number,
375): string {
376 const maxTokens =
377 contextLength -
378 tokensForCompletion -
379 getTokenCountingBufferSafety(contextLength);
380 return pruneStringFromTop(modelName, maxTokens, prompt);
381}
382
383/**
384 * Reconciles chat messages with available context length by intelligently pruning older messages
385 * while preserving critical conversation elements.
386 *
387 * Core Guidelines:
388 * - Always preserve the last user/tool message sequence (including any associated assistant message with tool calls)
389 * - Always preserve the system message and tools
390 * - Never allow orphaned tool responses without their corresponding tool calls
391 * - Remove older messages first when pruning is necessary
392 * - Maintain conversation coherence by flattening adjacent similar messages
393 *
394 * Process:
395 * 1. Handle image content conversion for models that don't support images
396 * 2. Extract and preserve system message
397 * 3. Filter out empty messages and trailing non-user/tool messages
398 * 4. Extract the complete tool sequence from the end (user message or assistant + tool responses)
399 * 5. Calculate token requirements for non-negotiable elements (system, tools, last sequence)
400 * 6. Prune older messages until within available token budget
401 * 7. Reassemble with proper ordering and flatten adjacent similar messages
402 *
403 * @param params - Configuration object containing:
404 * - modelName: LLM model name for token counting
405 * - msgs: Array of chat messages to process
406 * - contextLength: Maximum context length supported by the model
407 * - maxTokens: Maximum tokens to reserve for the response
408 * - supportsImages: Whether the model supports image content
409 * - tools: Optional array of available tools
410 * @returns Processed array of chat messages that fit within context constraints
411 * @throws Error if non-negotiable elements exceed available context
412 */
413function compileChatMessages({
414 modelName,
415 msgs,
416 contextLength,
417 maxTokens,
418 supportsImages,
419 tools,
420}: {
421 modelName: string;
422 msgs: ChatMessage[];
423 contextLength: number;
424 maxTokens: number;
425 supportsImages: boolean;
426 tools?: Tool[];
427}): CompiledMessagesResult {
428 let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m }));
429
430 // If images not supported, convert MessagePart[] to string
431 if (!supportsImages) {
432 for (const msg of msgsCopy) {
433 if ("content" in msg && Array.isArray(msg.content)) {
434 const content = renderChatMessage(msg);
435 msg.content = content;
436 }
437 }
438 }
439
440 // Extract system message
441 const systemMsg = msgsCopy.find((msg) => msg.role === "system");
442 msgsCopy = msgsCopy.filter((msg) => msg.role !== "system");
443
444 // Remove any empty messages or non-user/tool trailing messages
445 msgsCopy = msgsCopy.filter((msg) => !chatMessageIsEmpty(msg));
446
447 msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
448
449 while (msgsCopy.length > 1) {
450 if (isUserOrToolMsg(msgsCopy.at(-1))) {
451 break;
452 }
453 msgsCopy.pop();
454 }
455
456 // // Extract the tool sequence from the end of the message array
457 // const toolSequence = extractToolSequence(msgsCopy);
458
459 // // Count tokens for all messages in the tool sequence
460 // let lastMessagesTokens = 0;
461 // for (const msg of toolSequence) {
462 // lastMessagesTokens += countChatMessageTokens(modelName, msg);
463 // }
464
465 // System message
466 let systemMsgTokens = 0;
467 if (systemMsg) {
468 systemMsgTokens = countChatMessageTokens(modelName, systemMsg);
469 }
470
471 // Tools
472 let toolTokens = 0;
473 if (tools) {
474 toolTokens = countToolsTokens(tools, modelName);
475 }
476
477 const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength);
478 const minOutputTokens = getMinResponseTokens(maxTokens);
479
480 let inputTokensAvailable = contextLength;
481
482 // Leave space for output/safety
483 inputTokensAvailable -= countingSafetyBuffer;
484 inputTokensAvailable -= minOutputTokens;
485
486 // Non-negotiable messages
487 inputTokensAvailable -= toolTokens;
488 inputTokensAvailable -= systemMsgTokens;
489 // inputTokensAvailable -= lastMessagesTokens;
490
491 // Make sure there's enough context for the non-excludable items
492 if (inputTokensAvailable < 0) {
493 throw new Error(
494 `Not enough context available to include the system message, last user message, and tools.
495 There must be at least ${minOutputTokens} tokens remaining for output.
496 Request had the following token counts:
497 - contextLength: ${contextLength}
498 - counting safety buffer: ${countingSafetyBuffer}
499 - tools: ~${toolTokens}
500 - system message: ~${systemMsgTokens}
501 - max output tokens: ${maxTokens}`,
502 );
503 }
504
505 // Now remove messages till we're under the limit
506 let currentTotal = 0;
507 const historyWithTokens = msgsCopy.map((message) => {
508 const tokens = countChatMessageTokens(modelName, message);
509 currentTotal += tokens;
510 return {
511 ...message,
512 tokens,
513 };
514 });
515
516 let pruningStatus: PruningStatus = "not-pruned";
517
518 while (historyWithTokens.length > 0 && currentTotal > inputTokensAvailable) {
519 const message = historyWithTokens.shift()!;
520 currentTotal -= message.tokens;
521 pruningStatus = "pruned";
522
523 // At this point make sure no latent tool response without corresponding call
524 while (historyWithTokens[0]?.role === "tool") {
525 const message = historyWithTokens.shift()!;
526 currentTotal -= message.tokens;
527 }
528 }
529
530 if (historyWithTokens.length === 0) {
531 pruningStatus = "deleted-last-input";
532 }
533
534 // Now reassemble
535 const reassembled: ChatMessage[] = [];
536 if (systemMsg) {
537 reassembled.push(systemMsg);
538 }
539 reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest));
540
541 return { compiledChatMessages: reassembled, pruningStatus };
542}
543
544export {
545 compileChatMessages,
546 countTokens,
547 countTokensAsync,
548 extractToolSequence,
549 pruneLinesFromBottom,
550 pruneLinesFromTop,
551 pruneRawPromptFromTop,
552 pruneStringFromBottom,
553 pruneStringFromTop,
554};