Elffuss BraidHub

kikocis/continue public

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