Elffuss BraidHub

kikocis/continue public

51e47455f9be · 14.0 KiBRawPermalink
1import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
2
3import { ChatMessage, MessageContent, MessagePart, Tool } from "../index.js";
4
5import { renderChatMessage } from "../util/messageContent.js";
6import {
7 AsyncEncoder,
8 GPTAsyncEncoder,
9 LlamaAsyncEncoder,
10} from "./asyncEncoder.js";
11import { autodetectTemplateType } from "./autodetect.js";
12import llamaTokenizer from "./llamaTokenizer.js";
13import {
14 addSpaceToAnyEmptyMessages,
15 chatMessageIsEmpty,
16 flattenMessages,
17 isUserOrToolMsg,
18 messageHasToolCallId,
19} from "./messages.js";
20interface Encoding {
21 encode: Tiktoken["encode"];
22 decode: Tiktoken["decode"];
23}
24
25class 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
35class 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
49let gptEncoding: Encoding | null = null;
50const gptAsyncEncoder = new GPTAsyncEncoder();
51const llamaEncoding = new LlamaEncoding();
52const llamaAsyncEncoder = new LlamaAsyncEncoder();
53
54function 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
71function 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
85function countImageTokens(content: MessagePart): number {
86 if (content.type === "imageUrl") {
87 return 85;
88 }
89 throw new Error("Non-image content type");
90}
91
92async 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
110function 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
131function 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
175function 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
216function pruneLinesFromTop(
217 prompt: string,
218 maxTokens: number,
219 modelName: string,
220): string {
221 const lines = prompt.split("\n");
222 // Preprocess tokens for all lines and cache them.
223 const lineTokens = lines.map((line) => countTokens(line, modelName));
224 let totalTokens = lineTokens.reduce((sum, tokens) => sum + tokens, 0);
225 let start = 0;
226 let currentLines = lines.length;
227
228 // Calculate initial token count including newlines
229 totalTokens += Math.max(0, currentLines - 1); // Add tokens for joining newlines
230
231 // Using indexes instead of array modifications.
232 // Remove lines from the top until the token count is within the limit.
233 while (totalTokens > maxTokens && start < currentLines) {
234 totalTokens -= lineTokens[start];
235 // Decrement token count for the removed line and its preceding/joining newline (if not the last line)
236 if (currentLines - start > 1) {
237 totalTokens--;
238 }
239 start++;
240 }
241
242 return lines.slice(start).join("\n");
243}
244
245function pruneLinesFromBottom(
246 prompt: string,
247 maxTokens: number,
248 modelName: string,
249): string {
250 const lines = prompt.split("\n");
251 const lineTokens = lines.map((line) => countTokens(line, modelName));
252 let totalTokens = lineTokens.reduce((sum, tokens) => sum + tokens, 0);
253 let end = lines.length;
254
255 // Calculate initial token count including newlines
256 totalTokens += Math.max(0, end - 1); // Add tokens for joining newlines
257
258 // Reverse traversal to avoid array modification
259 // Remove lines from the bottom until the token count is within the limit.
260 while (totalTokens > maxTokens && end > 0) {
261 end--;
262 totalTokens -= lineTokens[end];
263 // Decrement token count for the removed line and its following/joining newline (if not the first line)
264 if (end > 0) {
265 totalTokens--;
266 }
267 }
268
269 return lines.slice(0, end).join("\n");
270}
271
272function pruneStringFromBottom(
273 modelName: string,
274 maxTokens: number,
275 prompt: string,
276): string {
277 const encoding = encodingForModel(modelName);
278
279 const tokens = encoding.encode(prompt, "all", []);
280 if (tokens.length <= maxTokens) {
281 return prompt;
282 }
283
284 return encoding.decode(tokens.slice(0, maxTokens));
285}
286
287function pruneStringFromTop(
288 modelName: string,
289 maxTokens: number,
290 prompt: string,
291): string {
292 const encoding = encodingForModel(modelName);
293
294 const tokens = encoding.encode(prompt, "all", []);
295 if (tokens.length <= maxTokens) {
296 return prompt;
297 }
298
299 return encoding.decode(tokens.slice(tokens.length - maxTokens));
300}
301
302const MAX_TOKEN_SAFETY_BUFFER = 1000;
303const TOKEN_SAFETY_PROPORTION = 0.02;
304function getTokenCountingBufferSafety(contextLength: number) {
305 return Math.min(
306 MAX_TOKEN_SAFETY_BUFFER,
307 contextLength * TOKEN_SAFETY_PROPORTION,
308 );
309}
310
311const MIN_RESPONSE_TOKENS = 1000;
312function getMinResponseTokens(maxTokens: number) {
313 return Math.min(MIN_RESPONSE_TOKENS, maxTokens);
314}
315
316function pruneRawPromptFromTop(
317 modelName: string,
318 contextLength: number,
319 prompt: string,
320 tokensForCompletion: number,
321): string {
322 const maxTokens =
323 contextLength -
324 tokensForCompletion -
325 getTokenCountingBufferSafety(contextLength);
326 return pruneStringFromTop(modelName, maxTokens, prompt);
327}
328
329/*
330 Goal: reconcile chat messages with available context length
331 Guidelines:
332 - Always keep last user message, system message, and tools
333 - Never allow tool output without the corresponding tool call
334 - Remove older messages first
335*/
336function compileChatMessages({
337 modelName,
338 msgs,
339 contextLength,
340 maxTokens,
341 supportsImages,
342 tools,
343}: {
344 modelName: string;
345 msgs: ChatMessage[];
346 contextLength: number;
347 maxTokens: number;
348 supportsImages: boolean;
349 tools?: Tool[];
350}): ChatMessage[] {
351 let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m }));
352
353 // If images not supported, convert MessagePart[] to string
354 if (!supportsImages) {
355 for (const msg of msgsCopy) {
356 if ("content" in msg && Array.isArray(msg.content)) {
357 const content = renderChatMessage(msg);
358 msg.content = content;
359 }
360 }
361 }
362
363 // Extract system message
364 const systemMsg = msgsCopy.find((msg) => msg.role === "system");
365 msgsCopy = msgsCopy.filter((msg) => msg.role !== "system");
366
367 // Remove any empty messages or non-user/tool trailing messages
368 msgsCopy = msgsCopy.filter((msg) => !chatMessageIsEmpty(msg));
369
370 msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
371
372 while (msgsCopy.length > 1) {
373 if (isUserOrToolMsg(msgsCopy.at(-1))) {
374 break;
375 }
376 msgsCopy.pop();
377 }
378
379 const lastUserOrToolMsg = msgsCopy.pop();
380 if (!lastUserOrToolMsg || !isUserOrToolMsg(lastUserOrToolMsg)) {
381 throw new Error("Error parsing chat history: no user/tool message found"); // should never happen
382 }
383
384 let lastToolCallsMsg: ChatMessage | undefined = undefined;
385 if (lastUserOrToolMsg.role === "tool") {
386 lastToolCallsMsg = msgsCopy.pop();
387 if (!messageHasToolCallId(lastToolCallsMsg, lastUserOrToolMsg.toolCallId)) {
388 throw new Error(
389 `Error parsing chat history: no tool call found to match tool output for id "${lastUserOrToolMsg.toolCallId}"`,
390 );
391 }
392 }
393
394 let lastMessagesTokens = countChatMessageTokens(modelName, lastUserOrToolMsg);
395 if (lastToolCallsMsg) {
396 lastMessagesTokens += countChatMessageTokens(modelName, lastToolCallsMsg);
397 }
398
399 // System message
400 let systemMsgTokens = 0;
401 if (systemMsg) {
402 systemMsgTokens = countChatMessageTokens(modelName, systemMsg);
403 }
404
405 // Tools
406 let toolTokens = 0;
407 if (tools) {
408 toolTokens = countToolsTokens(tools, modelName);
409 }
410
411 const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength);
412 const minOutputTokens = getMinResponseTokens(maxTokens);
413
414 let inputTokensAvailable = contextLength;
415
416 // Leave space for output/safety
417 inputTokensAvailable -= countingSafetyBuffer;
418 inputTokensAvailable -= minOutputTokens;
419
420 // Non-negotiable messages
421 inputTokensAvailable -= toolTokens;
422 inputTokensAvailable -= systemMsgTokens;
423 inputTokensAvailable -= lastMessagesTokens;
424
425 // Make sure there's enough context for the non-excludable items
426 if (inputTokensAvailable < 0) {
427 throw new Error(
428 `Not enough context available to include the system message, last user message, and tools.
429 There must be at least ${minOutputTokens} tokens remaining for output.
430 Request had the following token counts:
431 - contextLength: ${contextLength}
432 - counting safety buffer: ${countingSafetyBuffer}
433 - tools: ~${toolTokens}
434 - system message: ~${systemMsgTokens}
435 - last user or tool + tool call message tokens: ~${lastMessagesTokens}
436 - max output tokens: ${maxTokens}`,
437 );
438 }
439
440 // Now remove messages till we're under the limit
441 let currentTotal = 0;
442 const historyWithTokens = msgsCopy.map((message) => {
443 const tokens = countChatMessageTokens(modelName, message);
444 currentTotal += tokens;
445 return {
446 ...message,
447 tokens,
448 };
449 });
450
451 while (historyWithTokens.length > 0 && currentTotal > inputTokensAvailable) {
452 const message = historyWithTokens.shift()!;
453 currentTotal -= message.tokens;
454
455 // At this point make sure no latent tool response without corresponding call
456 while (historyWithTokens[0]?.role === "tool") {
457 const message = historyWithTokens.shift()!;
458 currentTotal -= message.tokens;
459 }
460 }
461
462 // Now reassemble
463 const reassembled: ChatMessage[] = [];
464 if (systemMsg) {
465 reassembled.push(systemMsg);
466 }
467 reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest));
468 if (lastToolCallsMsg) {
469 reassembled.push(lastToolCallsMsg);
470 }
471 reassembled.push(lastUserOrToolMsg);
472
473 // Flatten the messages (combines adjacent similar messages)
474 const flattenedHistory = flattenMessages(reassembled);
475 return flattenedHistory;
476}
477
478export {
479 compileChatMessages,
480 countTokens,
481 countTokensAsync,
482 pruneLinesFromBottom,
483 pruneLinesFromTop,
484 pruneRawPromptFromTop,
485 pruneStringFromBottom,
486 pruneStringFromTop,
487};