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