| 1 | import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken"; |
| 2 | |
| 3 | import { ChatMessage, MessageContent, MessagePart, Tool } from "../index.js"; |
| 4 | |
| 5 | import { renderChatMessage } from "../util/messageContent.js"; |
| 6 | import { |
| 7 | AsyncEncoder, |
| 8 | GPTAsyncEncoder, |
| 9 | LlamaAsyncEncoder, |
| 10 | } from "./asyncEncoder.js"; |
| 11 | import { autodetectTemplateType } from "./autodetect.js"; |
| 12 | import llamaTokenizer from "./llamaTokenizer.js"; |
| 13 | import { |
| 14 | addSpaceToAnyEmptyMessages, |
| 15 | chatMessageIsEmpty, |
| 16 | flattenMessages, |
| 17 | isUserOrToolMsg, |
| 18 | messageHasToolCallId, |
| 19 | } from "./messages.js"; |
| 20 | interface Encoding { |
| 21 | encode: Tiktoken["encode"]; |
| 22 | decode: Tiktoken["decode"]; |
| 23 | } |
| 24 | |
| 25 | class LlamaEncoding implements Encoding { |
| 26 | encode(text: string): number[] { |
| 27 | return llamaTokenizer.encode(text); |
| 28 | } |
| 29 | |
| 30 | decode(tokens: number[]): string { |
| 31 | return llamaTokenizer.decode(tokens); |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | class NonWorkerAsyncEncoder implements AsyncEncoder { |
| 36 | constructor(private readonly encoding: Encoding) {} |
| 37 | |
| 38 | async close(): Promise<void> {} |
| 39 | |
| 40 | async encode(text: string): Promise<number[]> { |
| 41 | return this.encoding.encode(text); |
| 42 | } |
| 43 | |
| 44 | async decode(tokens: number[]): Promise<string> { |
| 45 | return this.encoding.decode(tokens); |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | let gptEncoding: Encoding | null = null; |
| 50 | const gptAsyncEncoder = new GPTAsyncEncoder(); |
| 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 | return gptAsyncEncoder; |
| 64 | } |
| 65 | return llamaAsyncEncoder; |
| 66 | } |
| 67 | |
| 68 | function encodingForModel(modelName: string): Encoding { |
| 69 | const modelType = autodetectTemplateType(modelName); |
| 70 | |
| 71 | if (!modelType || modelType === "none") { |
| 72 | if (!gptEncoding) { |
| 73 | gptEncoding = _encodingForModel("gpt-4"); |
| 74 | } |
| 75 | |
| 76 | return gptEncoding; |
| 77 | } |
| 78 | |
| 79 | return llamaEncoding; |
| 80 | } |
| 81 | |
| 82 | function countImageTokens(content: MessagePart): number { |
| 83 | if (content.type === "imageUrl") { |
| 84 | return 85; |
| 85 | } |
| 86 | throw new Error("Non-image content type"); |
| 87 | } |
| 88 | |
| 89 | async function countTokensAsync( |
| 90 | content: MessageContent, |
| 91 | // defaults to llama2 because the tokenizer tends to produce more tokens |
| 92 | modelName = "llama2", |
| 93 | ): Promise<number> { |
| 94 | const encoding = asyncEncoderForModel(modelName); |
| 95 | if (Array.isArray(content)) { |
| 96 | const promises = content.map(async (part) => { |
| 97 | if (part.type === "imageUrl") { |
| 98 | return countImageTokens(part); |
| 99 | } |
| 100 | return (await encoding.encode(part.text ?? "")).length; |
| 101 | }); |
| 102 | return (await Promise.all(promises)).reduce((sum, val) => sum + val, 0); |
| 103 | } |
| 104 | return (await encoding.encode(content ?? "")).length; |
| 105 | } |
| 106 | |
| 107 | function countTokens( |
| 108 | content: MessageContent, |
| 109 | // defaults to llama2 because the tokenizer tends to produce more tokens |
| 110 | modelName = "llama2", |
| 111 | ): number { |
| 112 | const encoding = encodingForModel(modelName); |
| 113 | if (Array.isArray(content)) { |
| 114 | return content.reduce((acc, part) => { |
| 115 | return ( |
| 116 | acc + |
| 117 | (part.type === "text" |
| 118 | ? encoding.encode(part.text ?? "", "all", []).length |
| 119 | : countImageTokens(part)) |
| 120 | ); |
| 121 | }, 0); |
| 122 | } else { |
| 123 | return encoding.encode(content ?? "", "all", []).length; |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | // https://community.openai.com/t/how-to-calculate-the-tokens-when-using-function-call/266573/10 |
| 128 | function countToolsTokens(tools: Tool[], modelName: string): number { |
| 129 | const count = (value: string) => |
| 130 | encodingForModel(modelName).encode(value).length; |
| 131 | |
| 132 | let numTokens = 12; |
| 133 | |
| 134 | for (const tool of tools) { |
| 135 | let functionTokens = count(tool.function.name); |
| 136 | if (tool.function.description) { |
| 137 | functionTokens += count(tool.function.description); |
| 138 | } |
| 139 | const props = tool.function.parameters?.properties; |
| 140 | if (props) { |
| 141 | for (const key in props) { |
| 142 | functionTokens += count(key); |
| 143 | const fields = props[key]; |
| 144 | if (fields) { |
| 145 | const fieldType = fields["type"]; |
| 146 | const fieldDesc = fields["description"]; |
| 147 | const fieldEnum = fields["enum"]; |
| 148 | if (fieldType && typeof fieldType === "string") { |
| 149 | functionTokens += 2; |
| 150 | functionTokens += count(fieldType); |
| 151 | } |
| 152 | if (fieldDesc && typeof fieldDesc === "string") { |
| 153 | functionTokens += 2; |
| 154 | functionTokens += count(fieldDesc); |
| 155 | } |
| 156 | if (fieldEnum && Array.isArray(fieldEnum)) { |
| 157 | functionTokens -= 3; |
| 158 | for (const e of fieldEnum) { |
| 159 | functionTokens += 3; |
| 160 | functionTokens += typeof e === "string" ? count(e) : 5; |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | } |
| 165 | } |
| 166 | numTokens += functionTokens; |
| 167 | } |
| 168 | |
| 169 | return numTokens + 12; |
| 170 | } |
| 171 | |
| 172 | function countChatMessageTokens( |
| 173 | modelName: string, |
| 174 | chatMessage: ChatMessage, |
| 175 | ): number { |
| 176 | // Doing simpler, safer version of what is here: |
| 177 | // https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb |
| 178 | // every message follows <|im_start|>{role/name}\n{content}<|end|>\n |
| 179 | const BASE_TOKENS = 4; |
| 180 | const TOOL_CALL_EXTRA_TOKENS = 10; |
| 181 | const TOOL_OUTPUT_EXTRA_TOKENS = 10; |
| 182 | let tokens = BASE_TOKENS; |
| 183 | |
| 184 | if (chatMessage.content) { |
| 185 | tokens += countTokens(chatMessage.content, modelName); |
| 186 | } |
| 187 | |
| 188 | if ("toolCalls" in chatMessage && chatMessage.toolCalls) { |
| 189 | for (const call of chatMessage.toolCalls) { |
| 190 | tokens += TOOL_CALL_EXTRA_TOKENS; |
| 191 | tokens += countTokens(JSON.stringify(call), modelName); // TODO hone this |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | if (chatMessage.role === "thinking") { |
| 196 | if (chatMessage.redactedThinking) { |
| 197 | tokens += countTokens(chatMessage.redactedThinking, modelName); |
| 198 | } |
| 199 | if (chatMessage.signature) { |
| 200 | tokens += countTokens(chatMessage.signature, modelName); |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | if (chatMessage.role === "tool") { |
| 205 | tokens += TOOL_OUTPUT_EXTRA_TOKENS; // safety |
| 206 | if (chatMessage.toolCallId) { |
| 207 | tokens += countTokens(chatMessage.toolCallId, modelName); |
| 208 | } |
| 209 | } |
| 210 | return tokens; |
| 211 | } |
| 212 | |
| 213 | function pruneLinesFromTop( |
| 214 | prompt: string, |
| 215 | maxTokens: number, |
| 216 | modelName: string, |
| 217 | ): string { |
| 218 | const lines = prompt.split("\n"); |
| 219 | // Preprocess tokens for all lines and cache them. |
| 220 | const lineTokens = lines.map((line) => countTokens(line, modelName)); |
| 221 | let totalTokens = lineTokens.reduce((sum, tokens) => sum + tokens, 0); |
| 222 | let start = 0; |
| 223 | let currentLines = lines.length; |
| 224 | |
| 225 | // Calculate initial token count including newlines |
| 226 | totalTokens += Math.max(0, currentLines - 1); // Add tokens for joining newlines |
| 227 | |
| 228 | // Using indexes instead of array modifications. |
| 229 | // Remove lines from the top until the token count is within the limit. |
| 230 | while (totalTokens > maxTokens && start < currentLines) { |
| 231 | totalTokens -= lineTokens[start]; |
| 232 | // Decrement token count for the removed line and its preceding/joining newline (if not the last line) |
| 233 | if (currentLines - start > 1) { |
| 234 | totalTokens--; |
| 235 | } |
| 236 | start++; |
| 237 | } |
| 238 | |
| 239 | return lines.slice(start).join("\n"); |
| 240 | } |
| 241 | |
| 242 | function pruneLinesFromBottom( |
| 243 | prompt: string, |
| 244 | maxTokens: number, |
| 245 | modelName: string, |
| 246 | ): string { |
| 247 | const lines = prompt.split("\n"); |
| 248 | const lineTokens = lines.map((line) => countTokens(line, modelName)); |
| 249 | let totalTokens = lineTokens.reduce((sum, tokens) => sum + tokens, 0); |
| 250 | let end = lines.length; |
| 251 | |
| 252 | // Calculate initial token count including newlines |
| 253 | totalTokens += Math.max(0, end - 1); // Add tokens for joining newlines |
| 254 | |
| 255 | // Reverse traversal to avoid array modification |
| 256 | // Remove lines from the bottom until the token count is within the limit. |
| 257 | while (totalTokens > maxTokens && end > 0) { |
| 258 | end--; |
| 259 | totalTokens -= lineTokens[end]; |
| 260 | // Decrement token count for the removed line and its following/joining newline (if not the first line) |
| 261 | if (end > 0) { |
| 262 | totalTokens--; |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | return lines.slice(0, end).join("\n"); |
| 267 | } |
| 268 | |
| 269 | function pruneStringFromBottom( |
| 270 | modelName: string, |
| 271 | maxTokens: number, |
| 272 | prompt: string, |
| 273 | ): string { |
| 274 | const encoding = encodingForModel(modelName); |
| 275 | |
| 276 | const tokens = encoding.encode(prompt, "all", []); |
| 277 | if (tokens.length <= maxTokens) { |
| 278 | return prompt; |
| 279 | } |
| 280 | |
| 281 | return encoding.decode(tokens.slice(0, maxTokens)); |
| 282 | } |
| 283 | |
| 284 | function pruneStringFromTop( |
| 285 | modelName: string, |
| 286 | maxTokens: number, |
| 287 | prompt: string, |
| 288 | ): string { |
| 289 | const encoding = encodingForModel(modelName); |
| 290 | |
| 291 | const tokens = encoding.encode(prompt, "all", []); |
| 292 | if (tokens.length <= maxTokens) { |
| 293 | return prompt; |
| 294 | } |
| 295 | |
| 296 | return encoding.decode(tokens.slice(tokens.length - maxTokens)); |
| 297 | } |
| 298 | |
| 299 | const MAX_TOKEN_SAFETY_BUFFER = 1000; |
| 300 | const TOKEN_SAFETY_PROPORTION = 0.02; |
| 301 | function getTokenCountingBufferSafety(contextLength: number) { |
| 302 | return Math.min( |
| 303 | MAX_TOKEN_SAFETY_BUFFER, |
| 304 | contextLength * TOKEN_SAFETY_PROPORTION, |
| 305 | ); |
| 306 | } |
| 307 | |
| 308 | const MIN_RESPONSE_TOKENS = 1000; |
| 309 | function getMinResponseTokens(maxTokens: number) { |
| 310 | return Math.min(MIN_RESPONSE_TOKENS, maxTokens); |
| 311 | } |
| 312 | |
| 313 | function pruneRawPromptFromTop( |
| 314 | modelName: string, |
| 315 | contextLength: number, |
| 316 | prompt: string, |
| 317 | tokensForCompletion: number, |
| 318 | ): string { |
| 319 | const maxTokens = |
| 320 | contextLength - |
| 321 | tokensForCompletion - |
| 322 | getTokenCountingBufferSafety(contextLength); |
| 323 | return pruneStringFromTop(modelName, maxTokens, prompt); |
| 324 | } |
| 325 | |
| 326 | /* |
| 327 | Goal: reconcile chat messages with available context length |
| 328 | Guidelines: |
| 329 | - Always keep last user message, system message, and tools |
| 330 | - Never allow tool output without the corresponding tool call |
| 331 | - Remove older messages first |
| 332 | */ |
| 333 | function compileChatMessages({ |
| 334 | modelName, |
| 335 | msgs, |
| 336 | contextLength, |
| 337 | maxTokens, |
| 338 | supportsImages, |
| 339 | tools, |
| 340 | }: { |
| 341 | modelName: string; |
| 342 | msgs: ChatMessage[]; |
| 343 | contextLength: number; |
| 344 | maxTokens: number; |
| 345 | supportsImages: boolean; |
| 346 | tools?: Tool[]; |
| 347 | }): ChatMessage[] { |
| 348 | let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m })); |
| 349 | |
| 350 | // If images not supported, convert MessagePart[] to string |
| 351 | if (!supportsImages) { |
| 352 | for (const msg of msgsCopy) { |
| 353 | if ("content" in msg && Array.isArray(msg.content)) { |
| 354 | const content = renderChatMessage(msg); |
| 355 | msg.content = content; |
| 356 | } |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | // Extract system message |
| 361 | const systemMsg = msgsCopy.find((msg) => msg.role === "system"); |
| 362 | msgsCopy = msgsCopy.filter((msg) => msg.role !== "system"); |
| 363 | |
| 364 | // Remove any empty messages or non-user/tool trailing messages |
| 365 | msgsCopy = msgsCopy.filter((msg) => !chatMessageIsEmpty(msg)); |
| 366 | |
| 367 | msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy); |
| 368 | |
| 369 | while (msgsCopy.length > 1) { |
| 370 | if (isUserOrToolMsg(msgsCopy.at(-1))) { |
| 371 | break; |
| 372 | } |
| 373 | msgsCopy.pop(); |
| 374 | } |
| 375 | |
| 376 | const lastUserOrToolMsg = msgsCopy.pop(); |
| 377 | if (!lastUserOrToolMsg || !isUserOrToolMsg(lastUserOrToolMsg)) { |
| 378 | throw new Error("Error parsing chat history: no user/tool message found"); // should never happen |
| 379 | } |
| 380 | |
| 381 | let lastToolCallsMsg: ChatMessage | undefined = undefined; |
| 382 | if (lastUserOrToolMsg.role === "tool") { |
| 383 | lastToolCallsMsg = msgsCopy.pop(); |
| 384 | if (!messageHasToolCallId(lastToolCallsMsg, lastUserOrToolMsg.toolCallId)) { |
| 385 | throw new Error( |
| 386 | `Error parsing chat history: no tool call found to match tool output for id "${lastUserOrToolMsg.toolCallId}"`, |
| 387 | ); |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | let lastMessagesTokens = countChatMessageTokens(modelName, lastUserOrToolMsg); |
| 392 | if (lastToolCallsMsg) { |
| 393 | lastMessagesTokens += countChatMessageTokens(modelName, lastToolCallsMsg); |
| 394 | } |
| 395 | |
| 396 | // System message |
| 397 | let systemMsgTokens = 0; |
| 398 | if (systemMsg) { |
| 399 | systemMsgTokens = countChatMessageTokens(modelName, systemMsg); |
| 400 | } |
| 401 | |
| 402 | // Tools |
| 403 | let toolTokens = 0; |
| 404 | if (tools) { |
| 405 | toolTokens = countToolsTokens(tools, modelName); |
| 406 | } |
| 407 | |
| 408 | const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength); |
| 409 | const minOutputTokens = getMinResponseTokens(maxTokens); |
| 410 | |
| 411 | let inputTokensAvailable = contextLength; |
| 412 | |
| 413 | // Leave space for output/safety |
| 414 | inputTokensAvailable -= countingSafetyBuffer; |
| 415 | inputTokensAvailable -= minOutputTokens; |
| 416 | |
| 417 | // Non-negotiable messages |
| 418 | inputTokensAvailable -= toolTokens; |
| 419 | inputTokensAvailable -= systemMsgTokens; |
| 420 | inputTokensAvailable -= lastMessagesTokens; |
| 421 | |
| 422 | // Make sure there's enough context for the non-excludable items |
| 423 | if (inputTokensAvailable < 0) { |
| 424 | throw new Error( |
| 425 | `Not enough context available to include the system message, last user message, and tools. |
| 426 | There must be at least ${minOutputTokens} tokens remaining for output. |
| 427 | Request had the following token counts: |
| 428 | - contextLength: ${contextLength} |
| 429 | - counting safety buffer: ${countingSafetyBuffer} |
| 430 | - tools: ~${toolTokens} |
| 431 | - system message: ~${systemMsgTokens} |
| 432 | - last user or tool + tool call message tokens: ~${lastMessagesTokens} |
| 433 | - max output tokens: ${maxTokens}`, |
| 434 | ); |
| 435 | } |
| 436 | |
| 437 | // Now remove messages till we're under the limit |
| 438 | let currentTotal = 0; |
| 439 | const historyWithTokens = msgsCopy.map((message) => { |
| 440 | const tokens = countChatMessageTokens(modelName, message); |
| 441 | currentTotal += tokens; |
| 442 | return { |
| 443 | ...message, |
| 444 | tokens, |
| 445 | }; |
| 446 | }); |
| 447 | |
| 448 | while (historyWithTokens.length > 0 && currentTotal > inputTokensAvailable) { |
| 449 | const message = historyWithTokens.shift()!; |
| 450 | currentTotal -= message.tokens; |
| 451 | |
| 452 | // At this point make sure no latent tool response without corresponding call |
| 453 | while (historyWithTokens[0]?.role === "tool") { |
| 454 | const message = historyWithTokens.shift()!; |
| 455 | currentTotal -= message.tokens; |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | // Now reassemble |
| 460 | const reassembled: ChatMessage[] = []; |
| 461 | if (systemMsg) { |
| 462 | reassembled.push(systemMsg); |
| 463 | } |
| 464 | reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest)); |
| 465 | if (lastToolCallsMsg) { |
| 466 | reassembled.push(lastToolCallsMsg); |
| 467 | } |
| 468 | reassembled.push(lastUserOrToolMsg); |
| 469 | |
| 470 | // Flatten the messages (combines adjacent similar messages) |
| 471 | const flattenedHistory = flattenMessages(reassembled); |
| 472 | return flattenedHistory; |
| 473 | } |
| 474 | |
| 475 | export { |
| 476 | compileChatMessages, |
| 477 | countTokens, |
| 478 | countTokensAsync, |
| 479 | pruneLinesFromBottom, |
| 480 | pruneLinesFromTop, |
| 481 | pruneRawPromptFromTop, |
| 482 | pruneStringFromBottom, |
| 483 | pruneStringFromTop, |
| 484 | }; |