Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/giant-garlics-crash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@tanstack/ai-openrouter': patch
---

- Bump `@openrouter/sdk` to 0.9.11
- Updated model list with latest models (Opus 4.6, Sonnet 4.6, Gemini 3.1 Pro, etc.)
- Native structured output support for OpenRouter
- Refactored text-provider-options to derive types from SDK's `ChatGenerationParams`
- Refactored options passthrough to use camelCase naming convention
- Improved error handling
2 changes: 1 addition & 1 deletion examples/ts-react-chat/src/routes/api.tanchat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ export const Route = createFileRoute('/api/tanchat')({
createChatOptions({
adapter: openRouterText('openai/gpt-5.1'),
modelOptions: {
models: ['openai/chatgpt-4o-latest'],
models: ['openai/gpt-4o'],
route: 'fallback',
reasoning: {
effort: 'medium',
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
"dev": "pnpm run watch",
"format": "prettier --experimental-cli --ignore-unknown '**/*' --write",
"generate-docs": "node scripts/generate-docs.ts && pnpm run copy:readme",
"generate:models": "tsx scripts/convert-openrouter-models.ts",
"generate:models": "tsx scripts/fetch-openrouter-models.ts && tsx scripts/convert-openrouter-models.ts 2>/dev/null && tsx scripts/compare-openrouter-models.ts",
"sync-docs-config": "node scripts/sync-docs-config.ts",
"copy:readme": "cp README.md packages/typescript/ai/README.md && cp README.md packages/typescript/ai-devtools/README.md && cp README.md packages/typescript/preact-ai-devtools/README.md && cp README.md packages/typescript/ai-client/README.md && cp README.md packages/typescript/ai-gemini/README.md && cp README.md packages/typescript/ai-ollama/README.md && cp README.md packages/typescript/ai-openai/README.md && cp README.md packages/typescript/ai-react/README.md && cp README.md packages/typescript/ai-react-ui/README.md && cp README.md packages/typescript/react-ai-devtools/README.md && cp README.md packages/typescript/solid-ai-devtools/README.md",
"changeset": "changeset",
Expand Down
2 changes: 1 addition & 1 deletion packages/typescript/ai-fal/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
"video-generation"
],
"dependencies": {
"@fal-ai/client": "^1.9.1"
"@fal-ai/client": "^1.9.4"
},
"devDependencies": {
"@tanstack/ai": "workspace:*",
Expand Down
2 changes: 1 addition & 1 deletion packages/typescript/ai-openrouter/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
"adapter"
],
"dependencies": {
"@openrouter/sdk": "0.3.15",
"@openrouter/sdk": "0.9.11",
"@tanstack/ai": "workspace:*"
},
"devDependencies": {
Expand Down
44 changes: 23 additions & 21 deletions packages/typescript/ai-openrouter/src/adapters/image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,28 +71,30 @@ export class OpenRouterImageAdapter<

try {
const response = await this.client.chat.send({
model,
messages: [
{
role: 'user',
content: prompt,
chatGenerationParams: {
model,
messages: [
{
role: 'user',
content: prompt,
},
],
modalities: ['image'],
stream: false,
// OpenRouter filters out invalid config per provider specifications
imageConfig: {
...(numberOfImages ? { n: numberOfImages, numberOfImages } : {}),
...(aspectRatio
? {
aspect_ratio: aspectRatio,
}
: {}),
...(modelOptions?.image_size
? {
image_size: modelOptions.image_size,
}
: {}),
},
],
modalities: ['image'],
stream: false,
// OpenRouter filters out invalid config per provider specifications
imageConfig: {
...(numberOfImages ? { n: numberOfImages, numberOfImages } : {}),
...(aspectRatio
? {
aspect_ratio: aspectRatio,
}
: {}),
...(modelOptions?.image_size
? {
image_size: modelOptions.image_size,
}
: {}),
},
})

Expand Down
86 changes: 33 additions & 53 deletions packages/typescript/ai-openrouter/src/adapters/text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,7 @@ import type {
StreamChunk,
TextOptions,
} from '@tanstack/ai'
import type {
ExternalTextProviderOptions,
InternalTextProviderOptions,
} from '../text/text-provider-options'
import type { ExternalTextProviderOptions } from '../text/text-provider-options'
import type {
OpenRouterImageMetadata,
OpenRouterMessageMetadataByModality,
Expand Down Expand Up @@ -114,7 +111,7 @@ export class OpenRouterTextAdapter<
try {
const requestParams = this.mapTextOptionsToSDK(options)
const stream = await this.client.chat.send(
{ ...requestParams, stream: true },
{ chatGenerationParams: { ...requestParams, stream: true } },
{ signal: options.request?.signal },
)

Expand Down Expand Up @@ -218,59 +215,40 @@ export class OpenRouterTextAdapter<

const requestParams = this.mapTextOptionsToSDK(chatOptions)

const structuredOutputTool = {
type: 'function' as const,
function: {
name: 'structured_output',
description:
'Use this tool to provide your response in the required structured format.',
parameters: outputSchema,
},
}

try {
const result = await this.client.chat.send(
{
...requestParams,
stream: false,
tools: [structuredOutputTool],
toolChoice: {
type: 'function',
function: { name: 'structured_output' },
chatGenerationParams: {
...requestParams,
stream: false,
responseFormat: {
type: 'json_schema',
jsonSchema: {
name: 'structured_output',
schema: outputSchema,
strict: true,
},
},
},
},
{ signal: chatOptions.request?.signal },
)

const message = result.choices[0]?.message
const toolCall = message?.toolCalls?.[0]

if (toolCall && toolCall.function.name === 'structured_output') {
const parsed = JSON.parse(toolCall.function.arguments || '{}')
return {
data: parsed,
rawText: toolCall.function.arguments || '',
}
}

const content = (message?.content as any) || ''
let parsed: unknown
try {
parsed = JSON.parse(content)
} catch {
throw new Error(
`Failed to parse structured output as JSON. Content: ${content.slice(0, 200)}${content.length > 200 ? '...' : ''}`,
)
}

return {
data: parsed,
rawText: content,
const content = result.choices[0]?.message.content
const rawText = typeof content === 'string' ? content : ''
if (!rawText) {
throw new Error('Structured output response contained no content')
}
const parsed = JSON.parse(rawText)
return { data: parsed, rawText }
} catch (error: unknown) {
if (error instanceof RequestAbortedError) {
throw new Error('Structured output generation aborted')
}
if (error instanceof SyntaxError) {
throw new Error(
`Failed to parse structured output as JSON: ${error.message}`,
)
}
const err = error as Error
throw new Error(
`Structured output generation failed: ${err.message || 'Unknown error occurred'}`,
Expand Down Expand Up @@ -508,9 +486,7 @@ export class OpenRouterTextAdapter<
private mapTextOptionsToSDK(
options: TextOptions<ResolveProviderOptions<TModel>>,
): ChatGenerationParams {
const modelOptions = options.modelOptions as
| Omit<InternalTextProviderOptions, 'model' | 'messages' | 'tools'>
| undefined
const modelOptions = options.modelOptions

const messages = this.convertMessages(options.messages)

Expand All @@ -522,14 +498,18 @@ export class OpenRouterTextAdapter<
}

const request: ChatGenerationParams = {
...modelOptions,
model:
options.model +
(modelOptions?.variant ? `:${modelOptions.variant}` : ''),
messages,
temperature: options.temperature,
maxTokens: options.maxTokens,
topP: options.topP,
...modelOptions,
...(options.temperature !== undefined && {
temperature: options.temperature,
}),
...(options.maxTokens !== undefined && {
maxCompletionTokens: options.maxTokens,
}),
...(options.topP !== undefined && { topP: options.topP }),
tools: options.tools
? convertToolsToProviderFormat(options.tools)
: undefined,
Expand Down
8 changes: 6 additions & 2 deletions packages/typescript/ai-openrouter/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,16 @@ export type {
} from './message-types'
export type {
WebPlugin,
PluginResponseHealing,
PdfParserOptions,
PluginFileParser,
PluginModeration,
PluginAutoRouter,
Plugin,
ProviderPreferences,
ReasoningOptions,
StreamOptions,
ImageConfig,
PredictionOptions,
WebSearchOptions,
} from './text/text-provider-options'

// ============================================================================
Expand Down
Loading
Loading