@ai-sdk/azure 4.0.84 → 4.0.86

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.
package/dist/index.js CHANGED
@@ -1,476 +1,348 @@
1
- // src/azure-openai-provider.ts
2
- import {
3
- OpenAIChatLanguageModel,
4
- OpenAICompletionLanguageModel,
5
- OpenAIEmbeddingModel,
6
- OpenAIImageModel,
7
- OpenAIResponsesLanguageModel,
8
- OpenAISpeechModel,
9
- OpenAITranscriptionModel
10
- } from "@ai-sdk/openai/internal";
1
+ import { OpenAIChatLanguageModel, OpenAICompletionLanguageModel, OpenAIEmbeddingModel, OpenAIImageModel, OpenAIResponsesLanguageModel, OpenAISpeechModel, OpenAITranscriptionModel, codeInterpreter, fileSearch, imageGeneration, webSearch, webSearchPreview } from "@ai-sdk/openai/internal";
11
2
  import { DeepSeekChatLanguageModel } from "@ai-sdk/deepseek/internal";
12
- import {
13
- InvalidArgumentError,
14
- UnsupportedFunctionalityError
15
- } from "@ai-sdk/provider";
16
- import {
17
- loadApiKey,
18
- loadSetting,
19
- normalizeHeaders,
20
- parseProviderOptions,
21
- serializeModelOptions,
22
- WORKFLOW_DESERIALIZE,
23
- WORKFLOW_SERIALIZE,
24
- withoutTrailingSlash,
25
- withUserAgentSuffix
26
- } from "@ai-sdk/provider-utils";
27
-
28
- // src/azure-openai-tools.ts
29
- import {
30
- codeInterpreter,
31
- fileSearch,
32
- imageGeneration,
33
- webSearch,
34
- webSearchPreview
35
- } from "@ai-sdk/openai/internal";
36
- var azureOpenaiTools = {
37
- codeInterpreter,
38
- fileSearch,
39
- imageGeneration,
40
- webSearch,
41
- webSearchPreview
42
- };
43
-
44
- // src/azure-speech-transcription-model.ts
45
- import {
46
- combineHeaders,
47
- convertBase64ToUint8Array,
48
- createJsonErrorResponseHandler,
49
- createJsonResponseHandler,
50
- mediaTypeToExtension,
51
- postFormDataToApi
52
- } from "@ai-sdk/provider-utils";
53
- import { z as z3 } from "zod/v4";
54
-
55
- // src/azure-transcription-model-options.ts
56
- import {
57
- lazySchema as lazySchema2,
58
- zodSchema as zodSchema2
59
- } from "@ai-sdk/provider-utils";
60
- import { z as z2 } from "zod/v4";
61
-
62
- // src/azure-speech-transcription-model-options.ts
63
- import {
64
- lazySchema,
65
- zodSchema
66
- } from "@ai-sdk/provider-utils";
3
+ import { InvalidArgumentError, UnsupportedFunctionalityError } from "@ai-sdk/provider";
4
+ import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE, combineHeaders, convertBase64ToUint8Array, createJsonErrorResponseHandler, createJsonResponseHandler, lazySchema, loadApiKey, loadSetting, mediaTypeToExtension, normalizeHeaders, parseProviderOptions, postFormDataToApi, serializeModelOptions, withUserAgentSuffix, withoutTrailingSlash, zodSchema } from "@ai-sdk/provider-utils";
67
5
  import { z } from "zod/v4";
68
- var azureSpeechTranscriptionModelOptionsShape = () => ({
69
- /**
70
- * Timing granularity. Defaults to `segment` so that transcription results
71
- * include timed segments (Azure's own default is `none`).
72
- */
73
- timestamps: z.enum(["word", "segment", "none"]).optional(),
74
- /**
75
- * `verbatim` keeps fillers and false starts, `clean` removes them.
76
- * Azure defaults to `verbatim`.
77
- */
78
- transcribeStyle: z.enum(["verbatim", "clean"]).optional(),
79
- /**
80
- * Forces a single language, e.g. `['en']`. Omit for automatic language
81
- * detection and code switching.
82
- */
83
- locales: z.array(z.string()).length(1).optional(),
84
- /**
85
- * Speaker diarization. Speaker IDs are available in provider metadata.
86
- */
87
- diarization: z.strictObject({ enabled: z.boolean() }).optional(),
88
- /**
89
- * Keyword biasing for names and domain terminology.
90
- */
91
- phraseList: z.strictObject({ phrases: z.array(z.string()) }).optional()
6
+ //#region src/azure-openai-tools.ts
7
+ const azureOpenaiTools = {
8
+ codeInterpreter,
9
+ fileSearch,
10
+ imageGeneration,
11
+ webSearch,
12
+ webSearchPreview
13
+ };
14
+ //#endregion
15
+ //#region src/azure-speech-transcription-model-options.ts
16
+ const azureSpeechTranscriptionModelOptionsShape = () => ({
17
+ /**
18
+ * Timing granularity. Defaults to `segment` so that transcription results
19
+ * include timed segments (Azure's own default is `none`).
20
+ */
21
+ timestamps: z.enum([
22
+ "word",
23
+ "segment",
24
+ "none"
25
+ ]).optional(),
26
+ /**
27
+ * `verbatim` keeps fillers and false starts, `clean` removes them.
28
+ * Azure defaults to `verbatim`.
29
+ */
30
+ transcribeStyle: z.enum(["verbatim", "clean"]).optional(),
31
+ /**
32
+ * Forces a single language, e.g. `['en']`. Omit for automatic language
33
+ * detection and code switching.
34
+ */
35
+ locales: z.array(z.string()).length(1).optional(),
36
+ /**
37
+ * Speaker diarization. Speaker IDs are available in provider metadata.
38
+ */
39
+ diarization: z.strictObject({ enabled: z.boolean() }).optional(),
40
+ /**
41
+ * Keyword biasing for names and domain terminology.
42
+ */
43
+ phraseList: z.strictObject({ phrases: z.array(z.string()) }).optional()
92
44
  });
93
- var azureSpeechTranscriptionModelOptions = lazySchema(
94
- () => zodSchema(z.strictObject(azureSpeechTranscriptionModelOptionsShape()))
95
- );
96
-
97
- // src/azure-transcription-model-options.ts
98
- var azureTranscriptionModelOptions = lazySchema2(
99
- () => zodSchema2(
100
- z2.strictObject({
101
- /**
102
- * API to use. Defaults to Speech for MAI-Transcribe-2, OpenAI otherwise.
103
- */
104
- api: z2.enum(["openai", "speech"]).optional(),
105
- ...azureSpeechTranscriptionModelOptionsShape()
106
- })
107
- )
108
- );
45
+ lazySchema(() => zodSchema(z.strictObject(azureSpeechTranscriptionModelOptionsShape())));
46
+ //#endregion
47
+ //#region src/azure-transcription-model-options.ts
48
+ const azureTranscriptionModelOptions = lazySchema(() => zodSchema(z.strictObject({
49
+ /**
50
+ * API to use. Defaults to Speech for MAI-Transcribe-2, OpenAI otherwise.
51
+ */
52
+ api: z.enum(["openai", "speech"]).optional(),
53
+ ...azureSpeechTranscriptionModelOptionsShape()
54
+ })));
109
55
  function isMAITranscribe2(modelId) {
110
- return modelId.toLowerCase() === "mai-transcribe-2";
56
+ return modelId.toLowerCase() === "mai-transcribe-2";
111
57
  }
112
-
113
- // src/azure-speech-transcription-model.ts
58
+ //#endregion
59
+ //#region src/azure-speech-transcription-model.ts
114
60
  var AzureSpeechTranscriptionModel = class {
115
- constructor(modelId, config) {
116
- this.modelId = modelId;
117
- this.config = config;
118
- this.specificationVersion = "v4";
119
- this.provider = "azure.transcription";
120
- }
121
- async doGenerate(options, azureOptions = {}) {
122
- const timestamp = /* @__PURE__ */ new Date();
123
- const formData = new FormData();
124
- formData.append(
125
- "audio",
126
- new Blob(
127
- [
128
- typeof options.audio === "string" ? convertBase64ToUint8Array(options.audio) : options.audio
129
- ],
130
- { type: options.mediaType }
131
- ),
132
- `audio.${mediaTypeToExtension(options.mediaType)}`
133
- );
134
- formData.append(
135
- "definition",
136
- JSON.stringify({
137
- enhancedMode: {
138
- enabled: true,
139
- model: isMAITranscribe2(this.modelId) ? "MAI-Transcribe-2" : this.modelId,
140
- modelOptions: {
141
- timestamps: azureOptions.timestamps ?? "segment",
142
- transcribeStyle: azureOptions.transcribeStyle
143
- }
144
- },
145
- locales: azureOptions.locales,
146
- diarization: azureOptions.diarization,
147
- phraseList: azureOptions.phraseList
148
- })
149
- );
150
- const { value, rawValue, responseHeaders } = await postFormDataToApi({
151
- url: this.config.url(),
152
- headers: combineHeaders(this.config.headers(), options.headers),
153
- formData,
154
- abortSignal: options.abortSignal,
155
- fetch: this.config.fetch,
156
- failedResponseHandler: createJsonErrorResponseHandler({
157
- errorSchema: z3.union([
158
- z3.object({ error: z3.object({ message: z3.string() }) }),
159
- z3.object({ message: z3.string() })
160
- ]),
161
- errorToMessage: (data) => "error" in data ? data.error.message : data.message
162
- }),
163
- successfulResponseHandler: createJsonResponseHandler(responseSchema)
164
- });
165
- const phrases = value.phrases ?? [];
166
- const languages = new Set(
167
- phrases.flatMap(
168
- (phrase) => phrase.locale ? [phrase.locale.split("-")[0].toLowerCase()] : []
169
- )
170
- );
171
- const [language] = languages;
172
- const reportedLanguage = languages.size === 1 && /^[a-z]{2}$/.test(language) ? language : void 0;
173
- return {
174
- text: value.combinedPhrases.map((phrase) => phrase.text).join(" "),
175
- segments: phrases.flatMap(
176
- (phrase) => phrase.offsetMilliseconds != null && phrase.durationMilliseconds != null ? [
177
- {
178
- text: phrase.text,
179
- startSecond: phrase.offsetMilliseconds / 1e3,
180
- endSecond: (phrase.offsetMilliseconds + phrase.durationMilliseconds) / 1e3
181
- }
182
- ] : []
183
- ),
184
- language: reportedLanguage,
185
- durationInSeconds: value.durationMilliseconds != null ? value.durationMilliseconds / 1e3 : void 0,
186
- warnings: [],
187
- providerMetadata: {
188
- azure: { phrases }
189
- },
190
- response: {
191
- timestamp,
192
- modelId: this.modelId,
193
- headers: responseHeaders,
194
- body: rawValue
195
- }
196
- };
197
- }
61
+ constructor(modelId, config) {
62
+ this.modelId = modelId;
63
+ this.config = config;
64
+ this.specificationVersion = "v4";
65
+ this.provider = "azure.transcription";
66
+ }
67
+ async doGenerate(options, azureOptions = {}) {
68
+ const timestamp = /* @__PURE__ */ new Date();
69
+ const formData = new FormData();
70
+ formData.append("audio", new Blob([typeof options.audio === "string" ? convertBase64ToUint8Array(options.audio) : options.audio], { type: options.mediaType }), `audio.${mediaTypeToExtension(options.mediaType)}`);
71
+ formData.append("definition", JSON.stringify({
72
+ enhancedMode: {
73
+ enabled: true,
74
+ model: isMAITranscribe2(this.modelId) ? "MAI-Transcribe-2" : this.modelId,
75
+ modelOptions: {
76
+ timestamps: azureOptions.timestamps ?? "segment",
77
+ transcribeStyle: azureOptions.transcribeStyle
78
+ }
79
+ },
80
+ locales: azureOptions.locales,
81
+ diarization: azureOptions.diarization,
82
+ phraseList: azureOptions.phraseList
83
+ }));
84
+ const { value, rawValue, responseHeaders } = await postFormDataToApi({
85
+ url: this.config.url(),
86
+ headers: combineHeaders(this.config.headers(), options.headers),
87
+ formData,
88
+ abortSignal: options.abortSignal,
89
+ fetch: this.config.fetch,
90
+ failedResponseHandler: createJsonErrorResponseHandler({
91
+ errorSchema: z.union([z.object({ error: z.object({ message: z.string() }) }), z.object({ message: z.string() })]),
92
+ errorToMessage: (data) => "error" in data ? data.error.message : data.message
93
+ }),
94
+ successfulResponseHandler: createJsonResponseHandler(responseSchema)
95
+ });
96
+ const phrases = value.phrases ?? [];
97
+ const languages = new Set(phrases.flatMap((phrase) => phrase.locale ? [phrase.locale.split("-")[0].toLowerCase()] : []));
98
+ const [language] = languages;
99
+ const reportedLanguage = languages.size === 1 && /^[a-z]{2}$/.test(language) ? language : void 0;
100
+ return {
101
+ text: value.combinedPhrases.map((phrase) => phrase.text).join(" "),
102
+ segments: phrases.flatMap((phrase) => phrase.offsetMilliseconds != null && phrase.durationMilliseconds != null ? [{
103
+ text: phrase.text,
104
+ startSecond: phrase.offsetMilliseconds / 1e3,
105
+ endSecond: (phrase.offsetMilliseconds + phrase.durationMilliseconds) / 1e3
106
+ }] : []),
107
+ language: reportedLanguage,
108
+ durationInSeconds: value.durationMilliseconds != null ? value.durationMilliseconds / 1e3 : void 0,
109
+ warnings: [],
110
+ providerMetadata: { azure: { phrases } },
111
+ response: {
112
+ timestamp,
113
+ modelId: this.modelId,
114
+ headers: responseHeaders,
115
+ body: rawValue
116
+ }
117
+ };
118
+ }
198
119
  };
199
- var responseSchema = z3.object({
200
- combinedPhrases: z3.array(z3.object({ text: z3.string() })),
201
- durationMilliseconds: z3.number().nullish(),
202
- phrases: z3.array(
203
- z3.object({
204
- text: z3.string(),
205
- offsetMilliseconds: z3.number().nullish(),
206
- durationMilliseconds: z3.number().nullish(),
207
- locale: z3.string().nullish(),
208
- speaker: z3.number().nullish(),
209
- confidence: z3.number().nullish(),
210
- words: z3.array(
211
- z3.object({
212
- text: z3.string(),
213
- offsetMilliseconds: z3.number().nullish(),
214
- durationMilliseconds: z3.number().nullish()
215
- })
216
- ).nullish()
217
- })
218
- ).nullish()
120
+ const responseSchema = z.object({
121
+ combinedPhrases: z.array(z.object({ text: z.string() })),
122
+ durationMilliseconds: z.number().nullish(),
123
+ phrases: z.array(z.object({
124
+ text: z.string(),
125
+ offsetMilliseconds: z.number().nullish(),
126
+ durationMilliseconds: z.number().nullish(),
127
+ locale: z.string().nullish(),
128
+ speaker: z.number().nullish(),
129
+ confidence: z.number().nullish(),
130
+ words: z.array(z.object({
131
+ text: z.string(),
132
+ offsetMilliseconds: z.number().nullish(),
133
+ durationMilliseconds: z.number().nullish()
134
+ })).nullish()
135
+ })).nullish()
219
136
  });
220
-
221
- // src/version.ts
222
- var VERSION = true ? "4.0.84" : "0.0.0-test";
223
-
224
- // src/azure-openai-provider.ts
137
+ //#endregion
138
+ //#region src/version.ts
139
+ const VERSION = "4.0.86";
140
+ //#endregion
141
+ //#region src/azure-openai-provider.ts
225
142
  function getAzureOpenAIBaseURLInfo(baseURL) {
226
- if (baseURL == null) {
227
- return {
228
- isAzureOpenAI: true,
229
- isFoundryProject: false,
230
- isVersioned: false
231
- };
232
- }
233
- const url = new URL(baseURL);
234
- const hostname = url.hostname;
235
- const isAzureOpenAI = hostname.endsWith(".openai.azure.com") || hostname.endsWith(".services.ai.azure.com") || hostname.endsWith(".cognitiveservices.azure.com");
236
- const pathname = url.pathname.replace(/\/+$/, "");
237
- return {
238
- isAzureOpenAI,
239
- isFoundryProject: hostname.endsWith(".services.ai.azure.com") && pathname.startsWith("/api/projects/"),
240
- isVersioned: isAzureOpenAI && pathname.toLowerCase().endsWith("/openai/v1")
241
- };
143
+ if (baseURL == null) return {
144
+ isAzureOpenAI: true,
145
+ isFoundryProject: false,
146
+ isVersioned: false
147
+ };
148
+ const url = new URL(baseURL);
149
+ const hostname = url.hostname;
150
+ const isAzureOpenAI = hostname.endsWith(".openai.azure.com") || hostname.endsWith(".services.ai.azure.com") || hostname.endsWith(".cognitiveservices.azure.com");
151
+ const pathname = url.pathname.replace(/\/+$/, "");
152
+ return {
153
+ isAzureOpenAI,
154
+ isFoundryProject: hostname.endsWith(".services.ai.azure.com") && pathname.startsWith("/api/projects/"),
155
+ isVersioned: isAzureOpenAI && pathname.toLowerCase().endsWith("/openai/v1")
156
+ };
242
157
  }
158
+ /**
159
+ * Create an Azure OpenAI provider instance.
160
+ */
243
161
  function createAzure(options = {}) {
244
- const tokenProvider = options.tokenProvider;
245
- if (options.apiKey && tokenProvider) {
246
- throw new InvalidArgumentError({
247
- argument: "apiKey/tokenProvider",
248
- message: "Both apiKey and tokenProvider were provided. Please use only one authentication method."
249
- });
250
- }
251
- const getHeaders = (api = "openai") => {
252
- const authHeaders = tokenProvider ? {} : {
253
- [api === "speech" ? "Ocp-Apim-Subscription-Key" : "api-key"]: loadApiKey({
254
- apiKey: options.apiKey,
255
- environmentVariableName: "AZURE_API_KEY",
256
- description: api === "speech" ? "Azure Speech" : "Azure OpenAI"
257
- })
258
- };
259
- return withUserAgentSuffix(
260
- {
261
- ...authHeaders,
262
- ...options.headers
263
- },
264
- `ai-sdk-azure/${VERSION}`
265
- );
266
- };
267
- const fetch = tokenProvider ? async (input, init) => {
268
- const headers = normalizeHeaders(init?.headers);
269
- if (headers.authorization == null) {
270
- headers.authorization = `Bearer ${await tokenProvider()}`;
271
- }
272
- return (options.fetch ?? globalThis.fetch)(input, {
273
- ...init,
274
- headers
275
- });
276
- } : options.fetch;
277
- const getResourceName = () => {
278
- const resourceName = loadSetting({
279
- settingValue: options.resourceName,
280
- settingName: "resourceName",
281
- environmentVariableName: "AZURE_RESOURCE_NAME",
282
- description: "Azure OpenAI resource name"
283
- });
284
- if (!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(resourceName)) {
285
- throw new InvalidArgumentError({
286
- argument: "resourceName",
287
- message: "Invalid Azure resource name. Expected a single DNS label (letters, digits, and hyphens). Use `baseURL` for custom endpoints."
288
- });
289
- }
290
- return resourceName;
291
- };
292
- const apiVersion = options.apiVersion ?? "v1";
293
- const {
294
- isAzureOpenAI,
295
- isFoundryProject,
296
- isVersioned: isAzureOpenAIVersioned
297
- } = getAzureOpenAIBaseURLInfo(options.baseURL);
298
- const url = ({ path, modelId }) => {
299
- const baseUrlPrefix = withoutTrailingSlash(
300
- options.baseURL ?? `https://${getResourceName()}.openai.azure.com/openai`
301
- );
302
- let fullUrl;
303
- if (options.useDeploymentBasedUrls) {
304
- fullUrl = new URL(`${baseUrlPrefix}/deployments/${modelId}${path}`);
305
- } else if (!isAzureOpenAI || isAzureOpenAIVersioned) {
306
- fullUrl = new URL(`${baseUrlPrefix}${path}`);
307
- } else {
308
- fullUrl = new URL(`${baseUrlPrefix}/v1${path}`);
309
- }
310
- if (options.useDeploymentBasedUrls || isAzureOpenAI && !isAzureOpenAIVersioned && !isFoundryProject) {
311
- fullUrl.searchParams.set("api-version", apiVersion);
312
- }
313
- return fullUrl.toString();
314
- };
315
- const createChatModel = (deploymentName) => new OpenAIChatLanguageModel(deploymentName, {
316
- provider: "azure.chat",
317
- url,
318
- headers: getHeaders,
319
- fetch
320
- });
321
- const createDeepSeekModel = (deploymentName) => new DeepSeekChatLanguageModel(deploymentName, {
322
- provider: "azure.deepseek",
323
- url,
324
- headers: getHeaders,
325
- fetch,
326
- supportsPenaltySampling: true,
327
- supportsThinking: false,
328
- // json_object with thinking enabled makes Azure return the JSON in reasoning_content with empty content
329
- supportsStructuredOutputs: true
330
- });
331
- const createCompletionModel = (modelId) => new OpenAICompletionLanguageModel(modelId, {
332
- provider: "azure.completion",
333
- url,
334
- headers: getHeaders,
335
- fetch
336
- });
337
- const createEmbeddingModel = (modelId) => new OpenAIEmbeddingModel(modelId, {
338
- provider: "azure.embeddings",
339
- headers: getHeaders,
340
- url,
341
- fetch
342
- });
343
- const createResponsesModel = (modelId) => new OpenAIResponsesLanguageModel(modelId, {
344
- provider: "azure.responses",
345
- url,
346
- headers: getHeaders,
347
- fetch,
348
- explicitMessageItemType: isFoundryProject,
349
- // Soft-deprecated. TODO: remove in v8
350
- fileIdPrefixes: ["assistant-"]
351
- });
352
- const createImageModel = (modelId) => new OpenAIImageModel(modelId, {
353
- provider: "azure.image",
354
- url,
355
- headers: getHeaders,
356
- fetch,
357
- // Azure model IDs are user-defined deployment names, so OpenAI model
358
- // family capabilities cannot be inferred from them.
359
- imageInputCapabilities: {
360
- supportsFileInputs: void 0,
361
- supportsMaskInputs: void 0
362
- }
363
- });
364
- const createTranscriptionModel = (modelId) => new AzureTranscriptionModel(
365
- modelId,
366
- options,
367
- new OpenAITranscriptionModel(modelId, {
368
- provider: "azure.transcription",
369
- url,
370
- headers: getHeaders,
371
- fetch
372
- }),
373
- new AzureSpeechTranscriptionModel(modelId, {
374
- url: () => `${withoutTrailingSlash(options.speechBaseURL) ?? `https://${getResourceName()}.cognitiveservices.azure.com`}/speechtotext/transcriptions:transcribe?api-version=2025-10-15`,
375
- headers: () => getHeaders("speech"),
376
- fetch
377
- })
378
- );
379
- const createSpeechModel = (modelId) => new OpenAISpeechModel(modelId, {
380
- provider: "azure.speech",
381
- url,
382
- headers: getHeaders,
383
- fetch
384
- });
385
- const provider = function(deploymentId) {
386
- if (new.target) {
387
- throw new Error(
388
- "The Azure OpenAI model function cannot be called with the new keyword."
389
- );
390
- }
391
- return createResponsesModel(deploymentId);
392
- };
393
- provider.specificationVersion = "v4";
394
- provider.languageModel = createResponsesModel;
395
- provider.chat = createChatModel;
396
- provider.deepseek = createDeepSeekModel;
397
- provider.completion = createCompletionModel;
398
- provider.embedding = createEmbeddingModel;
399
- provider.embeddingModel = createEmbeddingModel;
400
- provider.textEmbedding = createEmbeddingModel;
401
- provider.textEmbeddingModel = createEmbeddingModel;
402
- provider.image = createImageModel;
403
- provider.imageModel = createImageModel;
404
- provider.responses = createResponsesModel;
405
- provider.transcription = createTranscriptionModel;
406
- provider.transcriptionModel = createTranscriptionModel;
407
- provider.speech = createSpeechModel;
408
- provider.tools = azureOpenaiTools;
409
- return provider;
162
+ const tokenProvider = options.tokenProvider;
163
+ if (options.apiKey && tokenProvider) throw new InvalidArgumentError({
164
+ argument: "apiKey/tokenProvider",
165
+ message: "Both apiKey and tokenProvider were provided. Please use only one authentication method."
166
+ });
167
+ const getHeaders = (api = "openai") => {
168
+ const authHeaders = tokenProvider ? {} : { [api === "speech" ? "Ocp-Apim-Subscription-Key" : "api-key"]: loadApiKey({
169
+ apiKey: options.apiKey,
170
+ environmentVariableName: "AZURE_API_KEY",
171
+ description: api === "speech" ? "Azure Speech" : "Azure OpenAI"
172
+ }) };
173
+ return withUserAgentSuffix({
174
+ ...authHeaders,
175
+ ...options.headers
176
+ }, `ai-sdk-azure/${VERSION}`);
177
+ };
178
+ const fetch = tokenProvider ? async (input, init) => {
179
+ const headers = normalizeHeaders(init?.headers);
180
+ if (headers.authorization == null) headers.authorization = `Bearer ${await tokenProvider()}`;
181
+ return (options.fetch ?? globalThis.fetch)(input, {
182
+ ...init,
183
+ headers
184
+ });
185
+ } : options.fetch;
186
+ const getResourceName = () => {
187
+ const resourceName = loadSetting({
188
+ settingValue: options.resourceName,
189
+ settingName: "resourceName",
190
+ environmentVariableName: "AZURE_RESOURCE_NAME",
191
+ description: "Azure OpenAI resource name"
192
+ });
193
+ if (!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(resourceName)) throw new InvalidArgumentError({
194
+ argument: "resourceName",
195
+ message: "Invalid Azure resource name. Expected a single DNS label (letters, digits, and hyphens). Use `baseURL` for custom endpoints."
196
+ });
197
+ return resourceName;
198
+ };
199
+ const apiVersion = options.apiVersion ?? "v1";
200
+ const { isAzureOpenAI, isFoundryProject, isVersioned: isAzureOpenAIVersioned } = getAzureOpenAIBaseURLInfo(options.baseURL);
201
+ const url = ({ path, modelId }) => {
202
+ const baseUrlPrefix = withoutTrailingSlash(options.baseURL ?? `https://${getResourceName()}.openai.azure.com/openai`);
203
+ let fullUrl;
204
+ if (options.useDeploymentBasedUrls) fullUrl = new URL(`${baseUrlPrefix}/deployments/${modelId}${path}`);
205
+ else if (!isAzureOpenAI || isAzureOpenAIVersioned) fullUrl = new URL(`${baseUrlPrefix}${path}`);
206
+ else fullUrl = new URL(`${baseUrlPrefix}/v1${path}`);
207
+ if (options.useDeploymentBasedUrls || isAzureOpenAI && !isAzureOpenAIVersioned && !isFoundryProject) fullUrl.searchParams.set("api-version", apiVersion);
208
+ return fullUrl.toString();
209
+ };
210
+ const createChatModel = (deploymentName) => new OpenAIChatLanguageModel(deploymentName, {
211
+ provider: "azure.chat",
212
+ url,
213
+ headers: getHeaders,
214
+ fetch
215
+ });
216
+ const createDeepSeekModel = (deploymentName) => new DeepSeekChatLanguageModel(deploymentName, {
217
+ provider: "azure.deepseek",
218
+ url,
219
+ headers: getHeaders,
220
+ fetch,
221
+ supportsPenaltySampling: true,
222
+ supportsThinking: false,
223
+ supportsStructuredOutputs: true
224
+ });
225
+ const createCompletionModel = (modelId) => new OpenAICompletionLanguageModel(modelId, {
226
+ provider: "azure.completion",
227
+ url,
228
+ headers: getHeaders,
229
+ fetch
230
+ });
231
+ const createEmbeddingModel = (modelId) => new OpenAIEmbeddingModel(modelId, {
232
+ provider: "azure.embeddings",
233
+ headers: getHeaders,
234
+ url,
235
+ fetch
236
+ });
237
+ const createResponsesModel = (modelId) => new OpenAIResponsesLanguageModel(modelId, {
238
+ provider: "azure.responses",
239
+ url,
240
+ headers: getHeaders,
241
+ fetch,
242
+ explicitMessageItemType: isFoundryProject,
243
+ fileIdPrefixes: ["assistant-"]
244
+ });
245
+ const createImageModel = (modelId) => new OpenAIImageModel(modelId, {
246
+ provider: "azure.image",
247
+ url,
248
+ headers: getHeaders,
249
+ fetch,
250
+ imageInputCapabilities: {
251
+ supportsFileInputs: void 0,
252
+ supportsMaskInputs: void 0
253
+ }
254
+ });
255
+ const createTranscriptionModel = (modelId) => new AzureTranscriptionModel(modelId, options, new OpenAITranscriptionModel(modelId, {
256
+ provider: "azure.transcription",
257
+ url,
258
+ headers: getHeaders,
259
+ fetch
260
+ }), new AzureSpeechTranscriptionModel(modelId, {
261
+ url: () => `${withoutTrailingSlash(options.speechBaseURL) ?? `https://${getResourceName()}.cognitiveservices.azure.com`}/speechtotext/transcriptions:transcribe?api-version=2025-10-15`,
262
+ headers: () => getHeaders("speech"),
263
+ fetch
264
+ }));
265
+ const createSpeechModel = (modelId) => new OpenAISpeechModel(modelId, {
266
+ provider: "azure.speech",
267
+ url,
268
+ headers: getHeaders,
269
+ fetch
270
+ });
271
+ const provider = function(deploymentId) {
272
+ if (new.target) throw new Error("The Azure OpenAI model function cannot be called with the new keyword.");
273
+ return createResponsesModel(deploymentId);
274
+ };
275
+ provider.specificationVersion = "v4";
276
+ provider.languageModel = createResponsesModel;
277
+ provider.chat = createChatModel;
278
+ provider.deepseek = createDeepSeekModel;
279
+ provider.completion = createCompletionModel;
280
+ provider.embedding = createEmbeddingModel;
281
+ provider.embeddingModel = createEmbeddingModel;
282
+ provider.textEmbedding = createEmbeddingModel;
283
+ provider.textEmbeddingModel = createEmbeddingModel;
284
+ provider.image = createImageModel;
285
+ provider.imageModel = createImageModel;
286
+ provider.responses = createResponsesModel;
287
+ provider.transcription = createTranscriptionModel;
288
+ provider.transcriptionModel = createTranscriptionModel;
289
+ provider.speech = createSpeechModel;
290
+ provider.tools = azureOpenaiTools;
291
+ return provider;
410
292
  }
411
- var azure = createAzure();
293
+ /**
294
+ * Default Azure OpenAI provider instance.
295
+ */
296
+ const azure = createAzure();
412
297
  var AzureTranscriptionModel = class {
413
- constructor(modelId, config, openai, speech) {
414
- this.modelId = modelId;
415
- this.config = config;
416
- this.openai = openai;
417
- this.speech = speech;
418
- this.specificationVersion = "v4";
419
- this.provider = "azure.transcription";
420
- }
421
- static [WORKFLOW_SERIALIZE](model) {
422
- return serializeModelOptions({
423
- modelId: model.modelId,
424
- config: model.config
425
- });
426
- }
427
- static [WORKFLOW_DESERIALIZE](options) {
428
- return createAzure(options.config).transcription(options.modelId);
429
- }
430
- async doGenerate(options) {
431
- const { api, ...speechOptions } = await this.getOptions(
432
- options.providerOptions
433
- );
434
- if (api === "speech") {
435
- return this.speech.doGenerate(options, speechOptions);
436
- }
437
- const result = await this.openai.doGenerate(options);
438
- return {
439
- ...result,
440
- warnings: [
441
- ...result.warnings,
442
- ...Object.keys(speechOptions).map((key) => ({
443
- type: "unsupported",
444
- feature: `providerOptions.azure.${key}`,
445
- details: "This option requires the Azure Speech API."
446
- }))
447
- ]
448
- };
449
- }
450
- async doStream(options) {
451
- const { api } = await this.getOptions(options.providerOptions);
452
- if (api === "speech") {
453
- throw new UnsupportedFunctionalityError({
454
- functionality: "streaming transcription with the Azure Speech API"
455
- });
456
- }
457
- return this.openai.doStream(options);
458
- }
459
- async getOptions(providerOptions) {
460
- const options = await parseProviderOptions({
461
- provider: "azure",
462
- providerOptions,
463
- schema: azureTranscriptionModelOptions
464
- });
465
- return {
466
- ...options,
467
- api: options?.api ?? (isMAITranscribe2(this.modelId) ? "speech" : "openai")
468
- };
469
- }
470
- };
471
- export {
472
- VERSION,
473
- azure,
474
- createAzure
298
+ constructor(modelId, config, openai, speech) {
299
+ this.modelId = modelId;
300
+ this.config = config;
301
+ this.openai = openai;
302
+ this.speech = speech;
303
+ this.specificationVersion = "v4";
304
+ this.provider = "azure.transcription";
305
+ }
306
+ static [WORKFLOW_SERIALIZE](model) {
307
+ return serializeModelOptions({
308
+ modelId: model.modelId,
309
+ config: model.config
310
+ });
311
+ }
312
+ static [WORKFLOW_DESERIALIZE](options) {
313
+ return createAzure(options.config).transcription(options.modelId);
314
+ }
315
+ async doGenerate(options) {
316
+ const { api, ...speechOptions } = await this.getOptions(options.providerOptions);
317
+ if (api === "speech") return this.speech.doGenerate(options, speechOptions);
318
+ const result = await this.openai.doGenerate(options);
319
+ return {
320
+ ...result,
321
+ warnings: [...result.warnings, ...Object.keys(speechOptions).map((key) => ({
322
+ type: "unsupported",
323
+ feature: `providerOptions.azure.${key}`,
324
+ details: "This option requires the Azure Speech API."
325
+ }))]
326
+ };
327
+ }
328
+ async doStream(options) {
329
+ const { api } = await this.getOptions(options.providerOptions);
330
+ if (api === "speech") throw new UnsupportedFunctionalityError({ functionality: "streaming transcription with the Azure Speech API" });
331
+ return this.openai.doStream(options);
332
+ }
333
+ async getOptions(providerOptions) {
334
+ const options = await parseProviderOptions({
335
+ provider: "azure",
336
+ providerOptions,
337
+ schema: azureTranscriptionModelOptions
338
+ });
339
+ return {
340
+ ...options,
341
+ api: options?.api ?? (isMAITranscribe2(this.modelId) ? "speech" : "openai")
342
+ };
343
+ }
475
344
  };
345
+ //#endregion
346
+ export { VERSION, azure, createAzure };
347
+
476
348
  //# sourceMappingURL=index.js.map