-
-
Notifications
You must be signed in to change notification settings - Fork 295
feat(ai-openrouter): per-request native combined tools + outputSchema mode #836
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
season179
wants to merge
9
commits into
TanStack:main
Choose a base branch
from
season179:feat/openrouter-combined-tools-schema
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
a7999f6
feat(ai-openrouter): per-request native combined tools + outputSchema…
season179 608f0c7
Support OpenRouter combined tools and schema
season179 0ae4ab6
Address OpenRouter review comments
season179 0ba58d3
Merge branch 'main' into feat/openrouter-combined-tools-schema
season179 60db187
Merge branch 'main' into feat/openrouter-combined-tools-schema
season179 2338314
Merge branch 'main' into feat/openrouter-combined-tools-schema
season179 035c585
Merge branch 'main' into feat/openrouter-combined-tools-schema
season179 e9d1841
Merge branch 'main' into feat/openrouter-combined-tools-schema
season179 18c7599
Merge remote-tracking branch 'upstream/main' into feat/openrouter-com…
season179 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| --- | ||
| '@tanstack/ai-openrouter': minor | ||
| --- | ||
|
|
||
| Add native combined tools + `outputSchema` mode to both OpenRouter text adapters (chat-completions and Responses). When the resolved upstream model supports emitting a schema-constrained final answer alongside tool calls in a single pass, `chat({ outputSchema, tools, stream: true })` now wires the JSON Schema into the same streaming request as the tools and harvests the final-turn JSON, skipping the separate finalization round-trip. | ||
|
|
||
| Because OpenRouter is a routing layer, capability is keyed per resolved upstream model via the new `OPENROUTER_COMBINED_TOOLS_AND_SCHEMA_MODELS` set, exported from `@tanstack/ai-openrouter/model-meta`, which both adapters consult from `supportsCombinedToolsAndSchema()`. The set is derived from each upstream provider's combined-mode gate (Anthropic 4.5+, Gemini 3.x, OpenAI's strict `json_schema` era, Grok 4.x) rather than the broader catalog `responseFormat` flag, so models that advertise structured output but predate native combined mode stay on the legacy finalization path. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
258 changes: 258 additions & 0 deletions
258
packages/ai-openrouter/src/adapters/openrouter-combined-structured-output.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,258 @@ | ||
| import { describe, expect, it, vi } from 'vitest' | ||
| import { | ||
| OPENROUTER_CHAT_MODELS, | ||
| OPENROUTER_COMBINED_TOOLS_AND_SCHEMA_MODELS, | ||
| } from '../model-meta' | ||
| import { createOpenRouterResponsesText } from './responses-text' | ||
| import { createOpenRouterText } from './text' | ||
| import type { Tool } from '@tanstack/ai' | ||
|
|
||
| // The adapter constructor instantiates `new OpenRouter(config)`. Mock the SDK | ||
| // so construction succeeds; these tests only exercise request building | ||
| // (`mapOptionsToRequest`) and the capability gate, never an SDK call. | ||
| vi.mock('@openrouter/sdk', () => ({ | ||
| OpenRouter: class { | ||
| chat = { send: () => undefined } | ||
| beta = { responses: { send: () => undefined } } | ||
| }, | ||
| })) | ||
|
|
||
| // JSON Schema as the engine hands it to the adapter on the combined path. | ||
| const outputSchema = { | ||
| type: 'object', | ||
| properties: { answer: { type: 'string' } }, | ||
| required: ['answer'], | ||
| } | ||
|
|
||
| const tools: Array<Tool> = [ | ||
| { name: 'lookup_weather', description: 'Return the forecast for a location' }, | ||
| ] | ||
|
|
||
| // `mapOptionsToRequest` is protected; reach it directly to assert the wire | ||
| // shape without standing up a full streaming round-trip. | ||
| type BuiltOpenRouterRequest = Record<string, unknown> & { | ||
| model?: string | ||
| models?: Array<string> | ||
| responseFormat?: unknown | ||
| text?: Record<string, unknown> & { | ||
| format?: Record<string, unknown> | ||
| verbosity?: string | ||
| } | ||
| tools?: Array<unknown> | ||
| } | ||
|
|
||
| type RequestBuilder = { | ||
| mapOptionsToRequest: (options: Record<string, unknown>) => BuiltOpenRouterRequest | ||
| } | ||
|
|
||
| function asRequestBuilder(adapter: unknown): RequestBuilder { | ||
| return adapter as RequestBuilder | ||
| } | ||
|
|
||
| function buildChatRequest( | ||
| model: string, | ||
| modelOptions?: Record<string, unknown>, | ||
| ) { | ||
| const adapter = asRequestBuilder( | ||
| createOpenRouterText(model as 'openai/gpt-4o', 'test-key'), | ||
| ) | ||
| return adapter.mapOptionsToRequest({ | ||
| model, | ||
| messages: [{ role: 'user', content: 'hi' }], | ||
| tools, | ||
| outputSchema, | ||
| ...(modelOptions ? { modelOptions } : {}), | ||
| }) | ||
| } | ||
|
|
||
| function buildResponsesRequest(model: string) { | ||
| const adapter = asRequestBuilder( | ||
| createOpenRouterResponsesText(model as 'openai/gpt-4o', 'test-key'), | ||
| ) | ||
| return adapter.mapOptionsToRequest({ | ||
| model, | ||
| messages: [{ role: 'user', content: 'hi' }], | ||
| tools, | ||
| outputSchema, | ||
| }) | ||
| } | ||
|
|
||
| describe('OpenRouter combined tools + outputSchema (#612)', () => { | ||
| describe('supportsCombinedToolsAndSchema gate', () => { | ||
| it('returns true for combined-capable upstream models', () => { | ||
| expect( | ||
| createOpenRouterText( | ||
| 'anthropic/claude-sonnet-4.5', | ||
| 'k', | ||
| ).supportsCombinedToolsAndSchema(), | ||
| ).toBe(true) | ||
| expect( | ||
| createOpenRouterText( | ||
| 'openai/gpt-4o', | ||
| 'k', | ||
| ).supportsCombinedToolsAndSchema(), | ||
| ).toBe(true) | ||
| expect( | ||
| createOpenRouterText( | ||
| 'x-ai/grok-4.3', | ||
| 'k', | ||
| ).supportsCombinedToolsAndSchema(), | ||
| ).toBe(true) | ||
| }) | ||
|
|
||
| it('returns false for upstream models the upstream gate excludes', () => { | ||
| // claude-opus-4.1 predates Anthropic combined mode (4.5+); gpt-4o-2024-05-13 | ||
| // predates strict json_schema — both have `responseFormat` in the catalog | ||
| // but are deliberately excluded. | ||
| expect( | ||
| createOpenRouterText( | ||
| 'anthropic/claude-opus-4.1', | ||
| 'k', | ||
| ).supportsCombinedToolsAndSchema(), | ||
| ).toBe(false) | ||
| expect( | ||
| createOpenRouterText( | ||
| 'openai/gpt-4o-2024-05-13', | ||
| 'k', | ||
| ).supportsCombinedToolsAndSchema(), | ||
| ).toBe(false) | ||
| }) | ||
|
|
||
| it('mirrors the gate on the Responses adapter', () => { | ||
| expect( | ||
| createOpenRouterResponsesText( | ||
| 'openai/gpt-4o', | ||
| 'k', | ||
| ).supportsCombinedToolsAndSchema(), | ||
| ).toBe(true) | ||
| expect( | ||
| createOpenRouterResponsesText( | ||
| 'openai/gpt-4o-2024-05-13', | ||
| 'k', | ||
| ).supportsCombinedToolsAndSchema(), | ||
| ).toBe(false) | ||
| }) | ||
|
|
||
| it('requires every OpenRouter fallback model to support combined mode', () => { | ||
| const adapter = createOpenRouterText('openai/gpt-4o', 'k') | ||
|
|
||
| expect( | ||
| adapter.supportsCombinedToolsAndSchema({ | ||
| models: ['anthropic/claude-sonnet-4.5'], | ||
| }), | ||
| ).toBe(true) | ||
| expect( | ||
| adapter.supportsCombinedToolsAndSchema({ | ||
| models: ['openai/gpt-4o-2024-05-13'], | ||
| }), | ||
| ).toBe(false) | ||
| }) | ||
| }) | ||
|
|
||
| describe('chat-completions request payload', () => { | ||
| it('attaches responseFormat alongside tools on the combined path', () => { | ||
| const req = buildChatRequest('openai/gpt-4o') | ||
| expect(req.responseFormat).toEqual({ | ||
| type: 'json_schema', | ||
| jsonSchema: { | ||
| name: 'structured_output', | ||
| schema: expect.any(Object), | ||
| strict: true, | ||
| }, | ||
| }) | ||
| expect(req.tools).toBeDefined() | ||
| expect(req.tools?.length).toBeGreaterThan(0) | ||
| }) | ||
|
|
||
| it('omits responseFormat for an unsupported model (legacy finalization path)', () => { | ||
| const req = buildChatRequest('anthropic/claude-opus-4.1') | ||
| expect(req.responseFormat).toBeUndefined() | ||
| // tools still flow — only the schema attachment is gated. | ||
| expect(req.tools).toBeDefined() | ||
| }) | ||
|
|
||
| it('omits responseFormat when any fallback model is unsupported', () => { | ||
| const req = buildChatRequest('openai/gpt-4o', { | ||
| models: ['openai/gpt-4o-2024-05-13'], | ||
| }) | ||
| expect(req.responseFormat).toBeUndefined() | ||
| expect(req.models).toEqual(['openai/gpt-4o-2024-05-13']) | ||
| expect(req.tools).toBeDefined() | ||
| }) | ||
|
|
||
| it('keys capability off the bare model id, ignoring the :variant suffix', () => { | ||
| const req = buildChatRequest('openai/gpt-4o', { variant: 'nitro' }) | ||
| expect(req.responseFormat).toBeDefined() | ||
| // variant rides the model id, not the wire body. | ||
| expect(req.model).toBe('openai/gpt-4o:nitro') | ||
| }) | ||
| }) | ||
|
|
||
| describe('Responses request payload', () => { | ||
| it('attaches text.format alongside tools on the combined path', () => { | ||
| const req = buildResponsesRequest('openai/gpt-4o') | ||
| expect(req.text).toEqual({ | ||
| format: { | ||
| type: 'json_schema', | ||
| name: 'structured_output', | ||
| schema: expect.any(Object), | ||
| strict: true, | ||
| }, | ||
| }) | ||
| expect(req.tools).toBeDefined() | ||
| }) | ||
|
|
||
| it('omits text.format for an unsupported model', () => { | ||
| const req = buildResponsesRequest('openai/gpt-4o-2024-05-13') | ||
| expect(req.text).toBeUndefined() | ||
| }) | ||
|
|
||
| it('omits text.format when any fallback model is unsupported', () => { | ||
| const adapter = asRequestBuilder( | ||
| createOpenRouterResponsesText('openai/gpt-4o', 'test-key'), | ||
| ) | ||
| const req = adapter.mapOptionsToRequest({ | ||
| model: 'openai/gpt-4o', | ||
| messages: [{ role: 'user', content: 'hi' }], | ||
| tools, | ||
| outputSchema, | ||
| modelOptions: { models: ['openai/gpt-4o-2024-05-13'] }, | ||
| }) | ||
| expect(req.text).toBeUndefined() | ||
| expect(req.models).toEqual(['openai/gpt-4o-2024-05-13']) | ||
| expect(req.tools).toBeDefined() | ||
| }) | ||
|
|
||
| it('preserves caller-supplied text.* fields when attaching the schema format', () => { | ||
| const adapter = asRequestBuilder( | ||
| createOpenRouterResponsesText('openai/gpt-4o', 'test-key'), | ||
| ) | ||
| const req = adapter.mapOptionsToRequest({ | ||
| model: 'openai/gpt-4o', | ||
| messages: [{ role: 'user', content: 'hi' }], | ||
| tools, | ||
| outputSchema, | ||
| modelOptions: { text: { verbosity: 'low' } }, | ||
| }) | ||
| // `text.format` carries the combined-mode schema; the caller's | ||
| // `text.verbosity` rides alongside it rather than being clobbered. | ||
| expect(req.text?.verbosity).toBe('low') | ||
| expect(req.text?.format).toMatchObject({ | ||
| type: 'json_schema', | ||
| name: 'structured_output', | ||
| strict: true, | ||
| }) | ||
| }) | ||
| }) | ||
|
|
||
| describe('set integrity', () => { | ||
| it('every combined-mode id exists in the OpenRouter catalog', () => { | ||
| const catalog = new Set<string>(OPENROUTER_CHAT_MODELS) | ||
| for (const id of OPENROUTER_COMBINED_TOOLS_AND_SCHEMA_MODELS) { | ||
| expect(catalog.has(id), `${id} is not in OPENROUTER_CHAT_MODELS`).toBe( | ||
| true, | ||
| ) | ||
| } | ||
| }) | ||
| }) | ||
| }) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
Repository: TanStack/ai
Length of output: 27493
🏁 Script executed:
Repository: TanStack/ai
Length of output: 13248
Use Zod and
toolDefinition()for test fixtures.Lines 21-29 use a raw schema and a handwritten
Tool; define the schema with Zod and create the tool withtoolDefinition(). If the tool usestoolDefinition(), implement both.server()and.client()sides for isomorphic execution.🤖 Prompt for AI Agents
Source: Coding guidelines