-
Notifications
You must be signed in to change notification settings - Fork 19
fix(images): correct image media types that disagree with their bytes #176
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ian-de-marcellus
wants to merge
1
commit into
anima-research:main
Choose a base branch
from
ian-de-marcellus:fix/image-media-type-sniff
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| - Image blocks whose declared `media_type` disagrees with their bytes (e.g. a | ||
| PNG labeled `image/webp` by an upstream surface) are corrected from the | ||
| magic bytes at compile time. The provider rejects any request with such a | ||
| mismatch, so one mislabeled image used to fail every subsequent turn. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| import type { ContentBlock, NormalizedMessage } from '@animalabs/membrane'; | ||
|
|
||
| /** Detect an image's real format from its leading bytes. */ | ||
| export function sniffImageMediaTypeBase64(data: string): string | undefined { | ||
| const head = Buffer.from(data.slice(0, 32), 'base64'); | ||
| if (head.length >= 4 && head[0] === 0x89 && head[1] === 0x50 && head[2] === 0x4e && head[3] === 0x47) return 'image/png'; | ||
| if (head.length >= 3 && head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff) return 'image/jpeg'; | ||
| if (head.length >= 3 && head[0] === 0x47 && head[1] === 0x49 && head[2] === 0x46) return 'image/gif'; | ||
| if ( | ||
| head.length >= 12 && | ||
| head[0] === 0x52 && head[1] === 0x49 && head[2] === 0x46 && head[3] === 0x46 && | ||
| head[8] === 0x57 && head[9] === 0x45 && head[10] === 0x42 && head[11] === 0x50 | ||
| ) return 'image/webp'; | ||
| return undefined; | ||
| } | ||
|
|
||
| /** | ||
| * Correct base64 image blocks whose declared media type doesn't match their | ||
| * bytes (e.g. Discord serving a PNG for an attachment it labels image/webp). | ||
| * The provider rejects the WHOLE request on a mismatch, so one mislabelled | ||
| * image in history would fail every turn. Returns new message/block objects | ||
| * for anything changed; stored history is never touched. | ||
| */ | ||
| export function correctImageMediaTypes(messages: NormalizedMessage[]): NormalizedMessage[] { | ||
| let changed = 0; | ||
| const fix = (blocks: ContentBlock[]): ContentBlock[] => { | ||
| let touched = false; | ||
| const out = blocks.map((block) => { | ||
| const b = block as { type: string; source?: { type?: string; data?: string; mediaType?: string }; content?: unknown }; | ||
| if (b.type === 'image' && b.source?.type === 'base64' && typeof b.source.data === 'string') { | ||
| const actual = sniffImageMediaTypeBase64(b.source.data); | ||
| if (actual && actual !== b.source.mediaType) { | ||
| touched = true; | ||
| changed++; | ||
| return { ...block, source: { ...b.source, mediaType: actual } } as ContentBlock; | ||
| } | ||
| } | ||
| if (b.type === 'tool_result' && Array.isArray(b.content)) { | ||
| const inner = fix(b.content as ContentBlock[]); | ||
| if (inner !== b.content) { | ||
| touched = true; | ||
| return { ...block, content: inner } as ContentBlock; | ||
| } | ||
| } | ||
| return block; | ||
| }); | ||
| return touched ? out : blocks; | ||
| }; | ||
| const result = messages.map((m) => { | ||
| const content = fix(m.content); | ||
| return content === m.content ? m : { ...m, content }; | ||
| }); | ||
| if (changed > 0) console.error(`[images] corrected media type on ${changed} image block(s) whose bytes disagreed with their label`); | ||
| return result; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| import { test } from 'node:test'; | ||
| import assert from 'node:assert/strict'; | ||
| import { correctImageMediaTypes } from '../src/image-media-type.js'; | ||
|
|
||
| const PNG_B64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4////fwAJ+wP9KobjigAAAABJRU5ErkJggg=='; | ||
|
|
||
| test('corrects a PNG labelled image/webp, including inside tool_result, without mutating input', () => { | ||
| const img = { type: 'image', source: { type: 'base64', data: PNG_B64, mediaType: 'image/webp' } }; | ||
| const messages = [ | ||
| { participant: 'user', content: [{ type: 'text', text: 'look' }, img] }, | ||
| { participant: 'user', content: [{ type: 'tool_result', toolUseId: 't', content: [img] }] }, | ||
| ] as never; | ||
| const out = correctImageMediaTypes(messages) as unknown as Array<{ content: any[] }>; | ||
| assert.equal(out[0].content[1].source.mediaType, 'image/png'); | ||
| assert.equal(out[1].content[0].content[0].source.mediaType, 'image/png'); | ||
| assert.equal(img.source.mediaType, 'image/webp', 'stored block untouched'); | ||
| }); | ||
|
|
||
| test('leaves correct and unknown images alone (same objects)', () => { | ||
| const messages = [{ participant: 'user', content: [ | ||
| { type: 'image', source: { type: 'base64', data: PNG_B64, mediaType: 'image/png' } }, | ||
| { type: 'image', source: { type: 'base64', data: 'AAAA', mediaType: 'image/png' } }, | ||
| ] }] as never; | ||
| assert.equal(correctImageMediaTypes(messages)[0], (messages as any)[0]); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
image/webp, the framework passes the image directly to the existing stream for the next inference round. That round does not recompile the context, so this correction never runs on the tool result and the provider can still reject the request. Correct image blocks at the live continuation boundary too.Prompt To Fix With AI