Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

tech(CS-1): Bilder zählen als Pauschale, nicht als Base64-Text — keine 256-Token-Antworten mehr

David21e67a1580e8
diff --git a/src/api/__tests__/provider-openai.test.ts b/src/api/__tests__/provider-openai.test.ts
index 439b4708..e7943543 100644
--- a/src/api/__tests__/provider-openai.test.ts
+++ b/src/api/__tests__/provider-openai.test.ts
@@ -440,6 +440,113 @@ describe('OpenAIProvider', () => {
vi.restoreAllMocks()
})
+ // ── Audit CS-1: a base64 attachment must not eat the completion budget ──
+ //
+ // applyMaxTokens estimated the prompt with
+ // `JSON.stringify(body.messages).length / 4`, and body.messages carries the
+ // full `data:<mime>;base64,...` URL by then. A 100 KB screenshot is ~137 KB
+ // of base64 → ~34 000 phantom tokens, which is more than the whole window of
+ // every model at or below 32k (built-in engine, LM Studio, llama.cpp, vLLM,
+ // KoboldCpp). ctxLen - promptTokens - RESERVE went negative, the 256 floor
+ // won, and every answer with an image attached was cut off at 256 tokens.
+ //
+ // Base64 chars for a `kb`-KB source image: 4 chars per 3 bytes.
+ const base64Payload = (kb: number) => 'A'.repeat(Math.round((kb * 1024 * 4) / 3))
+
+ async function maxTokensFor(
+ model: string,
+ messages: any[],
+ options?: any,
+ ): Promise<number> {
+ const provider = new OpenAIProvider(makeConfig())
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
+ new Response(JSON.stringify({
+ choices: [{ message: { content: 'ok' }, finish_reason: 'stop' }],
+ }), { status: 200 })
+ )
+ await provider.chatWithTools(model, messages, [], options)
+ const sent = JSON.parse((fetchSpy.mock.calls[0][1] as any).body)
+ vi.restoreAllMocks()
+ return sent.max_tokens
+ }
+
+ it('does not starve max_tokens to the 256 floor because of an image (CS-1)', async () => {
+ // mixtral-8x7b-32768 → 32768 ctx, the exact class of model that broke.
+ const maxTokens = await maxTokensFor('mixtral-8x7b-32768', [{
+ role: 'user',
+ content: 'what is in this screenshot?',
+ images: [{ data: base64Payload(100), mimeType: 'image/png' }],
+ }])
+ // Before the fix this was exactly 256.
+ expect(maxTokens).toBeGreaterThan(25000)
+ expect(maxTokens).toBeLessThanOrEqual(32768)
+ })
+
+ it('charges the flat image rate once per image (CS-1)', async () => {
+ const one = await maxTokensFor('mixtral-8x7b-32768', [{
+ role: 'user',
+ content: 'compare these',
+ images: [{ data: base64Payload(80), mimeType: 'image/png' }],
+ }])
+ const three = await maxTokensFor('mixtral-8x7b-32768', [{
+ role: 'user',
+ content: 'compare these',
+ images: [
+ { data: base64Payload(80), mimeType: 'image/png' },
+ { data: base64Payload(120), mimeType: 'image/jpeg' },
+ { data: base64Payload(40), mimeType: 'image/webp' },
+ ],
+ }])
+ // Two extra images = two extra flat allowances (1500 each), plus a few
+ // tokens for the placeholder parts themselves — NOT a size-driven blowup.
+ const delta = one - three
+ expect(delta).toBeGreaterThanOrEqual(3000)
+ expect(delta).toBeLessThan(3100)
+ })
+
+ it('counts images that ride along in the history, not just the last turn (CS-1)', async () => {
+ const maxTokens = await maxTokensFor('mixtral-8x7b-32768', [
+ { role: 'user', content: 'turn 1', images: [{ data: base64Payload(150), mimeType: 'image/png' }] },
+ { role: 'assistant', content: 'a screenshot' },
+ { role: 'user', content: 'turn 2', images: [{ data: base64Payload(150), mimeType: 'image/png' }] },
+ { role: 'assistant', content: 'another one' },
+ { role: 'user', content: 'and now?' },
+ ])
+ expect(maxTokens).toBeGreaterThan(25000)
+ expect(maxTokens).toBeLessThanOrEqual(32768)
+ })
+
+ it('still sends the full base64 image on the wire and does not mutate the messages (CS-1)', async () => {
+ const provider = new OpenAIProvider(makeConfig())
+ const data = base64Payload(20)
+ const messages: any[] = [{
+ role: 'user',
+ content: 'look',
+ images: [{ data, mimeType: 'image/png' }],
+ }]
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
+ new Response(JSON.stringify({
+ choices: [{ message: { content: 'ok' }, finish_reason: 'stop' }],
+ }), { status: 200 })
+ )
+ await provider.chatWithTools('mixtral-8x7b-32768', messages, [])
+ const sent = JSON.parse((fetchSpy.mock.calls[0][1] as any).body)
+ const part = sent.messages.at(-1).content.find((p: any) => p.type === 'image_url')
+ expect(part.image_url.url).toBe(`data:image/png;base64,${data}`)
+ // The estimator must be read-only.
+ expect(messages[0].images[0].data).toBe(data)
+ vi.restoreAllMocks()
+ })
+
+ it('leaves the text-only clamp untouched — a huge TEXT prompt still hits the floor (CS-1)', async () => {
+ // Same character count as the 100 KB image above, but real text. Text
+ // costs tokens, so the guard must still starve the budget here.
+ const maxTokens = await maxTokensFor('mixtral-8x7b-32768', [
+ { role: 'user', content: 'x'.repeat(Math.round((100 * 1024 * 4) / 3)) },
+ ])
+ expect(maxTokens).toBe(256)
+ })
+
it('handles response with no tool calls', async () => {
const provider = new OpenAIProvider(makeConfig())
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.ts
index 0f307fc0..4b21ea01 100644
--- a/src/api/providers/openai-provider.ts
+++ b/src/api/providers/openai-provider.ts
@@ -172,6 +172,59 @@ function keyForUnindexedDelta(
return Math.max(0, accum.size - 1)
}
+/**
+ * Flat token cost charged for one inline image during prompt estimation.
+ *
+ * Audit CS-1: a base64 data URL is ~1.37 characters per byte of source image,
+ * so a single 100 KB screenshot adds ~137 000 characters to `body.messages` —
+ * ~34 000 phantom "tokens" under the chars/4 rule, which is more than the ENTIRE
+ * window of every model at or below 32k (the built-in engine, LM Studio,
+ * llama.cpp, vLLM, KoboldCpp). The headroom subtraction then went negative and
+ * the 256 floor won, capping every answer with an attachment at 256 tokens —
+ * and getting worse each turn, because images ride along in the history.
+ *
+ * Images do not cost characters, they cost tiles. OpenAI bills a 1024x1024
+ * image at ~1100 tokens; Qwen2-VL / llava-style mmproj projectors on local
+ * servers land in the same order of magnitude, and vision backends generally
+ * cap a single image near 1.5k. 1500 is the conservative end of that range:
+ * over-estimating only shortens the completion cap a little, under-estimating
+ * risks the server rejecting the request outright.
+ */
+const IMAGE_TOKEN_ESTIMATE = 1500
+
+/**
+ * Serialized size of a request payload with every inline image replaced by a
+ * placeholder, plus how many images were found.
+ *
+ * Pure: the value is walked through JSON.stringify's replacer, so `messages`
+ * is never mutated and the body that goes on the wire keeps its full images.
+ * Recognises the OpenAI part shape (`{ type: 'image_url', image_url: {...} }`),
+ * the Anthropic-style `{ type: 'image', source: {...} }`, and any bare base64
+ * data URL string, wherever they sit in the history.
+ */
+function measurePayload(value: unknown): { chars: number; images: number } {
+ let images = 0
+ const json = JSON.stringify(value, (_key, val) => {
+ if (typeof val === 'string' && val.startsWith('data:') && val.includes(';base64,')) {
+ images++
+ return ''
+ }
+ if (val && typeof val === 'object' && !Array.isArray(val)) {
+ const part = val as Record<string, any>
+ if (part.type === 'image_url') {
+ images++
+ return { type: 'image_url' }
+ }
+ if (part.type === 'image' && part.source) {
+ images++
+ return { type: 'image' }
+ }
+ }
+ return val
+ })
+ return { chars: json ? json.length : 0, images }
+}
+
/** Test-only: reset the endpoint catalogue between test cases. */
export function __clearContextCatalogForTests(): void {
catalogContext.clear()
@@ -437,9 +490,15 @@ export class OpenAIProvider implements ProviderClient {
return
}
const RESERVE = 512
- const promptChars =
- JSON.stringify(body.messages || '').length + JSON.stringify(body.tools || '').length
- const promptTokens = Math.ceil(promptChars / 4)
+ // Audit CS-1: count characters WITHOUT the base64 image payloads and charge
+ // a flat per-image rate instead — see IMAGE_TOKEN_ESTIMATE. Counting the
+ // data URLs as text made one screenshot look like ~34k tokens and starved
+ // max_tokens down to the 256 floor on every model with a small window.
+ const msgPayload = measurePayload(body.messages || '')
+ const toolPayload = measurePayload(body.tools || '')
+ const promptChars = msgPayload.chars + toolPayload.chars
+ const promptTokens =
+ Math.ceil(promptChars / 4) + (msgPayload.images + toolPayload.images) * IMAGE_TOKEN_ESTIMATE
const headroom = Math.max(256, ctxLen - promptTokens - RESERVE)
// Audit E6: an UNSET budget used to send the whole remaining window as
// max_tokens — six figures on a 128k model. Servers that validate