Elffuss BraidHub

kikocis/continue public

71fd2e7d4456 · 12.6 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 return gptAsyncEncoder;
64 }
65 return llamaAsyncEncoder;
66}
67
68function 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
82function countImageTokens(content: MessagePart): number {
83 if (content.type === "imageUrl") {
84 return 85;
85 }
86 throw new Error("Non-image content type");
87}
88
89async 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
107function 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
128function 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
172function 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
213function pruneLinesFromTop(
214 prompt: string,
215 maxTokens: number,
216 modelName: string,
217): string {
218 let totalTokens = countTokens(prompt, modelName);
219 const lines = prompt.split("\n");
220 while (totalTokens > maxTokens && lines.length > 0) {
221 totalTokens -= countTokens(lines.shift()!, modelName);
222 }
223
224 return lines.join("\n");
225}
226
227function pruneLinesFromBottom(
228 prompt: string,
229 maxTokens: number,
230 modelName: string,
231): string {
232 let totalTokens = countTokens(prompt, modelName);
233 const lines = prompt.split("\n");
234 while (totalTokens > maxTokens && lines.length > 0) {
235 totalTokens -= countTokens(lines.pop()!, modelName);
236 }
237
238 return lines.join("\n");
239}
240
241function pruneStringFromBottom(
242 modelName: string,
243 maxTokens: number,
244 prompt: string,
245): string {
246 const encoding = encodingForModel(modelName);
247
248 const tokens = encoding.encode(prompt, "all", []);
249 if (tokens.length <= maxTokens) {
250 return prompt;
251 }
252
253 return encoding.decode(tokens.slice(0, maxTokens));
254}
255
256function pruneStringFromTop(
257 modelName: string,
258 maxTokens: number,
259 prompt: string,
260): string {
261 const encoding = encodingForModel(modelName);
262
263 const tokens = encoding.encode(prompt, "all", []);
264 if (tokens.length <= maxTokens) {
265 return prompt;
266 }
267
268 return encoding.decode(tokens.slice(tokens.length - maxTokens));
269}
270
271const MAX_TOKEN_SAFETY_BUFFER = 1000;
272const TOKEN_SAFETY_PROPORTION = 0.02;
273function getTokenCountingBufferSafety(contextLength: number) {
274 return Math.min(
275 MAX_TOKEN_SAFETY_BUFFER,
276 contextLength * TOKEN_SAFETY_PROPORTION,
277 );
278}
279
280const MIN_RESPONSE_TOKENS = 1000;
281function getMinResponseTokens(maxTokens: number) {
282 return Math.min(MIN_RESPONSE_TOKENS, maxTokens);
283}
284
285function pruneRawPromptFromTop(
286 modelName: string,
287 contextLength: number,
288 prompt: string,
289 tokensForCompletion: number,
290): string {
291 const maxTokens =
292 contextLength -
293 tokensForCompletion -
294 getTokenCountingBufferSafety(contextLength);
295 return pruneStringFromTop(modelName, maxTokens, prompt);
296}
297
298/*
299 Goal: reconcile chat messages with available context length
300 Guidelines:
301 - Always keep last user message, system message, and tools
302 - Never allow tool output without the corresponding tool call
303 - Remove older messages first
304*/
305function compileChatMessages({
306 modelName,
307 msgs,
308 contextLength,
309 maxTokens,
310 supportsImages,
311 tools,
312}: {
313 modelName: string;
314 msgs: ChatMessage[];
315 contextLength: number;
316 maxTokens: number;
317 supportsImages: boolean;
318 tools?: Tool[];
319}): ChatMessage[] {
320 let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m }));
321
322 // If images not supported, convert MessagePart[] to string
323 if (!supportsImages) {
324 for (const msg of msgsCopy) {
325 if ("content" in msg && Array.isArray(msg.content)) {
326 const content = renderChatMessage(msg);
327 msg.content = content;
328 }
329 }
330 }
331
332 // Extract system message
333 const systemMsg = msgsCopy.find((msg) => msg.role === "system");
334 msgsCopy = msgsCopy.filter((msg) => msg.role !== "system");
335
336 // Remove any empty messages or non-user/tool trailing messages
337 msgsCopy = msgsCopy.filter((msg) => !chatMessageIsEmpty(msg));
338
339 msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
340
341 while (msgsCopy.length > 1) {
342 if (isUserOrToolMsg(msgsCopy.at(-1))) {
343 break;
344 }
345 msgsCopy.pop();
346 }
347
348 const lastUserOrToolMsg = msgsCopy.pop();
349 if (!lastUserOrToolMsg || !isUserOrToolMsg(lastUserOrToolMsg)) {
350 throw new Error("Error parsing chat history: no user/tool message found"); // should never happen
351 }
352
353 let lastToolCallsMsg: ChatMessage | undefined = undefined;
354 if (lastUserOrToolMsg.role === "tool") {
355 lastToolCallsMsg = msgsCopy.pop();
356 if (!messageHasToolCallId(lastToolCallsMsg, lastUserOrToolMsg.toolCallId)) {
357 throw new Error(
358 `Error parsing chat history: no tool call found to match tool output for id "${lastUserOrToolMsg.toolCallId}"`,
359 );
360 }
361 }
362
363 let lastMessagesTokens = countChatMessageTokens(modelName, lastUserOrToolMsg);
364 if (lastToolCallsMsg) {
365 lastMessagesTokens += countChatMessageTokens(modelName, lastToolCallsMsg);
366 }
367
368 // System message
369 let systemMsgTokens = 0;
370 if (systemMsg) {
371 systemMsgTokens = countChatMessageTokens(modelName, systemMsg);
372 }
373
374 // Tools
375 let toolTokens = 0;
376 if (tools) {
377 toolTokens = countToolsTokens(tools, modelName);
378 }
379
380 const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength);
381 const minOutputTokens = getMinResponseTokens(maxTokens);
382
383 let inputTokensAvailable = contextLength;
384
385 // Leave space for output/safety
386 inputTokensAvailable -= countingSafetyBuffer;
387 inputTokensAvailable -= minOutputTokens;
388
389 // Non-negotiable messages
390 inputTokensAvailable -= toolTokens;
391 inputTokensAvailable -= systemMsgTokens;
392 inputTokensAvailable -= lastMessagesTokens;
393
394 // Make sure there's enough context for the non-excludable items
395 if (inputTokensAvailable < 0) {
396 throw new Error(
397 `Not enough context available to include the system message, last user message, and tools.
398 There must be at least ${minOutputTokens} tokens remaining for output.
399 Request had the following token counts:
400 - contextLength: ${contextLength}
401 - counting safety buffer: ${countingSafetyBuffer}
402 - tools: ~${toolTokens}
403 - system message: ~${systemMsgTokens}
404 - last user or tool + tool call message tokens: ~${lastMessagesTokens}
405 - max output tokens: ${maxTokens}`,
406 );
407 }
408
409 // Now remove messages till we're under the limit
410 let currentTotal = 0;
411 const historyWithTokens = msgsCopy.map((message) => {
412 const tokens = countChatMessageTokens(modelName, message);
413 currentTotal += tokens;
414 return {
415 ...message,
416 tokens,
417 };
418 });
419
420 while (historyWithTokens.length > 0 && currentTotal > inputTokensAvailable) {
421 const message = historyWithTokens.shift()!;
422 currentTotal -= message.tokens;
423
424 // At this point make sure no latent tool response without corresponding call
425 while (historyWithTokens[0]?.role === "tool") {
426 const message = historyWithTokens.shift()!;
427 currentTotal -= message.tokens;
428 }
429 }
430
431 // Now reassemble
432 const reassembled: ChatMessage[] = [];
433 if (systemMsg) {
434 reassembled.push(systemMsg);
435 }
436 reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest));
437 if (lastToolCallsMsg) {
438 reassembled.push(lastToolCallsMsg);
439 }
440 reassembled.push(lastUserOrToolMsg);
441
442 // Flatten the messages (combines adjacent similar messages)
443 const flattenedHistory = flattenMessages(reassembled);
444 return flattenedHistory;
445}
446
447export {
448 compileChatMessages,
449 countTokens,
450 countTokensAsync,
451 pruneLinesFromBottom,
452 pruneLinesFromTop,
453 pruneRawPromptFromTop,
454 pruneStringFromBottom,
455 pruneStringFromTop,
456};