Skip to content
Source
Sign inSign up
TanStack/ai

feat: extract @tanstack/openai-base and @tanstack/ai-utils packages #409

MergedAlemTuzlakmerged 31 commits intomain fromrefs/pull/409/headmerged by AlemTuzlak View on GitHub

AlemTuzlakcommented

Summary

Extracts shared logic into two new packages to eliminate code duplication across all adapter packages:

  • @tanstack/ai-utils — Zero-dependency, provider-agnostic utilities: generateId, getApiKeyFromEnv, transformNullsToUndefined, ModelMeta types + defineModelMeta. Used by all 9 adapter packages.
  • @tanstack/openai-base — OpenAI-compatible adapter base classes and utilities: Chat Completions text adapter, Responses API text adapter, image/summarize/transcription/TTS/video adapters, schema converter (makeStructuredOutputCompatible), 15 tool converters, shared types. Used by ai-openai and ai-grok (full adapter inheritance) and ai-groq/ai-openrouter/ai-ollama (selective utility imports).

Key results

  • ai-openai: ~1,800 lines removed, extends OpenAICompatibleResponsesTextAdapter
  • ai-grok: ~500 lines removed, extends OpenAICompatibleChatCompletionsTextAdapter
  • ai-groq, ai-openrouter, ai-ollama: utility dedup via imports
  • ai-anthropic, ai-gemini, ai-fal, ai-elevenlabs: generateId/getApiKeyFromEnv dedup via ai-utils
  • Zero breaking changes — all public APIs remain identical
  • 103 files changed, +6,469 / -3,154 lines

New package architecture

@tanstack/ai (core)
    ↑
@tanstack/ai-utils (new, zero deps)
    ↑
@tanstack/openai-base (new, deps: ai-utils + openai SDK)
    ↑              ↑
ai-openai      ai-grok          ← extend adapter classes

Test plan

  • pnpm build — 28/28 projects pass
  • pnpm test:lib — all unit tests pass across all packages
  • pnpm test:types — all type checks pass
  • pnpm test:build — publint validates all packages
  • pnpm format — all files formatted
  • New packages have dedicated test suites (21 tests in ai-utils, 48 in openai-base)
  • Existing tests in all migrated packages pass unchanged

Summary by CodeRabbit

  • New Features

    • New shared utilities package with API-key lookup, ID generation, null→undefined transform, and model-metadata types/validation
    • New OpenAI‑compatible base package providing unified adapters and tool converters for text, images, summarization, transcription, TTS, and video
  • Refactor

    • Provider packages delegate shared logic to the new shared utilities and OpenAI‑base while preserving public APIs
  • Tests

    • Added comprehensive tests covering utilities, schema converters, and OpenAI‑compatible adapters
    1. github-actions[bot](GitHub profile, opens in a new tab)commented

      🚀 Changeset Version Preview

      11 package(s) bumped directly, 3 bumped as dependents.

      🟨 Minor bumps

      PackageVersionReason
      @tanstack/ai-utils0.1.0 → 0.2.0Changeset
      @tanstack/openai-base0.1.0 → 0.2.0Changeset

      🟩 Patch bumps

      PackageVersionReason
      @tanstack/ai-anthropic0.8.4 → 0.8.5Changeset
      @tanstack/ai-elevenlabs0.2.1 → 0.2.2Changeset
      @tanstack/ai-fal0.7.1 → 0.7.2Changeset
      @tanstack/ai-gemini0.10.1 → 0.10.2Changeset
      @tanstack/ai-grok0.7.1 → 0.7.2Changeset
      @tanstack/ai-groq0.1.9 → 0.1.10Changeset
      @tanstack/ai-ollama0.6.11 → 0.6.12Changeset
      @tanstack/ai-openai0.8.3 → 0.8.4Changeset
      @tanstack/ai-openrouter0.8.3 → 0.8.4Changeset
      @tanstack/ai-code-mode-models-eval0.0.13 → 0.0.14Dependent
      ts-svelte-chat0.1.39 → 0.1.40Dependent
      ts-vue-chat0.1.39 → 0.1.40Dependent
    2. nx-cloud[bot](GitHub profile, opens in a new tab)commented

      View your CI Pipeline Execution ↗ for commit 2ae8ecae62c1a1608526968b6979f34697093ed8

      CommandStatusDurationResult
      nx run-many --targets=build --exclude=examples/**✅ Succeeded1m 9sView ↗

      ☁️ Nx Cloud last updated this comment at 2026-05-11 07:07:41 UTC

    3. pkg-pr-new[bot](GitHub profile, opens in a new tab)commented

      Open in StackBlitz

      @tanstack/ai

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai@409

      @tanstack/ai-anthropic

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-anthropic@409

      @tanstack/ai-client

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-client@409

      @tanstack/ai-code-mode

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-code-mode@409

      @tanstack/ai-code-mode-skills

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-code-mode-skills@409

      @tanstack/ai-devtools-core

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-devtools-core@409

      @tanstack/ai-elevenlabs

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-elevenlabs@409

      @tanstack/ai-event-client

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-event-client@409

      @tanstack/ai-fal

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-fal@409

      @tanstack/ai-gemini

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-gemini@409

      @tanstack/ai-grok

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-grok@409

      @tanstack/ai-groq

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-groq@409

      @tanstack/ai-isolate-cloudflare

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-cloudflare@409

      @tanstack/ai-isolate-node

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-node@409

      @tanstack/ai-isolate-quickjs

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-quickjs@409

      @tanstack/ai-ollama

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-ollama@409

      @tanstack/ai-openai

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-openai@409

      @tanstack/ai-openrouter

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-openrouter@409

      @tanstack/ai-preact

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-preact@409

      @tanstack/ai-react

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react@409

      @tanstack/ai-react-ui

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react-ui@409

      @tanstack/ai-solid

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid@409

      @tanstack/ai-solid-ui

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid-ui@409

      @tanstack/ai-svelte

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-svelte@409

      @tanstack/ai-utils

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-utils@409

      @tanstack/ai-vue

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vue@409

      @tanstack/ai-vue-ui

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vue-ui@409

      @tanstack/openai-base

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/openai-base@409

      @tanstack/preact-ai-devtools

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/preact-ai-devtools@409

      @tanstack/react-ai-devtools

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/react-ai-devtools@409

      @tanstack/solid-ai-devtools

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/solid-ai-devtools@409

      commit: 2ae8eca

    4. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Note

      Reviews paused

      It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

      Use the following commands to manage reviews:

      • @coderabbitai resume to resume automatic reviews.
      • @coderabbitai review to trigger a single review.

      Use the checkboxes below for quick actions:

      • ▶️ Resume reviews
      • 🔍 Trigger review
      📝 Walkthrough

      Walkthrough

      Adds two new packages—@tanstack/ai-utils and @tanstack/openai-base—and refactors many provider packages to delegate env/id/schema/tool logic to these shared packages; provider adapters now extend OpenAI-compatible base adapters and numerous local tool implementations were replaced by re-exports.

      Changes

      Cohort / File(s)Summary
      New ai-utils package
      packages/typescript/ai-utils/*
      New package exporting generateId, getApiKeyFromEnv, transformNullsToUndefined, ModelMeta/Modality types and defineModelMeta; includes tests, tsconfig, and vite config.
      New openai-base package
      packages/typescript/openai-base/*
      New package providing OpenAI-compatible base adapters (responses/chat-completions text, image, summarize, transcription, TTS, video), schema converter makeStructuredOutputCompatible, client factory, tool converters/types, tests, tsconfig, and vite config.
      Changesets
      .changeset/*
      Added changeset entries documenting the new packages and refactors (minor/patch bumps for relevant packages).
      Provider dependency updates
      packages/typescript/ai-*/package.json
      e.g. packages/typescript/ai-anthropic/package.json, .../ai-elevenlabs/package.json, .../ai-fal/package.json, .../ai-gemini/package.json, .../ai-groq/package.json, .../ai-ollama/package.json, .../ai-openai/package.json, .../ai-openrouter/package.json
      Added @tanstack/ai-utils (and where applicable @tanstack/openai-base) to runtime dependencies.
      Provider util refactors
      packages/typescript/ai-*/src/utils/client.ts
      (ai-anthropic, ai-elevenlabs, ai-fal, ai-gemini, ai-groq, ai-ollama, ai-openrouter, ai-openai)
      Replaced local env-key resolution and ID generation with getApiKeyFromEnv and generateId from @tanstack/ai-utils; added toCompatibleConfig adapters and removed some local client factories.
      ai-openai: adapters & tools delegation
      packages/typescript/ai-openai/src/adapters/*, .../src/tools/*, .../src/utils/*
      Adapters now extend OpenAI-compatible base classes from openai-base (removing local streaming/structured logic); many tool modules replaced by re-exports that point to @tanstack/openai-base.
      ai-grok: adapter, tools & schema refactor
      packages/typescript/ai-grok/src/...
      Grok text/image/summarize adapters now subclass OpenAI-compatible bases; local streaming/structured-output, tool conversion, and schema logic removed or delegated; function-tool and tool-converter deleted.
      ai-groq: schema & utils changes
      packages/typescript/ai-groq/src/utils/*, packages/typescript/ai-groq/tests/*
      Replaced local schema conversion and null→undefined transform with delegations/re-exports to openai-base/ai-utils; added normalization/pruning helpers and adjusted tests for changed error messages.
      Schema & transforms delegation
      packages/typescript/*/src/utils/schema-converter.ts, packages/typescript/*/src/utils/transforms.ts
      Local implementations of transformNullsToUndefined and structured-output converters replaced by re-exports/delegation to @tanstack/ai-utils and @tanstack/openai-base; some packages add small normalization/pruning helpers.
      Tools consolidation / re-exports
      packages/typescript/ai-openai/src/tools/* → packages/typescript/openai-base/src/tools/*
      Many tool types and converters (apply-patch, code-interpreter, computer-use, custom, file-search, function-tool, image-generation, local-shell, mcp, shell, web-search, web-search-preview) implemented in openai-base; ai-openai now re-exports them.
      Tests
      packages/typescript/openai-base/tests/*, packages/typescript/ai-utils/tests/*, plus provider tests
      Extensive new test suites for base adapters, converters, and utils; provider tests updated to use injected mocks and to reflect delegated error messages.
      Build/config files
      packages/typescript/{ai-utils,openai-base}/tsconfig.json, vite.config.ts
      New package-level TypeScript and Vite/Vitest configs added for the two new packages.

      Sequence Diagram(s)

      sequenceDiagram
          participant App
          participant ProviderAdapter
          participant OpenAIBase
          participant OpenAI_SDK
          App->>ProviderAdapter: chatStream(options)
          ProviderAdapter->>OpenAIBase: delegate chatStream(options)
          OpenAIBase->>OpenAIBase: mapOptionsToRequest()
          OpenAIBase->>OpenAI_SDK: responses.create(request, stream=true)
          OpenAI_SDK-->>OpenAIBase: async chunks
          OpenAIBase->>OpenAIBase: processStreamChunks() -> emit RUN_/TEXT_/TOOL_ events
          OpenAIBase-->>ProviderAdapter: StreamChunk events
          ProviderAdapter-->>App: StreamChunk events forwarded
      sequenceDiagram
          participant Provider
          participant Utils
          participant Env
          Provider->>Utils: getApiKeyFromEnv('ENV_VAR')
          Utils->>Env: check globalThis.window.env / process.env
          alt found
              Env-->>Utils: apiKey
              Utils-->>Provider: apiKey
          else not found
              Env-->>Utils: undefined
              Utils-->>Provider: throw Error("ENV_VAR not set")
          end
          Provider-->>Caller: apiKey or thrown error

      Estimated code review effort

      🎯 5 (Critical) | ⏱️ ~90+ minutes

      • TanStack/ai#332 — Refactors ai-groq to delegate utilities and OpenAI-compatible adapters to @tanstack/ai-utils and @tanstack/openai-base (overlaps files and behavior).

      Poem

      🐰 I hopped through code both near and far, moved keys and ids into one bright jar. Base adapters hum, tools find their place, shared hops of logic—tidy, no trace. carrots for tests, a neat little brace!

      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Commit unit tests in branch `feat/extract-openai-base-and-ai-utils`
    5. Actionable comments posted: 13

      Note

      Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

      Caution

      Some comments are outside the diff and can’t be posted inline due to platform limitations.

      ⚠️ Outside diff range comments (1)
      packages/typescript/ai-openai/src/adapters/image.ts (1)

      100-103: ⚠️ Potential issue | 🟡 Minor

      Fix the env lookup order in the JSDoc.

      getOpenAIApiKeyFromEnv() now prefers window.env before process.env, so this list documents the opposite behavior. The same copy appears in the sibling OpenAI factory helpers.

      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/ai-openai/src/adapters/image.ts` around lines 100 - 103,
      JSDoc lists env lookup order incorrectly; update the comment for
      getOpenAIApiKeyFromEnv to state it checks window.env (Browser injected env)
      first, then process.env (Node.js), and apply the same change to the matching
      OpenAI factory helper docs so both accurately reflect the current lookup order.
      🟡 Minor comments (10)
      packages/typescript/ai-utils/src/id.ts-1-5 (1)

      1-5: ⚠️ Potential issue | 🟡 Minor

      substring(7) may produce inconsistent or empty random segments.

      Math.random().toString(36) generates strings of varying length (e.g., "0.5" for 0.5, or "0.abc123..." for typical values). Using substring(7) starts extraction at index 7, which can yield an empty string or very short segment for smaller random numbers.

      Consider using substring(2, 10) to skip the "0." prefix and take a consistent 8-character segment:

      🔧 Proposed fix
       export function generateId(prefix: string): string {
         const timestamp = Date.now()
      -  const randomPart = Math.random().toString(36).substring(7)
      +  const randomPart = Math.random().toString(36).substring(2, 10)
         return `${prefix}-${timestamp}-${randomPart}`
       }
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/ai-utils/src/id.ts` around lines 1 - 5, The random
      segment in generateId can be empty because substring(7) may exceed the length of
      Math.random().toString(36); update the randomPart generation in function
      generateId to consistently extract characters after the "0." (for example use
      Math.random().toString(36).substring(2, 10) to get an 8-character segment) so
      the id always includes a predictable non-empty random portion; ensure the change
      is applied to the randomPart variable in generateId and keep the rest of the
      template literal intact.
      packages/typescript/openai-base/src/tools/web-search-preview-tool.ts-12-17 (1)

      12-17: ⚠️ Potential issue | 🟡 Minor

      Inconsistent type field handling.

      Other tool converters in this package hardcode the type value (e.g., type: 'apply_patch', type: 'image_generation'), but this converter reads metadata.type from the input. This could produce invalid output if metadata.type is undefined or incorrect.

      🔧 Proposed fix for consistency
       export function convertWebSearchPreviewToolToAdapterFormat(
         tool: Tool,
       ): WebSearchPreviewTool {
         const metadata = tool.metadata as WebSearchPreviewTool
         return {
      -    type: metadata.type,
      +    type: 'web_search_preview',
           search_context_size: metadata.search_context_size,
           user_location: metadata.user_location,
         }
       }
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/openai-base/src/tools/web-search-preview-tool.ts` around
      lines 12 - 17, The returned object's type field should be hardcoded for
      consistency rather than reading metadata.type; update the converter that builds
      the returned object (the code using metadata: WebSearchPreviewTool and returning
      { type, search_context_size, user_location }) to set type to a fixed literal
      (e.g., 'web_search_preview') and optionally fall back to that literal when
      metadata.type is falsy, leaving the other fields (search_context_size and
      user_location) as-is.
      packages/typescript/ai-grok/package.json-42-52 (1)

      42-52: ⚠️ Potential issue | 🟡 Minor

      Remove redundant entries from devDependencies.

      @tanstack/ai-utils and @tanstack/openai-base are runtime dependencies (imported in src files like adapters and utilities). They should only appear in dependencies, not duplicated in devDependencies. Other adapter packages in the monorepo (e.g., ai-groq) follow this pattern successfully.

      Remove redundant devDependencies
         "devDependencies": {
      -    "@tanstack/ai-utils": "workspace:*",
      -    "@tanstack/openai-base": "workspace:*",
           "@vitest/coverage-v8": "4.0.14",
           "vite": "^7.2.7"
         },
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/ai-grok/package.json` around lines 42 - 52, Remove the
      duplicate runtime packages from devDependencies in package.json so
      `@tanstack/ai-utils` and `@tanstack/openai-base` only appear under "dependencies";
      open the package.json in the ai-grok package, delete the two entries from the
      "devDependencies" block, ensure the versions remain defined in the top-level
      "dependencies" block, and then reinstall (npm/yarn/pnpm) to update the lockfile
      consistent with other adapter packages like ai-groq.
      packages/typescript/ai-groq/src/utils/client.ts-1-3 (1)

      1-3: ⚠️ Potential issue | 🟡 Minor

      Fix import order to satisfy ESLint (import/order).

      Static analysis reports this ordering as invalid; moving the value import before the type import should resolve it.

      🔧 Proposed fix
       import Groq_SDK from 'groq-sdk'
      -import type { ClientOptions } from 'groq-sdk'
       import { generateId as _generateId, getApiKeyFromEnv } from '@tanstack/ai-utils'
      +import type { ClientOptions } from 'groq-sdk'
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/ai-groq/src/utils/client.ts` around lines 1 - 3, ESLint
      import/order flags the type import position; reorder the imports so value
      imports come before the type-only import. Specifically, keep import Groq_SDK
      from 'groq-sdk' and move the value import "import { generateId as _generateId,
      getApiKeyFromEnv } from '@tanstack/ai-utils'" before the type import "import
      type { ClientOptions } from 'groq-sdk'"; ensure Groq_SDK and the ai-utils value
      import appear above the ClientOptions type-only import.
      packages/typescript/openai-base/src/tools/code-interpreter-tool.ts-22-31 (1)

      22-31: ⚠️ Potential issue | 🟡 Minor

      Parameter naming is misleading and metadata structure may cause round-trip issues.

      The parameter container: CodeInterpreterTool receives the entire CodeInterpreterTool object, not just the container portion. This creates a confusing API and potentially incorrect metadata structure.

      When codeInterpreterTool(toolData) is called, it stores toolData (the full CodeInterpreterTool) under metadata.container. But convertCodeInterpreterToolToAdapterFormat expects metadata.container to be just the container value, not the full tool object.

      Suggested fix
       /**
        * Creates a standard Tool from CodeInterpreterTool parameters
        */
      -export function codeInterpreterTool(container: CodeInterpreterTool): Tool {
      +export function codeInterpreterTool(toolData: CodeInterpreterTool): Tool {
         return {
           name: 'code_interpreter',
           description: 'Execute code in a sandboxed environment',
      -    metadata: {
      -      type: 'code_interpreter',
      -      container,
      -    },
      +    metadata: toolData,
         }
       }

      This aligns with the pattern used in webSearchTool where metadata stores the entire tool configuration.

      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/openai-base/src/tools/code-interpreter-tool.ts` around
      lines 22 - 31, The codeInterpreterTool function currently takes a misleading
      parameter named container (typed CodeInterpreterTool) and stores the whole tool
      object under metadata.container, which breaks
      convertCodeInterpreterToolToAdapterFormat expectations; rename the parameter to
      toolData (or similar) and change the metadata assignment so metadata.container =
      toolData.container (i.e., store only the container value), optionally keeping
      the full tool under a separate key like metadata.tool if you need the full
      config; update any references to the function signature accordingly.
      packages/typescript/ai-utils/package.json-40-43 (1)

      40-43: ⚠️ Potential issue | 🟡 Minor

      Add vitest to devDependencies.

      The test:lib script uses vitest run, but vitest is missing from devDependencies. While workspace hoisting (via pnpm-workspace.yaml) allows this to work in the monorepo, sibling packages like ai-vue and ai-solid explicitly declare vitest ^4.0.14. Add it to make the package consistent and more portable outside the workspace.

      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/ai-utils/package.json` around lines 40 - 43, The
      package.json devDependencies block is missing "vitest" even though the test:lib
      script uses `vitest run`; update the package.json devDependencies to add
      "vitest" with the same version used in siblings (e.g. "^4.0.14") so the package
      is portable outside the workspace and consistent with other packages — modify
      the "devDependencies" entry in packages/typescript/ai-utils/package.json
      accordingly.
      packages/typescript/openai-base/src/adapters/summarize.ts-51-53 (1)

      51-53: ⚠️ Potential issue | 🟡 Minor

      Don't return the same blank id from every summarize() call.

      const id = '' makes every result indistinguishable for tracing, cache keys, and UI bookkeeping. Seed a synthetic id at minimum, then overwrite it if a provider id becomes available later.

      💡 Proposed fix
      +import { generateId } from '@tanstack/ai-utils'
       import { BaseSummarizeAdapter } from '@tanstack/ai/adapters'
      -    const id = ''
      +    let id = generateId()

      Also applies to: 78-78

      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/openai-base/src/adapters/summarize.ts` around lines 51 -
      53, The summarize() function currently sets const id = '' so every call returns
      the same empty id; change it to generate a synthetic unique id (e.g., UUID or
      timestamp+random) when initializing id and keep it mutable so that you can
      overwrite it later if/when a provider returns a real id; update the declaration
      for id in summarize() (and the similar spot around the later block that
      currently uses '' at line ~78) to be initialized to a generated unique string
      and ensure later assignment from provider response replaces that value.
      packages/typescript/openai-base/src/adapters/image.ts-120-130 (1)

      120-130: ⚠️ Potential issue | 🟡 Minor

      Reject fractional and NaN image counts.

      NaN and non-integers both bypass the current range check, so this can still forward n: NaN or n: 1.5 to the provider.

      🛠️ Suggested fix
      -    if (numberOfImages < 1 || numberOfImages > 10) {
      +    if (
      +      !Number.isInteger(numberOfImages) ||
      +      numberOfImages < 1 ||
      +      numberOfImages > 10
      +    ) {
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/openai-base/src/adapters/image.ts` around lines 120 -
      130, validateNumberOfImages currently only checks range and allows NaN or
      fractional values through; update validateNumberOfImages to reject non-integer
      and NaN inputs by verifying Number.isFinite(numberOfImages) and
      Number.isInteger(numberOfImages) (or equivalent) before the range check, and
      throw a clear Error if the value is NaN or not an integer (include the invalid
      value in the error message) so calls with n: NaN or n: 1.5 are rejected.
      packages/typescript/openai-base/src/types/provider-options.ts-7-7 (1)

      7-7: ⚠️ Potential issue | 🟡 Minor

      Use the repo's configured array style for stop.

      This new shared type trips @typescript-eslint/array-type, so it will keep reporting a lint error until it's rewritten as Array<string>.

      🛠️ Suggested fix
      -  stop?: string | string[]
      +  stop?: string | Array<string>
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/openai-base/src/types/provider-options.ts` at line 7, The
      'stop' property in the shared type currently uses the bracket array syntax
      (stop?: string | string[]), which trips `@typescript-eslint/array-type`; change it
      to use the repo's configured generic array style by updating the property to
      stop?: string | Array<string> so the union remains but the array form satisfies
      the lint rule and keeps the type meaning identical.
      packages/typescript/openai-base/src/adapters/transcription.ts-78-85 (1)

      78-85: ⚠️ Potential issue | 🟡 Minor

      Don't drop avg_logprob = 0.

      The truthy check turns a valid 0 into undefined, so perfect-confidence segments lose their confidence field.

      🛠️ Suggested fix
      -            confidence: seg.avg_logprob ? Math.exp(seg.avg_logprob) : undefined,
      +            confidence:
      +              seg.avg_logprob == null
      +                ? undefined
      +                : Math.exp(seg.avg_logprob),
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/openai-base/src/adapters/transcription.ts` around lines
      78 - 85, The mapping in the segments conversion (response.segments?.map ->
      TranscriptionSegment) currently uses a truthy check (avg_logprob ? Math.exp(...)
      : undefined) which drops valid zero values; update the confidence assignment in
      the segments mapping (inside the function that builds TranscriptionSegment
      objects) to test for presence explicitly (e.g., seg.avg_logprob !==
      undefined/null or typeof seg.avg_logprob === "number") and only then compute
      Math.exp(seg.avg_logprob), so avg_logprob = 0 yields confidence = Math.exp(0)
      instead of undefined.
      🧹 Nitpick comments (14)
      packages/typescript/openai-base/src/tools/computer-use-tool.ts (1)

      23-31: Inconsistent function signature compared to other tool factories.

      The computerUseTool function accepts the full ComputerUseTool type including type, while similar factories like imageGenerationTool use Omit<..., 'type'>. This requires callers to redundantly specify type: 'computer_use_preview'.

      ♻️ Proposed fix for consistency
      -export function computerUseTool(toolData: ComputerUseTool): Tool {
      +export function computerUseTool(
      +  toolData: Omit<ComputerUseTool, 'type'>,
      +): Tool {
         return {
           name: 'computer_use_preview',
           description: 'Control a virtual computer',
           metadata: {
             ...toolData,
           },
         }
       }
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/openai-base/src/tools/computer-use-tool.ts` around lines
      23 - 31, Function signature inconsistent: change the parameter of
      computerUseTool from ComputerUseTool to Omit<ComputerUseTool, 'type'> so callers
      don't have to pass type. Update the factory function computerUseTool to accept
      toolData: Omit<ComputerUseTool, 'type'>, keep returning the same object with
      name: 'computer_use_preview' and metadata: { ...toolData }, and ensure any call
      sites that previously passed type no longer do so (or remove the redundant type
      property).
      packages/typescript/openai-base/src/tools/file-search-tool.ts (1)

      15-26: Consider adding validation or type guard in convertFileSearchToolToAdapterFormat.

      The function casts tool.metadata to OpenAI.Responses.FileSearchTool without validation, while fileSearchTool validates max_num_results. If a Tool with invalid/mismatched metadata is passed, this could produce malformed API requests silently.

      Consider adding a runtime check or documenting that callers must ensure the Tool was created via fileSearchTool:

      ♻️ Optional: Add validation for consistency
       export function convertFileSearchToolToAdapterFormat(
         tool: Tool,
       ): OpenAI.Responses.FileSearchTool {
         const metadata = tool.metadata as OpenAI.Responses.FileSearchTool
      +  validateMaxNumResults(metadata.max_num_results)
         return {
           type: 'file_search',
           vector_store_ids: metadata.vector_store_ids,
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/openai-base/src/tools/file-search-tool.ts` around lines
      15 - 26, convertFileSearchToolToAdapterFormat currently casts tool.metadata to
      OpenAI.Responses.FileSearchTool without validation; add a runtime type guard or
      validation at the start of convertFileSearchToolToAdapterFormat to verify
      required fields (e.g., vector_store_ids, max_num_results, ranking_options,
      filters) and that max_num_results meets the same constraints enforced by
      fileSearchTool, and throw or return a clear error if validation fails so
      malformed metadata cannot produce invalid adapter requests.
      packages/typescript/ai-gemini/package.json (1)

      42-54: Same redundancy concern: @tanstack/ai-utils in both dependency sections.

      As noted for ai-grok, the package appears in both dependencies and devDependencies. Consider removing from devDependencies unless there's a specific monorepo tooling requirement.

      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/ai-gemini/package.json` around lines 42 - 54, The
      package.json for ai-gemini lists "@tanstack/ai-utils" in both "dependencies" and
      "devDependencies", creating redundancy; remove the duplicate entry from
      "devDependencies" so "@tanstack/ai-utils" only appears once (leave it in
      "dependencies"), then run the package manager install to refresh the lockfile
      and ensure the workspace resolution is correct; locate the entries by the
      symbols "dependencies", "devDependencies", and the package name
      "@tanstack/ai-utils" in the package.json to make the change.
      packages/typescript/ai-utils/tests/env.test.ts (1)

      23-27: Add one regression test for window.env precedence.

      Given the shared helper is isomorphic, adding an explicit browser-env precedence case would prevent future regressions.

      Proposed test addition
       describe('getApiKeyFromEnv', () => {
         afterEach(() => {
           vi.unstubAllEnvs()
      +    delete (globalThis as { window?: { env?: Record<string, string> } }).window
         })
      @@
         it('should include the env var name in the error message', () => {
           expect(() => getApiKeyFromEnv('MY_PROVIDER_API_KEY')).toThrow(
             'MY_PROVIDER_API_KEY',
           )
         })
      +
      +  it('should prefer globalThis.window.env over process.env when both exist', () => {
      +    vi.stubEnv('TEST_API_KEY', 'from-process')
      +    ;(globalThis as { window?: { env?: Record<string, string> } }).window = {
      +      env: { TEST_API_KEY: 'from-window' },
      +    }
      +    expect(getApiKeyFromEnv('TEST_API_KEY')).toBe('from-window')
      +  })
       })
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/ai-utils/tests/env.test.ts` around lines 23 - 27, Add a
      regression test in the existing env.test.ts that verifies browser (window.env)
      precedence for the isomorphic helper: set process.env.MY_PROVIDER_API_KEY to one
      value and set global.window = { env: { MY_PROVIDER_API_KEY: 'browser_value' } }
      then assert getApiKeyFromEnv('MY_PROVIDER_API_KEY') returns 'browser_value';
      finally clean up/reset global.window and process.env to avoid test pollution.
      Use the getApiKeyFromEnv symbol and window.env/process.env references so the
      test prevents regressions where process.env accidentally overrides browser env.
      packages/typescript/ai-utils/tests/model-meta.test.ts (1)

      5-106: Add tests for the remaining validation branches.

      The suite doesn’t currently assert the max_output_tokens positivity check or negative pricing.input.cached path from defineModelMeta.

      ✅ Suggested test additions
       describe('defineModelMeta', () => {
      +  it('should throw for zero max output tokens', () => {
      +    expect(() =>
      +      defineModelMeta({
      +        name: 'test',
      +        supports: {
      +          input: ['text'] as Array<Modality>,
      +          output: ['text'] as Array<Modality>,
      +        },
      +        max_output_tokens: 0,
      +      }),
      +    ).toThrow('max_output_tokens')
      +  })
      +
      +  it('should throw for negative cached input pricing', () => {
      +    expect(() =>
      +      defineModelMeta({
      +        name: 'test',
      +        supports: {
      +          input: ['text'] as Array<Modality>,
      +          output: ['text'] as Array<Modality>,
      +        },
      +        pricing: {
      +          input: { normal: 1, cached: -0.1 },
      +          output: { normal: 1 },
      +        },
      +      }),
      +    ).toThrow('pricing.input.cached')
      +  })
      [review_comment_end]
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/ai-utils/tests/model-meta.test.ts` around lines 5 - 106,
      Tests are missing coverage for the positivity check on max_output_tokens and the
      validation that rejects negative pricing.input.cached in defineModelMeta; add
      two new test cases in model-meta.test.ts that call defineModelMeta with (1)
      max_output_tokens set to 0 (or negative) and assert it throws
      'max_output_tokens', and (2) pricing.input.cached set to a negative value and
      assert it throws 'pricing' (referencing the defineModelMeta function and the
      max_output_tokens and pricing.input.cached fields to locate the validation
      branches).
      packages/typescript/ai-utils/tests/transforms.test.ts (1)

      1-51: Good test coverage for transformNullsToUndefined.

      The tests comprehensively cover the main scenarios. One edge case that might be worth adding: arrays containing null values directly (e.g., [1, null, 3]) to verify whether nulls in arrays are filtered, converted, or preserved.

      💡 Optional: Add test for direct null values in arrays
      +  it('should handle arrays with direct null values', () => {
      +    const result = transformNullsToUndefined({
      +      items: [1, null, 'hello', null],
      +    })
      +    // Verify expected behavior - adjust assertion based on intended behavior
      +    expect(result.items).toEqual([1, null, 'hello', null]) // or filtered?
      +  })
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/ai-utils/tests/transforms.test.ts` around lines 1 - 51,
      Add a test case to verify how transformNullsToUndefined treats direct null
      entries inside arrays (e.g., items: [1, null, 3]) by calling
      transformNullsToUndefined with an object or array containing such an array and
      asserting the expected behavior (whether nulls are removed, converted to
      undefined, or preserved). Place the new spec alongside existing cases in
      transforms.test.ts and reference transformNullsToUndefined in the test name and
      assertions so reviewers can see the intended outcome clearly.
      packages/typescript/ai-fal/src/utils/client.ts (1)

      19-22: Dead code after migration to shared utility.

      The if (!apiKey) check is now unreachable. According to the AI summary, getApiKeyFromEnv throws an error when the key is not found, so getFalApiKeyFromEnv() will throw before returning a falsy value. This error handling block is dead code.

      Consider removing the redundant check or catching the exception from getFalApiKeyFromEnv() if you want to customize the error message:

      Option 1: Remove dead code
       export function configureFalClient(config?: FalClientConfig): void {
         if (config?.proxyUrl) {
           fal.config({
             proxyUrl: config.proxyUrl,
           })
         } else {
           const apiKey = config?.apiKey ?? getFalApiKeyFromEnv()
      -    if (!apiKey) {
      -      throw new Error('API key is required')
      -    }
           fal.config({
             credentials: apiKey,
           })
         }
       }
      Option 2: Wrap for custom error message
         } else {
      -    const apiKey = config?.apiKey ?? getFalApiKeyFromEnv()
      -    if (!apiKey) {
      -      throw new Error('API key is required')
      -    }
      +    let apiKey = config?.apiKey
      +    if (!apiKey) {
      +      try {
      +        apiKey = getFalApiKeyFromEnv()
      +      } catch {
      +        throw new Error('API key is required')
      +      }
      +    }
           fal.config({
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/ai-fal/src/utils/client.ts` around lines 19 - 22, The if
      (!apiKey) branch is dead because getFalApiKeyFromEnv() throws when the key is
      missing; remove the redundant check or wrap the call in a try/catch to provide a
      custom error message. Specifically, update the apiKey assignment that uses
      config?.apiKey ?? getFalApiKeyFromEnv(): either delete the subsequent if
      (!apiKey) throw new Error('API key is required') block, or change the fallback
      call to be try { getFalApiKeyFromEnv() } catch (err) { throw new Error(`Fal API
      key missing: ${err.message}`) } (adjusting throw text as desired) so error
      handling around getFalApiKeyFromEnv and the apiKey variable is correct.
      packages/typescript/ai-gemini/src/utils/client.ts (1)

      24-28: Consider improving the fallback error message.

      When both GOOGLE_API_KEY and GEMINI_API_KEY are missing, the error will only mention GEMINI_API_KEY. Users expecting GOOGLE_API_KEY might be confused.

      Suggested improvement
       export function getGeminiApiKeyFromEnv(): string {
         try {
           return getApiKeyFromEnv('GOOGLE_API_KEY')
         } catch {
      -    return getApiKeyFromEnv('GEMINI_API_KEY')
      +    try {
      +      return getApiKeyFromEnv('GEMINI_API_KEY')
      +    } catch {
      +      throw new Error('GOOGLE_API_KEY or GEMINI_API_KEY not found in environment')
      +    }
         }
       }
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/ai-gemini/src/utils/client.ts` around lines 24 - 28, The
      fallback currently calls getApiKeyFromEnv('GOOGLE_API_KEY') and on any error
      returns getApiKeyFromEnv('GEMINI_API_KEY'), which leads to an error that only
      mentions GEMINI_API_KEY when both are missing; update the logic to attempt the
      second call inside its own try/catch (or capture both errors) and when both
      attempts fail throw a single error that clearly lists both environment variables
      (GOOGLE_API_KEY and GEMINI_API_KEY) and their failure reasons so callers see
      that both keys are missing/invalid; reference getApiKeyFromEnv('GOOGLE_API_KEY')
      and getApiKeyFromEnv('GEMINI_API_KEY') when implementing the combined error.
      packages/typescript/openai-base/src/tools/web-search-tool.ts (1)

      9-12: Consider adding defensive checks for metadata.

      The function directly casts and returns tool.metadata without validation. If metadata is undefined or malformed, this will silently pass invalid data to OpenAI.

      Suggested defensive check
       export function convertWebSearchToolToAdapterFormat(tool: Tool): WebSearchTool {
         const metadata = tool.metadata as WebSearchTool
      +  if (!metadata || metadata.type !== 'web_search') {
      +    throw new Error('Invalid web_search tool: missing or invalid metadata')
      +  }
         return metadata
       }
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/openai-base/src/tools/web-search-tool.ts` around lines 9
      - 12, convertWebSearchToolToAdapterFormat currently casts tool.metadata to
      WebSearchTool without validation; add defensive checks to ensure tool.metadata
      exists and has the expected fields before returning it. In
      convertWebSearchToolToAdapterFormat, validate that tool.metadata is not
      undefined/null and that required WebSearchTool properties (e.g., any unique keys
      your type requires) are present and correctly typed, and either throw a clear
      error or return a safe default/converted object when validation fails; reference
      the Tool type, WebSearchTool type, and the metadata variable to locate where to
      add these checks.
      packages/typescript/openai-base/src/tools/tool-converter.ts (1)

      16-28: Consider adding runtime exhaustiveness check to guard against drift.

      The SPECIAL_TOOL_NAMES set and the switch statement must stay synchronized. If a name is added to the set but the corresponding case is missing, the tool silently falls through to the function tool converter at line 66—potentially incorrect behavior.

      A defensive default with an error would catch this during development:

      ♻️ Proposed exhaustiveness guard
               case 'custom':
                 return convertCustomToolToAdapterFormat(tool)
      +        default:
      +          // This should never be reached if SPECIAL_TOOL_NAMES and switch are in sync
      +          throw new Error(`Unhandled special tool: ${toolName}`)
             }
           }
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/openai-base/src/tools/tool-converter.ts` around lines 16
      - 28, The SPECIAL_TOOL_NAMES set and the switch in the tool conversion logic
      must be kept in sync to avoid falling back to functionToolConverter incorrectly;
      add a defensive exhaustiveness guard by updating the switch that branches on
      tool names (the same switch that currently falls through to
      functionToolConverter) to include a default branch that throws or logs an error
      referencing the unexpected tool name, and also add a runtime check that every
      entry in SPECIAL_TOOL_NAMES is covered by a corresponding switch case (or vice
      versa) so any drift fails fast during development.
      packages/typescript/openai-base/tests/schema-converter.test.ts (1)

      32-45: Add test case for already-nullable fields to improve coverage.

      The implementation correctly prevents adding duplicate 'null' via the !prop.type.includes('null') check at line 55 of the converter, but the test suite doesn't verify this edge case. Add a test where a field is already nullable (type: ['string', 'null']) to confirm it remains unchanged.

      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/openai-base/tests/schema-converter.test.ts` around lines
      32 - 45, Add a test to verify makeStructuredOutputCompatible preserves existing
      nullable types: create a schema where one property already has type
      ['string','null'] (e.g., nickname) and required includes only name, call
      makeStructuredOutputCompatible(schema, ['name']) and assert that nickname.type
      remains ['string','null'] (and name stays 'string'); reference the existing test
      in schema-converter.test.ts and the makeStructuredOutputCompatible function to
      place the new case next to the current optional-fields test.
      packages/typescript/openai-base/src/tools/custom-tool.ts (1)

      9-17: Tool converters should validate metadata schema at runtime using Zod, consistent with input/output validation guidelines.

      All tool converters in openai-base/src/tools/ (custom-tool, web-search-tool, mcp-tool, file-search-tool, code-interpreter-tool, computer-use-tool, image-generation-tool, web-search-preview-tool) cast tool.metadata without runtime validation. This pattern risks silently propagating undefined values if metadata structure is malformed. Consider adding Zod schema validation for each tool type to ensure compile-time type safety and runtime correctness, aligning with the schema validation guideline for tool definitions.

      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/openai-base/src/tools/custom-tool.ts` around lines 9 -
      17, The convertCustomToolToAdapterFormat function currently casts tool.metadata
      to CustomTool without runtime checks; add a Zod schema for the CustomTool
      metadata, validate tool.metadata at the start of
      convertCustomToolToAdapterFormat (using schema.parse or safeParse), and handle
      validation failures by throwing or logging a descriptive error so malformed
      metadata doesn't propagate; reference the convertCustomToolToAdapterFormat
      function, the metadata variable and the CustomTool shape when adding the Zod
      schema and validation call.
      packages/typescript/ai-openai/src/utils/client.ts (1)

      38-41: Consolidate the config type to prevent silent interface drift.

      Both OpenAIClientConfig and OpenAICompatibleClientConfig are structurally identical. The double-cast pattern at line 41 (and its duplicate in ai-grok) bypasses TypeScript's structural checking. If either interface diverges, the mismatch only surfaces at runtime or in consuming code downstream.

      Options:

      • Export OpenAICompatibleClientConfig from openai-base and reuse it directly (eliminate the local OpenAIClientConfig wrapper).
      • Create an explicit field-by-field mapper function that documents the boundary contract.
      • Or, define a shared internal config type that both packages import.

      The current approach leaves the package boundary unchecked.

      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/ai-openai/src/utils/client.ts` around lines 38 - 41, The
      double-cast in toCompatibleConfig permits silent interface drift between
      OpenAIClientConfig and OpenAICompatibleClientConfig; fix by consolidating types
      or mapping explicitly: either import and use a single shared config type
      exported from openai-base (replace
      OpenAIClientConfig/OpenAICompatibleClientConfig uses and remove the cast in
      toCompatibleConfig), or implement a field-by-field mapper inside
      toCompatibleConfig that constructs an OpenAICompatibleClientConfig from the
      OpenAIClientConfig properties (no unknown/as casts) so the boundary is explicit;
      update all callers of toCompatibleConfig accordingly (function name
      toCompatibleConfig is the change point).
      packages/typescript/openai-base/src/adapters/responses-tool-converter.ts (1)

      46-49: Avoid mutating the schema object returned by schemaConverter().

      If a custom converter returns a shared object, forcing additionalProperties in place leaks state across later conversions. Build a new object before tightening strict mode.

      ♻️ Proposed fix
      -  const jsonSchema = schemaConverter(inputSchema, inputSchema.required || [])
      -
      -  // Ensure additionalProperties is false for strict mode
      -  jsonSchema.additionalProperties = false
      +  const jsonSchema = {
      +    ...schemaConverter(inputSchema, inputSchema.required || []),
      +    additionalProperties: false,
      +  }
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/openai-base/src/adapters/responses-tool-converter.ts`
      around lines 46 - 49, The code mutates the object returned by
      schemaConverter(inputSchema, ...) by setting jsonSchema.additionalProperties =
      false which can leak state; instead create a new object (shallow or deep clone
      as appropriate) from the schemaConverter result and set
      additionalProperties=false on that new object before returning/using it. Locate
      the usage of schemaConverter and the jsonSchema variable in
      responses-tool-converter.ts and replace the in-place mutation with constructing
      a new schema object (e.g., via object spread or a deep clone helper) then set
      additionalProperties on that new object so the original converter output is not
      modified.
      🤖 Prompt for all review comments with AI agents
      Verify each finding against the current code and only fix it if needed.
      
      Inline comments:
      In `@packages/typescript/ai-groq/src/utils/schema-converter.ts`:
      - Around line 18-37: The post-pass in removeEmptyRequired only recurses into
      result.properties and result.items, so empty required arrays inside combinators
      and other schema-valued branches remain; update removeEmptyRequired to also
      detect and recurse into combinator arrays (result.anyOf, result.oneOf,
      result.allOf) by mapping each entry through removeEmptyRequired, and recurse
      into object-valued branches like result.additionalProperties (and any other
      schema-valued fields you spot) by calling removeEmptyRequired on them so empty
      required arrays are pruned throughout the schema tree.
      
      In `@packages/typescript/openai-base/src/adapters/chat-completions-text.ts`:
      - Around line 412-448: The adapter drops provider-specific settings by not
      forwarding options.modelOptions in mapOptionsToRequest; update
      mapOptionsToRequest (in chat-completions-text.ts) to merge options.modelOptions
      into the returned request object (e.g., spread options.modelOptions after the
      known top-level fields or merge with tools/stream fields) so provider-specific
      chat-completions settings reach the request; ensure the merged keys are
      typed/compatible with
      OpenAI_SDK.Chat.Completions.ChatCompletionCreateParamsStreaming and cast where
      necessary (e.g., when adding tools or stream_options) to avoid type errors.
      - Around line 141-152: structuredOutput is passing requestParams (from
      mapOptionsToRequest) which may contain stream_options (set by
      mapOptionsToRequest) into a non-stream request (stream: false); remove or omit
      stream_options when calling structuredOutput so stream_options is only sent when
      stream: true. Update structuredOutput (the call that creates
      chat.completions.create) to shallow-copy requestParams and delete or
      conditionally exclude requestParams.stream_options when stream is false, or
      modify mapOptionsToRequest to attach stream_options only when options specify
      streaming; reference the functions mapOptionsToRequest and
      structuredOutput/requestParams to locate the change.
      - Around line 75-81: mapOptionsToRequest currently only returns request
      parameters and ignores the optional request/requestInit in TextOptions; update
      mapOptionsToRequest to return a tuple or object containing both the
      requestParams and requestOptions (derived from TextOptions.request), then change
      both calls to this.client.chat.completions.create(...) (the streaming call that
      feeds processStreamChunks and the structured-output create call) to pass the
      requestOptions as the second argument to create(). Ensure requestOptions is the
      same forwarded Request | RequestInit so per-request headers and other
      RequestOptions are preserved.
      
      In `@packages/typescript/openai-base/src/adapters/responses-text.ts`:
      - Around line 79-82: The tool-call metadata map (toolCallMetadata) currently
      only stores index/name/started so emitted tool-call events use the internal id;
      update the map value type (used in responses-text adapter) to also store the
      Responses API function_call.call_id when you parse function_call items, then
      change all emissions of TOOL_CALL_START, TOOL_CALL_ARGS, and TOOL_CALL_END to
      include toolCallId: call_id (not the internal id) so that callers using
      convertMessagesToInput() can correlate results via function_call_output.call_id;
      reference the toolCallMetadata map and the event emission sites in
      responses-text.ts and ensure the stored call_id is propagated into those events.
      
      In `@packages/typescript/openai-base/src/adapters/transcription.ts`:
      - Around line 61-65: The transcription base currently sets useVerbose true
      whenever responseFormat is falsy and model !== 'whisper-1', which hardcodes an
      OpenAI model name into the shared adapter; remove that heuristic from the base
      by making useVerbose only true when responseFormat === 'verbose_json', and move
      any model-specific defaults into the OpenAI-specific adapter via a protected
      override (e.g., add a protected method like shouldDefaultToVerbose(model) that
      the OpenAI adapter overrides to enable the legacy behavior). Update uses of
      responseFormat, model, and useVerbose in
      packages/typescript/openai-base/src/adapters/transcription.ts to rely on the
      base opt-in rule and implement the override in the OpenAI adapter so non-OpenAI
      providers remain provider-agnostic.
      - Around line 105-147: The prepareAudioFile method uses ArrayBuffer and atob
      without runtime guards; update prepareAudioFile to check for typeof ArrayBuffer
      !== 'undefined' before using ArrayBuffer (in the ArrayBuffer branch) and check
      typeof atob === 'function' before calling atob (in both data URL and raw base64
      branches); if those globals are unavailable, either delegate to a runtime-safe
      helper or throw a clear error indicating the missing runtime capability (mention
      prepareAudioFile to locate the change) so the method behaves consistently with
      the existing File/Blob guards.
      
      In `@packages/typescript/openai-base/src/adapters/tts.ts`:
      - Around line 49-56: The returned format/contentType is derived from the
      original `format` variable even though `modelOptions` (spread into `request`)
      can override `response_format`; update the code around the `request:
      OpenAI_SDK.Audio.SpeechCreateParams` construction so the final returned `format`
      and `contentType` are computed from the merged `request` (e.g., read
      `request.response_format` after spreading `modelOptions`, falling back to a
      default like 'mp3'), and use that derived value for the response payload
      metadata (affects the same logic referenced on lines ~65-66).
      
      In `@packages/typescript/openai-base/src/adapters/video.ts`:
      - Around line 131-139: The method probes should check for the OpenAI SDK's
      videos.downloadContent(jobId) entrypoint instead of content/getContent/download
      so update the detection to call client.videos.downloadContent(jobId) when
      available (fall back to client.videos.retrieve(jobId) only otherwise) and avoid
      always falling through to the manual fetch; also fix the expires_at conversion
      where new Date(expires_at) is used (in the branches handling
      videoInfo.expires_at and the manual download path) by multiplying the seconds
      timestamp by 1000 (new Date(expires_at * 1000)) so expiration dates are correct.
      - Around line 140-146: The code returns expiresAt using new
      Date(videoInfo.expires_at) but OpenAI's expires_at is in seconds, while Date
      expects milliseconds; update the construction in the adapter (the block using
      videoInfo and jobId) to convert seconds to milliseconds (e.g., multiply the
      numeric expires_at by 1000 or use Number(...) * 1000) before passing to new
      Date, and preserve the existing undefined handling when expires_at is absent.
      
      In `@packages/typescript/openai-base/src/tools/mcp-tool.ts`:
      - Around line 18-24: In convertMCPToolToAdapterFormat the runtime metadata may
      include a type field that currently gets overridden by spreading metadata before
      setting type, allowing non-'mcp' types to leak through; fix by ensuring the
      'type' property is applied after spreading metadata (or by creating a shallow
      copy of metadata with any existing type removed) so the resulting MCPTool always
      has type: 'mcp' regardless of tool.metadata contents; reference
      convertMCPToolToAdapterFormat, Tool, MCPTool and the local metadata variable
      when making this change.
      
      In `@packages/typescript/openai-base/src/utils/schema-converter.ts`:
      - Around line 26-66: The branch logic in makeStructuredOutputCompatible
      currently recurses and assigns converted children directly, so optional fields
      (wasOptional) inside object/array/anyOf branches lose nullability when
      result.required is set; change the implementation to always produce a single
      convertedProp for each propName (for object: call
      makeStructuredOutputCompatible(prop, prop.required||[] ) and assign to
      convertedProp; for array: set convertedProp = { ...prop, items:
      makeStructuredOutputCompatible(prop.items, prop.items.required||[]) }; for
      anyOf: convertedProp = makeStructuredOutputCompatible(prop, prop.required||[]) ;
      for oneOf keep throwing) and only after that apply the wasOptional null-widening
      transformation to convertedProp (if prop.type exists and not array -> type =
      [type,'null']; if prop.type is array and missing 'null' -> append 'null');
      finally set properties[propName] = convertedProp and then set
      result.properties/result.required/additionalProperties as before.
      - Around line 12-24: The function makeStructuredOutputCompatible currently
      treats all fields as optional when originalRequired defaults to [], which can
      incorrectly widen originally required properties; change the optionality source
      to use schema.required when originalRequired is not supplied—inside
      makeStructuredOutputCompatible, derive a working required list (e.g., const
      requiredSource = originalRequired.length ? originalRequired : (schema.required
      ?? [])) and use requiredSource instead of originalRequired when computing
      wasOptional for each propName, ensuring originally required fields are not
      widened to include null before result.required is rewritten.
      
      ---
      
      Outside diff comments:
      In `@packages/typescript/ai-openai/src/adapters/image.ts`:
      - Around line 100-103: JSDoc lists env lookup order incorrectly; update the
      comment for getOpenAIApiKeyFromEnv to state it checks window.env (Browser
      injected env) first, then process.env (Node.js), and apply the same change to
      the matching OpenAI factory helper docs so both accurately reflect the current
      lookup order.
      
      ---
      
      Minor comments:
      In `@packages/typescript/ai-grok/package.json`:
      - Around line 42-52: Remove the duplicate runtime packages from devDependencies
      in package.json so `@tanstack/ai-utils` and `@tanstack/openai-base` only appear
      under "dependencies"; open the package.json in the ai-grok package, delete the
      two entries from the "devDependencies" block, ensure the versions remain defined
      in the top-level "dependencies" block, and then reinstall (npm/yarn/pnpm) to
      update the lockfile consistent with other adapter packages like ai-groq.
      
      In `@packages/typescript/ai-groq/src/utils/client.ts`:
      - Around line 1-3: ESLint import/order flags the type import position; reorder
      the imports so value imports come before the type-only import. Specifically,
      keep import Groq_SDK from 'groq-sdk' and move the value import "import {
      generateId as _generateId, getApiKeyFromEnv } from '@tanstack/ai-utils'" before
      the type import "import type { ClientOptions } from 'groq-sdk'"; ensure Groq_SDK
      and the ai-utils value import appear above the ClientOptions type-only import.
      
      In `@packages/typescript/ai-utils/package.json`:
      - Around line 40-43: The package.json devDependencies block is missing "vitest"
      even though the test:lib script uses `vitest run`; update the package.json
      devDependencies to add "vitest" with the same version used in siblings (e.g.
      "^4.0.14") so the package is portable outside the workspace and consistent with
      other packages — modify the "devDependencies" entry in
      packages/typescript/ai-utils/package.json accordingly.
      
      In `@packages/typescript/ai-utils/src/id.ts`:
      - Around line 1-5: The random segment in generateId can be empty because
      substring(7) may exceed the length of Math.random().toString(36); update the
      randomPart generation in function generateId to consistently extract characters
      after the "0." (for example use Math.random().toString(36).substring(2, 10) to
      get an 8-character segment) so the id always includes a predictable non-empty
      random portion; ensure the change is applied to the randomPart variable in
      generateId and keep the rest of the template literal intact.
      
      In `@packages/typescript/openai-base/src/adapters/image.ts`:
      - Around line 120-130: validateNumberOfImages currently only checks range and
      allows NaN or fractional values through; update validateNumberOfImages to reject
      non-integer and NaN inputs by verifying Number.isFinite(numberOfImages) and
      Number.isInteger(numberOfImages) (or equivalent) before the range check, and
      throw a clear Error if the value is NaN or not an integer (include the invalid
      value in the error message) so calls with n: NaN or n: 1.5 are rejected.
      
      In `@packages/typescript/openai-base/src/adapters/summarize.ts`:
      - Around line 51-53: The summarize() function currently sets const id = '' so
      every call returns the same empty id; change it to generate a synthetic unique
      id (e.g., UUID or timestamp+random) when initializing id and keep it mutable so
      that you can overwrite it later if/when a provider returns a real id; update the
      declaration for id in summarize() (and the similar spot around the later block
      that currently uses '' at line ~78) to be initialized to a generated unique
      string and ensure later assignment from provider response replaces that value.
      
      In `@packages/typescript/openai-base/src/adapters/transcription.ts`:
      - Around line 78-85: The mapping in the segments conversion
      (response.segments?.map -> TranscriptionSegment) currently uses a truthy check
      (avg_logprob ? Math.exp(...) : undefined) which drops valid zero values; update
      the confidence assignment in the segments mapping (inside the function that
      builds TranscriptionSegment objects) to test for presence explicitly (e.g.,
      seg.avg_logprob !== undefined/null or typeof seg.avg_logprob === "number") and
      only then compute Math.exp(seg.avg_logprob), so avg_logprob = 0 yields
      confidence = Math.exp(0) instead of undefined.
      
      In `@packages/typescript/openai-base/src/tools/code-interpreter-tool.ts`:
      - Around line 22-31: The codeInterpreterTool function currently takes a
      misleading parameter named container (typed CodeInterpreterTool) and stores the
      whole tool object under metadata.container, which breaks
      convertCodeInterpreterToolToAdapterFormat expectations; rename the parameter to
      toolData (or similar) and change the metadata assignment so metadata.container =
      toolData.container (i.e., store only the container value), optionally keeping
      the full tool under a separate key like metadata.tool if you need the full
      config; update any references to the function signature accordingly.
      
      In `@packages/typescript/openai-base/src/tools/web-search-preview-tool.ts`:
      - Around line 12-17: The returned object's type field should be hardcoded for
      consistency rather than reading metadata.type; update the converter that builds
      the returned object (the code using metadata: WebSearchPreviewTool and returning
      { type, search_context_size, user_location }) to set type to a fixed literal
      (e.g., 'web_search_preview') and optionally fall back to that literal when
      metadata.type is falsy, leaving the other fields (search_context_size and
      user_location) as-is.
      
      In `@packages/typescript/openai-base/src/types/provider-options.ts`:
      - Line 7: The 'stop' property in the shared type currently uses the bracket
      array syntax (stop?: string | string[]), which trips
      `@typescript-eslint/array-type`; change it to use the repo's configured generic
      array style by updating the property to stop?: string | Array<string> so the
      union remains but the array form satisfies the lint rule and keeps the type
      meaning identical.
      
      ---
      
      Nitpick comments:
      In `@packages/typescript/ai-fal/src/utils/client.ts`:
      - Around line 19-22: The if (!apiKey) branch is dead because
      getFalApiKeyFromEnv() throws when the key is missing; remove the redundant check
      or wrap the call in a try/catch to provide a custom error message. Specifically,
      update the apiKey assignment that uses config?.apiKey ?? getFalApiKeyFromEnv():
      either delete the subsequent if (!apiKey) throw new Error('API key is required')
      block, or change the fallback call to be try { getFalApiKeyFromEnv() } catch
      (err) { throw new Error(`Fal API key missing: ${err.message}`) } (adjusting
      throw text as desired) so error handling around getFalApiKeyFromEnv and the
      apiKey variable is correct.
      
      In `@packages/typescript/ai-gemini/package.json`:
      - Around line 42-54: The package.json for ai-gemini lists "@tanstack/ai-utils"
      in both "dependencies" and "devDependencies", creating redundancy; remove the
      duplicate entry from "devDependencies" so "@tanstack/ai-utils" only appears once
      (leave it in "dependencies"), then run the package manager install to refresh
      the lockfile and ensure the workspace resolution is correct; locate the entries
      by the symbols "dependencies", "devDependencies", and the package name
      "@tanstack/ai-utils" in the package.json to make the change.
      
      In `@packages/typescript/ai-gemini/src/utils/client.ts`:
      - Around line 24-28: The fallback currently calls
      getApiKeyFromEnv('GOOGLE_API_KEY') and on any error returns
      getApiKeyFromEnv('GEMINI_API_KEY'), which leads to an error that only mentions
      GEMINI_API_KEY when both are missing; update the logic to attempt the second
      call inside its own try/catch (or capture both errors) and when both attempts
      fail throw a single error that clearly lists both environment variables
      (GOOGLE_API_KEY and GEMINI_API_KEY) and their failure reasons so callers see
      that both keys are missing/invalid; reference getApiKeyFromEnv('GOOGLE_API_KEY')
      and getApiKeyFromEnv('GEMINI_API_KEY') when implementing the combined error.
      
      In `@packages/typescript/ai-openai/src/utils/client.ts`:
      - Around line 38-41: The double-cast in toCompatibleConfig permits silent
      interface drift between OpenAIClientConfig and OpenAICompatibleClientConfig; fix
      by consolidating types or mapping explicitly: either import and use a single
      shared config type exported from openai-base (replace
      OpenAIClientConfig/OpenAICompatibleClientConfig uses and remove the cast in
      toCompatibleConfig), or implement a field-by-field mapper inside
      toCompatibleConfig that constructs an OpenAICompatibleClientConfig from the
      OpenAIClientConfig properties (no unknown/as casts) so the boundary is explicit;
      update all callers of toCompatibleConfig accordingly (function name
      toCompatibleConfig is the change point).
      
      In `@packages/typescript/ai-utils/tests/env.test.ts`:
      - Around line 23-27: Add a regression test in the existing env.test.ts that
      verifies browser (window.env) precedence for the isomorphic helper: set
      process.env.MY_PROVIDER_API_KEY to one value and set global.window = { env: {
      MY_PROVIDER_API_KEY: 'browser_value' } } then assert
      getApiKeyFromEnv('MY_PROVIDER_API_KEY') returns 'browser_value'; finally clean
      up/reset global.window and process.env to avoid test pollution. Use the
      getApiKeyFromEnv symbol and window.env/process.env references so the test
      prevents regressions where process.env accidentally overrides browser env.
      
      In `@packages/typescript/ai-utils/tests/model-meta.test.ts`:
      - Around line 5-106: Tests are missing coverage for the positivity check on
      max_output_tokens and the validation that rejects negative pricing.input.cached
      in defineModelMeta; add two new test cases in model-meta.test.ts that call
      defineModelMeta with (1) max_output_tokens set to 0 (or negative) and assert it
      throws 'max_output_tokens', and (2) pricing.input.cached set to a negative value
      and assert it throws 'pricing' (referencing the defineModelMeta function and the
      max_output_tokens and pricing.input.cached fields to locate the validation
      branches).
      
      In `@packages/typescript/ai-utils/tests/transforms.test.ts`:
      - Around line 1-51: Add a test case to verify how transformNullsToUndefined
      treats direct null entries inside arrays (e.g., items: [1, null, 3]) by calling
      transformNullsToUndefined with an object or array containing such an array and
      asserting the expected behavior (whether nulls are removed, converted to
      undefined, or preserved). Place the new spec alongside existing cases in
      transforms.test.ts and reference transformNullsToUndefined in the test name and
      assertions so reviewers can see the intended outcome clearly.
      
      In `@packages/typescript/openai-base/src/adapters/responses-tool-converter.ts`:
      - Around line 46-49: The code mutates the object returned by
      schemaConverter(inputSchema, ...) by setting jsonSchema.additionalProperties =
      false which can leak state; instead create a new object (shallow or deep clone
      as appropriate) from the schemaConverter result and set
      additionalProperties=false on that new object before returning/using it. Locate
      the usage of schemaConverter and the jsonSchema variable in
      responses-tool-converter.ts and replace the in-place mutation with constructing
      a new schema object (e.g., via object spread or a deep clone helper) then set
      additionalProperties on that new object so the original converter output is not
      modified.
      
      In `@packages/typescript/openai-base/src/tools/computer-use-tool.ts`:
      - Around line 23-31: Function signature inconsistent: change the parameter of
      computerUseTool from ComputerUseTool to Omit<ComputerUseTool, 'type'> so callers
      don't have to pass type. Update the factory function computerUseTool to accept
      toolData: Omit<ComputerUseTool, 'type'>, keep returning the same object with
      name: 'computer_use_preview' and metadata: { ...toolData }, and ensure any call
      sites that previously passed type no longer do so (or remove the redundant type
      property).
      
      In `@packages/typescript/openai-base/src/tools/custom-tool.ts`:
      - Around line 9-17: The convertCustomToolToAdapterFormat function currently
      casts tool.metadata to CustomTool without runtime checks; add a Zod schema for
      the CustomTool metadata, validate tool.metadata at the start of
      convertCustomToolToAdapterFormat (using schema.parse or safeParse), and handle
      validation failures by throwing or logging a descriptive error so malformed
      metadata doesn't propagate; reference the convertCustomToolToAdapterFormat
      function, the metadata variable and the CustomTool shape when adding the Zod
      schema and validation call.
      
      In `@packages/typescript/openai-base/src/tools/file-search-tool.ts`:
      - Around line 15-26: convertFileSearchToolToAdapterFormat currently casts
      tool.metadata to OpenAI.Responses.FileSearchTool without validation; add a
      runtime type guard or validation at the start of
      convertFileSearchToolToAdapterFormat to verify required fields (e.g.,
      vector_store_ids, max_num_results, ranking_options, filters) and that
      max_num_results meets the same constraints enforced by fileSearchTool, and throw
      or return a clear error if validation fails so malformed metadata cannot produce
      invalid adapter requests.
      
      In `@packages/typescript/openai-base/src/tools/tool-converter.ts`:
      - Around line 16-28: The SPECIAL_TOOL_NAMES set and the switch in the tool
      conversion logic must be kept in sync to avoid falling back to
      functionToolConverter incorrectly; add a defensive exhaustiveness guard by
      updating the switch that branches on tool names (the same switch that currently
      falls through to functionToolConverter) to include a default branch that throws
      or logs an error referencing the unexpected tool name, and also add a runtime
      check that every entry in SPECIAL_TOOL_NAMES is covered by a corresponding
      switch case (or vice versa) so any drift fails fast during development.
      
      In `@packages/typescript/openai-base/src/tools/web-search-tool.ts`:
      - Around line 9-12: convertWebSearchToolToAdapterFormat currently casts
      tool.metadata to WebSearchTool without validation; add defensive checks to
      ensure tool.metadata exists and has the expected fields before returning it. In
      convertWebSearchToolToAdapterFormat, validate that tool.metadata is not
      undefined/null and that required WebSearchTool properties (e.g., any unique keys
      your type requires) are present and correctly typed, and either throw a clear
      error or return a safe default/converted object when validation fails; reference
      the Tool type, WebSearchTool type, and the metadata variable to locate where to
      add these checks.
      
      In `@packages/typescript/openai-base/tests/schema-converter.test.ts`:
      - Around line 32-45: Add a test to verify makeStructuredOutputCompatible
      preserves existing nullable types: create a schema where one property already
      has type ['string','null'] (e.g., nickname) and required includes only name,
      call makeStructuredOutputCompatible(schema, ['name']) and assert that
      nickname.type remains ['string','null'] (and name stays 'string'); reference the
      existing test in schema-converter.test.ts and the makeStructuredOutputCompatible
      function to place the new case next to the current optional-fields test.
      🪄 Autofix (Beta)

      Fix all unresolved CodeRabbit comments on this PR:

      • Push a commit to this branch (recommended)
      • Create a new PR with the fixes
    6. Actionable comments posted: 3

      🧹 Nitpick comments (5)
      packages/typescript/openai-base/tests/mcp-tool.test.ts (1)

      20-33: Align the preservation assertion with the test’s stated intent.

      The test says it preserves metadata fields other than type, but it only asserts server_url. Add an assertion for server_description (or assert the full projected object) to avoid false confidence.

      Suggested diff
         it('should preserve metadata fields other than type', () => {
      @@
           const result = convertMCPToolToAdapterFormat(tool)
           expect(result.type).toBe('mcp')
           expect(result.server_url).toBe('https://example.com/mcp')
      +    expect(result.server_description).toBe('Test server')
         })
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/openai-base/tests/mcp-tool.test.ts` around lines 20 - 33,
      The test currently only asserts that convertMCPToolToAdapterFormat(tool)
      preserves result.server_url even though it’s intended to preserve all metadata
      fields other than type; update the assertion to also check
      result.server_description (or assert the full projected object equals the
      expected projection) so the test verifies both server_url and server_description
      are preserved from the input tool.metadata when calling
      convertMCPToolToAdapterFormat.
      packages/typescript/openai-base/src/types/provider-options.ts (1)

      7-7: Use Array<string> per ESLint configuration.

      Static analysis indicates the project prefers Array<string> over string[].

      ✏️ Suggested fix
      -  stop?: string | string[]
      +  stop?: string | Array<string>
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/openai-base/src/types/provider-options.ts` at line 7, The
      stop property is declared using the `string[]` shorthand; update its type to use
      `Array<string>` to satisfy the project's ESLint rule. Locate the `stop` property
      in the provider options type (the `stop?: string | string[]` declaration in
      provider-options.ts) and change the union to use `Array<string>` (e.g., `stop?:
      string | Array<string>`) so the signature remains identical but conforms to the
      Array<string> style.
      packages/typescript/ai-grok/src/utils/client.ts (1)

      30-33: Consider avoiding the double cast through unknown.

      The as unknown as OpenAICompatibleClientConfig pattern bypasses type safety. If GrokClientConfig (which extends ClientOptions) is structurally compatible with OpenAICompatibleClientConfig, consider either:

      1. Aligning the types so direct assignment works
      2. Using a type assertion with a comment explaining why it's safe

      This isn't blocking since the runtime behavior is correct, but the double cast hides potential type mismatches.

      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/ai-grok/src/utils/client.ts` around lines 30 - 33, The
      return currently uses a double cast "as unknown as OpenAICompatibleClientConfig"
      which bypasses type safety; update the types or the cast so we don't go through
      unknown: either make GrokClientConfig (or ClientOptions) structurally extend
      OpenAICompatibleClientConfig so the object returned by the function can be
      returned directly, or replace the double-cast with a single assert "as
      OpenAICompatibleClientConfig" and add a short comment above the return
      explaining why the shape is compatible (refer to the returned object created by
      the spread of config and baseURL in client.ts). Ensure the change touches the
      return expression that builds the config object so the type assertion is safe
      and clear.
      packages/typescript/openai-base/src/adapters/chat-completions-text.ts (1)

      413-428: Use console.error for error logging consistency.

      Line 415 uses console.log for error logging, while the rest of the file uses console.error for errors (lines 117-122, 200-203). This inconsistency could make log filtering more difficult.

      ♻️ Suggested fix
           } catch (error: unknown) {
             const err = error as Error & { code?: string }
      -      console.log(`[${this.name}] Stream ended with error:`, err.message)
      +      console.error(`[${this.name}] Stream ended with error:`, err.message)
       
             // Emit AG-UI RUN_ERROR
             yield {
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/openai-base/src/adapters/chat-completions-text.ts` around
      lines 413 - 428, Replace the inconsistent console.log call in the catch block
      with console.error so error logging matches the rest of the file; specifically
      in the catch (error: unknown) block where you cast to const err = error as Error
      & { code?: string } and log `[${this.name}] Stream ended with error:`, change
      that call to use console.error and keep the rest of the RUN_ERROR yield (runId,
      model, timestamp, error.message, error.code) unchanged.
      packages/typescript/ai-grok/src/adapters/text.ts (1)

      27-41: Successful refactor to use shared base adapter.

      The adapter correctly extends OpenAICompatibleChatCompletionsTextAdapter, eliminating ~500 lines of duplicated streaming and structured output logic.

      Nit: Lines 35-36 declare kind and name as class properties, but these are already set by the parent class (via constructor parameter and parent's kind declaration). Consider removing the redundant declarations to clarify that values come from the inheritance chain.

      ♻️ Optional: Remove redundant property declarations
       export class GrokTextAdapter<
         TModel extends (typeof GROK_CHAT_MODELS)[number],
       > extends OpenAICompatibleChatCompletionsTextAdapter<
         TModel,
         ResolveProviderOptions<TModel>,
         ResolveInputModalities<TModel>,
         GrokMessageMetadataByModality
       > {
      -  readonly kind = 'text' as const
      -  readonly name = 'grok' as const
      +  override readonly name = 'grok' as const
      
         constructor(config: GrokTextConfig, model: TModel) {
           super(toCompatibleConfig(config), model, 'grok')
         }
       }
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/ai-grok/src/adapters/text.ts` around lines 27 - 41,
      Remove the redundant class properties readonly kind and readonly name from
      GrokTextAdapter since the parent OpenAICompatibleChatCompletionsTextAdapter
      already sets these via its constructor parameter (the 'grok' argument passed in
      the GrokTextAdapter constructor); delete the two property declarations (kind and
      name) so the adapter inherits them from the base class and ensure no other code
      in this class relies on those explicit declarations.
      🤖 Prompt for all review comments with AI agents
      Verify each finding against the current code and only fix it if needed.
      
      Inline comments:
      In `@packages/typescript/ai-groq/src/utils/client.ts`:
      - Line 3: The import order violates ESLint import/order: move the concrete
      import of generateId and getApiKeyFromEnv from '@tanstack/ai-utils' so it comes
      before the `import type` from 'groq-sdk'; update the top of the file so the
      non-type import (generateId as _generateId, getApiKeyFromEnv) appears before the
      `import type { ... } from 'groq-sdk'` to satisfy the rule.
      
      In `@packages/typescript/ai-groq/tests/schema-converter.test.ts`:
      - Around line 32-64: Rename the test case title to reflect the actual behavior
      being tested: update the it(...) description string in the test where
      makeGroqStructuredOutputCompatible and checkNoEmptyRequired are used (currently
      "'should remove empty required arrays inside oneOf variants'") to a clearer name
      such as "'should not have empty required arrays anywhere in the result'"; ensure
      only the descriptive string is changed and leave the test body (the schema, call
      to makeGroqStructuredOutputCompatible, and the checkNoEmptyRequired helper)
      untouched.
      
      In `@packages/typescript/ai-utils/tests/env.test.ts`:
      - Around line 14-16: The test is flaky because it relies on host environment
      state; make the assertions deterministic by explicitly controlling process.env
      within the test: save the original value of the env var, delete it (delete
      process.env['NONEXISTENT_KEY']) before calling
      getApiKeyFromEnv('NONEXISTENT_KEY') so the function reliably throws, and then
      restore the original value after the test (or use beforeEach/afterEach). Do the
      same for the other test that references 'MY_PROVIDER_API_KEY' — set
      process.env['MY_PROVIDER_API_KEY'] to a known value for the success case and
      restore the original afterward; reference getApiKeyFromEnv in the test file to
      locate the tests to change.
      
      ---
      
      Nitpick comments:
      In `@packages/typescript/ai-grok/src/adapters/text.ts`:
      - Around line 27-41: Remove the redundant class properties readonly kind and
      readonly name from GrokTextAdapter since the parent
      OpenAICompatibleChatCompletionsTextAdapter already sets these via its
      constructor parameter (the 'grok' argument passed in the GrokTextAdapter
      constructor); delete the two property declarations (kind and name) so the
      adapter inherits them from the base class and ensure no other code in this class
      relies on those explicit declarations.
      
      In `@packages/typescript/ai-grok/src/utils/client.ts`:
      - Around line 30-33: The return currently uses a double cast "as unknown as
      OpenAICompatibleClientConfig" which bypasses type safety; update the types or
      the cast so we don't go through unknown: either make GrokClientConfig (or
      ClientOptions) structurally extend OpenAICompatibleClientConfig so the object
      returned by the function can be returned directly, or replace the double-cast
      with a single assert "as OpenAICompatibleClientConfig" and add a short comment
      above the return explaining why the shape is compatible (refer to the returned
      object created by the spread of config and baseURL in client.ts). Ensure the
      change touches the return expression that builds the config object so the type
      assertion is safe and clear.
      
      In `@packages/typescript/openai-base/src/adapters/chat-completions-text.ts`:
      - Around line 413-428: Replace the inconsistent console.log call in the catch
      block with console.error so error logging matches the rest of the file;
      specifically in the catch (error: unknown) block where you cast to const err =
      error as Error & { code?: string } and log `[${this.name}] Stream ended with
      error:`, change that call to use console.error and keep the rest of the
      RUN_ERROR yield (runId, model, timestamp, error.message, error.code) unchanged.
      
      In `@packages/typescript/openai-base/src/types/provider-options.ts`:
      - Line 7: The stop property is declared using the `string[]` shorthand; update
      its type to use `Array<string>` to satisfy the project's ESLint rule. Locate the
      `stop` property in the provider options type (the `stop?: string | string[]`
      declaration in provider-options.ts) and change the union to use `Array<string>`
      (e.g., `stop?: string | Array<string>`) so the signature remains identical but
      conforms to the Array<string> style.
      
      In `@packages/typescript/openai-base/tests/mcp-tool.test.ts`:
      - Around line 20-33: The test currently only asserts that
      convertMCPToolToAdapterFormat(tool) preserves result.server_url even though it’s
      intended to preserve all metadata fields other than type; update the assertion
      to also check result.server_description (or assert the full projected object
      equals the expected projection) so the test verifies both server_url and
      server_description are preserved from the input tool.metadata when calling
      convertMCPToolToAdapterFormat.
      🪄 Autofix (Beta)

      Fix all unresolved CodeRabbit comments on this PR:

      • Push a commit to this branch (recommended)
      • Create a new PR with the fixes

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro

      Run ID: a438aa99-181f-4c47-8e75-5a71a52dae2b

      📥 Commits

      Reviewing files that changed from the base of the PR and between ce49ae5377e6340e0d2ba542a89c510d41af10c6 and 9b83f1a456f5417e2e285e33e1d1d6441a5d0aeb.

      ⛔ Files ignored due to path filters (1)
      • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
      📒 Files selected for processing (104)
      • .changeset/add-ai-utils-package.md
      • .changeset/add-openai-base-package.md
      • .changeset/refactor-providers-to-shared-packages.md
      • packages/typescript/ai-anthropic/package.json
      • packages/typescript/ai-anthropic/src/utils/client.ts
      • packages/typescript/ai-elevenlabs/package.json
      • packages/typescript/ai-elevenlabs/src/realtime/token.ts
      • packages/typescript/ai-fal/package.json
      • packages/typescript/ai-fal/src/utils/client.ts
      • packages/typescript/ai-gemini/package.json
      • packages/typescript/ai-gemini/src/utils/client.ts
      • packages/typescript/ai-grok/package.json
      • packages/typescript/ai-grok/src/adapters/image.ts
      • packages/typescript/ai-grok/src/adapters/summarize.ts
      • packages/typescript/ai-grok/src/adapters/text.ts
      • packages/typescript/ai-grok/src/tools/function-tool.ts
      • packages/typescript/ai-grok/src/tools/tool-converter.ts
      • packages/typescript/ai-grok/src/utils/client.ts
      • packages/typescript/ai-grok/src/utils/index.ts
      • packages/typescript/ai-grok/src/utils/schema-converter.ts
      • packages/typescript/ai-grok/tests/grok-adapter.test.ts
      • packages/typescript/ai-groq/package.json
      • packages/typescript/ai-groq/src/utils/client.ts
      • packages/typescript/ai-groq/src/utils/schema-converter.ts
      • packages/typescript/ai-groq/tests/groq-adapter.test.ts
      • packages/typescript/ai-groq/tests/schema-converter.test.ts
      • packages/typescript/ai-ollama/package.json
      • packages/typescript/ai-ollama/src/utils/client.ts
      • packages/typescript/ai-openai/package.json
      • packages/typescript/ai-openai/src/adapters/image.ts
      • packages/typescript/ai-openai/src/adapters/summarize.ts
      • packages/typescript/ai-openai/src/adapters/text.ts
      • packages/typescript/ai-openai/src/adapters/transcription.ts
      • packages/typescript/ai-openai/src/adapters/tts.ts
      • packages/typescript/ai-openai/src/adapters/video.ts
      • packages/typescript/ai-openai/src/tools/apply-patch-tool.ts
      • packages/typescript/ai-openai/src/tools/code-interpreter-tool.ts
      • packages/typescript/ai-openai/src/tools/computer-use-tool.ts
      • packages/typescript/ai-openai/src/tools/custom-tool.ts
      • packages/typescript/ai-openai/src/tools/file-search-tool.ts
      • packages/typescript/ai-openai/src/tools/function-tool.ts
      • packages/typescript/ai-openai/src/tools/image-generation-tool.ts
      • packages/typescript/ai-openai/src/tools/index.ts
      • packages/typescript/ai-openai/src/tools/local-shell-tool.ts
      • packages/typescript/ai-openai/src/tools/mcp-tool.ts
      • packages/typescript/ai-openai/src/tools/shell-tool.ts
      • packages/typescript/ai-openai/src/tools/tool-choice.ts
      • packages/typescript/ai-openai/src/tools/tool-converter.ts
      • packages/typescript/ai-openai/src/tools/web-search-preview-tool.ts
      • packages/typescript/ai-openai/src/tools/web-search-tool.ts
      • packages/typescript/ai-openai/src/utils/client.ts
      • packages/typescript/ai-openai/src/utils/schema-converter.ts
      • packages/typescript/ai-openrouter/package.json
      • packages/typescript/ai-openrouter/src/utils/client.ts
      • packages/typescript/ai-utils/package.json
      • packages/typescript/ai-utils/src/env.ts
      • packages/typescript/ai-utils/src/id.ts
      • packages/typescript/ai-utils/src/index.ts
      • packages/typescript/ai-utils/src/model-meta/define.ts
      • packages/typescript/ai-utils/src/model-meta/types.ts
      • packages/typescript/ai-utils/src/transforms.ts
      • packages/typescript/ai-utils/tests/env.test.ts
      • packages/typescript/ai-utils/tests/id.test.ts
      • packages/typescript/ai-utils/tests/model-meta.test.ts
      • packages/typescript/ai-utils/tests/transforms.test.ts
      • packages/typescript/ai-utils/tsconfig.json
      • packages/typescript/ai-utils/vite.config.ts
      • packages/typescript/openai-base/package.json
      • packages/typescript/openai-base/src/adapters/chat-completions-text.ts
      • packages/typescript/openai-base/src/adapters/chat-completions-tool-converter.ts
      • packages/typescript/openai-base/src/adapters/image.ts
      • packages/typescript/openai-base/src/adapters/responses-text.ts
      • packages/typescript/openai-base/src/adapters/responses-tool-converter.ts
      • packages/typescript/openai-base/src/adapters/summarize.ts
      • packages/typescript/openai-base/src/adapters/transcription.ts
      • packages/typescript/openai-base/src/adapters/tts.ts
      • packages/typescript/openai-base/src/adapters/video.ts
      • packages/typescript/openai-base/src/index.ts
      • packages/typescript/openai-base/src/tools/apply-patch-tool.ts
      • packages/typescript/openai-base/src/tools/code-interpreter-tool.ts
      • packages/typescript/openai-base/src/tools/computer-use-tool.ts
      • packages/typescript/openai-base/src/tools/custom-tool.ts
      • packages/typescript/openai-base/src/tools/file-search-tool.ts
      • packages/typescript/openai-base/src/tools/function-tool.ts
      • packages/typescript/openai-base/src/tools/image-generation-tool.ts
      • packages/typescript/openai-base/src/tools/index.ts
      • packages/typescript/openai-base/src/tools/local-shell-tool.ts
      • packages/typescript/openai-base/src/tools/mcp-tool.ts
      • packages/typescript/openai-base/src/tools/shell-tool.ts
      • packages/typescript/openai-base/src/tools/tool-choice.ts
      • packages/typescript/openai-base/src/tools/tool-converter.ts
      • packages/typescript/openai-base/src/tools/web-search-preview-tool.ts
      • packages/typescript/openai-base/src/tools/web-search-tool.ts
      • packages/typescript/openai-base/src/types/config.ts
      • packages/typescript/openai-base/src/types/message-metadata.ts
      • packages/typescript/openai-base/src/types/provider-options.ts
      • packages/typescript/openai-base/src/utils/client.ts
      • packages/typescript/openai-base/src/utils/schema-converter.ts
      • packages/typescript/openai-base/tests/chat-completions-text.test.ts
      • packages/typescript/openai-base/tests/mcp-tool.test.ts
      • packages/typescript/openai-base/tests/responses-text.test.ts
      • packages/typescript/openai-base/tests/schema-converter.test.ts
      • packages/typescript/openai-base/tsconfig.json
      • packages/typescript/openai-base/vite.config.ts
      ✅ Files skipped from review due to trivial changes (36)
      • packages/typescript/ai-ollama/package.json
      • packages/typescript/ai-fal/package.json
      • packages/typescript/ai-groq/package.json
      • packages/typescript/ai-utils/tests/id.test.ts
      • packages/typescript/ai-elevenlabs/package.json
      • packages/typescript/ai-utils/tsconfig.json
      • packages/typescript/ai-elevenlabs/src/realtime/token.ts
      • packages/typescript/ai-openai/package.json
      • packages/typescript/openai-base/tsconfig.json
      • packages/typescript/openai-base/src/utils/client.ts
      • packages/typescript/ai-anthropic/package.json
      • packages/typescript/ai-grok/package.json
      • packages/typescript/ai-gemini/package.json
      • packages/typescript/ai-openai/src/tools/tool-choice.ts
      • packages/typescript/ai-openrouter/package.json
      • packages/typescript/openai-base/src/tools/web-search-preview-tool.ts
      • packages/typescript/openai-base/src/types/config.ts
      • packages/typescript/ai-utils/src/id.ts
      • .changeset/add-ai-utils-package.md
      • packages/typescript/openai-base/src/tools/local-shell-tool.ts
      • packages/typescript/openai-base/src/tools/apply-patch-tool.ts
      • packages/typescript/openai-base/src/tools/tool-converter.ts
      • packages/typescript/ai-grok/src/utils/index.ts
      • packages/typescript/ai-utils/src/index.ts
      • packages/typescript/openai-base/src/tools/code-interpreter-tool.ts
      • packages/typescript/ai-openai/src/tools/local-shell-tool.ts
      • packages/typescript/ai-openai/src/tools/custom-tool.ts
      • packages/typescript/ai-utils/tests/model-meta.test.ts
      • packages/typescript/openai-base/package.json
      • packages/typescript/openai-base/src/tools/shell-tool.ts
      • packages/typescript/openai-base/src/tools/tool-choice.ts
      • packages/typescript/ai-utils/src/model-meta/types.ts
      • packages/typescript/openai-base/src/types/message-metadata.ts
      • packages/typescript/openai-base/src/adapters/tts.ts
      • packages/typescript/openai-base/src/index.ts
      • packages/typescript/openai-base/src/adapters/responses-text.ts
      🚧 Files skipped from review as they are similar to previous changes (41)
      • packages/typescript/ai-ollama/src/utils/client.ts
      • .changeset/add-openai-base-package.md
      • packages/typescript/ai-utils/src/transforms.ts
      • packages/typescript/ai-openai/src/tools/function-tool.ts
      • packages/typescript/ai-openai/src/tools/index.ts
      • packages/typescript/ai-utils/tests/transforms.test.ts
      • packages/typescript/openai-base/src/tools/web-search-tool.ts
      • packages/typescript/openai-base/src/tools/function-tool.ts
      • packages/typescript/ai-grok/src/tools/tool-converter.ts
      • packages/typescript/ai-groq/tests/groq-adapter.test.ts
      • packages/typescript/ai-openai/src/tools/apply-patch-tool.ts
      • packages/typescript/ai-anthropic/src/utils/client.ts
      • .changeset/refactor-providers-to-shared-packages.md
      • packages/typescript/ai-grok/src/adapters/summarize.ts
      • packages/typescript/ai-utils/vite.config.ts
      • packages/typescript/ai-openai/src/tools/shell-tool.ts
      • packages/typescript/openai-base/src/tools/image-generation-tool.ts
      • packages/typescript/ai-openai/src/tools/computer-use-tool.ts
      • packages/typescript/ai-openai/src/tools/mcp-tool.ts
      • packages/typescript/ai-openai/src/tools/file-search-tool.ts
      • packages/typescript/ai-utils/src/model-meta/define.ts
      • packages/typescript/openai-base/src/tools/mcp-tool.ts
      • packages/typescript/openai-base/src/tools/computer-use-tool.ts
      • packages/typescript/openai-base/src/tools/custom-tool.ts
      • packages/typescript/ai-utils/src/env.ts
      • packages/typescript/ai-openai/src/tools/web-search-tool.ts
      • packages/typescript/ai-openai/src/tools/code-interpreter-tool.ts
      • packages/typescript/openai-base/src/adapters/responses-tool-converter.ts
      • packages/typescript/ai-openai/src/utils/client.ts
      • packages/typescript/ai-utils/package.json
      • packages/typescript/openai-base/src/tools/file-search-tool.ts
      • packages/typescript/ai-openai/src/utils/schema-converter.ts
      • packages/typescript/openai-base/src/adapters/chat-completions-tool-converter.ts
      • packages/typescript/openai-base/src/tools/index.ts
      • packages/typescript/openai-base/src/utils/schema-converter.ts
      • packages/typescript/openai-base/src/adapters/summarize.ts
      • packages/typescript/ai-gemini/src/utils/client.ts
      • packages/typescript/openai-base/src/adapters/image.ts
      • packages/typescript/ai-openrouter/src/utils/client.ts
      • packages/typescript/openai-base/vite.config.ts
      • packages/typescript/openai-base/tests/schema-converter.test.ts
    7. Actionable comments posted: 1

      🤖 Prompt for all review comments with AI agents
      Verify each finding against the current code and only fix it if needed.
      
      Inline comments:
      In `@packages/typescript/ai-groq/src/utils/schema-converter.ts`:
      - Around line 82-93: The current normalization only patches a top-level `{ type:
      'object' }` (variable normalised) and misses nested empty-object branches,
      causing child schemas without properties to slip through
      makeStructuredOutputCompatible; update schema-converter.ts to recursively walk
      the schema before calling makeStructuredOutputCompatible and ensure any node
      with `type === 'object'` but no `properties` gets `properties: {}` (handle
      nested locations: `properties` values, `items`, `anyOf`/`oneOf`/`allOf`, and
      `additionalProperties`), keep the existing call to removeEmptyRequired for final
      cleanup, and add a regression test that constructs a schema like `{ type:
      'object', properties: { child: { type: 'object' } }, required: ['child'] }` to
      verify the nested child receives an empty properties object and passes Groq
      validation.
      🪄 Autofix (Beta)

      Fix all unresolved CodeRabbit comments on this PR:

      • Push a commit to this branch (recommended)
      • Create a new PR with the fixes

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro

      Run ID: a9d14e92-f334-464f-92c8-e0413dd4905f

      📥 Commits

      Reviewing files that changed from the base of the PR and between 9b83f1a456f5417e2e285e33e1d1d6441a5d0aeb and 19231f2d879681e30a23c5694b422a445e9e4d81.

      📒 Files selected for processing (12)
      • packages/typescript/ai-grok/src/text/text-provider-options.ts
      • packages/typescript/ai-grok/src/tools/function-tool.ts
      • packages/typescript/ai-grok/src/tools/index.ts
      • packages/typescript/ai-grok/src/tools/tool-converter.ts
      • packages/typescript/ai-groq/src/utils/client.ts
      • packages/typescript/ai-groq/src/utils/schema-converter.ts
      • packages/typescript/ai-openai/src/utils/client.ts
      • packages/typescript/openai-base/src/adapters/chat-completions-text.ts
      • packages/typescript/openai-base/src/adapters/responses-text.ts
      • packages/typescript/openai-base/src/types/provider-options.ts
      • packages/typescript/openai-base/src/utils/schema-converter.ts
      • packages/typescript/openai-base/tests/chat-completions-text.test.ts
      💤 Files with no reviewable changes (4)
      • packages/typescript/ai-grok/src/tools/index.ts
      • packages/typescript/ai-grok/src/text/text-provider-options.ts
      • packages/typescript/ai-grok/src/tools/function-tool.ts
      • packages/typescript/ai-grok/src/tools/tool-converter.ts
      ✅ Files skipped from review due to trivial changes (1)
      • packages/typescript/openai-base/src/types/provider-options.ts
      🚧 Files skipped from review as they are similar to previous changes (3)
      • packages/typescript/ai-groq/src/utils/client.ts
      • packages/typescript/openai-base/src/utils/schema-converter.ts
      • packages/typescript/openai-base/tests/chat-completions-text.test.ts
    8. Caution

      Some comments are outside the diff and can’t be posted inline due to platform limitations.

      ⚠️ Outside diff range comments (2)
      packages/typescript/ai-openai/src/adapters/video.ts (1)

      65-80: ⚠️ Potential issue | 🟡 Minor

      Validate modelOptions.size before using it.

      packages/typescript/openai-base/src/adapters/video.ts:60-71 only calls validateVideoSize(model, size) before buildRequest(). When size is omitted and this method falls back to modelOptions.size, that value skips validation and can reach the API with an unsupported size.

      🛠️ Suggested fix
      -    if (size) {
      -      request.size = size as OpenAI_SDK.Videos.VideoCreateParams['size']
      -    } else if (modelOptions?.size) {
      -      request.size = modelOptions.size
      -    }
      +    if (size) {
      +      request.size = size as OpenAI_SDK.Videos.VideoCreateParams['size']
      +    } else if (modelOptions?.size) {
      +      this.validateVideoSize(model, modelOptions.size)
      +      request.size = modelOptions.size
      +    }
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/ai-openai/src/adapters/video.ts` around lines 65 - 80,
      The buildRequest method currently assigns modelOptions.size to request.size
      without validation; ensure you validate modelOptions.size with the same
      validation used for explicit size by calling validateVideoSize(model,
      modelOptions.size) (or equivalent) before setting request.size in the fallback
      branch inside buildRequest, and only assign request.size if validation passes
      (or normalize/throw if invalid) so that modelOptions.size cannot reach the API
      unvalidated.
      packages/typescript/ai-openai/src/utils/schema-converter.ts (1)

      17-21: ⚠️ Potential issue | 🟠 Major

      Change originalRequired from default [] to optional undefined.

      The wrapper's default parameter originalRequired: Array<string> = [] prevents the fallback logic in makeStructuredOutputCompatible from working. When callers omit the second argument, the helper receives [] instead of undefined, so it cannot fall back to schema.required. This silently treats all properties as optional, incorrectly widening required fields to include null.

      While all current tests pass the second argument explicitly, the wrapper's signature invites single-argument calls that would trigger this bug. Change the default to originalRequired?: Array<string> to preserve the fallback behavior.

      Suggested fix
       export function makeOpenAIStructuredOutputCompatible(
         schema: Record<string, any>,
      -  originalRequired: Array<string> = [],
      +  originalRequired?: Array<string>,
       ): Record<string, any> {
         return makeStructuredOutputCompatible(schema, originalRequired)
       }
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/ai-openai/src/utils/schema-converter.ts` around lines 17
      - 21, The wrapper makeOpenAIStructuredOutputCompatible currently sets
      originalRequired: Array<string> = [] which prevents
      makeStructuredOutputCompatible from using its fallback (schema.required) when
      callers omit the second argument; change the signature to make originalRequired
      optional (originalRequired?: Array<string> or originalRequired: Array<string> |
      undefined) so undefined is passed through, preserving fallback behavior in
      makeStructuredOutputCompatible and keeping existing callers intact.
      🧹 Nitpick comments (1)
      packages/typescript/ai-grok/src/utils/client.ts (1)

      27-34: Consider removing the double cast for better type safety.

      Both GrokClientConfig and OpenAICompatibleClientConfig extend ClientOptions with a required apiKey: string, so they should be structurally compatible. The as unknown as pattern bypasses TypeScript's type checking entirely and could mask future type mismatches.

      ♻️ Suggested improvement
       export function toCompatibleConfig(
         config: GrokClientConfig,
       ): OpenAICompatibleClientConfig {
         return {
           ...config,
           baseURL: config.baseURL || 'https://api.x.ai/v1',
      -  } as unknown as OpenAICompatibleClientConfig
      +  }
       }

      If TypeScript complains, a single as OpenAICompatibleClientConfig would be preferable to the double cast, as it still performs some structural checking.

      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/ai-grok/src/utils/client.ts` around lines 27 - 34, The
      return value in toCompatibleConfig currently uses a double-cast which bypasses
      TypeScript checks; change the return to produce a properly typed
      OpenAICompatibleClientConfig by removing "as unknown as" and using a single cast
      or ensuring the object shape matches OpenAICompatibleClientConfig (e.g., return
      { ...config, baseURL: config.baseURL || 'https://api.x.ai/v1' } as
      OpenAICompatibleClientConfig) so the compiler verifies structural compatibility
      between GrokClientConfig and OpenAICompatibleClientConfig; update the
      toCompatibleConfig signature if needed to help the type checker locate
      mismatches.
      🤖 Prompt for all review comments with AI agents
      Verify each finding against the current code and only fix it if needed.
      
      Outside diff comments:
      In `@packages/typescript/ai-openai/src/adapters/video.ts`:
      - Around line 65-80: The buildRequest method currently assigns modelOptions.size
      to request.size without validation; ensure you validate modelOptions.size with
      the same validation used for explicit size by calling validateVideoSize(model,
      modelOptions.size) (or equivalent) before setting request.size in the fallback
      branch inside buildRequest, and only assign request.size if validation passes
      (or normalize/throw if invalid) so that modelOptions.size cannot reach the API
      unvalidated.
      
      In `@packages/typescript/ai-openai/src/utils/schema-converter.ts`:
      - Around line 17-21: The wrapper makeOpenAIStructuredOutputCompatible currently
      sets originalRequired: Array<string> = [] which prevents
      makeStructuredOutputCompatible from using its fallback (schema.required) when
      callers omit the second argument; change the signature to make originalRequired
      optional (originalRequired?: Array<string> or originalRequired: Array<string> |
      undefined) so undefined is passed through, preserving fallback behavior in
      makeStructuredOutputCompatible and keeping existing callers intact.
      
      ---
      
      Nitpick comments:
      In `@packages/typescript/ai-grok/src/utils/client.ts`:
      - Around line 27-34: The return value in toCompatibleConfig currently uses a
      double-cast which bypasses TypeScript checks; change the return to produce a
      properly typed OpenAICompatibleClientConfig by removing "as unknown as" and
      using a single cast or ensuring the object shape matches
      OpenAICompatibleClientConfig (e.g., return { ...config, baseURL: config.baseURL
      || 'https://api.x.ai/v1' } as OpenAICompatibleClientConfig) so the compiler
      verifies structural compatibility between GrokClientConfig and
      OpenAICompatibleClientConfig; update the toCompatibleConfig signature if needed
      to help the type checker locate mismatches.

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro

      Run ID: 32f81338-3bf4-43ab-8170-9f36f9066912

      📥 Commits

      Reviewing files that changed from the base of the PR and between 19231f2d879681e30a23c5694b422a445e9e4d81 and 857a88ea770b0ae64d28094daadefd887417d8bd.

      📒 Files selected for processing (56)
      • .changeset/add-ai-utils-package.md
      • .changeset/add-openai-base-package.md
      • .changeset/refactor-providers-to-shared-packages.md
      • packages/typescript/ai-anthropic/package.json
      • packages/typescript/ai-anthropic/src/utils/client.ts
      • packages/typescript/ai-elevenlabs/package.json
      • packages/typescript/ai-elevenlabs/src/realtime/token.ts
      • packages/typescript/ai-fal/package.json
      • packages/typescript/ai-fal/src/utils/client.ts
      • packages/typescript/ai-gemini/package.json
      • packages/typescript/ai-gemini/src/utils/client.ts
      • packages/typescript/ai-grok/package.json
      • packages/typescript/ai-grok/src/adapters/image.ts
      • packages/typescript/ai-grok/src/adapters/summarize.ts
      • packages/typescript/ai-grok/src/adapters/text.ts
      • packages/typescript/ai-grok/src/text/text-provider-options.ts
      • packages/typescript/ai-grok/src/tools/function-tool.ts
      • packages/typescript/ai-grok/src/tools/index.ts
      • packages/typescript/ai-grok/src/tools/tool-converter.ts
      • packages/typescript/ai-grok/src/utils/client.ts
      • packages/typescript/ai-grok/src/utils/index.ts
      • packages/typescript/ai-grok/src/utils/schema-converter.ts
      • packages/typescript/ai-grok/tests/grok-adapter.test.ts
      • packages/typescript/ai-groq/package.json
      • packages/typescript/ai-groq/src/utils/client.ts
      • packages/typescript/ai-groq/src/utils/schema-converter.ts
      • packages/typescript/ai-groq/tests/groq-adapter.test.ts
      • packages/typescript/ai-groq/tests/schema-converter.test.ts
      • packages/typescript/ai-ollama/package.json
      • packages/typescript/ai-ollama/src/utils/client.ts
      • packages/typescript/ai-openai/package.json
      • packages/typescript/ai-openai/src/adapters/image.ts
      • packages/typescript/ai-openai/src/adapters/summarize.ts
      • packages/typescript/ai-openai/src/adapters/text.ts
      • packages/typescript/ai-openai/src/adapters/transcription.ts
      • packages/typescript/ai-openai/src/adapters/tts.ts
      • packages/typescript/ai-openai/src/adapters/video.ts
      • packages/typescript/ai-openai/src/tools/apply-patch-tool.ts
      • packages/typescript/ai-openai/src/tools/code-interpreter-tool.ts
      • packages/typescript/ai-openai/src/tools/computer-use-tool.ts
      • packages/typescript/ai-openai/src/tools/custom-tool.ts
      • packages/typescript/ai-openai/src/tools/file-search-tool.ts
      • packages/typescript/ai-openai/src/tools/function-tool.ts
      • packages/typescript/ai-openai/src/tools/image-generation-tool.ts
      • packages/typescript/ai-openai/src/tools/index.ts
      • packages/typescript/ai-openai/src/tools/local-shell-tool.ts
      • packages/typescript/ai-openai/src/tools/mcp-tool.ts
      • packages/typescript/ai-openai/src/tools/shell-tool.ts
      • packages/typescript/ai-openai/src/tools/tool-choice.ts
      • packages/typescript/ai-openai/src/tools/tool-converter.ts
      • packages/typescript/ai-openai/src/tools/web-search-preview-tool.ts
      • packages/typescript/ai-openai/src/tools/web-search-tool.ts
      • packages/typescript/ai-openai/src/utils/client.ts
      • packages/typescript/ai-openai/src/utils/schema-converter.ts
      • packages/typescript/ai-openrouter/package.json
      • packages/typescript/ai-openrouter/src/utils/client.ts
      💤 Files with no reviewable changes (4)
      • packages/typescript/ai-grok/src/tools/tool-converter.ts
      • packages/typescript/ai-grok/src/text/text-provider-options.ts
      • packages/typescript/ai-grok/src/tools/index.ts
      • packages/typescript/ai-grok/src/tools/function-tool.ts
      ✅ Files skipped from review due to trivial changes (13)
      • packages/typescript/ai-ollama/package.json
      • packages/typescript/ai-groq/package.json
      • packages/typescript/ai-fal/package.json
      • packages/typescript/ai-grok/package.json
      • packages/typescript/ai-gemini/package.json
      • .changeset/add-ai-utils-package.md
      • packages/typescript/ai-openrouter/package.json
      • packages/typescript/ai-openai/package.json
      • .changeset/add-openai-base-package.md
      • .changeset/refactor-providers-to-shared-packages.md
      • packages/typescript/ai-openrouter/src/utils/client.ts
      • packages/typescript/ai-groq/tests/groq-adapter.test.ts
      • packages/typescript/ai-openai/src/tools/index.ts
      🚧 Files skipped from review as they are similar to previous changes (22)
      • packages/typescript/ai-grok/src/utils/index.ts
      • packages/typescript/ai-anthropic/package.json
      • packages/typescript/ai-elevenlabs/package.json
      • packages/typescript/ai-groq/src/utils/client.ts
      • packages/typescript/ai-openai/src/tools/tool-choice.ts
      • packages/typescript/ai-ollama/src/utils/client.ts
      • packages/typescript/ai-groq/tests/schema-converter.test.ts
      • packages/typescript/ai-fal/src/utils/client.ts
      • packages/typescript/ai-gemini/src/utils/client.ts
      • packages/typescript/ai-openai/src/tools/custom-tool.ts
      • packages/typescript/ai-openai/src/tools/shell-tool.ts
      • packages/typescript/ai-openai/src/tools/file-search-tool.ts
      • packages/typescript/ai-openai/src/tools/computer-use-tool.ts
      • packages/typescript/ai-openai/src/tools/code-interpreter-tool.ts
      • packages/typescript/ai-openai/src/tools/web-search-preview-tool.ts
      • packages/typescript/ai-openai/src/tools/tool-converter.ts
      • packages/typescript/ai-openai/src/adapters/transcription.ts
      • packages/typescript/ai-groq/src/utils/schema-converter.ts
      • packages/typescript/ai-openai/src/adapters/text.ts
      • packages/typescript/ai-openai/src/tools/local-shell-tool.ts
      • packages/typescript/ai-openai/src/tools/apply-patch-tool.ts
      • packages/typescript/ai-openai/src/utils/client.ts
    9. Actionable comments posted: 2

      🧹 Nitpick comments (2)
      packages/typescript/openai-base/src/adapters/chat-completions-text.ts (2)

      435-437: Keep TProviderOptions on the protected request mapper.

      mapOptionsToRequest() takes bare TextOptions, which erases provider-specific modelOptions typing at the main subclass extension point. Making this TextOptions<TProviderOptions> keeps provider adapters type-safe when they override request construction.

      Based on learnings: "Use type-safe per-model configuration with provider options typed based on selected model to ensure compile-time safety."

      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/openai-base/src/adapters/chat-completions-text.ts` around
      lines 435 - 437, The protected mapper mapOptionsToRequest currently accepts a
      bare TextOptions which strips provider-specific modelOptions typing; change its
      signature to accept TextOptions<TProviderOptions> (i.e.,
      mapOptionsToRequest(options: TextOptions<TProviderOptions>)) so subclasses can
      preserve provider-specific modelOptions types when overriding request
      construction—update any related generics on the adapter class or method
      declaration to propagate TProviderOptions through mapOptionsToRequest while
      keeping the same returned type
      OpenAI_SDK.Chat.Completions.ChatCompletionCreateParamsStreaming.

      51-58: Preserve the constructor config on the base adapter.

      super({}, model) guarantees this.config is always {} in subclasses, so any overridden hook that relies on the base adapter's protected config loses the constructor input. Pass the compatible subset through to BaseTextAdapter or store the original config on this class explicitly.

      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/typescript/openai-base/src/adapters/chat-completions-text.ts` around
      lines 51 - 58, The constructor currently calls super({}, model) which forces
      BaseTextAdapter's protected config to be empty; preserve the incoming
      OpenAICompatibleClientConfig by passing the compatible subset into the
      BaseTextAdapter or by storing it on this instance: update the constructor for
      the class in chat-completions-text.ts to forward the relevant config object to
      super(...) instead of {} (or assign this.config = config after super if
      BaseTextAdapter allows), and keep creating the client with
      createOpenAICompatibleClient(config); reference the constructor,
      BaseTextAdapter, super({}, model), OpenAICompatibleClientConfig, and
      createOpenAICompatibleClient when making the change.
      🤖 Prompt for all review comments with AI agents
      Verify each finding against the current code and only fix it if needed.
      
      Inline comments:
      In `@packages/typescript/openai-base/src/adapters/chat-completions-text.ts`:
      - Around line 530-534: The current loop over contentParts drops parts that
      convertContentPart() returns falsy for, allowing a message to become empty;
      instead, after mapping contentParts to parts (the array filled in the loop that
      uses convertContentPart), check if parts.length === 0 and throw (or return) a
      clear capability error indicating unsupported ContentPart types so we fail fast;
      apply the same guard wherever the code similarly builds parts/content (including
      the other conversions around the blocks that reference convertContentPart and
      content fallback) so you don't send an empty prompt.
      - Around line 76-80: The stream handler currently drops terminal chunks that
      have no choices but contain usage (due to the `if (!choice) continue` guard when
      iterating responses from `this.client.chat.completions.create`), causing
      RUN_FINISHED to be emitted before the iterator is fully consumed and before
      token counts are available; update the loop(s) that process the streaming
      response (the chat completions create stream handling and the similar blocks
      around the other processing loops) to: 1) detect and handle terminal chunks that
      contain `usage` even when `choices` is empty instead of skipping them, 2)
      aggregate and expose usage/token counts from that final chunk to the same state
      that triggers RUN_FINISHED, and 3) only emit RUN_FINISHED (and close/resolve the
      iterator) after the stream is fully exhausted and that final usage chunk has
      been processed. Ensure the change is applied to all analogous loops that
      currently `continue` on missing `choices`.
      
      ---
      
      Nitpick comments:
      In `@packages/typescript/openai-base/src/adapters/chat-completions-text.ts`:
      - Around line 435-437: The protected mapper mapOptionsToRequest currently
      accepts a bare TextOptions which strips provider-specific modelOptions typing;
      change its signature to accept TextOptions<TProviderOptions> (i.e.,
      mapOptionsToRequest(options: TextOptions<TProviderOptions>)) so subclasses can
      preserve provider-specific modelOptions types when overriding request
      construction—update any related generics on the adapter class or method
      declaration to propagate TProviderOptions through mapOptionsToRequest while
      keeping the same returned type
      OpenAI_SDK.Chat.Completions.ChatCompletionCreateParamsStreaming.
      - Around line 51-58: The constructor currently calls super({}, model) which
      forces BaseTextAdapter's protected config to be empty; preserve the incoming
      OpenAICompatibleClientConfig by passing the compatible subset into the
      BaseTextAdapter or by storing it on this instance: update the constructor for
      the class in chat-completions-text.ts to forward the relevant config object to
      super(...) instead of {} (or assign this.config = config after super if
      BaseTextAdapter allows), and keep creating the client with
      createOpenAICompatibleClient(config); reference the constructor,
      BaseTextAdapter, super({}, model), OpenAICompatibleClientConfig, and
      createOpenAICompatibleClient when making the change.
      🪄 Autofix (Beta)

      Fix all unresolved CodeRabbit comments on this PR:

      • Push a commit to this branch (recommended)
      • Create a new PR with the fixes

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro

      Run ID: ddc97292-0225-4c8e-85ef-29bdbe352faf

      📥 Commits

      Reviewing files that changed from the base of the PR and between 857a88ea770b0ae64d28094daadefd887417d8bd and 5e425bddaa82cda3adccc3671bcb3943abb5dd61.

      📒 Files selected for processing (10)
      • packages/typescript/ai-anthropic/package.json
      • packages/typescript/ai-elevenlabs/package.json
      • packages/typescript/ai-fal/package.json
      • packages/typescript/ai-gemini/package.json
      • packages/typescript/ai-gemini/src/utils/client.ts
      • packages/typescript/ai-grok/package.json
      • packages/typescript/ai-openai/package.json
      • packages/typescript/openai-base/src/adapters/chat-completions-text.ts
      • packages/typescript/openai-base/src/adapters/responses-text.ts
      • packages/typescript/openai-base/src/tools/tool-choice.ts
      ✅ Files skipped from review due to trivial changes (5)
      • packages/typescript/ai-fal/package.json
      • packages/typescript/ai-anthropic/package.json
      • packages/typescript/ai-gemini/package.json
      • packages/typescript/ai-elevenlabs/package.json
      • packages/typescript/ai-openai/package.json
      🚧 Files skipped from review as they are similar to previous changes (4)
      • packages/typescript/ai-grok/package.json
      • packages/typescript/openai-base/src/tools/tool-choice.ts
      • packages/typescript/ai-gemini/src/utils/client.ts
      • packages/typescript/openai-base/src/adapters/responses-text.ts
    10. tombeckenham requested changes

      This is a good move moving common code to base. In future, it would be useful if you'd re-organised in one PR, then made changes in another PR. It took quite a long time to review as I was comparing the base to the original and there were changes as well as reorganisation. It was a good exercise to go through though as it gave me a chance to properly go through all of the code.

      Please take a look through the suggestions. There are some changes you should make

      packages/typescript/ai-utils/src/env.ts line 5Resolvedby tombeckenham
      packages/typescript/openai-base/src/adapters/image.ts line 144OutdatedResolvedby tombeckenham
      packages/typescript/ai-openai/src/adapters/summarize.ts line 45OutdatedResolvedby tombeckenham
      packages/typescript/openai-base/src/adapters/video.ts line 127OutdatedResolvedby tombeckenham
      packages/typescript/openai-base/src/adapters/video.ts line 148OutdatedResolvedby tombeckenham
      packages/typescript/ai-grok/src/utils/client.ts line 33OutdatedResolvedby tombeckenham
      packages/typescript/ai-grok/src/utils/client.ts line 5OutdatedResolvedby tombeckenham
      packages/typescript/ai-openai/src/utils/client.ts line 5OutdatedResolvedby tombeckenham
      packages/typescript/ai-openai/src/utils/client.ts line 26OutdatedResolvedby tombeckenham
      packages/typescript/ai-utils/tests/model-meta.test.ts line 5OutdatedResolvedby tombeckenham
      packages/typescript/ai-openai/src/adapters/text.ts line 102OutdatedResolvedby tombeckenham
    11. @alem — flagging a question about migration scope, specifically around openrouter.

      On this branch, only ai-openai and ai-grok extend the new bases. ai-groq, ai-openrouter, and ai-ollama still extend BaseTextAdapter directly — together that's ~2k lines of duplicated text-adapter code the bases were designed to absorb.

      For groq the migration looks mechanical (Chat Completions wire format, OpenAI SDK works fine pointed at Groq's endpoint). openrouter is the interesting one — wanted to flag the design question before assuming it slots in.

      Wire format: identical. SDK shape: not.

      OpenRouter's HTTP API is OpenAI-compatible Chat Completions, so on the wire the base's SSE accumulator, partial-JSON, tool-call buffers, and RUN_ERROR taxonomy all apply unchanged. But the TypeScript SDK (@openrouter/sdk, Speakeasy-generated) has a different shape from the OpenAI SDK the base assumes:

      OpenAI SDK (base)@openrouter/sdk
      Call shapeclient.chat.completions.create(params)client.chat.send({ chatRequest: params })
      Field namingsnake_case (max_completion_tokens, top_p)camelCase (maxCompletionTokens, topP)
      Abort errorAPIUserAbortErrorRequestAbortedError from @openrouter/sdk/models/errors

      Grok gets away with a 60-line subclass because xAI's "OpenAI-compatible" endpoint accepts the OpenAI SDK verbatim — toCompatibleConfig just rewrites the baseURL. OpenRouter's SDK is not a drop-in.

      OpenRouter-specific surface

      These are real user-facing features, not incidental:

      1. Provider routing — provider: { order, fallbacks, allow_fallbacks, sort, ignore }, models[] fallback chain, route, transforms: ['middle-out']. OpenRouter's distinguishing feature.
      2. Response metadata — which provider served the request, which underlying model was actually used, generation ID for cost lookup.
      3. App attribution headers — HTTP-Referer, X-Title.

      Considered and ruled out: dropping @openrouter/sdk

      The cleanest-looking option would be replacing @openrouter/sdk with the OpenAI SDK pointed at openrouter.ai/api/v1 (i.e., the grok approach). That deletes ~700 lines and the base works unchanged.

      I ruled it out: it forces provider routing through untyped extra_body pass-through and loses the typed response metadata. That's a type-safety regression on OpenRouter's headline feature, and the SDK is purpose-built around exactly that surface — keeping it is the point.

      Proposal: parameterize the base with two protected hooks

      Add to OpenAICompatibleChatCompletionsTextAdapter:

      protected callChatCompletion(params, signal): Promise<ChatCompletion>
      protected callChatCompletionStream(params, signal): AsyncIterable<ChatCompletionChunk>

      Default impl calls the OpenAI SDK (covers grok and any future "OpenAI-compatible-endpoint" providers like deepseek/together/fireworks). openrouter overrides to call @openrouter/sdk.

      Everything else — tool/message converters, SSE accumulator, partial-JSON, RUN_ERROR taxonomy, structured output, lifecycle — stays in the base. openrouter subclass collapses to ~150 lines (SDK shim + provider-routing typing + response metadata extraction) vs. 807 today.

      Why this matters for #409 specifically

      PR #527 (streaming structured output) currently duplicates ~290 lines of structuredOutput + chatStreamStructured across openai/grok/groq. The plan there is to lift that into the bases so each wire format has one implementation. That lift only covers openrouter if openrouter is on the Chat Completions base. If #409 ships with openrouter unmigrated, #527 has to either keep duplicating into openrouter or fold the openrouter migration into a feature PR.

      Questions

      1. Was leaving groq/openrouter/ollama on BaseTextAdapter deliberate (scoping #409 to "introduce bases, migrate later") or time-boxed?
      2. Open to expanding #409 to migrate groq + openrouter, or would you prefer that as a follow-up?
      3. Any concerns with the two-hook approach to the base, or alternative shapes you'd prefer?

      Happy to take a swing at the hook signatures on a side branch if it'd help the conversation.

    12. Moved the migration-scope discussion to its own issue so it doesn't get lost regardless of how this PR lands: #543

    13. tombeckenham approved these changes

      Good work on this. Approving. There is still the open questiion about the openrouter base which is important before we rebase the streaming output pr.

    14. AlemTuzlak merged this27c9aeb

    15. AlemTuzlak closed this

Sign in to join this conversation.