| 1 | import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken"; |
| 2 | |
| 3 | import { |
| 4 | ChatMessage, |
| 5 | CompiledMessagesResult, |
| 6 | MessageContent, |
| 7 | MessagePart, |
| 8 | Tool, |
| 9 | } from "../index.js"; |
| 10 | import { autodetectTemplateType } from "./autodetect.js"; |
| 11 | import { |
| 12 | addSpaceToAnyEmptyMessages, |
| 13 | chatMessageIsEmpty, |
| 14 | isUserOrToolMsg, |
| 15 | messageHasToolCallId, |
| 16 | } from "./messages.js"; |
| 17 | |
| 18 | import { renderChatMessage } from "../util/messageContent.js"; |
| 19 | import { AsyncEncoder, LlamaAsyncEncoder } from "./asyncEncoder.js"; |
| 20 | import { DEFAULT_PRUNING_LENGTH } from "./constants.js"; |
| 21 | import llamaTokenizer from "./llamaTokenizer.js"; |
| 22 | interface Encoding { |
| 23 | encode: Tiktoken["encode"]; |
| 24 | decode: Tiktoken["decode"]; |
| 25 | } |
| 26 | |
| 27 | class 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 | |
| 37 | class 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 | |
| 51 | let gptEncoding: Encoding | null = null; |
| 52 | const llamaEncoding = new LlamaEncoding(); |
| 53 | const llamaAsyncEncoder = new LlamaAsyncEncoder(); |
| 54 | |
| 55 | function 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 | |
| 72 | function 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 | |
| 86 | function countImageTokens(content: MessagePart): number { |
| 87 | if (content.type === "imageUrl") { |
| 88 | return 1024; |
| 89 | } |
| 90 | throw new Error("Non-image content type"); |
| 91 | } |
| 92 | |
| 93 | async 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 | |
| 111 | function 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 |
| 132 | function 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 | |
| 176 | function 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 | */ |
| 225 | function 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 | |
| 270 | function 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 | |
| 299 | function 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 | |
| 326 | function 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 | |
| 341 | function 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 | |
| 356 | const MAX_TOKEN_SAFETY_BUFFER = 1000; |
| 357 | const TOKEN_SAFETY_PROPORTION = 0.02; |
| 358 | export function getTokenCountingBufferSafety(contextLength: number) { |
| 359 | return Math.min( |
| 360 | MAX_TOKEN_SAFETY_BUFFER, |
| 361 | contextLength * TOKEN_SAFETY_PROPORTION, |
| 362 | ); |
| 363 | } |
| 364 | |
| 365 | const MIN_RESPONSE_TOKENS = 1000; |
| 366 | |
| 367 | function pruneRawPromptFromTop( |
| 368 | modelName: string, |
| 369 | contextLength: number, |
| 370 | prompt: string, |
| 371 | tokensForCompletion: number, |
| 372 | ): string { |
| 373 | const maxTokens = |
| 374 | contextLength - |
| 375 | tokensForCompletion - |
| 376 | getTokenCountingBufferSafety(contextLength); |
| 377 | return pruneStringFromTop(modelName, maxTokens, prompt); |
| 378 | } |
| 379 | |
| 380 | /** |
| 381 | * Reconciles chat messages with available context length by intelligently pruning older messages |
| 382 | * while preserving critical conversation elements. |
| 383 | * |
| 384 | * Core Guidelines: |
| 385 | * - Always preserve the last user/tool message sequence (including any associated assistant message with tool calls) |
| 386 | * - Always preserve the system message and tools |
| 387 | * - Never allow orphaned tool responses without their corresponding tool calls |
| 388 | * - Remove older messages first when pruning is necessary |
| 389 | * - Maintain conversation coherence by flattening adjacent similar messages |
| 390 | * |
| 391 | * Process: |
| 392 | * 1. Handle image content conversion for models that don't support images |
| 393 | * 2. Extract and preserve system message |
| 394 | * 3. Filter out empty messages and trailing non-user/tool messages |
| 395 | * 4. Extract the complete tool sequence from the end (user message or assistant + tool responses) |
| 396 | * 5. Calculate token requirements for non-negotiable elements (system, tools, last sequence) |
| 397 | * 6. Prune older messages until within available token budget |
| 398 | * 7. Reassemble with proper ordering and flatten adjacent similar messages |
| 399 | * |
| 400 | * @param params - Configuration object containing: |
| 401 | * - modelName: LLM model name for token counting |
| 402 | * - msgs: Array of chat messages to process |
| 403 | * - contextLength: Maximum context length supported by the model |
| 404 | * - maxTokens: Maximum tokens to reserve for the response |
| 405 | * - supportsImages: Whether the model supports image content |
| 406 | * - tools: Optional array of available tools |
| 407 | * @returns Processed array of chat messages that fit within context constraints |
| 408 | * @throws Error if non-negotiable elements exceed available context |
| 409 | */ |
| 410 | function compileChatMessages({ |
| 411 | modelName, |
| 412 | msgs, |
| 413 | knownContextLength, |
| 414 | maxTokens, |
| 415 | supportsImages, |
| 416 | tools, |
| 417 | }: { |
| 418 | modelName: string; |
| 419 | msgs: ChatMessage[]; |
| 420 | knownContextLength: number | undefined; |
| 421 | maxTokens: number; |
| 422 | supportsImages: boolean; |
| 423 | tools?: Tool[]; |
| 424 | }): CompiledMessagesResult { |
| 425 | let didPrune = false; |
| 426 | |
| 427 | let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m })); |
| 428 | |
| 429 | // If images not supported, convert MessagePart[] to string |
| 430 | if (!supportsImages) { |
| 431 | for (const msg of msgsCopy) { |
| 432 | if ("content" in msg && Array.isArray(msg.content)) { |
| 433 | const content = renderChatMessage(msg); |
| 434 | msg.content = content; |
| 435 | } |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | // Extract system message |
| 440 | const systemMsg = msgsCopy.find((msg) => msg.role === "system"); |
| 441 | msgsCopy = msgsCopy.filter((msg) => msg.role !== "system"); |
| 442 | |
| 443 | // Remove any empty messages or non-user/tool trailing messages |
| 444 | msgsCopy = msgsCopy.filter((msg) => !chatMessageIsEmpty(msg)); |
| 445 | |
| 446 | msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy); |
| 447 | |
| 448 | // Extract the tool sequence from the end of the message array |
| 449 | const toolSequence = extractToolSequence(msgsCopy); |
| 450 | |
| 451 | // Count tokens for all messages in the tool sequence |
| 452 | let lastMessagesTokens = 0; |
| 453 | for (const msg of toolSequence) { |
| 454 | lastMessagesTokens += countChatMessageTokens(modelName, msg); |
| 455 | } |
| 456 | |
| 457 | // System message |
| 458 | let systemMsgTokens = 0; |
| 459 | if (systemMsg) { |
| 460 | systemMsgTokens = countChatMessageTokens(modelName, systemMsg); |
| 461 | } |
| 462 | |
| 463 | // Tools |
| 464 | let toolTokens = 0; |
| 465 | if (tools) { |
| 466 | toolTokens = countToolsTokens(tools, modelName); |
| 467 | } |
| 468 | |
| 469 | const contextLength = knownContextLength ?? DEFAULT_PRUNING_LENGTH; |
| 470 | const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength); |
| 471 | const minOutputTokens = Math.min(MIN_RESPONSE_TOKENS, maxTokens); |
| 472 | |
| 473 | let inputTokensAvailable = contextLength; |
| 474 | |
| 475 | // Leave space for output/safety |
| 476 | inputTokensAvailable -= countingSafetyBuffer; |
| 477 | inputTokensAvailable -= minOutputTokens; |
| 478 | |
| 479 | // Non-negotiable messages |
| 480 | inputTokensAvailable -= toolTokens; |
| 481 | inputTokensAvailable -= systemMsgTokens; |
| 482 | inputTokensAvailable -= lastMessagesTokens; |
| 483 | |
| 484 | // Make sure there's enough context for the non-excludable items |
| 485 | if (knownContextLength !== undefined && inputTokensAvailable < 0) { |
| 486 | throw new Error( |
| 487 | `Not enough context available to include the system message, last user message, and tools. |
| 488 | There must be at least ${minOutputTokens} tokens remaining for output. |
| 489 | Request had the following token counts: |
| 490 | - contextLength: ${knownContextLength} |
| 491 | - counting safety buffer: ${countingSafetyBuffer} |
| 492 | - tools: ~${toolTokens} |
| 493 | - system message: ~${systemMsgTokens} |
| 494 | - max output tokens: ${maxTokens}`, |
| 495 | ); |
| 496 | } |
| 497 | |
| 498 | // Now remove messages till we're under the limit |
| 499 | let currentTotal = 0; |
| 500 | const historyWithTokens = msgsCopy.map((message) => { |
| 501 | const tokens = countChatMessageTokens(modelName, message); |
| 502 | currentTotal += tokens; |
| 503 | return { |
| 504 | ...message, |
| 505 | tokens, |
| 506 | }; |
| 507 | }); |
| 508 | |
| 509 | while (historyWithTokens.length > 0 && currentTotal > inputTokensAvailable) { |
| 510 | const message = historyWithTokens.shift()!; |
| 511 | currentTotal -= message.tokens; |
| 512 | didPrune = true; |
| 513 | |
| 514 | // At this point make sure no latent tool response without corresponding call |
| 515 | while (historyWithTokens[0]?.role === "tool") { |
| 516 | const message = historyWithTokens.shift()!; |
| 517 | currentTotal -= message.tokens; |
| 518 | } |
| 519 | } |
| 520 | |
| 521 | // Now reassemble |
| 522 | const reassembled: ChatMessage[] = []; |
| 523 | if (systemMsg) { |
| 524 | reassembled.push(systemMsg); |
| 525 | } |
| 526 | reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest)); |
| 527 | reassembled.push(...toolSequence); |
| 528 | |
| 529 | const inputTokens = |
| 530 | currentTotal + systemMsgTokens + toolTokens + lastMessagesTokens; |
| 531 | const availableTokens = |
| 532 | contextLength - countingSafetyBuffer - minOutputTokens; |
| 533 | const contextPercentage = inputTokens / availableTokens; |
| 534 | return { |
| 535 | compiledChatMessages: reassembled, |
| 536 | didPrune, |
| 537 | contextPercentage, |
| 538 | }; |
| 539 | } |
| 540 | |
| 541 | async function cleanupAsyncEncoders(): Promise<void> { |
| 542 | try { |
| 543 | await llamaAsyncEncoder.close(); |
| 544 | } catch (e) {} |
| 545 | } |
| 546 | |
| 547 | export { |
| 548 | cleanupAsyncEncoders, |
| 549 | compileChatMessages, |
| 550 | countTokens, |
| 551 | countTokensAsync, |
| 552 | extractToolSequence, |
| 553 | pruneLinesFromBottom, |
| 554 | pruneLinesFromTop, |
| 555 | pruneRawPromptFromTop, |
| 556 | pruneStringFromBottom, |
| 557 | pruneStringFromTop, |
| 558 | }; |