@ai-sdk/azure 3.0.134 → 3.0.136

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,259 @@
1
+ import type {
2
+ ImageModelV3,
3
+ ImageModelV3File,
4
+ ImageModelV3Usage,
5
+ SharedV3Warning,
6
+ } from '@ai-sdk/provider';
7
+ import {
8
+ combineHeaders,
9
+ convertBase64ToUint8Array,
10
+ createJsonErrorResponseHandler,
11
+ createJsonResponseHandler,
12
+ downloadBlob,
13
+ postFormDataToApi,
14
+ postJsonToApi,
15
+ type FetchFunction,
16
+ } from '@ai-sdk/provider-utils';
17
+ import { z } from 'zod/v4';
18
+ import type { AzureImageModelMaiOptions } from './azure-mai-image-model-options';
19
+
20
+ // MAI rejects either side below 768px; 1024x1024 is its default output.
21
+ const MIN_SIDE = 768;
22
+ const DEFAULT_PIXELS = 1024 * 1024;
23
+
24
+ /**
25
+ * MAI image generations and edits (`/mai/v1/images/*`) on Azure AI Foundry.
26
+ * The API returns one PNG per request and takes `width`/`height`, not `size`.
27
+ */
28
+ export class AzureMaiImageModel implements ImageModelV3 {
29
+ readonly specificationVersion = 'v3';
30
+ readonly provider = 'azure.image';
31
+ readonly maxImagesPerCall = 1;
32
+
33
+ constructor(
34
+ readonly modelId: string,
35
+ private readonly config: {
36
+ url: (path: string) => string;
37
+ headers: () => Record<string, string | undefined>;
38
+ fetch?: FetchFunction;
39
+ _internal?: { currentDate?: () => Date };
40
+ },
41
+ ) {}
42
+
43
+ async doGenerate(
44
+ {
45
+ prompt,
46
+ n,
47
+ size,
48
+ aspectRatio,
49
+ seed,
50
+ files,
51
+ mask,
52
+ headers,
53
+ abortSignal,
54
+ }: Parameters<ImageModelV3['doGenerate']>[0],
55
+ { autoAspectRatio, webGrounding }: AzureImageModelMaiOptions = {},
56
+ ): Promise<Awaited<ReturnType<ImageModelV3['doGenerate']>>> {
57
+ const currentDate = this.config._internal?.currentDate?.() ?? new Date();
58
+ const warnings: SharedV3Warning[] = [];
59
+
60
+ if (seed != null) {
61
+ warnings.push({ type: 'unsupported', feature: 'seed' });
62
+ }
63
+ if (mask != null) {
64
+ warnings.push({
65
+ type: 'unsupported',
66
+ feature: 'mask',
67
+ details: 'MAI image edits do not support masks.',
68
+ });
69
+ }
70
+
71
+ let dimensions = parseSize(size);
72
+ if (size != null && aspectRatio != null) {
73
+ warnings.push({
74
+ type: 'unsupported',
75
+ feature: 'aspectRatio',
76
+ details: 'aspectRatio is ignored when size is set.',
77
+ });
78
+ } else if (aspectRatio != null) {
79
+ dimensions = dimensionsForAspectRatio(aspectRatio);
80
+ if (dimensions == null) {
81
+ warnings.push({
82
+ type: 'unsupported',
83
+ feature: 'aspectRatio',
84
+ details: `Invalid aspect ratio: ${aspectRatio}.`,
85
+ });
86
+ }
87
+ }
88
+
89
+ const fields = {
90
+ model: this.modelId,
91
+ prompt,
92
+ width: dimensions?.width,
93
+ height: dimensions?.height,
94
+ auto_aspect_ratio: autoAspectRatio,
95
+ web_grounding: webGrounding,
96
+ };
97
+ const requestOptions = {
98
+ headers: combineHeaders(this.config.headers(), headers),
99
+ failedResponseHandler: maiFailedResponseHandler,
100
+ successfulResponseHandler: createJsonResponseHandler(
101
+ maiImageResponseSchema,
102
+ ),
103
+ abortSignal,
104
+ fetch: this.config.fetch,
105
+ };
106
+ const images =
107
+ files != null && files.length > 0
108
+ ? await Promise.all(files.map(file => fileToBlob(file, abortSignal)))
109
+ : undefined;
110
+
111
+ // The API ignores `n`, so a call reached with n > 1 (e.g. through an
112
+ // `api: 'mai'` override) sends one request per image.
113
+ const responses = await Promise.all(
114
+ Array.from({ length: Math.max(1, n) }, () =>
115
+ images != null
116
+ ? postFormDataToApi({
117
+ ...requestOptions,
118
+ url: this.config.url('/images/edits'),
119
+ formData: toFormData(fields, images),
120
+ })
121
+ : postJsonToApi({
122
+ ...requestOptions,
123
+ url: this.config.url('/images/generations'),
124
+ body: fields,
125
+ }),
126
+ ),
127
+ );
128
+
129
+ let usage: ImageModelV3Usage | undefined;
130
+ const metadata: Array<Record<string, number | string>> = [];
131
+ for (const { value: response } of responses) {
132
+ const textTokens = response.usage?.num_input_text_tokens ?? undefined;
133
+ const imageTokens = response.usage?.num_input_image_tokens ?? undefined;
134
+ if (response.usage != null) {
135
+ const inputTokens = addTokens(textTokens, imageTokens);
136
+ const outputTokens = response.usage.num_output_tokens ?? undefined;
137
+ usage = {
138
+ inputTokens: addTokens(usage?.inputTokens, inputTokens),
139
+ outputTokens: addTokens(usage?.outputTokens, outputTokens),
140
+ totalTokens: addTokens(
141
+ usage?.totalTokens,
142
+ addTokens(inputTokens, outputTokens),
143
+ ),
144
+ };
145
+ }
146
+ metadata.push(
147
+ ...response.data.map(() => ({
148
+ ...(response.created != null ? { created: response.created } : {}),
149
+ ...(response.size != null ? { size: response.size } : {}),
150
+ ...(textTokens != null ? { textTokens } : {}),
151
+ ...(imageTokens != null ? { imageTokens } : {}),
152
+ })),
153
+ );
154
+ }
155
+
156
+ return {
157
+ images: responses.flatMap(({ value }) =>
158
+ value.data.map(item => item.b64_json),
159
+ ),
160
+ warnings,
161
+ response: {
162
+ timestamp: currentDate,
163
+ modelId: this.modelId,
164
+ headers: responses[0]?.responseHeaders,
165
+ },
166
+ usage,
167
+ providerMetadata: { azure: { images: metadata } },
168
+ };
169
+ }
170
+ }
171
+
172
+ function addTokens(a: number | undefined, b: number | undefined) {
173
+ return a == null && b == null ? undefined : (a ?? 0) + (b ?? 0);
174
+ }
175
+
176
+ function parseSize(size: `${number}x${number}` | undefined) {
177
+ if (size == null) return undefined;
178
+ const [width, height] = size.split('x').map(Number);
179
+ return { width, height };
180
+ }
181
+
182
+ // Keeps the default 1024x1024 pixel budget, raising the short side to 768.
183
+ export function dimensionsForAspectRatio(aspectRatio: string) {
184
+ const [w, h] = aspectRatio.split(':').map(Number);
185
+ if (!(w > 0 && h > 0)) return undefined;
186
+
187
+ const ratio = w / h;
188
+ let width = Math.sqrt(DEFAULT_PIXELS * ratio);
189
+ let height = width / ratio;
190
+ if (Math.min(width, height) < MIN_SIDE) {
191
+ [width, height] =
192
+ width < height
193
+ ? [MIN_SIDE, MIN_SIDE / ratio]
194
+ : [MIN_SIDE * ratio, MIN_SIDE];
195
+ }
196
+
197
+ const floor16 = (value: number) => Math.floor(value / 16 + 1e-9) * 16;
198
+ return {
199
+ width: Math.max(MIN_SIDE, floor16(width)),
200
+ height: Math.max(MIN_SIDE, floor16(height)),
201
+ };
202
+ }
203
+
204
+ function toFormData(
205
+ fields: Record<string, string | number | boolean | undefined>,
206
+ images: Blob[],
207
+ ) {
208
+ const formData = new FormData();
209
+ for (const [key, value] of Object.entries(fields)) {
210
+ if (value != null) formData.append(key, String(value));
211
+ }
212
+
213
+ images.forEach((blob, index) => {
214
+ const extension = blob.type === 'image/jpeg' ? 'jpg' : 'png';
215
+ formData.append('image', blob, `image-${index + 1}.${extension}`);
216
+ });
217
+ return formData;
218
+ }
219
+
220
+ async function fileToBlob(
221
+ file: ImageModelV3File,
222
+ abortSignal: AbortSignal | undefined,
223
+ ): Promise<Blob> {
224
+ if (file.type === 'url') {
225
+ return downloadBlob(file.url, { abortSignal });
226
+ }
227
+
228
+ const data =
229
+ file.data instanceof Uint8Array
230
+ ? file.data
231
+ : convertBase64ToUint8Array(file.data);
232
+ return new Blob([data as BlobPart], { type: file.mediaType });
233
+ }
234
+
235
+ const maiErrorSchema = z.object({
236
+ error: z.object({
237
+ code: z.union([z.string(), z.number()]).nullish(),
238
+ message: z.string(),
239
+ }),
240
+ });
241
+
242
+ const maiFailedResponseHandler = createJsonErrorResponseHandler({
243
+ errorSchema: maiErrorSchema,
244
+ errorToMessage: data => data.error.message,
245
+ });
246
+
247
+ // Only the fields used here, to tolerate API additions.
248
+ const maiImageResponseSchema = z.object({
249
+ created: z.number().nullish(),
250
+ size: z.string().nullish(),
251
+ usage: z
252
+ .object({
253
+ num_input_text_tokens: z.number().nullish(),
254
+ num_input_image_tokens: z.number().nullish(),
255
+ num_output_tokens: z.number().nullish(),
256
+ })
257
+ .nullish(),
258
+ data: z.array(z.object({ b64_json: z.string() })),
259
+ });
@@ -27,6 +27,11 @@ import {
27
27
  withUserAgentSuffix,
28
28
  type FetchFunction,
29
29
  } from '@ai-sdk/provider-utils';
30
+ import {
31
+ azureImageModelOptions,
32
+ isMAIImageModel,
33
+ } from './azure-image-model-options';
34
+ import { AzureMaiImageModel } from './azure-mai-image-model';
30
35
  import { azureOpenaiTools } from './azure-openai-tools';
31
36
  import {
32
37
  azureSpeechModelOptions,
@@ -89,12 +94,13 @@ export interface AzureOpenAIProvider extends ProviderV3 {
89
94
  textEmbeddingModel(deploymentId: string): EmbeddingModelV3;
90
95
 
91
96
  /**
92
- * Creates an Azure OpenAI DALL-E model for image generation.
97
+ * Creates an Azure image model. MAI-Image models use the MAI image API by
98
+ * default; other IDs use OpenAI. Override with providerOptions.azure.api.
93
99
  */
94
100
  image(deploymentId: string): ImageModelV3;
95
101
 
96
102
  /**
97
- * Creates an Azure OpenAI DALL-E model for image generation.
103
+ * Creates an Azure image model. Alias of `image`.
98
104
  */
99
105
  imageModel(deploymentId: string): ImageModelV3;
100
106
 
@@ -189,6 +195,12 @@ export interface AzureOpenAIProviderSettings {
189
195
  * Speech requests do not use `baseURL` or `apiVersion`.
190
196
  */
191
197
  speechBaseURL?: string;
198
+
199
+ /**
200
+ * URL prefix for MAI image requests (MAI-Image generations and edits).
201
+ * Defaults to `https://{resourceName}.services.ai.azure.com/mai/v1`.
202
+ */
203
+ maiBaseURL?: string;
192
204
  }
193
205
 
194
206
  function getAzureOpenAIBaseURLInfo(baseURL: string | undefined) {
@@ -233,7 +245,7 @@ export function createAzure(
233
245
  });
234
246
  }
235
247
 
236
- const getHeaders = (api: 'openai' | 'speech' = 'openai') => {
248
+ const getHeaders = (api: 'mai' | 'openai' | 'speech' = 'openai') => {
237
249
  const authHeaders = tokenProvider
238
250
  ? {}
239
251
  : {
@@ -241,7 +253,12 @@ export function createAzure(
241
253
  loadApiKey({
242
254
  apiKey: options.apiKey,
243
255
  environmentVariableName: 'AZURE_API_KEY',
244
- description: api === 'speech' ? 'Azure Speech' : 'Azure OpenAI',
256
+ description:
257
+ api === 'speech'
258
+ ? 'Azure Speech'
259
+ : api === 'mai'
260
+ ? 'Azure MAI'
261
+ : 'Azure OpenAI',
245
262
  }),
246
263
  };
247
264
 
@@ -371,13 +388,25 @@ export function createAzure(
371
388
  fileIdPrefixes: ['assistant-'],
372
389
  });
373
390
 
391
+ const maiBaseURL = () =>
392
+ withoutTrailingSlash(options.maiBaseURL) ??
393
+ `https://${getResourceName()}.services.ai.azure.com/mai/v1`;
394
+
374
395
  const createImageModel = (modelId: string) =>
375
- new OpenAIImageModel(modelId, {
376
- provider: 'azure.image',
377
- url,
378
- headers: getHeaders,
379
- fetch,
380
- });
396
+ new AzureImageModel(
397
+ modelId,
398
+ new OpenAIImageModel(modelId, {
399
+ provider: 'azure.image',
400
+ url,
401
+ headers: getHeaders,
402
+ fetch,
403
+ }),
404
+ new AzureMaiImageModel(modelId, {
405
+ url: path => `${maiBaseURL()}${path}`,
406
+ headers: () => getHeaders('mai'),
407
+ fetch,
408
+ }),
409
+ );
381
410
 
382
411
  const speechBaseURL = () =>
383
412
  withoutTrailingSlash(options.speechBaseURL) ??
@@ -548,3 +577,51 @@ class AzureSpeechModel implements SpeechModelV3 {
548
577
  };
549
578
  }
550
579
  }
580
+
581
+ // Resolves the API per request: providerOptions also reach this model via Gateway.
582
+ class AzureImageModel implements ImageModelV3 {
583
+ readonly specificationVersion = 'v3';
584
+ readonly provider = 'azure.image';
585
+
586
+ constructor(
587
+ readonly modelId: string,
588
+ private readonly openai: OpenAIImageModel,
589
+ private readonly mai: AzureMaiImageModel,
590
+ ) {}
591
+
592
+ // The limit follows the default route; an `api` override is per request.
593
+ get maxImagesPerCall() {
594
+ return isMAIImageModel(this.modelId)
595
+ ? this.mai.maxImagesPerCall
596
+ : this.openai.maxImagesPerCall;
597
+ }
598
+
599
+ async doGenerate(options: Parameters<ImageModelV3['doGenerate']>[0]) {
600
+ const { api, ...maiOptions } =
601
+ (await parseProviderOptions({
602
+ provider: 'azure',
603
+ providerOptions: options.providerOptions,
604
+ schema: azureImageModelOptions,
605
+ })) ?? {};
606
+ if ((api ?? (isMAIImageModel(this.modelId) ? 'mai' : 'openai')) === 'mai') {
607
+ return this.mai.doGenerate(options, maiOptions);
608
+ }
609
+
610
+ const result = await this.openai.doGenerate(options);
611
+ return {
612
+ ...result,
613
+ warnings: [
614
+ ...result.warnings,
615
+ ...Object.entries(maiOptions)
616
+ .filter(([, value]) => value !== undefined)
617
+ .map(
618
+ ([key]): SharedV3Warning => ({
619
+ type: 'unsupported',
620
+ feature: `providerOptions.azure.${key}`,
621
+ details: 'This option requires the MAI image API.',
622
+ }),
623
+ ),
624
+ ],
625
+ };
626
+ }
627
+ }
package/src/index.ts CHANGED
@@ -29,6 +29,7 @@ export type {
29
29
  AzureResponsesSourceDocumentProviderMetadata,
30
30
  } from './azure-openai-provider-metadata';
31
31
  export { VERSION } from './version';
32
+ export type { AzureImageModelOptions } from './azure-image-model-options';
32
33
  export type { AzureSpeechModelOptions } from './azure-speech-model-options';
33
34
  export type { AzureTranscriptionModelOptions } from './azure-transcription-model-options';
34
35
  export type { AzureTranscriptionProviderMetadata } from './azure-transcription-provider-metadata';