@ai-sdk/azure 4.0.91 → 4.0.92

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,261 @@
1
+ import type {
2
+ ImageModelV4,
3
+ ImageModelV4File,
4
+ ImageModelV4Usage,
5
+ SharedV4Warning,
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 ImageModelV4 {
29
+ readonly specificationVersion = 'v4';
30
+ readonly provider = 'azure.image';
31
+ readonly maxImagesPerCall = 1;
32
+ readonly supportsFileInputs = true;
33
+ readonly supportsMaskInputs = false;
34
+
35
+ constructor(
36
+ readonly modelId: string,
37
+ private readonly config: {
38
+ url: (path: string) => string;
39
+ headers: () => Record<string, string | undefined>;
40
+ fetch?: FetchFunction;
41
+ _internal?: { currentDate?: () => Date };
42
+ },
43
+ ) {}
44
+
45
+ async doGenerate(
46
+ {
47
+ prompt,
48
+ n,
49
+ size,
50
+ aspectRatio,
51
+ seed,
52
+ files,
53
+ mask,
54
+ headers,
55
+ abortSignal,
56
+ }: Parameters<ImageModelV4['doGenerate']>[0],
57
+ { autoAspectRatio, webGrounding }: AzureImageModelMaiOptions = {},
58
+ ): Promise<Awaited<ReturnType<ImageModelV4['doGenerate']>>> {
59
+ const currentDate = this.config._internal?.currentDate?.() ?? new Date();
60
+ const warnings: SharedV4Warning[] = [];
61
+
62
+ if (seed != null) {
63
+ warnings.push({ type: 'unsupported', feature: 'seed' });
64
+ }
65
+ if (mask != null) {
66
+ warnings.push({
67
+ type: 'unsupported',
68
+ feature: 'mask',
69
+ details: 'MAI image edits do not support masks.',
70
+ });
71
+ }
72
+
73
+ let dimensions = parseSize(size);
74
+ if (size != null && aspectRatio != null) {
75
+ warnings.push({
76
+ type: 'unsupported',
77
+ feature: 'aspectRatio',
78
+ details: 'aspectRatio is ignored when size is set.',
79
+ });
80
+ } else if (aspectRatio != null) {
81
+ dimensions = dimensionsForAspectRatio(aspectRatio);
82
+ if (dimensions == null) {
83
+ warnings.push({
84
+ type: 'unsupported',
85
+ feature: 'aspectRatio',
86
+ details: `Invalid aspect ratio: ${aspectRatio}.`,
87
+ });
88
+ }
89
+ }
90
+
91
+ const fields = {
92
+ model: this.modelId,
93
+ prompt,
94
+ width: dimensions?.width,
95
+ height: dimensions?.height,
96
+ auto_aspect_ratio: autoAspectRatio,
97
+ web_grounding: webGrounding,
98
+ };
99
+ const requestOptions = {
100
+ headers: combineHeaders(this.config.headers(), headers),
101
+ failedResponseHandler: maiFailedResponseHandler,
102
+ successfulResponseHandler: createJsonResponseHandler(
103
+ maiImageResponseSchema,
104
+ ),
105
+ abortSignal,
106
+ fetch: this.config.fetch,
107
+ };
108
+ const images =
109
+ files != null && files.length > 0
110
+ ? await Promise.all(files.map(file => fileToBlob(file, abortSignal)))
111
+ : undefined;
112
+
113
+ // The API ignores `n`, so a call reached with n > 1 (e.g. through an
114
+ // `api: 'mai'` override) sends one request per image.
115
+ const responses = await Promise.all(
116
+ Array.from({ length: Math.max(1, n) }, () =>
117
+ images != null
118
+ ? postFormDataToApi({
119
+ ...requestOptions,
120
+ url: this.config.url('/images/edits'),
121
+ formData: toFormData(fields, images),
122
+ })
123
+ : postJsonToApi({
124
+ ...requestOptions,
125
+ url: this.config.url('/images/generations'),
126
+ body: fields,
127
+ }),
128
+ ),
129
+ );
130
+
131
+ let usage: ImageModelV4Usage | undefined;
132
+ const metadata: Array<Record<string, number | string>> = [];
133
+ for (const { value: response } of responses) {
134
+ const textTokens = response.usage?.num_input_text_tokens ?? undefined;
135
+ const imageTokens = response.usage?.num_input_image_tokens ?? undefined;
136
+ if (response.usage != null) {
137
+ const inputTokens = addTokens(textTokens, imageTokens);
138
+ const outputTokens = response.usage.num_output_tokens ?? undefined;
139
+ usage = {
140
+ inputTokens: addTokens(usage?.inputTokens, inputTokens),
141
+ outputTokens: addTokens(usage?.outputTokens, outputTokens),
142
+ totalTokens: addTokens(
143
+ usage?.totalTokens,
144
+ addTokens(inputTokens, outputTokens),
145
+ ),
146
+ };
147
+ }
148
+ metadata.push(
149
+ ...response.data.map(() => ({
150
+ ...(response.created != null ? { created: response.created } : {}),
151
+ ...(response.size != null ? { size: response.size } : {}),
152
+ ...(textTokens != null ? { textTokens } : {}),
153
+ ...(imageTokens != null ? { imageTokens } : {}),
154
+ })),
155
+ );
156
+ }
157
+
158
+ return {
159
+ images: responses.flatMap(({ value }) =>
160
+ value.data.map(item => item.b64_json),
161
+ ),
162
+ warnings,
163
+ response: {
164
+ timestamp: currentDate,
165
+ modelId: this.modelId,
166
+ headers: responses[0]?.responseHeaders,
167
+ },
168
+ usage,
169
+ providerMetadata: { azure: { images: metadata } },
170
+ };
171
+ }
172
+ }
173
+
174
+ function addTokens(a: number | undefined, b: number | undefined) {
175
+ return a == null && b == null ? undefined : (a ?? 0) + (b ?? 0);
176
+ }
177
+
178
+ function parseSize(size: `${number}x${number}` | undefined) {
179
+ if (size == null) return undefined;
180
+ const [width, height] = size.split('x').map(Number);
181
+ return { width, height };
182
+ }
183
+
184
+ // Keeps the default 1024x1024 pixel budget, raising the short side to 768.
185
+ export function dimensionsForAspectRatio(aspectRatio: string) {
186
+ const [w, h] = aspectRatio.split(':').map(Number);
187
+ if (!(w > 0 && h > 0)) return undefined;
188
+
189
+ const ratio = w / h;
190
+ let width = Math.sqrt(DEFAULT_PIXELS * ratio);
191
+ let height = width / ratio;
192
+ if (Math.min(width, height) < MIN_SIDE) {
193
+ [width, height] =
194
+ width < height
195
+ ? [MIN_SIDE, MIN_SIDE / ratio]
196
+ : [MIN_SIDE * ratio, MIN_SIDE];
197
+ }
198
+
199
+ const floor16 = (value: number) => Math.floor(value / 16 + 1e-9) * 16;
200
+ return {
201
+ width: Math.max(MIN_SIDE, floor16(width)),
202
+ height: Math.max(MIN_SIDE, floor16(height)),
203
+ };
204
+ }
205
+
206
+ function toFormData(
207
+ fields: Record<string, string | number | boolean | undefined>,
208
+ images: Blob[],
209
+ ) {
210
+ const formData = new FormData();
211
+ for (const [key, value] of Object.entries(fields)) {
212
+ if (value != null) formData.append(key, String(value));
213
+ }
214
+
215
+ images.forEach((blob, index) => {
216
+ const extension = blob.type === 'image/jpeg' ? 'jpg' : 'png';
217
+ formData.append('image', blob, `image-${index + 1}.${extension}`);
218
+ });
219
+ return formData;
220
+ }
221
+
222
+ async function fileToBlob(
223
+ file: ImageModelV4File,
224
+ abortSignal: AbortSignal | undefined,
225
+ ): Promise<Blob> {
226
+ if (file.type === 'url') {
227
+ return downloadBlob(file.url, { abortSignal });
228
+ }
229
+
230
+ const data =
231
+ file.data instanceof Uint8Array
232
+ ? file.data
233
+ : convertBase64ToUint8Array(file.data);
234
+ return new Blob([data as BlobPart], { type: file.mediaType });
235
+ }
236
+
237
+ const maiErrorSchema = z.object({
238
+ error: z.object({
239
+ code: z.union([z.string(), z.number()]).nullish(),
240
+ message: z.string(),
241
+ }),
242
+ });
243
+
244
+ const maiFailedResponseHandler = createJsonErrorResponseHandler({
245
+ errorSchema: maiErrorSchema,
246
+ errorToMessage: data => data.error.message,
247
+ });
248
+
249
+ // Only the fields used here, to tolerate API additions.
250
+ const maiImageResponseSchema = z.object({
251
+ created: z.number().nullish(),
252
+ size: z.string().nullish(),
253
+ usage: z
254
+ .object({
255
+ num_input_text_tokens: z.number().nullish(),
256
+ num_input_image_tokens: z.number().nullish(),
257
+ num_output_tokens: z.number().nullish(),
258
+ })
259
+ .nullish(),
260
+ data: z.array(z.object({ b64_json: z.string() })),
261
+ });
@@ -33,6 +33,11 @@ import {
33
33
  type FetchFunction,
34
34
  type WebSocketConstructor,
35
35
  } from '@ai-sdk/provider-utils';
36
+ import {
37
+ azureImageModelOptions,
38
+ isMAIImageModel,
39
+ } from './azure-image-model-options';
40
+ import { AzureMaiImageModel } from './azure-mai-image-model';
36
41
  import { AzureMaiTranscriptionModel } from './azure-mai-transcription-model';
37
42
  import { azureOpenaiTools } from './azure-openai-tools';
38
43
  import {
@@ -97,12 +102,13 @@ export interface AzureOpenAIProvider extends ProviderV4 {
97
102
  textEmbeddingModel(deploymentId: string): EmbeddingModelV4;
98
103
 
99
104
  /**
100
- * Creates an Azure OpenAI DALL-E model for image generation.
105
+ * Creates an Azure image model. MAI-Image models use the MAI image API by
106
+ * default; other IDs use OpenAI. Override with providerOptions.azure.api.
101
107
  */
102
108
  image(deploymentId: string): ImageModelV4;
103
109
 
104
110
  /**
105
- * Creates an Azure OpenAI DALL-E model for image generation.
111
+ * Creates an Azure image model. Alias of `image`.
106
112
  */
107
113
  imageModel(deploymentId: string): ImageModelV4;
108
114
 
@@ -200,8 +206,8 @@ export interface AzureOpenAIProviderSettings {
200
206
  speechBaseURL?: string;
201
207
 
202
208
  /**
203
- * URL prefix for MAI realtime APIs (MAI-Transcribe-2-Streaming).
204
- * Defaults to `https://{resourceName}.services.ai.azure.com/mai/v1`.
209
+ * URL prefix for MAI APIs (MAI-Image, MAI-Transcribe-2-Streaming). Defaults
210
+ * to `https://{resourceName}.services.ai.azure.com/mai/v1`.
205
211
  */
206
212
  maiBaseURL?: string;
207
213
 
@@ -400,19 +406,32 @@ export function createAzure(
400
406
  fileIdPrefixes: ['assistant-'],
401
407
  });
402
408
 
409
+ const maiBaseURL = () =>
410
+ withoutTrailingSlash(options.maiBaseURL) ??
411
+ `https://${getResourceName()}.services.ai.azure.com/mai/v1`;
412
+
403
413
  const createImageModel = (modelId: string) =>
404
- new OpenAIImageModel(modelId, {
405
- provider: 'azure.image',
406
- url,
407
- headers: getHeaders,
408
- fetch,
409
- // Azure model IDs are user-defined deployment names, so OpenAI model
410
- // family capabilities cannot be inferred from them.
411
- imageInputCapabilities: {
412
- supportsFileInputs: undefined,
413
- supportsMaskInputs: undefined,
414
- },
415
- });
414
+ new AzureImageModel(
415
+ modelId,
416
+ options,
417
+ new OpenAIImageModel(modelId, {
418
+ provider: 'azure.image',
419
+ url,
420
+ headers: getHeaders,
421
+ fetch,
422
+ // Azure model IDs are user-defined deployment names, so OpenAI model
423
+ // family capabilities cannot be inferred from them.
424
+ imageInputCapabilities: {
425
+ supportsFileInputs: undefined,
426
+ supportsMaskInputs: undefined,
427
+ },
428
+ }),
429
+ new AzureMaiImageModel(modelId, {
430
+ url: path => `${maiBaseURL()}${path}`,
431
+ headers: () => getHeaders('mai'),
432
+ fetch,
433
+ }),
434
+ );
416
435
 
417
436
  const speechBaseURL = () =>
418
437
  withoutTrailingSlash(options.speechBaseURL) ??
@@ -435,11 +454,7 @@ export function createAzure(
435
454
  fetch,
436
455
  }),
437
456
  new AzureMaiTranscriptionModel(modelId, {
438
- url: () =>
439
- `${
440
- withoutTrailingSlash(options.maiBaseURL) ??
441
- `https://${getResourceName()}.services.ai.azure.com/mai/v1`
442
- }/realtime?intent=transcription`,
457
+ url: () => `${maiBaseURL()}/realtime?intent=transcription`,
443
458
  headers: async () =>
444
459
  tokenProvider
445
460
  ? {
@@ -650,6 +665,74 @@ class AzureSpeechModel implements SpeechModelV4 {
650
665
  }
651
666
  }
652
667
 
668
+ // Resolves the API per request: providerOptions also reach this model via Gateway.
669
+ class AzureImageModel implements ImageModelV4 {
670
+ readonly specificationVersion = 'v4';
671
+ readonly provider = 'azure.image';
672
+
673
+ constructor(
674
+ readonly modelId: string,
675
+ private readonly config: AzureOpenAIProviderSettings,
676
+ private readonly openai: OpenAIImageModel,
677
+ private readonly mai: AzureMaiImageModel,
678
+ ) {}
679
+
680
+ // Capabilities follow the default route; an `api` override is per request.
681
+ private get defaultModel() {
682
+ return isMAIImageModel(this.modelId) ? this.mai : this.openai;
683
+ }
684
+
685
+ get maxImagesPerCall() {
686
+ return this.defaultModel.maxImagesPerCall;
687
+ }
688
+
689
+ get supportsFileInputs() {
690
+ return this.defaultModel.supportsFileInputs;
691
+ }
692
+
693
+ get supportsMaskInputs() {
694
+ return this.defaultModel.supportsMaskInputs;
695
+ }
696
+
697
+ static [WORKFLOW_SERIALIZE](model: AzureImageModel) {
698
+ return serializeModelOptions({
699
+ modelId: model.modelId,
700
+ config: model.config,
701
+ });
702
+ }
703
+
704
+ static [WORKFLOW_DESERIALIZE](options: {
705
+ modelId: string;
706
+ config: AzureOpenAIProviderSettings;
707
+ }) {
708
+ return createAzure(options.config).image(options.modelId);
709
+ }
710
+
711
+ async doGenerate(options: Parameters<ImageModelV4['doGenerate']>[0]) {
712
+ const { api, ...maiOptions } =
713
+ (await parseProviderOptions({
714
+ provider: 'azure',
715
+ providerOptions: options.providerOptions,
716
+ schema: azureImageModelOptions,
717
+ })) ?? {};
718
+ if ((api ?? (isMAIImageModel(this.modelId) ? 'mai' : 'openai')) === 'mai') {
719
+ return this.mai.doGenerate(options, maiOptions);
720
+ }
721
+
722
+ const result = await this.openai.doGenerate(options);
723
+ return {
724
+ ...result,
725
+ warnings: [
726
+ ...result.warnings,
727
+ ...unsupportedOptionWarnings(
728
+ maiOptions,
729
+ 'This option requires the MAI image API.',
730
+ ),
731
+ ],
732
+ };
733
+ }
734
+ }
735
+
653
736
  function speechOnlyWarnings(options: Record<string, unknown>) {
654
737
  return unsupportedOptionWarnings(
655
738
  options,
package/src/index.ts CHANGED
@@ -28,6 +28,7 @@ export type {
28
28
  AzureResponsesSourceDocumentProviderMetadata,
29
29
  } from './azure-openai-provider-metadata';
30
30
  export { VERSION } from './version';
31
+ export type { AzureImageModelOptions } from './azure-image-model-options';
31
32
  export type { AzureSpeechModelOptions } from './azure-speech-model-options';
32
33
  export type { AzureTranscriptionModelOptions } from './azure-transcription-model-options';
33
34
  export type { AzureTranscriptionProviderMetadata } from './azure-transcription-provider-metadata';