Skip to content

fix(openrouter): use dedicated /api/v1/images endpoint for image generation - #101367

Merged
shakkernerd merged 3 commits into
openclaw:mainfrom
Robinnnnn:openrouter-images-endpoint
Aug 15, 2026
Merged

shakkernerd merged 3 commits into
openclaw:mainfrom
Robinnnnn:openrouter-images-endpoint

Conversation

@Robinnnnn

@Robinnnnn Robinnnnn commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

OpenClaw's OpenRouter image generation currently goes through /chat/completions, treating image models as chat models and scraping images out of chat responses with ~300 lines of custom parsing. OpenRouter now ships a dedicated, OpenAI-compatible images endpoint (POST /api/v1/images), which is the supported path for image generation going forward and returns images in the standard data[].b64_json shape.

Why This Change Was Made

The OpenRouter provider is rebuilt on the shared createOpenAiCompatibleImageGenerationProvider() factory — the same one used by xAI, DeepInfra, and LiteLLM — so it inherits the common auth, base-URL/config, timeout, SSRF, and response-size handling instead of maintaining a parallel implementation. Two small, backwards-compatible additions to shared code support this:

  • A new optional endpointPath option on the factory, so a provider can target a flat path like /api/v1/images instead of the default /images/generations + /images/edits split. The path is appended to the resolved base URL; leading and duplicate slashes are normalized (both "images" and "/images" resolve to <baseUrl>/images), documented on the option and covered by factory tests (string, leading-slash, and per-mode function forms). Providers that don't set it behave exactly as before.
  • The shared OpenAI-compatible response parser now reads media_type as a fallback when mime_type is absent (OpenRouter labels the image MIME type media_type). mime_type still wins when present, so other providers are unaffected.

The request body maps model, prompt, n, plus aspect_ratio/resolution for Gemini image models and input_references (data URLs) for image-to-image. The custom chat-completions parsing (extractOpenRouterImagesFromResponse and friends) is deleted.

The OpenRouter provider also enables the factory's magic-byte MIME sniffing: live testing showed the API omits media_type for PNG responses but can also return JPEG bytes without it, so sniffing keeps returned assets correctly labeled (an explicit media_type still takes precedence).

User Impact

OpenRouter image generation and image editing keep working with the same configuration and models, now against OpenRouter's supported dedicated endpoint. Gemini image models gain aspect-ratio and resolution control, and multi-image references are passed through natively. No config changes are required.

Evidence

Tests

  • pnpm vitest run extensions/openrouter/image-generation-provider.test.ts — 8 passed
  • pnpm vitest run src/image-generation/ — 53 passed (includes the shared factory tests, endpointPath normalization tests, and a media_type fallback test)
  • pnpm vitest run extensions/{xai,deepinfra,litellm,openai}/image-generation-provider.test.ts — factory consumers unaffected, all passed
  • pnpm tsgo:extensions:test and pnpm tsgo:test:src — clean (covers the check-test-types CI lane)
  • oxlint + oxfmt clean on all changed files

Live behavior proof (redacted)

Raw endpoint contract — curl -X POST https://openrouter.ai/api/v1/images with {"model":"google/gemini-3.1-flash-image-preview","prompt":"a red bicycle leaning against a brick wall","n":1,"aspect_ratio":"1:1"} (API key redacted). HTTP 200; response with b64_json elided:

{
  "created": 0,
  "usage": { "total_tokens": 1128 },
  "data": [
    {
      "media_type": "(absent — PNG default)",
      "b64_json_len": 3049104,
      "b64_json_prefix": "iVBORw0KGgoA"
    }
  ]
}

(iVBORw0KGgo is the base64 of the PNG magic bytes 89 50 4E 47.)

End-to-end through this PR's provider code — a small driver script imports buildOpenRouterImageGenerationProvider() from this branch and calls generateImage() twice against the live API (text-to-image, then image-to-image feeding the first output back as a reference image):

text-to-image  result: model=google/gemini-3.1-flash-image-preview mime=image/jpeg bytes=803555  magic=ffd8ffe0
image-to-image result: model=google/gemini-3.1-flash-image-preview mime=image/png  bytes=2020751 magic=89504e47

Both calls hit https://openrouter.ai/api/v1/images (flat path, no /images/generations suffix), decoded to valid images (file reports PNG image data, 1024 x 1024 / JPEG), and the reported mime matches the actual magic bytes — including the JPEG case where the API omitted media_type, which is what motivated enabling sniffMimeType.

Related Issues

None of these are literally "migrate to /api/v1/images", but this PR directly advances three open feature requests (referenced as related, not closed by this PR):

Lineage: #55066 (the original OpenRouter image provider this PR migrates) and #79535 (OpenRouter media-generation gaps) are the closed history behind the current implementation.

@clawsweeper

clawsweeper Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 15, 2026, 3:11 PM ET / 19:11 UTC.

ClawSweeper review

What this changes

The PR sends official OpenRouter image requests to its dedicated images endpoint, retains chat-completions for custom bases, and updates focused tests and user docs.

Merge readiness

⚠️ Ready for maintainer review - 4 items remain

Keep open. Current main still uses OpenRouter chat completions for image generation, while the current PR head routes official OpenRouter bases to /api/v1/images, preserves custom proxy routing, and addresses the prior batch-failure and legacy-base findings.

Priority: P1
Reviewed head: dd19d814992227006075ee79f942fe88a78632c5

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The current head resolves the prior route and batch-failure blockers with focused coverage and credible live provider proof.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR body provides redacted live endpoint and branch-level text-to-image and image-to-image output, including decoded MIME-byte checks.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body provides redacted live endpoint and branch-level text-to-image and image-to-image output, including decoded MIME-byte checks.
Evidence reviewed 9 items Current main behavior: Current main sends all OpenRouter image requests to the chat-completions route, so it does not implement the PR's dedicated-endpoint behavior.
Current-head route and batch semantics: The PR normalizes official and legacy OpenRouter bases, fans out the bounded batch to single-image dedicated requests, and rejects the whole batch when any request fails so runtime fallback remains available.
Compatibility owner contract: The existing OpenRouter normalizer recognizes both official base URLs and canonicalizes the legacy /v1 form to /api/v1; the PR reuses that contract before choosing the dedicated route.
Findings None None.
Security None None.

How this fits together

The OpenRouter plugin registers an image provider used by the shared image-generation runtime. It turns tool requests into provider HTTP calls and returns generated media assets for saving and delivery.

flowchart LR
  A[Image generation tool] --> B[Shared image runtime]
  B --> C[OpenRouter image provider]
  C --> D{Official or custom base}
  D -->|Official| E[Dedicated images endpoint]
  D -->|Custom proxy| F[Chat-completions endpoint]
  E --> G[Generated media assets]
  F --> G
Loading

Before merge

  • Resolve merge risk (P1) - Merging changes the default OpenRouter image transport; custom bases and the legacy official base need the tested routing split to avoid breaking proxy users.
  • Resolve merge risk (P1) - Production code is net +98 lines; it is contained in the OpenRouter plugin because the flat endpoint and proxy split do not justify a new shared plugin-SDK API for one provider.
  • Resolve merge risk (P1) - Independent upstream documentation could not be fetched from this reviewer environment, so a maintainer should compare the current endpoint reference with the supplied live proof before merge.
  • Complete next step (P2) - No remaining mechanical repair is identified; await exact-head CI and normal maintainer confirmation of the external API contract.
Agent review details

Security

None.

PR surface

Source +98, Tests +65, Docs +8. Total +171 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 1 99 1 +98
Tests 1 136 71 +65
Docs 2 14 6 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 249 78 +171

Review metrics

Metric Value Why it matters
Production versus tests production +98/-1; tests +136/-71; docs +14/-6 The added provider-local adapter is substantial for a fix, but avoids adding a shared SDK surface for a single flat-path provider endpoint.

Merge-risk options

Maintainer options:

  1. Confirm the transport split before merge (recommended)
    After exact-head CI is green, compare the current OpenRouter images-endpoint reference with the supplied live proof and retain chat-completions only for configured custom bases.
  2. Pause on endpoint-contract uncertainty
    If the current OpenRouter contract cannot be confirmed, pause the routing change rather than replacing the established default transport.

Technical review

Best possible solution:

Retain the plugin-local official/custom routing split, land after exact-head CI is green, and confirm the current OpenRouter endpoint contract against the contributor's live evidence.

Do we have a high-confidence way to reproduce the issue?

Yes—source inspection shows current main uses chat completions and the PR changes that branch; the PR also includes redacted live after-fix evidence. Local execution was unavailable because the read-only environment prevented Corepack from creating its cache.

Is this the best way to solve the issue?

Yes—the final plugin-local adapter is preferable to widening the shared image-provider API for one provider-specific flat endpoint, provided the external contract is reconfirmed before merge.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against dbc2356abc9a.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body provides redacted live endpoint and branch-level text-to-image and image-to-image output, including decoded MIME-byte checks.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: The change repairs the default image-generation transport for an active provider and affects configured user workflows.
  • merge-risk: 🚨 compatibility: Official and custom OpenRouter base URLs intentionally take different image routes, so an incorrect classification could break existing proxy configurations.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body provides redacted live endpoint and branch-level text-to-image and image-to-image output, including decoded MIME-byte checks.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides redacted live endpoint and branch-level text-to-image and image-to-image output, including decoded MIME-byte checks.

Evidence

What I checked:

Likely related people:

  • steipete: Current main's official-base normalization is attributed to the OpenRouter catalog history, including the proxy-transport hardening commit. (role: recent area contributor; confidence: high; commits: c77ee5ba37ce, 830ab164ef86; files: extensions/openrouter/provider-catalog.ts, extensions/openrouter/image-generation-provider.ts)
  • shakkernerd: Recent compatibility commits on this PR and prior OpenRouter catalog work connect this person to the routing boundary. (role: recent compatibility contributor; confidence: medium; commits: 23b0daedb473, dd19d8149922, 8ba52acc41c0; files: extensions/openrouter/image-generation-provider.ts, extensions/openrouter/image-generation-provider.test.ts, docs/providers/openrouter.md)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Wait for exact-head CI, then confirm the current upstream images-endpoint contract before merge.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (14 earlier review cycles; latest 8 shown)
  • reviewed 2026-07-31T00:01:57.524Z sha 91df3b95d896d42835f8bbd6e6ec50a706030f8a :: needs maintainer review before merge. :: none
  • reviewed 2026-08-04T05:07:22.006Z sha 91df3b95d896d42835f8bbd6e6ec50a706030f8a :: found issues before merge. :: [P1] Preserve OpenRouter request transport settings
  • reviewed 2026-08-12T07:58:06.607Z sha 91df3b95d896d42835f8bbd6e6ec50a706030f8a :: found issues before merge. :: [P1] Preserve OpenRouter’s configured image transport | [P2] Rebase the image configuration example to the current contract
  • reviewed 2026-08-15T11:47:19.974Z sha 8eb5ef97bd5480de228d567a068ce77380fedd74 :: found issues before merge. :: [P1] Do not preempt configured image fallbacks | [P2] Remove the release-owned changelog entry
  • reviewed 2026-08-15T16:17:49.482Z sha f730f271303c3d9fab239fd2db10fe700d491d9c :: found issues before merge. :: [P1] Preserve custom-base image compatibility | [P2] Update the image tool guide for the new endpoint
  • reviewed 2026-08-15T16:48:45.146Z sha 8052ad8b662d0f0db9f1474add9bce3f259aad3c :: found issues before merge. :: [P1] Preserve configured image proxy routes | [P2] Remove the release-owned changelog entry
  • reviewed 2026-08-15T18:38:33.266Z sha 819e1e5bb16a42b86b85c58380ceca4d59d02e73 :: needs changes before merge. :: [P2] Normalize the legacy OpenRouter base before routing images
  • reviewed 2026-08-15T18:49:13.632Z sha d5755b50d89519a54b68bf4f5ee742fafbbd8850 :: needs changes before merge. :: [P1] Fail the requested batch when an image request fails | [P2] Normalize the official legacy base before selecting its route

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Jul 7, 2026
@Robinnnnn

Copy link
Copy Markdown
Contributor Author

Addressed all three P1/P2 items from the review:

  • check-test-types (TS2322 at image-generation-provider.test.ts:259) — fixed in 509dea40: the hoisted resolveApiKeyForProvider mock now has an explicit Promise<{ apiKey: string | undefined }> return type, so the missing-key test compiles. Verified locally with pnpm tsgo:extensions:test and pnpm tsgo:test:src.
  • endpointPath normalization — also in 509dea40: resolveEndpointUrl now trims leading slashes from the resolved path, so "/images" and "images" both resolve to <baseUrl>/images with no double-slash. The behavior is documented on the option's JSDoc and covered by three new factory tests (plain string, leading slash, per-mode function).
  • Live behavior proof — the PR body now includes a redacted live transcript: a raw curl POST https://openrouter.ai/api/v1/images (HTTP 200, response shape with b64_json elided) plus an end-to-end run through this branch's buildOpenRouterImageGenerationProvider().generateImage() for both text-to-image and image-to-image, showing decoded image sizes and magic bytes.

One follow-up found during the live run (bcd48866): the API can return JPEG bytes without a media_type field, so the OpenRouter provider now enables the factory's existing magic-byte MIME sniffing (explicit media_type still wins), with a unit test.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 7, 2026
@openclaw-barnacle openclaw-barnacle Bot added the docs Improvements or additions to documentation label Jul 8, 2026
@Robinnnnn

Copy link
Copy Markdown
Contributor Author

Addressed the remaining P3 docs finding in 91df3b95: docs/providers/openrouter.md now describes the dedicated POST /api/v1/images flow — request shape (model, prompt, n, Gemini-only aspect_ratio/resolution hints, input_references for edits) and response handling (b64_json + optional media_type, with magic-byte sniffing when it's absent). Verified locally with pnpm format:docs:check and pnpm docs:check-mdx.

The endpointPath SDK-surface question is left as-is for maintainer decision per the review.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@Robinnnnn

Copy link
Copy Markdown
Contributor Author

@vincentkoc @RomneyDa @shakkernerd would appreciate a review here!

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jul 23, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 4, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Aug 5, 2026
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. label Aug 12, 2026
@shakkernerd
shakkernerd force-pushed the openrouter-images-endpoint branch from 91df3b9 to 8eb5ef9 Compare August 15, 2026 11:40
@shakkernerd
shakkernerd force-pushed the openrouter-images-endpoint branch 2 times, most recently from 8052ad8 to 819e1e5 Compare August 15, 2026 18:32
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. and removed P1 High-priority user-facing bug, regression, or broken workflow. labels Aug 15, 2026
@shakkernerd
shakkernerd force-pushed the openrouter-images-endpoint branch from 819e1e5 to d5755b5 Compare August 15, 2026 18:42
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. and removed P2 Normal backlog priority with limited blast radius. labels Aug 15, 2026
@shakkernerd
shakkernerd force-pushed the openrouter-images-endpoint branch from d5755b5 to dd19d81 Compare August 15, 2026 19:04
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 15, 2026
@shakkernerd
shakkernerd force-pushed the openrouter-images-endpoint branch from dd19d81 to cb2d825 Compare August 15, 2026 19:40
@shakkernerd
shakkernerd force-pushed the openrouter-images-endpoint branch from cb2d825 to 8f807ae Compare August 15, 2026 19:42
@shakkernerd
shakkernerd merged commit 8f807ae into openclaw:main Aug 15, 2026
9 checks passed
@shakkernerd

Copy link
Copy Markdown
Contributor

Fixed: OpenRouter image generation now uses the dedicated images endpoint for official bases while preserving custom proxy compatibility.

With thanks to @Robinnnnn.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation extensions: openrouter merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants