@ai-sdk/gateway4.0.163162.5 kB
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";
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";
import { APICallError, Experimental_ExtractionUnsupportedFieldTypeError, InvalidArgumentError, LoadAPIKeyError, UnsupportedFunctionalityError, getErrorMessage as getErrorMessage$1 } from "@ai-sdk/provider";
import { getContext, getVercelOidcToken } from "@vercel/oidc";
//#region src/gateway-realtime-auth.ts
/**
* Shared WebSocket subprotocol contract for AI Gateway realtime, streaming
* transcription, and streaming speech auth.
*
* The browser `WebSocket` API cannot set request headers, so the Gateway auth
* (bearer) token is carried through the `Sec-WebSocket-Protocol` handshake
* instead of an `Authorization` header — the same workaround OpenAI uses for
* `openai-insecure-api-key.<token>`.
*
* This module is the single source of truth for that contract so the client and
* the Gateway server can't drift: the client encodes values with
* `getGatewayRealtimeProtocols` / `getGatewayTranscriptionProtocols` /
* `getGatewaySpeechProtocols`, and the
* Gateway server decodes them with `getGatewayRealtimeAuthToken` /
* `getGatewayRealtimeTeamIdOrSlug`.
*
* WebSocket subprotocol values must fit the RFC token grammar. The auth token is
* sent as-is, so callers must use tokens that are valid subprotocol tokens; the
* optional team scope is base64url-encoded by this module. Keep the complete
* `Sec-WebSocket-Protocol` header compact (target under an 8 KiB safe header
* budget) because intermediaries may reject large upgrade headers.
*/
/**
* Marker subprotocol offered on every realtime handshake so the Gateway can
* echo a negotiated subprotocol on the 101 response (some clients require the
* server to select one of the offered subprotocols).
*/
const GATEWAY_REALTIME_SUBPROTOCOL = "ai-gateway-realtime.v1";
/**
* Marker subprotocol for streaming transcription handshakes (same negotiation
* purpose as `GATEWAY_REALTIME_SUBPROTOCOL`).
*/
const GATEWAY_TRANSCRIPTION_SUBPROTOCOL = "ai-gateway-transcription.v1";
/**
* Marker subprotocol for streaming speech handshakes (same negotiation
* purpose as `GATEWAY_REALTIME_SUBPROTOCOL`).
*/
const GATEWAY_SPEECH_SUBPROTOCOL = "ai-gateway-speech.v1";
/** Subprotocol prefix that carries the Gateway auth (bearer) token. */
const GATEWAY_AUTH_SUBPROTOCOL_PREFIX = "ai-gateway-auth.";
/** Subprotocol prefix that carries optional Vercel team scoping. */
const GATEWAY_TEAM_SUBPROTOCOL_PREFIX = "ai-gateway-team.";
/**
* Client-side: build the WebSocket subprotocols that carry `token` to the
* Gateway. Pass the result as the second argument to `new WebSocket(url, ...)`.
*/
function getGatewayRealtimeProtocols(token, options) {
return buildGatewayProtocols(GATEWAY_REALTIME_SUBPROTOCOL, token, options);
}
/**
* Client-side: `getGatewayRealtimeProtocols`, but with the streaming
* transcription marker subprotocol.
*/
function getGatewayTranscriptionProtocols(token, options) {
return buildGatewayProtocols(GATEWAY_TRANSCRIPTION_SUBPROTOCOL, token, options);
}
/**
* Client-side: `getGatewayRealtimeProtocols`, but with the streaming speech
* marker subprotocol.
*/
function getGatewaySpeechProtocols(token, options) {
return buildGatewayProtocols(GATEWAY_SPEECH_SUBPROTOCOL, token, options);
}
function buildGatewayProtocols(marker, token, options) {
const protocols = [marker, `${GATEWAY_AUTH_SUBPROTOCOL_PREFIX}${token}`];
if (options?.teamIdOrSlug) protocols.push(`${GATEWAY_TEAM_SUBPROTOCOL_PREFIX}${encodeSubprotocolValue(options.teamIdOrSlug)}`);
return protocols;
}
/**
* Server-side: extract the Gateway auth (bearer) token from a
* `Sec-WebSocket-Protocol` header value, or `undefined` when it is absent or
* empty. The Gateway upgrade handler turns this into an
* `Authorization: Bearer <token>` before its normal auth path.
*
* Accepts the raw header value (subprotocols are comma-separated and may carry
* surrounding whitespace).
*/
function getGatewayRealtimeAuthToken(secWebSocketProtocol) {
return findProtocol(secWebSocketProtocol, "ai-gateway-auth.")?.slice(16) || void 0;
}
/**
* Server-side: extract the optional Vercel team ID or slug from the
* `Sec-WebSocket-Protocol` header value. Team scoping is base64url-encoded so
* arbitrary team slugs stay within the WebSocket subprotocol token grammar.
*/
function getGatewayRealtimeTeamIdOrSlug(secWebSocketProtocol) {
const encoded = findProtocol(secWebSocketProtocol, GATEWAY_TEAM_SUBPROTOCOL_PREFIX)?.slice(16);
if (!encoded) return void 0;
try {
return decodeSubprotocolValue(encoded) || void 0;
} catch {
return;
}
}
function findProtocol(secWebSocketProtocol, prefix) {
return secWebSocketProtocol?.split(",").map((protocol) => protocol.trim()).find((protocol) => protocol.startsWith(prefix));
}
function encodeSubprotocolValue(value) {
const bytes = new TextEncoder().encode(value);
let binary = "";
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/u, "");
}
function decodeSubprotocolValue(value) {
const base64 = value.replace(/-/g, "+").replace(/_/g, "/");
const padding = "=".repeat((4 - base64.length % 4) % 4);
const binary = atob(`${base64}${padding}`);
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
return new TextDecoder().decode(bytes);
}
//#endregion
//#region src/zod.ts
const z = {
any,
array,
boolean,
catchall,
describe,
discriminatedUnion,
enum: enum$1,
extend,
instanceof: instanceof$1,
int,
json,
length,
literal,
maxLength,
maximum,
minLength,
minimum,
never,
nullable,
nullish,
number,
object,
optional,
pipe,
record,
refine,
string,
transform,
union,
unknown,
url
};
function describe(schema, description) {
const clone = schema.clone();
globalRegistry.add(clone, { description });
return clone;
}
//#endregion
//#region src/errors/gateway-error.ts
const symbol$11 = Symbol.for("vercel.ai.gateway.error");
var GatewayError = class GatewayError extends Error {
constructor({ message, statusCode = 500, cause, generationId, isRetryable = statusCode != null && (statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500) }) {
super(generationId ? `${message} [${generationId}]` : message);
this[symbol$11] = true;
this.statusCode = statusCode;
this.cause = cause;
this.generationId = generationId;
this.isRetryable = isRetryable;
}
/**
* Checks if the given error is a Gateway Error.
* @param {unknown} error - The error to check.
* @returns {boolean} True if the error is a Gateway Error, false otherwise.
*/
static isInstance(error) {
return GatewayError.hasMarker(error);
}
static hasMarker(error) {
return typeof error === "object" && error !== null && symbol$11 in error && error[symbol$11] === true;
}
};
//#endregion
//#region src/errors/gateway-authentication-error.ts
const name$10 = "GatewayAuthenticationError";
const marker$10 = `vercel.ai.gateway.error.${name$10}`;
const symbol$10 = Symbol.for(marker$10);
/**
* Authentication failed - invalid API key or OIDC token
*/
var GatewayAuthenticationError = class GatewayAuthenticationError extends GatewayError {
constructor({ message = "Authentication failed", statusCode = 401, cause, generationId } = {}) {
super({
message,
statusCode,
cause,
generationId
});
this[symbol$10] = true;
this.name = name$10;
this.type = "authentication_error";
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol$10 in error;
}
/**
* Creates a contextual error message when authentication fails
*/
static createContextualError({ apiKeyProvided, oidcTokenProvided, statusCode = 401, cause, generationId }) {
let contextualMessage;
if (apiKeyProvided) contextualMessage = `AI Gateway authentication failed: Invalid API key or token.
Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
Provide an API key or Vercel access token via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`;
else if (oidcTokenProvided) contextualMessage = `AI Gateway authentication failed: Invalid OIDC token.
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
or pass a Vercel access token via the 'apiKey' option.`;
else contextualMessage = `AI Gateway authentication failed: No authentication provided.
Option 1 - API key:
Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
Option 2 - Vercel access token:
Pass a Vercel personal access token or Vercel app access token via the 'apiKey' option.
Option 3 - OIDC token:
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`;
return new GatewayAuthenticationError({
message: contextualMessage,
statusCode,
cause,
generationId
});
}
};
//#endregion
//#region src/errors/gateway-invalid-request-error.ts
const name$9 = "GatewayInvalidRequestError";
const marker$9 = `vercel.ai.gateway.error.${name$9}`;
const symbol$9 = Symbol.for(marker$9);
/**
* Invalid request - missing headers, malformed data, etc.
*/
var GatewayInvalidRequestError = class extends GatewayError {
constructor({ message = "Invalid request", statusCode = 400, cause, generationId } = {}) {
super({
message,
statusCode,
cause,
generationId
});
this[symbol$9] = true;
this.name = name$9;
this.type = "invalid_request_error";
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol$9 in error;
}
};
//#endregion
//#region src/errors/gateway-rate-limit-error.ts
const name$8 = "GatewayRateLimitError";
const marker$8 = `vercel.ai.gateway.error.${name$8}`;
const symbol$8 = Symbol.for(marker$8);
/**
* Rate limit exceeded.
*/
var GatewayRateLimitError = class extends GatewayError {
constructor({ message = "Rate limit exceeded", statusCode = 429, cause, generationId } = {}) {
super({
message,
statusCode,
cause,
generationId
});
this[symbol$8] = true;
this.name = name$8;
this.type = "rate_limit_exceeded";
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol$8 in error;
}
};
//#endregion
//#region src/errors/gateway-model-not-found-error.ts
const name$7 = "GatewayModelNotFoundError";
const marker$7 = `vercel.ai.gateway.error.${name$7}`;
const symbol$7 = Symbol.for(marker$7);
const modelNotFoundParamSchema = lazySchema(() => zodSchema(z.object({ modelId: z.string() })));
/**
* Model not found or not available
*/
var GatewayModelNotFoundError = class extends GatewayError {
constructor({ message = "Model not found", statusCode = 404, modelId, cause, generationId } = {}) {
super({
message,
statusCode,
cause,
generationId
});
this[symbol$7] = true;
this.name = name$7;
this.type = "model_not_found";
this.modelId = modelId;
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol$7 in error;
}
};
//#endregion
//#region src/errors/gateway-not-found-error.ts
const name$6 = "GatewayNotFoundError";
const marker$6 = `vercel.ai.gateway.error.${name$6}`;
const symbol$6 = Symbol.for(marker$6);
/**
* Not found - the requested Gateway resource does not exist or is not
* visible to the caller (e.g. an unknown async batch/video job id).
* Distinct from `GatewayModelNotFoundError`, which is model-specific.
*/
var GatewayNotFoundError = class extends GatewayError {
constructor({ message = "Resource not found", statusCode = 404, cause, generationId } = {}) {
super({
message,
statusCode,
cause,
generationId
});
this[symbol$6] = true;
this.name = name$6;
this.type = "not_found";
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol$6 in error;
}
};
//#endregion
//#region src/errors/gateway-internal-server-error.ts
const name$5 = "GatewayInternalServerError";
const marker$5 = `vercel.ai.gateway.error.${name$5}`;
const symbol$5 = Symbol.for(marker$5);
/**
* Internal server error from the Gateway
*/
var GatewayInternalServerError = class extends GatewayError {
constructor({ message = "Internal server error", statusCode = 500, cause, generationId } = {}) {
super({
message,
statusCode,
cause,
generationId
});
this[symbol$5] = true;
this.name = name$5;
this.type = "internal_server_error";
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol$5 in error;
}
};
//#endregion
//#region src/errors/gateway-failed-dependency-error.ts
const name$4 = "GatewayFailedDependencyError";
const marker$4 = `vercel.ai.gateway.error.${name$4}`;
const symbol$4 = Symbol.for(marker$4);
/**
* The request could not be fulfilled because a dependency it relied on was not
* available on the credentials or provider used to serve it (HTTP 424). Not
* retryable — the caller must change the request.
*/
var GatewayFailedDependencyError = class extends GatewayError {
constructor({ message = "Failed dependency", statusCode = 424, cause, generationId } = {}) {
super({
message,
statusCode,
cause,
generationId
});
this[symbol$4] = true;
this.name = name$4;
this.type = "failed_dependency";
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol$4 in error;
}
};
//#endregion
//#region src/errors/gateway-forbidden-error.ts
const name$3 = "GatewayForbiddenError";
const marker$3 = `vercel.ai.gateway.error.${name$3}`;
const symbol$3 = Symbol.for(marker$3);
const forbiddenParamSchema = lazySchema(() => zodSchema(z.object({ ruleId: z.string() })));
/**
* Forbidden - the request was rejected by policy (e.g. a routing rule),
* not an authentication failure.
*/
var GatewayForbiddenError = class extends GatewayError {
constructor({ message = "Forbidden", statusCode = 403, cause, generationId, ruleId } = {}) {
super({
message,
statusCode,
cause,
generationId
});
this[symbol$3] = true;
this.name = name$3;
this.type = "forbidden";
this.ruleId = ruleId;
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol$3 in error;
}
};
//#endregion
//#region src/errors/gateway-access-policy-denied-error.ts
const name$2 = "GatewayAccessPolicyDeniedError";
const marker$2 = `vercel.ai.gateway.error.${name$2}`;
const symbol$2 = Symbol.for(marker$2);
const accessPolicyDeniedParamSchema = lazySchema(() => zodSchema(z.object({
policyIds: z.optional(z.array(z.string())),
removedModels: z.optional(z.array(z.string())),
removedProviders: z.optional(z.array(z.string()))
})));
/**
* Access policy denied - an AI Gateway access policy that applies to the
* request does not allow the requested model or provider.
*/
var GatewayAccessPolicyDeniedError = class extends GatewayError {
constructor({ message = "Access policy denied", statusCode = 403, cause, generationId, policyIds, removedModels, removedProviders } = {}) {
super({
message,
statusCode,
cause,
generationId
});
this[symbol$2] = true;
this.name = name$2;
this.type = "access_policy_denied";
this.policyIds = policyIds;
this.removedModels = removedModels;
this.removedProviders = removedProviders;
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol$2 in error;
}
};
//#endregion
//#region src/errors/gateway-response-error.ts
const name$1 = "GatewayResponseError";
const marker$1 = `vercel.ai.gateway.error.${name$1}`;
const symbol$1 = Symbol.for(marker$1);
/**
* Gateway response parsing error
*/
var GatewayResponseError = class extends GatewayError {
constructor({ message = "Invalid response from Gateway", statusCode = 502, response, validationError, cause, generationId, isRetryable } = {}) {
super({
message,
statusCode,
cause,
generationId,
isRetryable
});
this[symbol$1] = true;
this.name = name$1;
this.type = "response_error";
this.response = response;
this.validationError = validationError;
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol$1 in error;
}
};
//#endregion
//#region src/errors/create-gateway-error.ts
async function createGatewayErrorFromResponse({ response, statusCode, defaultMessage = "Gateway request failed", cause, authMethod, isRetryable }) {
const parseResult = await safeValidateTypes({
value: response,
schema: gatewayErrorResponseSchema
});
if (!parseResult.success) {
const rawGenerationId = typeof response === "object" && response !== null && "generationId" in response ? response.generationId : void 0;
return new GatewayResponseError({
message: `Invalid error response format: ${defaultMessage}`,
statusCode,
response,
validationError: parseResult.error,
cause,
generationId: rawGenerationId,
isRetryable
});
}
const validatedResponse = parseResult.value;
const errorType = validatedResponse.error.type;
const message = validatedResponse.error.message;
const generationId = validatedResponse.generationId ?? void 0;
switch (errorType) {
case "authentication_error": return GatewayAuthenticationError.createContextualError({
apiKeyProvided: authMethod === "api-key",
oidcTokenProvided: authMethod === "oidc",
statusCode,
cause,
generationId
});
case "invalid_request_error": return new GatewayInvalidRequestError({
message,
statusCode,
cause,
generationId
});
case "rate_limit_exceeded": return new GatewayRateLimitError({
message,
statusCode,
cause,
generationId
});
case "model_not_found": {
const modelResult = await safeValidateTypes({
value: validatedResponse.error.param,
schema: modelNotFoundParamSchema
});
return new GatewayModelNotFoundError({
message,
statusCode,
modelId: modelResult.success ? modelResult.value.modelId : void 0,
cause,
generationId
});
}
case "not_found": return new GatewayNotFoundError({
message,
statusCode,
cause,
generationId
});
case "internal_server_error": return new GatewayInternalServerError({
message,
statusCode,
cause,
generationId
});
case "failed_dependency": return new GatewayFailedDependencyError({
message,
statusCode,
cause,
generationId
});
case "forbidden": {
const ruleResult = await safeValidateTypes({
value: validatedResponse.error.param,
schema: forbiddenParamSchema
});
return new GatewayForbiddenError({
message,
statusCode,
cause,
generationId,
ruleId: ruleResult.success ? ruleResult.value.ruleId : void 0
});
}
case "access_policy_denied": {
const paramResult = await safeValidateTypes({
value: validatedResponse.error.param,
schema: accessPolicyDeniedParamSchema
});
const param = paramResult.success ? paramResult.value : void 0;
return new GatewayAccessPolicyDeniedError({
message,
statusCode,
cause,
generationId,
policyIds: param?.policyIds,
removedModels: param?.removedModels,
removedProviders: param?.removedProviders
});
}
default: return new GatewayInternalServerError({
message,
statusCode,
cause,
generationId
});
}
}
const gatewayErrorResponseSchema = lazySchema(() => zodSchema(z.object({
error: z.object({
message: z.string(),
type: z.nullish(z.string()),
param: z.nullish(z.unknown()),
code: z.nullish(z.union([z.string(), z.number()]))
}),
generationId: z.nullish(z.string())
})));
//#endregion
//#region src/errors/extract-api-call-response.ts
function extractApiCallResponse(error) {
if (error.data !== void 0) return error.data;
if (error.responseBody != null) try {
return secureJsonParse(error.responseBody);
} catch {
return error.responseBody;
}
return {};
}
//#endregion
//#region src/errors/gateway-timeout-error.ts
const name = "GatewayTimeoutError";
const marker = `vercel.ai.gateway.error.${name}`;
const symbol = Symbol.for(marker);
/**
* Client request timed out before receiving a response.
*/
var GatewayTimeoutError = class GatewayTimeoutError extends GatewayError {
constructor({ message = "Request timed out", statusCode = 408, cause, generationId } = {}) {
super({
message,
statusCode,
cause,
generationId
});
this[symbol] = true;
this.name = name;
this.type = "timeout_error";
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol in error;
}
/**
* Creates a helpful timeout error message with troubleshooting guidance
*/
static createTimeoutError({ originalMessage, statusCode = 408, cause, generationId }) {
const message = `Gateway request timed out: ${originalMessage}
This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;
return new GatewayTimeoutError({
message,
statusCode,
cause,
generationId
});
}
};
//#endregion
//#region src/errors/as-gateway-error.ts
/**
* Checks if an error is a timeout error from undici.
* Only checks undici-specific error codes to avoid false positives.
*/
function isTimeoutError(error) {
if (!(error instanceof Error)) return false;
const errorCode = error.code;
if (typeof errorCode === "string") return [
"UND_ERR_HEADERS_TIMEOUT",
"UND_ERR_BODY_TIMEOUT",
"UND_ERR_CONNECT_TIMEOUT"
].includes(errorCode);
return false;
}
async function asGatewayError(error, authMethod) {
if ((error instanceof Error || typeof DOMException === "function" && error instanceof DOMException) && (error.name === "AbortError" || error.name === "TimeoutError")) throw error;
if (GatewayError.isInstance(error)) return error;
if (isTimeoutError(error)) return GatewayTimeoutError.createTimeoutError({
originalMessage: error instanceof Error ? error.message : "Unknown error",
cause: error
});
if (APICallError.isInstance(error)) {
if (error.cause && isTimeoutError(error.cause)) return GatewayTimeoutError.createTimeoutError({
originalMessage: error.message,
cause: error
});
return await createGatewayErrorFromResponse({
response: extractApiCallResponse(error),
statusCode: error.statusCode ?? 500,
defaultMessage: "Gateway request failed",
cause: error,
authMethod,
isRetryable: error.isRetryable && (error.statusCode == null || error.statusCode < 400) ? true : void 0
});
}
return await createGatewayErrorFromResponse({
response: {},
statusCode: 500,
defaultMessage: error instanceof Error ? `Gateway request failed: ${error.message}` : "Unknown Gateway error",
cause: error,
authMethod
});
}
//#endregion
//#region src/gateway-headers.ts
const GATEWAY_AUTH_METHOD_HEADER = "ai-gateway-auth-method";
const VERCEL_AI_GATEWAY_TEAM_HEADER = "x-vercel-ai-gateway-team";
//#endregion
//#region src/errors/parse-auth-method.ts
async function parseAuthMethod(headers) {
const result = await safeValidateTypes({
value: headers[GATEWAY_AUTH_METHOD_HEADER],
schema: gatewayAuthMethodSchema
});
return result.success ? result.value : void 0;
}
const gatewayAuthMethodSchema = lazySchema(() => zodSchema(z.union([z.literal("api-key"), z.literal("oidc")])));
//#endregion
//#region src/gateway-model-entry.ts
const KNOWN_MODEL_TYPES = [
"embedding",
"decision",
"evaluation",
"extraction",
"image",
"language",
"realtime",
"reranking",
"speech",
"transcription",
"video"
];
//#endregion
//#region src/gateway-fetch-metadata.ts
var GatewayFetchMetadata = class {
constructor(config) {
this.config = config;
}
async getAvailableModels() {
try {
const { value } = await getFromApi({
url: `${this.config.baseURL}/config`,
validateUrl: false,
headers: this.config.headers ? await resolve(this.config.headers) : void 0,
successfulResponseHandler: createJsonResponseHandler(gatewayAvailableModelsResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => getErrorMessage(data) ?? "unknown error"
}),
fetch: this.config.fetch
});
return value;
} catch (error) {
throw await asGatewayError(error);
}
}
async getCredits() {
try {
const baseUrl = new URL(this.config.baseURL);
const headers = this.config.headers ? await resolve(this.config.headers) : void 0;
const url = new URL("/v1/credits", baseUrl.origin);
const teamIdOrSlug = getTeamIdOrSlug(headers);
if (teamIdOrSlug) url.searchParams.set(teamIdOrSlug.startsWith("team_") ? "teamId" : "slug", teamIdOrSlug);
const { value } = await getFromApi({
url: url.toString(),
validateUrl: false,
headers,
successfulResponseHandler: createJsonResponseHandler(gatewayCreditsResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => getErrorMessage(data) ?? "unknown error"
}),
fetch: this.config.fetch
});
return value;
} catch (error) {
throw await asGatewayError(error);
}
}
};
function getTeamIdOrSlug(headers) {
if (!headers) return void 0;
for (const [name, value] of Object.entries(headers)) if (name.toLowerCase() === "x-vercel-ai-gateway-team") return value?.trim() || void 0;
}
const gatewayAvailableModelsResponseSchema = lazySchema(() => zodSchema(z.object({ models: z.pipe(z.array(z.object({
id: z.string(),
name: z.string(),
description: z.nullish(z.string()),
pricing: z.nullish(z.pipe(z.object({
input: z.string(),
output: z.string(),
input_cache_read: z.nullish(z.string()),
input_cache_write: z.nullish(z.string())
}), z.transform(({ input, output, input_cache_read, input_cache_write }) => ({
input,
output,
...input_cache_read ? { cachedInputTokens: input_cache_read } : {},
...input_cache_write ? { cacheCreationInputTokens: input_cache_write } : {}
})))),
specification: z.object({
specificationVersion: z.literal("v4"),
provider: z.string(),
modelId: z.string()
}),
modelType: z.nullish(z.string())
})), z.transform((models) => models.filter((m) => m.modelType == null || KNOWN_MODEL_TYPES.includes(m.modelType)))) })));
const gatewayCreditsResponseSchema = lazySchema(() => zodSchema(z.pipe(z.object({
balance: z.string(),
total_used: z.string()
}), z.transform(({ balance, total_used }) => ({
balance,
totalUsed: total_used
})))));
//#endregion
//#region src/gateway-spend-report.ts
var GatewaySpendReport = class {
constructor(config) {
this.config = config;
}
async getSpendReport(params) {
try {
const baseUrl = new URL(this.config.baseURL);
const searchParams = new URLSearchParams();
searchParams.set("start_date", params.startDate);
searchParams.set("end_date", params.endDate);
if (params.groupBy) searchParams.set("group_by", params.groupBy);
if (params.datePart) searchParams.set("date_part", params.datePart);
if (params.userId) searchParams.set("user_id", params.userId);
if (params.model) searchParams.set("model", params.model);
if (params.provider) searchParams.set("provider", params.provider);
if (params.credentialType) searchParams.set("credential_type", params.credentialType);
if (params.tags && params.tags.length > 0) searchParams.set("tags", params.tags.join(","));
const { value } = await getFromApi({
url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`,
validateUrl: false,
headers: this.config.headers ? await resolve(this.config.headers) : void 0,
successfulResponseHandler: createJsonResponseHandler(gatewaySpendReportResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => getErrorMessage(data) ?? "unknown error"
}),
fetch: this.config.fetch
});
return value;
} catch (error) {
throw await asGatewayError(error);
}
}
};
const gatewaySpendReportResponseSchema = lazySchema(() => zodSchema(z.object({ results: z.array(z.pipe(z.object({
day: z.optional(z.string()),
hour: z.optional(z.string()),
user: z.optional(z.string()),
model: z.optional(z.string()),
tag: z.optional(z.string()),
provider: z.optional(z.string()),
credential_type: z.optional(z.enum(["byok", "system"])),
total_cost: z.number(),
market_cost: z.optional(z.number()),
input_tokens: z.optional(z.number()),
output_tokens: z.optional(z.number()),
cached_input_tokens: z.optional(z.number()),
cache_creation_input_tokens: z.optional(z.number()),
reasoning_tokens: z.optional(z.number()),
request_count: z.optional(z.number())
}), z.transform(({ credential_type, total_cost, market_cost, input_tokens, output_tokens, cached_input_tokens, cache_creation_input_tokens, reasoning_tokens, request_count, ...rest }) => ({
...rest,
...credential_type !== void 0 ? { credentialType: credential_type } : {},
totalCost: total_cost,
...market_cost !== void 0 ? { marketCost: market_cost } : {},
...input_tokens !== void 0 ? { inputTokens: input_tokens } : {},
...output_tokens !== void 0 ? { outputTokens: output_tokens } : {},
...cached_input_tokens !== void 0 ? { cachedInputTokens: cached_input_tokens } : {},
...cache_creation_input_tokens !== void 0 ? { cacheCreationInputTokens: cache_creation_input_tokens } : {},
...reasoning_tokens !== void 0 ? { reasoningTokens: reasoning_tokens } : {},
...request_count !== void 0 ? { requestCount: request_count } : {}
})))) })));
//#endregion
//#region src/gateway-generation-info.ts
var GatewayGenerationInfoFetcher = class {
constructor(config) {
this.config = config;
}
async getGenerationInfo(params) {
try {
const baseUrl = new URL(this.config.baseURL);
const { value } = await getFromApi({
url: `${baseUrl.origin}/v1/generation?id=${encodeURIComponent(params.id)}`,
validateUrl: false,
headers: this.config.headers ? await resolve(this.config.headers) : void 0,
successfulResponseHandler: createJsonResponseHandler(gatewayGenerationInfoResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => getErrorMessage(data) ?? "unknown error"
}),
fetch: this.config.fetch
});
return value;
} catch (error) {
throw await asGatewayError(error);
}
}
};
const gatewayGenerationInfoResponseSchema = lazySchema(() => zodSchema(z.pipe(z.object({ data: z.pipe(z.object({
id: z.string(),
total_cost: z.number(),
market_cost: z.nullish(z.number()),
surcharge_cost: z.nullish(z.number()),
gateway_cost: z.nullish(z.number()),
upstream_inference_cost: z.number(),
usage: z.number(),
created_at: z.string(),
model: z.string(),
is_byok: z.boolean(),
provider_name: z.string(),
streamed: z.boolean(),
finish_reason: z.string(),
latency: z.number(),
generation_time: z.number(),
native_tokens_prompt: z.number(),
native_tokens_completion: z.number(),
native_tokens_reasoning: z.number(),
native_tokens_cached: z.number(),
native_tokens_cache_creation: z.number(),
billable_web_search_calls: z.number()
}), z.transform(({ total_cost, market_cost, surcharge_cost, gateway_cost, upstream_inference_cost, created_at, is_byok, provider_name, finish_reason, generation_time, native_tokens_prompt, native_tokens_completion, native_tokens_reasoning, native_tokens_cached, native_tokens_cache_creation, billable_web_search_calls, ...rest }) => ({
...rest,
totalCost: total_cost,
...market_cost != null ? { marketCost: market_cost } : {},
...surcharge_cost != null ? { surchargeCost: surcharge_cost } : {},
...gateway_cost != null ? { gatewayCost: gateway_cost } : {},
upstreamInferenceCost: upstream_inference_cost,
createdAt: created_at,
isByok: is_byok,
providerName: provider_name,
finishReason: finish_reason,
generationTime: generation_time,
promptTokens: native_tokens_prompt,
completionTokens: native_tokens_completion,
reasoningTokens: native_tokens_reasoning,
cachedTokens: native_tokens_cached,
cacheCreationTokens: native_tokens_cache_creation,
billableWebSearchCalls: billable_web_search_calls
}))) }), z.transform(({ data }) => data))));
//#endregion
//#region src/redact-gateway-request-credentials.ts
const REDACTED = "[redacted]";
/**
* Gateway request bodies can carry request-scoped BYOK credentials in
* `providerOptions.gateway.byok`. The credentials must reach the Gateway and
* stay on application-facing errors, but telemetry-only copies must not expose
* them.
*/
function withGatewayRequestTelemetryRedaction(value) {
if (!isRecord$1(value)) return value;
const body = value;
if (!hasByok(body.providerOptions) && !hasRequestByok(body.requests)) return value;
return withTelemetryRedaction(body, (redacted) => ({
...redacted,
...hasByok(redacted.providerOptions) && { providerOptions: redactProviderOptions(redacted.providerOptions) },
...Array.isArray(redacted.requests) && { requests: redacted.requests.map(redactRequestProviderOptions) }
}));
}
/** Batch bodies nest the same provider options in every request's options. */
function redactRequestProviderOptions(request) {
if (!isRecord$1(request) || !isRecord$1(request.options)) return request;
const options = request.options;
if (!hasByok(options.providerOptions)) return request;
return {
...request,
options: {
...options,
providerOptions: redactProviderOptions(options.providerOptions)
}
};
}
function redactProviderOptions(value) {
if (!isRecord$1(value) || !isRecord$1(value.gateway)) return value;
return {
...value,
gateway: {
...value.gateway,
byok: redactByok(value.gateway.byok)
}
};
}
/** Keep provider names and credential shapes; replace every BYOK value. */
function redactByok(value) {
if (Array.isArray(value)) return value.map(redactByok);
if (isRecord$1(value)) return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, redactByok(entry)]));
return REDACTED;
}
function hasByok(providerOptions) {
return isRecord$1(providerOptions) && isRecord$1(providerOptions.gateway) && providerOptions.gateway.byok !== void 0;
}
function hasRequestByok(requests) {
return Array.isArray(requests) && requests.some((request) => {
if (!isRecord$1(request) || !isRecord$1(request.options)) return false;
return hasByok(request.options.providerOptions);
});
}
function isRecord$1(value) {
return value != null && typeof value === "object" && !Array.isArray(value);
}
//#endregion
//#region src/gateway-batch.ts
var GatewayBatch = class {
constructor(config) {
this.config = config;
this.specificationVersion = "v4";
this.supportedUrls = { "*/*": [/.*/] };
this.provider = `${config.provider}.batch`;
}
/**
* Starts a durable batch of text-generation requests through the Gateway's
* async batch surface (`POST {baseURL}/batch/start`). The returned
* `batchId` is the Gateway job id — provider-native batch ids stay
* server-side, so status and results always route back through the
* Gateway job.
*/
async doStartBatch({ requests, providerOptions, headers, abortSignal, webhookUrl }) {
assertTextBatchRequests(requests);
const modelId = validateSingleModel(requests);
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
const idempotencyKey = getGatewayBatchIdempotencyKey(providerOptions);
const forwardedProviderOptions = omitGatewayIdempotencyKey(providerOptions);
try {
const { value: responseBody } = await postJsonToApi({
url: this.getBatchUrl("start"),
headers: combineHeaders(resolvedHeaders, headers, { "ai-model-id": modelId }, await resolve(this.config.o11yHeaders), idempotencyKey != null ? { "idempotency-key": idempotencyKey } : void 0),
body: withGatewayRequestTelemetryRedaction({
...webhookUrl != null && { callbackUrl: webhookUrl },
requests: requests.map((request) => ({
id: request.id,
type: request.type,
modelId: request.modelId,
options: maybeEncodeBatchFileParts(request.options)
})),
...forwardedProviderOptions != null && { providerOptions: forwardedProviderOptions }
}),
successfulResponseHandler: createJsonResponseHandler(gatewayBatchStartResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => getErrorMessage(data) ?? "unknown error"
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
batchId: responseBody.batchId,
...convertGatewayBatchStatus(responseBody),
warnings: responseBody.warnings ?? []
};
} catch (error) {
if (isAbortOrTimeoutError(error)) throw error;
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders ?? {}));
}
}
/**
* Retrieves the lifecycle status of a Gateway batch job
* (`POST {baseURL}/batch/status`).
*/
async doGetBatchStatus({ batchId, headers, abortSignal }) {
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { value: responseBody } = await postJsonToApi({
url: this.getBatchUrl("status"),
headers: combineHeaders(resolvedHeaders, headers, await resolve(this.config.o11yHeaders)),
body: { batchId },
successfulResponseHandler: createJsonResponseHandler(gatewayBatchStatusResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => getErrorMessage(data) ?? "unknown error"
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return convertGatewayBatchStatus(responseBody);
} catch (error) {
if (isAbortOrTimeoutError(error)) throw error;
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders ?? {}));
}
}
/**
* Streams the per-request results of a terminal Gateway batch job
* (`POST {baseURL}/batch/results`, `application/x-ndjson`: one
* `BatchV4ItemResult` JSON object per line). Items are validated minimally
* (id + status) and passed through — the Gateway sanitizes them
* server-side. The route responds 400 while the batch is non-terminal.
*/
async doGetBatchResults({ batchId, headers, abortSignal }) {
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { value: lines } = await postJsonToApi({
url: this.getBatchUrl("results"),
headers: combineHeaders(resolvedHeaders, headers, await resolve(this.config.o11yHeaders)),
body: { batchId },
successfulResponseHandler: createJsonLinesResponseHandler(gatewayBatchItemResultLineSchema, { maxLineBytes: this.config.maxLineBytes }),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => getErrorMessage(data) ?? "unknown error"
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return convertAsyncIteratorToReadableStream(convertGatewayBatchResultLines(lines));
} catch (error) {
if (isAbortOrTimeoutError(error)) throw error;
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders ?? {}));
}
}
/** Requests cancellation; status and partial results remain separate reads. */
async doCancelBatch({ batchId, headers, abortSignal }) {
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { value: responseBody } = await postJsonToApi({
url: this.getBatchUrl("cancel"),
headers: combineHeaders(resolvedHeaders, headers, await resolve(this.config.o11yHeaders)),
body: { batchId },
successfulResponseHandler: createJsonResponseHandler(gatewayBatchStatusResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => getErrorMessage(data) ?? "unknown error"
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return { ...responseBody.providerMetadata != null && { providerMetadata: responseBody.providerMetadata } };
} catch (error) {
if (isAbortOrTimeoutError(error)) throw error;
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders ?? {}));
}
}
getBatchUrl(path) {
return `${this.config.baseURL}/batch/${path}`;
}
};
function maybeEncodeBatchFileParts(options) {
for (const message of options.prompt) {
if (!Array.isArray(message.content)) continue;
for (const part of message.content) if (part.type === "file" || part.type === "reasoning-file") part.data = maybeBase64EncodeFileData$1(part.data);
else if (part.type === "tool-result" && part.output.type === "content") {
for (const contentPart of part.output.value) if (contentPart.type === "file") contentPart.data = maybeBase64EncodeFileData$1(contentPart.data);
}
}
return options;
}
function maybeBase64EncodeFileData$1(data) {
if (data.type === "data") {
const bytes = data.data;
if (bytes instanceof Uint8Array) return {
...data,
data: Buffer.from(bytes).toString("base64")
};
}
return data;
}
function validateSingleModel(requests) {
const modelId = requests[0]?.modelId;
if (modelId == null) throw new InvalidArgumentError({
argument: "requests",
message: "The AI Gateway Batch API requires at least one request."
});
for (const request of requests) if (request.modelId !== modelId) throw new InvalidArgumentError({
argument: "requests",
message: `The AI Gateway Batch API requires all requests in a batch to use the same model. Found "${modelId}" and "${request.modelId}".`
});
return modelId;
}
function assertTextBatchRequests(requests) {
for (const request of requests) {
const requestType = request.type;
if (requestType !== "text") throw new UnsupportedFunctionalityError({
functionality: `batch request type: ${requestType}`,
message: `The AI Gateway Batch API does not support batch requests with type "${requestType}".`
});
}
}
/**
* Extracts the optional Gateway idempotency key from
* `providerOptions.gateway.idempotencyKey`. It is sent as the
* `idempotency-key` request header — the Gateway's replay contract for batch
* starts — and stripped from the forwarded body by
* `omitGatewayIdempotencyKey`.
*/
function getGatewayBatchIdempotencyKey(providerOptions) {
const gatewayOptions = providerOptions?.gateway;
if (gatewayOptions == null || typeof gatewayOptions !== "object" || Array.isArray(gatewayOptions)) return;
const key = gatewayOptions.idempotencyKey;
return typeof key === "string" && key.length > 0 ? key : void 0;
}
/**
* Removes `gateway.idempotencyKey` from the providerOptions forwarded in the
* request body. The key is transport metadata (it rides the `idempotency-key`
* header); the Gateway hashes the raw body for replay payload identity but
* normalizes the header separately, so keeping it out of the payload prevents
* equivalent retries from producing different digests (a false 422).
*/
function omitGatewayIdempotencyKey(providerOptions) {
const gatewayOptions = providerOptions?.gateway;
if (gatewayOptions == null || typeof gatewayOptions !== "object" || Array.isArray(gatewayOptions) || !("idempotencyKey" in gatewayOptions)) return providerOptions;
const { idempotencyKey: _idempotencyKey, ...restGatewayOptions } = gatewayOptions;
const restProviderOptions = { ...providerOptions };
if (Object.keys(restGatewayOptions).length === 0) delete restProviderOptions.gateway;
else restProviderOptions.gateway = restGatewayOptions;
if (Object.keys(restProviderOptions).length === 0) return;
return restProviderOptions;
}
/**
* Matches cancellation errors (`AbortError`/`TimeoutError`), which
* `asGatewayError` would otherwise wrap into a retryable Gateway 500. Kept
* local because `isAbortError` is not exported from `@ai-sdk/provider-utils`;
* `DOMException` does not extend `Error`, so both must be checked.
*/
function isAbortOrTimeoutError(error) {
if (!(error instanceof Error || error instanceof DOMException)) return false;
return error.name === "AbortError" || error.name === "TimeoutError";
}
function convertGatewayBatchStatus(body) {
const requestCounts = normalizeBatchRequestCounts({
total: body.requestCounts?.total,
pending: body.requestCounts?.pending,
completed: body.requestCounts?.completed,
failed: body.requestCounts?.failed
});
return {
status: body.status,
...body.rawStatus != null && { rawStatus: body.rawStatus },
...requestCounts != null && { requestCounts },
...body.error != null && { error: {
message: body.error.message,
...body.error.type != null && { type: body.error.type },
...body.error.code != null && { code: body.error.code },
...body.error.statusCode != null && { statusCode: body.error.statusCode }
} },
...body.createdAt != null && { createdAt: body.createdAt },
...body.expiresAt != null && { expiresAt: body.expiresAt },
...body.providerMetadata != null && { providerMetadata: body.providerMetadata }
};
}
/**
* Converts the minimally validated Gateway batch result lines. The Gateway
* already sanitizes the complete result objects server-side.
*
* @yields Each Gateway batch item result.
*/
async function* convertGatewayBatchResultLines(lines) {
for await (const line of lines) {
const item = line;
if (item.status === "succeeded") {
const response = item.result?.response;
if (response !== void 0 && typeof response.timestamp === "string") response.timestamp = new Date(response.timestamp);
}
yield item;
}
}
const gatewayBatchItemResultLineSchema = lazySchema(() => zodSchema(z.catchall(z.object({
type: z.literal("text"),
id: z.string(),
status: z.enum([
"cancelled",
"expired",
"failed",
"succeeded"
])
}), z.unknown())));
const gatewayBatchErrorSchema = () => z.object({
message: z.string(),
type: z.nullish(z.string()),
code: z.nullish(z.string()),
statusCode: z.nullish(z.number())
});
const gatewayBatchRequestCountsSchema = () => z.object({
total: z.nullish(z.number()),
pending: z.nullish(z.number()),
completed: z.nullish(z.number()),
failed: z.nullish(z.number())
});
const gatewayBatchProviderMetadataSchema = () => z.record(z.string(), z.record(z.string(), z.unknown()));
const gatewayBatchStatusFieldsSchema = () => z.object({
status: z.enum([
"completed",
"failed",
"pending"
]),
rawStatus: z.nullish(z.string()),
requestCounts: z.nullish(gatewayBatchRequestCountsSchema()),
error: z.nullish(gatewayBatchErrorSchema()),
createdAt: z.nullish(z.string()),
expiresAt: z.nullish(z.string()),
providerMetadata: z.nullish(gatewayBatchProviderMetadataSchema())
});
const gatewayBatchStartResponseSchema = lazySchema(() => zodSchema(z.extend(gatewayBatchStatusFieldsSchema(), {
batchId: z.string(),
warnings: z.nullish(z.array(z.catchall(z.object({
requestId: z.nullish(z.string()),
warning: z.unknown()
}), z.unknown())))
})));
const gatewayBatchStatusResponseSchema = lazySchema(() => zodSchema(gatewayBatchStatusFieldsSchema()));
//#endregion
//#region src/gateway-language-model.ts
var GatewayLanguageModel = class GatewayLanguageModel {
static [WORKFLOW_SERIALIZE](model) {
return serializeModelOptions({
modelId: model.modelId,
config: model.config
});
}
static [WORKFLOW_DESERIALIZE](options) {
return new GatewayLanguageModel(options.modelId, options.config);
}
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
this.supportedUrls = { "*/*": [/.*/] };
}
get provider() {
return this.config.provider;
}
async getArgs(options) {
const { abortSignal: _abortSignal, ...optionsWithoutSignal } = options;
return {
args: withGatewayRequestTelemetryRedaction(this.maybeEncodeFileParts(optionsWithoutSignal)),
warnings: []
};
}
async doGenerate(options) {
const { args, warnings } = await this.getArgs(options);
const { abortSignal } = options;
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { responseHeaders, value: responseBody, rawValue: rawResponse } = await postJsonToApi({
url: this.getUrl(),
headers: combineHeaders(resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, false), await resolve(this.config.o11yHeaders)),
body: args,
successfulResponseHandler: createJsonResponseHandler(z.any()),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => getErrorMessage(data) ?? "unknown error"
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
...responseBody,
request: { body: args },
response: {
headers: responseHeaders,
body: rawResponse
},
warnings: [...responseBody.warnings ?? [], ...warnings]
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders ?? {}));
}
}
async doStream(options) {
const { args, warnings } = await this.getArgs(options);
const { abortSignal } = options;
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { value: response, responseHeaders } = await postJsonToApi({
url: this.getUrl(),
headers: combineHeaders(resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, true), await resolve(this.config.o11yHeaders)),
body: args,
successfulResponseHandler: createEventSourceResponseHandler(z.any()),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => getErrorMessage(data) ?? "unknown error"
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
stream: response.pipeThrough(new TransformStream({
start(controller) {
if (warnings.length > 0) controller.enqueue({
type: "stream-start",
warnings
});
},
transform(chunk, controller) {
if (chunk.success) {
const streamPart = chunk.value;
if (streamPart.type === "raw" && !options.includeRawChunks) return;
if (streamPart.type === "response-metadata" && streamPart.timestamp && typeof streamPart.timestamp === "string") streamPart.timestamp = new Date(streamPart.timestamp);
controller.enqueue(streamPart);
} else controller.error(chunk.error);
}
})),
request: { body: args },
response: { headers: responseHeaders }
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders ?? {}));
}
}
/**
* Encodes inline `Uint8Array` file data to a base64 string in place.
* @param options - The options to encode.
* @returns The options with the file data encoded.
*/
maybeEncodeFileParts(options) {
for (const message of options.prompt) {
if (!Array.isArray(message.content)) continue;
for (const part of message.content) if (part.type === "file" || part.type === "reasoning-file") part.data = maybeBase64EncodeFileData(part.data);
else if (part.type === "tool-result" && part.output.type === "content") {
for (const contentPart of part.output.value) if (contentPart.type === "file") contentPart.data = maybeBase64EncodeFileData(contentPart.data);
}
}
return options;
}
getUrl() {
return `${this.config.baseURL}/language-model`;
}
getModelConfigHeaders(modelId, streaming) {
return {
"ai-language-model-specification-version": "4",
"ai-language-model-id": modelId,
"ai-language-model-streaming": String(streaming)
};
}
};
function maybeBase64EncodeFileData(data) {
if (data.type === "data") {
const bytes = data.data;
if (bytes instanceof Uint8Array) return {
...data,
data: Buffer.from(bytes).toString("base64")
};
}
return data;
}
//#endregion
//#region src/gateway-embedding-model.ts
var GatewayEmbeddingModel = class GatewayEmbeddingModel {
static [WORKFLOW_SERIALIZE](model) {
return serializeModelOptions({
modelId: model.modelId,
config: model.config
});
}
static [WORKFLOW_DESERIALIZE](options) {
return new GatewayEmbeddingModel(options.modelId, options.config);
}
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
this.maxEmbeddingsPerCall = 2048;
this.supportsParallelCalls = true;
}
get provider() {
return this.config.provider;
}
async doEmbed({ values, dimensions, headers, abortSignal, providerOptions }) {
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
url: this.getUrl(),
headers: combineHeaders(resolvedHeaders, headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
body: withGatewayRequestTelemetryRedaction({
values,
dimensions,
...providerOptions ? { providerOptions } : {}
}),
successfulResponseHandler: createJsonResponseHandler(gatewayEmbeddingResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => getErrorMessage(data) ?? "unknown error"
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
embeddings: responseBody.embeddings,
usage: responseBody.usage ?? void 0,
providerMetadata: responseBody.providerMetadata,
response: {
headers: responseHeaders,
body: rawValue
},
warnings: responseBody.warnings ?? []
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders ?? {}));
}
}
getUrl() {
return `${this.config.baseURL}/embedding-model`;
}
getModelConfigHeaders() {
return {
"ai-embedding-model-specification-version": "4",
"ai-model-id": this.modelId
};
}
};
const gatewayEmbeddingWarningSchema = () => z.discriminatedUnion("type", [
z.object({
type: z.literal("unsupported"),
feature: z.string(),
details: z.optional(z.string())
}),
z.object({
type: z.literal("compatibility"),
feature: z.string(),
details: z.optional(z.string())
}),
z.object({
type: z.literal("deprecated"),
setting: z.string(),
message: z.string()
}),
z.object({
type: z.literal("other"),
message: z.string()
})
]);
const gatewayEmbeddingResponseSchema = lazySchema(() => zodSchema(z.object({
embeddings: z.array(z.array(z.number())),
usage: z.nullish(z.object({ tokens: z.number() })),
warnings: z.optional(z.array(gatewayEmbeddingWarningSchema())),
providerMetadata: z.optional(z.record(z.string(), z.record(z.string(), z.unknown())))
})));
//#endregion
//#region src/gateway-image-model.ts
var GatewayImageModel = class GatewayImageModel {
static [WORKFLOW_SERIALIZE](model) {
return serializeModelOptions({
modelId: model.modelId,
config: model.config
});
}
static [WORKFLOW_DESERIALIZE](options) {
return new GatewayImageModel(options.modelId, options.config);
}
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
this.maxImagesPerCall = Number.MAX_SAFE_INTEGER;
}
get provider() {
return this.config.provider;
}
async doGenerate({ prompt, n, size, aspectRatio, seed, files, mask, providerOptions, headers, abortSignal }) {
const gatewayOptions = providerOptions?.gateway;
const streamingImageDecoding = gatewayOptions?.experimental_streamingImageDecoding === true;
let requestProviderOptions = providerOptions;
if (gatewayOptions && "experimental_streamingImageDecoding" in gatewayOptions) {
const { experimental_streamingImageDecoding: _, ...serviceOptions } = gatewayOptions;
requestProviderOptions = { ...providerOptions };
if (Object.keys(serviceOptions).length > 0) requestProviderOptions.gateway = serviceOptions;
else delete requestProviderOptions.gateway;
if (Object.keys(requestProviderOptions).length === 0) requestProviderOptions = void 0;
}
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { responseHeaders, value: responseBody } = await postJsonToApi({
url: this.getUrl(),
headers: combineHeaders(resolvedHeaders, headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
body: withGatewayRequestTelemetryRedaction({
prompt,
n,
...size && { size },
...aspectRatio && { aspectRatio },
...seed != null && { seed },
...requestProviderOptions && { providerOptions: requestProviderOptions },
...files && { files: files.map((file) => maybeEncodeImageFile(file)) },
...mask && { mask: maybeEncodeImageFile(mask) }
}),
successfulResponseHandler: createJsonResponseHandler(gatewayImageResponseSchema, streamingImageDecoding ? { experimental_binaryFields: ["images[*]"] } : void 0),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => getErrorMessage(data) ?? "unknown error"
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
images: toImageModelImages(responseBody.images),
...responseBody.isRetryable != null && { isRetryable: responseBody.isRetryable },
warnings: responseBody.warnings ?? [],
providerMetadata: responseBody.providerMetadata,
response: {
timestamp: /* @__PURE__ */ new Date(),
modelId: this.modelId,
headers: responseHeaders
},
...responseBody.usage != null && { usage: {
inputTokens: responseBody.usage.inputTokens ?? void 0,
outputTokens: responseBody.usage.outputTokens ?? void 0,
totalTokens: responseBody.usage.totalTokens ?? void 0
} }
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders ?? {}));
}
}
getUrl() {
return `${this.config.baseURL}/image-model`;
}
getModelConfigHeaders() {
return {
"ai-image-model-specification-version": "4",
"ai-model-id": this.modelId
};
}
};
function maybeEncodeImageFile(file) {
if (file.type === "file" && file.data instanceof Uint8Array) return {
...file,
data: convertUint8ArrayToBase64(file.data)
};
return file;
}
function toImageModelImages(images) {
if (images.every((image) => typeof image === "string")) return images;
return images.map((image) => typeof image === "string" ? convertBase64ToUint8Array(image) : image);
}
const providerMetadataEntrySchema$3 = () => z.catchall(z.object({ images: z.optional(z.array(z.unknown())) }), z.unknown());
const gatewayImageWarningSchema = () => z.discriminatedUnion("type", [
z.object({
type: z.literal("unsupported"),
feature: z.string(),
details: z.optional(z.string())
}),
z.object({
type: z.literal("compatibility"),
feature: z.string(),
details: z.optional(z.string())
}),
z.object({
type: z.literal("deprecated"),
setting: z.string(),
message: z.string()
}),
z.object({
type: z.literal("other"),
message: z.string()
})
]);
const gatewayImageUsageSchema = () => z.object({
inputTokens: z.nullish(z.number()),
outputTokens: z.nullish(z.number()),
totalTokens: z.nullish(z.number())
});
const gatewayImageResponseSchema = lazySchema(() => zodSchema(z.object({
images: z.array(z.union([z.string(), z.instanceof(Uint8Array)])),
isRetryable: z.optional(z.boolean()),
warnings: z.optional(z.array(gatewayImageWarningSchema())),
providerMetadata: z.optional(z.record(z.string(), providerMetadataEntrySchema$3())),
usage: z.optional(gatewayImageUsageSchema())
})));
//#endregion
//#region src/gateway-video-model.ts
/**
* Maximum size of the result event: 512 * 1024 * 1024 characters.
*
* The result event contains all generated videos, which can be base64 encoded,
* so it can be much larger than the default maximum event size. The limit is
* about the maximum length of a string in V8.
*/
const MAX_RESULT_EVENT_SIZE = 536870912;
var GatewayVideoModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
this.maxVideosPerCall = Number.MAX_SAFE_INTEGER;
}
get provider() {
return this.config.provider;
}
async doGenerate(options) {
const { headers, abortSignal } = options;
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { responseHeaders, value: responseBody } = await postJsonToApi({
url: this.getUrl(),
headers: combineHeaders(resolvedHeaders, headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders), { accept: "text/event-stream" }),
body: withGatewayRequestTelemetryRedaction(this.buildRequestBody(options)),
successfulResponseHandler: async ({ response, url, requestBodyValues }) => {
if (response.body == null) throw new APICallError({
message: "SSE response body is empty",
url,
requestBodyValues,
statusCode: response.status
});
const reader = parseJsonEventStream({
stream: response.body,
schema: gatewayVideoEventSchema,
maxEventSize: MAX_RESULT_EVENT_SIZE
}).getReader();
const { done, value: parseResult } = await reader.read();
reader.releaseLock();
if (done || !parseResult) throw new APICallError({
message: "SSE stream ended without a data event",
url,
requestBodyValues,
statusCode: response.status
});
if (!parseResult.success) throw new APICallError({
message: "Failed to parse video SSE event",
cause: parseResult.error,
url,
requestBodyValues,
statusCode: response.status
});
const event = parseResult.value;
if (event.type === "error") throw new APICallError({
message: event.message,
statusCode: event.statusCode,
url,
requestBodyValues,
responseHeaders: Object.fromEntries([...response.headers]),
responseBody: JSON.stringify(event),
data: { error: {
message: event.message,
type: event.errorType,
param: event.param
} }
});
return {
value: {
videos: event.videos,
warnings: event.warnings,
providerMetadata: event.providerMetadata
},
responseHeaders: Object.fromEntries([...response.headers])
};
},
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => getErrorMessage$1(data) ?? "unknown error"
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
videos: responseBody.videos,
warnings: responseBody.warnings ?? [],
providerMetadata: responseBody.providerMetadata ?? void 0,
response: {
timestamp: /* @__PURE__ */ new Date(),
modelId: this.modelId,
headers: responseHeaders
}
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders ?? {}));
}
}
async handleWebhookOption({ webhook }) {
const { url, received } = await webhook();
return {
webhookUrl: url,
received
};
}
async doStart(options) {
const { headers, abortSignal, webhookUrl } = options;
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { responseHeaders, value: responseBody } = await postJsonToApi({
url: this.getStartUrl(),
headers: combineHeaders(resolvedHeaders, headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
body: withGatewayRequestTelemetryRedaction({
...this.buildRequestBody(options),
...webhookUrl && { callbackUrl: webhookUrl }
}),
successfulResponseHandler: createJsonResponseHandler(gatewayVideoStartResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => getErrorMessage$1(data) ?? "unknown error"
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
operation: responseBody.operation,
warnings: responseBody.warnings ?? [],
providerMetadata: responseBody.providerMetadata ?? void 0,
response: {
timestamp: /* @__PURE__ */ new Date(),
modelId: this.modelId,
headers: responseHeaders
}
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders ?? {}));
}
}
async doStatus({ operation, abortSignal, headers }) {
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { responseHeaders, value: responseBody } = await postJsonToApi({
url: this.getStatusUrl(),
headers: combineHeaders(resolvedHeaders, headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
body: { operation },
successfulResponseHandler: createJsonResponseHandler(gatewayVideoStatusResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => getErrorMessage$1(data) ?? "unknown error"
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
const response = {
timestamp: /* @__PURE__ */ new Date(),
modelId: this.modelId,
headers: responseHeaders
};
if (responseBody.status === "completed") return {
status: "completed",
videos: responseBody.videos,
warnings: responseBody.warnings ?? [],
providerMetadata: responseBody.providerMetadata ?? void 0,
response
};
if (responseBody.status === "error") return {
status: "error",
error: responseBody.error,
providerMetadata: responseBody.providerMetadata ?? void 0,
response
};
if (responseBody.status === "cancelled") return {
status: "error",
error: "Video generation was cancelled.",
providerMetadata: responseBody.providerMetadata ?? void 0,
response
};
return {
status: "pending",
warnings: responseBody.warnings ?? [],
providerMetadata: responseBody.providerMetadata ?? void 0,
response
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders ?? {}));
}
}
buildRequestBody({ prompt, n, aspectRatio, resolution, duration, fps, seed, generateAudio, image, frameImages, inputReferences, providerOptions }) {
return {
prompt,
n,
...aspectRatio && { aspectRatio },
...resolution && { resolution },
...duration && { duration },
...fps && { fps },
...seed != null && { seed },
...generateAudio !== void 0 && { generateAudio },
...providerOptions && { providerOptions },
...image && { image: maybeEncodeVideoFile(image) },
...frameImages && { frameImages: frameImages.map((frame) => ({
...frame,
image: maybeEncodeVideoFile(frame.image)
})) },
...inputReferences && { inputReferences: inputReferences.map((reference) => maybeEncodeVideoFile(reference)) }
};
}
getUrl() {
return `${this.config.baseURL}/video-model`;
}
getStartUrl() {
return `${this.config.baseURL}/video-model/start`;
}
getStatusUrl() {
return `${this.config.baseURL}/video-model/status`;
}
getModelConfigHeaders() {
return {
"ai-video-model-specification-version": "4",
"ai-model-id": this.modelId
};
}
};
function maybeEncodeVideoFile(file) {
if (file.type === "file" && file.data instanceof Uint8Array) return {
...file,
data: convertUint8ArrayToBase64(file.data)
};
return file;
}
const providerMetadataEntrySchema$2 = () => z.catchall(z.object({ videos: z.optional(z.array(z.unknown())) }), z.unknown());
const gatewayVideoDataSchema = () => z.union([
z.object({
type: z.literal("uploaded"),
mediaType: z.string()
}),
z.object({
type: z.literal("url"),
url: z.string(),
mediaType: z.string()
}),
z.object({
type: z.literal("base64"),
data: z.string(),
mediaType: z.string()
})
]);
const gatewayVideoWarningSchema = () => z.discriminatedUnion("type", [
z.object({
type: z.literal("unsupported"),
feature: z.string(),
details: z.optional(z.string())
}),
z.object({
type: z.literal("compatibility"),
feature: z.string(),
details: z.optional(z.string())
}),
z.object({
type: z.literal("deprecated"),
setting: z.string(),
message: z.string()
}),
z.object({
type: z.literal("other"),
message: z.string()
})
]);
const gatewayVideoEventSchema = lazySchema(() => zodSchema(z.discriminatedUnion("type", [z.object({
type: z.literal("result"),
videos: z.array(gatewayVideoDataSchema()),
warnings: z.optional(z.array(gatewayVideoWarningSchema())),
providerMetadata: z.optional(z.record(z.string(), providerMetadataEntrySchema$2()))
}), z.object({
type: z.literal("error"),
message: z.string(),
errorType: z.string(),
statusCode: z.number(),
param: z.nullable(z.unknown())
})])));
const gatewayVideoStartResponseSchema = lazySchema(() => zodSchema(z.object({
operation: z.unknown(),
warnings: z.nullish(z.array(gatewayVideoWarningSchema())),
providerMetadata: z.nullish(z.record(z.string(), providerMetadataEntrySchema$2()))
})));
const gatewayVideoStatusResponseSchema = lazySchema(() => zodSchema(z.discriminatedUnion("status", [
z.object({
status: z.literal("pending"),
warnings: z.nullish(z.array(gatewayVideoWarningSchema())),
providerMetadata: z.nullish(z.record(z.string(), providerMetadataEntrySchema$2()))
}),
z.object({
status: z.literal("completed"),
videos: z.array(gatewayVideoDataSchema()),
warnings: z.nullish(z.array(gatewayVideoWarningSchema())),
providerMetadata: z.nullish(z.record(z.string(), providerMetadataEntrySchema$2()))
}),
z.object({
status: z.literal("error"),
error: z.string(),
providerMetadata: z.nullish(z.record(z.string(), providerMetadataEntrySchema$2()))
}),
z.object({
status: z.literal("cancelled"),
providerMetadata: z.nullish(z.record(z.string(), providerMetadataEntrySchema$2()))
})
])));
const gatewayDecisionProviderOptionsSchema = lazySchema(() => zodSchema(z.catchall(z.object({ models: z.optional(gatewayModelFallbacksSchema()) }), z.unknown())));
const probabilitySchema = () => z.number().check(z.minimum(0)).check(z.maximum(1));
const questionSchema = () => z.string().check(z.minLength(1)).check(z.maxLength(256));
const directConditionSchema = () => z.union([z.catchall(z.object({
question: z.optional(questionSchema()),
confidenceBelow: probabilitySchema()
}), z.never()), z.catchall(z.object({
question: z.optional(questionSchema()),
probabilityBetween: z.array(probabilitySchema()).check(z.length(2)).check(z.refine(([minimum, maximum]) => minimum <= maximum, { message: "probabilityBetween minimum must be less than or equal to maximum" }))
}), z.never())]);
const groupBeyondMaxDepthSchema = () => z.union([
z.object({ any: z.unknown() }),
z.object({ all: z.unknown() }),
z.object({ atLeast: z.unknown() })
]).check((context) => {
context.issues.push({
input: context.value,
continue: true,
code: "custom",
message: `conditions can be nested at most 5 levels deep`
});
});
const conditionalModelFallbackSchema = () => z.catchall(z.object({
model: z.string().check(z.minLength(1)),
when: conditionSchema(1)
}), z.never());
const gatewayModelFallbacksSchema = () => z.array(z.union([z.string(), conditionalModelFallbackSchema()])).check((context) => {
const conditionalIndexes = context.value.flatMap((entry, index) => typeof entry === "string" ? [] : [index]);
if (conditionalIndexes.length > 1) context.issues.push({
input: context.value,
continue: true,
code: "custom",
message: "models supports at most one conditional decision fallback"
});
if (conditionalIndexes[0] !== void 0 && conditionalIndexes[0] !== 0) context.issues.push({
input: context.value,
continue: true,
code: "custom",
message: "a conditional decision fallback must be the first models entry",
path: [conditionalIndexes[0]]
});
});
function conditionSchema(depth) {
if (depth === 5) return z.union([directConditionSchema(), groupBeyondMaxDepthSchema()]);
const childConditionSchema = conditionSchema(depth + 1);
const conditionListSchema = z.array(childConditionSchema).check(z.minLength(1)).check(z.maxLength(20));
return z.union([
directConditionSchema(),
z.catchall(z.object({ any: conditionListSchema }), z.never()),
z.catchall(z.object({ all: conditionListSchema }), z.never()),
z.catchall(z.object({ atLeast: z.catchall(z.object({
count: z.number().check(z.int()).check(z.minimum(1)),
conditions: conditionListSchema
}), z.never()).check(z.refine(({ count, conditions }) => count <= conditions.length, {
message: "atLeast count cannot exceed the number of conditions",
path: ["count"]
})) }), z.never())
]);
}
//#endregion
//#region src/gateway-warning-schema.ts
const gatewayWarningSchema = () => z.discriminatedUnion("type", [
z.object({
type: z.literal("unsupported"),
feature: z.string(),
details: z.optional(z.string())
}),
z.object({
type: z.literal("compatibility"),
feature: z.string(),
details: z.optional(z.string())
}),
z.object({
type: z.literal("deprecated"),
setting: z.string(),
message: z.string()
}),
z.object({
type: z.literal("other"),
message: z.string()
})
]);
//#endregion
//#region src/to-gateway-state-parts.ts
/** Converts inline file bytes to base64 and rejects file data that cannot be sent. */
function toGatewayStateParts({ state, modelType, allowReferences = false }) {
return state.map((part) => {
if (part.type !== "file") return part;
if (allowReferences && part.data.type === "reference") return part;
if (part.data.type !== "data") throw new UnsupportedFunctionalityError({ functionality: `Gateway ${modelType} file input: ${part.data.type} data` });
const { data } = part.data;
return {
...part,
data: {
type: "data",
data: typeof data === "string" ? data : convertUint8ArrayToBase64(data)
}
};
});
}
//#endregion
//#region src/gateway-decision-model.ts
var GatewayDecisionModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
this.supportedQuestionTypes = [
"choice",
"score",
"boolean"
];
}
get provider() {
return this.config.provider;
}
/** @deprecated Use `doDecide` instead. */
doEvaluate(options) {
return this.doDecide(options);
}
async doDecide({ state, questions, maxOutputTokens, reasoning, headers, abortSignal, providerOptions }) {
const stateParts = toGatewayStateParts({
state,
modelType: "decision"
});
const gatewayOptions = await parseProviderOptions({
provider: "gateway",
providerOptions,
schema: gatewayDecisionProviderOptionsSchema
});
const validatedProviderOptions = gatewayOptions == null ? providerOptions : {
...providerOptions,
gateway: gatewayOptions
};
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
url: this.getUrl(),
headers: combineHeaders(resolvedHeaders, headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
body: withGatewayRequestTelemetryRedaction({
stateParts,
questions,
maxOutputTokens,
reasoning,
...validatedProviderOptions ? { providerOptions: validatedProviderOptions } : {}
}),
successfulResponseHandler: createJsonResponseHandler(gatewayDecisionResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => getErrorMessage(data) ?? "unknown error"
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
answers: responseBody.answers,
...responseBody.rounding ? { rounding: responseBody.rounding } : {},
...responseBody.usage ? { usage: responseBody.usage } : {},
warnings: responseBody.warnings ?? [],
providerMetadata: responseBody.providerMetadata,
response: {
modelId: responseBody.model ?? this.modelId,
headers: responseHeaders,
body: rawValue
}
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders ?? {}));
}
}
getUrl() {
return `${this.config.baseURL}/decision-model`;
}
getModelConfigHeaders() {
return {
"ai-decision-model-specification-version": "4",
"ai-model-id": this.modelId
};
}
};
const gatewayDecisionAnswerSchema = () => z.discriminatedUnion("type", [
z.object({
type: z.literal("choice"),
choice: z.string(),
probabilities: z.optional(z.record(z.string(), z.number()))
}),
z.object({
type: z.literal("score"),
score: z.number(),
probabilities: z.optional(z.record(z.string(), z.number()))
}),
z.object({
type: z.literal("boolean"),
probability: z.number()
}),
z.object({ type: z.literal("refusal") })
]);
const gatewayDecisionResponseSchema = lazySchema(() => zodSchema(z.object({
answers: z.record(z.string(), gatewayDecisionAnswerSchema()),
model: z.optional(z.string()),
rounding: z.optional(z.object({
probabilityDecimals: z.optional(z.number()),
scoreDecimals: z.optional(z.number())
})),
usage: z.optional(z.object({
inputTokens: z.optional(z.number()),
outputTokens: z.optional(z.number())
})),
warnings: z.optional(z.array(gatewayWarningSchema())),
providerMetadata: z.optional(z.record(z.string(), z.record(z.string(), z.unknown())))
})));
//#endregion
//#region src/gateway-extraction-model.ts
var GatewayExtractionModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
this.supportedFieldTypes = [
"text",
"number",
"date",
"time",
"datetime",
"duration",
"list"
];
}
get provider() {
return this.config.provider;
}
async doExtract({ state, fields, referenceDate, maxOutputTokens, reasoning, headers, abortSignal, providerOptions }) {
const stateParts = toGatewayStateParts({
state,
modelType: "extraction",
allowReferences: true
});
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
url: this.getUrl(),
headers: combineHeaders(resolvedHeaders, headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
body: withGatewayRequestTelemetryRedaction({
stateParts,
fields,
referenceDate,
maxOutputTokens,
reasoning,
...providerOptions ? { providerOptions } : {}
}),
successfulResponseHandler: createJsonResponseHandler(gatewayExtractionResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => getErrorMessage(data) ?? "unknown error"
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
answers: omitNulls(responseBody.answers),
...responseBody.usage ? { usage: {
inputTokens: responseBody.usage.inputTokens ?? void 0,
outputTokens: responseBody.usage.outputTokens ?? void 0
} } : {},
warnings: responseBody.warnings ?? [],
providerMetadata: responseBody.providerMetadata ?? void 0,
response: {
modelId: responseBody.model ?? this.modelId,
headers: responseHeaders,
body: rawValue
}
};
} catch (error) {
const unsupportedField = await getUnsupportedField(error);
if (unsupportedField != null) throw new Experimental_ExtractionUnsupportedFieldTypeError({
...unsupportedField,
provider: this.provider,
modelId: this.modelId
});
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders ?? {}));
}
}
getUrl() {
return `${this.config.baseURL}/extraction-model`;
}
getModelConfigHeaders() {
return {
"ai-extraction-model-specification-version": "4",
"ai-model-id": this.modelId
};
}
};
const gatewayExtractionSourceSchema = () => z.discriminatedUnion("type", [z.object({
type: z.literal("text"),
part: z.number(),
start: z.number(),
end: z.number()
}), z.object({
type: z.literal("file"),
part: z.number()
})]);
const stringAnswerSchema = (type) => z.object({
type: z.literal(type),
value: z.nullable(z.string()),
guess: z.nullish(z.string()),
pNull: z.nullish(z.number()),
confidence: z.nullish(z.number()),
source: z.nullish(gatewayExtractionSourceSchema())
});
const numberAnswerSchema = (type) => z.object({
type: z.literal(type),
value: z.nullable(z.number()),
guess: z.nullish(z.number()),
pNull: z.nullish(z.number()),
confidence: z.nullish(z.number()),
source: z.nullish(gatewayExtractionSourceSchema())
});
const gatewayExtractionAnswerSchema = () => z.discriminatedUnion("type", [
stringAnswerSchema("text"),
numberAnswerSchema("number"),
stringAnswerSchema("date"),
stringAnswerSchema("time"),
stringAnswerSchema("datetime"),
numberAnswerSchema("duration"),
z.object({
type: z.literal("list"),
value: z.nullable(z.union([z.array(z.string()), z.array(z.number())])),
pNull: z.nullish(z.number()),
confidence: z.nullish(z.number()),
items: z.nullish(z.array(z.object({
confidence: z.nullish(z.number()),
source: z.nullish(gatewayExtractionSourceSchema())
})))
}),
z.object({ type: z.literal("refusal") })
]);
const gatewayExtractionWarningSchema = () => z.union([gatewayWarningSchema(), z.pipe(z.unknown(), z.transform((warning) => ({
type: "other",
message: `Unknown warning: ${JSON.stringify(warning)}`
})))]);
const gatewayExtractionResponseSchema = lazySchema(() => zodSchema(z.object({
answers: z.record(z.string(), gatewayExtractionAnswerSchema()),
model: z.nullish(z.string()),
usage: z.nullish(z.object({
inputTokens: z.nullish(z.number()),
outputTokens: z.nullish(z.number())
})),
warnings: z.nullish(z.array(gatewayExtractionWarningSchema())),
providerMetadata: z.nullish(z.record(z.string(), z.record(z.string(), z.unknown())))
})));
const gatewayUnsupportedFieldErrorSchema = lazySchema(() => zodSchema(z.object({ error: z.object({
type: z.literal("invalid_request_error"),
param: z.object({
name: z.literal("AI_ExtractionUnsupportedFieldTypeError"),
fieldId: z.string(),
fieldType: z.string()
})
}) })));
/** Reads the field from the gateway's unsupported field type response. */
async function getUnsupportedField(error) {
if (!APICallError.isInstance(error)) return void 0;
const result = await safeValidateTypes({
value: extractApiCallResponse(error),
schema: gatewayUnsupportedFieldErrorSchema
});
if (!result.success) return void 0;
const { fieldId, fieldType } = result.value.error.param;
return {
fieldId,
fieldType
};
}
/** Drops `null` optional fields, which the specification leaves out. */
function omitNulls(value) {
if (Array.isArray(value)) return value.map(omitNulls);
if (value == null || typeof value !== "object") return value;
return Object.fromEntries(Object.entries(value).filter(([key, entry]) => entry !== null || key === "value").map(([key, entry]) => [key, omitNulls(entry)]));
}
//#endregion
//#region src/gateway-reranking-model.ts
var GatewayRerankingModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
}
get provider() {
return this.config.provider;
}
async doRerank({ documents, query, topN, headers, abortSignal, providerOptions }) {
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
url: this.getUrl(),
headers: combineHeaders(resolvedHeaders, headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
body: withGatewayRequestTelemetryRedaction({
documents,
query,
...topN != null ? { topN } : {},
...providerOptions ? { providerOptions } : {}
}),
successfulResponseHandler: createJsonResponseHandler(gatewayRerankingResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => getErrorMessage(data) ?? "unknown error"
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
ranking: responseBody.ranking,
providerMetadata: responseBody.providerMetadata,
response: {
headers: responseHeaders,
body: rawValue
},
warnings: responseBody.warnings ?? []
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders ?? {}));
}
}
getUrl() {
return `${this.config.baseURL}/reranking-model`;
}
getModelConfigHeaders() {
return {
"ai-reranking-model-specification-version": "4",
"ai-model-id": this.modelId
};
}
};
const gatewayRerankingWarningSchema = () => z.discriminatedUnion("type", [
z.object({
type: z.literal("unsupported"),
feature: z.string(),
details: z.optional(z.string())
}),
z.object({
type: z.literal("compatibility"),
feature: z.string(),
details: z.optional(z.string())
}),
z.object({
type: z.literal("deprecated"),
setting: z.string(),
message: z.string()
}),
z.object({
type: z.literal("other"),
message: z.string()
})
]);
const gatewayRerankingResponseSchema = lazySchema(() => zodSchema(z.object({
ranking: z.array(z.object({
index: z.number(),
relevanceScore: z.number()
})),
warnings: z.optional(z.array(gatewayRerankingWarningSchema())),
providerMetadata: z.optional(z.record(z.string(), z.record(z.string(), z.unknown())))
})));
//#endregion
//#region src/gateway-stream-errors.ts
/**
* `asGatewayError` is async while the WebSocket event handlers are
* synchronous, hence this helper.
*/
async function errorControllerWithGatewayError(controller, error, authMethod) {
controller.error(await asGatewayError(error, authMethod).catch((error) => error));
}
/**
* Extract a human-readable message from an `error` stream part's payload for
* the terminal close error.
*/
function getServerErrorMessage(error) {
if (error != null && typeof error === "object" && "message" in error && typeof error.message === "string") return error.message;
return getErrorMessage$1(error);
}
/** Canonical status codes for server error-part types (no HTTP status exists on the WebSocket). */
const SERVER_ERROR_STATUS_CODES = {
authentication_error: 401,
failed_dependency: 424,
forbidden: 403,
internal_server_error: 500,
invalid_request_error: 400,
model_not_found: 404,
rate_limit_exceeded: 429
};
/**
* Maps a server error-part payload (`{ message, type }`) to the public
* Gateway error class for its type; unknown shapes keep the generic message.
*/
async function createErrorFromServerErrorPart(error, authMethod, streamLabel = "transcription") {
if (typeof error === "object" && error != null && "message" in error && typeof error.message === "string" && "type" in error && typeof error.type === "string" && error.type in SERVER_ERROR_STATUS_CODES) return createGatewayErrorFromResponse({
response: { error: {
message: error.message,
type: error.type
} },
statusCode: SERVER_ERROR_STATUS_CODES[error.type],
authMethod
});
return /* @__PURE__ */ new Error(`AI Gateway ${streamLabel} stream failed: ${getServerErrorMessage(error)}`);
}
//#endregion
//#region src/gateway-transcription-model.ts
var GatewayTranscriptionModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
}
get provider() {
return this.config.provider;
}
async doGenerate({ audio, mediaType, providerOptions, timestampGranularities, headers, abortSignal }) {
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
url: this.getUrl(),
headers: combineHeaders(resolvedHeaders, headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
body: withGatewayRequestTelemetryRedaction({
audio: audio instanceof Uint8Array ? convertUint8ArrayToBase64(audio) : audio,
mediaType,
...providerOptions && { providerOptions }
}),
successfulResponseHandler: createJsonResponseHandler(gatewayTranscriptionResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => getErrorMessage$1(data) ?? "unknown error"
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
const warnings = [...responseBody.warnings ?? []];
if (timestampGranularities?.length) warnings.push({
type: "unsupported",
feature: "timestampGranularities",
details: "The AI Gateway adapter does not forward the shared timestampGranularities option."
});
if (isXaiTranscriptionModel(this.modelId) && requestsXaiDiarization(providerOptions) && !containsSpeaker(rawValue)) warnings.push({
type: "unsupported",
feature: "providerOptions.xai.diarize",
details: "AI Gateway does not currently expose xAI speaker diarization metadata."
});
return {
text: responseBody.text,
segments: responseBody.segments ?? [],
...responseBody.words != null && { words: responseBody.words },
language: responseBody.language ?? void 0,
durationInSeconds: responseBody.durationInSeconds ?? void 0,
warnings,
...responseBody.usage != null && { usage: responseBody.usage },
providerMetadata: responseBody.providerMetadata,
response: {
timestamp: /* @__PURE__ */ new Date(),
modelId: this.modelId,
headers: responseHeaders,
body: rawValue
}
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders ?? {}));
}
}
async doStream(options) {
const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
const headers = combineHeaders(await resolve(this.config.headers ?? {}), options.headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders));
const authMethod = await parseAuthMethod(headers);
const startFrame = withGatewayRequestTelemetryRedaction({
type: EXPERIMENTAL_TRANSCRIPTION_STREAM_START_FRAME_TYPE,
inputAudioFormat: options.inputAudioFormat,
...options.providerOptions != null && { providerOptions: options.providerOptions },
...options.includeRawChunks != null && { includeRawChunks: options.includeRawChunks }
});
return {
stream: createGatewayTranscriptionStream({
webSocket: this.config.webSocket,
url: toGatewayTranscriptionUrl(this.config.baseURL, this.modelId),
protocols: getProtocolsFromHeaders(headers),
headers,
startFrame,
audio: options.audio,
abortSignal: options.abortSignal,
authMethod
}),
request: { body: startFrame },
response: {
timestamp: currentDate,
modelId: this.modelId
}
};
}
getUrl() {
return `${this.config.baseURL}/transcription-model`;
}
getModelConfigHeaders() {
return {
"ai-transcription-model-specification-version": "4",
"ai-model-id": this.modelId
};
}
};
function isXaiTranscriptionModel(modelId) {
return modelId.startsWith("spacexai/") || modelId.startsWith("xai/");
}
function requestsXaiDiarization(providerOptions) {
return providerOptions?.xai?.diarize === true || providerOptions?.spacexai?.diarize === true;
}
function containsSpeaker(value) {
if (Array.isArray(value)) return value.some(containsSpeaker);
if (value == null || typeof value !== "object") return false;
return Object.entries(value).some(([key, nestedValue]) => key === "speaker" && nestedValue != null || containsSpeaker(nestedValue));
}
/**
* Gateway streaming transcription WebSocket URL: HTTP(S) base upgraded to
* WS(S), model id in `?ai-model-id=` (browser `WebSocket` cannot set headers;
* slash-safe for qualified ids like `openai/gpt-realtime-whisper`).
*/
function toGatewayTranscriptionUrl(baseURL, modelId) {
const url = new URL(`${baseURL.replace(/^http/, "ws")}/transcription-model`);
url.searchParams.set("ai-model-id", modelId);
return url.toString();
}
/**
* Auth-carrying subprotocols from the resolved request headers (bearer token
* + optional team scope). Native `WebSocket` cannot send headers, so auth
* rides the `Sec-WebSocket-Protocol` handshake. Header lookups are
* case-insensitive because `combineHeaders` does not normalize casing and
* callers can pass arbitrary casing via the `headers` option.
*/
function getProtocolsFromHeaders(headers, { marker = GATEWAY_TRANSCRIPTION_SUBPROTOCOL, getProtocols = getGatewayTranscriptionProtocols } = {}) {
const normalizedHeaders = normalizeHeaders(headers);
const authorization = normalizedHeaders.authorization;
const token = authorization?.startsWith("Bearer ") ? authorization.slice(7) : void 0;
return token == null ? [marker] : getProtocols(token, { teamIdOrSlug: normalizedHeaders[VERCEL_AI_GATEWAY_TEAM_HEADER] });
}
/** Audio frames stay under server frame-size limits (envelope rule 7). */
const MAX_AUDIO_FRAME_BYTES = 65536;
function createGatewayTranscriptionStream({ webSocket, url, protocols, headers, startFrame, audio, abortSignal, authMethod }) {
let finished = false;
let cleanup = () => {};
return new ReadableStream({
start: (controller) => {
let audioReader;
let hasServerErrorPart = false;
let lastServerError;
let audioStopped = false;
let connection;
cleanup = (closeCode) => {
if (audioReader != null) audioReader.cancel().catch(() => {});
else audio.cancel().catch(() => {});
connection?.close(closeCode);
};
const stopAudio = () => {
audioStopped = true;
if (audioReader != null) {
audioReader.cancel().catch(() => {});
audioReader = void 0;
} else audio.cancel().catch(() => {});
};
const finishWithError = (error) => {
if (finished) return;
finished = true;
cleanup();
errorControllerWithGatewayError(controller, error, authMethod);
};
const sendAudio = async (socket) => {
const reader = audio.getReader();
audioReader = reader;
try {
while (true) {
const { done, value } = await reader.read();
if (done || finished) break;
const bytes = typeof value === "string" ? convertBase64ToUint8Array(value) : value;
for (let offset = 0; offset < bytes.length; offset += MAX_AUDIO_FRAME_BYTES) {
if (finished) break;
socket.send(bytes.subarray(offset, offset + MAX_AUDIO_FRAME_BYTES));
await waitForWebSocketBufferDrain(socket);
}
}
} finally {
reader.releaseLock();
if (audioReader === reader) audioReader = void 0;
}
if (!finished && !audioStopped) socket.send(JSON.stringify({ type: EXPERIMENTAL_TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE }));
};
connection = connectToWebSocket({
url,
protocols,
headers,
webSocket,
abortSignal,
onAbort: (reason) => {
if (finished) return;
finished = true;
cleanup();
controller.error(reason);
},
onProcessingError: finishWithError,
onOpen: (socket) => {
socket.send(JSON.stringify(startFrame));
sendAudio(socket).catch(finishWithError);
},
onMessageText: (text) => {
if (finished) return;
const part = experimental_parseTranscriptionStreamPart(text);
if (part == null) return;
if (part.type === "finish") {
finished = true;
controller.enqueue(part);
controller.close();
cleanup(1e3);
return;
}
if (part.type === "error") {
hasServerErrorPart = true;
lastServerError = part.error;
stopAudio();
}
controller.enqueue(part);
},
onSocketError: () => {
finishWithError(/* @__PURE__ */ new Error("Connection error on AI Gateway transcription stream"));
},
onClose: () => {
if (hasServerErrorPart) {
if (finished) return;
createErrorFromServerErrorPart(lastServerError, authMethod).then(finishWithError);
return;
}
finishWithError(/* @__PURE__ */ new Error("AI Gateway transcription stream closed before a finish part was received"));
}
});
},
cancel: () => {
if (finished) return;
finished = true;
cleanup();
}
});
}
const providerMetadataEntrySchema$1 = () => z.catchall(z.object({}), z.unknown());
const gatewayTranscriptionWarningSchema = () => z.discriminatedUnion("type", [
z.object({
type: z.literal("unsupported"),
feature: z.string(),
details: z.optional(z.string())
}),
z.object({
type: z.literal("compatibility"),
feature: z.string(),
details: z.optional(z.string())
}),
z.object({
type: z.literal("deprecated"),
setting: z.string(),
message: z.string()
}),
z.object({
type: z.literal("other"),
message: z.string()
})
]);
const gatewayTranscriptionResponseSchema = lazySchema(() => zodSchema(z.object({
text: z.string(),
segments: z.optional(z.array(z.object({
text: z.string(),
startSecond: z.number(),
endSecond: z.number()
}))),
words: z.nullish(z.array(z.object({
text: z.string(),
startSecond: z.number(),
endSecond: z.number()
}))),
language: z.nullish(z.string()),
durationInSeconds: z.nullish(z.number()),
warnings: z.optional(z.array(gatewayTranscriptionWarningSchema())),
usage: z.optional(z.record(z.string(), z.json())),
providerMetadata: z.optional(z.record(z.string(), providerMetadataEntrySchema$1()))
})));
//#endregion
//#region src/gateway-speech-model.ts
var GatewaySpeechModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
}
get provider() {
return this.config.provider;
}
async doGenerate({ text, voice, outputFormat, instructions, speed, language, providerOptions, headers, abortSignal }) {
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
url: this.getUrl(),
headers: combineHeaders(resolvedHeaders, headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
body: withGatewayRequestTelemetryRedaction({
text,
...voice && { voice },
...outputFormat && { outputFormat },
...instructions && { instructions },
...speed != null && { speed },
...language && { language },
...providerOptions && { providerOptions }
}),
successfulResponseHandler: createJsonResponseHandler(gatewaySpeechResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => getErrorMessage(data) ?? "unknown error"
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
audio: responseBody.audio,
warnings: responseBody.warnings ?? [],
...responseBody.usage != null && { usage: responseBody.usage },
providerMetadata: responseBody.providerMetadata,
response: {
timestamp: /* @__PURE__ */ new Date(),
modelId: this.modelId,
headers: responseHeaders,
body: rawValue
}
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders ?? {}));
}
}
async doStream(options) {
const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
const headers = combineHeaders(await resolve(this.config.headers ?? {}), options.headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders));
const authMethod = await parseAuthMethod(headers);
const startFrame = withGatewayRequestTelemetryRedaction({
type: EXPERIMENTAL_SPEECH_STREAM_START_FRAME_TYPE,
...options.voice != null && { voice: options.voice },
...options.outputFormat != null && { outputFormat: options.outputFormat },
...options.instructions != null && { instructions: options.instructions },
...options.speed != null && { speed: options.speed },
...options.language != null && { language: options.language },
...options.providerOptions != null && { providerOptions: options.providerOptions },
...options.includeRawChunks != null && { includeRawChunks: options.includeRawChunks }
});
return {
stream: createGatewaySpeechStream({
webSocket: this.config.webSocket,
url: toGatewaySpeechUrl(this.config.baseURL, this.modelId),
protocols: getProtocolsFromHeaders(headers, {
marker: GATEWAY_SPEECH_SUBPROTOCOL,
getProtocols: getGatewaySpeechProtocols
}),
headers,
startFrame,
text: options.text,
abortSignal: options.abortSignal,
authMethod
}),
request: { body: startFrame },
response: {
timestamp: currentDate,
modelId: this.modelId
}
};
}
getUrl() {
return `${this.config.baseURL}/speech-model`;
}
getModelConfigHeaders() {
return {
"ai-speech-model-specification-version": "4",
"ai-model-id": this.modelId
};
}
};
/**
* Gateway streaming speech WebSocket URL: HTTP(S) base upgraded to WS(S),
* model id in `?ai-model-id=` (browser `WebSocket` cannot set headers).
*/
function toGatewaySpeechUrl(baseURL, modelId) {
const url = new URL(`${baseURL.replace(/^http/, "ws")}/speech-model`);
url.searchParams.set("ai-model-id", modelId);
return url.toString();
}
/**
* Keeps text-delta frames under 64 KiB (envelope rule 7) even when JSON
* escapes every code unit as `\uXXXX`.
*/
const MAX_TEXT_DELTA_CODE_UNITS = 8192;
/**
* Splits a long text delta into pieces of at most `MAX_TEXT_DELTA_CODE_UNITS`
* UTF-16 code units without separating a surrogate pair.
*/
function splitTextDelta(delta) {
const pieces = [];
let offset = 0;
while (offset < delta.length) {
let end = Math.min(offset + MAX_TEXT_DELTA_CODE_UNITS, delta.length);
const lastCodeUnit = delta.charCodeAt(end - 1);
if (end < delta.length && lastCodeUnit >= 55296 && lastCodeUnit <= 56319) end--;
pieces.push(delta.slice(offset, end));
offset = end;
}
return pieces;
}
function createGatewaySpeechStream({ webSocket, url, protocols, headers, startFrame, text, abortSignal, authMethod }) {
let finished = false;
let cleanup = () => {};
return new ReadableStream({
start: (controller) => {
let textReader;
let hasServerErrorPart = false;
let lastServerError;
let textStopped = false;
let connection;
const cancelText = () => {
if (textReader != null) {
textReader.cancel().catch(() => {});
textReader = void 0;
} else text.cancel().catch(() => {});
};
cleanup = (closeCode) => {
cancelText();
connection?.close(closeCode);
};
const finishWithError = (error) => {
if (finished) return;
finished = true;
cleanup();
errorControllerWithGatewayError(controller, error, authMethod);
};
const sendText = async (socket) => {
const reader = text.getReader();
textReader = reader;
try {
while (true) {
const { done, value } = await reader.read();
if (done || finished || textStopped) break;
let first = true;
const pieces = splitTextDelta(value.text);
if (pieces.length === 0 && (value.voice != null || value.providerOptions != null)) pieces.push("");
for (const delta of pieces) {
if (finished || textStopped) break;
const frame = {
type: EXPERIMENTAL_SPEECH_STREAM_TEXT_DELTA_FRAME_TYPE,
delta,
...value.voice != null && { voice: value.voice },
...first && value.providerOptions != null && { providerOptions: value.providerOptions }
};
first = false;
socket.send(JSON.stringify(frame));
await waitForWebSocketBufferDrain(socket);
}
}
} finally {
reader.releaseLock();
if (textReader === reader) textReader = void 0;
}
if (!finished && !textStopped) socket.send(JSON.stringify({ type: EXPERIMENTAL_SPEECH_STREAM_TEXT_DONE_FRAME_TYPE }));
};
connection = connectToWebSocket({
url,
protocols,
headers,
webSocket,
abortSignal,
onAbort: (reason) => {
if (finished) return;
finished = true;
cleanup();
controller.error(reason);
},
onProcessingError: finishWithError,
onOpen: (socket) => {
socket.send(JSON.stringify(startFrame));
sendText(socket).catch(finishWithError);
},
onMessageText: async (messageText) => {
if (finished) return;
const part = experimental_parseSpeechStreamPart(messageText);
if (part == null) return;
if (part.type === "finish") {
finished = true;
controller.enqueue(part);
controller.close();
cleanup(1e3);
return;
}
if (part.type === "error") {
hasServerErrorPart = true;
lastServerError = part.error;
textStopped = true;
cancelText();
part.error = await createErrorFromServerErrorPart(part.error, authMethod, "speech");
if (finished) return;
}
controller.enqueue(part);
},
onSocketError: () => {
finishWithError(/* @__PURE__ */ new Error("Connection error on AI Gateway speech stream"));
},
onClose: ({ code, reason }) => {
if (hasServerErrorPart) {
if (finished) return;
createErrorFromServerErrorPart(lastServerError, authMethod, "speech").then(finishWithError);
return;
}
finishWithError(/* @__PURE__ */ new Error("AI Gateway speech stream closed before a finish part was received" + (code != null ? ` (code ${code}${reason ? `: ${reason}` : ""})` : "") + "."));
}
});
},
cancel: () => {
if (finished) return;
finished = true;
cleanup();
}
});
}
const providerMetadataEntrySchema = () => z.catchall(z.object({}), z.unknown());
const gatewaySpeechWarningSchema = () => z.discriminatedUnion("type", [
z.object({
type: z.literal("unsupported"),
feature: z.string(),
details: z.optional(z.string())
}),
z.object({
type: z.literal("compatibility"),
feature: z.string(),
details: z.optional(z.string())
}),
z.object({
type: z.literal("deprecated"),
setting: z.string(),
message: z.string()
}),
z.object({
type: z.literal("other"),
message: z.string()
})
]);
const gatewaySpeechResponseSchema = lazySchema(() => zodSchema(z.object({
audio: z.string(),
warnings: z.optional(z.array(gatewaySpeechWarningSchema())),
usage: z.optional(z.record(z.string(), z.json())),
providerMetadata: z.optional(z.record(z.string(), providerMetadataEntrySchema()))
})));
//#endregion
//#region src/gateway-realtime-model-live.ts
const supportedOpenAILiveOptions = /* @__PURE__ */ new Set([
"delegation",
"input",
"store",
"voice"
]);
const contextChannels = /* @__PURE__ */ new Set([
"commentary",
"instructions",
"thinking"
]);
const supportedSessionSettings = /* @__PURE__ */ new Set([
"instructions",
"voice",
"inputAudioFormat",
"outputAudioFormat",
"providerOptions"
]);
/**
* Live model backed by the AI Gateway.
*
* Live is a continuous conversation API: one `session-start` opens the
* session, PCM audio streams in both directions, and `session-close` ends it
* with final usage. The client speaks the Gateway's normalized Live protocol
* on `/v4/ai/live-model`, and the Gateway runs the provider mapping
* server-side, so server events arrive already normalized.
*/
var GatewayRealtimeModelLive = class {
constructor(modelId, config) {
this.specificationVersion = "v4";
this.capabilities = {
conversation: "continuous",
transports: ["websocket"],
connections: ["client-secret-websocket", "server-websocket"],
startup: "session-start",
finalization: "session-close"
};
this.modelId = modelId;
this.provider = config.provider;
this.config = config;
}
/**
* Mints a short-lived client secret bound to this Live model. The browser
* opens the Live WebSocket with it through the `ai-gateway-auth.<token>`
* subprotocol; the session configuration is sent later in `session-start`.
*/
async doCreateClientSecret(options) {
const secret = await this.config.createClientSecret({
modelId: this.modelId,
routeKind: "live",
...options?.expiresAfterSeconds != null && { expiresAfterSeconds: options.expiresAfterSeconds }
});
return {
token: secret.token,
url: toGatewayLiveUrl(this.config.baseURL, this.modelId),
...secret.expiresAt != null && { expiresAt: secret.expiresAt }
};
}
getWebSocketConfig(options) {
return {
url: options.url,
protocols: getGatewayRealtimeProtocols(options.token, { teamIdOrSlug: this.config.teamIdOrSlug })
};
}
async getServerWebSocketConfig(options) {
this.assertConversationIntent(options);
return {
url: toGatewayLiveUrl(this.config.baseURL, this.modelId),
headers: removeUndefinedEntries(await this.config.getHeaders())
};
}
parseServerEvent(raw) {
if (raw == null || typeof raw !== "object" || Array.isArray(raw) || typeof raw.type !== "string") return {
type: "error",
code: "invalid_server_event",
message: "Invalid AI Gateway Live server event.",
raw
};
if (raw.type === "error" && !("raw" in raw)) return {
...raw,
raw
};
return raw;
}
serializeClientEvent(event, options) {
this.assertConversationIntent(options);
const eventId = "eventId" in event && event.eventId != null ? { eventId: event.eventId } : {};
switch (event.type) {
case "session-start": return {
type: "session-start",
modelId: this.modelId,
config: this.buildSessionConfig(event.config),
...eventId
};
case "session-close":
case "input-audio-mute":
case "input-audio-unmute": return {
type: event.type,
...eventId
};
case "input-audio-append": return {
type: "input-audio-append",
audio: event.audio,
...eventId
};
case "context-append":
validateContextOptions(event.providerOptions);
return {
type: "context-append",
content: event.content,
delegationId: event.delegationId,
...event.providerOptions != null && { providerOptions: event.providerOptions },
...eventId
};
default: throw new UnsupportedFunctionalityError({ functionality: `AI Gateway Live client event: ${event.type}` });
}
}
buildSessionConfig(config, options) {
this.assertConversationIntent(options);
for (const [key, value] of Object.entries(config)) if (value != null && !supportedSessionSettings.has(key)) throw new UnsupportedFunctionalityError({ functionality: `AI Gateway Live session setting: ${key}` });
validateSessionProviderOptions(config.providerOptions);
const input = config.inputAudioFormat;
const output = config.outputAudioFormat;
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` });
if (input != null && output != null && (input.type !== output.type || input.rate !== output.rate)) throw new InvalidArgumentError({
argument: "outputAudioFormat",
message: "AI Gateway Live requires the same input and output audio format."
});
return removeUndefinedEntries(config);
}
assertConversationIntent(options) {
if (options?.intent != null && options.intent !== "conversation") throw new Error(`AI Gateway Live does not support the '${options.intent}' session intent.`);
}
};
function isRecord(value) {
return value != null && typeof value === "object" && !Array.isArray(value);
}
/** Gateway options stay service-owned; OpenAI Live options are WebSocket-only. */
function validateSessionProviderOptions(providerOptions) {
if (providerOptions == null) return;
if (!isRecord(providerOptions)) throw new InvalidArgumentError({
argument: "providerOptions",
message: "providerOptions must be an object."
});
for (const [namespace, options] of Object.entries(providerOptions)) {
if (options === void 0) continue;
if (namespace !== "gateway" && namespace !== "openai") throw new UnsupportedFunctionalityError({ functionality: `AI Gateway Live provider options namespace: ${namespace}` });
if (!isRecord(options)) throw new InvalidArgumentError({
argument: `providerOptions.${namespace}`,
message: `providerOptions.${namespace} must be an object.`
});
}
const openai = providerOptions.openai;
if (!isRecord(openai)) return;
for (const [key, value] of Object.entries(openai)) {
if (value === void 0) continue;
if (!supportedOpenAILiveOptions.has(key)) throw new UnsupportedFunctionalityError({ functionality: `AI Gateway Live OpenAI option: ${key}` });
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" });
if (!isValidOpenAILiveOption(key, value)) throw new InvalidArgumentError({
argument: `providerOptions.openai.${key}`,
message: openaiLiveOptionMessages[key]
});
}
}
const openaiLiveOptionMessages = {
delegation: "delegation must be { type: \"client\" } or null.",
input: "input must be at most 128 messages, each { type: \"message\", role, content: [{ type, text }] }.",
store: "store must be a boolean.",
voice: "voice must be { id: string } with a nonempty id."
};
function isValidOpenAILiveOption(key, value) {
switch (key) {
case "delegation": return true;
case "store": return typeof value === "boolean";
case "voice": return hasExactKeys(value, ["id"]) && typeof value.id === "string" && value.id.length > 0;
case "input": return Array.isArray(value) && value.length <= 128 && Array.from(value).every(isInputMessage);
default: return false;
}
}
function isInputMessage(message) {
if (!hasExactKeys(message, [
"type",
"role",
"content"
]) || message.type !== "message" || !Array.isArray(message.content) || message.content.length !== 1) return false;
const [part] = message.content;
if (!hasExactKeys(part, ["type", "text"]) || typeof part.text !== "string") return false;
return message.role === "assistant" ? part.type === "text" || part.type === "output_text" : (message.role === "developer" || message.role === "user") && part.type === "input_text";
}
function hasExactKeys(value, keys) {
if (!isRecord(value)) return false;
const present = Object.keys(value).filter((key) => value[key] !== void 0);
return present.length === keys.length && keys.every((key) => present.includes(key));
}
function validateContextOptions(providerOptions) {
if (providerOptions == null) return;
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" });
}
function isSupportedAudioFormat(format) {
return format.type === "audio/pcm" ? format.rate === 16e3 || format.rate === 24e3 : (format.type === "audio/pcma" || format.type === "audio/pcmu") && format.rate === 8e3;
}
/** Live WebSocket URL; the model id rides `?ai-model-id=` like the realtime route. */
function toGatewayLiveUrl(baseURL, modelId) {
const url = new URL(`${baseURL.replace(/^http/, "ws")}/live-model`);
url.searchParams.set("ai-model-id", modelId);
return url.toString();
}
//#endregion
//#region src/gateway-realtime-model.ts
/**
* Realtime model backed by the AI Gateway.
*
* The Gateway normalizes realtime exactly like it normalizes every other
* modality: the client speaks the normalized AI SDK realtime protocol and the
* Gateway translates to and from the upstream provider server-side. This model
* is therefore a thin identity codec over that normalized protocol — only the
* connection and authentication are Gateway-specific.
*/
var GatewayRealtimeModel = class {
constructor(modelId, config) {
this.specificationVersion = "v4";
this.capabilities = {
conversation: "turn-based",
transports: ["websocket"],
connections: ["client-secret-websocket", "server-websocket"]
};
this.modelId = modelId;
this.provider = config.provider;
this.config = config;
}
/**
* Mints a single-use, short-lived client secret (`vcst_`) the browser uses to
* open the realtime WebSocket without ever holding the long-lived Gateway
* credential. The customer's server calls this (via
* `gateway.experimental_realtime.getToken`) and hands the returned token to
* the browser, which connects with it through the `ai-gateway-auth.<token>`
* subprotocol. `expiresAfterSeconds` is forwarded to the mint endpoint;
* `sessionConfig` is intentionally unused here — it is applied later via the
* normalized `session-update` event.
*/
async doCreateClientSecret(options) {
const secret = await this.config.createClientSecret({
modelId: this.modelId,
...options?.expiresAfterSeconds != null && { expiresAfterSeconds: options.expiresAfterSeconds }
});
return {
token: secret.token,
url: toGatewayRealtimeUrl(this.config.baseURL, this.modelId),
...secret.expiresAt != null && { expiresAt: secret.expiresAt }
};
}
getWebSocketConfig(options) {
return {
url: options.url,
protocols: getGatewayRealtimeProtocols(options.token, { teamIdOrSlug: this.config.teamIdOrSlug })
};
}
async getServerWebSocketConfig(options) {
this.assertConversationIntent(options);
return {
url: toGatewayRealtimeUrl(this.config.baseURL, this.modelId),
headers: removeUndefinedEntries(await this.config.getHeaders())
};
}
assertConversationIntent(options) {
if (options?.intent != null && options.intent !== "conversation") throw new Error(`AI Gateway realtime does not support the '${options.intent}' session intent on the normalized realtime route.`);
}
parseServerEvent(raw) {
return raw;
}
serializeClientEvent(event, options) {
this.assertConversationIntent(options);
return event;
}
buildSessionConfig(config, options) {
this.assertConversationIntent(options);
return config;
}
};
/**
* Build the Gateway realtime WebSocket URL. The HTTP(S) base URL is upgraded to
* WS(S) and the model id rides the `?ai-model-id=` query — the WS transport of
* the `ai-model-id` header the HTTP routes use, since a browser `WebSocket`
* cannot set headers. The model id is passed through verbatim; the Gateway owns
* resolution (including the bare → `openai/` qualification), exactly like the
* non-realtime routes. The query is slash-safe for qualified ids such as
* `openai/gpt-realtime-2`.
*/
function toGatewayRealtimeUrl(baseURL, modelId) {
const url = new URL(`${baseURL.replace(/^http/, "ws")}/realtime-model`);
url.searchParams.set("ai-model-id", modelId);
return url.toString();
}
//#endregion
//#region src/gateway-realtime-model-settings.ts
/**
* Realtime model IDs that use the continuous Live API by default. Other IDs use
* the realtime API unless `{ api: 'live' }` is passed.
*/
const gatewayLiveModelIds = ["openai/gpt-live-1", "openai/gpt-live-1.1"];
//#endregion
//#region src/tool/browserbase-fetch.ts
const jsonObjectSchema = () => z.record(z.string(), z.unknown());
const browserbaseFetchInputSchema = lazySchema(() => zodSchema(z.object({
url: z.describe(z.url(), "URL of the page to fetch."),
allow_redirects: z.describe(z.optional(z.boolean()), "Whether to follow HTTP redirects (default: false)."),
allow_insecure_ssl: z.describe(z.optional(z.boolean()), "Whether to bypass TLS certificate verification (default: false). Only use for trusted hosts."),
proxies: z.describe(z.optional(z.boolean()), "Whether to route the request through Browserbase proxies (default: false)."),
format: z.describe(z.optional(z.enum([
"raw",
"json",
"markdown"
])), "Output format. raw returns the response body unchanged, markdown returns page content as Markdown, and json returns structured content using schema."),
schema: z.describe(z.optional(jsonObjectSchema()), "JSON Schema for structured extraction. Only use with format set to json.")
})));
const browserbaseFetchOutputSchema = lazySchema(() => zodSchema(z.union([z.object({
id: z.string(),
content: z.union([z.string(), jsonObjectSchema()]),
contentType: z.string(),
encoding: z.string(),
headers: z.record(z.string(), z.string()),
statusCode: z.number()
}), z.object({
error: z.enum([
"api_error",
"configuration_error",
"execution_error",
"invalid_input",
"rate_limit",
"timeout",
"unknown"
]),
statusCode: z.optional(z.number()),
message: z.string()
})])));
const browserbaseFetchToolFactory = createProviderExecutedToolFactory({
id: "gateway.browserbase_fetch",
inputSchema: browserbaseFetchInputSchema,
outputSchema: browserbaseFetchOutputSchema
});
const browserbaseFetch = (config = {}) => browserbaseFetchToolFactory(config);
//#endregion
//#region src/tool/browserbase-search.ts
const browserbaseSearchInputSchema = lazySchema(() => zodSchema(z.object({
query: z.describe(z.string().check(z.minLength(1)).check(z.maxLength(200)), "Web search query. Must be between 1 and 200 characters."),
num_results: z.describe(z.optional(z.number().check(z.int()).check(z.minimum(1)).check(z.maximum(25))), "Maximum number of results to return (1-25, default: 10).")
})));
const browserbaseSearchOutputSchema = lazySchema(() => zodSchema(z.union([z.object({
query: z.string(),
requestId: z.string(),
results: z.array(z.object({
id: z.string(),
title: z.string(),
url: z.string(),
author: z.optional(z.string()),
favicon: z.optional(z.string()),
image: z.optional(z.string()),
publishedDate: z.optional(z.string())
}))
}), z.object({
error: z.enum([
"api_error",
"configuration_error",
"execution_error",
"invalid_input",
"rate_limit",
"timeout",
"unknown"
]),
statusCode: z.optional(z.number()),
message: z.string()
})])));
const browserbaseSearchToolFactory = createProviderExecutedToolFactory({
id: "gateway.browserbase_search",
inputSchema: browserbaseSearchInputSchema,
outputSchema: browserbaseSearchOutputSchema
});
const browserbaseSearch = (config = {}) => browserbaseSearchToolFactory(config);
//#endregion
//#region src/tool/gateway-tool-error.ts
const gatewayToolErrorSchema = () => z.catchall(z.object({
error: z.enum([
"api_error",
"configuration_error",
"execution_error",
"gateway_rate_limit",
"invalid_input",
"rate_limit",
"timeout",
"unknown",
"unknown_tool"
]),
message: z.string(),
statusCode: z.optional(z.number()),
retryAfter: z.optional(z.string()),
statusText: z.optional(z.string())
}), z.unknown());
//#endregion
//#region src/tool/deepseek-fetch.ts
const deepseekFetchInputSchema = lazySchema(() => zodSchema(z.object({ url: z.describe(z.string(), "URL to fetch, at most 8192 characters; HTTP(S) only, without a username or password.") })));
const deepseekFetchOutputSchema = lazySchema(() => zodSchema(z.union([z.catchall(z.object({
title: z.nullish(z.string()),
content: z.string()
}), z.unknown()), gatewayToolErrorSchema()])));
const deepseekFetchToolFactory = createProviderExecutedToolFactory({
id: "gateway.deepseek_fetch",
inputSchema: deepseekFetchInputSchema,
outputSchema: deepseekFetchOutputSchema
});
const deepseekFetch = (config = {}) => deepseekFetchToolFactory(config);
//#endregion
//#region src/tool/deepseek-search.ts
const deepseekSearchInputSchema = lazySchema(() => zodSchema(z.object({
query: z.describe(z.string(), "Web search query, 1 to 128 Unicode characters. Supports site:, -site:, lang:, after:, before:, and quoted phrases."),
count: z.describe(z.optional(z.number().check(z.int())), "Number of results, 1 to 50 (default: 10)."),
need_content: z.describe(z.optional(z.boolean()), "Include available page content (default: false)."),
ori_question: z.describe(z.optional(z.nullable(z.string())), "Original user question, 1 to 128 Unicode characters.")
})));
const deepseekSearchOutputSchema = lazySchema(() => zodSchema(z.union([z.catchall(z.object({ results: z.array(z.catchall(z.object({
authority: z.nullish(z.number()),
content: z.nullish(z.string()),
date: z.nullish(z.string()),
rerank_score: z.nullish(z.number()),
site_icon: z.nullish(z.string()),
site_name: z.nullish(z.string()),
snippet: z.nullish(z.string()),
summary: z.nullish(z.string()),
title: z.nullish(z.string()),
url: z.nullish(z.string())
}), z.unknown())) }), z.unknown()), gatewayToolErrorSchema()])));
const deepseekSearchToolFactory = createProviderExecutedToolFactory({
id: "gateway.deepseek_search",
inputSchema: deepseekSearchInputSchema,
outputSchema: deepseekSearchOutputSchema
});
const deepseekSearch = (config = {}) => deepseekSearchToolFactory(config);
//#endregion
//#region src/tool/exa-search.ts
const exaSearchInputSchema = lazySchema(() => zodSchema(z.object({
query: z.describe(z.string(), "Natural-language web search query. This is required."),
type: z.describe(z.optional(z.enum([
"auto",
"fast",
"instant"
])), "Search method. Use auto for the default balance of speed and quality."),
num_results: z.describe(z.optional(z.number()), "Maximum number of results to return (1-100, default: 10)."),
category: z.describe(z.optional(z.enum([
"company",
"people",
"research paper",
"news",
"personal site",
"financial report"
])), "Optional content category to focus results."),
user_location: z.describe(z.optional(z.string()), "Two-letter ISO country code such as 'US'."),
include_domains: z.describe(z.optional(z.array(z.string())), "Only return results from these domains."),
exclude_domains: z.describe(z.optional(z.array(z.string())), "Exclude results from these domains."),
start_published_date: z.describe(z.optional(z.string()), "Only return links published after this ISO 8601 date."),
end_published_date: z.describe(z.optional(z.string()), "Only return links published before this ISO 8601 date."),
contents: z.describe(z.optional(z.object({
text: z.optional(z.union([z.boolean(), z.object({
max_characters: z.optional(z.number()),
include_html_tags: z.optional(z.boolean()),
verbosity: z.optional(z.enum([
"compact",
"standard",
"full"
])),
include_sections: z.optional(z.array(z.enum([
"header",
"navigation",
"banner",
"body",
"sidebar",
"footer",
"metadata"
]))),
exclude_sections: z.optional(z.array(z.enum([
"header",
"navigation",
"banner",
"body",
"sidebar",
"footer",
"metadata"
])))
})])),
highlights: z.optional(z.union([z.boolean(), z.object({
query: z.optional(z.string()),
max_characters: z.optional(z.number())
})])),
max_age_hours: z.optional(z.number()),
livecrawl_timeout: z.optional(z.number()),
subpages: z.optional(z.number()),
subpage_target: z.optional(z.union([z.string(), z.array(z.string())])),
extras: z.optional(z.object({
links: z.optional(z.number()),
image_links: z.optional(z.number())
}))
})), "Controls extracted page content and freshness.")
})));
const exaSearchOutputSchema = lazySchema(() => zodSchema(z.union([z.object({
requestId: z.string(),
searchType: z.optional(z.string()),
resolvedSearchType: z.optional(z.string()),
results: z.array(z.object({
title: z.string(),
url: z.string(),
id: z.string(),
publishedDate: z.optional(z.nullable(z.string())),
author: z.optional(z.nullable(z.string())),
image: z.optional(z.nullable(z.string())),
favicon: z.optional(z.nullable(z.string())),
text: z.optional(z.string()),
highlights: z.optional(z.array(z.string())),
highlightScores: z.optional(z.array(z.number())),
summary: z.optional(z.string()),
subpages: z.optional(z.array(z.any())),
extras: z.optional(z.object({
links: z.optional(z.array(z.string())),
imageLinks: z.optional(z.array(z.string()))
}))
})),
costDollars: z.optional(z.object({
total: z.optional(z.number()),
search: z.optional(z.record(z.string(), z.number()))
}))
}), z.object({
error: z.enum([
"api_error",
"rate_limit",
"timeout",
"invalid_input",
"configuration_error",
"execution_error",
"unknown"
]),
statusCode: z.optional(z.number()),
message: z.string()
})])));
const exaSearchToolFactory = createProviderExecutedToolFactory({
id: "gateway.exa_search",
inputSchema: exaSearchInputSchema,
outputSchema: exaSearchOutputSchema
});
const exaSearch = (config = {}) => exaSearchToolFactory(config);
//#endregion
//#region src/tool/parallel-search.ts
const parallelSearchModes = [
"turbo",
"fast",
"basic",
"advanced",
"one-shot",
"agentic"
];
const parallelSearchInputSchema = lazySchema(() => zodSchema(z.object({
objective: z.describe(z.string(), "Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),
search_queries: z.describe(z.optional(z.array(z.string())), "Provide 2-3 concise keyword queries, 3-6 words each (max 5, 200 chars each). Strongly recommended; the search runs on these queries."),
mode: z.describe(z.optional(z.enum(parallelSearchModes)), "Search mode: \"turbo\" and \"fast\" return quickly with shorter excerpts, \"basic\" is balanced (default), \"advanced\" is the most thorough. \"turbo\" supports English and Japanese only. \"one-shot\" and \"agentic\" are deprecated aliases of \"basic\" and \"advanced\"."),
max_results: z.describe(z.optional(z.number()), "Maximum number of results to return (1-20). Defaults to 10 if not specified."),
source_policy: z.describe(z.optional(z.object({
include_domains: z.describe(z.optional(z.array(z.string())), "Domains or domain/path prefixes to restrict results to, without scheme or port. Example: ['wikipedia.org', 'docs.python.org/3']."),
exclude_domains: z.describe(z.optional(z.array(z.string())), "Domains or domain/path prefixes to exclude, without scheme or port. Example: ['reddit.com']."),
after_date: z.describe(z.optional(z.string()), "Only include results published on or after this date. Use an ISO 8601 calendar date formatted YYYY-MM-DD (e.g. 2025-01-01); do not include a time.")
})), "Source policy for controlling which domains to include/exclude and freshness."),
excerpts: z.describe(z.optional(z.object({
max_chars_per_result: z.describe(z.optional(z.number()), "Maximum characters per result."),
max_chars_total: z.describe(z.optional(z.number()), "Deprecated: use the top-level max_chars_total.")
})), "Excerpt configuration for controlling result length."),
max_chars_total: z.describe(z.optional(z.number()), "Maximum total characters across all result excerpts."),
fetch_policy: z.describe(z.optional(z.object({
max_age_seconds: z.describe(z.optional(z.number()), "Maximum age of cached content in seconds before a live fetch, minimum 600."),
timeout_seconds: z.describe(z.optional(z.number()), "Timeout in seconds for a live fetch when content is not cached. Capped by the gateway tool timeout."),
disable_cache_fallback: z.describe(z.optional(z.boolean()), "Return an error instead of older cached content when a live fetch fails.")
})), "Fetch policy for controlling content freshness."),
location: z.describe(z.optional(z.string()), "ISO 3166-1 alpha-2 country code to localize results, e.g. \"us\".")
})));
const parallelSearchOutputSchema = lazySchema(() => zodSchema(z.union([z.object({
search_id: z.string(),
results: z.array(z.object({
url: z.string(),
title: z.optional(z.nullable(z.string())),
publish_date: z.optional(z.nullable(z.string())),
excerpts: z.array(z.string())
})),
warnings: z.optional(z.nullable(z.array(z.object({
type: z.string(),
message: z.string(),
detail: z.optional(z.nullable(z.record(z.string(), z.unknown())))
})))),
usage: z.optional(z.nullable(z.array(z.object({
name: z.string(),
count: z.optional(z.number())
})))),
session_id: z.optional(z.string())
}), gatewayToolErrorSchema()])));
const parallelSearchToolFactory = createProviderExecutedToolFactory({
id: "gateway.parallel_search",
inputSchema: parallelSearchInputSchema,
outputSchema: parallelSearchOutputSchema
});
const parallelSearch = (config = {}) => parallelSearchToolFactory(config);
//#endregion
//#region src/tool/perplexity-search.ts
const perplexitySearchInputSchema = lazySchema(() => zodSchema(z.object({
query: z.describe(z.union([z.string(), z.array(z.string())]), "Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),
max_results: z.describe(z.optional(z.number()), "Maximum number of search results to return (1-20, default: 10)"),
max_tokens_per_page: z.describe(z.optional(z.number()), "Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),
max_tokens: z.describe(z.optional(z.number()), "Maximum total tokens across all search results (default: 25000, max: 1000000)"),
country: z.describe(z.optional(z.string()), "Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),
search_domain_filter: z.describe(z.optional(z.array(z.string())), "List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),
search_language_filter: z.describe(z.optional(z.array(z.string())), "List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),
search_after_date: z.describe(z.optional(z.string()), "Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),
search_before_date: z.describe(z.optional(z.string()), "Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),
last_updated_after_filter: z.describe(z.optional(z.string()), "Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),
last_updated_before_filter: z.describe(z.optional(z.string()), "Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),
search_recency_filter: z.describe(z.optional(z.enum([
"day",
"week",
"month",
"year"
])), "Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")
})));
const perplexitySearchOutputSchema = lazySchema(() => zodSchema(z.union([z.object({
results: z.array(z.object({
title: z.string(),
url: z.string(),
snippet: z.string(),
date: z.optional(z.string()),
lastUpdated: z.optional(z.string())
})),
id: z.string()
}), z.object({
error: z.enum([
"api_error",
"rate_limit",
"timeout",
"invalid_input",
"unknown"
]),
statusCode: z.optional(z.number()),
message: z.string()
})])));
const perplexitySearchToolFactory = createProviderExecutedToolFactory({
id: "gateway.perplexity_search",
inputSchema: perplexitySearchInputSchema,
outputSchema: perplexitySearchOutputSchema
});
const perplexitySearch = (config = {}) => perplexitySearchToolFactory(config);
//#endregion
//#region src/tool/tako-search.ts
const takoDataSourceInputSchema = () => z.object({
count: z.describe(z.optional(z.number()), "Maximum number of data results to return (1-20). When include_contents is true, each additional result adds its own data surcharge."),
include_contents: z.describe(z.optional(z.boolean()), "Inline rows for each data result. This adds a data surcharge based on row count and dataset source. To estimate cost, search with include_contents disabled and inspect cards.content.export_pricing. This applies to every returned card; limit sources.data.count and sources.data.max_rows to control cost."),
mode: z.describe(z.optional(z.enum(["inline", "url"])), "Requested data delivery mode. Search card data is always inline."),
content_format: z.describe(z.optional(z.enum([
"card_json",
"csv",
"json_compact",
"json_records"
])), "Serialization for inlined card data."),
max_rows: z.describe(z.optional(z.number()), "Maximum rows to inline per result. Omit to use the allowance in cards.content.export_pricing. A data surcharge applies per 1,000 exported rows; lower values reduce cost."),
node_ids: z.describe(z.optional(z.array(z.string())), "Data Graph node IDs to prioritize. Maximum 20."),
strict: z.describe(z.optional(z.boolean()), "Only return cards matching node_ids. Requires a non-empty node_ids.")
});
const takoWebSourceInputSchema = () => z.object({
count: z.describe(z.optional(z.number()), "Maximum number of web results to return (1-20)."),
include_contents: z.describe(z.optional(z.boolean()), "Inline extracted web page text. This can add a data charge."),
category: z.describe(z.optional(z.enum([
"finance",
"news",
"sports"
])), "Optional web-result category filter."),
include_domains: z.describe(z.optional(z.array(z.string())), "Only return results from these bare domains."),
exclude_domains: z.describe(z.optional(z.array(z.string())), "Exclude results from these bare domains."),
snippet_max_chars: z.describe(z.optional(z.number()), "Maximum characters in each web-result snippet."),
highlights: z.describe(z.optional(z.boolean()), "Include highlighted passages in web results. Defaults to true in AI Gateway."),
article_content_max_chars: z.describe(z.optional(z.number()), "Maximum extracted characters per web page when including contents."),
published_after: z.describe(z.optional(z.string()), "Keep results published on or after this ISO date (YYYY-MM-DD)."),
published_before: z.describe(z.optional(z.string()), "Keep results published on or before this ISO date (YYYY-MM-DD).")
});
const takoSearchInputSchema = lazySchema(() => zodSchema(z.object({
query: z.describe(z.string(), "Natural-language search query. Include the entity, metric, and time period. Quote a phrase to force it to one entity, for example \"Tesla\":PRODUCT price."),
effort: z.describe(z.optional(z.enum([
"deep",
"fast",
"instant"
])), "Search effort. fast is the balanced default, instant favors cached results and low latency, and deep broadens retrieval with reranking at higher cost and latency."),
sources: z.describe(z.optional(z.object({
data: z.optional(takoDataSourceInputSchema()),
web: z.optional(takoWebSourceInputSchema())
})), "Sources to search. Omit to search both curated data and the web. When provided, only keys present are searched."),
location: z.describe(z.optional(z.object({
latitude: z.describe(z.number(), "Latitude between -90 and 90."),
longitude: z.describe(z.number(), "Longitude between -180 and 180.")
})), "End-user coordinates for localized results."),
country_code: z.describe(z.optional(z.string()), "Two-letter ISO 3166-1 country code, such as 'US'."),
locale: z.describe(z.optional(z.string()), "BCP-47 locale, such as 'en-US'."),
timezone: z.describe(z.optional(z.string()), "IANA timezone, such as 'America/New_York'."),
output_settings: z.describe(z.optional(z.object({
image_dark_mode: z.describe(z.optional(z.boolean()), "Render card preview images in dark mode."),
force_refresh: z.describe(z.optional(z.boolean()), "Instant-effort only. Request a refreshed instant result.")
})), "Controls card rendering in the search response."),
include_related: z.describe(z.optional(z.number()), "Maximum related search suggestions to include (1-20).")
})));
const takoDatasetCellSchema = () => z.nullable(z.union([
z.boolean(),
z.number(),
z.string()
]));
const takoResultContentSchema = () => z.catchall(z.object({
content_format: z.nullish(z.enum([
"card_json",
"csv",
"json_compact",
"json_records"
])),
cost: z.optional(z.number()),
data: z.nullish(z.string()),
records: z.nullish(z.array(z.record(z.string(), takoDatasetCellSchema()))),
dataset: z.nullish(z.object({
columns: z.array(z.object({
name: z.string(),
type: z.enum([
"boolean",
"date",
"datetime",
"number",
"string"
]),
unit: z.nullish(z.string())
})),
rows: z.array(z.array(takoDatasetCellSchema())),
total_rows: z.number(),
truncated: z.boolean(),
ref: z.string(),
sources: z.array(z.object({
name: z.string(),
index: z.optional(z.enum(["data", "web"]))
})),
provenance: z.optional(z.enum(["query", "web_extraction"]))
})),
card_data: z.nullish(z.catchall(z.object({}), z.unknown())),
card_data_schema: z.nullish(z.catchall(z.object({}), z.unknown())),
url: z.nullish(z.string()),
expires_at: z.nullish(z.string()),
total_rows: z.nullish(z.number()),
truncated: z.optional(z.boolean()),
premium_rows: z.nullish(z.record(z.string(), z.number())),
redacted_cells: z.nullish(z.record(z.string(), z.array(z.number()))),
total_matching: z.nullish(z.number()),
export_pricing: z.nullish(z.catchall(z.object({
baseline_usd: z.number(),
free_rows: z.optional(z.number()),
max_rows_ceiling: z.number(),
row_cpm_usd: z.number(),
premium_row_cpm_usd: z.nullish(z.record(z.string(), z.number())),
variable_cost_max_usd: z.nullish(z.number())
}), z.unknown())),
manifest: z.nullish(z.array(z.object({
dtype: z.nullish(z.enum([
"boolean",
"date",
"datetime",
"number",
"string"
])),
entity: z.nullish(z.string()),
metric: z.nullish(z.string()),
name: z.nullish(z.string()),
unit: z.nullish(z.string())
})))
}), z.unknown());
const takoCardSchema = () => z.catchall(z.object({
card_id: z.nullish(z.string()),
title: z.nullish(z.string()),
description: z.nullish(z.string()),
semantic_description: z.nullish(z.string()),
webpage_url: z.nullish(z.string()),
image_url: z.nullish(z.string()),
embed_url: z.nullish(z.string()),
sources: z.nullish(z.array(z.object({
source_name: z.nullish(z.string()),
source_description: z.nullish(z.string()),
source_index: z.enum(["data", "web"]),
source_text: z.nullish(z.string()),
url: z.nullish(z.string())
}))),
methodologies: z.nullish(z.array(z.object({
methodology_name: z.nullable(z.string()),
methodology_description: z.nullable(z.string())
}))),
source_indexes: z.nullish(z.array(z.enum(["data", "web"]))),
card_type: z.nullish(z.string()),
relevance: z.nullish(z.enum([
"High",
"Low",
"Medium"
])),
relevance_score: z.nullish(z.number()),
content: z.nullish(takoResultContentSchema()),
exportable: z.optional(z.boolean()),
nodes: z.nullish(z.array(z.object({
id: z.string(),
type: z.enum(["entity", "metric"]),
name: z.string(),
description: z.nullish(z.string())
}))),
metric_definitions: z.nullish(z.array(z.object({
name: z.string(),
definition: z.string()
}))),
data_freshness: z.nullish(z.object({
coverage_end: z.nullish(z.string()),
data_as_of: z.nullish(z.string()),
last_updated: z.nullish(z.string())
})),
placeholder: z.nullish(z.catchall(z.object({
withheld_source: z.string(),
reason: z.nullish(z.enum(["not_served", "over_cap"]))
}), z.unknown()))
}), z.unknown());
const takoWebResultSchema = () => z.catchall(z.object({
title: z.string(),
url: z.string(),
snippet: z.nullish(z.string()),
source_name: z.nullish(z.string()),
publish_date: z.nullish(z.string()),
content: z.nullish(takoResultContentSchema())
}), z.unknown());
const takoSearchOutputSchema = lazySchema(() => zodSchema(z.union([z.catchall(z.object({
request_id: z.string(),
cards: z.optional(z.array(takoCardSchema())),
web_results: z.optional(z.array(takoWebResultSchema())),
usage: z.nullish(z.catchall(z.object({
total_cost_usd: z.number(),
compute: z.nullish(z.catchall(z.object({ cost_usd: z.number() }), z.unknown())),
data: z.nullish(z.catchall(z.object({
cost_usd: z.number(),
datasets: z.number(),
data_points: z.nullish(z.number())
}), z.unknown())),
variable_cost: z.nullish(z.catchall(z.object({ cost_usd: z.number() }), z.unknown()))
}), z.unknown())),
related: z.nullish(z.array(z.catchall(z.object({}), z.unknown())))
}), z.unknown()), gatewayToolErrorSchema()])));
const takoSearchToolFactory = createProviderExecutedToolFactory({
id: "gateway.tako_search",
inputSchema: takoSearchInputSchema,
outputSchema: takoSearchOutputSchema
});
const takoSearch = (config = {}) => takoSearchToolFactory(config);
//#endregion
//#region src/tool/tako-contents.ts
const takoContentsInputSchema = lazySchema(() => zodSchema(z.object({
url: z.describe(z.string(), "The result to fetch: a Tako card's webpage_url or a web result's url, usually from Tako Search. A card URL returns the card's data, and any other URL returns the page's extracted text."),
mode: z.describe(z.optional(z.enum(["inline", "url"])), "Delivery mode. inline, the default, returns the content in the result. url returns a signed download link that expires after a few minutes; use it only when the application saves the content to a file. A url export without max_rows exports and bills the whole card, up to 100,000 rows."),
content_format: z.describe(z.optional(z.enum([
"card_json",
"csv",
"json_compact",
"json_records"
])), "Serialization for Tako card data. card_json returns the card's own structure, and not every card type supports it. Web pages always return text."),
max_rows: z.describe(z.optional(z.number()), "Maximum card rows to return and bill. A data surcharge applies per 1,000 exported rows; lower values reduce cost. In inline mode it defaults to and is capped at 2,000. A card with a date column keeps its newest rows. Web pages ignore it."),
offset: z.describe(z.optional(z.number()), "Card rows to skip before the export starts (0-100,000). Use it with max_rows to page through a long list, and stop when a call returns fewer rows than max_rows. Cards with a date column, sports cards, and card_json reject an offset above 0. Web pages ignore it."),
max_chars: z.describe(z.optional(z.number()), "Maximum characters of a web page's full extracted text (1-1,000,000). Omit it to return the whole page. It doesn't apply to highlights, which use highlights.max_characters. Tako cards ignore it."),
highlights: z.describe(z.optional(z.object({
query: z.describe(z.optional(z.string()), "The question the passages should answer. Omit it to get the page's leading passages."),
max_characters: z.describe(z.optional(z.number()), "Total characters across the returned passages (100-20,000). Defaults to 4,000.")
})), "Return only the passages of a web page that answer query, instead of its full text. Tako cards reject it."),
quote_only: z.describe(z.optional(z.boolean()), "Return only the export's price (cost and export_pricing), without fetching content or charging for it. The quote is the most the export can cost, including any variable cost. Use it before a large export, or before exporting a card that can carry variable cost.")
})));
const columnTypeSchema = () => z.string();
const cellSchema = () => z.nullable(z.union([
z.boolean(),
z.number(),
z.string(),
z.array(z.record(z.string(), z.unknown()))
]));
const takoContentItemSchema = () => z.extend(takoResultContentSchema(), {
records: z.nullish(z.array(z.record(z.string(), cellSchema()))),
dataset: z.nullish(z.catchall(z.object({
columns: z.array(z.object({
name: z.string(),
type: columnTypeSchema(),
unit: z.nullish(z.string())
})),
rows: z.array(z.array(cellSchema())),
total_rows: z.number(),
truncated: z.boolean(),
ref: z.string(),
sources: z.array(z.object({
name: z.string(),
index: z.optional(z.string())
})),
provenance: z.optional(z.string())
}), z.unknown())),
manifest: z.nullish(z.array(z.catchall(z.object({
dtype: z.nullish(columnTypeSchema()),
entity: z.nullish(z.string()),
metric: z.nullish(z.string()),
name: z.nullish(z.string()),
unit: z.nullish(z.string()),
premium_class: z.nullish(z.string())
}), z.unknown()))),
source_url: z.string(),
delivery: z.optional(z.string()),
description: z.nullish(z.string()),
offset: z.nullish(z.number()),
premium: z.optional(z.boolean())
});
const takoContentsOutputSchema = lazySchema(() => zodSchema(z.union([z.catchall(z.object({
request_id: z.string(),
contents: z.optional(z.array(takoContentItemSchema())),
usage: z.nullish(z.catchall(z.object({
total_cost_usd: z.number(),
compute: z.nullish(z.catchall(z.object({ cost_usd: z.number() }), z.unknown())),
data: z.nullish(z.catchall(z.object({
cost_usd: z.number(),
datasets: z.number(),
data_points: z.nullish(z.number())
}), z.unknown())),
variable_cost: z.nullish(z.catchall(z.object({ cost_usd: z.number() }), z.unknown()))
}), z.unknown()))
}), z.unknown()), gatewayToolErrorSchema()])));
const takoContentsToolFactory = createProviderExecutedToolFactory({
id: "gateway.tako_contents",
inputSchema: takoContentsInputSchema,
outputSchema: takoContentsOutputSchema
});
const takoContents = (config = {}) => takoContentsToolFactory(config);
//#endregion
//#region src/gateway-tools.ts
/**
* Gateway-specific provider-defined tools.
*/
const gatewayTools = {
/**
* Fetch page content using Browserbase's lightweight Fetch API.
*
* Supports raw, Markdown, and schema-driven JSON output as well as redirects,
* proxy routing, and TLS controls.
*/
browserbaseFetch,
/**
* Search the web using Browserbase's Search API for fast, structured results.
*
* Returns titles, URLs, and available publication metadata without requiring
* a browser session.
*/
browserbaseSearch,
/**
* Fetch a page as Markdown through DeepSeek's standalone Fetch API.
* Executed by AI Gateway for any model, separate from native model web search.
*/
deepseekFetch,
/**
* Search the web through DeepSeek's standalone Search API.
* Executed by AI Gateway for any model, separate from native model web search.
*/
deepseekSearch,
/**
* Search the web using Exa for current information and token-efficient
* excerpts optimized for agent workflows.
*
* Supports search type, category, domain, date, location, and content
* extraction controls.
*/
exaSearch,
/**
* Search the web using Parallel AI's Search API for LLM-optimized excerpts.
*
* Takes a natural language objective and returns relevant excerpts,
* replacing multiple keyword searches with a single call for broad
* or complex queries. Supports different search types for depth vs
* breadth tradeoffs.
*/
parallelSearch,
/**
* Search the web using Perplexity's Search API for real-time information,
* news, research papers, and articles.
*
* Provides ranked search results with advanced filtering options including
* domain, language, date range, and recency filters.
*/
perplexitySearch,
/**
* Fetch the data behind one Tako result: a Tako card's rows, or a web page's
* extracted text. Pairs with `takoSearch`.
*
* Supports inline delivery or a short-lived download link, card data
* formats, row paging, query-focused web passages, free price quotes, and a
* limit on each export's quoted price. A card export is billed per row at the card's
* `content.export_pricing`; see Tako's pricing page:
* https://docs.tako.com/documentation/integrating-tako/contents/pricing
*/
takoContents,
/**
* Search the web and Tako's curated knowledge graph in one call for
* token-efficient web excerpts and structured data results grounded in
* premium sources, each with an embed-ready visualization.
*
* Supports effort, per-source web and data controls, localization, and inline
* contents for agents that need to reason over underlying data.
*/
takoSearch
};
//#endregion
//#region src/vercel-environment.ts
async function getVercelRequestId() {
return getContext().headers?.["x-vercel-id"];
}
//#endregion
//#region src/version.ts
const VERSION = "4.0.163";
//#endregion
//#region src/gateway-provider.ts
const AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
/** Response shape of `POST /v1/realtime/client-secrets`. `expiresAt` is epoch seconds. */
const gatewayClientSecretResponseSchema = lazySchema(() => zodSchema(z.object({
token: z.string(),
expiresAt: z.nullish(z.number())
})));
/**
* Create a remote provider instance.
*/
function createGateway(options = {}) {
let pendingMetadata = null;
let metadataCache = null;
const cacheRefreshMillis = options.metadataCacheRefreshMillis ?? 3e5;
let lastFetchTime = 0;
const baseURL = withoutTrailingSlash(options.baseURL) ?? "https://ai-gateway.vercel.sh/v4/ai";
const createAuthHeaders = (auth) => withUserAgentSuffix({
Authorization: `Bearer ${auth.token}`,
"ai-gateway-protocol-version": AI_GATEWAY_PROTOCOL_VERSION,
[GATEWAY_AUTH_METHOD_HEADER]: auth.authMethod,
...options.teamIdOrSlug != null ? { [VERCEL_AI_GATEWAY_TEAM_HEADER]: options.teamIdOrSlug } : {},
...options.headers
}, `ai-sdk-gateway/${VERSION}`);
const getHeaders = async (onResolved) => {
try {
const headers = createAuthHeaders(await getGatewayAuthToken(options));
onResolved?.(headers);
return headers;
} catch (error) {
throw GatewayAuthenticationError.createContextualError({
apiKeyProvided: false,
oidcTokenProvided: false,
statusCode: 401,
cause: error
});
}
};
const getRealtimeAuthToken = async () => {
try {
return await getGatewayAuthToken(options);
} catch (error) {
throw GatewayAuthenticationError.createContextualError({
apiKeyProvided: false,
oidcTokenProvided: false,
statusCode: 401,
cause: error
});
}
};
const mintClientSecret = async (params) => {
assertGatewayClientSecretServerEnvironment();
const auth = await getRealtimeAuthToken();
const headers = createAuthHeaders(auth);
const url = new URL("/v1/realtime/client-secrets", baseURL).toString();
try {
const { value } = await postJsonToApi({
url,
headers,
body: {
model: params.modelId,
...params.routeKind != null && { routeKind: params.routeKind },
...params.expiresAfterSeconds != null && { expiresIn: params.expiresAfterSeconds }
},
successfulResponseHandler: createJsonResponseHandler(gatewayClientSecretResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => getErrorMessage(data) ?? "unknown error"
}),
fetch: options.fetch
});
return {
token: value.token,
...value.expiresAt != null && { expiresAt: value.expiresAt }
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(headers));
}
};
const createO11yHeaders = () => {
const deploymentId = loadOptionalSetting({
settingValue: void 0,
environmentVariableName: "VERCEL_DEPLOYMENT_ID"
});
const environment = loadOptionalSetting({
settingValue: void 0,
environmentVariableName: "VERCEL_ENV"
});
const region = loadOptionalSetting({
settingValue: void 0,
environmentVariableName: "VERCEL_REGION"
});
const projectId = loadOptionalSetting({
settingValue: void 0,
environmentVariableName: "VERCEL_PROJECT_ID"
});
return async () => {
const requestId = await getVercelRequestId();
return {
...deploymentId && { "ai-o11y-deployment-id": deploymentId },
...environment && { "ai-o11y-environment": environment },
...region && { "ai-o11y-region": region },
...requestId && { "ai-o11y-request-id": requestId },
...projectId && { "ai-o11y-project-id": projectId }
};
};
};
const createLanguageModel = (modelId) => {
return new GatewayLanguageModel(modelId, {
provider: "gateway",
baseURL,
headers: getHeaders,
fetch: options.fetch,
o11yHeaders: createO11yHeaders()
});
};
const createBatch = () => new GatewayBatch({
provider: "gateway",
maxLineBytes: options.batchResultDownloads?.maxLineBytes,
baseURL,
headers: getHeaders,
fetch: options.fetch,
o11yHeaders: createO11yHeaders()
});
const getAvailableModels = async () => {
const now = options._internal?.currentDate?.().getTime() ?? Date.now();
if (!pendingMetadata || now - lastFetchTime > cacheRefreshMillis) {
lastFetchTime = now;
let resolvedHeaders;
pendingMetadata = new GatewayFetchMetadata({
baseURL,
headers: () => getHeaders((headers) => {
resolvedHeaders = headers;
}),
fetch: options.fetch
}).getAvailableModels().then((metadata) => {
metadataCache = metadata;
return metadata;
}).catch(async (error) => {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders ?? {}));
});
}
return metadataCache ? Promise.resolve(metadataCache) : pendingMetadata;
};
const getCredits = async () => {
let resolvedHeaders;
return new GatewayFetchMetadata({
baseURL,
headers: () => getHeaders((headers) => {
resolvedHeaders = headers;
}),
fetch: options.fetch
}).getCredits().catch(async (error) => {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders ?? {}));
});
};
const getSpendReport = async (params) => {
let resolvedHeaders;
return new GatewaySpendReport({
baseURL,
headers: () => getHeaders((headers) => {
resolvedHeaders = headers;
}),
fetch: options.fetch
}).getSpendReport(params).catch(async (error) => {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders ?? {}));
});
};
const getGenerationInfo = async (params) => {
let resolvedHeaders;
return new GatewayGenerationInfoFetcher({
baseURL,
headers: () => getHeaders((headers) => {
resolvedHeaders = headers;
}),
fetch: options.fetch
}).getGenerationInfo(params).catch(async (error) => {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders ?? {}));
});
};
const provider = function(modelId) {
if (new.target) throw new Error("The Gateway Provider model function cannot be called with the new keyword.");
return createLanguageModel(modelId);
};
provider.specificationVersion = "v4";
provider.getAvailableModels = getAvailableModels;
provider.getCredits = getCredits;
provider.getSpendReport = getSpendReport;
provider.getGenerationInfo = getGenerationInfo;
provider.imageModel = (modelId) => {
return new GatewayImageModel(modelId, {
provider: "gateway",
baseURL,
headers: getHeaders,
fetch: options.fetch,
o11yHeaders: createO11yHeaders()
});
};
provider.languageModel = createLanguageModel;
provider.experimental_batch = createBatch;
const createEmbeddingModel = (modelId) => {
return new GatewayEmbeddingModel(modelId, {
provider: "gateway",
baseURL,
headers: getHeaders,
fetch: options.fetch,
o11yHeaders: createO11yHeaders()
});
};
provider.embeddingModel = createEmbeddingModel;
provider.textEmbeddingModel = createEmbeddingModel;
provider.videoModel = (modelId) => {
return new GatewayVideoModel(modelId, {
provider: "gateway",
baseURL,
headers: getHeaders,
fetch: options.fetch,
o11yHeaders: createO11yHeaders()
});
};
const createRerankingModel = (modelId) => {
return new GatewayRerankingModel(modelId, {
provider: "gateway",
baseURL,
headers: getHeaders,
fetch: options.fetch,
o11yHeaders: createO11yHeaders()
});
};
provider.rerankingModel = createRerankingModel;
provider.reranking = createRerankingModel;
const createDecisionModel = (modelId) => {
return new GatewayDecisionModel(modelId, {
provider: "gateway",
baseURL,
headers: getHeaders,
fetch: options.fetch,
o11yHeaders: createO11yHeaders()
});
};
provider.decisionModel = createDecisionModel;
provider.decision = createDecisionModel;
provider.evaluationModel = createDecisionModel;
provider.evaluation = createDecisionModel;
const createExtractionModel = (modelId) => {
return new GatewayExtractionModel(modelId, {
provider: "gateway",
baseURL,
headers: getHeaders,
fetch: options.fetch,
o11yHeaders: createO11yHeaders()
});
};
provider.extractionModel = createExtractionModel;
provider.extraction = createExtractionModel;
const createSpeechModel = (modelId) => {
return new GatewaySpeechModel(modelId, {
provider: "gateway",
baseURL,
headers: getHeaders,
fetch: options.fetch,
o11yHeaders: createO11yHeaders(),
webSocket: options.webSocket
});
};
provider.speechModel = createSpeechModel;
provider.speech = createSpeechModel;
provider.experimental_speech = Object.assign((modelId) => createSpeechModel(modelId), { getToken: async (tokenOptions) => {
const secret = await mintClientSecret({
modelId: tokenOptions.model,
routeKind: "speech",
...tokenOptions.expiresAfterSeconds != null && { expiresAfterSeconds: tokenOptions.expiresAfterSeconds }
});
return {
token: secret.token,
url: toGatewaySpeechUrl(baseURL, tokenOptions.model),
...secret.expiresAt != null && { expiresAt: secret.expiresAt }
};
} });
const createTranscriptionModel = (modelId) => {
return new GatewayTranscriptionModel(modelId, {
provider: "gateway",
baseURL,
headers: getHeaders,
fetch: options.fetch,
o11yHeaders: createO11yHeaders(),
webSocket: options.webSocket
});
};
provider.transcriptionModel = createTranscriptionModel;
provider.transcription = createTranscriptionModel;
provider.experimental_transcription = Object.assign((modelId) => createTranscriptionModel(modelId), { getToken: async (tokenOptions) => {
const secret = await mintClientSecret({
modelId: tokenOptions.model,
routeKind: "transcription",
...tokenOptions.expiresAfterSeconds != null && { expiresAfterSeconds: tokenOptions.expiresAfterSeconds }
});
return {
token: secret.token,
url: toGatewayTranscriptionUrl(baseURL, tokenOptions.model),
...secret.expiresAt != null && { expiresAt: secret.expiresAt }
};
} });
const createRealtimeModel = (modelId, realtimeOptions) => resolveGatewayRealtimeApi(modelId, realtimeOptions) === "live" ? new GatewayRealtimeModelLive(modelId, {
provider: "gateway.live",
baseURL,
teamIdOrSlug: options.teamIdOrSlug,
createClientSecret: mintClientSecret,
getHeaders
}) : new GatewayRealtimeModel(modelId, {
provider: "gateway.realtime",
baseURL,
teamIdOrSlug: options.teamIdOrSlug,
createClientSecret: mintClientSecret,
getHeaders
});
provider.experimental_realtime = Object.assign((modelId, realtimeOptions) => createRealtimeModel(modelId, realtimeOptions), { getToken: async (tokenOptions) => {
const { model: modelId, api, ...secretOptions } = tokenOptions;
const secret = await createRealtimeModel(modelId, { api }).doCreateClientSecret(secretOptions);
return {
token: secret.token,
url: secret.url,
...secret.expiresAt != null && { expiresAt: secret.expiresAt }
};
} });
provider.chat = provider.languageModel;
provider.embedding = provider.embeddingModel;
provider.image = provider.imageModel;
provider.video = provider.videoModel;
provider.tools = gatewayTools;
return provider;
}
const gateway = createGateway();
/**
* Resolves the credential for a Gateway request, in this order:
*
* 1. The `apiKey` setting (a string, or a callback resolved per request).
* 2. The `AI_GATEWAY_API_KEY` environment variable.
* 3. The Vercel OIDC token from `getVercelOidcToken()`. It is available
* automatically on Vercel deployments, and locally after `vercel env pull`
* or under `vercel dev`.
*
* A non-empty configured API key is never replaced by OIDC, even if the key is
* invalid. An empty string option or environment variable falls through to
* OIDC; a callback must return a non-empty key. Callers wrap a failure here in a
* `GatewayAuthenticationError` ("No authentication provided").
*/
async function getGatewayAuthToken(options) {
const resolvedApiKey = typeof options.apiKey === "string" || options.apiKey == null ? options.apiKey : await resolve(options.apiKey);
if (options.apiKey != null && typeof options.apiKey !== "string" && (typeof resolvedApiKey !== "string" || !resolvedApiKey.trim())) throw new LoadAPIKeyError({ message: "AI Gateway API key must be a non-empty string." });
const apiKey = loadOptionalSetting({
settingValue: resolvedApiKey,
environmentVariableName: "AI_GATEWAY_API_KEY"
});
if (apiKey) return {
token: apiKey,
authMethod: "api-key"
};
return {
token: await getVercelOidcToken(),
authMethod: "oidc"
};
}
function resolveGatewayRealtimeApi(modelId, options) {
const api = options?.api;
if (api !== void 0) {
if (api !== "live" && api !== "realtime") throw new InvalidArgumentError({
argument: "api",
message: "AI Gateway realtime api must be \"live\" or \"realtime\"."
});
return api;
}
return gatewayLiveModelIds.includes(modelId) ? "live" : "realtime";
}
function assertGatewayClientSecretServerEnvironment() {
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.");
}
//#endregion
export { GATEWAY_AUTH_SUBPROTOCOL_PREFIX, GATEWAY_REALTIME_SUBPROTOCOL, GATEWAY_SPEECH_SUBPROTOCOL, GATEWAY_TEAM_SUBPROTOCOL_PREFIX, GATEWAY_TRANSCRIPTION_SUBPROTOCOL, GatewayAccessPolicyDeniedError, GatewayAuthenticationError, GatewayError, GatewayFailedDependencyError, GatewayForbiddenError, GatewayInternalServerError, GatewayInvalidRequestError, GatewayModelNotFoundError, GatewayNotFoundError, GatewayRateLimitError, GatewayResponseError, VERSION, createGateway, createGateway as createGatewayProvider, gateway, getGatewayRealtimeAuthToken, getGatewayRealtimeProtocols, getGatewayRealtimeTeamIdOrSlug, getGatewaySpeechProtocols, getGatewayTranscriptionProtocols };
//# sourceMappingURL=index.js.map
Shown as plain text from the published tarball, after apm checked it against the version's checksum. Nothing in it runs on this page.