@ai-sdk/gateway 4.0.151 → 4.0.153
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/CHANGELOG.md +18 -0
- package/dist/index.d.ts +173 -9
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +323 -30
- package/dist/index.js.map +1 -1
- package/docs/00-ai-gateway.mdx +66 -0
- package/package.json +1 -1
- package/src/gateway-batch.ts +3 -2
- package/src/gateway-decision-model.ts +3 -2
- package/src/gateway-embedding-model.ts +3 -2
- package/src/gateway-extraction-model.ts +3 -2
- package/src/gateway-image-model.ts +3 -2
- package/src/gateway-language-model.ts +4 -1
- package/src/gateway-model-catalog.ts +3 -3
- package/src/gateway-provider.ts +84 -17
- package/src/gateway-realtime-model-live.ts +385 -0
- package/src/gateway-realtime-model-settings.ts +16 -0
- package/src/gateway-reranking-model.ts +3 -2
- package/src/gateway-speech-model.ts +22 -20
- package/src/gateway-transcription-model.ts +14 -12
- package/src/gateway-video-model.ts +6 -3
- package/src/index.ts +6 -1
- package/src/redact-gateway-request-credentials.ts +88 -0
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { EXPERIMENTAL_SPEECH_STREAM_START_FRAME_TYPE, EXPERIMENTAL_SPEECH_STREAM_TEXT_DELTA_FRAME_TYPE, EXPERIMENTAL_SPEECH_STREAM_TEXT_DONE_FRAME_TYPE, EXPERIMENTAL_TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE, EXPERIMENTAL_TRANSCRIPTION_STREAM_START_FRAME_TYPE, WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE, combineHeaders, connectToWebSocket, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertUint8ArrayToBase64, createEventSourceResponseHandler, createJsonErrorResponseHandler, createJsonLinesResponseHandler, createJsonResponseHandler, createProviderExecutedToolFactory, experimental_parseSpeechStreamPart, experimental_parseTranscriptionStreamPart, getErrorMessage, getFromApi, lazySchema, loadOptionalSetting, normalizeBatchRequestCounts, normalizeHeaders, parseJsonEventStream, parseProviderOptions, postJsonToApi, removeUndefinedEntries, resolve, safeValidateTypes, secureJsonParse, serializeModelOptions, waitForWebSocketBufferDrain, withUserAgentSuffix, withoutTrailingSlash, zodSchema } from "@ai-sdk/provider-utils";
|
|
1
|
+
import { EXPERIMENTAL_SPEECH_STREAM_START_FRAME_TYPE, EXPERIMENTAL_SPEECH_STREAM_TEXT_DELTA_FRAME_TYPE, EXPERIMENTAL_SPEECH_STREAM_TEXT_DONE_FRAME_TYPE, EXPERIMENTAL_TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE, EXPERIMENTAL_TRANSCRIPTION_STREAM_START_FRAME_TYPE, WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE, combineHeaders, connectToWebSocket, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertUint8ArrayToBase64, createEventSourceResponseHandler, createJsonErrorResponseHandler, createJsonLinesResponseHandler, createJsonResponseHandler, createProviderExecutedToolFactory, experimental_parseSpeechStreamPart, experimental_parseTranscriptionStreamPart, getErrorMessage, getFromApi, lazySchema, loadOptionalSetting, normalizeBatchRequestCounts, normalizeHeaders, parseJsonEventStream, parseProviderOptions, postJsonToApi, removeUndefinedEntries, resolve, safeValidateTypes, secureJsonParse, serializeModelOptions, waitForWebSocketBufferDrain, withTelemetryRedaction, withUserAgentSuffix, withoutTrailingSlash, zodSchema } from "@ai-sdk/provider-utils";
|
|
2
2
|
import { any, array, boolean, catchall, discriminatedUnion, enum as enum$1, extend, globalRegistry, instanceof as instanceof$1, int, json, length, literal, maxLength, maximum, minLength, minimum, never, nullable, nullish, number, object, optional, pipe, record, refine, string, transform, union, unknown, url } from "zod/v4/mini";
|
|
3
3
|
import { APICallError, Experimental_ExtractionUnsupportedFieldTypeError, InvalidArgumentError, LoadAPIKeyError, UnsupportedFunctionalityError, getErrorMessage as getErrorMessage$1 } from "@ai-sdk/provider";
|
|
4
4
|
import { getContext, getVercelOidcToken } from "@vercel/oidc";
|
|
@@ -928,6 +928,66 @@ const gatewayGenerationInfoResponseSchema = lazySchema(() => zodSchema(z.pipe(z.
|
|
|
928
928
|
billableWebSearchCalls: billable_web_search_calls
|
|
929
929
|
}))) }), z.transform(({ data }) => data))));
|
|
930
930
|
//#endregion
|
|
931
|
+
//#region src/redact-gateway-request-credentials.ts
|
|
932
|
+
const REDACTED = "[redacted]";
|
|
933
|
+
/**
|
|
934
|
+
* Gateway request bodies can carry request-scoped BYOK credentials in
|
|
935
|
+
* `providerOptions.gateway.byok`. The credentials must reach the Gateway and
|
|
936
|
+
* stay on application-facing errors, but telemetry-only copies must not expose
|
|
937
|
+
* them.
|
|
938
|
+
*/
|
|
939
|
+
function withGatewayRequestTelemetryRedaction(value) {
|
|
940
|
+
if (!isRecord$1(value)) return value;
|
|
941
|
+
const body = value;
|
|
942
|
+
if (!hasByok(body.providerOptions) && !hasRequestByok(body.requests)) return value;
|
|
943
|
+
return withTelemetryRedaction(body, (redacted) => ({
|
|
944
|
+
...redacted,
|
|
945
|
+
...hasByok(redacted.providerOptions) && { providerOptions: redactProviderOptions(redacted.providerOptions) },
|
|
946
|
+
...Array.isArray(redacted.requests) && { requests: redacted.requests.map(redactRequestProviderOptions) }
|
|
947
|
+
}));
|
|
948
|
+
}
|
|
949
|
+
/** Batch bodies nest the same provider options in every request's options. */
|
|
950
|
+
function redactRequestProviderOptions(request) {
|
|
951
|
+
if (!isRecord$1(request) || !isRecord$1(request.options)) return request;
|
|
952
|
+
const options = request.options;
|
|
953
|
+
if (!hasByok(options.providerOptions)) return request;
|
|
954
|
+
return {
|
|
955
|
+
...request,
|
|
956
|
+
options: {
|
|
957
|
+
...options,
|
|
958
|
+
providerOptions: redactProviderOptions(options.providerOptions)
|
|
959
|
+
}
|
|
960
|
+
};
|
|
961
|
+
}
|
|
962
|
+
function redactProviderOptions(value) {
|
|
963
|
+
if (!isRecord$1(value) || !isRecord$1(value.gateway)) return value;
|
|
964
|
+
return {
|
|
965
|
+
...value,
|
|
966
|
+
gateway: {
|
|
967
|
+
...value.gateway,
|
|
968
|
+
byok: redactByok(value.gateway.byok)
|
|
969
|
+
}
|
|
970
|
+
};
|
|
971
|
+
}
|
|
972
|
+
/** Keep provider names and credential shapes; replace every BYOK value. */
|
|
973
|
+
function redactByok(value) {
|
|
974
|
+
if (Array.isArray(value)) return value.map(redactByok);
|
|
975
|
+
if (isRecord$1(value)) return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, redactByok(entry)]));
|
|
976
|
+
return REDACTED;
|
|
977
|
+
}
|
|
978
|
+
function hasByok(providerOptions) {
|
|
979
|
+
return isRecord$1(providerOptions) && isRecord$1(providerOptions.gateway) && providerOptions.gateway.byok !== void 0;
|
|
980
|
+
}
|
|
981
|
+
function hasRequestByok(requests) {
|
|
982
|
+
return Array.isArray(requests) && requests.some((request) => {
|
|
983
|
+
if (!isRecord$1(request) || !isRecord$1(request.options)) return false;
|
|
984
|
+
return hasByok(request.options.providerOptions);
|
|
985
|
+
});
|
|
986
|
+
}
|
|
987
|
+
function isRecord$1(value) {
|
|
988
|
+
return value != null && typeof value === "object" && !Array.isArray(value);
|
|
989
|
+
}
|
|
990
|
+
//#endregion
|
|
931
991
|
//#region src/gateway-batch.ts
|
|
932
992
|
var GatewayBatch = class {
|
|
933
993
|
constructor(config) {
|
|
@@ -953,7 +1013,7 @@ var GatewayBatch = class {
|
|
|
953
1013
|
const { value: responseBody } = await postJsonToApi({
|
|
954
1014
|
url: this.getBatchUrl("start"),
|
|
955
1015
|
headers: combineHeaders(resolvedHeaders, headers, { "ai-model-id": modelId }, await resolve(this.config.o11yHeaders), idempotencyKey != null ? { "idempotency-key": idempotencyKey } : void 0),
|
|
956
|
-
body: {
|
|
1016
|
+
body: withGatewayRequestTelemetryRedaction({
|
|
957
1017
|
...webhookUrl != null && { callbackUrl: webhookUrl },
|
|
958
1018
|
requests: requests.map((request) => ({
|
|
959
1019
|
id: request.id,
|
|
@@ -962,7 +1022,7 @@ var GatewayBatch = class {
|
|
|
962
1022
|
options: maybeEncodeBatchFileParts(request.options)
|
|
963
1023
|
})),
|
|
964
1024
|
...forwardedProviderOptions != null && { providerOptions: forwardedProviderOptions }
|
|
965
|
-
},
|
|
1025
|
+
}),
|
|
966
1026
|
successfulResponseHandler: createJsonResponseHandler(gatewayBatchStartResponseSchema),
|
|
967
1027
|
failedResponseHandler: createJsonErrorResponseHandler({
|
|
968
1028
|
errorSchema: z.any(),
|
|
@@ -1247,7 +1307,7 @@ var GatewayLanguageModel = class GatewayLanguageModel {
|
|
|
1247
1307
|
async getArgs(options) {
|
|
1248
1308
|
const { abortSignal: _abortSignal, ...optionsWithoutSignal } = options;
|
|
1249
1309
|
return {
|
|
1250
|
-
args: this.maybeEncodeFileParts(optionsWithoutSignal),
|
|
1310
|
+
args: withGatewayRequestTelemetryRedaction(this.maybeEncodeFileParts(optionsWithoutSignal)),
|
|
1251
1311
|
warnings: []
|
|
1252
1312
|
};
|
|
1253
1313
|
}
|
|
@@ -1386,11 +1446,11 @@ var GatewayEmbeddingModel = class GatewayEmbeddingModel {
|
|
|
1386
1446
|
const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
|
|
1387
1447
|
url: this.getUrl(),
|
|
1388
1448
|
headers: combineHeaders(resolvedHeaders, headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
|
|
1389
|
-
body: {
|
|
1449
|
+
body: withGatewayRequestTelemetryRedaction({
|
|
1390
1450
|
values,
|
|
1391
1451
|
dimensions,
|
|
1392
1452
|
...providerOptions ? { providerOptions } : {}
|
|
1393
|
-
},
|
|
1453
|
+
}),
|
|
1394
1454
|
successfulResponseHandler: createJsonResponseHandler(gatewayEmbeddingResponseSchema),
|
|
1395
1455
|
failedResponseHandler: createJsonErrorResponseHandler({
|
|
1396
1456
|
errorSchema: z.any(),
|
|
@@ -1487,7 +1547,7 @@ var GatewayImageModel = class GatewayImageModel {
|
|
|
1487
1547
|
const { responseHeaders, value: responseBody } = await postJsonToApi({
|
|
1488
1548
|
url: this.getUrl(),
|
|
1489
1549
|
headers: combineHeaders(resolvedHeaders, headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
|
|
1490
|
-
body: {
|
|
1550
|
+
body: withGatewayRequestTelemetryRedaction({
|
|
1491
1551
|
prompt,
|
|
1492
1552
|
n,
|
|
1493
1553
|
...size && { size },
|
|
@@ -1496,7 +1556,7 @@ var GatewayImageModel = class GatewayImageModel {
|
|
|
1496
1556
|
...requestProviderOptions && { providerOptions: requestProviderOptions },
|
|
1497
1557
|
...files && { files: files.map((file) => maybeEncodeImageFile(file)) },
|
|
1498
1558
|
...mask && { mask: maybeEncodeImageFile(mask) }
|
|
1499
|
-
},
|
|
1559
|
+
}),
|
|
1500
1560
|
successfulResponseHandler: createJsonResponseHandler(gatewayImageResponseSchema, streamingImageDecoding ? { experimental_binaryFields: ["images[*]"] } : void 0),
|
|
1501
1561
|
failedResponseHandler: createJsonErrorResponseHandler({
|
|
1502
1562
|
errorSchema: z.any(),
|
|
@@ -1599,7 +1659,7 @@ var GatewayVideoModel = class {
|
|
|
1599
1659
|
const { responseHeaders, value: responseBody } = await postJsonToApi({
|
|
1600
1660
|
url: this.getUrl(),
|
|
1601
1661
|
headers: combineHeaders(resolvedHeaders, headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders), { accept: "text/event-stream" }),
|
|
1602
|
-
body: this.buildRequestBody(options),
|
|
1662
|
+
body: withGatewayRequestTelemetryRedaction(this.buildRequestBody(options)),
|
|
1603
1663
|
successfulResponseHandler: async ({ response, url, requestBodyValues }) => {
|
|
1604
1664
|
if (response.body == null) throw new APICallError({
|
|
1605
1665
|
message: "SSE response body is empty",
|
|
@@ -1684,10 +1744,10 @@ var GatewayVideoModel = class {
|
|
|
1684
1744
|
const { responseHeaders, value: responseBody } = await postJsonToApi({
|
|
1685
1745
|
url: this.getStartUrl(),
|
|
1686
1746
|
headers: combineHeaders(resolvedHeaders, headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
|
|
1687
|
-
body: {
|
|
1747
|
+
body: withGatewayRequestTelemetryRedaction({
|
|
1688
1748
|
...this.buildRequestBody(options),
|
|
1689
1749
|
...webhookUrl && { callbackUrl: webhookUrl }
|
|
1690
|
-
},
|
|
1750
|
+
}),
|
|
1691
1751
|
successfulResponseHandler: createJsonResponseHandler(gatewayVideoStartResponseSchema),
|
|
1692
1752
|
failedResponseHandler: createJsonErrorResponseHandler({
|
|
1693
1753
|
errorSchema: z.any(),
|
|
@@ -2017,13 +2077,13 @@ var GatewayDecisionModel = class {
|
|
|
2017
2077
|
const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
|
|
2018
2078
|
url: this.getUrl(),
|
|
2019
2079
|
headers: combineHeaders(resolvedHeaders, headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
|
|
2020
|
-
body: {
|
|
2080
|
+
body: withGatewayRequestTelemetryRedaction({
|
|
2021
2081
|
stateParts,
|
|
2022
2082
|
questions,
|
|
2023
2083
|
maxOutputTokens,
|
|
2024
2084
|
reasoning,
|
|
2025
2085
|
...validatedProviderOptions ? { providerOptions: validatedProviderOptions } : {}
|
|
2026
|
-
},
|
|
2086
|
+
}),
|
|
2027
2087
|
successfulResponseHandler: createJsonResponseHandler(gatewayDecisionResponseSchema),
|
|
2028
2088
|
failedResponseHandler: createJsonErrorResponseHandler({
|
|
2029
2089
|
errorSchema: z.any(),
|
|
@@ -2120,14 +2180,14 @@ var GatewayExtractionModel = class {
|
|
|
2120
2180
|
const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
|
|
2121
2181
|
url: this.getUrl(),
|
|
2122
2182
|
headers: combineHeaders(resolvedHeaders, headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
|
|
2123
|
-
body: {
|
|
2183
|
+
body: withGatewayRequestTelemetryRedaction({
|
|
2124
2184
|
stateParts,
|
|
2125
2185
|
fields,
|
|
2126
2186
|
referenceDate,
|
|
2127
2187
|
maxOutputTokens,
|
|
2128
2188
|
reasoning,
|
|
2129
2189
|
...providerOptions ? { providerOptions } : {}
|
|
2130
|
-
},
|
|
2190
|
+
}),
|
|
2131
2191
|
successfulResponseHandler: createJsonResponseHandler(gatewayExtractionResponseSchema),
|
|
2132
2192
|
failedResponseHandler: createJsonErrorResponseHandler({
|
|
2133
2193
|
errorSchema: z.any(),
|
|
@@ -2273,12 +2333,12 @@ var GatewayRerankingModel = class {
|
|
|
2273
2333
|
const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
|
|
2274
2334
|
url: this.getUrl(),
|
|
2275
2335
|
headers: combineHeaders(resolvedHeaders, headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
|
|
2276
|
-
body: {
|
|
2336
|
+
body: withGatewayRequestTelemetryRedaction({
|
|
2277
2337
|
documents,
|
|
2278
2338
|
query,
|
|
2279
2339
|
...topN != null ? { topN } : {},
|
|
2280
2340
|
...providerOptions ? { providerOptions } : {}
|
|
2281
|
-
},
|
|
2341
|
+
}),
|
|
2282
2342
|
successfulResponseHandler: createJsonResponseHandler(gatewayRerankingResponseSchema),
|
|
2283
2343
|
failedResponseHandler: createJsonErrorResponseHandler({
|
|
2284
2344
|
errorSchema: z.any(),
|
|
@@ -2398,11 +2458,11 @@ var GatewayTranscriptionModel = class {
|
|
|
2398
2458
|
const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
|
|
2399
2459
|
url: this.getUrl(),
|
|
2400
2460
|
headers: combineHeaders(resolvedHeaders, headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
|
|
2401
|
-
body: {
|
|
2461
|
+
body: withGatewayRequestTelemetryRedaction({
|
|
2402
2462
|
audio: audio instanceof Uint8Array ? convertUint8ArrayToBase64(audio) : audio,
|
|
2403
2463
|
mediaType,
|
|
2404
2464
|
...providerOptions && { providerOptions }
|
|
2405
|
-
},
|
|
2465
|
+
}),
|
|
2406
2466
|
successfulResponseHandler: createJsonResponseHandler(gatewayTranscriptionResponseSchema),
|
|
2407
2467
|
failedResponseHandler: createJsonErrorResponseHandler({
|
|
2408
2468
|
errorSchema: z.any(),
|
|
@@ -2446,12 +2506,12 @@ var GatewayTranscriptionModel = class {
|
|
|
2446
2506
|
const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
|
|
2447
2507
|
const headers = combineHeaders(await resolve(this.config.headers ?? {}), options.headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders));
|
|
2448
2508
|
const authMethod = await parseAuthMethod(headers);
|
|
2449
|
-
const startFrame = {
|
|
2509
|
+
const startFrame = withGatewayRequestTelemetryRedaction({
|
|
2450
2510
|
type: EXPERIMENTAL_TRANSCRIPTION_STREAM_START_FRAME_TYPE,
|
|
2451
2511
|
inputAudioFormat: options.inputAudioFormat,
|
|
2452
2512
|
...options.providerOptions != null && { providerOptions: options.providerOptions },
|
|
2453
2513
|
...options.includeRawChunks != null && { includeRawChunks: options.includeRawChunks }
|
|
2454
|
-
};
|
|
2514
|
+
});
|
|
2455
2515
|
return {
|
|
2456
2516
|
stream: createGatewayTranscriptionStream({
|
|
2457
2517
|
webSocket: this.config.webSocket,
|
|
@@ -2676,7 +2736,7 @@ var GatewaySpeechModel = class {
|
|
|
2676
2736
|
const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
|
|
2677
2737
|
url: this.getUrl(),
|
|
2678
2738
|
headers: combineHeaders(resolvedHeaders, headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
|
|
2679
|
-
body: {
|
|
2739
|
+
body: withGatewayRequestTelemetryRedaction({
|
|
2680
2740
|
text,
|
|
2681
2741
|
...voice && { voice },
|
|
2682
2742
|
...outputFormat && { outputFormat },
|
|
@@ -2684,7 +2744,7 @@ var GatewaySpeechModel = class {
|
|
|
2684
2744
|
...speed != null && { speed },
|
|
2685
2745
|
...language && { language },
|
|
2686
2746
|
...providerOptions && { providerOptions }
|
|
2687
|
-
},
|
|
2747
|
+
}),
|
|
2688
2748
|
successfulResponseHandler: createJsonResponseHandler(gatewaySpeechResponseSchema),
|
|
2689
2749
|
failedResponseHandler: createJsonErrorResponseHandler({
|
|
2690
2750
|
errorSchema: z.any(),
|
|
@@ -2713,7 +2773,7 @@ var GatewaySpeechModel = class {
|
|
|
2713
2773
|
const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
|
|
2714
2774
|
const headers = combineHeaders(await resolve(this.config.headers ?? {}), options.headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders));
|
|
2715
2775
|
const authMethod = await parseAuthMethod(headers);
|
|
2716
|
-
const startFrame = {
|
|
2776
|
+
const startFrame = withGatewayRequestTelemetryRedaction({
|
|
2717
2777
|
type: EXPERIMENTAL_SPEECH_STREAM_START_FRAME_TYPE,
|
|
2718
2778
|
...options.voice != null && { voice: options.voice },
|
|
2719
2779
|
...options.outputFormat != null && { outputFormat: options.outputFormat },
|
|
@@ -2722,7 +2782,7 @@ var GatewaySpeechModel = class {
|
|
|
2722
2782
|
...options.language != null && { language: options.language },
|
|
2723
2783
|
...options.providerOptions != null && { providerOptions: options.providerOptions },
|
|
2724
2784
|
...options.includeRawChunks != null && { includeRawChunks: options.includeRawChunks }
|
|
2725
|
-
};
|
|
2785
|
+
});
|
|
2726
2786
|
return {
|
|
2727
2787
|
stream: createGatewaySpeechStream({
|
|
2728
2788
|
webSocket: this.config.webSocket,
|
|
@@ -2926,6 +2986,215 @@ const gatewaySpeechResponseSchema = lazySchema(() => zodSchema(z.object({
|
|
|
2926
2986
|
providerMetadata: z.optional(z.record(z.string(), providerMetadataEntrySchema()))
|
|
2927
2987
|
})));
|
|
2928
2988
|
//#endregion
|
|
2989
|
+
//#region src/gateway-realtime-model-live.ts
|
|
2990
|
+
const supportedOpenAILiveOptions = /* @__PURE__ */ new Set([
|
|
2991
|
+
"delegation",
|
|
2992
|
+
"input",
|
|
2993
|
+
"store",
|
|
2994
|
+
"voice"
|
|
2995
|
+
]);
|
|
2996
|
+
const contextChannels = /* @__PURE__ */ new Set([
|
|
2997
|
+
"commentary",
|
|
2998
|
+
"instructions",
|
|
2999
|
+
"thinking"
|
|
3000
|
+
]);
|
|
3001
|
+
const supportedSessionSettings = /* @__PURE__ */ new Set([
|
|
3002
|
+
"instructions",
|
|
3003
|
+
"voice",
|
|
3004
|
+
"inputAudioFormat",
|
|
3005
|
+
"outputAudioFormat",
|
|
3006
|
+
"providerOptions"
|
|
3007
|
+
]);
|
|
3008
|
+
/**
|
|
3009
|
+
* Live model backed by the AI Gateway.
|
|
3010
|
+
*
|
|
3011
|
+
* Live is a continuous conversation API: one `session-start` opens the
|
|
3012
|
+
* session, PCM audio streams in both directions, and `session-close` ends it
|
|
3013
|
+
* with final usage. The client speaks the Gateway's normalized Live protocol
|
|
3014
|
+
* on `/v4/ai/live-model`, and the Gateway runs the provider mapping
|
|
3015
|
+
* server-side, so server events arrive already normalized.
|
|
3016
|
+
*/
|
|
3017
|
+
var GatewayRealtimeModelLive = class {
|
|
3018
|
+
constructor(modelId, config) {
|
|
3019
|
+
this.specificationVersion = "v4";
|
|
3020
|
+
this.capabilities = {
|
|
3021
|
+
conversation: "continuous",
|
|
3022
|
+
transports: ["websocket"],
|
|
3023
|
+
connections: ["client-secret-websocket", "server-websocket"],
|
|
3024
|
+
startup: "session-start",
|
|
3025
|
+
finalization: "session-close"
|
|
3026
|
+
};
|
|
3027
|
+
this.modelId = modelId;
|
|
3028
|
+
this.provider = config.provider;
|
|
3029
|
+
this.config = config;
|
|
3030
|
+
}
|
|
3031
|
+
/**
|
|
3032
|
+
* Mints a short-lived client secret bound to this Live model. The browser
|
|
3033
|
+
* opens the Live WebSocket with it through the `ai-gateway-auth.<token>`
|
|
3034
|
+
* subprotocol; the session configuration is sent later in `session-start`.
|
|
3035
|
+
*/
|
|
3036
|
+
async doCreateClientSecret(options) {
|
|
3037
|
+
const secret = await this.config.createClientSecret({
|
|
3038
|
+
modelId: this.modelId,
|
|
3039
|
+
routeKind: "live",
|
|
3040
|
+
...options?.expiresAfterSeconds != null && { expiresAfterSeconds: options.expiresAfterSeconds }
|
|
3041
|
+
});
|
|
3042
|
+
return {
|
|
3043
|
+
token: secret.token,
|
|
3044
|
+
url: toGatewayLiveUrl(this.config.baseURL, this.modelId),
|
|
3045
|
+
...secret.expiresAt != null && { expiresAt: secret.expiresAt }
|
|
3046
|
+
};
|
|
3047
|
+
}
|
|
3048
|
+
getWebSocketConfig(options) {
|
|
3049
|
+
return {
|
|
3050
|
+
url: options.url,
|
|
3051
|
+
protocols: getGatewayRealtimeProtocols(options.token, { teamIdOrSlug: this.config.teamIdOrSlug })
|
|
3052
|
+
};
|
|
3053
|
+
}
|
|
3054
|
+
async getServerWebSocketConfig(options) {
|
|
3055
|
+
this.assertConversationIntent(options);
|
|
3056
|
+
return {
|
|
3057
|
+
url: toGatewayLiveUrl(this.config.baseURL, this.modelId),
|
|
3058
|
+
headers: removeUndefinedEntries(await this.config.getHeaders())
|
|
3059
|
+
};
|
|
3060
|
+
}
|
|
3061
|
+
parseServerEvent(raw) {
|
|
3062
|
+
if (raw == null || typeof raw !== "object" || Array.isArray(raw) || typeof raw.type !== "string") return {
|
|
3063
|
+
type: "error",
|
|
3064
|
+
code: "invalid_server_event",
|
|
3065
|
+
message: "Invalid AI Gateway Live server event.",
|
|
3066
|
+
raw
|
|
3067
|
+
};
|
|
3068
|
+
if (raw.type === "error" && !("raw" in raw)) return {
|
|
3069
|
+
...raw,
|
|
3070
|
+
raw
|
|
3071
|
+
};
|
|
3072
|
+
return raw;
|
|
3073
|
+
}
|
|
3074
|
+
serializeClientEvent(event, options) {
|
|
3075
|
+
this.assertConversationIntent(options);
|
|
3076
|
+
const eventId = "eventId" in event && event.eventId != null ? { eventId: event.eventId } : {};
|
|
3077
|
+
switch (event.type) {
|
|
3078
|
+
case "session-start": return {
|
|
3079
|
+
type: "session-start",
|
|
3080
|
+
modelId: this.modelId,
|
|
3081
|
+
config: this.buildSessionConfig(event.config),
|
|
3082
|
+
...eventId
|
|
3083
|
+
};
|
|
3084
|
+
case "session-close":
|
|
3085
|
+
case "input-audio-mute":
|
|
3086
|
+
case "input-audio-unmute": return {
|
|
3087
|
+
type: event.type,
|
|
3088
|
+
...eventId
|
|
3089
|
+
};
|
|
3090
|
+
case "input-audio-append": return {
|
|
3091
|
+
type: "input-audio-append",
|
|
3092
|
+
audio: event.audio,
|
|
3093
|
+
...eventId
|
|
3094
|
+
};
|
|
3095
|
+
case "context-append":
|
|
3096
|
+
validateContextOptions(event.providerOptions);
|
|
3097
|
+
return {
|
|
3098
|
+
type: "context-append",
|
|
3099
|
+
content: event.content,
|
|
3100
|
+
delegationId: event.delegationId,
|
|
3101
|
+
...event.providerOptions != null && { providerOptions: event.providerOptions },
|
|
3102
|
+
...eventId
|
|
3103
|
+
};
|
|
3104
|
+
default: throw new UnsupportedFunctionalityError({ functionality: `AI Gateway Live client event: ${event.type}` });
|
|
3105
|
+
}
|
|
3106
|
+
}
|
|
3107
|
+
buildSessionConfig(config, options) {
|
|
3108
|
+
this.assertConversationIntent(options);
|
|
3109
|
+
for (const [key, value] of Object.entries(config)) if (value != null && !supportedSessionSettings.has(key)) throw new UnsupportedFunctionalityError({ functionality: `AI Gateway Live session setting: ${key}` });
|
|
3110
|
+
validateSessionProviderOptions(config.providerOptions);
|
|
3111
|
+
const input = config.inputAudioFormat;
|
|
3112
|
+
const output = config.outputAudioFormat;
|
|
3113
|
+
for (const [argument, format] of [["inputAudioFormat", input], ["outputAudioFormat", output]]) if (format != null && !isSupportedAudioFormat(format)) throw new UnsupportedFunctionalityError({ functionality: `AI Gateway Live ${argument} ${format.type} at ${format.rate ?? "an unspecified"} Hz; use audio/pcm at 16000 or 24000 Hz, or audio/pcma or audio/pcmu at 8000 Hz` });
|
|
3114
|
+
if (input != null && output != null && (input.type !== output.type || input.rate !== output.rate)) throw new InvalidArgumentError({
|
|
3115
|
+
argument: "outputAudioFormat",
|
|
3116
|
+
message: "AI Gateway Live requires the same input and output audio format."
|
|
3117
|
+
});
|
|
3118
|
+
return removeUndefinedEntries(config);
|
|
3119
|
+
}
|
|
3120
|
+
assertConversationIntent(options) {
|
|
3121
|
+
if (options?.intent != null && options.intent !== "conversation") throw new Error(`AI Gateway Live does not support the '${options.intent}' session intent.`);
|
|
3122
|
+
}
|
|
3123
|
+
};
|
|
3124
|
+
function isRecord(value) {
|
|
3125
|
+
return value != null && typeof value === "object" && !Array.isArray(value);
|
|
3126
|
+
}
|
|
3127
|
+
/** Gateway options stay service-owned; OpenAI Live options are WebSocket-only. */
|
|
3128
|
+
function validateSessionProviderOptions(providerOptions) {
|
|
3129
|
+
if (providerOptions == null) return;
|
|
3130
|
+
if (!isRecord(providerOptions)) throw new InvalidArgumentError({
|
|
3131
|
+
argument: "providerOptions",
|
|
3132
|
+
message: "providerOptions must be an object."
|
|
3133
|
+
});
|
|
3134
|
+
for (const [namespace, options] of Object.entries(providerOptions)) {
|
|
3135
|
+
if (options === void 0) continue;
|
|
3136
|
+
if (namespace !== "gateway" && namespace !== "openai") throw new UnsupportedFunctionalityError({ functionality: `AI Gateway Live provider options namespace: ${namespace}` });
|
|
3137
|
+
if (!isRecord(options)) throw new InvalidArgumentError({
|
|
3138
|
+
argument: `providerOptions.${namespace}`,
|
|
3139
|
+
message: `providerOptions.${namespace} must be an object.`
|
|
3140
|
+
});
|
|
3141
|
+
}
|
|
3142
|
+
const openai = providerOptions.openai;
|
|
3143
|
+
if (!isRecord(openai)) return;
|
|
3144
|
+
for (const [key, value] of Object.entries(openai)) {
|
|
3145
|
+
if (value === void 0) continue;
|
|
3146
|
+
if (!supportedOpenAILiveOptions.has(key)) throw new UnsupportedFunctionalityError({ functionality: `AI Gateway Live OpenAI option: ${key}` });
|
|
3147
|
+
if (key === "delegation" && value !== null && !(hasExactKeys(value, ["type"]) && value.type === "client")) throw new UnsupportedFunctionalityError({ functionality: "AI Gateway Live delegation other than { type: \"client\" } or null" });
|
|
3148
|
+
if (!isValidOpenAILiveOption(key, value)) throw new InvalidArgumentError({
|
|
3149
|
+
argument: `providerOptions.openai.${key}`,
|
|
3150
|
+
message: openaiLiveOptionMessages[key]
|
|
3151
|
+
});
|
|
3152
|
+
}
|
|
3153
|
+
}
|
|
3154
|
+
const openaiLiveOptionMessages = {
|
|
3155
|
+
delegation: "delegation must be { type: \"client\" } or null.",
|
|
3156
|
+
input: "input must be at most 128 messages, each { type: \"message\", role, content: [{ type, text }] }.",
|
|
3157
|
+
store: "store must be a boolean.",
|
|
3158
|
+
voice: "voice must be { id: string } with a nonempty id."
|
|
3159
|
+
};
|
|
3160
|
+
function isValidOpenAILiveOption(key, value) {
|
|
3161
|
+
switch (key) {
|
|
3162
|
+
case "delegation": return true;
|
|
3163
|
+
case "store": return typeof value === "boolean";
|
|
3164
|
+
case "voice": return hasExactKeys(value, ["id"]) && typeof value.id === "string" && value.id.length > 0;
|
|
3165
|
+
case "input": return Array.isArray(value) && value.length <= 128 && Array.from(value).every(isInputMessage);
|
|
3166
|
+
default: return false;
|
|
3167
|
+
}
|
|
3168
|
+
}
|
|
3169
|
+
function isInputMessage(message) {
|
|
3170
|
+
if (!hasExactKeys(message, [
|
|
3171
|
+
"type",
|
|
3172
|
+
"role",
|
|
3173
|
+
"content"
|
|
3174
|
+
]) || message.type !== "message" || !Array.isArray(message.content) || message.content.length !== 1) return false;
|
|
3175
|
+
const [part] = message.content;
|
|
3176
|
+
if (!hasExactKeys(part, ["type", "text"]) || typeof part.text !== "string") return false;
|
|
3177
|
+
return message.role === "assistant" ? part.type === "text" || part.type === "output_text" : (message.role === "developer" || message.role === "user") && part.type === "input_text";
|
|
3178
|
+
}
|
|
3179
|
+
function hasExactKeys(value, keys) {
|
|
3180
|
+
if (!isRecord(value)) return false;
|
|
3181
|
+
const present = Object.keys(value).filter((key) => value[key] !== void 0);
|
|
3182
|
+
return present.length === keys.length && keys.every((key) => present.includes(key));
|
|
3183
|
+
}
|
|
3184
|
+
function validateContextOptions(providerOptions) {
|
|
3185
|
+
if (providerOptions == null) return;
|
|
3186
|
+
if (!(isRecord(providerOptions) && Object.entries(providerOptions).every(([namespace, options]) => options === void 0 || namespace === "openai" && isRecord(options) && Object.entries(options).every(([key, value]) => value === void 0 || key === "channel" && typeof value === "string" && contextChannels.has(value))))) throw new UnsupportedFunctionalityError({ functionality: "AI Gateway Live context options other than openai.channel commentary, instructions, or thinking" });
|
|
3187
|
+
}
|
|
3188
|
+
function isSupportedAudioFormat(format) {
|
|
3189
|
+
return format.type === "audio/pcm" ? format.rate === 16e3 || format.rate === 24e3 : (format.type === "audio/pcma" || format.type === "audio/pcmu") && format.rate === 8e3;
|
|
3190
|
+
}
|
|
3191
|
+
/** Live WebSocket URL; the model id rides `?ai-model-id=` like the realtime route. */
|
|
3192
|
+
function toGatewayLiveUrl(baseURL, modelId) {
|
|
3193
|
+
const url = new URL(`${baseURL.replace(/^http/, "ws")}/live-model`);
|
|
3194
|
+
url.searchParams.set("ai-model-id", modelId);
|
|
3195
|
+
return url.toString();
|
|
3196
|
+
}
|
|
3197
|
+
//#endregion
|
|
2929
3198
|
//#region src/gateway-realtime-model.ts
|
|
2930
3199
|
/**
|
|
2931
3200
|
* Realtime model backed by the AI Gateway.
|
|
@@ -3012,6 +3281,13 @@ function toGatewayRealtimeUrl(baseURL, modelId) {
|
|
|
3012
3281
|
return url.toString();
|
|
3013
3282
|
}
|
|
3014
3283
|
//#endregion
|
|
3284
|
+
//#region src/gateway-realtime-model-settings.ts
|
|
3285
|
+
/**
|
|
3286
|
+
* Realtime model IDs that use the continuous Live API by default. Other IDs use
|
|
3287
|
+
* the realtime API unless `{ api: 'live' }` is passed.
|
|
3288
|
+
*/
|
|
3289
|
+
const gatewayLiveModelIds = ["openai/gpt-live-1", "openai/gpt-live-1.1"];
|
|
3290
|
+
//#endregion
|
|
3015
3291
|
//#region src/tool/browserbase-fetch.ts
|
|
3016
3292
|
const jsonObjectSchema = () => z.record(z.string(), z.unknown());
|
|
3017
3293
|
const browserbaseFetchInputSchema = lazySchema(() => zodSchema(z.object({
|
|
@@ -3636,7 +3912,7 @@ async function getVercelRequestId() {
|
|
|
3636
3912
|
}
|
|
3637
3913
|
//#endregion
|
|
3638
3914
|
//#region src/version.ts
|
|
3639
|
-
const VERSION = "4.0.
|
|
3915
|
+
const VERSION = "4.0.153";
|
|
3640
3916
|
//#endregion
|
|
3641
3917
|
//#region src/gateway-provider.ts
|
|
3642
3918
|
const AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
|
|
@@ -3940,16 +4216,22 @@ function createGateway(options = {}) {
|
|
|
3940
4216
|
...secret.expiresAt != null && { expiresAt: secret.expiresAt }
|
|
3941
4217
|
};
|
|
3942
4218
|
} });
|
|
3943
|
-
const createRealtimeModel = (modelId) => new
|
|
4219
|
+
const createRealtimeModel = (modelId, realtimeOptions) => resolveGatewayRealtimeApi(modelId, realtimeOptions) === "live" ? new GatewayRealtimeModelLive(modelId, {
|
|
4220
|
+
provider: "gateway.live",
|
|
4221
|
+
baseURL,
|
|
4222
|
+
teamIdOrSlug: options.teamIdOrSlug,
|
|
4223
|
+
createClientSecret: mintClientSecret,
|
|
4224
|
+
getHeaders
|
|
4225
|
+
}) : new GatewayRealtimeModel(modelId, {
|
|
3944
4226
|
provider: "gateway.realtime",
|
|
3945
4227
|
baseURL,
|
|
3946
4228
|
teamIdOrSlug: options.teamIdOrSlug,
|
|
3947
4229
|
createClientSecret: mintClientSecret,
|
|
3948
4230
|
getHeaders
|
|
3949
4231
|
});
|
|
3950
|
-
provider.experimental_realtime = Object.assign((modelId) => createRealtimeModel(modelId), { getToken: async (tokenOptions) => {
|
|
3951
|
-
const { model: modelId, ...secretOptions } = tokenOptions;
|
|
3952
|
-
const secret = await createRealtimeModel(modelId).doCreateClientSecret(secretOptions);
|
|
4232
|
+
provider.experimental_realtime = Object.assign((modelId, realtimeOptions) => createRealtimeModel(modelId, realtimeOptions), { getToken: async (tokenOptions) => {
|
|
4233
|
+
const { model: modelId, api, ...secretOptions } = tokenOptions;
|
|
4234
|
+
const secret = await createRealtimeModel(modelId, { api }).doCreateClientSecret(secretOptions);
|
|
3953
4235
|
return {
|
|
3954
4236
|
token: secret.token,
|
|
3955
4237
|
url: secret.url,
|
|
@@ -3994,6 +4276,17 @@ async function getGatewayAuthToken(options) {
|
|
|
3994
4276
|
authMethod: "oidc"
|
|
3995
4277
|
};
|
|
3996
4278
|
}
|
|
4279
|
+
function resolveGatewayRealtimeApi(modelId, options) {
|
|
4280
|
+
const api = options?.api;
|
|
4281
|
+
if (api !== void 0) {
|
|
4282
|
+
if (api !== "live" && api !== "realtime") throw new InvalidArgumentError({
|
|
4283
|
+
argument: "api",
|
|
4284
|
+
message: "AI Gateway realtime api must be \"live\" or \"realtime\"."
|
|
4285
|
+
});
|
|
4286
|
+
return api;
|
|
4287
|
+
}
|
|
4288
|
+
return gatewayLiveModelIds.includes(modelId) ? "live" : "realtime";
|
|
4289
|
+
}
|
|
3997
4290
|
function assertGatewayClientSecretServerEnvironment() {
|
|
3998
4291
|
if (typeof globalThis.window !== "undefined") throw new Error("AI Gateway client secrets must be minted server-side: minting needs your Gateway credential, which must never reach the browser. Call gateway.experimental_realtime.getToken(), gateway.experimental_transcription.getToken(), or gateway.experimental_speech.getToken() from your server and pass the returned token to the client.");
|
|
3999
4292
|
}
|