import type { ImageModelV4, SharedV4Warning } from '@ai-sdk/provider'; import { type Resolvable, resolve, lazySchema, zodSchema, combineHeaders, convertImageModelFileToDataUri, createBinaryResponseHandler, createJsonResponseHandler, createStatusCodeErrorResponseHandler, getFromApi, parseProviderOptions, postJsonToApi, serializeModelOptions, WORKFLOW_SERIALIZE, WORKFLOW_DESERIALIZE, type FetchFunction, } from '@ai-sdk/provider-utils'; import { z } from 'zod/v4'; import { xaiFailedResponseHandler } from './xai-error'; import { xaiImageModelOptions } from './xai-image-model-options'; import type { XaiImageModelId } from './xai-image-settings'; import { getXaiImageModelEntry } from './xai-model-catalog'; interface XaiImageModelConfig { provider: string; baseURL: string | undefined; headers?: Resolvable>; fetch?: FetchFunction; _internal?: { currentDate?: () => Date; }; } export class XaiImageModel implements ImageModelV4 { readonly specificationVersion = 'v4'; readonly maxImagesPerCall: number; get supportsFileInputs(): boolean | undefined { const support = getXaiImageModelEntry(this.modelId).capabilities.image .fileInput; return typeof support === 'boolean' ? support : undefined; } get supportsMaskInputs(): boolean | undefined { const support = getXaiImageModelEntry(this.modelId).capabilities.image .maskInput; return typeof support === 'boolean' ? support : undefined; } get provider(): string { return this.config.provider; } static [WORKFLOW_SERIALIZE](model: XaiImageModel) { return serializeModelOptions({ modelId: model.modelId, config: model.config, }); } static [WORKFLOW_DESERIALIZE](options: { modelId: XaiImageModelId; config: XaiImageModelConfig; }) { return new XaiImageModel(options.modelId, options.config); } constructor( readonly modelId: XaiImageModelId, private config: XaiImageModelConfig, ) { this.maxImagesPerCall = getXaiImageModelEntry(modelId).capabilities.image.maxImagesPerCall; } async doGenerate({ prompt, n, size, aspectRatio, seed, providerOptions, headers, abortSignal, files, mask, }: Parameters[0]): Promise< Awaited> > { const warnings: Array = []; if (size != null) { warnings.push({ type: 'unsupported', feature: 'size', details: 'This model does not support the `size` option. Use `aspectRatio` instead.', }); } if (seed != null) { warnings.push({ type: 'unsupported', feature: 'seed', }); } if (mask != null) { warnings.push({ type: 'unsupported', feature: 'mask', }); } const xaiOptions = await parseProviderOptions({ provider: 'xai', providerOptions, schema: xaiImageModelOptions, }); const hasFiles = files != null && files.length > 0; const imageUrls = hasFiles ? files.map(file => convertImageModelFileToDataUri(file)) : []; const endpoint = hasFiles ? '/images/edits' : '/images/generations'; const body: Record = { model: this.modelId, prompt, n, response_format: 'b64_json', }; if (aspectRatio != null) { body.aspect_ratio = aspectRatio; } if (xaiOptions?.output_format != null) { body.output_format = xaiOptions.output_format; } if (xaiOptions?.sync_mode != null) { body.sync_mode = xaiOptions.sync_mode; } if (xaiOptions?.aspect_ratio != null && aspectRatio == null) { body.aspect_ratio = xaiOptions.aspect_ratio; } if (xaiOptions?.resolution != null) { body.resolution = xaiOptions.resolution; } if (xaiOptions?.quality != null) { body.quality = xaiOptions.quality; } if (xaiOptions?.user != null) { body.user = xaiOptions.user; } if (imageUrls.length === 1) { body.image = { url: imageUrls[0], type: 'image_url' }; } else if (imageUrls.length > 1) { body.images = imageUrls.map(url => ({ url, type: 'image_url' })); } const baseURL = this.config.baseURL ?? 'https://api.x.ai/v1'; const currentDate = this.config._internal?.currentDate?.() ?? new Date(); const { value: response, responseHeaders } = await postJsonToApi({ url: `${baseURL}${endpoint}`, headers: combineHeaders(await resolve(this.config.headers), headers), body, failedResponseHandler: xaiFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler( xaiImageResponseSchema, ), abortSignal, fetch: this.config.fetch, }); if (response.data.some(image => image.respect_moderation === false)) { throw new Error( 'Image generation was blocked due to a content policy violation.', ); } const hasAllBase64 = response.data.every(image => image.b64_json != null); const images = hasAllBase64 ? response.data.map(image => image.b64_json!) : await Promise.all( response.data.map(image => this.downloadImage(image.url!, abortSignal), ), ); return { images, warnings, response: { timestamp: currentDate, modelId: this.modelId, headers: responseHeaders, }, providerMetadata: { xai: { images: response.data.map(item => ({ ...(item.revised_prompt ? { revisedPrompt: item.revised_prompt } : {}), })), ...(response.usage?.cost_in_usd_ticks != null ? { costInUsdTicks: response.usage.cost_in_usd_ticks } : {}), }, }, }; } private async downloadImage( url: string, abortSignal: AbortSignal | undefined, ): Promise { const { value } = await getFromApi({ url, // url is a generated-image URL from the provider response; validate it. validateUrl: true, trustedOrigin: this.config.baseURL, abortSignal, failedResponseHandler: createStatusCodeErrorResponseHandler(), successfulResponseHandler: createBinaryResponseHandler(), fetch: this.config.fetch, }); return value; } } const xaiImageResponseSchema = lazySchema(() => zodSchema( z.object({ data: z.array( z.object({ url: z.string().nullish(), b64_json: z.string().nullish(), revised_prompt: z.string().nullish(), respect_moderation: z.boolean().nullish(), }), ), usage: z .object({ cost_in_usd_ticks: z.number().nullish(), }) .nullish(), }), ), );