diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index b742d70b0f0..f295ae3ed21 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -20,6 +20,7 @@ import { AsyncEncoder, LlamaAsyncEncoder } from "./asyncEncoder.js"; import { DEFAULT_PRUNING_LENGTH } from "./constants.js"; import { getAdjustedTokenCountFromModel } from "./getAdjustedTokenCount.js"; import llamaTokenizer from "./llamaTokenizer.js"; +import { withCachedMessageTokens } from "./tokenCountCache.js"; interface Encoding { encode: Tiktoken["encode"]; decode: Tiktoken["decode"]; @@ -179,6 +180,19 @@ function countToolsTokens(tools: Tool[], modelName: string): number { function countChatMessageTokens( modelName: string, chatMessage: ChatMessage, +): number { + // Memoised: this is a pure function of (modelName, chatMessage), and the + // compiler calls it for every message on every request. Without the cache a + // long session re-tokenises its whole history each turn, blocking the + // extension host for seconds. See tokenCountCache.ts. + return withCachedMessageTokens(modelName, chatMessage, () => + computeChatMessageTokens(modelName, chatMessage), + ); +} + +function computeChatMessageTokens( + modelName: string, + chatMessage: ChatMessage, ): number { // Doing simpler, safer version of what is here: // https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb diff --git a/core/llm/tokenCountCache.test.ts b/core/llm/tokenCountCache.test.ts new file mode 100644 index 00000000000..ab4dd5a9cde --- /dev/null +++ b/core/llm/tokenCountCache.test.ts @@ -0,0 +1,201 @@ +import { ChatMessage } from "../index.js"; +import { + __resetTokenCountCacheForTests, + getTokenCountCacheKeysForTests, + getTokenCountCacheStats, + withCachedMessageTokens, +} from "./tokenCountCache.js"; + +describe("tokenCountCache", () => { + beforeEach(() => { + __resetTokenCountCacheForTests(); + }); + + const msg = (content: string): ChatMessage => + ({ role: "user", content }) as ChatMessage; + + it("computes on first call and serves the second from cache", () => { + let calls = 0; + const compute = () => { + calls++; + return 42; + }; + + expect(withCachedMessageTokens("m", msg("hello"), compute)).toBe(42); + expect(calls).toBe(1); + + expect(withCachedMessageTokens("m", msg("hello"), compute)).toBe(42); + expect(calls).toBe(1); // still 1 - served from cache + + const stats = getTokenCountCacheStats(); + expect(stats.hits).toBe(1); + expect(stats.misses).toBe(1); + }); + + // The compiler rebuilds message objects on every call + // (`msgs.map((m) => ({ ...m }))`), and messages also cross the messenger + // boundary as JSON. Identity-keyed caching (WeakMap) can therefore never + // hit; the key must be derived from content. + it("hits across distinct object instances with equal content", () => { + let calls = 0; + const compute = () => { + calls++; + return 7; + }; + + withCachedMessageTokens( + "m", + { role: "user", content: "abc" } as ChatMessage, + compute, + ); + withCachedMessageTokens( + "m", + { role: "user", content: "abc" } as ChatMessage, + compute, + ); + + expect(calls).toBe(1); + }); + + it("does not confuse different content", () => { + const compute = (n: number) => () => n; + + expect(withCachedMessageTokens("m", msg("aaa"), compute(1))).toBe(1); + expect(withCachedMessageTokens("m", msg("bbb"), compute(2))).toBe(2); + expect(withCachedMessageTokens("m", msg("aaa"), compute(99))).toBe(1); + }); + + it("keys on model - the same text tokenizes differently per tokenizer", () => { + const compute = (n: number) => () => n; + + expect(withCachedMessageTokens("llama", msg("x"), compute(10))).toBe(10); + expect(withCachedMessageTokens("gpt-4", msg("x"), compute(20))).toBe(20); + expect(withCachedMessageTokens("llama", msg("x"), compute(99))).toBe(10); + }); + + it("distinguishes messages that differ only by role", () => { + const compute = (n: number) => () => n; + + const user = { role: "user", content: "same" } as ChatMessage; + const assistant = { role: "assistant", content: "same" } as ChatMessage; + + expect(withCachedMessageTokens("m", user, compute(1))).toBe(1); + expect(withCachedMessageTokens("m", assistant, compute(2))).toBe(2); + }); + + it("distinguishes tool calls that differ only in arguments", () => { + const compute = (n: number) => () => n; + + const call = (args: string) => + ({ + role: "assistant", + content: "", + toolCalls: [ + { + id: "1", + type: "function", + function: { name: "f", arguments: args }, + }, + ], + }) as ChatMessage; + + expect(withCachedMessageTokens("m", call('{"a":1}'), compute(1))).toBe(1); + expect(withCachedMessageTokens("m", call('{"a":2}'), compute(2))).toBe(2); + }); + + // The entry-count cap alone does not bound memory: a key that embeds full + // message content means 4096 large tool outputs can retain hundreds of MiB + // (a 1MB message x 4096 is ~4 GiB) long after the conversation is released. + // Keys are fixed-size digests so worst-case memory is a function of the cap + // alone, and raw prompt/tool text is not retained by the cache. + // `stripImages` joins text parts with `.join("\n")`, which renders an absent + // `text` as "". A key that interpolates `part.text` instead produces + // "undefined", so a part with no text and a part whose text is literally + // "undefined" share a key - and one is served the other's count. + it("separates a text part with absent text from the literal string 'undefined'", () => { + const part = (text?: string): ChatMessage => + ({ + role: "user", + content: [ + text === undefined ? { type: "text" } : { type: "text", text }, + ], + }) as unknown as ChatMessage; + + expect(withCachedMessageTokens("m", part(undefined), () => 1)).toBe(1); + expect(withCachedMessageTokens("m", part("undefined"), () => 2)).toBe(2); + + // And each keeps its own count on the way back out. + expect(withCachedMessageTokens("m", part(undefined), () => 99)).toBe(1); + expect(withCachedMessageTokens("m", part("undefined"), () => 99)).toBe(2); + }); + + // Absent text and empty-string text DO normalize together, matching + // `stripImages` - they tokenize identically, so sharing a key is correct. + it("treats absent text and empty text as the same message", () => { + const absent = { + role: "user", + content: [{ type: "text" }], + } as unknown as ChatMessage; + const empty = { + role: "user", + content: [{ type: "text", text: "" }], + } as unknown as ChatMessage; + + let calls = 0; + withCachedMessageTokens("m", absent, () => { + calls++; + return 5; + }); + expect( + withCachedMessageTokens("m", empty, () => { + calls++; + return 6; + }), + ).toBe(5); + expect(calls).toBe(1); + }); + + it("stores fixed-size keys regardless of message size", () => { + const small = msg("x"); + const huge = msg("y".repeat(2 * 1024 * 1024)); + + withCachedMessageTokens("m", small, () => 1); + withCachedMessageTokens("m", huge, () => 2); + + const keys = getTokenCountCacheKeysForTests(); + expect(keys).toHaveLength(2); + + const [a, b] = keys.map((k) => k.length); + expect(a).toBe(b); + // Comfortably smaller than either message; a content-embedding key would + // be megabytes here. + expect(a).toBeLessThan(512); + }); + + it("does not retain raw message content in its keys", () => { + const secret = "correct-horse-battery-staple-" + "z".repeat(5000); + withCachedMessageTokens("m", msg(secret), () => 1); + + for (const key of getTokenCountCacheKeysForTests()) { + expect(key).not.toContain("correct-horse-battery-staple"); + } + }); + + it("evicts oldest entries past the cap so a long session cannot grow unbounded", () => { + const cap = getTokenCountCacheStats().maxEntries; + + for (let i = 0; i < cap + 50; i++) { + withCachedMessageTokens("m", msg(`msg-${i}`), () => i); + } + + expect(getTokenCountCacheStats().size).toBeLessThanOrEqual(cap); + + // The most recent entries must still be present. + let calls = 0; + withCachedMessageTokens("m", msg(`msg-${cap + 49}`), () => { + calls++; + return -1; + }); + expect(calls).toBe(0); + }); +}); diff --git a/core/llm/tokenCountCache.ts b/core/llm/tokenCountCache.ts new file mode 100644 index 00000000000..b026ab5dee0 --- /dev/null +++ b/core/llm/tokenCountCache.ts @@ -0,0 +1,155 @@ +import { createHash } from "crypto"; + +import { ChatMessage } from "../index.js"; + +/** + * Memoises per-message token counts across `compileChatMessages` calls. + * + * Why this exists: the chat tokenizer for non-GPT models is a pure-JS BPE + * (`llamaTokenizer`) running synchronously on the extension host, and nothing + * cached its results. Every request re-tokenised the entire conversation from + * scratch, so turn N paid for all N-1 previous turns again. Measured at ctx + * 288768, a 20-turn session with 128KB tool outputs spent ~4.5s in + * `compileChatMessages` before a single byte reached the model - the host was + * blocked the whole time, which VS Code reports as an unresponsive extension. + * + * Keyed on content rather than object identity: `compileChatMessages` rebuilds + * every message (`msgs.map((m) => ({ ...m }))`) and messages cross the + * messenger boundary as JSON, so a `WeakMap` keyed on the object would never + * hit. Token counts are a pure function of (model, message), so a content key + * is exact - not an approximation. + */ + +// Keys are fixed-size digests, so this entry cap really does bound worst-case +// memory. That is the reason for hashing: an earlier version embedded message +// content in the key, where 4096 entries of large tool outputs could retain +// gigabytes long after the conversation itself was released. +const MAX_ENTRIES = 4096; + +const cache = new Map(); +let hits = 0; +let misses = 0; + +/** + * Builds the cache key: a SHA-256 digest over the fields that affect the count. + * + * Hashing keeps keys fixed-size, which is what makes the entry cap a real + * memory bound, and avoids retaining raw prompt or tool-output text in a + * long-lived map. The digest is cheap relative to the work being cached - + * ~0.66ms for 1MB versus ~3187ms to tokenize the same text - so it does not + * erode the win. + * + * SHA-256 collisions are not a practical concern at this cache size. They are + * not harmless, though: a wrong count feeds the pruning loop in + * `compileChatMessages`, so it can drop a message that would have fit or let an + * over-long prompt through. The argument is that the probability is negligible, + * not that the consequence is. + * + * Only the fields `countChatMessageTokens` actually counts are included. + */ +function cacheKey(modelName: string, message: ChatMessage): string { + const parts: string[] = [modelName, message.role]; + + const content = message.content; + if (typeof content === "string") { + parts.push(content); + } else if (Array.isArray(content)) { + for (const part of content) { + // `stripImages` collects text parts with `.join("\n")`, which renders an + // absent `text` as "" - so the key must too. Interpolating it instead + // would produce "undefined" and collide with a part whose text is + // literally "undefined", serving one the other's count. + if (part.type === "text") { + parts.push("t:", part.text ?? ""); + } else { + // Image parts contribute a flat token count, so their presence matters + // but their payload does not - avoid keying on base64 blobs. + parts.push("i:", part.type); + } + } + } + + if ("toolCalls" in message && message.toolCalls) { + for (const call of message.toolCalls) { + parts.push(JSON.stringify(call)); + } + } + + if (message.role === "thinking") { + if (message.redactedThinking) parts.push(message.redactedThinking); + if (message.signature) parts.push(message.signature); + } + + if (message.role === "tool" && message.toolCallId) { + parts.push(message.toolCallId); + } + + // Length-prefix each part before hashing: any delimiter can also occur + // inside message content, which would let one message forge another's key + // and return a wrong token count. + const hash = createHash("sha256"); + for (const part of parts) { + hash.update(`${part.length}:`); + hash.update(part); + } + return hash.digest("base64"); +} + +/** + * Returns the cached token count for `message`, or computes and stores it. + * + * `compute` must be a pure function of the same (modelName, message) pair. + */ +export function withCachedMessageTokens( + modelName: string, + message: ChatMessage, + compute: () => number, +): number { + const key = cacheKey(modelName, message); + + const cached = cache.get(key); + if (cached !== undefined) { + hits++; + // Refresh recency: re-inserting moves the key to the end of Map iteration + // order, so eviction below drops genuinely cold entries rather than merely + // old ones. + cache.delete(key); + cache.set(key, cached); + return cached; + } + + misses++; + const value = compute(); + cache.set(key, value); + + if (cache.size > MAX_ENTRIES) { + // Map preserves insertion order, so the first key is the least recently + // used. Evict in a loop: a single delete is not enough if the cap is + // lowered or several entries are added before the next check. + for (const oldest of cache.keys()) { + cache.delete(oldest); + if (cache.size <= MAX_ENTRIES) break; + } + } + + return value; +} + +export function getTokenCountCacheStats(): { + size: number; + hits: number; + misses: number; + maxEntries: number; +} { + return { size: cache.size, hits, misses, maxEntries: MAX_ENTRIES }; +} + +export function getTokenCountCacheKeysForTests(): string[] { + return [...cache.keys()]; +} + +export function __resetTokenCountCacheForTests(): void { + cache.clear(); + hits = 0; + misses = 0; +}