Skip to content

fix(gemini): read data URLs in linear time, send https images for Gemini to fetch, and read every block as a content filter - #342

Merged
jddunn merged 2 commits into
masterfrom
fix/gemini-image-parts
Oct 12, 2026
Merged

jddunn merged 2 commits into
masterfrom
fix/gemini-image-parts

Conversation

@jddunn

@jddunn jddunn commented Oct 12, 2026 •

Copy link
Copy Markdown
Member

Summary

GeminiProvider read an image's data URL with /^data:([^;,]+)[^,]*?(;base64)?,(.*)$/is. On a string with no comma, the greedy and lazy loops cover the same characters, so the match backtracks about n²/2 steps: a 1 MB data:AAAA... URL held the Node event loop for minutes, synchronously, before any request. A host that forwards a caller's image URL to a Gemini-backed generateText, a vision tier or a GMI turn could be stalled by one request.

Data URLs are now read as WHATWG Fetch reads them, each step linear in the URL's length:

  1. Tabs and line breaks are dropped.
  2. The media type is the text before the first comma; ;base64 may have spaces or a tab around it.
  3. The payload is percent-decoded before it is read as base64.
  4. The base64 is checked against its alphabet and length (forgiving-base64's rules, plus the URL-safe alphabet Gemini accepts).

The same change settles the other findings of the cold read on Gemini's image parts:

  • https images go to Gemini. An https URL is sent as fileData, which Gemini fetches itself, up to 15 MB a file (Google, 2026-01-12; file input methods). fileData.mimeType is optional in the v1beta API, and it is named when the path ends in an image extension. An http URL is still refused, and the provider fetches nothing.
  • The inline limit is 100 MB of base64. Google raised the payload for inline data from 20 MB to 100 MB, "base64 encoded"; the provider refused 20 MB of decoded bytes.
  • Refusals made before a request carry HTTP 400. A refused URL, a malformed data URL and too much inline data had no status, so the health registry counted them as transient Gemini failures: five opened Gemini's breaker for the whole process. With 400 they are the caller's error.
  • Every block reads as a content filter. A prompt Gemini blocks (promptFeedback.blockReason, which comes with no candidates) and an answer stopped with no content by BLOCKLIST, PROHIBITED_CONTENT, SPII or the IMAGE_ filter reasons now throw content_filter naming the reason, as SAFETY and RECITATION did. They returned an empty answer, which the vision tier read as an image with no text.

Linked issues

None: the findings come from a cold read of the 2026-10-08 changes to Gemini's image parts.

Type of change

  • Bug fix
  • Feature
  • Performance
  • Documentation
  • Refactor
  • Tests
  • Build or CI

How this was verified

CI runs the tests; nothing was run locally.

  • GeminiProvider.test.ts: the WHATWG spellings, each malformed URL refused with status 400 before any request, a 100,000-character URL with no comma refused in under a second, 30 MiB of base64 sent and 120 MiB refused, https URLs sent as fileData, and http refused.
  • GeminiProvider.safety.test.ts: a blocked prompt, the new filter finish reasons, OTHER left as a finish reason, and a blocked prompt while streaming.
  • createVisionPipeline.gemini.e2e.test.ts, through the real generateText and GeminiProvider with only fetch stubbed: an https image reaches Gemini as fileData with no other request, a blocked prompt fails the scan naming the reason, and five malformed data URLs leave Gemini's breaker closed.

The docs (LLM_PROVIDERS.md, VISION_PIPELINE.md) describe the two image routes, the limits and the block handling.

A second commit (bd75a97) keeps the usage Gemini reported on the content_filter error, as details.usage, where the fallback chain and the completion gateway read a failed attempt's tokens.

Migration notes

None: no option or type is removed. An https image URL that the provider refused now reaches Gemini as fileData, and inline images up to 100 MB of base64 per request are sent.

Checklist

  • Tests cover the changed behavior.
  • Docs are updated.
  • The title follows Conventional Commits, with ! before the colon for a change that breaks users (feat!: or feat(api)!:).
  • No secrets or private data are included.
  • Every automated review thread is settled (how).
  • I have read this change and can explain every line.

…ini to fetch, and read every block as a content filter

The data-URL pattern /^data:([^;,]+)[^,]*?(;base64)?,(.*)$/is backtracked
quadratically on a string with no comma: a 1 MB `data:AAAA...` image URL
held the event loop for minutes before any request. Data URLs are now read
as WHATWG Fetch reads them, each step linear: tabs and line breaks dropped,
the media type before the first comma, `;base64` with spaces or a tab
around it, the payload percent-decoded before it is read as base64, and the
base64 checked against its alphabet and length.

- An https image URL is sent as fileData, which Gemini fetches itself (up to
  15 MB a file); its type is named from the path's extension when it has
  one. An http URL is still refused, and the provider fetches nothing.
- The inline limit is Gemini's current 100 MB per request, counted in base64
  characters as Gemini counts it, in place of the 20 MB rule it replaced.
- The errors raised before a request (a refused URL, a malformed data URL,
  too much inline data) carry HTTP status 400, so the provider health
  registry reads them as the caller's error and they no longer open
  Gemini's breaker.
- A prompt Gemini blocks (promptFeedback.blockReason, with no candidates)
  and an answer stopped with no content by BLOCKLIST, PROHIBITED_CONTENT,
  SPII or the IMAGE_ filter reasons throw content_filter naming the reason,
  as SAFETY and RECITATION did. They returned an empty answer, which the
  vision tier read as an image with no text.
@jddunn
jddunn requested a review from Victor-Evogor as a code owner October 12, 2026 14:58
@sourcery-ai

sourcery-ai Bot commented Oct 12, 2026

Copy link
Copy Markdown

Sorry @jddunn, you've used your own review budget of 250,000 diff characters for the last 7 days.

You can request another review in 5 days and 2 hours by commenting @sourcery-ai review. Upgrade to get a review now.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-12T15:01:50.574901Z fbdd767 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: framerslab/agentos/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Team
  • Run ID: 52001ac1-935c-40c3-a59b-c61665a1e9b0

📥 Commits

Reviewing files that changed from the base of the PR and between a81d09d and bd75a97.


📒 Files selected for processing (6)
  • docs/features/LLM_PROVIDERS.md
  • docs/features/VISION_PIPELINE.md
  • src/core/llm/providers/__tests__/GeminiProvider.safety.test.ts
  • src/core/llm/providers/__tests__/GeminiProvider.test.ts
  • src/core/llm/providers/implementations/GeminiProvider.ts
  • src/io/vision/__tests__/createVisionPipeline.gemini.e2e.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.



📝 Walkthrough
📝 Walkthrough

Walkthrough

GeminiProvider now forwards supported HTTPS image URLs, validates inline data URLs, and applies a 100 MiB inline-data limit. It also reports prompt blocks and filtered responses without content as content_filter errors.

Changes

Gemini provider behavior

Layer / File(s) Summary
Gemini image input handling
src/core/llm/providers/implementations/GeminiProvider.ts, src/core/llm/providers/__tests__/GeminiProvider.test.ts, src/io/vision/__tests__/createVisionPipeline.gemini.e2e.test.ts, docs/features/VISION_PIPELINE.md
HTTPS image URLs are sent as fileData. Data URLs are validated and converted to inline image data. Inline data is limited to 100 MiB of base64 characters per request. Unit and real-provider tests cover URL forwarding, invalid inputs, size limits, and health-breaker behavior.
Gemini content-filter errors
src/core/llm/providers/implementations/GeminiProvider.ts, src/core/llm/providers/__tests__/GeminiProvider.safety.test.ts, docs/features/LLM_PROVIDERS.md
Streaming and non-streaming completions detect prompt blocks and recognized candidate filter reasons when no text or tool calls are returned. The resulting content_filter errors include available usage. Tests cover error reasons, usage, and streamed prompt blocks.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant VisionPipeline
  participant GeminiProvider
  participant GeminiAPI
  VisionPipeline->>GeminiProvider: Pass HTTPS image URL
  GeminiProvider->>GeminiAPI: Send fileData in completion request
Loading

Merge Risk: ⚪ Minimal · up to bd75a

No actionable merge-blocking issue was established; the change is mergeable after normal checks.

Pre-merge checks | Passed 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 4 files. (2 skipped: 2 …
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Title check Passed The title clearly summarizes the main Gemini changes and follows the Conventional Commits format. It is somewhat long but remains specific and readable.
Description check Passed The description includes all required template sections. It explains the changes, verification, migration impact, tests, documentation, and checklist status in sufficient detail.

✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR

🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@sourcery-ai

sourcery-ai Bot commented Oct 12, 2026

Copy link
Copy Markdown

Reviewer's Guide

Gemini image handling now uses linear-time, WHATWG-compatible data URL parsing, delegates HTTPS image fetching to Gemini, measures inline payloads against the 100 MiB base64 limit, and reports malformed inputs and all content-policy blocks as structured caller or content-filter errors. Tests cover provider behavior, streaming, vision integration, breaker health, and documentation reflects the new routes and limits.

Sequence diagram for Gemini image submission routes

sequenceDiagram
    participant Caller
    participant GeminiProvider
    participant GeminiAPI
    participant ImageHost

    Caller->>GeminiProvider: generateText(image_url)
    alt https image URL
        GeminiProvider->>GeminiProvider: imagePartOf(url)
        GeminiProvider->>GeminiAPI: generateContent(fileData.fileUri)
        GeminiAPI->>ImageHost: Fetch image
        ImageHost-->>GeminiAPI: Image bytes
    else data URL
        GeminiProvider->>GeminiProvider: imagePartOf(url)
        GeminiProvider->>GeminiAPI: generateContent(inlineData)
    else http or malformed URL
        GeminiProvider-->>Caller: GeminiProviderError(status 400)
    end
Loading

Sequence diagram for Gemini content-filter error handling

sequenceDiagram
    participant Caller
    participant GeminiProvider
    participant GeminiAPI
    participant Fallback

    Caller->>GeminiProvider: generateText()
    GeminiProvider->>GeminiAPI: generateContent()
    alt prompt blocked
        GeminiAPI-->>GeminiProvider: promptFeedback.blockReason
    else response filtered
        GeminiAPI-->>GeminiProvider: finishReason with no content
    end
    GeminiProvider->>GeminiProvider: contentFilterBlock(blockReason, finishReason)
    GeminiProvider-->>Fallback: GeminiProviderError(content_filter)
    Fallback-->>Caller: Policy-aware fallback or error
Loading

Flow diagram for linear-time Gemini data URL parsing

flowchart TD
    A[Data URL] --> B[Remove tabs and line breaks]
    B --> C[Find first comma]
    C --> D{Base64 marker?}
    D -- Yes --> E[Percent-decode payload]
    E --> F[Validate forgiving base64 alphabet and length]
    D -- No --> G[Percent-decode payload]
    G --> H[Encode bytes as base64]
    F --> I[Check non-empty payload and 100 MiB base64 limit]
    H --> I
    I --> J[Build inlineData]
Loading

File-Level Changes

Change Details Files
Replace regex-based data URL parsing with linear-time WHATWG-compatible parsing and validation.
  • Strip ASCII whitespace, split at the first comma, normalize the media type, and support spaced ;base64 markers.
  • Percent-decode payloads before forgiving-base64 validation, including URL-safe characters and padding checks.
  • Reject malformed, empty, or unsupported image URLs with structured HTTP 400 errors before any network request.
src/core/llm/providers/implementations/GeminiProvider.ts
src/core/llm/providers/__tests__/GeminiProvider.test.ts
Expand Gemini image input handling and update inline-size accounting.
  • Send HTTPS image URLs as fileData for Gemini to fetch without provider-side fetching, optionally inferring MIME types from image extensions.
  • Continue rejecting HTTP URLs and other unsupported schemes.
  • Raise the aggregate inline-data limit to 100 MiB measured in base64 characters.
src/core/llm/providers/implementations/GeminiProvider.ts
src/core/llm/providers/__tests__/GeminiProvider.test.ts
src/io/vision/__tests__/createVisionPipeline.gemini.e2e.test.ts
Surface all Gemini content-policy blocks consistently in synchronous and streaming flows.
  • Convert blocked prompts with promptFeedback.blockReason into content_filter errors naming the reason.
  • Map the additional BLOCKLIST, PROHIBITED_CONTENT, SPII, and IMAGE_* finish reasons to content_filter when no content is returned.
  • Preserve non-filter finish reasons and filter responses that still contain text.
src/core/llm/providers/implementations/GeminiProvider.ts
src/core/llm/providers/__tests__/GeminiProvider.safety.test.ts
src/io/vision/__tests__/createVisionPipeline.gemini.e2e.test.ts
Document the new Gemini image routes, limits, validation behavior, and block handling.
  • Describe HTTPS fileData handling and provider-versus-Gemini fetching responsibilities.
  • Document data URL inline limits and HTTP 400 behavior for caller input errors.
  • Document prompt and response content-filter failures.
docs/features/LLM_PROVIDERS.md
docs/features/VISION_PIPELINE.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

…or the request

The fallback chain and the completion gateway read a failed attempt's
tokens from error.details.usage. The content_filter errors carried none, so
a blocked Gemini attempt's billed prompt tokens were left out of fallback
results and session ledgers. Both the completion and the streaming path now
attach the usage they mapped.
@jddunn
jddunn merged commit ad4df66 into master Oct 12, 2026
12 checks passed
@jddunn
jddunn deleted the fix/gemini-image-parts branch October 12, 2026 15:36
github-actions Bot pushed a commit that referenced this pull request Oct 12, 2026
## [0.13.69](v0.13.68...v0.13.69) (2026-10-12)

### fix

* **gateway:** onFallback reports the most recent error, as the walkers do (#348) ([c1b4847](c1b4847))
* **gemini:** read data URLs in linear time, send https images for Gemini to fetch, and read every block as a content filter (#342) ([ad4df66](ad4df66))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant