Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

image.ts

276 lines8.8 KB

1import { OpenRouter } from '@openrouter/sdk'
2import {
3 isFileSource,
4 resolveMediaPrompt,
5 unsupportedFileSourceError,
6} from '@tanstack/ai'
7import { BaseImageAdapter } from '@tanstack/ai/adapters'
8import {
9 getOpenRouterApiKeyFromEnv,
10 generateId as utilGenerateId,
11} from '../utils/client'
12import { buildOpenRouterUsage } from '../usage'
13import { extractUsageCost } from './cost'
14import type { OpenRouterClientConfig } from '../utils/client'
15import type {
16 OpenRouterImageModelInputModalitiesByName,
17 OpenRouterImageModelProviderOptionsByName,
18 OpenRouterImageModelSizeByName,
19 OpenRouterImageProviderOptions,
20} from '../image/image-provider-options'
21import type {
22 GeneratedImage,
23 ImageGenerationOptions,
24 ImageGenerationResult,
25 ImagePart,
26 MediaInputMetadata,
27} from '@tanstack/ai'
28import type { OPENROUTER_IMAGE_MODELS } from '../model-meta'
29import type { ChatResult } from '@openrouter/sdk/models'
30​
31export interface OpenRouterImageConfig extends OpenRouterClientConfig {}
32​
33export type OpenRouterImageModel = (typeof OPENROUTER_IMAGE_MODELS)[number]
34​
35/**
36 * Mapping of standard image sizes to their aspect ratios
37 * Used for Gemini and other models that support aspect ratio configuration
38 */
39const SIZE_TO_ASPECT_RATIO: Record<string, string> = {
40 '1024x1024': '1:1', // default
41 '832x1248': '2:3',
42 '1248x832': '3:2',
43 '864x1184': '3:4',
44 '1184x864': '4:3',
45 '896x1152': '4:5',
46 '1152x896': '5:4',
47 '768x1344': '9:16',
48 '1344x768': '16:9',
49 '1536x672': '21:9',
51​
52/**
53 * Resolve a requested size to the aspect ratio OpenRouter's chat-completions
54 * image pathway understands (`image_config.aspect_ratio`). The pathway has
55 * no free-form size field, so a size outside the mapping table cannot be
56 * expressed — throw rather than silently generating at the default 1:1.
57 * Accepts the multiplication sign ('×') as a separator for tolerance.
58 */
59function sizeToAspectRatio(size: string | undefined): string | undefined {
60 if (!size) return undefined
61 const normalized = size.replace('×', 'x')
62 const aspectRatio = SIZE_TO_ASPECT_RATIO[normalized]
63 if (!aspectRatio) {
64 throw new Error(
65 `openrouter: unsupported image size '${size}'. Supported sizes: ${Object.keys(SIZE_TO_ASPECT_RATIO).join(', ')}.`,
66 )
67 }
68 return aspectRatio
70​
71/**
72 * Convert a TanStack ImagePart into the URL string accepted by OpenRouter's
73 * `image_url` content parts: public URLs pass through, data sources become
74 * base64 data URIs.
75 */
76function imagePartToUrl(part: ImagePart<MediaInputMetadata>): string {
77 if (isFileSource(part.source)) throw unsupportedFileSourceError('openrouter')
78 if (part.source.type === 'url') return part.source.value
79 return `data:${part.source.mimeType};base64,${part.source.value}`
81​
82export class OpenRouterImageAdapter<
83 TModel extends OpenRouterImageModel,
84> extends BaseImageAdapter<
85 TModel,
86 OpenRouterImageProviderOptions,
87 OpenRouterImageModelProviderOptionsByName,
88 OpenRouterImageModelSizeByName,
89 OpenRouterImageModelInputModalitiesByName
90> {
91 override readonly kind = 'image' as const
92 readonly name = 'openrouter' as const
93​
94 private readonly client: OpenRouter
95​
96 constructor(config: OpenRouterImageConfig, model: TModel) {
97 super(model, {})
98 this.client = new OpenRouter({
99 ...config,
100 apiKey: config.apiKey,
101 serverURL: config.baseURL,
102 })
103 }
104​
105 async generateImages(
106 options: ImageGenerationOptions<OpenRouterImageProviderOptions>,
107 ): Promise<ImageGenerationResult> {
108 const resolved = resolveMediaPrompt(options.prompt)
109​
110 if (resolved.videos.length > 0 || resolved.audios.length > 0) {
111 throw new Error(
112 `openrouter.generateImages does not support video / audio prompt parts on model ${this.model}.`,
113 )
114 }
115​
116 const { model, numberOfImages, size, modelOptions, logger } = options
117 // OpenRouter's chat-completions image pathway returns exactly one image
118 // per request and ignores any count key in image_config (verified
119 // against the live API), so reject multi-image requests instead of
120 // silently under-delivering.
121 if (numberOfImages !== undefined && numberOfImages > 1) {
122 throw new Error(
123 `openrouter: the chat-completions image pathway generates one image per request (numberOfImages: ${numberOfImages}). Make multiple requests instead.`,
124 )
125 }
126 const aspectRatio = sizeToAspectRatio(size)
127​
128 // Image-conditioned generation: map the prompt parts 1:1 onto
129 // chat-completions content parts, preserving the interleaved order —
130 // OpenRouter forwards them to the underlying image model (e.g. Gemini
131 // image models), where position is meaningful. Role hints carry no
132 // per-field semantics on this pathway.
133 type ContentItem =
134 | { type: 'text'; text: string }
135 | { type: 'image_url'; imageUrl: { url: string } }
136 const content =
137 resolved.images.length > 0
138 ? resolved.parts.flatMap((part): Array<ContentItem> => {
139 if (part.type === 'text') {
140 return [{ type: 'text', text: part.content }]
141 }
142 if (part.type === 'image') {
143 return [
144 { type: 'image_url', imageUrl: { url: imagePartToUrl(part) } },
145 ]
146 }
147 // Video / audio parts were rejected above.
148 return []
149 })
150 : resolved.text
151​
152 logger.request(
153 `activity=generateImage provider=openrouter model=${this.model}`,
154 {
155 provider: 'openrouter',
156 model: this.model,
157 },
158 )
159​
160 const response = await this.client.chat.send({
161 chatRequest: {
162 model,
163 messages: [
164 {
165 role: 'user',
166 content,
167 },
168 ],
169 modalities: ['image'],
170 stream: false,
171 // The SDK serializes this record verbatim as `image_config`, so keys
172 // must match the HTTP API's documented snake_case fields — miskeyed
173 // entries are silently ignored by the gateway (verified live:
174 // `aspect_ratio` changes output dimensions, `aspectRatio` does not).
175 imageConfig: {
176 ...(aspectRatio
177 ? {
178 aspect_ratio: aspectRatio,
179 }
180 : {}),
181 ...(modelOptions?.image_size
182 ? {
183 image_size: modelOptions.image_size,
184 }
185 : {}),
186 ...(modelOptions?.strength !== undefined
187 ? {
188 strength: modelOptions.strength,
189 }
190 : {}),
191 },
192 },
193 })
194​
195 // Check for error in response
196 if ('error' in response && response.error) {
197 const { error } = response
198 const errorMsg =
199 typeof error === 'object' && 'message' in error
200 ? String(error.message)
201 : String(error)
202 throw new Error(`Image generation failed: ${errorMsg}`)
203 }
204​
205 return this.transformResponse(model, response)
206 }
207​
208 protected override generateId(): string {
209 return utilGenerateId(this.name)
210 }
211​
212 private transformResponse(
213 model: string,
214 response: ChatResult,
215 ): ImageGenerationResult {
216 const images: Array<GeneratedImage> = []
217​
218 for (const choice of response.choices) {
219 const choiceImages = choice.message.images
220 if (choiceImages) {
221 for (const img of choiceImages) {
222 if (typeof img.imageUrl.url !== 'string') {
223 continue
224 }
225 const url = img.imageUrl.url
226 if (url.startsWith('data:')) {
227 const base64Match = url.match(/^data:image\/[^;]+;base64,(.+)$/)
228 if (base64Match && base64Match[1]) {
229 images.push({ b64Json: base64Match[1] })
230 } else {
231 images.push({ url })
232 }
233 } else {
234 images.push({ url })
235 }
236 }
237 }
238 }
239​
240 if (images.length === 0) {
241 throw new Error('Image generation failed: response contained no images')
242 }
243​
244 // OpenRouter routes image generation through the chat surface, so the
245 // response carries the same `usage` shape as text. Surface it (with any
246 // detail breakdowns and provider-reported cost) when present.
247 const baseUsage = buildOpenRouterUsage(response.usage)
248 const usage = baseUsage && {
249 ...baseUsage,
250 ...extractUsageCost(response.usage),
251 }
252​
253 return {
254 id: response.id || this.generateId(),
255 model: response.model || model,
256 images,
257 ...(usage ? { usage } : {}),
258 }
259 }
261​
262export function createOpenRouterImage<TModel extends OpenRouterImageModel>(
263 model: TModel,
264 apiKey: string,
265 config?: Omit<OpenRouterImageConfig, 'apiKey'>,
266): OpenRouterImageAdapter<TModel> {
267 return new OpenRouterImageAdapter({ apiKey, ...config }, model)
269​
270export function openRouterImage<TModel extends OpenRouterImageModel>(
271 model: TModel,
272 config?: Omit<OpenRouterImageConfig, 'apiKey'>,
273): OpenRouterImageAdapter<TModel> {
274 const apiKey = getOpenRouterApiKeyFromEnv()
275 return createOpenRouterImage(model, apiKey, config)