Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(chat): count a tool image as a fixed token cost in the context trimmer
thinhlpg0180206b5f65
diff --git a/web-app/src/lib/__tests__/context-manager.test.ts b/web-app/src/lib/__tests__/context-manager.test.tsindex 14f2ad42f..4318c1a48 100644--- a/web-app/src/lib/__tests__/context-manager.test.ts+++ b/web-app/src/lib/__tests__/context-manager.test.ts@@ -8,6 +8,7 @@ import {deriveToolOutputCap,type ContextManagerConfig,} from '../context-manager'+import { encodeToolImageSentinel } from '../tool-image-sentinel'function makeMessage(id: string,@@ -70,6 +71,72 @@ describe('estimateMessageTokens', () => {const tokens = estimateMessageTokens(msg)expect(tokens).toBe(4) // just overhead})++ // An image is a fixed, small cost to the model however many base64+ // characters carry it; counting those characters would evict the user's+ // question from a local model's window as soon as a tool returned a picture.+ describe('tool images', () => {+ const b64 = 'A'.repeat(1_500_000)+ const toolMessage = (output: unknown): UIMessage =>+ ({+ id: 'a1',+ role: 'assistant',+ parts: [+ {+ type: 'tool-read_media_file',+ toolCallId: 'c1',+ state: 'output-available',+ input: { path: '/a.png' },+ output,+ },+ ],+ }) as unknown as UIMessage++ it('does not count the base64 of an MCP image result', () => {+ const tokens = estimateMessageTokens(+ toolMessage([{ type: 'image', data: b64, mimeType: 'image/png' }])+ )+ expect(tokens).toBeLessThan(10_000)+ expect(tokens).toBeGreaterThan(0)+ })++ it('does not count the base64 of a tool image sentinel', () => {+ const tokens = estimateMessageTokens(+ toolMessage(+ `Screenshot${encodeToolImageSentinel(`data:image/png;base64,${b64}`)}`+ )+ )+ expect(tokens).toBeLessThan(10_000)+ })++ it('still counts the text that rides with an image', () => {+ const text = 'caption '.repeat(2_000)+ const withImage = estimateMessageTokens(+ toolMessage([+ { type: 'text', text },+ { type: 'image', data: b64, mimeType: 'image/png' },+ ])+ )+ const imageOnly = estimateMessageTokens(+ toolMessage([{ type: 'image', data: b64, mimeType: 'image/png' }])+ )+ expect(withImage - imageOnly).toBeGreaterThanOrEqual(estimateTokens(text))+ })++ it('keeps the question that led to an image result in the window', () => {+ const messages = [+ makeMessage('u1', 'user', 'what is in the frame?'),+ toolMessage([{ type: 'image', data: b64, mimeType: 'image/png' }]),+ ]+ const { messages: kept, trimmedCount } = trimMessages(messages, {+ maxContextTokens: 16_384,+ maxOutputTokens: 2_048,+ autoCompact: false,+ })+ expect(trimmedCount).toBe(0)+ expect(kept).toHaveLength(2)+ })+ })})describe('trimMessages', () => {diff --git a/web-app/src/lib/context-manager.ts b/web-app/src/lib/context-manager.tsindex 153c1ee1b..6c2110461 100644--- a/web-app/src/lib/context-manager.ts+++ b/web-app/src/lib/context-manager.ts@@ -1,5 +1,6 @@import type { UIMessage } from '@ai-sdk/react'import { generateText, type LanguageModel } from 'ai'+import { stripToolImageSentinels } from './tool-image-sentinel'/*** Approximate token count using a character-based heuristic.@@ -41,13 +42,33 @@ export function deriveToolOutputCap()}+/**+ * What one tool-result image costs the model. Vision encoders turn an image+ * into a roughly fixed number of tokens, not one per base64 character, so+ * counting the characters would put a 1 MB screenshot at hundreds of thousands+ * of tokens and evict the user's question from the window.+ */+const TOOL_IMAGE_TOKENS = 2_000+const TOOL_IMAGE_STAND_IN = 'x'.repeat(+ Math.ceil(TOOL_IMAGE_TOKENS * CHARS_PER_TOKEN)+)+function messageToText(message: UIMessage): string {const parts: string[] = []for (const part of message.parts) {if (part.type === 'text') {parts.push(part.text)} else if (part.type === 'dynamic-tool' || part.type.startsWith('tool-')) {- parts.push(JSON.stringify(part))+ // Swap each image's base64 for a stand-in of `TOOL_IMAGE_TOKENS`. An+ // image takes two forms in a tool output: an MCP `{ type: 'image',+ // data }` item and an inline tool image sentinel inside a string.+ parts.push(+ JSON.stringify(part, function (this: { type?: unknown }, key, value) {+ if (typeof value !== 'string') return value+ if (key === 'data' && this.type === 'image') return TOOL_IMAGE_STAND_IN+ return stripToolImageSentinels(value, TOOL_IMAGE_STAND_IN)+ })+ )}}