Skip to content

feat: support Vercel AI SDK v7 - #511

Merged
robert-j-y merged 8 commits into
OpenRouterTeam:mainfrom
Shreyaan:feat/support-ai-sdk-v7
Jul 6, 2026
Merged

robert-j-y merged 8 commits into
OpenRouterTeam:mainfrom
Shreyaan:feat/support-ai-sdk-v7

Conversation

@Shreyaan

Copy link
Copy Markdown
Contributor

Fixes #510.

Design choice

Chose (A) v7-only. AI SDK v7 is Node >=22 and ESM-only, and first-party v7-line providers such as @ai-sdk/openai@4 target @ai-sdk/provider@4 V4 interfaces. Keeping v6 support would require compatibility branching around provider/model specs, file payloads, tool factories, packaging, and usage shapes, so this is a major release.

Summary

  • Bumps ai to ^7, @ai-sdk/provider to ^4, and @ai-sdk/provider-utils to ^5; peers on ai@^7.0.0.
  • Migrates chat and completion language models to LanguageModelV4, including V4 content/file payloads, provider tools, reasoning, structured outputs, cache-control passthrough, tool calls, and stream lifecycle events.
  • Migrates embedding, image, and video models to the V4 spec. Video tests now pass the required generateAudio call option.
  • Updates OpenRouter web search to createProviderDefinedToolFactory / ProviderDefinedToolFactory.
  • Publishes ESM-only output with type: module, Node >=22, and no CommonJS export branch.
  • Preserves OpenRouter usage accounting, reasoning details, cache control/cached-token handling, tool calling, structured outputs, BYOK cost metadata, and provider options.

Usage/token remapping

Provider usage now follows the V4 internal shape: inputTokens.cacheRead/cacheWrite/noCache and outputTokens.reasoning/text. In AI SDK v7 public results, cached input tokens are read from usage.inputTokenDetails.cacheReadTokens and reasoning tokens from usage.outputTokenDetails.reasoningTokens; OpenRouter-specific usage details remain under providerMetadata.openrouter.usage.

Local checks

Baseline on upstream main before migration:

pnpm typecheck && pnpm build && pnpm test
Test Files 21 passed (21)
Tests 427 passed (427)

Final checks on this branch:

pnpm stylecheck
Checked 133 files in 140ms. No fixes applied.

pnpm typecheck
tsc --noEmit

pnpm build
ESM dist/index.js     179.58 KB
ESM dist/internal/index.js     170.70 KB
DTS dist/index.d.ts 31.30 KB
DTS dist/internal/index.d.ts 25.47 KB

pnpm test:node
Test Files 21 passed (21)
Tests 427 passed (427)

pnpm test:edge
Test Files 21 passed (21)
Tests 427 passed (427)

pnpm test:e2e and pnpm test:issues were not run because they hit the real OpenRouter API and require OPENROUTER_API_KEY.

Release notes

  • Added a major changeset.
  • Updated README and CHANGELOG for AI SDK v7, Node 22, ESM-only packaging, and v7 usage token details.

@Shreyaan

Copy link
Copy Markdown
Contributor Author

Review/context after the final two follow-up commits:

  • 1e01a81 updates CI and publish workflows from Node 20.x to 22.x, matching the new engines.node >=22 requirement from AI SDK v7.
  • a3e097f updates live e2e issue tests for AI SDK v7 semantics: allowSystemInMessages: true where those regression tests intentionally place cache-control system messages in messages[], and include: { responseBody: true } where the test asserts result.response.body.
  • Retired Anthropic model slugs were intentionally not changed in this PR; tracked separately in e2e tests pin retired Anthropic model slugs → 404 "No endpoints found" #512.
  • Live-model edge cases left open for maintainers/follow-up: issue-194 (grok invalid JSON), issue-248 (gemini web-search empty), issue-438 (gemini reasoning redacted). These look model/API-behavior dependent rather than core v7 migration blockers.

Fresh local checks run on the final 3-commit branch:

  • pnpm stylecheck ✅ Checked 133 files in 154ms. No fixes applied.
  • pnpm typecheck ✅ tsc --noEmit
  • pnpm build ✅ ESM build + DTS build succeeded
  • pnpm test:node ✅ Test Files 21 passed (21), Tests 427 passed (427)
  • pnpm test:edge ✅ Test Files 21 passed (21), Tests 427 passed (427)

As expected for a fork PR, GitHub Actions have not started yet because the first workflow run needs maintainer approval.

@Shreyaan
Shreyaan marked this pull request as ready for review June 25, 2026 22:31

@perry-the-pr-reviewer perry-the-pr-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perry's Review

Migrates the OpenRouter provider to Vercel AI SDK v7 (the v4 provider model interfaces, a tagged file-data union, ESM-only output, Node 22) as a v7-only major release.

Verdict: 🔁 Needs changes

Details

Risk: 🟡 Medium — major-version breaking release touching the streaming/usage path, but the changes are structural type renames plus a well-tested file-part shape migration.

CI: ⚠️ The repo CI workflow shows action_required (awaiting maintainer approval for an external contributor — not a code failure). However, I reproduced a hard install failure locally that CI will hit once it runs — see the blocker below.

Findings (see inline comment):

  • 🔴 package.json:68 — the lockfile was not regenerated after the zod peer-range bump, so pnpm install fails under CI's default frozen-lockfile.

What I verified locally (Node 22.23, pnpm 10.12):

  • frozen-lockfile install fails with ERR_PNPM_OUTDATED_LOCKFILE (zod specifier mismatch).
  • After a no-frozen-lockfile install (1-line lockfile change), everything is green: typecheck passes, node tests 427/427 pass, edge tests 427/427 pass, build succeeds with ESM-only output.
  • The getFileDataUrl switch (data / url / text / reference + exhaustive never default) matches the SharedV4FileData union in the v4 provider package.
  • getToolResultContent and mapToolResultContentParts cover all v4 output and content member types; the removed image-data / image-url / file-data / file-url / file-id cases no longer exist in v4.
  • computeTokenUsage and emptyUsage match the structured v4 usage shape (inputTokens / outputTokens objects).
  • The provider-defined tool factory exports exist in provider-utils v5 (the issue #474 export path).
  • No leftover V3 type references remain in non-test source.

Codex (heavy second-opinion): no additional valid findings.

Analysis lanes: no valid net-new findings (candidates were stale restatements of the migration itself).

Research: Verified the v4 type surface directly against the published v4 provider and v5 provider-utils type declarations (unpkg) rather than from memory — the file-data union, usage shape, tool-result output union, and tool-factory exports all line up with the diff.

Security: Touches the streaming response path and file/media handling (categories 2, 4). No credential handling, auth, or tenant-isolation changes; the file-data union rewrite preserves the prior data-URL/base64 behavior (confirmed by the passing chat tests). No concerns.

Test coverage: Excellent — every test file was migrated to the v4 file-part shape and all 854 node and edge assertions pass against the new SDK.

Unresolved threads: none

Scope: first review (full)
Review: tier=large · model=claude-opus-latest · score=10.5

Comment thread package.json Resolved
@Shreyaan

Copy link
Copy Markdown
Contributor Author

Local CodeRabbit CLI review result:

Initial run found 3 issues, all addressed in follow-up commit 1486aef:

  • cross-platform build cleanup: changed clean away from POSIX-only rm now that build invokes clean directly
  • V4 file URL validation: { type: "url" } file data now accepts only http:, https:, and data: URLs; rejects file:/blob: before request construction
  • completion streaming V4 contract: emits { type: "stream-start", warnings: [] } before completion stream parts

Fresh local checks after the fix commit:

  • pnpm stylecheck ✅ Checked 133 files in 380ms. No fixes applied.
  • pnpm typecheck ✅ tsc --noEmit
  • pnpm build ✅ ESM + DTS build succeeded
  • pnpm test:node ✅ Test Files 21 passed (21), Tests 429 passed (429)
  • pnpm test:edge ✅ Test Files 21 passed (21), Tests 429 passed (429)

Reran local CodeRabbit CLI against the full branch (coderabbit review --agent --type all --base upstream/main) after the fixes: ✅ review_completed, findings: 0.

@perry-the-pr-reviewer
perry-the-pr-reviewer Bot dismissed their stale review June 25, 2026 23:10

Superseded by updated Perry review

perry-the-pr-reviewer[bot]

This comment was marked as outdated.

@Shreyaan

Copy link
Copy Markdown
Contributor Author

Final local + live retest update:

Final PR-state checks run after reverting all temporary live-test slug changes:

  • pnpm format ✅ Formatted 133 files in 74ms. No fixes applied.
  • pnpm install --frozen-lockfile ✅ Lockfile is up to date, resolution step is skipped
  • pnpm stylecheck ✅ Checked 133 files in 103ms. No fixes applied.
  • pnpm typecheck ✅ tsc --noEmit
  • pnpm build ✅ ESM + DTS build succeeded
  • pnpm test:node ✅ Test Files 21 passed (21), Tests 429 passed (429)
  • pnpm test:edge ✅ Test Files 21 passed (21), Tests 429 passed (429)

Live API checks with temporary local slug/output-cap substitutions:

  • pnpm test:e2e ✅ Test Files 12 passed (12), Tests 26 passed (26)
  • Initial pnpm test:issues progressed to 38 passed files, 145 passed tests, 4 skipped; failures were limited to 6 files.
  • Targeted rerun of failed issue files with current/cheaper slugs and explicit output caps:
    • issue-194 (x-ai/grok-4-fast → x-ai/grok-4.3) ✅ 3/3 passed
    • issue-196 (allowSystemInMessages, current Anthropic slug, output cap) ✅ 1/1 passed
    • issue-248 (current/capped Anthropic web-search cases) ✅ 4 passed, 3 skipped
    • issue-453 (capped Anthropic signature cases) ✅ 4/4 passed
    • issue-190 still timed out: 2/2 timed out at 120s even with openai/gpt-4.1-nano and maxOutputTokens: 100
    • issue-438 still failed: Gemini response did not include reasoning.encrypted details, so both assertions expecting encrypted details failed

The temporary live-test substitutions were not committed; the branch is clean and still only contains the 5 PR commits.

@Shreyaan

Copy link
Copy Markdown
Contributor Author

Follow-up for Perry's non-blocking stream-start symmetry note:

  • Chat doStream now emits the same initial { type: "stream-start", warnings: [] } part as completion doStream.
  • The returned warnings array is shared with the stream-start part, matching the V4 stream warning surface.
  • Updated exact chat stream expectations for text, tool, file, error, and parse-error paths.

Fresh verification after commit b3e696b:

  • pnpm format ✅ Formatted 133 files in 176ms. No fixes applied.
  • pnpm install --frozen-lockfile ✅ Lockfile is up to date, resolution step is skipped
  • pnpm stylecheck ✅ Checked 133 files in 120ms. No fixes applied.
  • pnpm typecheck ✅ tsc --noEmit
  • pnpm build ✅ ESM + DTS build succeeded
  • pnpm test:node ✅ Test Files 21 passed (21), Tests 429 passed (429)
  • pnpm test:edge ✅ Test Files 21 passed (21), Tests 429 passed (429)

@Shreyaan
Shreyaan force-pushed the feat/support-ai-sdk-v7 branch from b3e696b to 5a01929 Compare June 25, 2026 23:25
Shreyaan added 6 commits June 26, 2026 04:56
ai@7 is ESM-only and requires Node >=22; package.json now declares
engines.node >=22, so the CI and publish workflows must match to avoid
running install/test/build on an unsupported Node version.
- v7 rejects {role:'system'} in messages[] by default; the cache-control
  tests intentionally attach cacheControl to a system message, so they now
  pass allowSystemInMessages: true (issue-234, issue-341, issue-389).
- v7 excludes response bodies by default; opt in via
  include: { responseBody: true } so result.response.body is populated (issue-432).
@Shreyaan
Shreyaan force-pushed the feat/support-ai-sdk-v7 branch from 5a01929 to 777f517 Compare June 25, 2026 23:26
perry-the-pr-reviewer[bot]

This comment was marked as outdated.

@Shreyaan

Copy link
Copy Markdown
Contributor Author

Heads up: I force-pushed this branch only to fix commit attribution.

All commits are now authored by the personal Shreyaan account instead of my work account. The source tree is unchanged from the previous PR tip; this was a history/metadata rewrite only.

No new code changes were introduced by the force-push.

perry-the-pr-reviewer[bot]

This comment was marked as outdated.

perry-the-pr-reviewer[bot]

This comment was marked as outdated.

@yonatan-shorani

Copy link
Copy Markdown

Hi, any update on this PR?

@Shreyaan

Copy link
Copy Markdown
Contributor Author

Hi, any update on this PR?

waiting on any feedback or update 😅

@yonatan-shorani yonatan-shorani mentioned this pull request Jul 1, 2026
@bdezso

bdezso commented Jul 1, 2026

Copy link
Copy Markdown

any update? 🔔

@ahmed-mkacher

Copy link
Copy Markdown

Just here to spread word that we also need this, this is a desired PR. thank you for your work! 🙌

@garshythoel

Copy link
Copy Markdown

Tagging @robert-j-y @Robinnnnn - apologies if not the right people, just saw y'all have committed recently

@cursor

cursor Bot commented Jul 4, 2026

Copy link
Copy Markdown

Bugbot is not enabled for this team, so this pull request was not reviewed.

Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs.

@Shreyaan

Shreyaan commented Jul 4, 2026

Copy link
Copy Markdown
Contributor Author

Small follow-up pushed: while rerunning the live issue tests, I found one more AI SDK v7 semantics case in issue-196.

That test intentionally sends a system role inside messages[] to verify cache-control behavior. AI SDK v7 rejects system messages there unless allowSystemInMessages: true is set, matching the earlier fixes for the other cache-control issue tests. I added that flag only for this regression test.

Reverified locally after the push:

  • pnpm install --frozen-lockfile
  • pnpm format
  • pnpm stylecheck
  • pnpm typecheck
  • pnpm build
  • pnpm test:node — 432/432
  • pnpm test:edge — 432/432

Could a maintainer approve the workflow run for the latest fork push when convenient?

@perry-the-pr-reviewer perry-the-pr-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perry's Review

Incremental re-review of the AI SDK v7 migration. Since my last review at b1e685d, the sole delta is one added line in the issue-196 1-hour-cache e2e regression test, enabling the AI SDK v7 opt-in that permits a system-role entry inside the messages array.

Verdict: 💬 Comments / questions

Details

Scope: incremental — 1 new line since prior review (b1e685d → 9e2941c)

Risk: 🟢 Low — test-only change; no production code touched since last review.

Delta reviewed: the added flag is the correct AI SDK v7 requirement. In v7, a system-role message placed inside the messages array is rejected by default (opting in also carries a documented prompt-injection caveat when the messages array is user-controlled). Here the content is static test fixture data, so the opt-in is safe, and this regression test must keep the exact message structure the issue reported — so switching to the top-level system property would change what is under test. The change is consistent with the sibling cache e2e tests, which set the same flag.

CI: the repo CI workflow is in an action_required state on the head SHA (a GitHub gate awaiting maintainer approval to run for this contributor), not a check failure. No failing checks. Perry does not gate its verdict on CI — branch protection handles merge-blocking.

Findings: none on the delta. No net-new nits regenerated on already-reviewed code (differential-scope re-review).

Codex (heavy second opinion): ran; all surfaced items target chat adapter code that is unchanged since the prior review — out of differential scope, not re-litigated here.

Analysis lanes: no verified findings.

Research: confirmed against the AI SDK v7 prompts docs — system messages in the messages array are opt-in via this flag in v7; the top-level system/instructions property is the alternative for non-reproduction cases.

Security: no concerns — test-only, static fixture content.

Test coverage: the change keeps the issue-196 regression test runnable under v7.

Unresolved threads: none.

Review: tier=large · model=claude-opus-latest · score=11.3

@garshythoel

Copy link
Copy Markdown

Hey folks - still blocked here for an upgrade, Could a mantainer look ?

@DavertMik

Copy link
Copy Markdown

Please please please! 🙏

@Shreyaan

Shreyaan commented Jul 6, 2026

Copy link
Copy Markdown
Contributor Author

Thanks everyone for the support here 🙏
@Robinnnnn @robert-j-y, could one of you please approve the workflow when convenient? Happy to address anything else needed to get this merged.

@robert-j-y
robert-j-y merged commit 0c90b8b into OpenRouterTeam:main Jul 6, 2026
2 checks passed
@github-actions github-actions Bot mentioned this pull request Jul 6, 2026
@robert-j-y

Copy link
Copy Markdown
Contributor

This is merged, lets keep an eye out for any issues that may come up from the community!

LukasParke added a commit that referenced this pull request Oct 21, 2026
…536)

* fix(completion): finish AI SDK v7 migration for the completion model

The v7 migration (#511) updated the chat model but left the completion
model non-functional under AI SDK v7:

- The AI SDK always sends a default toolChoice of { type: 'auto' }, even
  when no tools are configured, so every generateText/streamText call
  through the completion model threw UnsupportedFunctionalityError.
  Only reject tool choices that actually request tool usage.

- doStream emitted bare text-delta parts, each with a fresh generated id
  and no text-start/text-end events. AI SDK v7 consumers drop deltas
  that do not belong to a started text part, so streamed text never
  reached result.text. Mirror the chat model's text lifecycle: emit
  text-start once with a stable id, reuse that id for every delta, and
  emit text-end in flush.

Adds regression tests that call generateText/streamText from the ai
package against the mock server, updates the stream unit test to expect
the lifecycle events, and includes a patch changeset.

* fix(completion): accept toolChoice none and tidy text lifecycle ids

- Only reject 'required' and 'tool' tool choices; 'none' is satisfiable
  without tools.
- Use textId as the started flag and drop the unreachable generateId()
  fallbacks.
- Move the AI SDK integration tests into the existing doGenerate/doStream
  suites instead of a second test server for the same URL.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Luke Parke <5702154+LukasParke@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
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.

Support ai v7

8 participants