fix(core): cap images per request and compact on image-count errors

This commit is contained in:
Aiden Cline 2026-10-26 09:36:39 -05:00
parent 7359a48573
commit a587e8aaee
4 changed files with 117 additions and 11 deletions

View file

@ -55,6 +55,13 @@ const patterns = [
/too many tokens/i,
/token limit exceeded/i,
/request_too_large/i,
// Image-count caps: compaction drops the replayed images, so these recover the same way.
// OpenCode Console/Zen gateway
/request contains \d+ images, exceeding the maximum/i,
// Azure OpenAI
/exceeded maximum number of images/i,
// Anthropic and Bedrock
/too many images and documents/i,
]
const payloadPatterns = [/request entity too large/i, /payload too large/i, /request too large/i]

View file

@ -36,6 +36,47 @@ describe("provider error classification", () => {
expect(isContextOverflow("413 status code (no body)")).toBe(true)
})
test("classifies image-count rejections as context overflow", () => {
const cases = [
{
message:
"Error from provider (Console Go): Upstream request failed: [invalid_request_error] request contains 51 images, exceeding the maximum of 50 allowed per request",
body: {
error: {
type: "invalid_request_error",
message:
"Error from provider (Console Go): Upstream request failed: [invalid_request_error] request contains 51 images, exceeding the maximum of 50 allowed per request",
},
},
},
{
message: "Exceeded maximum number of images (50).",
body: { error: { code: "BadRequest", message: "Exceeded maximum number of images (50)." } },
},
{
message: "messages: too many images and documents: 101 > 100",
body: {
type: "error",
error: { type: "invalid_request_error", message: "messages: too many images and documents: 101 > 100" },
},
},
{
message: "The model returned the following errors: too many images and documents: 150 + 0 > 100",
body: { message: "The model returned the following errors: too many images and documents: 150 + 0 > 100" },
},
]
expect(
cases.map((item) => {
const reason = classifyProviderFailure({
message: item.message,
status: 400,
rawBody: JSON.stringify(item.body),
})
return reason._tag === "InvalidRequest" ? reason.classification : reason._tag
}),
).toEqual(["context-overflow", "context-overflow", "context-overflow", "context-overflow"])
})
test("classifies generic request size failures separately from context overflow", () => {
const failures = [
classifyProviderFailure({ message: "request too large", status: 413 }),

View file

@ -41,8 +41,14 @@ import type { SessionMessage } from "./message.js"
const IMAGE_BYTES_TRIGGER = 25 * 1024 * 1024 // 25 MiB
const IMAGE_BYTES_TARGET = 15 * 1024 * 1024 // 15 MiB
const IMAGE_REMOVED =
"[This image was removed to reduce the request size and is no longer visible. Do not make claims about its contents from memory. If needed, retrieve it again with an available tool or ask the user to attach it again.]"
// The lowest per-request image cap among supported providers is 50 (OpenCode Console/Zen, Azure OpenAI).
// A per-model limit would replace this constant; the target stays a fixed fraction of it.
const IMAGE_COUNT_TRIGGER = 40
const IMAGE_COUNT_TARGET = 30
const imageRemoved = (name: string | undefined) =>
name
? `[The image "${name}" was removed from this request and is no longer visible. Do not make claims about its contents from memory. If needed, read "${name}" again with an available tool or ask the user to attach it again.]`
: "[This image was removed from this request and is no longer visible. Do not make claims about its contents from memory. If needed, retrieve it again with an available tool or ask the user to attach it again.]"
const GENERATION_KEYS = new Set(Object.keys(GenerationOptions.fields))
// Used when the catalog has no output limit for the model.
const OUTPUT_TOKEN_FALLBACK = 32_000
@ -190,22 +196,22 @@ export const boundImages = (messages: LLMRequest["messages"]) => {
)
}),
)
// Replay the images in order, dropping the oldest down to the target whenever the kept payload passes the trigger.
// A new image then moves the cut only every (trigger - target) bytes instead of on every request, so the replaced
// prefix, and with it the provider's prompt cache, stays the same between cuts.
// Replay the images in order, dropping the oldest down to the target whenever the kept payload or count passes its
// trigger. A new image then moves the cut only every (trigger - target) bytes or images instead of on every request,
// so the replaced prefix, and with it the provider's prompt cache, stays the same between cuts.
let cut = 0
let kept = 0
for (const size of sizes) {
sizes.forEach((size, index) => {
kept += size
if (kept <= IMAGE_BYTES_TRIGGER) continue
while (kept > IMAGE_BYTES_TARGET) kept -= sizes[cut++]!
}
if (kept > IMAGE_BYTES_TRIGGER) while (kept > IMAGE_BYTES_TARGET) kept -= sizes[cut++]!
if (index + 1 - cut > IMAGE_COUNT_TRIGGER) while (index + 1 - cut > IMAGE_COUNT_TARGET) kept -= sizes[cut++]!
})
if (cut === 0) return messages
let index = 0
return replaceMedia(messages, (media) => {
if (!isImage(media.mime)) return
return index++ < cut ? IMAGE_REMOVED : undefined
return index++ < cut ? imageRemoved(media.name) : undefined
})
}

View file

@ -196,7 +196,7 @@ describe("SessionModelRequest.boundImages", () => {
const result = boundImages(messages)
expect(result[0]).toBeInstanceOf(Message)
expect(result[0]?.content).toEqual([Message.text(expect.stringContaining("image was removed"))])
expect(result[0]?.content).toEqual([Message.text(expect.stringContaining('The image "first.png" was removed'))])
expect(result[1]).toBe(text)
expect(result[2]).not.toBe(messages[2])
expect(result[2]?.content[0]).toMatchObject({ type: "text" })
@ -218,6 +218,58 @@ describe("SessionModelRequest.boundImages", () => {
expect(removed(boundImages([...history, ...Array.from({ length: 4 }, (_, i) => image(`${9 + i}.png`))]))).toBe(8)
})
test("keeps at most the newest 40 images, cutting back to 30 so the prompt cache survives", () => {
const image = (name: string) =>
Message.user({ type: "media", media: Media.base64("aGVsbG8=", "image/png"), filename: name })
const history = (count: number) => Array.from({ length: count }, (_, i) => image(`${i}.png`))
const removed = (messages: ReturnType<typeof boundImages>) =>
messages.filter((message) => message.content[0]?.type === "text").length
expect(removed(boundImages(history(40)))).toBe(0)
// The 41st image passes the trigger: the oldest 11 go, leaving 30.
expect(removed(boundImages(history(41)))).toBe(11)
// The cut holds until the kept count passes the trigger again.
expect(removed(boundImages(history(51)))).toBe(11)
expect(removed(boundImages(history(52)))).toBe(22)
})
test("names the removed file so the model can read it again", () => {
const read = (index: number) =>
Message.tool(
ToolResultPart.make({
id: `call_${index}`,
name: "read",
result: {
type: "content",
value: [
{ type: "text", text: "Image read successfully" },
{
type: "file",
uri: "data:image/png;base64,aGVsbG8=",
mime: "image/png",
name: `/tmp/shot-${index}.png`,
},
],
},
}),
)
const messages = Array.from({ length: 41 }, (_, i) => read(i))
const result = boundImages(messages)
expect(result[0]?.content[0]).toMatchObject({
type: "tool-result",
result: {
type: "content",
value: [
{ type: "text", text: "Image read successfully" },
{ type: "text", text: expect.stringContaining('read "/tmp/shot-0.png" again') },
],
},
})
expect(result[10]).not.toBe(messages[10])
expect(result[11]).toBe(messages[11])
})
test("replaces images nested in tool results", () => {
const image = "a".repeat(13 * 1024 * 1024)
const result = boundImages([