@mastra/core
Version:
43,411 lines • 1.52 MB
JavaScript
import { n as __exportAll } from "./rolldown-runtime-tIEjjQTE.js";
import { i as MastraError } from "./error-oh2DLsP2.js";
import { r as createGatewayProvider } from "./dist-ByO0vuJJ-CCXLBnvJ.js";
import { t as InMemoryServerCache } from "./inmemory-BDD0w8gx.js";
import * as z4 from "zod/v4";
import { safeParseAsync, z } from "zod/v4";
import { ZodFirstPartyTypeKind } from "zod/v3";
import { config, toJSONSchema } from "zod/v4/core";
import en from "zod/v4/locales/en.js";
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/provider/3.0.19/0b1d7b6863750d2561eeffa8e8855a8a3237be133a137f63f15430e10633b053/node_modules/@ai-sdk/provider/dist/index.mjs
var marker$14 = "vercel.ai.error";
var symbol$14 = Symbol.for(marker$14);
var _a$4;
var _b$2;
var AISDKError$2 = class _AISDKError extends (_b$2 = Error, _a$4 = symbol$14, _b$2) {
/**
* Creates an AI SDK Error.
*
* @param {Object} params - The parameters for creating the error.
* @param {string} params.name - The name of the error.
* @param {string} params.message - The error message.
* @param {unknown} [params.cause] - The underlying cause of the error.
*/
constructor({ name: name14, message, cause }) {
super(message);
this[_a$4] = true;
this.name = name14;
this.cause = cause;
}
/**
* Checks if the given error is an AI SDK Error.
* @param {unknown} error - The error to check.
* @returns {boolean} True if the error is an AI SDK Error, false otherwise.
*/
static isInstance(error) {
return _AISDKError.hasMarker(error, marker$14);
}
static hasMarker(error, marker15) {
const markerSymbol = Symbol.for(marker15);
return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
}
};
var name$12 = "AI_APICallError";
var marker2$1 = `vercel.ai.error.${name$12}`;
var symbol2$1 = Symbol.for(marker2$1);
var _a2$1;
var _b2$1;
var APICallError$2 = class extends (_b2$1 = AISDKError$2, _a2$1 = symbol2$1, _b2$1) {
constructor({ message, url, requestBodyValues, statusCode, responseHeaders, responseBody, cause, isRetryable = statusCode != null && (statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500), data }) {
super({
name: name$12,
message,
cause
});
this[_a2$1] = true;
this.url = url;
this.requestBodyValues = requestBodyValues;
this.statusCode = statusCode;
this.responseHeaders = responseHeaders;
this.responseBody = responseBody;
this.isRetryable = isRetryable;
this.data = data;
}
static isInstance(error) {
return AISDKError$2.hasMarker(error, marker2$1);
}
};
var name2$1 = "AI_EmptyResponseBodyError";
var marker3$1 = `vercel.ai.error.${name2$1}`;
var symbol3$1 = Symbol.for(marker3$1);
var _a3$1;
var _b3$1;
var EmptyResponseBodyError$2 = class extends (_b3$1 = AISDKError$2, _a3$1 = symbol3$1, _b3$1) {
constructor({ message = "Empty response body" } = {}) {
super({
name: name2$1,
message
});
this[_a3$1] = true;
}
static isInstance(error) {
return AISDKError$2.hasMarker(error, marker3$1);
}
};
function getErrorMessage$2(error) {
if (error == null) return "unknown error";
if (typeof error === "string") return error;
if (error instanceof Error) return error.message;
return JSON.stringify(error);
}
var name3$1 = "AI_InvalidArgumentError";
var marker4$1 = `vercel.ai.error.${name3$1}`;
var symbol4$1 = Symbol.for(marker4$1);
var _a4$1;
var _b4$1;
var InvalidArgumentError$2 = class extends (_b4$1 = AISDKError$2, _a4$1 = symbol4$1, _b4$1) {
constructor({ message, cause, argument }) {
super({
name: name3$1,
message,
cause
});
this[_a4$1] = true;
this.argument = argument;
}
static isInstance(error) {
return AISDKError$2.hasMarker(error, marker4$1);
}
};
var name4$1 = "AI_InvalidPromptError";
var marker5$1 = `vercel.ai.error.${name4$1}`;
var symbol5$1 = Symbol.for(marker5$1);
var _a5$1;
var _b5$1;
var InvalidPromptError$2 = class extends (_b5$1 = AISDKError$2, _a5$1 = symbol5$1, _b5$1) {
constructor({ prompt, message, cause }) {
super({
name: name4$1,
message: `Invalid prompt: ${message}`,
cause
});
this[_a5$1] = true;
this.prompt = prompt;
}
static isInstance(error) {
return AISDKError$2.hasMarker(error, marker5$1);
}
};
var name5$1 = "AI_InvalidResponseDataError";
var marker6$1 = `vercel.ai.error.${name5$1}`;
var symbol6$1 = Symbol.for(marker6$1);
var _a6$1;
var _b6$1;
var InvalidResponseDataError$2 = class extends (_b6$1 = AISDKError$2, _a6$1 = symbol6$1, _b6$1) {
constructor({ data, message = `Invalid response data: ${JSON.stringify(data)}.` }) {
super({
name: name5$1,
message
});
this[_a6$1] = true;
this.data = data;
}
static isInstance(error) {
return AISDKError$2.hasMarker(error, marker6$1);
}
};
var name6$1 = "AI_JSONParseError";
var marker7$1 = `vercel.ai.error.${name6$1}`;
var symbol7$1 = Symbol.for(marker7$1);
var _a7$1;
var _b7$1;
var JSONParseError$2 = class extends (_b7$1 = AISDKError$2, _a7$1 = symbol7$1, _b7$1) {
constructor({ text, cause }) {
super({
name: name6$1,
message: `JSON parsing failed: Text: ${text}.
Error message: ${getErrorMessage$2(cause)}`,
cause
});
this[_a7$1] = true;
this.text = text;
}
static isInstance(error) {
return AISDKError$2.hasMarker(error, marker7$1);
}
};
var name7$1 = "AI_LoadAPIKeyError";
var marker8$1 = `vercel.ai.error.${name7$1}`;
var symbol8$1 = Symbol.for(marker8$1);
var _a8$1;
var _b8$1;
var LoadAPIKeyError$2 = class extends (_b8$1 = AISDKError$2, _a8$1 = symbol8$1, _b8$1) {
constructor({ message }) {
super({
name: name7$1,
message
});
this[_a8$1] = true;
}
static isInstance(error) {
return AISDKError$2.hasMarker(error, marker8$1);
}
};
var name10 = "AI_NoSuchModelError";
var marker11 = `vercel.ai.error.${name10}`;
var symbol11 = Symbol.for(marker11);
var _a11;
var _b11;
var NoSuchModelError$1 = class extends (_b11 = AISDKError$2, _a11 = symbol11, _b11) {
constructor({ errorName = name10, modelId, modelType, message = `No such ${modelType}: ${modelId}` }) {
super({
name: errorName,
message
});
this[_a11] = true;
this.modelId = modelId;
this.modelType = modelType;
}
static isInstance(error) {
return AISDKError$2.hasMarker(error, marker11);
}
};
var name11 = "AI_TooManyEmbeddingValuesForCallError";
var marker12 = `vercel.ai.error.${name11}`;
var symbol12 = Symbol.for(marker12);
var _a12;
var _b12;
var TooManyEmbeddingValuesForCallError$1 = class extends (_b12 = AISDKError$2, _a12 = symbol12, _b12) {
constructor(options) {
super({
name: name11,
message: `Too many values for a single embedding call. The ${options.provider} model "${options.modelId}" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`
});
this[_a12] = true;
this.provider = options.provider;
this.modelId = options.modelId;
this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;
this.values = options.values;
}
static isInstance(error) {
return AISDKError$2.hasMarker(error, marker12);
}
};
var name12$1 = "AI_TypeValidationError";
var marker13$1 = `vercel.ai.error.${name12$1}`;
var symbol13$1 = Symbol.for(marker13$1);
var _a13$1;
var _b13$1;
var TypeValidationError$2 = class _TypeValidationError extends (_b13$1 = AISDKError$2, _a13$1 = symbol13$1, _b13$1) {
constructor({ value, cause, context }) {
let contextPrefix = "Type validation failed";
if (context == null ? void 0 : context.field) contextPrefix += ` for ${context.field}`;
if ((context == null ? void 0 : context.entityName) || (context == null ? void 0 : context.entityId)) {
contextPrefix += " (";
const parts = [];
if (context.entityName) parts.push(context.entityName);
if (context.entityId) parts.push(`id: "${context.entityId}"`);
contextPrefix += parts.join(", ");
contextPrefix += ")";
}
super({
name: name12$1,
message: `${contextPrefix}: Value: ${JSON.stringify(value)}.
Error message: ${getErrorMessage$2(cause)}`,
cause
});
this[_a13$1] = true;
this.value = value;
this.context = context;
}
static isInstance(error) {
return AISDKError$2.hasMarker(error, marker13$1);
}
/**
* Wraps an error into a TypeValidationError.
* If the cause is already a TypeValidationError with the same value and context, it returns the cause.
* Otherwise, it creates a new TypeValidationError.
*
* @param {Object} params - The parameters for wrapping the error.
* @param {unknown} params.value - The value that failed validation.
* @param {unknown} params.cause - The original error or cause of the validation failure.
* @param {TypeValidationContext} params.context - Optional context about what is being validated.
* @returns {TypeValidationError} A TypeValidationError instance.
*/
static wrap({ value, cause, context }) {
var _a15, _b15, _c;
if (_TypeValidationError.isInstance(cause) && cause.value === value && ((_a15 = cause.context) == null ? void 0 : _a15.field) === (context == null ? void 0 : context.field) && ((_b15 = cause.context) == null ? void 0 : _b15.entityName) === (context == null ? void 0 : context.entityName) && ((_c = cause.context) == null ? void 0 : _c.entityId) === (context == null ? void 0 : context.entityId)) return cause;
return new _TypeValidationError({
value,
cause,
context
});
}
};
var name13$1 = "AI_UnsupportedFunctionalityError";
var marker14$1 = `vercel.ai.error.${name13$1}`;
var symbol14$1 = Symbol.for(marker14$1);
var _a14$1;
var _b14$1;
var UnsupportedFunctionalityError$2 = class extends (_b14$1 = AISDKError$2, _a14$1 = symbol14$1, _b14$1) {
constructor({ functionality, message = `'${functionality}' functionality not supported.` }) {
super({
name: name13$1,
message
});
this[_a14$1] = true;
this.functionality = functionality;
}
static isInstance(error) {
return AISDKError$2.hasMarker(error, marker14$1);
}
};
function isJSONValue(value) {
if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") return true;
if (Array.isArray(value)) return value.every(isJSONValue);
if (typeof value === "object") return Object.entries(value).every(([key, val]) => typeof key === "string" && (val === void 0 || isJSONValue(val)));
return false;
}
function isJSONObject(value) {
return value != null && typeof value === "object" && Object.entries(value).every(([key, val]) => typeof key === "string" && (val === void 0 || isJSONValue(val)));
}
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/eventsource-parser/3.1.1/e30f67b0ff61a3a3a39b8308894e655beffc18d0fdc6af8dfff3c5512ba88c3a/node_modules/eventsource-parser/dist/index.js
var ParseError$1 = class extends Error {
constructor(message, options) {
super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
}
};
const LF = 10;
const CR = 13;
const SPACE = 32;
function noop$1(_arg) {}
function createParser$1(config) {
if (typeof config == "function") throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");
const { onEvent = noop$1, onError = noop$1, onRetry = noop$1, onComment, maxBufferSize } = config, pendingFragments = [];
let pendingFragmentsLength = 0, isFirstChunk = !0, id, data = "", dataLines = 0, eventType, terminated = !1;
function feed(chunk) {
if (terminated) throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");
if (isFirstChunk && (isFirstChunk = !1, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
const trailing2 = processLines(chunk);
trailing2 !== "" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();
return;
}
if (chunk.indexOf(`
`) === -1 && chunk.indexOf("\r") === -1) {
pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();
return;
}
pendingFragments.push(chunk);
const input = pendingFragments.join("");
pendingFragments.length = 0, pendingFragmentsLength = 0;
const trailing = processLines(input);
trailing !== "" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();
}
function checkBufferSize() {
maxBufferSize !== void 0 && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = !0, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data = "", dataLines = 0, eventType = void 0, onError(new ParseError$1(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, { type: "max-buffer-size-exceeded" }))));
}
function processLines(chunk) {
let searchIndex = 0;
if (chunk.indexOf("\r") === -1) {
let lfIndex = chunk.indexOf(`
`, searchIndex);
for (; lfIndex !== -1;) {
if (searchIndex === lfIndex) {
dataLines > 0 && onEvent({
id,
event: eventType,
data
}), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
`, searchIndex);
continue;
}
const firstCharCode = chunk.charCodeAt(searchIndex);
if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
onEvent({
id,
event: eventType,
data: value
}), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
`, searchIndex);
continue;
}
data = dataLines === 0 ? value : `${data}
${value}`, dataLines++;
} else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6, lfIndex) || void 0 : parseLine(chunk, searchIndex, lfIndex);
searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
`, searchIndex);
}
return chunk.slice(searchIndex);
}
for (; searchIndex < chunk.length;) {
const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
`, searchIndex);
let lineEnd = -1;
if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) break;
parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
}
return chunk.slice(searchIndex);
}
function parseLine(chunk, start, end) {
if (start === end) {
dispatchEvent();
return;
}
const firstCharCode = chunk.charCodeAt(start);
if (isDataPrefix(chunk, start, firstCharCode)) {
const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
data = dataLines === 0 ? value2 : `${data}
${value2}`, dataLines++;
return;
}
if (isEventPrefix(chunk, start, firstCharCode)) {
eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
return;
}
if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
value2.includes("\0") || (id = value2);
return;
}
if (firstCharCode === 58) {
if (onComment) {
const line2 = chunk.slice(start, end);
onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
}
return;
}
const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
if (fieldSeparatorIndex === -1) {
processField(line, "", line);
return;
}
const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1;
processField(field, line.slice(fieldSeparatorIndex + offset), line);
}
function processField(field, value, line) {
switch (field) {
case "event":
eventType = value || void 0;
break;
case "data":
data = dataLines === 0 ? value : `${data}
${value}`, dataLines++;
break;
case "id":
value.includes("\0") || (id = value);
break;
case "retry":
/^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(new ParseError$1(`Invalid \`retry\` value: "${value}"`, {
type: "invalid-retry",
value,
line
}));
break;
default: onError(new ParseError$1(`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, {
type: "unknown-field",
field,
value,
line
}));
}
}
function dispatchEvent() {
dataLines > 0 && onEvent({
id,
event: eventType,
data
}), id = void 0, data = "", dataLines = 0, eventType = void 0;
}
function reset(options = {}) {
if (options.consume && pendingFragments.length > 0) {
const incompleteLine = pendingFragments.join("");
parseLine(incompleteLine, 0, incompleteLine.length);
}
isFirstChunk = !0, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = !1;
}
return {
feed,
reset
};
}
function isDataPrefix(chunk, i, firstCharCode) {
return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
}
function isEventPrefix(chunk, i, firstCharCode) {
return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;
}
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/eventsource-parser/3.1.1/e30f67b0ff61a3a3a39b8308894e655beffc18d0fdc6af8dfff3c5512ba88c3a/node_modules/eventsource-parser/dist/stream.js
var EventSourceParserStream$1 = class extends TransformStream {
constructor({ onError, onRetry, onComment, maxBufferSize } = {}) {
let parser;
super({
start(controller) {
parser = createParser$1({
onEvent: (event) => {
controller.enqueue(event);
},
onError(error) {
typeof onError == "function" && onError(error), (onError === "terminate" || error.type === "max-buffer-size-exceeded") && controller.error(error);
},
onRetry,
onComment,
maxBufferSize
});
},
transform(chunk) {
parser.feed(chunk);
}
});
}
};
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/provider-utils/4.0.66/b622c802b4d37b51174bde15e2479e370e993113aea38fb145ab9dcdcb4e96fb/node_modules/@ai-sdk/provider-utils/dist/index.mjs
function combineHeaders$2(...headers) {
return headers.reduce((combinedHeaders, currentHeaders) => ({
...combinedHeaders,
...currentHeaders
}), {});
}
function createToolNameMapping({ tools = [], providerToolNames, resolveProviderToolName }) {
var _a2;
const customToolNameToProviderToolName = {};
const providerToolNameToCustomToolName = {};
for (const tool2 of tools) if (tool2.type === "provider") {
const providerToolName = (_a2 = resolveProviderToolName == null ? void 0 : resolveProviderToolName(tool2)) != null ? _a2 : tool2.id in providerToolNames ? providerToolNames[tool2.id] : void 0;
if (providerToolName == null) continue;
customToolNameToProviderToolName[tool2.name] = providerToolName;
providerToolNameToCustomToolName[providerToolName] = tool2.name;
}
return {
toProviderToolName: (customToolName) => {
var _a3;
return (_a3 = customToolNameToProviderToolName[customToolName]) != null ? _a3 : customToolName;
},
toCustomToolName: (providerToolName) => {
var _a3;
return (_a3 = providerToolNameToCustomToolName[providerToolName]) != null ? _a3 : providerToolName;
}
};
}
async function delay$2(delayInMs, options) {
if (delayInMs == null) return;
const signal = options == null ? void 0 : options.abortSignal;
return new Promise((resolve2, reject) => {
if (signal == null ? void 0 : signal.aborted) {
reject(createAbortError$2());
return;
}
const timeoutId = setTimeout(() => {
cleanup();
resolve2();
}, delayInMs);
const cleanup = () => {
clearTimeout(timeoutId);
signal?.removeEventListener("abort", onAbort);
};
const onAbort = () => {
cleanup();
reject(createAbortError$2());
};
signal?.addEventListener("abort", onAbort);
});
}
function createAbortError$2() {
return new DOMException("Delay was aborted", "AbortError");
}
function extractResponseHeaders$2(response) {
return Object.fromEntries([...response.headers]);
}
var { btoa: btoa$2, atob: atob$2 } = globalThis;
function convertBase64ToUint8Array$1(base64String) {
const latin1string = atob$2(base64String.replace(/-/g, "+").replace(/_/g, "/"));
const bytes = new Uint8Array(latin1string.length);
for (let i = 0; i < latin1string.length; i++) bytes[i] = latin1string.charCodeAt(i);
return bytes;
}
function convertUint8ArrayToBase64$2(array) {
var _a2;
if (typeof ((_a2 = globalThis.Buffer) == null ? void 0 : _a2.from) === "function") return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString("base64");
const chunks = [];
const chunkSize = 4096;
for (let i = 0; i < array.length; i += chunkSize) chunks.push(String.fromCodePoint(...array.subarray(i, i + chunkSize)));
return btoa$2(chunks.join(""));
}
var typedArrayTag$1 = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
function isUint8Array$1(value) {
return ArrayBuffer.isView(value) && typedArrayTag$1.call(value) === "Uint8Array";
}
function convertToBase64$1(value) {
return isUint8Array$1(value) ? convertUint8ArrayToBase64$2(value) : value;
}
function convertToFormData$1(input, options = {}) {
const { useArrayBrackets = true } = options;
const formData = new FormData();
for (const [key, value] of Object.entries(input)) {
if (value == null) continue;
if (Array.isArray(value)) {
if (value.length === 1) {
formData.append(key, value[0]);
continue;
}
const arrayKey = useArrayBrackets ? `${key}[]` : key;
for (const item of value) formData.append(arrayKey, item);
continue;
}
formData.append(key, value);
}
return formData;
}
async function cancelResponseBody$1(response) {
var _a2;
try {
await ((_a2 = response.body) == null ? void 0 : _a2.cancel());
} catch (e) {}
}
var name$13 = "AI_DownloadError";
var marker$5 = `vercel.ai.error.${name$13}`;
var symbol$5 = Symbol.for(marker$5);
var _a$3;
var _b$1;
var DownloadError$1 = class extends (_b$1 = AISDKError$2, _a$3 = symbol$5, _b$1) {
constructor({ url, statusCode, statusText, cause, message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}` }) {
super({
name: name$13,
message,
cause
});
this[_a$3] = true;
this.url = url;
this.statusCode = statusCode;
this.statusText = statusText;
}
static isInstance(error) {
return AISDKError$2.hasMarker(error, marker$5);
}
};
function isBrowserRuntime$1(globalThisAny = globalThis) {
return globalThisAny.window != null;
}
function isSameOrigin$1(url, baseUrl) {
try {
return new URL(url).origin === new URL(baseUrl).origin;
} catch (e) {
return false;
}
}
function validateDownloadUrl$1(url) {
let parsed;
try {
parsed = new URL(url);
} catch (e) {
throw new DownloadError$1({
url,
message: `Invalid URL: ${url}`
});
}
if (parsed.protocol === "data:") return;
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new DownloadError$1({
url,
message: `URL scheme must be http, https, or data, got ${parsed.protocol}`
});
const hostname = parsed.hostname.toLowerCase().replace(/\.+$/, "");
if (!hostname) throw new DownloadError$1({
url,
message: `URL must have a hostname`
});
if (hostname === "localhost" || hostname.endsWith(".local") || hostname.endsWith(".localhost") || hostname.endsWith(".internal")) throw new DownloadError$1({
url,
message: `URL with hostname ${hostname} is not allowed`
});
if (hostname.startsWith("[") && hostname.endsWith("]")) {
if (isPrivateIPv6$1(hostname.slice(1, -1))) throw new DownloadError$1({
url,
message: `URL with IPv6 address ${hostname} is not allowed`
});
return;
}
if (isIPv4$1(hostname)) {
if (isPrivateIPv4$1(hostname)) throw new DownloadError$1({
url,
message: `URL with IP address ${hostname} is not allowed`
});
}
}
function validateDownloadAddress({ address, family, hostname }) {
if (family === 4 ? !isIPv4$1(address) || isPrivateIPv4$1(address) : family === 6 ? isPrivateIPv6$1(address) : true) throw new DownloadError$1({
url: hostname,
message: `Hostname ${hostname} resolved to disallowed IP address ${address}`
});
}
function isIPv4$1(hostname) {
const parts = hostname.split(".");
if (parts.length !== 4) return false;
return parts.every((part) => {
const num = Number(part);
return Number.isInteger(num) && num >= 0 && num <= 255 && String(num) === part;
});
}
function isPrivateIPv4$1(ip) {
const [a, b, c] = ip.split(".").map(Number);
if (a === 0) return true;
if (a === 10) return true;
if (a === 100 && b >= 64 && b <= 127) return true;
if (a === 127) return true;
if (a === 169 && b === 254) return true;
if (a === 172 && b >= 16 && b <= 31) return true;
if (a === 192 && b === 0 && c === 0) return true;
if (a === 192 && b === 168) return true;
if (a === 198 && (b === 18 || b === 19)) return true;
if (a >= 240) return true;
return false;
}
function parseIPv6$1(ip) {
let address = ip.toLowerCase();
const zoneIndex = address.indexOf("%");
if (zoneIndex !== -1) address = address.slice(0, zoneIndex);
const halves = address.split("::");
if (halves.length > 2) return null;
const toGroups = (segment) => {
if (segment === "") return [];
const groups = [];
const parts = segment.split(":");
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (part.includes(".")) {
if (i !== parts.length - 1 || !isIPv4$1(part)) return null;
const [a, b, c, d] = part.split(".").map(Number);
groups.push(a << 8 | b, c << 8 | d);
continue;
}
if (!/^[0-9a-f]{1,4}$/.test(part)) return null;
groups.push(parseInt(part, 16));
}
return groups;
};
const head = toGroups(halves[0]);
if (head === null) return null;
if (halves.length === 2) {
const tail = toGroups(halves[1]);
if (tail === null) return null;
const fill = 8 - head.length - tail.length;
if (fill < 0) return null;
return [
...head,
...new Array(fill).fill(0),
...tail
];
}
return head.length === 8 ? head : null;
}
function isPrivateIPv6$1(ip) {
const groups = parseIPv6$1(ip);
if (groups === null) return true;
const topZero = (count) => groups.slice(0, count).every((group) => group === 0);
if (topZero(7) && (groups[7] === 0 || groups[7] === 1)) return true;
if ((groups[0] & 65024) === 64512) return true;
if ((groups[0] & 65472) === 65152) return true;
if ((groups[0] & 65472) === 65216) return true;
if ((groups[0] & 65280) === 65280) return true;
if (topZero(6) || topZero(5) && groups[5] === 65535 || topZero(4) && groups[4] === 65535 && groups[5] === 0 || groups[0] === 100 && groups[1] === 65435 && groups[2] === 0 && groups[3] === 0 && groups[4] === 0 && groups[5] === 0 || groups[0] === 100 && groups[1] === 65435 && groups[2] === 1) return isPrivateIPv4$1(`${groups[6] >> 8 & 255}.${groups[6] & 255}.${groups[7] >> 8 & 255}.${groups[7] & 255}`);
return false;
}
function createSafeLookup(lookup) {
return ((hostname, options, callback) => {
lookup(hostname, {
...options,
all: true
}, (error, addresses) => {
if (error) {
callback(error);
return;
}
try {
const [firstAddress] = addresses;
if (firstAddress == null) throw new Error(`Hostname ${hostname} did not resolve to an address`);
for (const { address, family } of addresses) validateDownloadAddress({
address,
family,
hostname
});
if (options.all === true) callback(null, addresses);
else callback(null, firstAddress.address, firstAddress.family);
} catch (error2) {
callback(error2 instanceof Error ? error2 : new Error(String(error2)));
}
});
});
}
var safeNodeFetchPromise;
function isNodeRuntime() {
var _a2, _b2, _c;
const runtimeProcess = globalThis.process;
return ((_a2 = runtimeProcess == null ? void 0 : runtimeProcess.release) == null ? void 0 : _a2.name) === "node" && ((_b2 = runtimeProcess.versions) == null ? void 0 : _b2.bun) == null && ((_c = runtimeProcess.versions) == null ? void 0 : _c.deno) == null && runtimeProcess.title !== "workerd" && globalThis.EdgeRuntime == null;
}
async function getDefaultDownloadFetch() {
if (!isNodeRuntime()) return globalThis.fetch;
return safeNodeFetchPromise != null ? safeNodeFetchPromise : safeNodeFetchPromise = createSafeNodeFetch();
}
async function createSafeNodeFetch() {
const [module, { lookup }] = await Promise.all([loadNodeModule("node:module"), loadNodeModule("node:dns")]);
const { Agent, fetch } = module.createRequire(getCurrentModulePath())("undici");
const dispatcher = new Agent({ connect: { lookup: createSafeLookup(lookup) } });
return ((input, init) => fetch(input, {
...init,
dispatcher
}));
}
async function loadNodeModule(id) {
var _a2;
const processWithBuiltins = globalThis.process;
const builtinModule = (_a2 = processWithBuiltins == null ? void 0 : processWithBuiltins.getBuiltinModule) == null ? void 0 : _a2.call(processWithBuiltins, id);
if (builtinModule == null) throw new Error(`Node.js built-in module ${id} is unavailable`);
return builtinModule;
}
function getCurrentModulePath() {
const originalPrepareStackTrace = Error.prepareStackTrace;
try {
Error.prepareStackTrace = (_error, callSites) => callSites;
const error = /* @__PURE__ */ new Error("Capture current module path");
Error.captureStackTrace(error, getCurrentModulePath);
const [caller] = error.stack;
const fileName = caller == null ? void 0 : caller.getFileName();
if (fileName == null) throw new Error("Unable to determine the current module path");
return fileName;
} finally {
Error.prepareStackTrace = originalPrepareStackTrace;
}
}
var BLOCKED_REQUEST_HEADERS$1 = [
"connection",
"keep-alive",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"host",
"forwarded",
"proxy-authorization",
"via",
"x-forwarded-for",
"x-forwarded-host",
"x-forwarded-proto",
"x-real-ip",
"metadata",
"metadata-flavor",
"x-aws-ec2-metadata-token",
"x-metadata-token",
"cookie",
"set-cookie"
];
function sanitizeRequestHeaders$1(input) {
const headers = new Headers(input);
for (const name2 of BLOCKED_REQUEST_HEADERS$1) headers.delete(name2);
return headers;
}
var MAX_DOWNLOAD_REDIRECTS$1 = 10;
var REDIRECT_STATUS_CODES$1 = /* @__PURE__ */ new Set([
301,
302,
303,
307,
308
]);
async function getValidatedFetch(customFetch) {
return customFetch == null || customFetch === globalThis.fetch ? await getDefaultDownloadFetch() : customFetch;
}
async function fetchWithValidatedRedirects$1({ url, headers, abortSignal, maxRedirects = MAX_DOWNLOAD_REDIRECTS$1, fetch: customFetch, trustedOrigin }) {
var _a2;
let currentHeaders = headers === void 0 ? void 0 : sanitizeRequestHeaders$1(headers);
const perHopInit = (redirect) => {
const init = {
signal: abortSignal,
redirect
};
if (currentHeaders !== void 0) init.headers = new Headers(currentHeaders);
return init;
};
let currentUrl = url;
for (let redirectCount = 0; redirectCount <= maxRedirects; redirectCount++) {
const isTrustedHop = trustedOrigin !== void 0 && isSameOrigin$1(currentUrl, trustedOrigin);
if (!isTrustedHop) validateDownloadUrl$1(currentUrl);
const fetch = isTrustedHop && customFetch != null ? customFetch : isTrustedHop ? globalThis.fetch : await getValidatedFetch(customFetch);
const response = await fetch(currentUrl, perHopInit("manual"));
if (response.type === "opaqueredirect") {
if (!isBrowserRuntime$1()) throw new DownloadError$1({
url,
message: `Redirect from ${currentUrl} could not be validated and was blocked`
});
return await fetch(currentUrl, perHopInit("follow"));
}
const location = (_a2 = response.headers) == null ? void 0 : _a2.get("location");
if (REDIRECT_STATUS_CODES$1.has(response.status) && location) {
cancelResponseBody$1(response);
const nextUrl = new URL(location, currentUrl).toString();
if (new URL(currentUrl).protocol === "https:" && new URL(nextUrl).protocol === "http:") throw new DownloadError$1({
url,
message: "Redirect from HTTPS to HTTP was blocked"
});
if (currentHeaders !== void 0 && !isSameOrigin$1(nextUrl, currentUrl)) {
const userAgent = currentHeaders.get("user-agent");
currentHeaders = new Headers(userAgent == null ? void 0 : { "user-agent": userAgent });
}
currentUrl = nextUrl;
continue;
}
return response;
}
throw new DownloadError$1({
url,
message: `Too many redirects (max ${maxRedirects})`
});
}
var DEFAULT_MAX_DOWNLOAD_SIZE$1 = 2147483648;
async function readResponseWithSizeLimit$1({ response, url, maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE$1 }) {
const contentLength = response.headers.get("content-length");
if (contentLength != null) {
const length = parseInt(contentLength, 10);
if (!isNaN(length) && length > maxBytes) {
await cancelResponseBody$1(response);
throw new DownloadError$1({
url,
message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes (Content-Length: ${length}).`
});
}
}
const body = response.body;
if (body == null) return /* @__PURE__ */ new Uint8Array(0);
const reader = body.getReader();
const chunks = [];
let totalBytes = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
totalBytes += value.length;
if (totalBytes > maxBytes) throw new DownloadError$1({
url,
message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.`
});
chunks.push(value);
}
} finally {
try {
await reader.cancel();
} catch (e) {} finally {
reader.releaseLock();
}
}
const result = new Uint8Array(totalBytes);
let offset = 0;
for (const chunk of chunks) {
result.set(chunk, offset);
offset += chunk.length;
}
return result;
}
async function downloadBlob$1(url, options) {
var _a2, _b2;
try {
const response = await fetchWithValidatedRedirects$1({
url,
abortSignal: options == null ? void 0 : options.abortSignal
});
if (!response.ok) {
await cancelResponseBody$1(response);
throw new DownloadError$1({
url,
statusCode: response.status,
statusText: response.statusText
});
}
const data = await readResponseWithSizeLimit$1({
response,
url,
maxBytes: (_a2 = options == null ? void 0 : options.maxBytes) != null ? _a2 : DEFAULT_MAX_DOWNLOAD_SIZE$1
});
const contentType = (_b2 = response.headers.get("content-type")) != null ? _b2 : void 0;
return new Blob([data], contentType ? { type: contentType } : void 0);
} catch (error) {
if (DownloadError$1.isInstance(error)) throw error;
throw new DownloadError$1({
url,
cause: error
});
}
}
var EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL = /* @__PURE__ */ Symbol.for("vercel.ai.embeddingModel.maxInputBytesPerCall");
var EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER = /* @__PURE__ */ Symbol.for("vercel.ai.embeddingModel.providerOptionsTransformer");
var createIdGenerator$2 = ({ prefix, size = 16, alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", separator = "-" } = {}) => {
const generator = () => {
const alphabetLength = alphabet.length;
const chars = new Array(size);
for (let i = 0; i < size; i++) chars[i] = alphabet[Math.random() * alphabetLength | 0];
return chars.join("");
};
if (prefix == null) return generator;
if (alphabet.includes(separator)) throw new InvalidArgumentError$2({
argument: "separator",
message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
});
return () => `${prefix}${separator}${generator()}`;
};
var generateId$2 = createIdGenerator$2();
function isAbortError$2(error) {
return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || error.name === "TimeoutError");
}
var FETCH_FAILED_ERROR_MESSAGES$2 = ["fetch failed", "failed to fetch"];
var RETRYABLE_NETWORK_ERROR_CODES$1 = /* @__PURE__ */ new Set([
"ConnectionRefused",
"ConnectionClosed",
"FailedToOpenSocket",
"ECONNRESET",
"ECONNREFUSED",
"ETIMEDOUT",
"EPIPE",
"UND_ERR_SOCKET",
"UND_ERR_HEADERS_TIMEOUT",
"UND_ERR_BODY_TIMEOUT",
"UND_ERR_CONNECT_TIMEOUT"
]);
function findNetworkError$1(error) {
const visited = /* @__PURE__ */ new Set();
let current = error;
while (current instanceof Error && !visited.has(current)) {
visited.add(current);
const errorWithCode = current;
if (typeof errorWithCode.code === "string" && RETRYABLE_NETWORK_ERROR_CODES$1.has(errorWithCode.code)) return errorWithCode;
current = current.cause;
}
}
function handleFetchError$2({ error, url, requestBodyValues }) {
if (isAbortError$2(error)) return error;
if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES$2.includes(error.message.toLowerCase())) {
const cause = error.cause;
if (cause != null) return new APICallError$2({
message: `Cannot connect to API: ${cause.message}`,
cause,
url,
requestBodyValues,
isRetryable: true
});
}
const networkError = findNetworkError$1(error);
if (networkError != null) {
if (APICallError$2.isInstance(error)) return new APICallError$2({
message: error.message,
cause: error.cause,
url: error.url,
requestBodyValues: error.requestBodyValues,
statusCode: error.statusCode,
responseHeaders: error.responseHeaders,
responseBody: error.responseBody,
data: error.data,
isRetryable: true
});
return new APICallError$2({
message: `Cannot connect to API: ${error instanceof Error ? error.message : networkError.message}`,
cause: error,
url,
requestBodyValues,
isRetryable: true
});
}
return error;
}
function getRuntimeEnvironmentUserAgent$2(globalThisAny = globalThis) {
var _a2, _b2, _c;
if (globalThisAny.window) return `runtime/browser`;
if ((_a2 = globalThisAny.navigator) == null ? void 0 : _a2.userAgent) return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
if ((_c = (_b2 = globalThisAny.process) == null ? void 0 : _b2.versions) == null ? void 0 : _c.node) return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
if (globalThisAny.EdgeRuntime) return `runtime/vercel-edge`;
return "runtime/unknown";
}
function normalizeHeaders$2(headers) {
if (headers == null) return {};
const normalized = {};
if (headers instanceof Headers) headers.forEach((value, key) => {
normalized[key.toLowerCase()] = value;
});
else {
if (!Array.isArray(headers)) headers = Object.entries(headers);
for (const [key, value] of headers) if (value != null) normalized[key.toLowerCase()] = value;
}
return normalized;
}
function withUserAgentSuffix$2(headers, ...userAgentSuffixParts) {
const normalizedHeaders = new Headers(normalizeHeaders$2(headers));
const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
normalizedHeaders.set("user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" "));
return Object.fromEntries(normalizedHeaders.entries());
}
var VERSION$15 = "4.0.66";
var getOriginalFetch$6 = () => globalThis.fetch;
var getFromApi$2 = async ({ url, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, validateUrl, credentialedOrigin, trustedOrigin }) => {
try {
const requestFetch = fetch != null ? fetch : getOriginalFetch$6();
const requestHeaders = withUserAgentSuffix$2(credentialedOrigin !== void 0 && !isSameOrigin$1(url, credentialedOrigin) ? {} : headers, `ai-sdk/provider-utils/${VERSION$15}`, getRuntimeEnvironmentUserAgent$2());
const response = validateUrl ? await fetchWithValidatedRedirects$1({
url,
headers: requestHeaders,
abortSignal,
fetch,
trustedOrigin
}) : await requestFetch(url, {
method: "GET",
headers: requestHeaders,
signal: abortSignal
});
const responseHeaders = extractResponseHeaders$2(response);
if (!response.ok) {
let errorInformation;
try {
errorInformation = await failedResponseHandler({
response,
url,
requestBodyValues: {}
});
} catch (error) {
if (isAbortError$2(error) || APICallError$2.isInstance(error)) throw error;
throw new APICallError$2({
message: "Failed to process error response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: {}
});
}
throw errorInformation.value;
}
try {
return await successfulResponseHandler({
response,
url,
requestBodyValues: {}
});
} catch (error) {
if (error instanceof Error) {
if (isAbortError$2(error) || APICallError$2.isInstance(error)) throw error;
}
throw new APICallError$2({
message: "Failed to process successful response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: {}
});
}
} catch (error) {
throw handleFetchError$2({
error,
url,
requestBodyValues: {}
});
}
};
var DEFAULT_SCHEMA_PREFIX$1 = "JSON schema:";
var DEFAULT_SCHEMA_SUFFIX$1 = "You MUST answer with a JSON object that matches the JSON schema above.";
var DEFAULT_GENERIC_SUFFIX$1 = "You MUST answer with JSON.";
function injectJsonInstruction$1({ prompt, schema, schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX$1 : void 0, schemaSuffix = schema != null ? DEFAULT_SCHEMA_SUFFIX$1 : DEFAULT_GENERIC_SUFFIX$1 }) {
return [
prompt != null && prompt.length > 0 ? prompt : void 0,
prompt != null && prompt.length > 0 ? "" : void 0,
schemaPrefix,
schema != null ? JSON.stringify(schema) : void 0,
schemaSuffix
].filter((line) => line != null).join("\n");
}
function injectJsonInstructionIntoMessages$1({ messages, schema, schemaPrefix, schemaSuffix }) {
var _a2, _b2;
const systemMessage = ((_a2 = messages[0]) == null ? void 0 : _a2.role) === "system" ? { ...messages[0] } : {
role: "system",
content: ""
};
systemMessage.content = injectJsonInstruction$1({
prompt: systemMessage.content,
schema,
schemaPrefix,
schemaSuffix
});
return [systemMessage, ...((_b2 = messages[0]) == null ? void 0 : _b2.role) === "system" ? messages.slice(1) : messages];
}
function isNonNullable(value) {
return value != null;
}
function isUrlSupported({ mediaType, url, supportedUrls }) {
mediaType = mediaType.toLowerCase();
return Object.entries(supportedUrls).map(([key, value]) => {
const mediaType2 = key.toLowerCase();
return mediaType2 === "*" || mediaType2 === "*/*" ? {
mediaTypePrefix: "",
regexes: value
} : {
mediaTypePrefix: mediaType2.replace(/\*/, ""),
regexes: value
};
}).filter(({ mediaTypePrefix }) => mediaTypePrefix === "" || mediaTypePrefix.endsWith("/") ? mediaType.startsWith(mediaTypePrefix) : mediaType === mediaTypePrefix).flatMap(({ regexes }) => regexes).some((pattern) => pattern.test(url));
}
function loadApiKey$2({ apiKey, environmentVariableName, apiKeyParameterName = "apiKey", description }) {
if (typeof apiKey === "string") return apiKey;
if (apiKey != null) throw new LoadAPIKeyError$2({ message: `${description} API key must be a string.` });
if (typeof process === "undefined") throw new LoadAPIKeyError$2({ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables are not supported in this environment.` });
apiKey = process.env[environmentVariableName];
if (apiKey == null) throw new LoadAPIKeyError$2({ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.` });
if (typeof apiKey !== "string") throw new LoadAPIKeyError$2({ message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.` });
return apiKey;
}
function loadOptionalSetting({ settingValue, environmentVariableName }) {
if (typeof settingValue === "string") return settingValue;
if (settingValue != null || typeof process === "undefined") return;
settingValue = process.env[environmentVariableName];
if (settingValue == null || typeof settingValue !== "string") return;
return settingValue;
}
function mediaTypeToExtension$1(mediaType) {
var _a2;
const [_type, subtype = ""] = mediaType.toLowerCase().split("/");
return (_a2 = {
mpeg: "mp3",
"x-wav": "wav",
opus: "ogg",
mp4: "m4a",
"x-m4a": "m4a"
}[subtype]) != null ? _a2 : subtype;
}
var suspectProtoRx$2 = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
var suspectConstructorRx$2 = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
function _parse$2(text) {
const obj = JSON.parse(text);
if (obj === null || typeof obj !== "object") return obj;
if (suspectProtoRx$2.test(text) === false && suspectConstructorRx$2.test(text) === false) return obj;
return filter$2(obj);
}
function filter$2(obj) {
let next = [obj];
while (next.length) {
const nodes = next;
next = [];
for (const node of nodes) {
if (Object.prototype.hasOwnProperty.call(node, "__proto__")) throw new SyntaxError("Object contains forbidden prototype property");
if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) throw new SyntaxError("Object contains forbidden prototype property");
for (const key in node) {
const value = node[key];
if (value && typeof value === "object") next.push(value);
}
}
}
return obj;
}
function secureJsonParse$2(text) {
const { stackTraceLimit } = Error;
try {
Error.stackTraceLimit = 0;
} catch (e) {
return _parse$2(text);
}
try {
return _parse$2(text);
} finally {
Error.stackTraceLimit = stackTraceLimit;
}
}
function addAdditionalPropertiesToJsonSchema$2(jsonSchema2) {
if (jsonSchema2.type === "object" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes("object")) {
const { additionalProperties } = jsonSchema2;
jsonSchema2.additionalProperties = additionalProperties != null && typeof additionalProperties !== "boolean" ? visit$2(additionalProperties) : false;
const { properties } = jsonSchema2;
if (properties != null) for (const key of Object.keys(properties)) properties[key] = visit$2(properties[key]);
}
if (jsonSchema2.items != null) jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit$2) : visit$2(jsonSchema2.items);
if (jsonSchema2.anyOf != null) jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit$2);
if (jsonSchema2.allOf != null) jsonSchema2.allOf = jsonSchema2.allOf.map(visit$2);
if (jsonSchema2.oneOf != null) jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit$2);
const { definitions } = jsonSchema2;
if (definitions != null) for (const key of Object.keys(definitions)) definitions[key] = visit$2(definitions[key]);
return jsonSchema2;
}
function visit$2(def) {
if (typeof def === "boolean") return def;
return addAdditionalPropertiesToJsonSchema$2(def);
}
var ignoreOverride$2 = /* @__PURE__ */ Symbol("Let zodToJsonSchema decide on which parser to use");
var defaultOptions$2 = {
name: void 0,
$refStrategy: "root",
basePath: ["#"],
effectStrategy: "input",
pipeStrategy: "all",
dateStrategy: "format:date-time",
mapStrategy: "entries",
removeAdditionalStrategy: "passthrough",
allowedAdditionalProperties: true,
rejectedAdditionalProperties: false,
definitionPath: "definitions",
strictUnions: false,
definitions: {},
errorMessages: false,
patternStrategy: "escape",
applyRegexFlags: false,
emailStrategy: "format:email",
base64Strategy: "contentEncoding:base64",
nameStrategy: "ref"
};
var getDefaultOptions$2 = (options) => typeof options === "string" ? {
...defaultOptions$2,
name: options
} : {
...defaultOptions$2,
...options
};
function parseAnyDef$2() {
return {};
}
function parseArrayDef$2(def, refs) {
var _a2, _b2, _c;
const res = { type: "array" };
if (((_a2 = def.type) == null ? void 0 : _a2._def) && ((_c = (_b2 = def.type) == null ? void 0 : _b2._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) res.items = parseDef$2(def.type._def, {
...refs,
currentPath: [...refs.currentPath, "items"]
});
if (def.minLength) res.minItems = def.minLength.value;
if (def.maxLength) res.maxItems = def.maxLength.value;
if (def.exactLength) {
res.minItems = def.exactLength.value;
res.maxItems = def.exactLength.value;
}
return res;
}
function parseBigintDef$2(def) {
const res = {
type: "integer",
format: "int64"
};
if (!def.checks) return res;
for (const check of def.checks) switch (check.kind) {
case "min":
if (check.inclusive) res.minimum = check.value;
else res.exclusiveMinimum = check.value;
break;
case "max":
if (check.inclusive) res.maximum = check.value;
else res.exclusiveMaximum = check.value;
break;
case "multipleOf": res.multipleOf = check.value;
}
return res;
}
function parseBooleanDef$2() {
return { type: "boolean" };
}
function parseBrandedDef$2(_def, refs) {
return parseDef$2(_def.type._def, refs);
}
var parseCatchDef$2 = (def, refs) => {
return parseDef$2(def.innerType._def, refs);
};
function parseDateDef$2(def, refs, overrideDateStrategy) {
const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
if (Array.isArray(strategy)) return { anyOf: strategy.map((item, i) => parseDateDef$2(def, refs, item)) };
switch (strategy) {
case "string":
case "format:date-time": return {
type: "string",
format: "date-time"
};
case "format:date": return {
type: "string",
format: "date"
};
case "integer": return integerDateParser$2(def);
}
}
var integerDateParser$2 = (def) => {
const res = {
type: "integer",
format: "unix-time"
};
for (const check of def.checks) switch (check.kind) {
case "min":
res.minimum = check.value;
break;
case "max": res.maximum = check.value;
}
return res;
};
function parseDefaultDef$2(_def, refs) {
return {
...parseDef$2(_def.innerType._def, refs),
default: _def.defaultValue()
};
}
function parseEffectsDef$2(_def, refs) {
return refs.effectStrategy === "input" ? parseDef$2(_def.schema._def, refs) : parseAnyDef$2();
}
function parseEnumDef$2(def) {
return {
type: "string",
enum: Array.from(def.values)
};
}
var isJsonSchema7AllOfType$2 = (type) => {
if ("type" in type && type.type === "string") return false;
return "allOf" in type;
};
function parseIntersectionDef$2(def, refs) {
const allOf = [parseDef$2(def.left._def, {
...refs,
currentPath: [
...refs.currentPath,
"allOf",
"0"
]
}), parseDef$2(def.right._def, {
...refs,
currentPath: [
...refs.currentPath,
"allOf",
"1"
]
})].filter((x) => !!x);
const mergedAllOf = [];
allOf.forEach((schema) => {
if (isJsonSchema7AllOfType$2(schema)) mergedAllOf.push(...schema.allOf);
else {
let nestedSchema = schema;
if ("additionalProperties" in schema && schema.additionalProperties === false) {
const { additionalProperties, ...rest } = schema;
nestedSchema = rest;
}
mergedAllOf.push(nestedSchema);
}
});
return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
}
function parseLiteralDef$2(def) {
const parsedType = typeof def.value;
if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") return { type: Array.isArray(def.value) ? "array" : "object" };
return {
type: parsedType === "bigint" ? "integer" : parsedType,
const: def.value
};
}
var emojiRegex$2 = void 0;
var zodPatterns$2 = {
/**
* `c` was changed to `[cC]` to replicate /i flag
*/
cuid: /^[cC][^\s-]{8,}$/,
cuid2: /^[0-9a-z]+$/,
ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
/**
* `a-z` was added to replicate /i flag
*/
email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9-]*\.)+[a-zA-Z]{2,}$/,
/**
* Constructed a valid Unicode RegExp
*
* Lazily instantiate since this type of regex isn't supported
* in all envs (e.g. React Native).
*
* See:
* https://github.com/colinhacks/zod/issues/2433
* Fix in Zod:
* https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
*/
emoji: () => {
if (emojiRegex$2 === void 0) emojiRegex$2 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
return emojiRegex$2;
},
/**
* Unused
*/
uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
/**
* Unused
*/
ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
/**
* Unused
*/
ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
nanoid: /^[a-zA-Z0-9_-]{21}$/,
jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
};
function parseStringDef$2(def, refs) {
const res = { type: "string" };
if (def.checks) for (const check of def.checks) switch (check.kind) {
case "min":
res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
break;
case "max":
res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
break;
case "email":
switch (refs.emailStrategy) {
case "format:email":
addFormat$2(res, "email", check.message, refs);
break;
case "format:idn-email":
addFormat$2(res, "idn-email", check.message, refs);
break;
case "pattern:zod": addPattern$2(res, zodPatterns$2.email, check.message, refs);
}
break;
case "url":
addFormat$2(res, "uri", check.message, refs);
break;
case "uuid":
addFormat$2(res, "uuid", check.message, refs);
break;
case "regex":
addPattern$2(res, check.regex, check.message, refs);
break;
case "cuid":
addPattern$2(res, zodPatterns$2.cuid, check.message, refs);
break;
case "cuid2":
addPattern$2(res, zodPatterns$2.cuid2, check.message, refs);
break;
case "startsWith":
addPattern$2(res, RegExp(`^${escapeLiteralCheckValue$2(check.value, refs)}`), check.message, refs);
break;
case "endsWith":
addPattern$2(res, RegExp(`${escapeLiteralCheckValue$2(check.value, refs)}$`), check.message, refs);
break;
case "datetime":
addFormat$2(res, "date-time", check.message, refs);
break;
case "date":
addFormat$2(res, "date", check.message, refs);
break;
case "time":
addFormat$2(res, "time", check.message, refs);
break;
case "duration":
addFormat$2(res, "duration", check.message, refs);
break;
case "length":
res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
break;
case "includes":
addPattern$2(res, RegExp(escapeLiteralCheckValue$2(check.value, refs)), check.message, refs);
break;
case "ip":
if (check.version !== "v6") addFormat$2(res, "ipv4", check.message, refs);
if (check.version !== "v4") addFormat$2(res, "ipv6", check.message, refs);
break;
case "base64url":
addPattern$2(res, zodPatterns$2.base64url, check.message, refs);
break;
case "jwt":
addPattern$2(res, zodPatterns$2.jwt, check.message, refs);
break;
case "cidr":
if (check.version !== "v6") addPattern$2(res, zodPatterns$2.ipv4Cidr, check.message, refs);
if (check.version !== "v4") addPattern$2(res, zodPatterns$2.ipv6Cidr, check.message, refs);
break;
case "emoji":
addPattern$2(res, zodPatterns$2.emoji(), check.message, refs);
break;
case "ulid":
addPattern$2(res, zodPatterns$2.ulid, check.message, refs);
break;
case "base64":
switch (refs.base64Strategy) {
case "format:binary":
addFormat$2(res, "binary", check.message, refs);
break;
case "contentEncoding:base64":
res.contentEncoding = "base64";
break;
case "pattern:zod": addPattern$2(res, zodPatterns$2.base64, check.message, refs);
}
break;
case "nanoid": addPattern$2(res, zodPatterns$2.nanoid, check.message, refs);
}
return res;
}
function escapeLiteralCheckValue$2(literal, refs) {
return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric$2(literal) : literal;
}
var ALPHA_NUMERIC$2 = /* @__PURE__ */ new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
function escapeNonAlphaNumeric$2(source) {
let result = "";
for (let i = 0; i < source.length; i++) {
if (!ALPHA_NUMERIC$2.has(source[i])) result += "\\";
result += source[i];
}
return result;
}
function addFormat$2(schema, value, message, refs) {
var _a2;
if (schema.format || ((_a2 = schema.anyOf) == null ? void 0 : _a2.some((x) => x.format))) {
if (!schema.anyOf) schema.anyOf = [];
if (schema.format) {
schema.anyOf.push({ format: schema.format });
delete schema.format;
}
schema.anyOf.push({
format: value,
...message && refs.errorMessages && { errorMessage: { format: message } }
});
} else schema.format = value;
}
function addPattern$2(schema, regex, message, refs) {
var _a2;
if (schema.pattern || ((_a2 = schema.allOf) == null ? void 0 : _a2.some((x) => x.pattern))) {
if (!schema.allOf) schema.allOf = [];
if (schema.pattern) {
schema.allOf.push({ pattern: schema.pattern });
delete schema.pattern;
}
schema.allOf.push({
pattern: stringifyRegExpWithFlags$2(regex, refs),
...message && refs.errorMessages && { errorMessage: { pattern: message } }
});
} else schema.pattern = stringifyRegExpWithFlags$2(regex, refs);
}
function stringifyRegExpWithFlags$2(regex, refs) {
var _a2;
if (!refs.applyRegexFlags || !regex.flags) return regex.source;
const flags = {
i: regex.flags.includes("i"),
m: regex.flags.includes("m"),
s: regex.flags.includes("s")
};
const source = flags.i ? regex.source.toLowerCase() : regex.source;
let pattern = "";
let isEscaped = false;
let inCharGroup = false;
let inCharRange = false;
for (let i = 0; i < source.length; i++) {
if (isEscaped) {
pattern += source[i];
isEscaped = false;
continue;
}
if (flags.i) {
if (inCharGroup) {
if (source[i].match(/[a-z]/)) {
if (inCharRange) {
pattern += source[i];
pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
inCharRange = false;
} else if (source[i + 1] === "-" && ((_a2 = source[i + 2]) == null ? void 0 : _a2.match(/[a-z]/))) {
pattern += source[i];
inCharRange = true;
} else pattern += `${source[i]}${source[i].toUpperCase()}`;
continue;
}
} else if (source[i].match(/[a-z]/)) {
pattern += `[${source[i]}${source[i].toUpperCase()}]`;
continue;
}
}
if (flags.m) {
if (source[i] === "^") {
pattern += `(^|(?<=[\r
]))`;
continue;
} else if (source[i] === "$") {
pattern += `($|(?=[\r
]))`;
continue;
}
}
if (flags.s && source[i] === ".") {
pattern += inCharGroup ? `${source[i]}\r
` : `[${source[i]}\r
]`;
continue;
}
pattern += source[i];
if (source[i] === "\\") isEscaped = true;
else if (inCharGroup && source[i] === "]") inCharGroup = false;
else if (!inCharGroup && source[i] === "[") inCharGroup = true;
}
try {
new RegExp(pattern);
} catch (e) {
console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
return regex.source;
}
return pattern;
}
function parseRecordDef$2(def, refs) {
var _a2, _b2, _c, _d, _e, _f;
const schema = {
type: "object",
additionalProperties: (_a2 = parseDef$2(def.valueType._def, {
...refs,
currentPath: [...refs.currentPath, "additionalProperties"]
})) != null ? _a2 : refs.allowedAdditionalProperties
};
if (((_b2 = def.keyType) == null ? void 0 : _b2._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
const { type, ...keyType } = parseStringDef$2(def.keyType._def, refs);
return {
...schema,
propertyNames: keyType
};
} else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind.ZodEnum) return {
...schema,
propertyNames: { enum: def.keyType._def.values }
};
else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
const { type, ...keyType } = parseBrandedDef$2(def.keyType._def, refs);
return {
...schema,
propertyNames: keyType
};
}
return schema;
}
function parseMapDef$2(def, refs) {
if (refs.mapStrategy === "record") return parseRecordDef$2(def, refs);
return {
type: "array",
maxItems: 125,
items: {
type: "array",
items: [parseDef$2(def.keyType._def, {
...refs,
currentPath: [
...refs.currentPath,
"items",
"items",
"0"
]
}) || parseAnyDef$2(), parseDef$2(def.valueType._def, {
...refs,
currentPath: [
...refs.currentPath,
"items",
"items",
"1"
]
}) || parseAnyDef$2()],
minItems: 2,
maxItems: 2
}
};
}
function parseNativeEnumDef$2(def) {
const object = def.values;
const actualValues = Object.keys(def.values).filter((key) => {
return typeof object[object[key]] !== "number";
}).map((key) => object[key]);
const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
return {
type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
enum: actualValues
};
}
function parseNeverDef$2() {
return { not: parseAnyDef$2() };
}
function parseNullDef$2() {
return { type: "null" };
}
var primitiveMappings$2 = {
ZodString: "string",
ZodNumber: "number",
ZodBigInt: "integer",
ZodBoolean: "boolean",
ZodNull: "null"
};
function parseUnionDef$2(def, refs) {
const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
if (options.every((x) => x._def.typeName in primitiveMappings$2 && (!x._def.checks || !x._def.checks.length))) {
const types = options.reduce((types2, x) => {
const type = primitiveMappings$2[x._def.typeName];
return type && !types2.includes(type) ? [...types2, type] : types2;
}, []);
return { type: types.length > 1 ? types : types[0] };
} else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
const types = options.reduce((acc, x) => {
const type = typeof x._def.value;
switch (type) {
case "string":
case "number":
case "boolean": return [...acc, type];
case "bigint": return [...acc, "integer"];
case "object": if (x._def.value === null) return [...acc, "null"];
default: return acc;
}
}, []);
if (types.length === options.length) {
const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
return {
type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
enum: options.reduce((acc, x) => {
return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
}, [])
};
}
} else if (options.every((x) => x._def.typeName === "ZodEnum")) return {
type: "string",
enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x2) => !acc.includes(x2))], [])
};
return asAnyOf$2(def, refs);
}
var asAnyOf$2 = (def, refs) => {
const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef$2(x._def, {
...refs,
currentPath: [
...refs.currentPath,
"anyOf",
`${i}`
]
})).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
return anyOf.length ? { anyOf } : void 0;
};
function parseNullableDef$2(def, refs) {
if ([
"ZodString",
"ZodNumber",
"ZodBigInt",
"ZodBoolean",
"ZodNull"
].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) return { type: [primitiveMappings$2[def.innerType._def.typeName], "null"] };
const base = parseDef$2(def.innerType._def, {
...refs,
currentPath: [
...refs.currentPath,
"anyOf",
"0"
]
});
return base && { anyOf: [base, { type: "null" }] };
}
function parseNumberDef$2(def) {
const res = { type: "number" };
if (!def.checks) return res;
for (const check of def.checks) switch (check.kind) {
case "int":
res.type = "integer";
break;
case "min":
if (check.inclusive) res.minimum = check.value;
else res.exclusiveMinimum = check.value;
break;
case "max":
if (check.inclusive) res.maximum = check.value;
else res.exclusiveMaximum = check.value;
break;
case "multipleOf": res.multipleOf = check.value;
}
return res;
}
function parseObjectDef$2(def, refs) {
const result = {
type: "object",
properties: {}
};
const required = [];
const shape = def.shape();
for (const propName in shape) {
let propDef = shape[propName];
if (propDef === void 0 || propDef._def === void 0) continue;
const propOptional = safeIsOptional$2(propDef);
const parsedDef = parseDef$2(propDef._def, {
...refs,
currentPath: [
...refs.currentPath,
"properties",
propName
],
propertyPath: [
...refs.currentPath,
"properties",
propName
]
});
if (parsedDef === void 0) continue;
result.properties[propName] = parsedDef;
if (!propOptional) required.push(propName);
}
if (required.length) result.required = required;
const additionalProperties = decideAdditionalProperties$2(def, refs);
if (additionalProperties !== void 0) result.additionalProperties = additionalProperties;
return result;
}
function decideAdditionalProperties$2(def, refs) {
if (def.catchall._def.typeName !== "ZodNever") return parseDef$2(def.catchall._def, {
...refs,
currentPath: [...refs.currentPath, "additionalProperties"]
});
switch (def.unknownKeys) {
case "passthrough": return refs.allowedAdditionalProperties;
case "strict": return refs.rejectedAdditionalProperties;
case "strip": return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
}
}
function safeIsOptional$2(schema) {
try {
return schema.isOptional();
} catch (e) {
return true;
}
}
var parseOptionalDef$2 = (def, refs) => {
var _a2;
if (refs.currentPath.toString() === ((_a2 = refs.propertyPath) == null ? void 0 : _a2.toString())) return parseDef$2(def.innerType._def, refs);
const innerSchema = parseDef$2(def.innerType._def, {
...refs,
currentPath: [
...refs.currentPath,
"anyOf",
"1"
]
});
return innerSchema ? { anyOf: [{ not: parseAnyDef$2() }, innerSchema] } : parseAnyDef$2();
};
var parsePipelineDef$2 = (def, refs) => {
if (refs.pipeStrategy === "input") return parseDef$2(def.in._def, refs);
else if (refs.pipeStrategy === "output") return parseDef$2(def.out._def, refs);
const a = parseDef$2(def.in._def, {
...refs,
currentPath: [
...refs.currentPath,
"allOf",
"0"
]
});
return { allOf: [a, parseDef$2(def.out._def, {
...refs,
currentPath: [
...refs.currentPath,
"allOf",
a ? "1" : "0"
]
})].filter((x) => x !== void 0) };
};
function parsePromiseDef$2(def, refs) {
return parseDef$2(def.type._def, refs);
}
function parseSetDef$2(def, refs) {
const schema = {
type: "array",
uniqueItems: true,
items: parseDef$2(def.valueType._def, {
...refs,
currentPath: [...refs.currentPath, "items"]
})
};
if (def.minSize) schema.minItems = def.minSize.value;
if (def.maxSize) schema.maxItems = def.maxSize.value;
return schema;
}
function parseTupleDef$2(def, refs) {
if (def.rest) return {
type: "array",
minItems: def.items.length,
items: def.items.map((x, i) => parseDef$2(x._def, {
...refs,
currentPath: [
...refs.currentPath,
"items",
`${i}`
]
})).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),
additionalItems: parseDef$2(def.rest._def, {
...refs,
currentPath: [...refs.currentPath, "additionalItems"]
})
};
else return {
type: "array",
minItems: def.items.length,
maxItems: def.items.length,
items: def.items.map((x, i) => parseDef$2(x._def, {
...refs,
currentPath: [
...refs.currentPath,
"items",
`${i}`
]
})).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])
};
}
function parseUndefinedDef$2() {
return { not: parseAnyDef$2() };
}
function parseUnknownDef$2() {
return parseAnyDef$2();
}
var parseReadonlyDef$2 = (def, refs) => {
return parseDef$2(def.innerType._def, refs);
};
var selectParser$2 = (def, typeName, refs) => {
switch (typeName) {
case ZodFirstPartyTypeKind.ZodString: return parseStringDef$2(def, refs);
case ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef$2(def);
case ZodFirstPartyTypeKind.ZodObject: return parseObjectDef$2(def, refs);
case ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef$2(def);
case ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef$2();
case ZodFirstPartyTypeKind.ZodDate: return parseDateDef$2(def, refs);
case ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef$2();
case ZodFirstPartyTypeKind.ZodNull: return parseNullDef$2();
case ZodFirstPartyTypeKind.ZodArray: return parseArrayDef$2(def, refs);
case ZodFirstPartyTypeKind.ZodUnion:
case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef$2(def, refs);
case ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef$2(def, refs);
case ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef$2(def, refs);
case ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef$2(def, refs);
case ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef$2(def);
case ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef$2(def);
case ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef$2(def);
case ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef$2(def, refs);
case ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef$2(def, refs);
case ZodFirstPartyTypeKind.ZodMap: return parseMapDef$2(def, refs);
case ZodFirstPartyTypeKind.ZodSet: return parseSetDef$2(def, refs);
case ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def;
case ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef$2(def, refs);
case ZodFirstPartyTypeKind.ZodNaN:
case ZodFirstPartyTypeKind.ZodNever: return parseNeverDef$2();
case ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef$2(def, refs);
case ZodFirstPartyTypeKind.ZodAny: return parseAnyDef$2();
case ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef$2();
case ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef$2(def, refs);
case ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef$2(def, refs);
case ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef$2(def, refs);
case ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef$2(def, refs);
case ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef$2(def, refs);
case ZodFirstPartyTypeKind.ZodFunction:
case ZodFirstPartyTypeKind.ZodVoid:
case ZodFirstPartyTypeKind.ZodSymbol: return;
default: return /* @__PURE__ */ ((_) => void 0)(typeName);
}
};
var getRelativePath$2 = (pathA, pathB) => {
let i = 0;
for (; i < pathA.length && i < pathB.length; i++) if (pathA[i] !== pathB[i]) break;
return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
};
function parseDef$2(def, refs, forceResolution = false) {
var _a2;
const seenItem = refs.seen.get(def);
if (refs.override) {
const overrideResult = (_a2 = refs.override) == null ? void 0 : _a2.call(refs, def, refs, seenItem, forceResolution);
if (overrideResult !== ignoreOverride$2) return overrideResult;
}
if (seenItem && !forceResolution) {
const seenSchema = get$ref$2(seenItem, refs);
if (seenSchema !== void 0) return seenSchema;
}
const newItem = {
def,
path: refs.currentPath,
jsonSchema: void 0
};
refs.seen.set(def, newItem);
const jsonSchemaOrGetter = selectParser$2(def, def.typeName, refs);
const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef$2(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
if (jsonSchema2) addMeta$2(def, refs, jsonSchema2);
if (refs.postProcess) {
const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
newItem.jsonSchema = jsonSchema2;
return postProcessResult;
}
newItem.jsonSchema = jsonSchema2;
return jsonSchema2;
}
var get$ref$2 = (item, refs) => {
switch (refs.$refStrategy) {
case "root": return { $ref: item.path.join("/") };
case "relative": return { $ref: getRelativePath$2(refs.currentPath, item.path) };
case "none":
case "seen":
if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
return parseAnyDef$2();
}
return refs.$refStrategy === "seen" ? parseAnyDef$2() : void 0;
}
};
var addMeta$2 = (def, refs, jsonSchema2) => {
if (def.description) jsonSchema2.description = def.description;
return jsonSchema2;
};
var getRefs$2 = (options) => {
const _options = getDefaultOptions$2(options);
const currentPath = _options.name !== void 0 ? [
..._options.basePath,
_options.definitionPath,
_options.name
] : _options.basePath;
return {
..._options,
currentPath,
propertyPath: void 0,
seen: new Map(Object.entries(_options.definitions).map(([name2, def]) => [def._def, {
def: def._def,
path: [
..._options.basePath,
_options.definitionPath,
name2
],
jsonSchema: void 0
}]))
};
};
var zod3ToJsonSchema$2 = (schema, options) => {
var _a2;
const refs = getRefs$2(options);
let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name3, schema2]) => {
var _a3;
return {
...acc,
[name3]: (_a3 = parseDef$2(schema2._def, {
...refs,
currentPath: [
...refs.basePath,
refs.definitionPath,
name3
]
}, true)) != null ? _a3 : parseAnyDef$2()
};
}, {}) : void 0;
const name2 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
const main = (_a2 = parseDef$2(schema._def, name2 === void 0 ? refs : {
...refs,
currentPath: [
...refs.basePath,
refs.definitionPath,
name2
]
}, false)) != null ? _a2 : parseAnyDef$2();
const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
if (title !== void 0) main.title = title;
const combined = name2 === void 0 ? definitions ? {
...main,
[refs.definitionPath]: definitions
} : main : {
$ref: [
...refs.$refStrategy === "relative" ? [] : refs.basePath,
refs.definitionPath,
name2
].join("/"),
[refs.definitionPath]: {
...definitions,
[name2]: main
}
};
combined.$schema = "http://json-schema.org/draft-07/schema#";
return combined;
};
var schemaSymbol$2 = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
function lazySchema$1(createSchema) {
let schema;
return () => {
if (schema == null) schema = createSchema();
return schema;
};
}
function jsonSchema$2(jsonSchema2, { validate } = {}) {
return {
[schemaSymbol$2]: true,
_type: void 0,
get jsonSchema() {
if (typeof jsonSchema2 === "function") jsonSchema2 = jsonSchema2();
return jsonSchema2;
},
validate
};
}
function isSchema$2(value) {
return typeof value === "object" && value !== null && schemaSymbol$2 in value && value[schemaSymbol$2] === true && "jsonSchema" in value && "validate" in value;
}
function asSchema$2(schema) {
return schema == null ? jsonSchema$2({
type: "object",
properties: {},
additionalProperties: false
}) : isSchema$2(schema) ? schema : "~standard" in schema ? schema["~standard"].vendor === "zod" ? zodSchema$2(schema) : standardSchema$2(schema) : schema();
}
function standardSchema$2(standardSchema2) {
return jsonSchema$2(() => {
if (!hasStandardJsonSchema$1(standardSchema2)) throw new Error(`Standard schema vendor '${standardSchema2["~standard"].vendor}' does not support JSON Schema conversion.`);
return addAdditionalPropertiesToJsonSchema$2(standardSchema2["~standard"].jsonSchema.input({ target: "draft-07" }));
}, { validate: async (value) => {
const result = await standardSchema2["~standard"].validate(value);
return "value" in result ? {
success: true,
value: result.value
} : {
success: false,
error: new TypeValidationError$2({
value,
cause: result.issues
})
};
} });
}
function hasStandardJsonSchema$1(schema) {
return schema["~standard"].jsonSchema != null;
}
function zod3Schema$2(zodSchema2, options) {
var _a2;
const useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;
return jsonSchema$2(() => zod3ToJsonSchema$2(zodSchema2, { $refStrategy: useReferences ? "root" : "none" }), { validate: async (value) => {
const result = await zodSchema2.safeParseAsync(value);
return result.success ? {
success: true,
value: result.data
} : {
success: false,
error: result.error
};
} });
}
function zod4Schema$2(zodSchema2, options) {
var _a2;
const useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;
return jsonSchema$2(() => addAdditionalPropertiesToJsonSchema$2(z4.toJSONSchema(zodSchema2, {
target: "draft-7",
io: "input",
reused: useReferences ? "ref" : "inline"
})), { validate: async (value) => {
const result = await z4.safeParseAsync(zodSchema2, value);
return result.success ? {
success: true,
value: result.data
} : {
success: false,
error: result.error
};
} });
}
function isZod4Schema$2(zodSchema2) {
return "_zod" in zodSchema2;
}
function zodSchema$2(zodSchema2, options) {
if (isZod4Schema$2(zodSchema2)) return zod4Schema$2(zodSchema2, options);
else return zod3Schema$2(zodSchema2, options);
}
async function validateTypes$2({ value, schema, context }) {
const result = await safeValidateTypes$2({
value,
schema,
context
});
if (!result.success) throw TypeValidationError$2.wrap({
value,
cause: result.error,
context
});
return result.value;
}
async function safeValidateTypes$2({ value, schema, context }) {
const actualSchema = asSchema$2(schema);
try {
if (actualSchema.validate == null) return {
success: true,
value,
rawValue: value
};
const result = await actualSchema.validate(value);
if (result.success) return {
success: true,
value: result.value,
rawValue: value
};
return {
success: false,
error: TypeValidationError$2.wrap({
value,
cause: result.error,
context
}),
rawValue: value
};
} catch (error) {
return {
success: false,
error: TypeValidationError$2.wrap({
value,
cause: error,
context
}),
rawValue: value
};
}
}
async function parseJSON$2({ text, schema }) {
try {
const value = secureJsonParse$2(text);
if (schema == null) return value;
return validateTypes$2({
value,
schema
});
} catch (error) {
if (JSONParseError$2.isInstance(error) || TypeValidationError$2.isInstance(error)) throw error;
throw new JSONParseError$2({
text,
cause: error
});
}
}
async function safeParseJSON$2({ text, schema }) {
try {
const value = secureJsonParse$2(text);
if (schema == null) return {
success: true,
value,
rawValue: value
};
return await safeValidateTypes$2({
value,
schema
});
} catch (error) {
return {
success: false,
error: JSONParseError$2.isInstance(error) ? error : new JSONParseError$2({
text,
cause: error
}),
rawValue: void 0
};
}
}
function parseJsonEventStream$2({ stream, schema }) {
return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream$1()).pipeThrough(new TransformStream({ async transform({ data }, controller) {
if (data === "[DONE]") return;
controller.enqueue(await safeParseJSON$2({
text: data,
schema
}));
} }));
}
async function parseProviderOptions$1({ provider, providerOptions, schema }) {
if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) return;
const parsedProviderOptions = await safeValidateTypes$2({
value: providerOptions[provider],
schema
});
if (!parsedProviderOptions.success) throw new InvalidArgumentError$2({
argument: "providerOptions",
message: `invalid ${provider} provider options`,
cause: parsedProviderOptions.error
});
return parsedProviderOptions.value;
}
var getOriginalFetch2$1 = () => globalThis.fetch;
var postJsonToApi$2 = async ({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch }) => postToApi$2({
url,
headers: {
"Content-Type": "application/json",
...headers
},
body: {
content: JSON.stringify(body),
values: body
},
failedResponseHandler,
successfulResponseHandler,
abortSignal,
fetch
});
var postFormDataToApi$1 = async ({ url, headers, formData, failedResponseHandler, successfulResponseHandler, abortSignal, fetch }) => postToApi$2({
url,
headers,
body: {
content: formData,
values: Object.fromEntries(formData.entries())
},
failedResponseHandler,
successfulResponseHandler,
abortSignal,
fetch
});
var postToApi$2 = async ({ url, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch = getOriginalFetch2$1() }) => {
try {
const response = await fetch(url, {
method: "POST",
headers: withUserAgentSuffix$2(headers, `ai-sdk/provider-utils/${VERSION$15}`, getRuntimeEnvironmentUserAgent$2()),
body: body.content,
signal: abortSignal
});
const responseHeaders = extractResponseHeaders$2(response);
if (!response.ok) {
let errorInformation;
try {
errorInformation = await failedResponseHandler({
response,
url,
requestBodyValues: body.values
});
} catch (error) {
if (isAbortError$2(error) || APICallError$2.isInstance(error)) throw error;
throw new APICallError$2({
message: "Failed to process error response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: body.values
});
}
throw errorInformation.value;
}
try {
return await successfulResponseHandler({
response,
url,
requestBodyValues: body.values
});
} catch (error) {
if (error instanceof Error) {
if (isAbortError$2(error) || APICallError$2.isInstance(error)) throw error;
}
throw new APICallError$2({
message: "Failed to process successful response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: body.values
});
}
} catch (error) {
throw handleFetchError$2({
error,
url,
requestBodyValues: body.values
});
}
};
function tool$2(tool2) {
return tool2;
}
function createProviderToolFactory$1({ id, inputSchema }) {
return ({ execute, outputSchema, needsApproval, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool$2({
type: "provider",
id,
args,
inputSchema,
outputSchema,
execute,
needsApproval,
toModelOutput,
onInputStart,
onInputDelta,
onInputAvailable
});
}
function createProviderToolFactoryWithOutputSchema({ id, inputSchema, outputSchema, supportsDeferredResults }) {
return ({ execute, needsApproval, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool$2({
type: "provider",
id,
args,
inputSchema,
outputSchema,
execute,
needsApproval,
toModelOutput,
onInputStart,
onInputDelta,
onInputAvailable,
supportsDeferredResults
});
}
async function resolve$1(value) {
if (typeof value === "function") value = value();
return value;
}
var textDecoder$3 = new TextDecoder();
function wrapResponseBodyStream$1({ stream, url, requestBodyValues, statusCode, responseHeaders }) {
const reader = stream.getReader();
let readerReleased = false;
const releaseReader = () => {
if (!readerReleased) {
reader.releaseLock();
readerReleased = true;
}
};
return new ReadableStream({
async pull(controller) {
try {
const { done, value } = await reader.read();
if (done) {
releaseReader();
controller.close();
} else controller.enqueue(value);
} catch (error) {
releaseReader();
if (isAbortError$2(error)) {
controller.error(error);
return;
}
controller.error(handleFetchError$2({
error: new APICallError$2({
message: "Failed to process successful response",
cause: error,
statusCode,
url,
responseHeaders,
requestBodyValues
}),
url,
requestBodyValues
}));
}
},
async cancel(reason) {
try {
await reader.cancel(reason);
} finally {
releaseReader();
}
}
});
}
async function readResponseBodyAsText$1({ response, url }) {
return textDecoder$3.decode(await readResponseWithSizeLimit$1({
response,
url
}));
}
var createJsonErrorResponseHandler$2 = ({ errorSchema, errorToMessage, isRetryable }) => async ({ response, url, requestBodyValues }) => {
const responseBody = await readResponseBodyAsText$1({
response,
url
});
const responseHeaders = extractResponseHeaders$2(response);
if (responseBody.trim() === "") return {
responseHeaders,
value: new APICallError$2({
message: response.statusText,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody,
isRetryable: isRetryable == null ? void 0 : isRetryable(response)
})
};
try {
const parsedError = await parseJSON$2({
text: responseBody,
schema: errorSchema
});
return {
responseHeaders,
value: new APICallError$2({
message: errorToMessage(parsedError),
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody,
data: parsedError,
isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
})
};
} catch (parseError) {
return {
responseHeaders,
value: new APICallError$2({
message: response.statusText,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody,
isRetryable: isRetryable == null ? void 0 : isRetryable(response)
})
};
}
};
var createEventSourceResponseHandler$2 = (chunkSchema) => async ({ response, url, requestBodyValues }) => {
const responseHeaders = extractResponseHeaders$2(response);
if (response.body == null) throw new EmptyResponseBodyError$2({});
return {
responseHeaders,
value: parseJsonEventStream$2({
stream: wrapResponseBodyStream$1({
stream: response.body,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders
}),
schema: chunkSchema
})
};
};
var createJsonResponseHandler$2 = (responseSchema) => async ({ response, url, requestBodyValues }) => {
const responseBody = await readResponseBodyAsText$1({
response,
url
});
const parsedResult = await safeParseJSON$2({
text: responseBody,
schema: responseSchema
});
const responseHeaders = extractResponseHeaders$2(response);
if (!parsedResult.success) throw new APICallError$2({
message: "Invalid JSON response",
cause: parsedResult.error,
statusCode: response.status,
responseHeaders,
responseBody,
url,
requestBodyValues
});
return {
responseHeaders,
value: parsedResult.value,
rawValue: parsedResult.rawValue
};
};
var createBinaryResponseHandler$1 = () => async ({ response, url, requestBodyValues }) => {
const responseHeaders = extractResponseHeaders$2(response);
if (!response.body) throw new APICallError$2({
message: "Response body is empty",
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody: void 0
});
try {
const buffer = await response.arrayBuffer();
return {
responseHeaders,
value: new Uint8Array(buffer)
};
} catch (error) {
throw new APICallError$2({
message: "Failed to read response as array buffer",
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody: void 0,
cause: error
});
}
};
var createStatusCodeErrorResponseHandler$1 = () => async ({ response, url, requestBodyValues }) => {
const responseHeaders = extractResponseHeaders$2(response);
const responseBody = await readResponseBodyAsText$1({
response,
url
});
return {
responseHeaders,
value: new APICallError$2({
message: response.statusText,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody
})
};
};
function startsWithStructuredValue$1(value) {
if (typeof value !== "string") return false;
const firstCharacter = value.trimStart()[0];
return firstCharacter === "{" || firstCharacter === "[";
}
var StreamingToolCallArgumentState$1 = class {
constructor(initialValue = "") {
this.structure = { kind: "undetermined" };
this.append(initialValue);
}
get hasCompleteStructuredValue() {
return this.structure.kind === "structured" && this.structure.complete === true;
}
append(delta) {
let nextStructure = this.structure;
for (const character of delta) {
if (nextStructure.kind === "undetermined") {
if (/\s/.test(character)) continue;
if (character !== "{" && character !== "[") {
nextStructure = { kind: "other" };
continue;
}
nextStructure = {
kind: "structured",
stack: [character],
inString: false,
escaped: false,
complete: false
};
continue;
}
if (nextStructure.kind !== "structured" || nextStructure.complete) continue;
if (nextStructure.inString) {
if (nextStructure.escaped) nextStructure.escaped = false;
else if (character === "\\") nextStructure.escaped = true;
else if (character === "\"") nextStructure.inString = false;
continue;
}
if (character === "\"") nextStructure.inString = true;
else if (character === "{" || character === "[") nextStructure.stack.push(character);
else if (character === "}" || character === "]") {
const expectedOpening = character === "}" ? "{" : "[";
if (nextStructure.stack[nextStructure.stack.length - 1] !== expectedOpening) {
nextStructure = { kind: "other" };
continue;
}
nextStructure.stack.pop();
if (nextStructure.stack.length === 0) nextStructure.complete = true;
}
}
this.structure = nextStructure;
}
};
var StreamingToolCallTracker$1 = class {
constructor(controller, options = {}) {
this.toolCalls = [];
this.toolCallsById = /* @__PURE__ */ new Map();
this.toolCallsByIndex = /* @__PURE__ */ new Map();
this.usedToolCallIds = /* @__PURE__ */ new Set();
this.nextGeneratedIdSuffixes = /* @__PURE__ */ new Map();
var _a2, _b2;
this.controller = controller;
this._generateId = (_a2 = options.generateId) != null ? _a2 : generateId$2;
this.typeValidation = (_b2 = options.typeValidation) != null ? _b2 : "none";
this.extractMetadata = options.extractMetadata;
this.buildToolCallProviderMetadata = options.buildToolCallProviderMetadata;
}
processDelta(toolCallDelta) {
var _a2, _b2;
const wireName = (_a2 = toolCallDelta.function) == null ? void 0 : _a2.name;
const hasBlankName = typeof wireName === "string" && wireName.trim().length === 0;
const wireId = this.getNonBlankString(toolCallDelta.id);
const name2 = this.getNonBlankString(wireName);
const { index } = toolCallDelta;
const resolution = this.resolveToolCall({
wireId,
index,
name: name2,
hasExplicitCallStart: name2 != null && startsWithStructuredValue$1((_b2 = toolCallDelta.function) == null ? void 0 : _b2.arguments)
});
if (resolution.kind === "ambiguous") return;
let toolCall;
if (resolution.kind === "new") {
if (hasBlankName) return;
toolCall = this.processNewToolCall(toolCallDelta, {
wireId,
index,
name: name2
});
} else {
toolCall = resolution.toolCall;
if (wireId != null) this.associateWireId(toolCall, wireId);
this.processExistingToolCall(toolCall, toolCallDelta);
}
if (index != null) this.associateIndex(toolCall, index);
}
flush() {
const toolCalls = this.toolCalls.every((toolCall) => toolCall.index != null) ? [...this.toolCalls].sort((a, b) => a.index - b.index || a.sequence - b.sequence) : this.toolCalls;
for (const toolCall of toolCalls) if (!toolCall.hasFinished) this.finishToolCall(toolCall);
}
resolveToolCall({ wireId, index, name: name2, hasExplicitCallStart }) {
const indexedToolCalls = index != null ? this.toolCallsByIndex.get(index) : void 0;
const matchingIndexedToolCalls = this.filterToolCallsByName(indexedToolCalls, name2);
if (wireId != null) {
const toolCallsWithId = this.toolCallsById.get(wireId);
if (toolCallsWithId != null) {
if (index != null) {
const matchingToolCalls = matchingIndexedToolCalls.filter((toolCall) => toolCallsWithId.has(toolCall));
const matchingToolCall = this.resolveMatchingToolCall(matchingToolCalls, hasExplicitCallStart);
if (matchingToolCall.kind !== "new") return matchingToolCall;
if (name2 != null) return { kind: "new" };
if (indexedToolCalls != null) return { kind: "ambiguous" };
return this.resolveMatchingToolCall([...toolCallsWithId], false);
}
if (name2 != null) {
const matchingToolCalls = [...toolCallsWithId].filter((toolCall) => toolCall.function.name === name2);
return this.resolveMatchingToolCall(matchingToolCalls, hasExplicitCallStart);
}
return this.resolveMatchingToolCall([...toolCallsWithId], false);
}
if (matchingIndexedToolCalls.length > 0) return hasExplicitCallStart ? { kind: "new" } : this.resolveMatchingToolCall(matchingIndexedToolCalls, false);
return { kind: "new" };
}
if (indexedToolCalls != null) return this.resolveMatchingToolCall(matchingIndexedToolCalls, hasExplicitCallStart);
if (name2 != null) return { kind: "new" };
const unfinishedToolCalls = this.toolCalls.filter((toolCall) => !toolCall.hasFinished);
if (unfinishedToolCalls.length === 1) return {
kind: "existing",
toolCall: unfinishedToolCalls[0]
};
return unfinishedToolCalls.length > 1 ? { kind: "ambiguous" } : { kind: "new" };
}
filterToolCallsByName(toolCalls, name2) {
if (toolCalls == null) return [];
return [...toolCalls].filter((toolCall) => name2 == null || toolCall.function.name === name2);
}
resolveMatchingToolCall(toolCalls, hasExplicitCallStart) {
if (toolCalls.length === 0) return { kind: "new" };
if (!hasExplicitCallStart) return toolCalls.length === 1 ? {
kind: "existing",
toolCall: toolCalls[0]
} : { kind: "ambiguous" };
const continuableToolCalls = toolCalls.filter((toolCall) => !toolCall.argumentState.hasCompleteStructuredValue);
if (continuableToolCalls.length === 1) return {
kind: "existing",
toolCall: continuableToolCalls[0]
};
return continuableToolCalls.length > 1 ? { kind: "ambiguous" } : { kind: "new" };
}
processNewToolCall(toolCallDelta, { wireId, index, name: name2 }) {
var _a2, _b2, _c, _d, _e;
if (this.typeValidation === "required") {
if (toolCallDelta.type !== "function") throw new InvalidResponseDataError$2({
data: toolCallDelta,
message: `Expected 'function' type.`
});
} else if (this.typeValidation === "if-present") {
if (toolCallDelta.type != null && toolCallDelta.type !== "function") throw new InvalidResponseDataError$2({
data: toolCallDelta,
message: `Expected 'function' type.`
});
}
if (name2 == null) throw new InvalidResponseDataError$2({
data: toolCallDelta,
message: `Expected 'function.name' to be a string.`
});
const id = this.createToolCallId(wireId);
this.controller.enqueue({
type: "tool-input-start",
id,
toolName: name2
});
const toolCall = {
id,
index: index != null ? index : void 0,
sequence: this.toolCalls.length,
type: "function",
function: {
name: name2,
arguments: (_b2 = (_a2 = toolCallDelta.function) == null ? void 0 : _a2.arguments) != null ? _b2 : ""
},
argumentState: new StreamingToolCallArgumentState$1((_d = (_c = toolCallDelta.function) == null ? void 0 : _c.arguments) != null ? _d : ""),
hasFinished: false,
metadata: (_e = this.extractMetadata) == null ? void 0 : _e.call(this, toolCallDelta)
};
this.toolCalls.push(toolCall);
if (wireId != null) this.associateWireId(toolCall, wireId);
if (toolCall.function.arguments.length > 0) this.controller.enqueue({
type: "tool-input-delta",
id: toolCall.id,
delta: toolCall.function.arguments
});
return toolCall;
}
associateWireId(toolCall, wireId) {
let toolCallsWithId = this.toolCallsById.get(wireId);
if (toolCallsWithId == null) {
toolCallsWithId = /* @__PURE__ */ new Set();
this.toolCallsById.set(wireId, toolCallsWithId);
}
toolCallsWithId.add(toolCall);
}
associateIndex(toolCall, index) {
let toolCallsWithIndex = this.toolCallsByIndex.get(index);
if (toolCallsWithIndex == null) {
toolCallsWithIndex = /* @__PURE__ */ new Set();
this.toolCallsByIndex.set(index, toolCallsWithIndex);
}
toolCallsWithIndex.add(toolCall);
}
createToolCallId(wireId) {
var _a2, _b2;
if (wireId != null && !this.usedToolCallIds.has(wireId)) {
this.usedToolCallIds.add(wireId);
return wireId;
}
const generatedId = (_a2 = this.getNonBlankString(this._generateId())) != null ? _a2 : "tool-call";
if (!this.usedToolCallIds.has(generatedId)) {
this.usedToolCallIds.add(generatedId);
return generatedId;
}
const initialSuffix = (_b2 = this.nextGeneratedIdSuffixes.get(generatedId)) != null ? _b2 : 1;
const maximumSuffix = initialSuffix + this.usedToolCallIds.size;
for (let suffix = initialSuffix; suffix <= maximumSuffix; suffix++) {
const suffixedId = `${generatedId}-${suffix}`;
if (!this.usedToolCallIds.has(suffixedId)) {
this.usedToolCallIds.add(suffixedId);
this.nextGeneratedIdSuffixes.set(generatedId, suffix + 1);
return suffixedId;
}
}
throw new Error("Failed to create a unique tool call ID.");
}
getNonBlankString(value) {
return value != null && value.trim().length > 0 ? value : void 0;
}
processExistingToolCall(toolCall, toolCallDelta) {
var _a2;
if (!toolCall.hasFinished && ((_a2 = toolCallDelta.function) == null ? void 0 : _a2.arguments) != null) {
toolCall.argumentState.append(toolCallDelta.function.arguments);
toolCall.function.arguments += toolCallDelta.function.arguments;
this.controller.enqueue({
type: "tool-input-delta",
id: toolCall.id,
delta: toolCallDelta.function.arguments
});
}
}
finishToolCall(toolCall) {
var _a2;
this.controller.enqueue({
type: "tool-input-end",
id: toolCall.id
});
const providerMetadata = (_a2 = this.buildToolCallProviderMetadata) == null ? void 0 : _a2.call(this, toolCall.metadata);
this.controller.enqueue({
type: "tool-call",
toolCallId: toolCall.id,
toolName: toolCall.function.name,
input: toolCall.function.arguments,
...providerMetadata ? { providerMetadata } : {}
});
toolCall.hasFinished = true;
}
};
function withoutTrailingSlash$2(url) {
return url == null ? void 0 : url.replace(/\/$/, "");
}
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/openai-compatible/2.0.88/d1d0359bf44bd79da5e120c8cc560648629d2ac9989b32e687a6553c516a8e1a/node_modules/@ai-sdk/openai-compatible/dist/index.mjs
function toCamelCase$1(str) {
return str.replace(/[_-]([a-z])/g, (g) => g[1].toUpperCase());
}
function resolveProviderOptionsKey$1(rawName, providerOptions) {
const camelName = toCamelCase$1(rawName);
if (camelName !== rawName && (providerOptions == null ? void 0 : providerOptions[camelName]) != null) return camelName;
return rawName;
}
var defaultOpenAICompatibleErrorStructure$1 = {
errorSchema: z.object({ error: z.object({
message: z.string(),
type: z.string().nullish(),
param: z.any().nullish(),
code: z.union([z.string(), z.number()]).nullish()
}) }),
errorToMessage: (data) => data.error.message
};
function convertOpenAICompatibleChatUsage$1(usage) {
var _a, _b, _c, _d, _e, _f;
if (usage == null) return {
inputTokens: {
total: void 0,
noCache: void 0,
cacheRead: void 0,
cacheWrite: void 0
},
outputTokens: {
total: void 0,
text: void 0,
reasoning: void 0
},
raw: void 0
};
const promptTokens = (_a = usage.prompt_tokens) != null ? _a : 0;
const completionTokens = (_b = usage.completion_tokens) != null ? _b : 0;
const cacheReadTokens = (_d = (_c = usage.prompt_tokens_details) == null ? void 0 : _c.cached_tokens) != null ? _d : 0;
const reasoningTokens = (_f = (_e = usage.completion_tokens_details) == null ? void 0 : _e.reasoning_tokens) != null ? _f : 0;
return {
inputTokens: {
total: promptTokens,
noCache: promptTokens - cacheReadTokens,
cacheRead: cacheReadTokens,
cacheWrite: void 0
},
outputTokens: {
total: completionTokens,
text: Math.max(0, completionTokens - reasoningTokens),
reasoning: reasoningTokens
},
raw: usage
};
}
function getOpenAIMetadata$1(message) {
var _a, _b;
return (_b = (_a = message == null ? void 0 : message.providerOptions) == null ? void 0 : _a.openaiCompatible) != null ? _b : {};
}
function getAudioFormat$1(mediaType) {
switch (mediaType) {
case "audio/wav": return "wav";
case "audio/mp3":
case "audio/mpeg": return "mp3";
default: return null;
}
}
function convertToOpenAICompatibleChatMessages$1(prompt) {
var _a, _b, _c;
const messages = [];
for (const { role, content, ...message } of prompt) {
const metadata = getOpenAIMetadata$1({ ...message });
switch (role) {
case "system":
messages.push({
role: "system",
content,
...metadata
});
break;
case "user":
if (content.length === 1 && content[0].type === "text") {
messages.push({
role: "user",
content: content[0].text,
...getOpenAIMetadata$1(content[0])
});
break;
}
messages.push({
role: "user",
content: content.map((part) => {
var _a2;
const partMetadata = getOpenAIMetadata$1(part);
switch (part.type) {
case "text": return {
type: "text",
text: part.text,
...partMetadata
};
case "file":
if (part.mediaType.startsWith("image/")) {
const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
return {
type: "image_url",
image_url: { url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${convertToBase64$1(part.data)}` },
...partMetadata
};
}
if (part.mediaType.startsWith("audio/")) {
if (part.data instanceof URL) throw new UnsupportedFunctionalityError$2({ functionality: "audio file parts with URLs" });
const format = getAudioFormat$1(part.mediaType);
if (format === null) throw new UnsupportedFunctionalityError$2({ functionality: `audio media type ${part.mediaType}` });
return {
type: "input_audio",
input_audio: {
data: convertToBase64$1(part.data),
format
},
...partMetadata
};
}
if (part.mediaType === "application/pdf") {
if (part.data instanceof URL) throw new UnsupportedFunctionalityError$2({ functionality: "PDF file parts with URLs" });
return {
type: "file",
file: {
filename: (_a2 = part.filename) != null ? _a2 : "document.pdf",
file_data: `data:application/pdf;base64,${convertToBase64$1(part.data)}`
},
...partMetadata
};
}
if (part.mediaType.startsWith("text/")) return {
type: "text",
text: part.data instanceof URL ? part.data.toString() : typeof part.data === "string" ? new TextDecoder().decode(convertBase64ToUint8Array$1(part.data)) : new TextDecoder().decode(part.data),
...partMetadata
};
throw new UnsupportedFunctionalityError$2({ functionality: `file part media type ${part.mediaType}` });
}
}),
...metadata
});
break;
case "assistant": {
let text = "";
let reasoning = "";
const toolCalls = [];
for (const part of content) {
const partMetadata = getOpenAIMetadata$1(part);
switch (part.type) {
case "text":
text += part.text;
break;
case "reasoning":
reasoning += part.text;
break;
case "tool-call": {
const thoughtSignature = (_b = (_a = part.providerOptions) == null ? void 0 : _a.google) == null ? void 0 : _b.thoughtSignature;
toolCalls.push({
id: part.toolCallId,
type: "function",
function: {
name: part.toolName,
arguments: JSON.stringify(part.input)
},
...partMetadata,
...thoughtSignature ? { extra_content: { google: { thought_signature: String(thoughtSignature) } } } : {}
});
break;
}
}
}
messages.push({
role: "assistant",
content: toolCalls.length > 0 ? text || null : text,
...reasoning.length > 0 ? { reasoning_content: reasoning } : {},
tool_calls: toolCalls.length > 0 ? toolCalls : void 0,
...metadata
});
break;
}
case "tool":
for (const toolResponse of content) {
if (toolResponse.type === "tool-approval-response") continue;
const output = toolResponse.output;
let contentValue;
switch (output.type) {
case "text":
case "error-text":
contentValue = output.value;
break;
case "execution-denied":
contentValue = (_c = output.reason) != null ? _c : "Tool call execution denied.";
break;
case "content":
case "json":
case "error-json": contentValue = JSON.stringify(output.value);
}
const toolResponseMetadata = getOpenAIMetadata$1(toolResponse);
messages.push({
role: "tool",
tool_call_id: toolResponse.toolCallId,
content: contentValue,
...toolResponseMetadata
});
}
break;
default: throw new Error(`Unsupported role: ${role}`);
}
}
return messages;
}
function getResponseMetadata$4({ id, model, created }) {
return {
id: id != null ? id : void 0,
modelId: model != null ? model : void 0,
timestamp: created != null ? /* @__PURE__ */ new Date(created * 1e3) : void 0
};
}
function mapOpenAICompatibleFinishReason$2(finishReason) {
switch (finishReason) {
case "stop": return "stop";
case "length": return "length";
case "content_filter": return "content-filter";
case "function_call":
case "tool_calls": return "tool-calls";
default: return "other";
}
}
var openaiCompatibleLanguageModelChatOptions$1 = z.object({
/**
* A unique identifier representing your end-user, which can help the provider to
* monitor and detect abuse.
*/
user: z.string().optional(),
/**
* Reasoning effort for reasoning models. Defaults to `medium`.
*/
reasoningEffort: z.string().optional(),
/**
* Controls the verbosity of the generated text. Defaults to `medium`.
*/
textVerbosity: z.string().optional(),
/**
* Whether to use strict JSON schema validation.
* When true, the model uses constrained decoding to guarantee schema compliance.
* Only used when the provider supports structured outputs and a schema is provided.
*
* @default true
*/
strictJsonSchema: z.boolean().optional()
});
function prepareTools$7({ tools, toolChoice }) {
tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
const toolWarnings = [];
if (tools == null) return {
tools: void 0,
toolChoice: void 0,
toolWarnings
};
const openaiCompatTools = [];
for (const tool of tools) if (tool.type === "provider") toolWarnings.push({
type: "unsupported",
feature: `provider-defined tool ${tool.id}`
});
else openaiCompatTools.push({
type: "function",
function: {
name: tool.name,
description: tool.description,
parameters: tool.inputSchema,
...tool.strict != null ? { strict: tool.strict } : {}
}
});
if (toolChoice == null) return {
tools: openaiCompatTools,
toolChoice: void 0,
toolWarnings
};
const type = toolChoice.type;
switch (type) {
case "auto":
case "none":
case "required": return {
tools: openaiCompatTools,
toolChoice: type,
toolWarnings
};
case "tool": return {
tools: openaiCompatTools,
toolChoice: {
type: "function",
function: { name: toolChoice.toolName }
},
toolWarnings
};
default: throw new UnsupportedFunctionalityError$2({ functionality: `tool choice type: ${type}` });
}
}
var OpenAICompatibleChatLanguageModel$1 = class {
constructor(modelId, config) {
this.specificationVersion = "v3";
var _a, _b;
this.modelId = modelId;
this.config = config;
const errorStructure = (_a = config.errorStructure) != null ? _a : defaultOpenAICompatibleErrorStructure$1;
this.chunkSchema = createOpenAICompatibleChatChunkSchema$1(errorStructure.errorSchema);
this.failedResponseHandler = createJsonErrorResponseHandler$2(errorStructure);
this.supportsStructuredOutputs = (_b = config.supportsStructuredOutputs) != null ? _b : false;
}
get provider() {
return this.config.provider;
}
get providerOptionsName() {
return this.config.provider.split(".")[0].trim();
}
get supportedUrls() {
var _a, _b, _c;
return (_c = (_b = (_a = this.config).supportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {};
}
transformRequestBody(args) {
var _a, _b, _c;
return (_c = (_b = (_a = this.config).transformRequestBody) == null ? void 0 : _b.call(_a, args)) != null ? _c : args;
}
convertUsage(usage) {
var _a, _b, _c;
return (_c = (_b = (_a = this.config).convertUsage) == null ? void 0 : _b.call(_a, usage)) != null ? _c : convertOpenAICompatibleChatUsage$1(usage);
}
async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, providerOptions, stopSequences, responseFormat, seed, toolChoice, tools }) {
var _a, _b, _c, _d, _e;
const warnings = [];
const deprecatedOptions = await parseProviderOptions$1({
provider: "openai-compatible",
providerOptions,
schema: openaiCompatibleLanguageModelChatOptions$1
});
if (deprecatedOptions != null) warnings.push({
type: "other",
message: `The 'openai-compatible' key in providerOptions is deprecated. Use 'openaiCompatible' instead.`
});
const compatibleOptions = Object.assign(deprecatedOptions != null ? deprecatedOptions : {}, (_a = await parseProviderOptions$1({
provider: "openaiCompatible",
providerOptions,
schema: openaiCompatibleLanguageModelChatOptions$1
})) != null ? _a : {}, (_b = await parseProviderOptions$1({
provider: this.providerOptionsName,
providerOptions,
schema: openaiCompatibleLanguageModelChatOptions$1
})) != null ? _b : {}, (_c = await parseProviderOptions$1({
provider: toCamelCase$1(this.providerOptionsName),
providerOptions,
schema: openaiCompatibleLanguageModelChatOptions$1
})) != null ? _c : {});
const strictJsonSchema = (_d = compatibleOptions == null ? void 0 : compatibleOptions.strictJsonSchema) != null ? _d : true;
if (topK != null) warnings.push({
type: "unsupported",
feature: "topK"
});
if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && !this.supportsStructuredOutputs) warnings.push({
type: "unsupported",
feature: "responseFormat",
details: "JSON response format schema is only supported with structuredOutputs"
});
const { tools: openaiTools, toolChoice: openaiToolChoice, toolWarnings } = prepareTools$7({
tools,
toolChoice
});
return {
metadataKey: resolveProviderOptionsKey$1(this.providerOptionsName, providerOptions),
args: {
model: this.modelId,
user: compatibleOptions.user,
max_tokens: maxOutputTokens,
temperature,
top_p: topP,
frequency_penalty: frequencyPenalty,
presence_penalty: presencePenalty,
response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? this.supportsStructuredOutputs === true && responseFormat.schema != null ? {
type: "json_schema",
json_schema: {
schema: responseFormat.schema,
strict: strictJsonSchema,
name: (_e = responseFormat.name) != null ? _e : "response",
description: responseFormat.description
}
} : { type: "json_object" } : void 0,
stop: stopSequences,
seed,
...Object.fromEntries(Object.entries({
...providerOptions == null ? void 0 : providerOptions[this.providerOptionsName],
...providerOptions == null ? void 0 : providerOptions[toCamelCase$1(this.providerOptionsName)]
}).filter(([key]) => !Object.keys(openaiCompatibleLanguageModelChatOptions$1.shape).includes(key))),
reasoning_effort: compatibleOptions.reasoningEffort,
verbosity: compatibleOptions.textVerbosity,
messages: convertToOpenAICompatibleChatMessages$1(prompt),
tools: openaiTools,
tool_choice: openaiToolChoice
},
warnings: [...warnings, ...toolWarnings]
};
}
async doGenerate(options) {
var _a, _b, _c, _d, _e, _f, _g, _h;
const { args, warnings, metadataKey } = await this.getArgs({ ...options });
const transformedBody = this.transformRequestBody(args);
const body = JSON.stringify(transformedBody);
const { responseHeaders, value: responseBody, rawValue: rawResponse } = await postJsonToApi$2({
url: this.config.url({
path: "/chat/completions",
modelId: this.modelId
}),
headers: combineHeaders$2(this.config.headers(), options.headers),
body: transformedBody,
failedResponseHandler: this.failedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$2(OpenAICompatibleChatResponseSchema$1),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const choice = responseBody.choices[0];
if (choice == null) throw new InvalidResponseDataError$2({
data: rawResponse,
message: "Response did not contain any choices."
});
const content = [];
const reasoning = (_a = choice.message.reasoning_content) != null ? _a : choice.message.reasoning;
if (reasoning != null && reasoning.length > 0) content.push({
type: "reasoning",
text: reasoning
});
content.push(...convertOpenAICompatibleContent$1(choice.message.content));
if (choice.message.tool_calls != null) for (const toolCall of choice.message.tool_calls) {
const thoughtSignature = (_c = (_b = toolCall.extra_content) == null ? void 0 : _b.google) == null ? void 0 : _c.thought_signature;
content.push({
type: "tool-call",
toolCallId: (_d = toolCall.id) != null ? _d : generateId$2(),
toolName: toolCall.function.name,
input: toolCall.function.arguments,
...thoughtSignature ? { providerMetadata: { [metadataKey]: { thoughtSignature } } } : {}
});
}
const providerMetadata = {
[metadataKey]: {},
...await ((_f = (_e = this.config.metadataExtractor) == null ? void 0 : _e.extractMetadata) == null ? void 0 : _f.call(_e, { parsedBody: rawResponse }))
};
const completionTokenDetails = (_g = responseBody.usage) == null ? void 0 : _g.completion_tokens_details;
if ((completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens) != null) providerMetadata[metadataKey].acceptedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens;
if ((completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens) != null) providerMetadata[metadataKey].rejectedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens;
return {
content,
finishReason: {
unified: mapOpenAICompatibleFinishReason$2(choice.finish_reason),
raw: (_h = choice.finish_reason) != null ? _h : void 0
},
usage: this.convertUsage(responseBody.usage),
providerMetadata,
request: { body },
response: {
...getResponseMetadata$4(responseBody),
headers: responseHeaders,
body: rawResponse
},
warnings
};
}
async doStream(options) {
var _a;
const { args, warnings, metadataKey } = await this.getArgs({ ...options });
const body = this.transformRequestBody({
...args,
stream: true,
stream_options: this.config.includeUsage ? { include_usage: true } : void 0
});
const metadataExtractor = (_a = this.config.metadataExtractor) == null ? void 0 : _a.createStreamExtractor();
const { responseHeaders, value: response } = await postJsonToApi$2({
url: this.config.url({
path: "/chat/completions",
modelId: this.modelId
}),
headers: combineHeaders$2(this.config.headers(), options.headers),
body,
failedResponseHandler: this.failedResponseHandler,
successfulResponseHandler: createEventSourceResponseHandler$2(this.chunkSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const providerOptionsName = metadataKey;
let toolCallTracker;
const pendingToolCalls = /* @__PURE__ */ new Map();
const forwardedToolCallIndices = /* @__PURE__ */ new Set();
const processToolCallDelta = (toolCallDelta) => {
var _a2, _b, _c, _d, _e;
const index = toolCallDelta.index;
if (index == null || forwardedToolCallIndices.has(index)) {
toolCallTracker.processDelta(toolCallDelta);
return;
}
let pending = pendingToolCalls.get(index);
if (pending == null) {
pending = {
id: (_a2 = toolCallDelta.id) != null ? _a2 : null,
bufferedArguments: "",
extraContent: (_b = toolCallDelta.extra_content) != null ? _b : null
};
pendingToolCalls.set(index, pending);
} else {
if (pending.id == null && toolCallDelta.id != null) pending.id = toolCallDelta.id;
if (pending.extraContent == null && toolCallDelta.extra_content != null) pending.extraContent = toolCallDelta.extra_content;
}
const argumentsDelta = (_c = toolCallDelta.function) == null ? void 0 : _c.arguments;
if (argumentsDelta != null) pending.bufferedArguments += argumentsDelta;
const name = (_d = toolCallDelta.function) == null ? void 0 : _d.name;
if (name != null) {
toolCallTracker.processDelta({
index,
id: pending.id,
function: {
name,
arguments: pending.bufferedArguments
},
extra_content: (_e = pending.extraContent) != null ? _e : void 0
});
pendingToolCalls.delete(index);
forwardedToolCallIndices.add(index);
}
};
let finishReason;
let usage = void 0;
let isFirstChunk = true;
let isActiveReasoning = false;
let isActiveText = false;
const convertUsage = (usage2) => this.convertUsage(usage2);
return {
stream: response.pipeThrough(new TransformStream({
start(controller) {
toolCallTracker = new StreamingToolCallTracker$1(controller, {
generateId: generateId$2,
extractMetadata: (delta) => {
var _a2, _b;
const thoughtSignature = (_b = (_a2 = delta.extra_content) == null ? void 0 : _a2.google) == null ? void 0 : _b.thought_signature;
return thoughtSignature ? { [providerOptionsName]: { thoughtSignature } } : void 0;
},
buildToolCallProviderMetadata: (metadata) => metadata
});
controller.enqueue({
type: "stream-start",
warnings
});
},
transform(chunk, controller) {
var _a2, _b;
if (options.includeRawChunks) controller.enqueue({
type: "raw",
rawValue: chunk.rawValue
});
if (!chunk.success) {
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error: chunk.error
});
return;
}
metadataExtractor?.processChunk(chunk.rawValue);
if ("error" in chunk.value) {
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error: chunk.value.error
});
return;
}
const value = chunk.value;
if (isFirstChunk) {
isFirstChunk = false;
controller.enqueue({
type: "response-metadata",
...getResponseMetadata$4(value)
});
}
if (value.usage != null) usage = value.usage;
const choice = value.choices[0];
if ((choice == null ? void 0 : choice.finish_reason) != null) finishReason = {
unified: mapOpenAICompatibleFinishReason$2(choice.finish_reason),
raw: (_a2 = choice.finish_reason) != null ? _a2 : void 0
};
if ((choice == null ? void 0 : choice.delta) == null) return;
const delta = choice.delta;
const enqueueReasoningDelta = (reasoningDelta) => {
if (isActiveText) {
controller.enqueue({
type: "text-end",
id: "txt-0"
});
isActiveText = false;
}
if (!isActiveReasoning) {
controller.enqueue({
type: "reasoning-start",
id: "reasoning-0"
});
isActiveReasoning = true;
}
controller.enqueue({
type: "reasoning-delta",
id: "reasoning-0",
delta: reasoningDelta
});
};
const enqueueTextDelta = (textDelta) => {
if (isActiveReasoning) {
controller.enqueue({
type: "reasoning-end",
id: "reasoning-0"
});
isActiveReasoning = false;
}
if (!isActiveText) {
controller.enqueue({
type: "text-start",
id: "txt-0"
});
isActiveText = true;
}
controller.enqueue({
type: "text-delta",
id: "txt-0",
delta: textDelta
});
};
const reasoningContent = (_b = delta.reasoning_content) != null ? _b : delta.reasoning;
if (reasoningContent) enqueueReasoningDelta(reasoningContent);
for (const contentPart of convertOpenAICompatibleContent$1(delta.content)) if (contentPart.type === "reasoning") enqueueReasoningDelta(contentPart.text);
else enqueueTextDelta(contentPart.text);
if (delta.tool_calls != null && delta.tool_calls.length > 0) {
if (isActiveReasoning) {
controller.enqueue({
type: "reasoning-end",
id: "reasoning-0"
});
isActiveReasoning = false;
}
for (const toolCallDelta of delta.tool_calls) processToolCallDelta(toolCallDelta);
}
},
flush(controller) {
var _a2, _b, _c, _d;
if (isActiveReasoning) controller.enqueue({
type: "reasoning-end",
id: "reasoning-0"
});
if (isActiveText) controller.enqueue({
type: "text-end",
id: "txt-0"
});
for (const [index, pending] of pendingToolCalls) toolCallTracker.processDelta({
index,
id: pending.id,
function: { arguments: pending.bufferedArguments }
});
pendingToolCalls.clear();
toolCallTracker.flush();
if (finishReason == null) {
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error: new InvalidResponseDataError$2({
data: void 0,
message: "Response stream ended without a finish reason."
})
});
}
const providerMetadata = {
[providerOptionsName]: {},
...metadataExtractor == null ? void 0 : metadataExtractor.buildMetadata()
};
if (((_a2 = usage == null ? void 0 : usage.completion_tokens_details) == null ? void 0 : _a2.accepted_prediction_tokens) != null) providerMetadata[providerOptionsName].acceptedPredictionTokens = (_b = usage == null ? void 0 : usage.completion_tokens_details) == null ? void 0 : _b.accepted_prediction_tokens;
if (((_c = usage == null ? void 0 : usage.completion_tokens_details) == null ? void 0 : _c.rejected_prediction_tokens) != null) providerMetadata[providerOptionsName].rejectedPredictionTokens = (_d = usage == null ? void 0 : usage.completion_tokens_details) == null ? void 0 : _d.rejected_prediction_tokens;
controller.enqueue({
type: "finish",
finishReason,
usage: convertUsage(usage),
providerMetadata
});
}
})),
request: { body },
response: { headers: responseHeaders }
};
}
};
var openaiCompatibleTokenUsageSchema$1 = () => z.looseObject({
prompt_tokens: z.number().nullish(),
completion_tokens: z.number().nullish(),
total_tokens: z.number().nullish(),
prompt_tokens_details: z.looseObject({ cached_tokens: z.number().nullish() }).nullish(),
completion_tokens_details: z.looseObject({
reasoning_tokens: z.number().nullish(),
accepted_prediction_tokens: z.number().nullish(),
rejected_prediction_tokens: z.number().nullish()
}).nullish()
}).nullish();
var openAICompatibleContentSchema$1 = () => z.union([z.string(), z.array(z.looseObject({ type: z.string() }))]).nullish();
function convertOpenAICompatibleContent$1(content) {
if (content == null) return [];
if (typeof content === "string") return content.length > 0 ? [{
type: "text",
text: content
}] : [];
const result = [];
for (const part of content) if (part.type === "text" && typeof part.text === "string") {
if (part.text.length > 0) result.push({
type: "text",
text: part.text
});
} else if (part.type === "thinking" && Array.isArray(part.thinking)) {
const reasoningText = part.thinking.filter((chunk) => chunk != null && typeof chunk === "object" && "type" in chunk && chunk.type === "text" && "text" in chunk && typeof chunk.text === "string").map((chunk) => chunk.text).join("");
if (reasoningText.length > 0) result.push({
type: "reasoning",
text: reasoningText
});
}
return result;
}
var OpenAICompatibleChatResponseSchema$1 = lazySchema$1(() => zodSchema$2(z.looseObject({
id: z.string().nullish(),
created: z.number().nullish(),
model: z.string().nullish(),
choices: z.array(z.object({
message: z.object({
role: z.literal("assistant").nullish(),
content: openAICompatibleContentSchema$1(),
reasoning_content: z.string().nullish(),
reasoning: z.string().nullish(),
tool_calls: z.array(z.object({
id: z.string().nullish(),
function: z.object({
name: z.string(),
arguments: z.string()
}),
extra_content: z.object({ google: z.object({ thought_signature: z.string().nullish() }).nullish() }).nullish()
})).nullish()
}),
finish_reason: z.string().nullish()
})),
usage: openaiCompatibleTokenUsageSchema$1()
})));
var chunkBaseSchema$1 = () => z.looseObject({
id: z.string().nullish(),
created: z.number().nullish(),
model: z.string().nullish(),
choices: z.array(z.object({
delta: z.object({
role: z.enum(["assistant", ""]).nullish(),
content: openAICompatibleContentSchema$1(),
reasoning_content: z.string().nullish(),
reasoning: z.string().nullish(),
tool_calls: z.array(z.object({
index: z.number().nullish(),
id: z.string().nullish(),
function: z.object({
name: z.string().nullish(),
arguments: z.string().nullish()
}),
extra_content: z.object({ google: z.object({ thought_signature: z.string().nullish() }).nullish() }).nullish()
})).nullish()
}).nullish(),
finish_reason: z.string().nullish()
})),
usage: openaiCompatibleTokenUsageSchema$1()
});
var createOpenAICompatibleChatChunkSchema$1 = (errorSchema) => z.union([chunkBaseSchema$1(), errorSchema]);
function convertOpenAICompatibleCompletionUsage$1(usage) {
var _a, _b;
if (usage == null) return {
inputTokens: {
total: void 0,
noCache: void 0,
cacheRead: void 0,
cacheWrite: void 0
},
outputTokens: {
total: void 0,
text: void 0,
reasoning: void 0
},
raw: void 0
};
const promptTokens = (_a = usage.prompt_tokens) != null ? _a : 0;
const completionTokens = (_b = usage.completion_tokens) != null ? _b : 0;
return {
inputTokens: {
total: promptTokens,
noCache: promptTokens,
cacheRead: void 0,
cacheWrite: void 0
},
outputTokens: {
total: completionTokens,
text: completionTokens,
reasoning: void 0
},
raw: usage
};
}
function convertToOpenAICompatibleCompletionPrompt$1({ prompt, user = "user", assistant = "assistant" }) {
let text = "";
if (prompt[0].role === "system") {
text += `${prompt[0].content}
`;
prompt = prompt.slice(1);
}
for (const { role, content } of prompt) switch (role) {
case "system": throw new InvalidPromptError$2({
message: "Unexpected system message in prompt: ${content}",
prompt
});
case "user": {
const userMessage = content.map((part) => {
switch (part.type) {
case "text": return part.text;
}
}).filter(Boolean).join("");
text += `${user}:
${userMessage}
`;
break;
}
case "assistant": {
const assistantMessage = content.map((part) => {
switch (part.type) {
case "text": return part.text;
case "tool-call": throw new UnsupportedFunctionalityError$2({ functionality: "tool-call messages" });
}
}).join("");
text += `${assistant}:
${assistantMessage}
`;
break;
}
case "tool": throw new UnsupportedFunctionalityError$2({ functionality: "tool messages" });
default: throw new Error(`Unsupported role: ${role}`);
}
text += `${assistant}:
`;
return {
prompt: text,
stopSequences: [`
${user}:`]
};
}
function getResponseMetadata2$1({ id, model, created }) {
return {
id: id != null ? id : void 0,
modelId: model != null ? model : void 0,
timestamp: created != null ? /* @__PURE__ */ new Date(created * 1e3) : void 0
};
}
function mapOpenAICompatibleFinishReason2(finishReason) {
switch (finishReason) {
case "stop": return "stop";
case "length": return "length";
case "content_filter": return "content-filter";
case "function_call":
case "tool_calls": return "tool-calls";
default: return "other";
}
}
var openaiCompatibleLanguageModelCompletionOptions$1 = lazySchema$1(() => zodSchema$2(z.object({
/**
* Echo back the prompt in addition to the completion.
*/
echo: z.boolean().optional(),
/**
* Modify the likelihood of specified tokens appearing in the completion.
*
* Accepts a JSON object that maps tokens (specified by their token ID in
* the GPT tokenizer) to an associated bias value from -100 to 100.
*/
logitBias: z.record(z.string(), z.number()).optional(),
/**
* The suffix that comes after a completion of inserted text.
*/
suffix: z.string().optional(),
/**
* A unique identifier representing your end-user, which can help providers to
* monitor and detect abuse.
*/
user: z.string().optional()
})));
var OpenAICompatibleCompletionLanguageModel$1 = class {
constructor(modelId, config) {
this.specificationVersion = "v3";
var _a;
this.modelId = modelId;
this.config = config;
const errorStructure = (_a = config.errorStructure) != null ? _a : defaultOpenAICompatibleErrorStructure$1;
this.chunkSchema = createOpenAICompatibleCompletionChunkSchema$1(errorStructure.errorSchema);
this.failedResponseHandler = createJsonErrorResponseHandler$2(errorStructure);
}
get provider() {
return this.config.provider;
}
get providerOptionsName() {
return this.config.provider.split(".")[0].trim();
}
get supportedUrls() {
var _a, _b, _c;
return (_c = (_b = (_a = this.config).supportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {};
}
async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences: userStopSequences, responseFormat, seed, providerOptions, tools, toolChoice }) {
var _a, _b;
const warnings = [];
const completionOptions = Object.assign((_a = await parseProviderOptions$1({
provider: this.providerOptionsName,
providerOptions,
schema: openaiCompatibleLanguageModelCompletionOptions$1
})) != null ? _a : {}, (_b = await parseProviderOptions$1({
provider: toCamelCase$1(this.providerOptionsName),
providerOptions,
schema: openaiCompatibleLanguageModelCompletionOptions$1
})) != null ? _b : {});
if (topK != null) warnings.push({
type: "unsupported",
feature: "topK"
});
if (tools == null ? void 0 : tools.length) warnings.push({
type: "unsupported",
feature: "tools"
});
if (toolChoice != null) warnings.push({
type: "unsupported",
feature: "toolChoice"
});
if (responseFormat != null && responseFormat.type !== "text") warnings.push({
type: "unsupported",
feature: "responseFormat",
details: "JSON response format is not supported."
});
const { prompt: completionPrompt, stopSequences } = convertToOpenAICompatibleCompletionPrompt$1({ prompt });
const stop = [...stopSequences != null ? stopSequences : [], ...userStopSequences != null ? userStopSequences : []];
return {
args: {
model: this.modelId,
echo: completionOptions.echo,
logit_bias: completionOptions.logitBias,
suffix: completionOptions.suffix,
user: completionOptions.user,
max_tokens: maxOutputTokens,
temperature,
top_p: topP,
frequency_penalty: frequencyPenalty,
presence_penalty: presencePenalty,
seed,
...providerOptions == null ? void 0 : providerOptions[this.providerOptionsName],
...providerOptions == null ? void 0 : providerOptions[toCamelCase$1(this.providerOptionsName)],
prompt: completionPrompt,
stop: stop.length > 0 ? stop : void 0
},
warnings
};
}
async doGenerate(options) {
const { args, warnings } = await this.getArgs(options);
const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi$2({
url: this.config.url({
path: "/completions",
modelId: this.modelId
}),
headers: combineHeaders$2(this.config.headers(), options.headers),
body: args,
failedResponseHandler: this.failedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$2(openaiCompatibleCompletionResponseSchema$1),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const choice = response.choices[0];
const content = [];
if (choice.text != null && choice.text.length > 0) content.push({
type: "text",
text: choice.text
});
return {
content,
usage: convertOpenAICompatibleCompletionUsage$1(response.usage),
finishReason: {
unified: mapOpenAICompatibleFinishReason2(choice.finish_reason),
raw: choice.finish_reason
},
request: { body: args },
response: {
...getResponseMetadata2$1(response),
headers: responseHeaders,
body: rawResponse
},
warnings
};
}
async doStream(options) {
const { args, warnings } = await this.getArgs(options);
const body = {
...args,
stream: true,
stream_options: this.config.includeUsage ? { include_usage: true } : void 0
};
const { responseHeaders, value: response } = await postJsonToApi$2({
url: this.config.url({
path: "/completions",
modelId: this.modelId
}),
headers: combineHeaders$2(this.config.headers(), options.headers),
body,
failedResponseHandler: this.failedResponseHandler,
successfulResponseHandler: createEventSourceResponseHandler$2(this.chunkSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
let finishReason = {
unified: "other",
raw: void 0
};
let usage = void 0;
let isFirstChunk = true;
return {
stream: response.pipeThrough(new TransformStream({
start(controller) {
controller.enqueue({
type: "stream-start",
warnings
});
},
transform(chunk, controller) {
var _a;
if (options.includeRawChunks) controller.enqueue({
type: "raw",
rawValue: chunk.rawValue
});
if (!chunk.success) {
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error: chunk.error
});
return;
}
const value = chunk.value;
if ("error" in value) {
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error: value.error
});
return;
}
if (isFirstChunk) {
isFirstChunk = false;
controller.enqueue({
type: "response-metadata",
...getResponseMetadata2$1(value)
});
controller.enqueue({
type: "text-start",
id: "0"
});
}
if (value.usage != null) usage = value.usage;
const choice = value.choices[0];
if ((choice == null ? void 0 : choice.finish_reason) != null) finishReason = {
unified: mapOpenAICompatibleFinishReason2(choice.finish_reason),
raw: (_a = choice.finish_reason) != null ? _a : void 0
};
if ((choice == null ? void 0 : choice.text) != null) controller.enqueue({
type: "text-delta",
id: "0",
delta: choice.text
});
},
flush(controller) {
if (!isFirstChunk) controller.enqueue({
type: "text-end",
id: "0"
});
controller.enqueue({
type: "finish",
finishReason,
usage: convertOpenAICompatibleCompletionUsage$1(usage)
});
}
})),
request: { body },
response: { headers: responseHeaders }
};
}
};
var usageSchema$2 = () => z.looseObject({
prompt_tokens: z.number(),
completion_tokens: z.number(),
total_tokens: z.number()
});
var openaiCompatibleCompletionResponseSchema$1 = lazySchema$1(() => zodSchema$2(z.object({
id: z.string().nullish(),
created: z.number().nullish(),
model: z.string().nullish(),
choices: z.array(z.object({
text: z.string(),
finish_reason: z.string()
})),
usage: usageSchema$2().nullish()
})));
var createOpenAICompatibleCompletionChunkSchema$1 = (errorSchema) => z.union([z.object({
id: z.string().nullish(),
created: z.number().nullish(),
model: z.string().nullish(),
choices: z.array(z.object({
text: z.string(),
finish_reason: z.string().nullish(),
index: z.number()
})),
usage: usageSchema$2().nullish()
}), errorSchema]);
var openaiCompatibleEmbeddingModelOptions$1 = lazySchema$1(() => zodSchema$2(z.object({
/**
* The number of dimensions the resulting output embeddings should have.
* Only supported in text-embedding-3 and later models.
*/
dimensions: z.number().optional(),
/**
* A unique identifier representing your end-user, which can help providers to
* monitor and detect abuse.
*/
user: z.string().optional()
})));
var OpenAICompatibleEmbeddingModel$1 = class {
constructor(modelId, config) {
this.specificationVersion = "v3";
this.modelId = modelId;
this.config = config;
}
get provider() {
return this.config.provider;
}
get maxEmbeddingsPerCall() {
var _a;
return (_a = this.config.maxEmbeddingsPerCall) != null ? _a : 2048;
}
get supportsParallelCalls() {
var _a;
return (_a = this.config.supportsParallelCalls) != null ? _a : true;
}
get providerOptionsName() {
return this.config.provider.split(".")[0].trim();
}
async doEmbed({ values, headers, abortSignal, providerOptions }) {
var _a, _b, _c;
const warnings = [];
const deprecatedOptions = await parseProviderOptions$1({
provider: "openai-compatible",
providerOptions,
schema: openaiCompatibleEmbeddingModelOptions$1
});
if (deprecatedOptions != null) warnings.push({
type: "other",
message: `The 'openai-compatible' key in providerOptions is deprecated. Use 'openaiCompatible' instead.`
});
const compatibleOptions = Object.assign(deprecatedOptions != null ? deprecatedOptions : {}, (_a = await parseProviderOptions$1({
provider: "openaiCompatible",
providerOptions,
schema: openaiCompatibleEmbeddingModelOptions$1
})) != null ? _a : {}, (_b = await parseProviderOptions$1({
provider: this.providerOptionsName,
providerOptions,
schema: openaiCompatibleEmbeddingModelOptions$1
})) != null ? _b : {});
if (values.length > this.maxEmbeddingsPerCall) throw new TooManyEmbeddingValuesForCallError$1({
provider: this.provider,
modelId: this.modelId,
maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
values
});
const { responseHeaders, value: response, rawValue } = await postJsonToApi$2({
url: this.config.url({
path: "/embeddings",
modelId: this.modelId
}),
headers: combineHeaders$2(this.config.headers(), headers),
body: {
model: this.modelId,
input: values,
encoding_format: "float",
dimensions: compatibleOptions.dimensions,
user: compatibleOptions.user
},
failedResponseHandler: createJsonErrorResponseHandler$2((_c = this.config.errorStructure) != null ? _c : defaultOpenAICompatibleErrorStructure$1),
successfulResponseHandler: createJsonResponseHandler$2(openaiTextEmbeddingResponseSchema$2),
abortSignal,
fetch: this.config.fetch
});
return {
warnings,
embeddings: response.data.map((item) => item.embedding),
usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0,
providerMetadata: response.providerMetadata,
response: {
headers: responseHeaders,
body: rawValue
}
};
}
};
var openaiTextEmbeddingResponseSchema$2 = lazySchema$1(() => zodSchema$2(z.object({
data: z.array(z.object({ embedding: z.array(z.number()) })),
usage: z.object({ prompt_tokens: z.number() }).nullish(),
providerMetadata: z.record(z.string(), z.record(z.string(), z.any())).optional()
})));
var OpenAICompatibleImageModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v3";
this.maxImagesPerCall = 10;
}
get provider() {
return this.config.provider;
}
/**
* The provider options key used to extract provider-specific options.
*/
get providerOptionsKey() {
return this.config.provider.split(".")[0].trim();
}
getArgs(providerOptions) {
return {
...providerOptions[this.providerOptionsKey],
...providerOptions[toCamelCase$1(this.providerOptionsKey)]
};
}
async doGenerate({ prompt, n, size, aspectRatio, seed, providerOptions, headers, abortSignal, files, mask }) {
var _a, _b, _c, _d, _e;
const warnings = [];
if (aspectRatio != null) warnings.push({
type: "unsupported",
feature: "aspectRatio",
details: "This model does not support aspect ratio. Use `size` instead."
});
if (seed != null) warnings.push({
type: "unsupported",
feature: "seed"
});
const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
const args = this.getArgs(providerOptions);
const isEditing = files != null && files.length > 0;
const url = this.config.url({
path: isEditing ? "/images/edits" : "/images/generations",
modelId: this.modelId
});
const requestHeaders = combineHeaders$2(this.config.headers(), headers);
if (isEditing) {
const { value: response2, responseHeaders: responseHeaders2 } = await postFormDataToApi$1({
url,
headers: requestHeaders,
formData: convertToFormData$1({
model: this.modelId,
prompt,
image: await Promise.all(files.map((file) => fileToBlob$2(file))),
mask: mask != null ? await fileToBlob$2(mask) : void 0,
n,
size,
...args
}),
failedResponseHandler: createJsonErrorResponseHandler$2((_d = this.config.errorStructure) != null ? _d : defaultOpenAICompatibleErrorStructure$1),
successfulResponseHandler: createJsonResponseHandler$2(openaiCompatibleImageResponseSchema$1),
abortSignal,
fetch: this.config.fetch
});
return {
images: await this.getImages(response2.data, {
url,
headers: requestHeaders,
abortSignal
}),
warnings,
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders2
}
};
}
const { value: response, responseHeaders } = await postJsonToApi$2({
url,
headers: requestHeaders,
body: {
model: this.modelId,
prompt,
n,
size,
...args,
response_format: "b64_json"
},
failedResponseHandler: createJsonErrorResponseHandler$2((_e = this.config.errorStructure) != null ? _e : defaultOpenAICompatibleErrorStructure$1),
successfulResponseHandler: createJsonResponseHandler$2(openaiCompatibleImageResponseSchema$1),
abortSignal,
fetch: this.config.fetch
});
return {
images: await this.getImages(response.data, {
url,
headers: requestHeaders,
abortSignal
}),
warnings,
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders
}
};
}
async getImages(data, options) {
if (data.every((image) => image.b64_json != null)) return data.map((image) => image.b64_json);
return Promise.all(data.map(async (image) => {
if (image.b64_json != null) return convertBase64ToUint8Array$1(image.b64_json);
if (image.url == null) throw new InvalidResponseDataError$2({
data: image,
message: "Expected url in the image response"
});
const { value } = await getFromApi$2({
url: image.url,
validateUrl: true,
trustedOrigin: options.url,
credentialedOrigin: options.url,
headers: options.headers,
abortSignal: options.abortSignal,
fetch: this.config.fetch,
successfulResponseHandler: createBinaryResponseHandler$1(),
failedResponseHandler: createStatusCodeErrorResponseHandler$1()
});
return value;
}));
}
};
var openaiCompatibleImageResponseSchema$1 = lazySchema$1(() => zodSchema$2(z.object({ data: z.array(z.object({
b64_json: z.string().nullish(),
url: z.string().nullish()
}).refine((image) => image.b64_json != null || image.url != null, { message: "Expected b64_json or url in the image response" })) })));
async function fileToBlob$2(file) {
if (file.type === "url") return downloadBlob$1(file.url);
const data = file.data instanceof Uint8Array ? file.data : convertBase64ToUint8Array$1(file.data);
return new Blob([data], { type: file.mediaType });
}
var VERSION$14 = "2.0.88";
function createOpenAICompatible(options) {
const baseURL = withoutTrailingSlash$2(options.baseURL);
const providerName = options.name;
const headers = {
...options.apiKey && { Authorization: `Bearer ${options.apiKey}` },
...options.headers
};
const getHeaders = () => withUserAgentSuffix$2(headers, `ai-sdk/openai-compatible/${VERSION$14}`);
const getCommonModelConfig = (modelType) => ({
provider: `${providerName}.${modelType}`,
url: ({ path }) => {
const url = new URL(`${baseURL}${path}`);
if (options.queryParams) url.search = new URLSearchParams(options.queryParams).toString();
return url.toString();
},
headers: getHeaders,
fetch: options.fetch
});
const createLanguageModel = (modelId) => createChatModel(modelId);
const createChatModel = (modelId) => new OpenAICompatibleChatLanguageModel$1(modelId, {
...getCommonModelConfig("chat"),
includeUsage: options.includeUsage,
supportsStructuredOutputs: options.supportsStructuredOutputs,
supportedUrls: options.supportedUrls,
transformRequestBody: options.transformRequestBody,
metadataExtractor: options.metadataExtractor,
convertUsage: options.convertUsage
});
const createCompletionModel = (modelId) => new OpenAICompatibleCompletionLanguageModel$1(modelId, {
...getCommonModelConfig("completion"),
includeUsage: options.includeUsage
});
const createEmbeddingModel = (modelId) => new OpenAICompatibleEmbeddingModel$1(modelId, { ...getCommonModelConfig("embedding") });
const createImageModel = (modelId) => new OpenAICompatibleImageModel(modelId, getCommonModelConfig("image"));
const provider = (modelId) => createLanguageModel(modelId);
provider.specificationVersion = "v3";
provider.languageModel = createLanguageModel;
provider.chatModel = createChatModel;
provider.completionModel = createCompletionModel;
provider.embeddingModel = createEmbeddingModel;
provider.textEmbeddingModel = createEmbeddingModel;
provider.imageModel = createImageModel;
return provider;
}
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/openai/3.0.135/0cbc2af149c9f6a51280c2a42bf32923563c0fa673ab0f281e180ff76995d307/node_modules/@ai-sdk/openai/dist/index.mjs
var openaiErrorDataSchema = () => z.object({ error: z.object({
message: z.string(),
type: z.string().nullish(),
param: z.any().nullish(),
code: z.union([z.string(), z.number()]).nullish()
}) });
var openaiFailedResponseHandler = createJsonErrorResponseHandler$2({
errorSchema: lazySchema$1(() => zodSchema$2(openaiErrorDataSchema())),
errorToMessage: (data) => data.error.message
});
function getOpenAILanguageModelCapabilities(modelId) {
var _a2, _b, _c, _d, _e;
const oSeriesVersion = getOSeriesVersion(modelId);
const gptVersion = getGptVersion(modelId);
const isGptChatModel = (gptVersion == null ? void 0 : gptVersion.minor) == null && ((_b = (_a2 = gptVersion == null ? void 0 : gptVersion.variant) == null ? void 0 : _a2.startsWith("chat")) != null ? _b : false);
const isGptNanoModel = (_d = (_c = gptVersion == null ? void 0 : gptVersion.variant) == null ? void 0 : _c.startsWith("nano")) != null ? _d : false;
const isGpt6OrLaterModel = gptVersion != null && gptVersion.major >= 6;
const isGpt6OrLaterModelWithNoneEffort = modelId === "gpt-6-sol" || modelId === "gpt-6-luna" || modelId === "gpt-6.1-terra";
const supportsFlexProcessing = oSeriesVersion != null && oSeriesVersion >= 3 || gptVersion != null && gptVersion.major >= 5 && !isGptChatModel;
const supportsPriorityProcessing = modelId.startsWith("gpt-4") || gptVersion != null && gptVersion.major >= 5 && !isGptNanoModel && !isGptChatModel || oSeriesVersion != null && oSeriesVersion >= 3;
const isReasoningModel = oSeriesVersion != null || gptVersion != null && gptVersion.major >= 5 && !isGptChatModel;
const supportsNonReasoningParameters = !isGpt6OrLaterModel && gptVersion != null && (gptVersion.major > 5 || gptVersion.major === 5 && ((_e = gptVersion.minor) != null ? _e : 0) >= 1);
return {
supportsFlexProcessing,
supportsPriorityProcessing,
supportsConfigurationUpdate: isGpt6OrLaterModel,
supportsAsyncToolCalling: isGpt6OrLaterModel,
supportedReasoningEfforts: isGpt6OrLaterModelWithNoneEffort ? [
"none",
"low",
"medium",
"high",
"xhigh",
"max"
] : isGpt6OrLaterModel ? [
"low",
"medium",
"high",
"xhigh",
"max"
] : void 0,
isReasoningModel,
systemMessageMode: isReasoningModel ? "developer" : "system",
supportsNonReasoningParameters
};
}
function getOSeriesVersion(modelId) {
const match = /^o(\d+)(?:-|$)/.exec(modelId);
return match == null ? void 0 : Number(match[1]);
}
function getGptVersion(modelId) {
const match = /^gpt-(\d+)(?:\.(\d+))?(?:-(.+))?$/.exec(modelId);
if (match == null) return;
return {
major: Number(match[1]),
minor: match[2] == null ? void 0 : Number(match[2]),
variant: match[3]
};
}
function normalizeOpenAIJsonSchema(schema) {
const normalizedSchema = normalizeSchema(schema, true);
const reference = getSingletonReference(normalizedSchema);
if (reference == null) return normalizedSchema;
const { allOf: _allOf, ...schemaWithoutAllOf } = normalizedSchema;
const referencedSchema = getLocalReferenceSchema(reference, normalizedSchema);
return typeof referencedSchema !== "object" || referencedSchema == null ? normalizedSchema : {
...referencedSchema,
...schemaWithoutAllOf
};
function normalizeSchema(schema2, isRoot = false) {
if (typeof schema2 !== "object" || schema2 == null) return schema2;
const normalizedSchema2 = { ...schema2 };
if (normalizedSchema2.properties != null) normalizedSchema2.properties = normalizeSchemaRecord(normalizedSchema2.properties);
if (normalizedSchema2.patternProperties != null) normalizedSchema2.patternProperties = normalizeSchemaRecord(normalizedSchema2.patternProperties);
if (normalizedSchema2.definitions != null) normalizedSchema2.definitions = normalizeSchemaRecord(normalizedSchema2.definitions);
if (normalizedSchema2.$defs != null) normalizedSchema2.$defs = normalizeSchemaRecord(normalizedSchema2.$defs);
if (normalizedSchema2.items != null) normalizedSchema2.items = Array.isArray(normalizedSchema2.items) ? normalizedSchema2.items.map((item) => normalizeSchema(item)) : normalizeSchema(normalizedSchema2.items);
if (normalizedSchema2.allOf != null) normalizedSchema2.allOf = normalizedSchema2.allOf.map((item) => normalizeSchema(item));
if (normalizedSchema2.anyOf != null) normalizedSchema2.anyOf = normalizedSchema2.anyOf.map((item) => normalizeSchema(item));
if (normalizedSchema2.oneOf != null) normalizedSchema2.oneOf = normalizedSchema2.oneOf.map((item) => normalizeSchema(item));
if (typeof normalizedSchema2.additionalProperties === "object" && normalizedSchema2.additionalProperties != null) normalizedSchema2.additionalProperties = normalizeSchema(normalizedSchema2.additionalProperties);
const reference2 = getSingletonReference(normalizedSchema2);
if (reference2 == null || isRoot) return normalizedSchema2;
const { allOf: _allOf2, ...schemaWithoutAllOf2 } = normalizedSchema2;
return {
...schemaWithoutAllOf2,
$ref: reference2
};
}
function normalizeSchemaRecord(record) {
return Object.fromEntries(Object.entries(record).map(([key, value]) => [key, normalizeSchema(value)]));
}
function getSingletonReference(schema2) {
var _a2;
if (((_a2 = schema2.allOf) == null ? void 0 : _a2.length) !== 1) return;
const [allOfSchema] = schema2.allOf;
return typeof allOfSchema === "object" && allOfSchema != null && Object.keys(allOfSchema).length === 1 && typeof allOfSchema.$ref === "string" ? allOfSchema.$ref : void 0;
}
function getLocalReferenceSchema(reference2, schema2) {
var _a2, _b;
const match = /^#\/(definitions|\$defs)\/(.+)$/.exec(reference2);
if (match == null) return;
const [, keyword, encodedName] = match;
const name = encodedName.replace(/~1/g, "/").replace(/~0/g, "~");
return keyword === "definitions" ? (_a2 = schema2.definitions) == null ? void 0 : _a2[name] : (_b = schema2.$defs) == null ? void 0 : _b[name];
}
}
function createOpenAIProviderStreamError(frame) {
var _a2, _b;
const streamError = parseStreamError(frame);
if (streamError == null) return;
const statusCode = getStatusCode(streamError);
return {
message: streamError.message,
type: (_a2 = streamError.type) != null ? _a2 : void 0,
code: (_b = streamError.code) != null ? _b : void 0,
statusCode,
isRetryable: isRetryableStreamError(streamError, statusCode),
data: frame
};
}
async function throwIfOpenAIStreamErrorBeforeOutput({ stream, getError, isOutputChunk, url, requestBodyValues, responseHeaders }) {
const [streamForEarlyError, streamForConsumer] = stream.tee();
const reader = streamForEarlyError.getReader();
try {
while (true) {
const result = await reader.read();
if (result.done) return streamForConsumer;
const chunk = result.value;
if (!chunk.success) return streamForConsumer;
const errorFrame = getError(chunk.value);
if (errorFrame != null) {
streamForConsumer.cancel().catch(() => {});
throw createOpenAIStreamError({
frame: errorFrame,
url,
requestBodyValues,
responseHeaders
});
}
if (isOutputChunk(chunk.value)) return streamForConsumer;
}
} finally {
reader.cancel().catch(() => {});
reader.releaseLock();
}
}
function createOpenAIStreamError({ frame, url, requestBodyValues, responseHeaders }) {
var _a2;
const streamError = parseStreamError(frame);
return new APICallError$2({
message: (_a2 = streamError == null ? void 0 : streamError.message) != null ? _a2 : "OpenAI stream failed before any output was generated",
url,
requestBodyValues,
statusCode: streamError == null ? 500 : getStatusCode(streamError),
responseHeaders,
responseBody: JSON.stringify(frame),
data: frame,
isRetryable: streamError == null ? true : isRetryableStreamError(streamError, getStatusCode(streamError))
});
}
function parseStreamError(frame) {
var _a2;
const value = asRecord(frame);
if (value == null) return;
if (value.type === "response.failed") {
const response = asRecord(value.response);
const responseError = asRecord(response == null ? void 0 : response.error);
return typeof (responseError == null ? void 0 : responseError.message) === "string" ? {
message: responseError.message,
code: getStringOrNumber(responseError.code),
type: "response.failed"
} : void 0;
}
const error = (_a2 = asRecord(value.error)) != null ? _a2 : value;
return typeof error.message === "string" && (asRecord(value.error) != null || typeof error.type === "string" || "code" in error || "param" in error) ? {
message: error.message,
code: getStringOrNumber(error.code),
type: typeof error.type === "string" ? error.type : void 0
} : void 0;
}
function getStatusCode(error) {
if (typeof error.code === "number" && isHttpErrorStatusCode(error.code)) return error.code;
if (typeof error.code === "string" && /^\d{3}$/.test(error.code)) {
const numericCode = Number(error.code);
if (isHttpErrorStatusCode(numericCode)) return numericCode;
}
const discriminator = [error.code, error.type].filter((value) => typeof value === "string" || typeof value === "number").join(" ").toLowerCase();
if (["insufficient_quota", "rate_limit"].some((term) => discriminator.includes(term))) return 429;
if (discriminator.includes("authentication")) return 401;
if (discriminator.includes("permission")) return 403;
if (discriminator.includes("not_found")) return 404;
if ([
"invalid",
"bad_request",
"context_length"
].some((term) => discriminator.includes(term))) return 400;
if (discriminator.includes("overload")) return 503;
if (discriminator.includes("timeout")) return 504;
return 500;
}
function asRecord(value) {
return typeof value === "object" && value != null ? value : void 0;
}
function getStringOrNumber(value) {
return typeof value === "string" || typeof value === "number" ? value : void 0;
}
function isHttpErrorStatusCode(value) {
return Number.isInteger(value) && value >= 400 && value <= 599;
}
function isRetryableStatusCode$2(statusCode) {
return statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500;
}
function isRetryableStreamError(error, statusCode) {
if (error.code === "insufficient_quota" || error.type === "insufficient_quota") return false;
return isRetryableStatusCode$2(statusCode);
}
function convertOpenAIChatUsage(usage) {
var _a2, _b, _c, _d, _e, _f, _g, _h;
if (usage == null) return {
inputTokens: {
total: void 0,
noCache: void 0,
cacheRead: void 0,
cacheWrite: void 0
},
outputTokens: {
total: void 0,
text: void 0,
reasoning: void 0
},
raw: void 0
};
const promptTokens = (_a2 = usage.prompt_tokens) != null ? _a2 : 0;
const completionTokens = (_b = usage.completion_tokens) != null ? _b : 0;
const cachedTokens = (_d = (_c = usage.prompt_tokens_details) == null ? void 0 : _c.cached_tokens) != null ? _d : 0;
const cacheWriteTokens = (_f = (_e = usage.prompt_tokens_details) == null ? void 0 : _e.cache_write_tokens) != null ? _f : void 0;
const reasoningTokens = (_h = (_g = usage.completion_tokens_details) == null ? void 0 : _g.reasoning_tokens) != null ? _h : 0;
return {
inputTokens: {
total: promptTokens,
noCache: promptTokens - cachedTokens - (cacheWriteTokens != null ? cacheWriteTokens : 0),
cacheRead: cachedTokens,
cacheWrite: cacheWriteTokens
},
outputTokens: {
total: completionTokens,
text: Math.max(0, completionTokens - reasoningTokens),
reasoning: reasoningTokens
},
raw: usage
};
}
function serializeToolCallArguments(input) {
return JSON.stringify(typeof input === "object" && input !== null && !Array.isArray(input) ? input : {});
}
function getPromptCacheBreakpoint(providerOptions) {
var _a2;
return (_a2 = providerOptions == null ? void 0 : providerOptions.openai) == null ? void 0 : _a2.promptCacheBreakpoint;
}
function convertToOpenAIChatMessages({ prompt, systemMessageMode = "system" }) {
var _a2, _b;
const messages = [];
const warnings = [];
for (const { role, content, providerOptions } of prompt) switch (role) {
case "system":
switch (systemMessageMode) {
case "system": {
const promptCacheBreakpoint = getPromptCacheBreakpoint(providerOptions);
messages.push({
role: "system",
content: promptCacheBreakpoint == null ? content : [{
type: "text",
text: content,
prompt_cache_breakpoint: promptCacheBreakpoint
}]
});
break;
}
case "developer": {
const promptCacheBreakpoint = getPromptCacheBreakpoint(providerOptions);
messages.push({
role: "developer",
content: promptCacheBreakpoint == null ? content : [{
type: "text",
text: content,
prompt_cache_breakpoint: promptCacheBreakpoint
}]
});
break;
}
case "remove":
warnings.push({
type: "other",
message: "system messages are removed for this model"
});
break;
default: throw new Error(`Unsupported system message mode: ${systemMessageMode}`);
}
break;
case "user":
if (content.length === 1 && content[0].type === "text" && getPromptCacheBreakpoint(content[0].providerOptions) == null) {
messages.push({
role: "user",
content: content[0].text
});
break;
}
messages.push({
role: "user",
content: content.map((part, index) => {
var _a3, _b2, _c;
switch (part.type) {
case "text": {
const promptCacheBreakpoint = getPromptCacheBreakpoint(part.providerOptions);
return {
type: "text",
text: part.text,
...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint }
};
}
case "file": {
const promptCacheBreakpoint = getPromptCacheBreakpoint(part.providerOptions);
if (part.mediaType.startsWith("image/")) {
const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
return {
type: "image_url",
image_url: {
url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${convertToBase64$1(part.data)}`,
detail: (_b2 = (_a3 = part.providerOptions) == null ? void 0 : _a3.openai) == null ? void 0 : _b2.imageDetail
},
...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint }
};
} else if (part.mediaType.startsWith("audio/")) {
if (part.data instanceof URL) throw new UnsupportedFunctionalityError$2({ functionality: "audio file parts with URLs" });
switch (part.mediaType) {
case "audio/wav": return {
type: "input_audio",
input_audio: {
data: convertToBase64$1(part.data),
format: "wav"
},
...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint }
};
case "audio/mp3":
case "audio/mpeg": return {
type: "input_audio",
input_audio: {
data: convertToBase64$1(part.data),
format: "mp3"
},
...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint }
};
default: throw new UnsupportedFunctionalityError$2({ functionality: `audio content parts with media type ${part.mediaType}` });
}
} else if (part.mediaType === "application/pdf") {
if (part.data instanceof URL) throw new UnsupportedFunctionalityError$2({ functionality: "PDF file parts with URLs" });
return {
type: "file",
file: typeof part.data === "string" && part.data.startsWith("file-") ? { file_id: part.data } : {
filename: (_c = part.filename) != null ? _c : `part-${index}.pdf`,
file_data: `data:application/pdf;base64,${convertToBase64$1(part.data)}`
},
...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint }
};
} else throw new UnsupportedFunctionalityError$2({ functionality: `file part media type ${part.mediaType}` });
}
}
})
});
break;
case "assistant": {
let text = "";
const textParts = [];
let hasPromptCacheBreakpoint = false;
const toolCalls = [];
for (const part of content) switch (part.type) {
case "text": {
const promptCacheBreakpoint = getPromptCacheBreakpoint(part.providerOptions);
text += part.text;
textParts.push({
type: "text",
text: part.text,
...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint }
});
hasPromptCacheBreakpoint || (hasPromptCacheBreakpoint = promptCacheBreakpoint != null);
break;
}
case "tool-call": toolCalls.push({
id: part.toolCallId,
type: "function",
function: {
name: part.toolName,
arguments: serializeToolCallArguments(part.input)
}
});
}
messages.push({
role: "assistant",
content: hasPromptCacheBreakpoint ? textParts : toolCalls.length > 0 ? text || null : text,
tool_calls: toolCalls.length > 0 ? toolCalls : void 0
});
break;
}
case "tool":
for (const toolResponse of content) {
if (toolResponse.type === "tool-approval-response") continue;
const output = toolResponse.output;
const promptCacheBreakpoint = (_a2 = output.type === "content" ? output.value.map((part) => getPromptCacheBreakpoint(part.providerOptions)).find((breakpoint) => breakpoint != null) : getPromptCacheBreakpoint(output.providerOptions)) != null ? _a2 : getPromptCacheBreakpoint(toolResponse.providerOptions);
let contentValue;
switch (output.type) {
case "text":
case "error-text":
contentValue = output.value;
break;
case "execution-denied":
contentValue = (_b = output.reason) != null ? _b : "Tool call execution denied.";
break;
case "content":
case "json":
case "error-json": contentValue = JSON.stringify(output.value);
}
messages.push({
role: "tool",
tool_call_id: toolResponse.toolCallId,
content: promptCacheBreakpoint == null ? contentValue : [{
type: "text",
text: contentValue,
prompt_cache_breakpoint: promptCacheBreakpoint
}]
});
}
break;
default: throw new Error(`Unsupported role: ${role}`);
}
return {
messages,
warnings
};
}
function getResponseMetadata$3({ id, model, created }) {
return {
id: id != null ? id : void 0,
modelId: model != null ? model : void 0,
timestamp: created ? /* @__PURE__ */ new Date(created * 1e3) : void 0
};
}
function mapOpenAIFinishReason(finishReason) {
switch (finishReason) {
case "stop": return "stop";
case "length": return "length";
case "content_filter": return "content-filter";
case "function_call":
case "tool_calls": return "tool-calls";
default: return "other";
}
}
var openaiChatResponseSchema = lazySchema$1(() => zodSchema$2(z.object({
id: z.string().nullish(),
created: z.number().nullish(),
model: z.string().nullish(),
choices: z.array(z.object({
message: z.object({
role: z.literal("assistant").nullish(),
content: z.string().nullish(),
audio: z.object({ transcript: z.string().nullish() }).nullish(),
tool_calls: z.array(z.object({
id: z.string().nullish(),
type: z.literal("function"),
function: z.object({
name: z.string(),
arguments: z.string()
})
})).nullish(),
annotations: z.array(z.object({
type: z.literal("url_citation"),
url_citation: z.object({
start_index: z.number(),
end_index: z.number(),
url: z.string(),
title: z.string()
})
})).nullish()
}),
index: z.number(),
logprobs: z.object({ content: z.array(z.object({
token: z.string(),
logprob: z.number(),
top_logprobs: z.array(z.object({
token: z.string(),
logprob: z.number()
}))
})).nullish() }).nullish(),
finish_reason: z.string().nullish()
})),
usage: z.object({
prompt_tokens: z.number().nullish(),
completion_tokens: z.number().nullish(),
total_tokens: z.number().nullish(),
prompt_tokens_details: z.object({
cached_tokens: z.number().nullish(),
cache_write_tokens: z.number().nullish()
}).nullish(),
completion_tokens_details: z.object({
reasoning_tokens: z.number().nullish(),
accepted_prediction_tokens: z.number().nullish(),
rejected_prediction_tokens: z.number().nullish()
}).nullish()
}).nullish()
})));
var openaiChatChunkSchema = lazySchema$1(() => zodSchema$2(z.union([z.object({
id: z.string().nullish(),
created: z.number().nullish(),
model: z.string().nullish(),
choices: z.array(z.object({
delta: z.object({
role: z.enum(["assistant"]).nullish(),
content: z.string().nullish(),
tool_calls: z.array(z.object({
index: z.number(),
id: z.string().nullish(),
type: z.literal("function").nullish(),
function: z.object({
name: z.string().nullish(),
arguments: z.string().nullish()
})
})).nullish(),
annotations: z.array(z.object({
type: z.literal("url_citation"),
url_citation: z.object({
start_index: z.number(),
end_index: z.number(),
url: z.string(),
title: z.string()
})
})).nullish()
}).nullish(),
logprobs: z.object({ content: z.array(z.object({
token: z.string(),
logprob: z.number(),
top_logprobs: z.array(z.object({
token: z.string(),
logprob: z.number()
}))
})).nullish() }).nullish(),
finish_reason: z.string().nullish(),
index: z.number()
})),
usage: z.object({
prompt_tokens: z.number().nullish(),
completion_tokens: z.number().nullish(),
total_tokens: z.number().nullish(),
prompt_tokens_details: z.object({
cached_tokens: z.number().nullish(),
cache_write_tokens: z.number().nullish()
}).nullish(),
completion_tokens_details: z.object({
reasoning_tokens: z.number().nullish(),
accepted_prediction_tokens: z.number().nullish(),
rejected_prediction_tokens: z.number().nullish()
}).nullish()
}).nullish()
}), openaiErrorDataSchema()])));
var openaiLanguageModelChatOptions = lazySchema$1(() => zodSchema$2(z.object({
/**
* Modify the likelihood of specified tokens appearing in the completion.
*
* Accepts a JSON object that maps tokens (specified by their token ID in
* the GPT tokenizer) to an associated bias value from -100 to 100.
*/
logitBias: z.record(z.coerce.number(), z.number()).optional(),
/**
* Return the log probabilities of the tokens.
*
* Setting to true will return the log probabilities of the tokens that
* were generated.
*
* Setting to a number will return the log probabilities of the top n
* tokens that were generated.
*/
logprobs: z.union([z.boolean(), z.number()]).optional(),
/**
* Whether to enable parallel function calling during tool use. Default to true.
*/
parallelToolCalls: z.boolean().optional(),
/**
* A unique identifier representing your end-user, which can help OpenAI to
* monitor and detect abuse.
*/
user: z.string().optional(),
/**
* Reasoning effort for reasoning models. Defaults to `medium`.
* GPT-6 and later models support 'low' | 'medium' | 'high' | 'xhigh' | 'max'.
*/
reasoningEffort: z.enum([
"none",
"minimal",
"low",
"medium",
"high",
"xhigh",
"max"
]).optional(),
/**
* Maximum number of completion tokens to generate. Useful for reasoning models.
*/
maxCompletionTokens: z.number().optional(),
/**
* Whether to enable persistence in responses API.
*/
store: z.boolean().optional(),
/**
* Metadata to associate with the request.
*/
metadata: z.record(z.string().max(64), z.string().max(512)).optional(),
/**
* Parameters for prediction mode.
*/
prediction: z.record(z.string(), z.any()).optional(),
/**
* Service tier for the request.
* - 'auto': Default service tier. The request will be processed with the service tier configured in the
* Project settings. Unless otherwise configured, the Project will use 'default'.
* - 'flex': 50% cheaper processing at the cost of increased latency. Only available for o3 and o4-mini models.
* - 'priority': Higher-speed processing with predictably low latency at premium cost. Available for Enterprise customers.
* - 'fast': OpenAI's newer name for the 'priority' tier. Interchangeable with it.
* - 'ultrafast': Access-controlled Ultrafast processing. Only available for gpt-5.6-sol.
* - 'default': The request will be processed with the standard pricing and performance for the selected model.
*
* @default 'auto'
*/
serviceTier: z.enum([
"auto",
"flex",
"priority",
"fast",
"ultrafast",
"default"
]).optional(),
/**
* Whether to use strict JSON schema validation.
*
* @default true
*/
strictJsonSchema: z.boolean().optional(),
/**
* Controls the verbosity of the model's responses.
* Lower values will result in more concise responses, while higher values will result in more verbose responses.
*/
textVerbosity: z.enum([
"low",
"medium",
"high"
]).optional(),
/**
* A cache key for prompt caching. Allows manual control over prompt caching behavior.
* Useful for improving cache hit rates and working around automatic caching issues.
*/
promptCacheKey: z.string().optional(),
/**
* Prompt cache behavior for GPT-5.6 and later models.
* `mode` controls whether OpenAI also places an implicit breakpoint.
* `ttl` sets the minimum cache lifetime and currently only supports 30 minutes.
*/
promptCacheOptions: z.object({
mode: z.enum(["implicit", "explicit"]).optional(),
ttl: z.literal("30m").optional()
}).optional(),
/**
* The retention policy for the prompt cache.
* - 'in_memory': Default. Standard prompt caching behavior.
* - '24h': Extended prompt caching that keeps cached prefixes active for up to 24 hours.
* Available for models before GPT-5.6 that support extended caching.
*
* @deprecated For GPT-5.6 and later models, use `promptCacheOptions.ttl`.
*
* @default 'in_memory'
*/
promptCacheRetention: z.enum(["in_memory", "24h"]).optional(),
/**
* A stable identifier used to help detect users of your application
* that may be violating OpenAI's usage policies. The IDs should be a
* string that uniquely identifies each user. We recommend hashing their
* username or email address, in order to avoid sending us any identifying
* information.
*/
safetyIdentifier: z.string().optional(),
/**
* Override the system message mode for this model.
* - 'system': Use the 'system' role for system messages (default for most models)
* - 'developer': Use the 'developer' role for system messages (used by reasoning models)
* - 'remove': Remove system messages entirely
*
* If not specified, the mode is automatically determined based on the model.
*/
systemMessageMode: z.enum([
"system",
"developer",
"remove"
]).optional(),
/**
* Force treating this model as a reasoning model.
*
* This is useful for "stealth" reasoning models (e.g. via a custom baseURL)
* where the model ID is not recognized by the SDK's allowlist.
*
* When enabled, the SDK applies reasoning-model parameter compatibility rules
* and defaults `systemMessageMode` to `developer` unless overridden.
*/
forceReasoning: z.boolean().optional()
})));
function prepareChatTools({ tools, toolChoice }) {
tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
const toolWarnings = [];
if (tools == null) return {
tools: void 0,
toolChoice: void 0,
toolWarnings
};
const openaiTools2 = [];
for (const tool of tools) switch (tool.type) {
case "function":
openaiTools2.push({
type: "function",
function: {
name: tool.name,
description: tool.description,
parameters: tool.inputSchema,
...tool.strict != null ? { strict: tool.strict } : {}
}
});
break;
default: toolWarnings.push({
type: "unsupported",
feature: `tool type: ${tool.type}`
});
}
if (toolChoice == null) return {
tools: openaiTools2,
toolChoice: void 0,
toolWarnings
};
const type = toolChoice.type;
switch (type) {
case "auto":
case "none":
case "required": return {
tools: openaiTools2,
toolChoice: type,
toolWarnings
};
case "tool": return {
tools: openaiTools2,
toolChoice: {
type: "function",
function: { name: toolChoice.toolName }
},
toolWarnings
};
default: throw new UnsupportedFunctionalityError$2({ functionality: `tool choice type: ${type}` });
}
}
var OpenAIChatLanguageModel = class {
constructor(modelId, config) {
this.specificationVersion = "v3";
this.supportedUrls = { "image/*": [/^https?:\/\/.*$/] };
this.modelId = modelId;
this.config = config;
}
get provider() {
return this.config.provider;
}
async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, responseFormat, seed, tools, toolChoice, providerOptions }) {
var _a2, _b, _c, _d, _e;
const warnings = [];
const openaiOptions = (_a2 = await parseProviderOptions$1({
provider: "openai",
providerOptions,
schema: openaiLanguageModelChatOptions
})) != null ? _a2 : {};
const modelCapabilities = getOpenAILanguageModelCapabilities(this.modelId);
const isReasoningModel = (_b = openaiOptions.forceReasoning) != null ? _b : modelCapabilities.isReasoningModel;
let resolvedReasoningEffort = openaiOptions.reasoningEffort;
if (resolvedReasoningEffort != null && modelCapabilities.supportedReasoningEfforts != null && !modelCapabilities.supportedReasoningEfforts.includes(resolvedReasoningEffort)) {
warnings.push({
type: "unsupported",
feature: "reasoningEffort",
details: `${this.modelId} only supports the following reasoning efforts: ${modelCapabilities.supportedReasoningEfforts.join(", ")}`
});
resolvedReasoningEffort = void 0;
}
if (topK != null) warnings.push({
type: "unsupported",
feature: "topK"
});
const { messages, warnings: messageWarnings } = convertToOpenAIChatMessages({
prompt,
systemMessageMode: (_c = openaiOptions.systemMessageMode) != null ? _c : isReasoningModel ? "developer" : modelCapabilities.systemMessageMode
});
warnings.push(...messageWarnings);
const strictJsonSchema = (_d = openaiOptions.strictJsonSchema) != null ? _d : true;
const baseArgs = {
model: this.modelId,
logit_bias: openaiOptions.logitBias,
logprobs: openaiOptions.logprobs === true || typeof openaiOptions.logprobs === "number" ? true : void 0,
top_logprobs: typeof openaiOptions.logprobs === "number" ? openaiOptions.logprobs : typeof openaiOptions.logprobs === "boolean" ? openaiOptions.logprobs ? 0 : void 0 : void 0,
user: openaiOptions.user,
parallel_tool_calls: openaiOptions.parallelToolCalls,
max_tokens: maxOutputTokens,
temperature,
top_p: topP,
frequency_penalty: frequencyPenalty,
presence_penalty: presencePenalty,
response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? responseFormat.schema != null ? {
type: "json_schema",
json_schema: {
schema: normalizeOpenAIJsonSchema(responseFormat.schema),
strict: strictJsonSchema,
name: (_e = responseFormat.name) != null ? _e : "response",
description: responseFormat.description
}
} : { type: "json_object" } : void 0,
stop: stopSequences,
seed,
verbosity: openaiOptions.textVerbosity,
max_completion_tokens: openaiOptions.maxCompletionTokens,
store: openaiOptions.store,
metadata: openaiOptions.metadata,
prediction: openaiOptions.prediction,
reasoning_effort: resolvedReasoningEffort,
service_tier: openaiOptions.serviceTier,
prompt_cache_key: openaiOptions.promptCacheKey,
prompt_cache_options: openaiOptions.promptCacheOptions,
prompt_cache_retention: openaiOptions.promptCacheRetention,
safety_identifier: openaiOptions.safetyIdentifier,
messages
};
if (modelCapabilities.supportedReasoningEfforts != null && baseArgs.prompt_cache_retention != null) {
baseArgs.prompt_cache_retention = void 0;
warnings.push({
type: "unsupported",
feature: "promptCacheRetention",
details: "promptCacheRetention is not supported by GPT-6 and later models; use promptCacheOptions instead"
});
}
if (isReasoningModel) {
if (openaiOptions.reasoningEffort !== "none" || !modelCapabilities.supportsNonReasoningParameters) {
if (baseArgs.temperature != null) {
baseArgs.temperature = void 0;
warnings.push({
type: "unsupported",
feature: "temperature",
details: "temperature is not supported for reasoning models"
});
}
if (baseArgs.top_p != null) {
baseArgs.top_p = void 0;
warnings.push({
type: "unsupported",
feature: "topP",
details: "topP is not supported for reasoning models"
});
}
if (baseArgs.logprobs != null) {
baseArgs.logprobs = void 0;
warnings.push({
type: "other",
message: "logprobs is not supported for reasoning models"
});
}
}
if (baseArgs.frequency_penalty != null) {
baseArgs.frequency_penalty = void 0;
warnings.push({
type: "unsupported",
feature: "frequencyPenalty",
details: "frequencyPenalty is not supported for reasoning models"
});
}
if (baseArgs.presence_penalty != null) {
baseArgs.presence_penalty = void 0;
warnings.push({
type: "unsupported",
feature: "presencePenalty",
details: "presencePenalty is not supported for reasoning models"
});
}
if (baseArgs.logit_bias != null) {
baseArgs.logit_bias = void 0;
warnings.push({
type: "other",
message: "logitBias is not supported for reasoning models"
});
}
if (baseArgs.top_logprobs != null) {
baseArgs.top_logprobs = void 0;
warnings.push({
type: "other",
message: "topLogprobs is not supported for reasoning models"
});
}
if (baseArgs.max_tokens != null) {
if (baseArgs.max_completion_tokens == null) baseArgs.max_completion_tokens = baseArgs.max_tokens;
baseArgs.max_tokens = void 0;
}
} else if (this.modelId.startsWith("gpt-4o-search-preview") || this.modelId.startsWith("gpt-4o-mini-search-preview")) {
if (baseArgs.temperature != null) {
baseArgs.temperature = void 0;
warnings.push({
type: "unsupported",
feature: "temperature",
details: "temperature is not supported for the search preview models and has been removed."
});
}
}
if (openaiOptions.serviceTier === "flex" && !modelCapabilities.supportsFlexProcessing) {
warnings.push({
type: "unsupported",
feature: "serviceTier",
details: "flex processing is only available for o3, o4-mini, and gpt-5 models"
});
baseArgs.service_tier = void 0;
}
if ((openaiOptions.serviceTier === "priority" || openaiOptions.serviceTier === "fast") && !modelCapabilities.supportsPriorityProcessing) {
warnings.push({
type: "unsupported",
feature: "serviceTier",
details: "priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"
});
baseArgs.service_tier = void 0;
}
const { tools: openaiTools2, toolChoice: openaiToolChoice, toolWarnings } = prepareChatTools({
tools,
toolChoice
});
return {
args: {
...baseArgs,
tools: openaiTools2,
tool_choice: openaiToolChoice
},
warnings: [...warnings, ...toolWarnings]
};
}
async doGenerate(options) {
var _a2, _b, _c, _d, _e, _f, _g, _h;
const { args: body, warnings } = await this.getArgs(options);
const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi$2({
url: this.config.url({
path: "/chat/completions",
modelId: this.modelId
}),
headers: combineHeaders$2(this.config.headers(), options.headers),
body,
failedResponseHandler: openaiFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$2(openaiChatResponseSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const choice = response.choices[0];
if (choice == null) throw new InvalidResponseDataError$2({
data: rawResponse,
message: "Response did not contain any choices."
});
const content = [];
const text = choice.message.content != null && choice.message.content.length > 0 ? choice.message.content : (_a2 = choice.message.audio) == null ? void 0 : _a2.transcript;
if (text != null && text.length > 0) content.push({
type: "text",
text
});
for (const toolCall of (_b = choice.message.tool_calls) != null ? _b : []) content.push({
type: "tool-call",
toolCallId: (_c = toolCall.id) != null ? _c : generateId$2(),
toolName: toolCall.function.name,
input: toolCall.function.arguments
});
for (const annotation of (_d = choice.message.annotations) != null ? _d : []) content.push({
type: "source",
sourceType: "url",
id: generateId$2(),
url: annotation.url_citation.url,
title: annotation.url_citation.title
});
const completionTokenDetails = (_e = response.usage) == null ? void 0 : _e.completion_tokens_details;
(_f = response.usage) == null || _f.prompt_tokens_details;
const providerMetadata = { openai: {} };
if ((completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens) != null) providerMetadata.openai.acceptedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens;
if ((completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens) != null) providerMetadata.openai.rejectedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens;
if (((_g = choice.logprobs) == null ? void 0 : _g.content) != null) providerMetadata.openai.logprobs = choice.logprobs.content;
return {
content,
finishReason: {
unified: mapOpenAIFinishReason(choice.finish_reason),
raw: (_h = choice.finish_reason) != null ? _h : void 0
},
usage: convertOpenAIChatUsage(response.usage),
request: { body },
response: {
...getResponseMetadata$3(response),
headers: responseHeaders,
body: rawResponse
},
warnings,
providerMetadata
};
}
async doStream(options) {
const { args, warnings } = await this.getArgs(options);
const body = {
...args,
stream: true,
stream_options: { include_usage: true }
};
const url = this.config.url({
path: "/chat/completions",
modelId: this.modelId
});
const { responseHeaders, value: response } = await postJsonToApi$2({
url,
headers: combineHeaders$2(this.config.headers(), options.headers),
body,
failedResponseHandler: openaiFailedResponseHandler,
successfulResponseHandler: createEventSourceResponseHandler$2(openaiChatChunkSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const checkedResponse = await throwIfOpenAIStreamErrorBeforeOutput({
stream: response,
getError: (chunk) => "error" in chunk ? chunk.error : void 0,
isOutputChunk: isOpenAIChatOutputChunk,
url,
requestBodyValues: body,
responseHeaders
});
let toolCallTracker;
let finishReason = {
unified: "other",
raw: void 0
};
let usage = void 0;
let metadataExtracted = false;
let isActiveText = false;
const providerMetadata = { openai: {} };
return {
stream: checkedResponse.pipeThrough(new TransformStream({
start(controller) {
toolCallTracker = new StreamingToolCallTracker$1(controller, {
generateId: generateId$2,
typeValidation: "if-present"
});
controller.enqueue({
type: "stream-start",
warnings
});
},
transform(chunk, controller) {
var _a2, _b, _c, _d, _e;
if (options.includeRawChunks) controller.enqueue({
type: "raw",
rawValue: chunk.rawValue
});
if (!chunk.success) {
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error: chunk.error
});
return;
}
const value = chunk.value;
if ("error" in value) {
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error: value.error
});
return;
}
if (!metadataExtracted) {
const metadata = getResponseMetadata$3(value);
if (Object.values(metadata).some(Boolean)) {
metadataExtracted = true;
controller.enqueue({
type: "response-metadata",
...getResponseMetadata$3(value)
});
}
}
if (value.usage != null) {
usage = value.usage;
if (((_a2 = value.usage.completion_tokens_details) == null ? void 0 : _a2.accepted_prediction_tokens) != null) providerMetadata.openai.acceptedPredictionTokens = (_b = value.usage.completion_tokens_details) == null ? void 0 : _b.accepted_prediction_tokens;
if (((_c = value.usage.completion_tokens_details) == null ? void 0 : _c.rejected_prediction_tokens) != null) providerMetadata.openai.rejectedPredictionTokens = (_d = value.usage.completion_tokens_details) == null ? void 0 : _d.rejected_prediction_tokens;
}
const choice = value.choices[0];
if ((choice == null ? void 0 : choice.finish_reason) != null) finishReason = {
unified: mapOpenAIFinishReason(choice.finish_reason),
raw: choice.finish_reason
};
if (((_e = choice == null ? void 0 : choice.logprobs) == null ? void 0 : _e.content) != null) providerMetadata.openai.logprobs = choice.logprobs.content;
if ((choice == null ? void 0 : choice.delta) == null) return;
const delta = choice.delta;
if (delta.content != null) {
if (!isActiveText) {
controller.enqueue({
type: "text-start",
id: "0"
});
isActiveText = true;
}
controller.enqueue({
type: "text-delta",
id: "0",
delta: delta.content
});
}
if (delta.tool_calls != null) for (const toolCallDelta of delta.tool_calls) toolCallTracker.processDelta(toolCallDelta);
if (delta.annotations != null) for (const annotation of delta.annotations) controller.enqueue({
type: "source",
sourceType: "url",
id: generateId$2(),
url: annotation.url_citation.url,
title: annotation.url_citation.title
});
},
flush(controller) {
if (isActiveText) controller.enqueue({
type: "text-end",
id: "0"
});
toolCallTracker.flush();
controller.enqueue({
type: "finish",
finishReason,
usage: convertOpenAIChatUsage(usage),
...providerMetadata != null ? { providerMetadata } : {}
});
}
})),
request: { body },
response: { headers: responseHeaders }
};
}
};
function isOpenAIChatOutputChunk(chunk) {
if ("error" in chunk) return false;
return chunk.choices.some((choice) => {
const delta = choice.delta;
return (delta == null ? void 0 : delta.content) != null && delta.content.length > 0 || (delta == null ? void 0 : delta.tool_calls) != null && delta.tool_calls.length > 0 || (delta == null ? void 0 : delta.annotations) != null && delta.annotations.length > 0;
});
}
function convertOpenAICompletionUsage(usage) {
var _a2, _b, _c, _d;
if (usage == null) return {
inputTokens: {
total: void 0,
noCache: void 0,
cacheRead: void 0,
cacheWrite: void 0
},
outputTokens: {
total: void 0,
text: void 0,
reasoning: void 0
},
raw: void 0
};
const promptTokens = (_a2 = usage.prompt_tokens) != null ? _a2 : 0;
const completionTokens = (_b = usage.completion_tokens) != null ? _b : 0;
return {
inputTokens: {
total: (_c = usage.prompt_tokens) != null ? _c : void 0,
noCache: promptTokens,
cacheRead: void 0,
cacheWrite: void 0
},
outputTokens: {
total: (_d = usage.completion_tokens) != null ? _d : void 0,
text: completionTokens,
reasoning: void 0
},
raw: usage
};
}
function convertToOpenAICompletionPrompt({ prompt, user = "user", assistant = "assistant" }) {
let text = "";
if (prompt[0].role === "system") {
text += `${prompt[0].content}
`;
prompt = prompt.slice(1);
}
for (const { role, content } of prompt) switch (role) {
case "system": throw new InvalidPromptError$2({
message: "Unexpected system message in prompt: ${content}",
prompt
});
case "user": {
const userMessage = content.map((part) => {
switch (part.type) {
case "text": return part.text;
}
}).filter(Boolean).join("");
text += `${user}:
${userMessage}
`;
break;
}
case "assistant": {
const assistantMessage = content.map((part) => {
switch (part.type) {
case "text": return part.text;
case "tool-call": throw new UnsupportedFunctionalityError$2({ functionality: "tool-call messages" });
}
}).join("");
text += `${assistant}:
${assistantMessage}
`;
break;
}
case "tool": throw new UnsupportedFunctionalityError$2({ functionality: "tool messages" });
default: throw new Error(`Unsupported role: ${role}`);
}
text += `${assistant}:
`;
return {
prompt: text,
stopSequences: [`
${user}:`]
};
}
function getResponseMetadata2({ id, model, created }) {
return {
id: id != null ? id : void 0,
modelId: model != null ? model : void 0,
timestamp: created != null ? /* @__PURE__ */ new Date(created * 1e3) : void 0
};
}
function mapOpenAIFinishReason2(finishReason) {
switch (finishReason) {
case "stop": return "stop";
case "length": return "length";
case "content_filter": return "content-filter";
case "function_call":
case "tool_calls": return "tool-calls";
default: return "other";
}
}
var openaiCompletionResponseSchema = lazySchema$1(() => zodSchema$2(z.object({
id: z.string().nullish(),
created: z.number().nullish(),
model: z.string().nullish(),
choices: z.array(z.object({
text: z.string(),
finish_reason: z.string(),
logprobs: z.object({
tokens: z.array(z.string()),
token_logprobs: z.array(z.number()),
top_logprobs: z.array(z.record(z.string(), z.number())).nullish()
}).nullish()
})),
usage: z.object({
prompt_tokens: z.number(),
completion_tokens: z.number(),
total_tokens: z.number()
}).nullish()
})));
var openaiCompletionChunkSchema = lazySchema$1(() => zodSchema$2(z.union([z.object({
id: z.string().nullish(),
created: z.number().nullish(),
model: z.string().nullish(),
choices: z.array(z.object({
text: z.string(),
finish_reason: z.string().nullish(),
index: z.number(),
logprobs: z.object({
tokens: z.array(z.string()),
token_logprobs: z.array(z.number()),
top_logprobs: z.array(z.record(z.string(), z.number())).nullish()
}).nullish()
})),
usage: z.object({
prompt_tokens: z.number(),
completion_tokens: z.number(),
total_tokens: z.number()
}).nullish()
}), openaiErrorDataSchema()])));
var openaiLanguageModelCompletionOptions = lazySchema$1(() => zodSchema$2(z.object({
/**
* Echo back the prompt in addition to the completion.
*/
echo: z.boolean().optional(),
/**
* Modify the likelihood of specified tokens appearing in the completion.
*
* Accepts a JSON object that maps tokens (specified by their token ID in
* the GPT tokenizer) to an associated bias value from -100 to 100. You
* can use this tokenizer tool to convert text to token IDs. Mathematically,
* the bias is added to the logits generated by the model prior to sampling.
* The exact effect will vary per model, but values between -1 and 1 should
* decrease or increase likelihood of selection; values like -100 or 100
* should result in a ban or exclusive selection of the relevant token.
*
* As an example, you can pass {"50256": -100} to prevent the <|endoftext|>
* token from being generated.
*/
logitBias: z.record(z.string(), z.number()).optional(),
/**
* The suffix that comes after a completion of inserted text.
*/
suffix: z.string().optional(),
/**
* A unique identifier representing your end-user, which can help OpenAI to
* monitor and detect abuse. Learn more.
*/
user: z.string().optional(),
/**
* Return the log probabilities of the tokens. Including logprobs will increase
* the response size and can slow down response times. However, it can
* be useful to better understand how the model is behaving.
* Setting to true will return the log probabilities of the tokens that
* were generated.
* Setting to a number will return the log probabilities of the top n
* tokens that were generated.
*/
logprobs: z.union([z.boolean(), z.number()]).optional()
})));
var OpenAICompletionLanguageModel = class {
constructor(modelId, config) {
this.specificationVersion = "v3";
this.supportedUrls = {};
this.modelId = modelId;
this.config = config;
}
get providerOptionsName() {
return this.config.provider.split(".")[0].trim();
}
get provider() {
return this.config.provider;
}
async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences: userStopSequences, responseFormat, tools, toolChoice, seed, providerOptions }) {
const warnings = [];
const openaiOptions = {
...await parseProviderOptions$1({
provider: "openai",
providerOptions,
schema: openaiLanguageModelCompletionOptions
}),
...await parseProviderOptions$1({
provider: this.providerOptionsName,
providerOptions,
schema: openaiLanguageModelCompletionOptions
})
};
if (topK != null) warnings.push({
type: "unsupported",
feature: "topK"
});
if (tools == null ? void 0 : tools.length) warnings.push({
type: "unsupported",
feature: "tools"
});
if (toolChoice != null) warnings.push({
type: "unsupported",
feature: "toolChoice"
});
if (responseFormat != null && responseFormat.type !== "text") warnings.push({
type: "unsupported",
feature: "responseFormat",
details: "JSON response format is not supported."
});
const { prompt: completionPrompt, stopSequences } = convertToOpenAICompletionPrompt({ prompt });
const stop = [...stopSequences != null ? stopSequences : [], ...userStopSequences != null ? userStopSequences : []];
return {
args: {
model: this.modelId,
echo: openaiOptions.echo,
logit_bias: openaiOptions.logitBias,
logprobs: (openaiOptions == null ? void 0 : openaiOptions.logprobs) === true ? 0 : (openaiOptions == null ? void 0 : openaiOptions.logprobs) === false ? void 0 : openaiOptions == null ? void 0 : openaiOptions.logprobs,
suffix: openaiOptions.suffix,
user: openaiOptions.user,
max_tokens: maxOutputTokens,
temperature,
top_p: topP,
frequency_penalty: frequencyPenalty,
presence_penalty: presencePenalty,
seed,
prompt: completionPrompt,
stop: stop.length > 0 ? stop : void 0
},
warnings
};
}
async doGenerate(options) {
var _a2;
const { args, warnings } = await this.getArgs(options);
const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi$2({
url: this.config.url({
path: "/completions",
modelId: this.modelId
}),
headers: combineHeaders$2(this.config.headers(), options.headers),
body: args,
failedResponseHandler: openaiFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$2(openaiCompletionResponseSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const choice = response.choices[0];
const providerMetadata = { openai: {} };
if (choice.logprobs != null) providerMetadata.openai.logprobs = choice.logprobs;
return {
content: [{
type: "text",
text: choice.text
}],
usage: convertOpenAICompletionUsage(response.usage),
finishReason: {
unified: mapOpenAIFinishReason2(choice.finish_reason),
raw: (_a2 = choice.finish_reason) != null ? _a2 : void 0
},
request: { body: args },
response: {
...getResponseMetadata2(response),
headers: responseHeaders,
body: rawResponse
},
providerMetadata,
warnings
};
}
async doStream(options) {
const { args, warnings } = await this.getArgs(options);
const body = {
...args,
stream: true,
stream_options: { include_usage: true }
};
const url = this.config.url({
path: "/completions",
modelId: this.modelId
});
const { responseHeaders, value: response } = await postJsonToApi$2({
url,
headers: combineHeaders$2(this.config.headers(), options.headers),
body,
failedResponseHandler: openaiFailedResponseHandler,
successfulResponseHandler: createEventSourceResponseHandler$2(openaiCompletionChunkSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const checkedResponse = await throwIfOpenAIStreamErrorBeforeOutput({
stream: response,
getError: (chunk) => "error" in chunk ? chunk.error : void 0,
isOutputChunk: isOpenAICompletionOutputChunk,
url,
requestBodyValues: body,
responseHeaders
});
let finishReason = {
unified: "other",
raw: void 0
};
const providerMetadata = { openai: {} };
let usage = void 0;
let isFirstChunk = true;
return {
stream: checkedResponse.pipeThrough(new TransformStream({
start(controller) {
controller.enqueue({
type: "stream-start",
warnings
});
},
transform(chunk, controller) {
if (options.includeRawChunks) controller.enqueue({
type: "raw",
rawValue: chunk.rawValue
});
if (!chunk.success) {
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error: chunk.error
});
return;
}
const value = chunk.value;
if ("error" in value) {
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error: value.error
});
return;
}
if (isFirstChunk) {
isFirstChunk = false;
controller.enqueue({
type: "response-metadata",
...getResponseMetadata2(value)
});
controller.enqueue({
type: "text-start",
id: "0"
});
}
if (value.usage != null) usage = value.usage;
const choice = value.choices[0];
if ((choice == null ? void 0 : choice.finish_reason) != null) finishReason = {
unified: mapOpenAIFinishReason2(choice.finish_reason),
raw: choice.finish_reason
};
if ((choice == null ? void 0 : choice.logprobs) != null) providerMetadata.openai.logprobs = choice.logprobs;
if ((choice == null ? void 0 : choice.text) != null && choice.text.length > 0) controller.enqueue({
type: "text-delta",
id: "0",
delta: choice.text
});
},
flush(controller) {
if (!isFirstChunk) controller.enqueue({
type: "text-end",
id: "0"
});
controller.enqueue({
type: "finish",
finishReason,
providerMetadata,
usage: convertOpenAICompletionUsage(usage)
});
}
})),
request: { body },
response: { headers: responseHeaders }
};
}
};
function isOpenAICompletionOutputChunk(chunk) {
return !("error" in chunk) && chunk.choices.some((choice) => choice.text.length > 0);
}
var openaiEmbeddingModelOptions = lazySchema$1(() => zodSchema$2(z.object({
/**
* The number of dimensions the resulting output embeddings should have.
* Only supported in text-embedding-3 and later models.
*/
dimensions: z.number().optional(),
/**
* A unique identifier representing your end-user, which can help OpenAI to
* monitor and detect abuse. Learn more.
*/
user: z.string().optional()
})));
var openaiTextEmbeddingResponseSchema$1 = lazySchema$1(() => zodSchema$2(z.object({
data: z.array(z.object({ embedding: z.array(z.number()) })),
usage: z.object({ prompt_tokens: z.number() }).nullish()
})));
var _a$2 = EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL;
var OpenAIEmbeddingModel = class {
constructor(modelId, config) {
this.specificationVersion = "v3";
this.maxEmbeddingsPerCall = 2048;
this[_a$2] = 3e5;
this.supportsParallelCalls = true;
this.modelId = modelId;
this.config = config;
}
get provider() {
return this.config.provider;
}
async doEmbed({ values, headers, abortSignal, providerOptions }) {
var _a2;
if (values.length > this.maxEmbeddingsPerCall) throw new TooManyEmbeddingValuesForCallError$1({
provider: this.provider,
modelId: this.modelId,
maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
values
});
const openaiOptions = (_a2 = await parseProviderOptions$1({
provider: "openai",
providerOptions,
schema: openaiEmbeddingModelOptions
})) != null ? _a2 : {};
const { responseHeaders, value: response, rawValue } = await postJsonToApi$2({
url: this.config.url({
path: "/embeddings",
modelId: this.modelId
}),
headers: combineHeaders$2(this.config.headers(), headers),
body: {
model: this.modelId,
input: values,
encoding_format: "float",
dimensions: openaiOptions.dimensions,
user: openaiOptions.user
},
failedResponseHandler: openaiFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$2(openaiTextEmbeddingResponseSchema$1),
abortSignal,
fetch: this.config.fetch
});
return {
warnings: [],
embeddings: response.data.map((item) => item.embedding),
usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0,
response: {
headers: responseHeaders,
body: rawValue
}
};
}
};
var openaiImageResponseSchema = lazySchema$1(() => zodSchema$2(z.object({
created: z.number().nullish(),
data: z.array(z.object({
b64_json: z.string(),
revised_prompt: z.string().nullish()
})),
background: z.string().nullish(),
output_format: z.string().nullish(),
size: z.string().nullish(),
quality: z.string().nullish(),
usage: z.object({
input_tokens: z.number().nullish(),
output_tokens: z.number().nullish(),
total_tokens: z.number().nullish(),
input_tokens_details: z.object({
image_tokens: z.number().nullish(),
text_tokens: z.number().nullish()
}).nullish()
}).nullish()
})));
var modelMaxImagesPerCall = {
"dall-e-3": 1,
"dall-e-2": 10,
"gpt-image-1": 10,
"gpt-image-1-mini": 10,
"gpt-image-1.5": 10,
"gpt-image-2": 10,
"gpt-image-2.5-flare": 10,
"gpt-image-2.5-flare-2026-09-08": 10,
"gpt-image-2.5-sunburst": 10,
"gpt-image-2.5-sunburst-2026-09-08": 10,
"chatgpt-image-latest": 10
};
var defaultResponseFormatPrefixes = ["chatgpt-image-", "gpt-image-"];
function hasDefaultResponseFormat(modelId) {
return defaultResponseFormatPrefixes.some((prefix) => modelId.startsWith(prefix));
}
function getMaxImagesPerCall(modelId) {
var _a2;
return (_a2 = modelMaxImagesPerCall[modelId]) != null ? _a2 : modelId.startsWith("gpt-image-") ? 10 : 1;
}
var baseImageModelOptionsObject = () => z.object({
/**
* Quality of the generated image(s).
*
* Valid values: `standard`, `hd`, `low`, `medium`, `high`, `xhigh`, `max`, `auto`.
* `xhigh` and `max` are supported by GPT Image 2.5 models.
*/
quality: z.enum([
"standard",
"hd",
"low",
"medium",
"high",
"xhigh",
"max",
"auto"
]).optional(),
/**
* Background behavior for the generated image(s).
*
* If `transparent`, the output format must support transparency
* (i.e. `png` or `webp`).
*/
background: z.enum([
"transparent",
"opaque",
"auto"
]).optional(),
/**
* Format in which the generated image(s) are returned.
*/
outputFormat: z.enum([
"png",
"jpeg",
"webp"
]).optional(),
/**
* Compression level (0-100) for the generated image(s). Applies to the
* `jpeg` and `webp` output formats.
*/
outputCompression: z.number().int().min(0).max(100).optional(),
/**
* A unique identifier representing your end-user, which can help OpenAI
* to monitor and detect abuse.
*/
user: z.string().optional()
});
var openaiImageModelGenerationOptions = lazySchema$1(() => zodSchema$2(baseImageModelOptionsObject().extend({
/**
* Style of the generated image. `vivid` produces hyper-real and
* dramatic images; `natural` produces more subdued, less hyper-real
* looking images.
*/
style: z.enum(["vivid", "natural"]).optional(),
/**
* Content moderation level for the generated image(s). `low` applies
* less restrictive filtering.
*/
moderation: z.enum(["auto", "low"]).optional()
})));
var openaiImageModelEditOptions = lazySchema$1(() => zodSchema$2(baseImageModelOptionsObject().extend({
/**
* Fidelity of the output image(s) to the input image(s).
*/
inputFidelity: z.enum(["high", "low"]).optional() })));
var OpenAIImageModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v3";
}
get maxImagesPerCall() {
return getMaxImagesPerCall(this.modelId);
}
get provider() {
return this.config.provider;
}
async doGenerate({ prompt, files, mask, n, size, aspectRatio, seed, providerOptions, headers, abortSignal }) {
var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
const warnings = [];
if (aspectRatio != null) warnings.push({
type: "unsupported",
feature: "aspectRatio",
details: "This model does not support aspect ratio. Use `size` instead."
});
if (seed != null) warnings.push({
type: "unsupported",
feature: "seed"
});
const currentDate = (_c = (_b = (_a2 = this.config._internal) == null ? void 0 : _a2.currentDate) == null ? void 0 : _b.call(_a2)) != null ? _c : /* @__PURE__ */ new Date();
if (files != null) {
const openaiOptions2 = (_d = await parseProviderOptions$1({
provider: "openai",
providerOptions,
schema: openaiImageModelEditOptions
})) != null ? _d : {};
const { value: response2, responseHeaders: responseHeaders2 } = await postFormDataToApi$1({
url: this.config.url({
path: "/images/edits",
modelId: this.modelId
}),
headers: combineHeaders$2(this.config.headers(), headers),
formData: convertToFormData$1({
model: this.modelId,
prompt,
image: await Promise.all(files.map((file) => file.type === "file" ? new Blob([file.data instanceof Uint8Array ? new Blob([file.data], { type: file.mediaType }) : new Blob([convertBase64ToUint8Array$1(file.data)], { type: file.mediaType })], { type: file.mediaType }) : downloadBlob$1(file.url))),
mask: mask != null ? await fileToBlob$1(mask) : void 0,
n,
size,
quality: openaiOptions2.quality,
background: openaiOptions2.background,
output_format: openaiOptions2.outputFormat,
output_compression: openaiOptions2.outputCompression,
input_fidelity: openaiOptions2.inputFidelity,
user: openaiOptions2.user
}),
failedResponseHandler: openaiFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$2(openaiImageResponseSchema),
abortSignal,
fetch: this.config.fetch
});
return {
images: response2.data.map((item) => item.b64_json),
warnings,
usage: response2.usage != null ? {
inputTokens: (_e = response2.usage.input_tokens) != null ? _e : void 0,
outputTokens: (_f = response2.usage.output_tokens) != null ? _f : void 0,
totalTokens: (_g = response2.usage.total_tokens) != null ? _g : void 0
} : void 0,
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders2
},
providerMetadata: { openai: { images: response2.data.map((item, index) => {
var _a3, _b2, _c2, _d2, _e2, _f2;
return {
...item.revised_prompt ? { revisedPrompt: item.revised_prompt } : {},
created: (_a3 = response2.created) != null ? _a3 : void 0,
size: (_b2 = response2.size) != null ? _b2 : void 0,
quality: (_c2 = response2.quality) != null ? _c2 : void 0,
background: (_d2 = response2.background) != null ? _d2 : void 0,
outputFormat: (_e2 = response2.output_format) != null ? _e2 : void 0,
...distributeTokenDetails((_f2 = response2.usage) == null ? void 0 : _f2.input_tokens_details, index, response2.data.length)
};
}) } }
};
}
const openaiOptions = (_h = await parseProviderOptions$1({
provider: "openai",
providerOptions,
schema: openaiImageModelGenerationOptions
})) != null ? _h : {};
const { value: response, responseHeaders } = await postJsonToApi$2({
url: this.config.url({
path: "/images/generations",
modelId: this.modelId
}),
headers: combineHeaders$2(this.config.headers(), headers),
body: {
model: this.modelId,
prompt,
n,
size,
quality: openaiOptions.quality,
style: openaiOptions.style,
background: openaiOptions.background,
moderation: openaiOptions.moderation,
output_format: openaiOptions.outputFormat,
output_compression: openaiOptions.outputCompression,
user: openaiOptions.user,
...!hasDefaultResponseFormat(this.modelId) ? { response_format: "b64_json" } : {}
},
failedResponseHandler: openaiFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$2(openaiImageResponseSchema),
abortSignal,
fetch: this.config.fetch
});
return {
images: response.data.map((item) => item.b64_json),
warnings,
usage: response.usage != null ? {
inputTokens: (_i = response.usage.input_tokens) != null ? _i : void 0,
outputTokens: (_j = response.usage.output_tokens) != null ? _j : void 0,
totalTokens: (_k = response.usage.total_tokens) != null ? _k : void 0
} : void 0,
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders
},
providerMetadata: { openai: { images: response.data.map((item, index) => {
var _a3, _b2, _c2, _d2, _e2, _f2;
return {
...item.revised_prompt ? { revisedPrompt: item.revised_prompt } : {},
created: (_a3 = response.created) != null ? _a3 : void 0,
size: (_b2 = response.size) != null ? _b2 : void 0,
quality: (_c2 = response.quality) != null ? _c2 : void 0,
background: (_d2 = response.background) != null ? _d2 : void 0,
outputFormat: (_e2 = response.output_format) != null ? _e2 : void 0,
...distributeTokenDetails((_f2 = response.usage) == null ? void 0 : _f2.input_tokens_details, index, response.data.length)
};
}) } }
};
}
};
function distributeTokenDetails(details, index, total) {
if (details == null) return {};
const result = {};
if (details.image_tokens != null) {
const base = Math.floor(details.image_tokens / total);
const remainder = details.image_tokens - base * (total - 1);
result.imageTokens = index === total - 1 ? remainder : base;
}
if (details.text_tokens != null) {
const base = Math.floor(details.text_tokens / total);
const remainder = details.text_tokens - base * (total - 1);
result.textTokens = index === total - 1 ? remainder : base;
}
return result;
}
async function fileToBlob$1(file) {
if (!file) return void 0;
if (file.type === "url") return downloadBlob$1(file.url);
const data = file.data instanceof Uint8Array ? file.data : convertBase64ToUint8Array$1(file.data);
return new Blob([data], { type: file.mediaType });
}
var applyPatchInputSchema = lazySchema$1(() => zodSchema$2(z.object({
callId: z.string(),
operation: z.discriminatedUnion("type", [
z.object({
type: z.literal("create_file"),
path: z.string(),
diff: z.string()
}),
z.object({
type: z.literal("delete_file"),
path: z.string()
}),
z.object({
type: z.literal("update_file"),
path: z.string(),
diff: z.string()
})
])
})));
var applyPatchOutputSchema = lazySchema$1(() => zodSchema$2(z.object({
status: z.enum(["completed", "failed"]),
output: z.string().optional()
})));
var applyPatch = createProviderToolFactoryWithOutputSchema({
id: "openai.apply_patch",
inputSchema: applyPatchInputSchema,
outputSchema: applyPatchOutputSchema
});
var codeInterpreterInputSchema = lazySchema$1(() => zodSchema$2(z.object({
code: z.string().nullish(),
containerId: z.string()
})));
var codeInterpreterOutputSchema = lazySchema$1(() => zodSchema$2(z.object({ outputs: z.array(z.discriminatedUnion("type", [z.object({
type: z.literal("logs"),
logs: z.string()
}), z.object({
type: z.literal("image"),
url: z.string()
})])).nullish() })));
var codeInterpreterArgsSchema = lazySchema$1(() => zodSchema$2(z.object({ container: z.union([z.string(), z.object({ fileIds: z.array(z.string()).optional() })]).optional() })));
var codeInterpreterToolFactory = createProviderToolFactoryWithOutputSchema({
id: "openai.code_interpreter",
inputSchema: codeInterpreterInputSchema,
outputSchema: codeInterpreterOutputSchema
});
var codeInterpreter = (args = {}) => {
return codeInterpreterToolFactory(args);
};
var customArgsSchema = lazySchema$1(() => zodSchema$2(z.object({
name: z.string(),
description: z.string().optional(),
async: z.boolean().optional(),
format: z.union([z.object({
type: z.literal("grammar"),
syntax: z.enum(["regex", "lark"]),
definition: z.string()
}), z.object({ type: z.literal("text") })]).optional()
})));
var customToolFactory = createProviderToolFactory$1({
id: "openai.custom",
inputSchema: lazySchema$1(() => zodSchema$2(z.string()))
});
var customTool = (args) => customToolFactory(args);
var comparisonFilterSchema = () => z.object({
key: z.string(),
type: z.enum([
"eq",
"ne",
"gt",
"gte",
"lt",
"lte",
"in",
"nin"
]),
value: z.union([
z.string(),
z.number(),
z.boolean(),
z.array(z.string())
])
});
var cachedCompoundFilterSchema;
var compoundFilterSchema = () => cachedCompoundFilterSchema != null ? cachedCompoundFilterSchema : cachedCompoundFilterSchema = z.object({
type: z.enum(["and", "or"]),
filters: z.array(z.union([comparisonFilterSchema(), z.lazy(() => compoundFilterSchema())]))
});
var fileSearchArgsSchema$2 = lazySchema$1(() => zodSchema$2(z.object({
vectorStoreIds: z.array(z.string()),
maxNumResults: z.number().optional(),
ranking: z.object({
ranker: z.string().optional(),
scoreThreshold: z.number().optional()
}).optional(),
filters: z.union([comparisonFilterSchema(), compoundFilterSchema()]).optional()
})));
var fileSearchOutputSchema$1 = lazySchema$1(() => zodSchema$2(z.object({
queries: z.array(z.string()),
results: z.array(z.object({
attributes: z.record(z.string(), z.unknown()),
fileId: z.string(),
filename: z.string(),
score: z.number(),
text: z.string()
})).nullable()
})));
var fileSearch$2 = createProviderToolFactoryWithOutputSchema({
id: "openai.file_search",
inputSchema: z.object({}),
outputSchema: fileSearchOutputSchema$1
});
var imageGenerationArgsSchema$1 = lazySchema$1(() => zodSchema$2(z.object({
background: z.enum([
"auto",
"opaque",
"transparent"
]).optional(),
inputFidelity: z.enum(["low", "high"]).optional(),
inputImageMask: z.object({
fileId: z.string().optional(),
imageUrl: z.string().optional()
}).optional(),
model: z.string().optional(),
moderation: z.enum(["auto"]).optional(),
outputCompression: z.number().int().min(0).max(100).optional(),
outputFormat: z.enum([
"png",
"jpeg",
"webp"
]).optional(),
partialImages: z.number().int().min(0).max(3).optional(),
quality: z.enum([
"auto",
"low",
"medium",
"high",
"xhigh",
"max"
]).optional(),
size: z.enum([
"1024x1024",
"1024x1536",
"1536x1024",
"auto"
]).optional()
}).strict()));
var imageGenerationToolFactory$1 = createProviderToolFactoryWithOutputSchema({
id: "openai.image_generation",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({}))),
outputSchema: lazySchema$1(() => zodSchema$2(z.object({ result: z.string() })))
});
var imageGeneration$1 = (args = {}) => {
return imageGenerationToolFactory$1(args);
};
var localShellInputSchema = lazySchema$1(() => zodSchema$2(z.object({ action: z.object({
type: z.literal("exec"),
command: z.array(z.string()),
timeoutMs: z.number().optional(),
user: z.string().optional(),
workingDirectory: z.string().optional(),
env: z.record(z.string(), z.string()).optional()
}) })));
var localShellOutputSchema = lazySchema$1(() => zodSchema$2(z.object({ output: z.string() })));
var localShell = createProviderToolFactoryWithOutputSchema({
id: "openai.local_shell",
inputSchema: localShellInputSchema,
outputSchema: localShellOutputSchema
});
var shellInputSchema = lazySchema$1(() => zodSchema$2(z.object({ action: z.object({
commands: z.array(z.string()),
timeoutMs: z.number().optional(),
maxOutputLength: z.number().optional()
}) })));
var shellOutputSchema = lazySchema$1(() => zodSchema$2(z.object({ output: z.array(z.object({
stdout: z.string(),
stderr: z.string(),
outcome: z.discriminatedUnion("type", [z.object({ type: z.literal("timeout") }), z.object({
type: z.literal("exit"),
exitCode: z.number()
})])
})) })));
var shellSkillsSchema = () => z.array(z.discriminatedUnion("type", [z.object({
type: z.literal("skillReference"),
skillId: z.string(),
version: z.string().optional()
}), z.object({
type: z.literal("inline"),
name: z.string(),
description: z.string(),
source: z.object({
type: z.literal("base64"),
mediaType: z.literal("application/zip"),
data: z.string()
})
})])).optional();
var shellArgsSchema = lazySchema$1(() => zodSchema$2(z.object({ environment: z.union([
z.object({
type: z.literal("containerAuto"),
fileIds: z.array(z.string()).optional(),
memoryLimit: z.enum([
"1g",
"4g",
"16g",
"64g"
]).optional(),
networkPolicy: z.discriminatedUnion("type", [z.object({ type: z.literal("disabled") }), z.object({
type: z.literal("allowlist"),
allowedDomains: z.array(z.string()),
domainSecrets: z.array(z.object({
domain: z.string(),
name: z.string(),
value: z.string()
})).optional()
})]).optional(),
skills: shellSkillsSchema()
}),
z.object({
type: z.literal("containerReference"),
containerId: z.string()
}),
z.object({
type: z.literal("local").optional(),
skills: z.array(z.object({
name: z.string(),
description: z.string(),
path: z.string()
})).optional()
})
]).optional() })));
var shell = createProviderToolFactoryWithOutputSchema({
id: "openai.shell",
inputSchema: shellInputSchema,
outputSchema: shellOutputSchema
});
var toolSearchArgsSchema = lazySchema$1(() => zodSchema$2(z.object({
execution: z.enum(["server", "client"]).optional(),
description: z.string().optional(),
parameters: z.record(z.string(), z.unknown()).optional()
})));
var toolSearchInputSchema = lazySchema$1(() => zodSchema$2(z.object({
arguments: z.unknown().optional(),
call_id: z.string().nullish()
})));
var toolSearchOutputSchema = lazySchema$1(() => zodSchema$2(z.object({ tools: z.array(z.record(z.string(), z.unknown())) })));
var toolSearchToolFactory = createProviderToolFactoryWithOutputSchema({
id: "openai.tool_search",
inputSchema: toolSearchInputSchema,
outputSchema: toolSearchOutputSchema
});
var toolSearch = (args = {}) => toolSearchToolFactory(args);
var webSearchArgsSchema$1 = lazySchema$1(() => zodSchema$2(z.object({
externalWebAccess: z.boolean().optional(),
filters: z.object({
allowedDomains: z.array(z.string()).optional(),
blockedDomains: z.array(z.string()).optional()
}).optional(),
searchContextSize: z.enum([
"low",
"medium",
"high"
]).optional(),
userLocation: z.object({
type: z.literal("approximate"),
country: z.string().optional(),
city: z.string().optional(),
region: z.string().optional(),
timezone: z.string().optional()
}).optional()
})));
var webSearchInputSchema = lazySchema$1(() => zodSchema$2(z.object({})));
var webSearchOutputSchema$1 = lazySchema$1(() => zodSchema$2(z.object({
action: z.discriminatedUnion("type", [
z.object({
type: z.literal("search"),
query: z.string().optional(),
queries: z.array(z.string()).optional()
}),
z.object({
type: z.literal("openPage"),
url: z.string().nullish()
}),
z.object({
type: z.literal("findInPage"),
url: z.string().nullish(),
pattern: z.string().nullish()
})
]).optional(),
sources: z.array(z.discriminatedUnion("type", [z.object({
type: z.literal("url"),
url: z.string()
}), z.object({
type: z.literal("api"),
name: z.string()
})])).optional()
})));
var webSearchToolFactory$1 = createProviderToolFactoryWithOutputSchema({
id: "openai.web_search",
inputSchema: webSearchInputSchema,
outputSchema: webSearchOutputSchema$1
});
var webSearch$2 = (args = {}) => webSearchToolFactory$1(args);
var webSearchPreviewArgsSchema = lazySchema$1(() => zodSchema$2(z.object({
searchContextSize: z.enum([
"low",
"medium",
"high"
]).optional(),
userLocation: z.object({
type: z.literal("approximate"),
country: z.string().optional(),
city: z.string().optional(),
region: z.string().optional(),
timezone: z.string().optional()
}).optional()
})));
var webSearchPreview = createProviderToolFactoryWithOutputSchema({
id: "openai.web_search_preview",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({}))),
outputSchema: lazySchema$1(() => zodSchema$2(z.object({ action: z.discriminatedUnion("type", [
z.object({
type: z.literal("search"),
query: z.string().optional()
}),
z.object({
type: z.literal("openPage"),
url: z.string().nullish()
}),
z.object({
type: z.literal("findInPage"),
url: z.string().nullish(),
pattern: z.string().nullish()
})
]).optional() })))
});
var cachedJsonValueSchema;
var jsonValueSchema = () => cachedJsonValueSchema != null ? cachedJsonValueSchema : cachedJsonValueSchema = z.lazy(() => z.union([
z.string(),
z.number(),
z.boolean(),
z.null(),
z.array(jsonValueSchema()),
z.record(z.string(), jsonValueSchema())
]));
var mcpArgsSchema = lazySchema$1(() => zodSchema$2(z.object({
serverLabel: z.string(),
allowedTools: z.union([z.array(z.string()), z.object({
readOnly: z.boolean().optional(),
toolNames: z.array(z.string()).optional()
})]).optional(),
authorization: z.string().optional(),
connectorId: z.string().optional(),
headers: z.record(z.string(), z.string()).optional(),
requireApproval: z.union([z.enum(["always", "never"]), z.object({ never: z.object({ toolNames: z.array(z.string()).optional() }).optional() })]).optional(),
serverDescription: z.string().optional(),
serverUrl: z.string().optional()
}).refine((v) => v.serverUrl != null || v.connectorId != null, "One of serverUrl or connectorId must be provided.")));
var mcpToolFactory = createProviderToolFactoryWithOutputSchema({
id: "openai.mcp",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({}))),
outputSchema: lazySchema$1(() => zodSchema$2(z.object({
type: z.literal("call"),
serverLabel: z.string(),
name: z.string(),
arguments: z.string(),
output: z.string().nullish(),
error: z.union([z.string(), jsonValueSchema()]).optional()
})))
});
var mcp = (args) => mcpToolFactory(args);
var openaiTools = {
/**
* The apply_patch tool lets GPT-5.1 create, update, and delete files in your
* codebase using structured diffs. Instead of just suggesting edits, the model
* emits patch operations that your application applies and then reports back on,
* enabling iterative, multi-step code editing workflows.
*
*/
applyPatch,
/**
* Custom tools let callers constrain model output to a grammar (regex or
* Lark syntax). The model returns a `custom_tool_call` output item whose
* `input` field is a string matching the specified grammar.
*
* @param name - The name of the custom tool.
* @param description - An optional description of the tool.
* @param async - Whether the model can continue without waiting for the tool result.
* @param format - The output format constraint (grammar type, syntax, and definition).
*/
customTool,
/**
* The Code Interpreter tool allows models to write and run Python code in a
* sandboxed environment to solve complex problems in domains like data analysis,
* coding, and math.
*
* @param container - The container to use for the code interpreter.
*/
codeInterpreter,
/**
* File search is a tool available in the Responses API. It enables models to
* retrieve information in a knowledge base of previously uploaded files through
* semantic and keyword search.
*
* @param vectorStoreIds - The vector store IDs to use for the file search.
* @param maxNumResults - The maximum number of results to return.
* @param ranking - The ranking options to use for the file search.
* @param filters - The filters to use for the file search.
*/
fileSearch: fileSearch$2,
/**
* The image generation tool allows you to generate images using a text prompt,
* and optionally image inputs. It leverages the GPT Image model,
* and automatically optimizes text inputs for improved performance.
*
* @param background - Background type for the generated image. One of 'auto', 'opaque', or 'transparent'.
* @param inputFidelity - Input fidelity for the generated image. One of 'low' or 'high'.
* @param inputImageMask - Optional mask for inpainting. Contains fileId and/or imageUrl.
* @param model - The image generation model to use. Default: gpt-image-1.
* @param moderation - Moderation level for the generated image. Default: 'auto'.
* @param outputCompression - Compression level for the output image (0-100).
* @param outputFormat - The output format of the generated image. One of 'png', 'jpeg', or 'webp'.
* @param partialImages - Number of partial images to generate in streaming mode (0-3).
* @param quality - The quality of the generated image. One of 'auto', 'low', 'medium', 'high', 'xhigh', or 'max'. 'xhigh' and 'max' require a GPT Image 2.5 model.
* @param size - The size of the generated image. One of 'auto', '1024x1024', '1024x1536', or '1536x1024'.
*/
imageGeneration: imageGeneration$1,
/**
* Local shell is a tool that allows agents to run shell commands locally
* on a machine you or the user provides.
*
* Supported models: `gpt-5-codex`
*/
localShell,
/**
* The shell tool allows the model to interact with your local computer through
* a controlled command-line interface. The model proposes shell commands; your
* integration executes them and returns the outputs.
*
* Available through the Responses API for use with GPT-5.1.
*
* WARNING: Running arbitrary shell commands can be dangerous. Always sandbox
* execution or add strict allow-/deny-lists before forwarding a command to
* the system shell.
*/
shell,
/**
* Web search allows models to access up-to-date information from the internet
* and provide answers with sourced citations.
*
* @param searchContextSize - The search context size to use for the web search.
* @param userLocation - The user location to use for the web search.
*/
webSearchPreview,
/**
* Web search allows models to access up-to-date information from the internet
* and provide answers with sourced citations.
*
* @param filters - The filters to use for the web search.
* @param searchContextSize - The search context size to use for the web search.
* @param userLocation - The user location to use for the web search.
*/
webSearch: webSearch$2,
/**
* MCP (Model Context Protocol) allows models to call tools exposed by
* remote MCP servers or service connectors.
*
* @param serverLabel - Label to identify the MCP server.
* @param allowedTools - Allowed tool names or filter object.
* @param authorization - OAuth access token for the MCP server/connector.
* @param connectorId - Identifier for a service connector.
* @param headers - Optional headers to include in MCP requests.
* // param requireApproval - Approval policy ('always'|'never'|filter object). (Removed - always 'never')
* @param serverDescription - Optional description of the server.
* @param serverUrl - URL for the MCP server.
*/
mcp,
/**
* Tool search allows the model to dynamically search for and load deferred
* tools into the model's context as needed. This helps reduce overall token
* usage, cost, and latency by only loading tools when the model needs them.
*
* To use tool search, mark functions or namespaces with `defer_loading: true`
* in the tools array. The model will use tool search to load these tools
* when it determines they are needed.
*/
toolSearch
};
function convertOpenAIResponsesUsage(usage) {
var _a2, _b, _c, _d, _e, _f;
if (usage == null) return {
inputTokens: {
total: void 0,
noCache: void 0,
cacheRead: void 0,
cacheWrite: void 0
},
outputTokens: {
total: void 0,
text: void 0,
reasoning: void 0
},
raw: void 0
};
const inputTokens = usage.input_tokens;
const outputTokens = usage.output_tokens;
const cachedTokens = (_b = (_a2 = usage.input_tokens_details) == null ? void 0 : _a2.cached_tokens) != null ? _b : 0;
const cacheWriteTokens = (_d = (_c = usage.input_tokens_details) == null ? void 0 : _c.cache_write_tokens) != null ? _d : void 0;
const reasoningTokens = (_f = (_e = usage.output_tokens_details) == null ? void 0 : _e.reasoning_tokens) != null ? _f : 0;
return {
inputTokens: {
total: inputTokens,
noCache: inputTokens - cachedTokens - (cacheWriteTokens != null ? cacheWriteTokens : 0),
cacheRead: cachedTokens,
cacheWrite: cacheWriteTokens
},
outputTokens: {
total: outputTokens,
text: outputTokens - reasoningTokens,
reasoning: reasoningTokens
},
raw: usage
};
}
var TOP_LOGPROBS_MAX = 20;
var openaiLanguageModelResponsesOptionsSchema = lazySchema$1(() => zodSchema$2(z.object({
/**
* The ID of the OpenAI Conversation to continue.
* You must create a conversation first via the OpenAI API.
* Cannot be used in conjunction with `previousResponseId`.
* Defaults to `undefined`.
* @see https://platform.openai.com/docs/api-reference/conversations/create
*/
conversation: z.string().nullish(),
/**
* The set of extra fields to include in the response (advanced, usually not needed).
* Example values: 'reasoning.encrypted_content', 'file_search_call.results', 'web_search_call.results', 'message.output_text.logprobs'.
*/
include: z.array(z.enum([
"reasoning.encrypted_content",
"file_search_call.results",
"web_search_call.results",
"message.output_text.logprobs"
])).nullish(),
/**
* Instructions for the model.
* They can be used to change the system or developer message when continuing a conversation using the `previousResponseId` option.
* Defaults to `undefined`.
*/
instructions: z.string().nullish(),
/**
* Return the log probabilities of the tokens. Including logprobs will increase
* the response size and can slow down response times. However, it can
* be useful to better understand how the model is behaving.
*
* Setting to true will return the log probabilities of the tokens that
* were generated.
*
* Setting to a number will return the log probabilities of the top n
* tokens that were generated.
*
* @see https://platform.openai.com/docs/api-reference/responses/create
* @see https://cookbook.openai.com/examples/using_logprobs
*/
logprobs: z.union([z.boolean(), z.number().min(1).max(TOP_LOGPROBS_MAX)]).optional(),
/**
* The maximum number of total calls to built-in tools that can be processed in a response.
* This maximum number applies across all built-in tool calls, not per individual tool.
* Any further attempts to call a tool by the model will be ignored.
*/
maxToolCalls: z.number().nullish(),
/**
* Additional metadata to store with the generation.
*/
metadata: z.any().nullish(),
/**
* Whether to use parallel tool calls. Defaults to `true`.
*/
parallelToolCalls: z.boolean().nullish(),
/**
* The ID of the previous response. You can use it to continue a conversation.
* Defaults to `undefined`.
*/
previousResponseId: z.string().nullish(),
/**
* Sets a cache key to tie this prompt to cached prefixes for better caching performance.
*/
promptCacheKey: z.string().nullish(),
/**
* Prompt cache behavior for GPT-5.6 and later models.
* `mode` controls whether OpenAI also places an implicit breakpoint.
* `ttl` sets the minimum cache lifetime: `'30m'` (default) or `'12h'`.
* `prewarm` writes the prompt to the cache without generating output.
*/
promptCacheOptions: z.object({
mode: z.enum(["implicit", "explicit"]).optional(),
ttl: z.enum(["30m", "12h"]).optional(),
prewarm: z.boolean().optional()
}).optional(),
/**
* The retention policy for the prompt cache.
* - 'in_memory': Default. Standard prompt caching behavior.
* - '24h': Extended prompt caching that keeps cached prefixes active for up to 24 hours.
* Available for models before GPT-5.6 that support extended caching.
*
* @deprecated For GPT-5.6 and later models, use `promptCacheOptions.ttl`.
*
* @default 'in_memory'
*/
promptCacheRetention: z.enum(["in_memory", "24h"]).nullish(),
/**
* Reasoning effort for reasoning models. Defaults to `medium`. If you use
* `providerOptions` to set the `reasoningEffort` option, this model setting will be ignored.
* GPT-5.6 supports 'none' | 'low' | 'medium' | 'high' | 'xhigh' | 'max'.
* GPT-6 and later models support 'low' | 'medium' | 'high' | 'xhigh' | 'max'.
* Supported values vary by model.
*/
reasoningEffort: z.string().nullish(),
/**
* Updates the reasoning effort for GPT-6 and later models starting with this response
* without changing the request-level reasoning effort. This preserves the
* request prefix for prompt caching.
*
* Only supported by GPT-6 and later models in standard, single-agent mode. Cannot be
* combined with automatic truncation.
*/
reasoningEffortUpdate: z.enum([
"low",
"medium",
"high",
"xhigh",
"max"
]).optional(),
/**
* Controls how much model work GPT-5.6 performs before returning a final answer.
* `standard` is the default. `pro` increases quality, latency, and token usage.
*/
reasoningMode: z.enum(["standard", "pro"]).optional(),
/**
* Controls which available reasoning items GPT-5.6 can use.
* `auto` uses the model default, `current_turn` excludes reasoning from earlier
* turns, and `all_turns` makes compatible earlier reasoning available.
*/
reasoningContext: z.enum([
"auto",
"current_turn",
"all_turns"
]).optional(),
/**
* Controls reasoning summary output from the model.
* Set to "auto" to automatically receive the richest level available,
* or "detailed" for comprehensive summaries.
*/
reasoningSummary: z.string().nullish(),
/**
* The identifier for safety monitoring and tracking.
*/
safetyIdentifier: z.string().nullish(),
/**
* Service tier for the request.
* Set to 'flex' for 50% cheaper processing at the cost of increased latency (available for o3, o4-mini, and gpt-5 models).
* Set to 'priority' for faster processing with Enterprise access (available for gpt-4, gpt-5, gpt-5-mini, o3, o4-mini; gpt-5-nano is not supported).
* Set to 'fast' for the same tier as 'priority' (OpenAI's newer name for it).
* Set to 'ultrafast' for access-controlled Ultrafast processing (available only for gpt-5.6-sol).
*
* Defaults to 'auto'.
*/
serviceTier: z.enum([
"auto",
"flex",
"priority",
"fast",
"ultrafast",
"default"
]).nullish(),
/**
* Whether to store the generation. Defaults to `true`.
*/
store: z.boolean().nullish(),
/**
* Whether to pass through non-image file types as generic input files.
*
* By default, inline file inputs are restricted to images and PDFs.
* Enable this when the target OpenAI Responses model supports additional
* file media types, such as text/csv.
*/
passThroughUnsupportedFiles: z.boolean().optional(),
/**
* Whether to use strict JSON schema validation.
* Defaults to `true`.
*/
strictJsonSchema: z.boolean().nullish(),
/**
* Controls the verbosity of the model's responses. Lower values ('low') will result
* in more concise responses, while higher values ('high') will result in more verbose responses.
* Valid values: 'low', 'medium', 'high'.
*/
textVerbosity: z.enum([
"low",
"medium",
"high"
]).nullish(),
/**
* Controls output truncation. 'auto' (default) performs truncation automatically;
* 'disabled' turns truncation off.
*/
truncation: z.enum(["auto", "disabled"]).nullish(),
/**
* A unique identifier representing your end-user, which can help OpenAI to
* monitor and detect abuse.
* Defaults to `undefined`.
* @see https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids
*/
user: z.string().nullish(),
/**
* Override the system message mode for this model.
* - 'system': Use the 'system' role for system messages (default for most models)
* - 'developer': Use the 'developer' role for system messages (used by reasoning models)
* - 'remove': Remove system messages entirely
*
* If not specified, the mode is automatically determined based on the model.
*/
systemMessageMode: z.enum([
"system",
"developer",
"remove"
]).optional(),
/**
* Force treating this model as a reasoning model.
*
* This is useful for "stealth" reasoning models (e.g. via a custom baseURL)
* where the model ID is not recognized by the SDK's allowlist.
*
* When enabled, the SDK applies reasoning-model parameter compatibility rules
* and defaults `systemMessageMode` to `developer` unless overridden.
*/
forceReasoning: z.boolean().optional(),
/**
* Restrict the callable tools to a subset while keeping the full tools
* list intact, so prompt caching is preserved across requests with
* different allowlists.
*
* When set, this overrides the request-level `toolChoice` and emits
* `tool_choice: { type: "allowed_tools", mode, tools }` on the wire.
*
* @see https://developers.openai.com/api/reference/resources/responses/methods/create#(resource)%20responses%20%3E%20(model)%20tool_choice_allowed%20%3E%20(schema)
*/
allowedTools: z.object({
toolNames: z.array(z.string()).min(1),
mode: z.enum(["auto", "required"]).optional()
}).optional()
})));
var openaiResponsesSystemMessageOptionsSchema = lazySchema$1(() => zodSchema$2(z.object({
/**
* Emit a configuration update at this position in Responses history.
* Requires empty system message content and the same supported
* configuration as the request-level reasoningEffortUpdate option.
* Unsupported historical updates throw instead of being omitted.
*
* @see https://developers.openai.com/api/docs/guides/reasoning#change-reasoning-mid-conversation
*/
reasoningEffortUpdate: z.enum([
"low",
"medium",
"high",
"xhigh",
"max"
]).optional() })));
var parallelToolName = "parallel";
var recipientNamePrefix = "functions.";
function getParallelToolCallMetadata({ providerOptions, providerOptionsName }) {
var _a2;
const metadata = (_a2 = providerOptions == null ? void 0 : providerOptions[providerOptionsName]) == null ? void 0 : _a2.parallelToolCall;
if (!isJSONObject(metadata) || typeof metadata.itemId !== "string" || typeof metadata.toolCallId !== "string" || typeof metadata.toolName !== "string" || typeof metadata.input !== "string" || typeof metadata.index !== "number" || !Number.isInteger(metadata.index) || typeof metadata.count !== "number" || !Number.isInteger(metadata.count) || metadata.index < 0 || metadata.count <= metadata.index) return;
return metadata;
}
function isUndeclaredParallelToolCall({ toolName, tools }) {
return toolName === parallelToolName && !tools.some((tool) => tool.name === parallelToolName);
}
async function expandParallelToolCall({ toolCall, tools, providerOptionsName, itemId }) {
if (!isUndeclaredParallelToolCall({
toolName: toolCall.toolName,
tools
})) return;
const parsedInput = await safeParseJSON$2({ text: toolCall.input });
if (!parsedInput.success || !isJSONObject(parsedInput.value)) return;
const toolUses = parsedInput.value.tool_uses;
if (!Array.isArray(toolUses) || toolUses.length === 0) return;
const availableToolNames = new Set(tools.map((tool) => tool.name));
const expandedToolCalls = [];
for (const [index, toolUse] of toolUses.entries()) {
if (!isJSONObject(toolUse)) return;
const recipientName = toolUse.recipient_name;
const parameters = toolUse.parameters;
if (typeof recipientName !== "string" || !recipientName.startsWith(recipientNamePrefix) || !isJSONObject(parameters)) return;
const toolName = recipientName.slice(recipientNamePrefix.length);
if (toolName.length === 0 || !availableToolNames.has(toolName)) return;
expandedToolCalls.push({
type: "tool-call",
toolCallId: `${toolCall.toolCallId}_${index}`,
toolName,
input: JSON.stringify(parameters),
providerMetadata: { [providerOptionsName]: { parallelToolCall: {
itemId,
toolCallId: toolCall.toolCallId,
toolName: toolCall.toolName,
input: toolCall.input,
index,
count: toolUses.length
} } }
});
}
return expandedToolCalls;
}
function serializeToolCallArguments2(input) {
return JSON.stringify(input === void 0 ? {} : input);
}
async function convertWebSearchToolResultOutput({ output, id }) {
if (output.type !== "json") return;
const validation = await safeValidateTypes$2({
value: output.value,
schema: webSearchOutputSchema$1
});
if (!validation.success || validation.value.action == null) return;
const { action, sources } = validation.value;
switch (action.type) {
case "search": return {
type: "web_search_call",
id,
status: "completed",
action: {
type: "search",
...action.query != null && { query: action.query },
...action.queries != null && { queries: action.queries },
...sources != null && { sources }
}
};
case "openPage": return {
type: "web_search_call",
id,
status: "completed",
action: {
type: "open_page",
url: action.url
}
};
case "findInPage": return {
type: "web_search_call",
id,
status: "completed",
action: {
type: "find_in_page",
url: action.url,
pattern: action.pattern
}
};
}
}
async function convertFunctionToolResultOutput({ output, promptCacheBreakpoint, providerOptionsName, warnings }) {
var _a2;
const convertScalarOutput = (value) => promptCacheBreakpoint == null ? value : [{
type: "input_text",
text: value,
prompt_cache_breakpoint: promptCacheBreakpoint
}];
switch (output.type) {
case "text":
case "error-text": return convertScalarOutput(output.value);
case "execution-denied": return convertScalarOutput((_a2 = output.reason) != null ? _a2 : "Tool call execution denied.");
case "json":
case "error-json": return convertScalarOutput(JSON.stringify(output.value));
case "content": return output.value.map((item) => {
var _a3, _b, _c, _d, _e, _f, _g;
const promptCacheBreakpoint2 = getPromptCacheBreakpoint2(item.providerOptions, providerOptionsName);
switch (item.type) {
case "text": return {
type: "input_text",
text: item.text,
...promptCacheBreakpoint2 != null && { prompt_cache_breakpoint: promptCacheBreakpoint2 }
};
case "image-data": return {
type: "input_image",
image_url: `data:${item.mediaType};base64,${item.data}`,
detail: (_b = (_a3 = item.providerOptions) == null ? void 0 : _a3[providerOptionsName]) == null ? void 0 : _b.imageDetail,
...promptCacheBreakpoint2 != null && { prompt_cache_breakpoint: promptCacheBreakpoint2 }
};
case "image-url": return {
type: "input_image",
image_url: item.url,
detail: (_d = (_c = item.providerOptions) == null ? void 0 : _c[providerOptionsName]) == null ? void 0 : _d.imageDetail,
...promptCacheBreakpoint2 != null && { prompt_cache_breakpoint: promptCacheBreakpoint2 }
};
case "file-id": return {
type: "input_file",
file_id: typeof item.fileId === "string" ? item.fileId : item.fileId[providerOptionsName],
...promptCacheBreakpoint2 != null && { prompt_cache_breakpoint: promptCacheBreakpoint2 }
};
case "image-file-id": return {
type: "input_image",
file_id: typeof item.fileId === "string" ? item.fileId : item.fileId[providerOptionsName],
detail: (_f = (_e = item.providerOptions) == null ? void 0 : _e[providerOptionsName]) == null ? void 0 : _f.imageDetail,
...promptCacheBreakpoint2 != null && { prompt_cache_breakpoint: promptCacheBreakpoint2 }
};
case "file-data": return {
type: "input_file",
filename: (_g = item.filename) != null ? _g : "data",
file_data: `data:${item.mediaType};base64,${item.data}`,
...promptCacheBreakpoint2 != null && { prompt_cache_breakpoint: promptCacheBreakpoint2 }
};
case "file-url": return {
type: "input_file",
file_url: item.url,
...promptCacheBreakpoint2 != null && { prompt_cache_breakpoint: promptCacheBreakpoint2 }
};
default:
warnings.push({
type: "other",
message: `unsupported tool content part type: ${item.type}`
});
return;
}
}).filter(isNonNullable);
}
}
function hasSameParallelToolCall(first, second) {
return first.itemId === second.itemId && first.toolCallId === second.toolCallId && first.toolName === second.toolName && first.input === second.input && first.count === second.count;
}
function collectCompleteParallelToolResultGroups({ prompt, providerOptionsName }) {
const pendingGroups = /* @__PURE__ */ new Map();
for (const message of prompt) {
if (message.role !== "tool") continue;
for (const part of message.content) {
if (part.type !== "tool-result") continue;
const metadata = getParallelToolCallMetadata({
providerOptions: part.providerOptions,
providerOptionsName
});
if (metadata == null) continue;
const existing = pendingGroups.get(metadata.toolCallId);
if (existing == null) {
pendingGroups.set(metadata.toolCallId, {
metadata,
results: /* @__PURE__ */ new Map([[metadata.index, part]]),
invalid: false
});
continue;
}
if (!hasSameParallelToolCall(existing.metadata, metadata) || existing.results.has(metadata.index)) {
existing.invalid = true;
continue;
}
existing.results.set(metadata.index, part);
}
}
const completeGroups = /* @__PURE__ */ new Map();
for (const [toolCallId, group] of pendingGroups) {
if (group.invalid || group.results.size !== group.metadata.count) continue;
const results = Array.from({ length: group.metadata.count }, (_, index) => group.results.get(index));
if (results.every(isNonNullable)) completeGroups.set(toolCallId, {
metadata: group.metadata,
results
});
}
return completeGroups;
}
function getPromptCacheBreakpoint2(providerOptions, providerOptionsName) {
var _a2;
return (_a2 = providerOptions == null ? void 0 : providerOptions[providerOptionsName]) == null ? void 0 : _a2.promptCacheBreakpoint;
}
function getScalarToolResultPromptCacheBreakpoint({ output, toolResultProviderOptions, providerOptionsName }) {
var _a2;
return output.type === "content" ? void 0 : (_a2 = getPromptCacheBreakpoint2(output.providerOptions, providerOptionsName)) != null ? _a2 : getPromptCacheBreakpoint2(toolResultProviderOptions, providerOptionsName);
}
function isFileId(data, prefixes) {
if (!prefixes) return false;
return prefixes.some((prefix) => data.startsWith(prefix));
}
async function convertToOpenAIResponsesInput({ prompt, toolNameMapping, systemMessageMode, providerOptionsName, explicitMessageItemType = false, fileIdPrefixes, passThroughUnsupportedFiles = false, store, isReasoningModel = false, hasConversation = false, hasPreviousResponseId = false, configurationUpdateUnsupportedReason, hasLocalShellTool = false, hasShellTool = false, hasApplyPatchTool = false, toolSearchToolName, customProviderToolNames }) {
var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G;
let input = [];
const warnings = [];
const processedApprovalIds = /* @__PURE__ */ new Set();
const parallelToolResultGroups = hasConversation || hasPreviousResponseId ? collectCompleteParallelToolResultGroups({
prompt,
providerOptionsName
}) : /* @__PURE__ */ new Map();
const emittedParallelToolCalls = /* @__PURE__ */ new Set();
const emittedParallelToolResults = /* @__PURE__ */ new Set();
for (const { role, content, providerOptions } of prompt) switch (role) {
case "system": {
let options = await parseProviderOptions$1({
provider: providerOptionsName,
providerOptions,
schema: openaiResponsesSystemMessageOptionsSchema
});
if (options == null && providerOptionsName !== "openai") options = await parseProviderOptions$1({
provider: "openai",
providerOptions,
schema: openaiResponsesSystemMessageOptionsSchema
});
const effort = options == null ? void 0 : options.reasoningEffortUpdate;
if (effort != null) {
const unsupportedReason = content !== "" ? "Message-level reasoningEffortUpdate requires empty system message content." : configurationUpdateUnsupportedReason;
if (unsupportedReason != null) throw new UnsupportedFunctionalityError$2({
functionality: "Message-level reasoningEffortUpdate",
message: unsupportedReason
});
input.push({
type: "configuration_update",
reasoning: { effort }
});
break;
}
switch (systemMessageMode) {
case "system": {
const promptCacheBreakpoint = getPromptCacheBreakpoint2(providerOptions, providerOptionsName);
input.push({
...explicitMessageItemType && { type: "message" },
role: "system",
content: promptCacheBreakpoint == null ? content : [{
type: "input_text",
text: content,
prompt_cache_breakpoint: promptCacheBreakpoint
}]
});
break;
}
case "developer": {
const promptCacheBreakpoint = getPromptCacheBreakpoint2(providerOptions, providerOptionsName);
input.push({
...explicitMessageItemType && { type: "message" },
role: "developer",
content: promptCacheBreakpoint == null ? content : [{
type: "input_text",
text: content,
prompt_cache_breakpoint: promptCacheBreakpoint
}]
});
break;
}
case "remove":
warnings.push({
type: "other",
message: "system messages are removed for this model"
});
break;
default: throw new Error(`Unsupported system message mode: ${systemMessageMode}`);
}
break;
}
case "user":
input.push({
...explicitMessageItemType && { type: "message" },
role: "user",
content: content.map((part, index) => {
var _a3, _b2, _c2;
switch (part.type) {
case "text": {
const promptCacheBreakpoint = getPromptCacheBreakpoint2(part.providerOptions, providerOptionsName);
return {
type: "input_text",
text: part.text,
...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint }
};
}
case "file": {
const promptCacheBreakpoint = getPromptCacheBreakpoint2(part.providerOptions, providerOptionsName);
const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
if (mediaType.startsWith("image/")) return {
type: "input_image",
...part.data instanceof URL ? { image_url: part.data.toString() } : typeof part.data === "string" && isFileId(part.data, fileIdPrefixes) ? { file_id: part.data } : { image_url: `data:${mediaType};base64,${convertToBase64$1(part.data)}` },
detail: (_b2 = (_a3 = part.providerOptions) == null ? void 0 : _a3[providerOptionsName]) == null ? void 0 : _b2.imageDetail,
...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint }
};
if (part.data instanceof URL) return {
type: "input_file",
file_url: part.data.toString(),
...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint }
};
if (mediaType !== "application/pdf" && !passThroughUnsupportedFiles) throw new UnsupportedFunctionalityError$2({ functionality: `file part media type ${mediaType}` });
return {
type: "input_file",
...typeof part.data === "string" && isFileId(part.data, fileIdPrefixes) ? { file_id: part.data } : {
filename: (_c2 = part.filename) != null ? _c2 : mediaType === "application/pdf" ? `part-${index}.pdf` : `part-${index}`,
file_data: `data:${mediaType};base64,${convertToBase64$1(part.data)}`
},
...promptCacheBreakpoint != null && { prompt_cache_breakpoint: promptCacheBreakpoint }
};
}
}
})
});
break;
case "assistant": {
const reasoningMessages = {};
let hasPrecedingReasoning = false;
for (const part of content) switch (part.type) {
case "text": {
const providerOpts = (_a2 = part.providerOptions) == null ? void 0 : _a2[providerOptionsName];
const id = providerOpts == null ? void 0 : providerOpts.itemId;
const phase = providerOpts == null ? void 0 : providerOpts.phase;
if (hasConversation && id != null) break;
const canUseItemId = id != null && (!isReasoningModel || hasPrecedingReasoning);
if (store && canUseItemId) {
input.push({
type: "item_reference",
id
});
break;
}
input.push({
...explicitMessageItemType && { type: "message" },
role: "assistant",
content: [{
type: "output_text",
text: part.text
}],
id: canUseItemId ? id : void 0,
...phase != null && { phase }
});
break;
}
case "tool-call": {
const parallelToolCallMetadata = getParallelToolCallMetadata({
providerOptions: part.providerOptions,
providerOptionsName
});
const parallelToolResultGroup = parallelToolCallMetadata == null ? void 0 : parallelToolResultGroups.get(parallelToolCallMetadata.toolCallId);
if (parallelToolCallMetadata != null && parallelToolResultGroup != null && hasSameParallelToolCall(parallelToolResultGroup.metadata, parallelToolCallMetadata)) {
if (!emittedParallelToolCalls.has(parallelToolResultGroup.metadata.toolCallId)) {
emittedParallelToolCalls.add(parallelToolResultGroup.metadata.toolCallId);
if (!hasConversation) input.push({
type: "function_call",
call_id: parallelToolResultGroup.metadata.toolCallId,
name: parallelToolResultGroup.metadata.toolName,
arguments: parallelToolResultGroup.metadata.input
});
}
break;
}
const id = (_f = (_c = (_b = part.providerOptions) == null ? void 0 : _b[providerOptionsName]) == null ? void 0 : _c.itemId) != null ? _f : (_e = (_d = part.providerMetadata) == null ? void 0 : _d[providerOptionsName]) == null ? void 0 : _e.itemId;
const namespace = (_k = (_h = (_g = part.providerOptions) == null ? void 0 : _g[providerOptionsName]) == null ? void 0 : _h.namespace) != null ? _k : (_j = (_i = part.providerMetadata) == null ? void 0 : _i[providerOptionsName]) == null ? void 0 : _j.namespace;
const isAsync = (_p = (_m = (_l = part.providerOptions) == null ? void 0 : _l[providerOptionsName]) == null ? void 0 : _m.async) != null ? _p : (_o = (_n = part.providerMetadata) == null ? void 0 : _n[providerOptionsName]) == null ? void 0 : _o.async;
if (hasConversation && id != null) break;
const resolvedToolName = toolNameMapping.toProviderToolName(part.toolName);
if (part.toolName === toolSearchToolName) {
if (store && id != null) {
input.push({
type: "item_reference",
id
});
break;
}
const parsedInput = typeof part.input === "string" ? await parseJSON$2({
text: part.input,
schema: toolSearchInputSchema
}) : await validateTypes$2({
value: part.input,
schema: toolSearchInputSchema
});
const execution = parsedInput.call_id != null ? "client" : "server";
input.push({
type: "tool_search_call",
id: id != null ? id : part.toolCallId,
execution,
call_id: (_q = parsedInput.call_id) != null ? _q : null,
status: "completed",
arguments: parsedInput.arguments
});
break;
}
if (part.providerExecuted) {
if (store && id != null) input.push({
type: "item_reference",
id
});
if (store || !hasShellTool || resolvedToolName !== "shell") break;
}
const isProviderDefinedToolCall = hasLocalShellTool && resolvedToolName === "local_shell" || hasShellTool && resolvedToolName === "shell" || hasApplyPatchTool && resolvedToolName === "apply_patch" || ((_r = customProviderToolNames == null ? void 0 : customProviderToolNames.has(resolvedToolName)) != null ? _r : false);
if (hasPreviousResponseId && store && id != null && isProviderDefinedToolCall) break;
if (store && id != null && isProviderDefinedToolCall) {
input.push({
type: "item_reference",
id
});
break;
}
if (hasLocalShellTool && resolvedToolName === "local_shell") {
const parsedInput = await validateTypes$2({
value: part.input,
schema: localShellInputSchema
});
input.push({
type: "local_shell_call",
call_id: part.toolCallId,
id,
action: {
type: "exec",
command: parsedInput.action.command,
timeout_ms: parsedInput.action.timeoutMs,
user: parsedInput.action.user,
working_directory: parsedInput.action.workingDirectory,
env: parsedInput.action.env
}
});
break;
}
if (hasShellTool && resolvedToolName === "shell") {
const parsedInput = await validateTypes$2({
value: part.input,
schema: shellInputSchema
});
input.push({
type: "shell_call",
call_id: part.toolCallId,
id,
status: "completed",
action: {
commands: parsedInput.action.commands,
timeout_ms: parsedInput.action.timeoutMs,
max_output_length: parsedInput.action.maxOutputLength
}
});
break;
}
if (hasApplyPatchTool && resolvedToolName === "apply_patch") {
const parsedInput = await validateTypes$2({
value: part.input,
schema: applyPatchInputSchema
});
input.push({
type: "apply_patch_call",
call_id: parsedInput.callId,
id,
status: "completed",
operation: parsedInput.operation
});
break;
}
if (customProviderToolNames == null ? void 0 : customProviderToolNames.has(resolvedToolName)) {
input.push({
type: "custom_tool_call",
call_id: part.toolCallId,
name: resolvedToolName,
input: typeof part.input === "string" ? part.input : JSON.stringify(part.input),
...isAsync != null && { async: isAsync },
id
});
break;
}
input.push({
type: "function_call",
call_id: part.toolCallId,
name: resolvedToolName,
arguments: serializeToolCallArguments2(part.input),
...isAsync != null && { async: isAsync },
...namespace != null && { namespace }
});
break;
}
case "tool-result": {
if (part.output.type === "execution-denied" || part.output.type === "json" && typeof part.output.value === "object" && part.output.value != null && "type" in part.output.value && part.output.value.type === "execution-denied") break;
if (hasConversation) break;
const resolvedResultToolName = toolNameMapping.toProviderToolName(part.toolName);
if (resolvedResultToolName === "web_search" || resolvedResultToolName === "web_search_preview") {
const itemId = (_u = (_t = (_s = part.providerOptions) == null ? void 0 : _s[providerOptionsName]) == null ? void 0 : _t.itemId) != null ? _u : part.toolCallId;
if (store) {
input.push({
type: "item_reference",
id: itemId
});
break;
}
const webSearchCall = await convertWebSearchToolResultOutput({
output: part.output,
id: itemId
});
if (webSearchCall != null) {
input.push(webSearchCall);
break;
}
}
if (part.toolName === toolSearchToolName) {
const itemId = (_A = (_z = (_w = (_v = part.providerOptions) == null ? void 0 : _v[providerOptionsName]) == null ? void 0 : _w.itemId) != null ? _z : (_y = (_x = part.providerMetadata) == null ? void 0 : _x[providerOptionsName]) == null ? void 0 : _y.itemId) != null ? _A : part.toolCallId;
if (store) input.push({
type: "item_reference",
id: itemId
});
else if (part.output.type === "json") {
const parsedOutput = await validateTypes$2({
value: part.output.value,
schema: toolSearchOutputSchema
});
input.push({
type: "tool_search_output",
id: itemId,
execution: "server",
call_id: null,
status: "completed",
tools: parsedOutput.tools
});
}
break;
}
if (hasShellTool && resolvedResultToolName === "shell") {
if (part.output.type === "json") {
const parsedOutput = await validateTypes$2({
value: part.output.value,
schema: shellOutputSchema
});
input.push({
type: "shell_call_output",
call_id: part.toolCallId,
output: parsedOutput.output.map((item) => ({
stdout: item.stdout,
stderr: item.stderr,
outcome: item.outcome.type === "timeout" ? { type: "timeout" } : {
type: "exit",
exit_code: item.outcome.exitCode
}
}))
});
}
break;
}
if (store) {
const itemId = (_D = (_C = (_B = part.providerOptions) == null ? void 0 : _B[providerOptionsName]) == null ? void 0 : _C.itemId) != null ? _D : part.toolCallId;
input.push({
type: "item_reference",
id: itemId
});
} else warnings.push({
type: "other",
message: `Results for OpenAI tool ${part.toolName} are not sent to the API when store is false`
});
break;
}
case "reasoning": {
hasPrecedingReasoning = true;
const providerOptions2 = await parseProviderOptions$1({
provider: providerOptionsName,
providerOptions: part.providerOptions,
schema: openaiResponsesReasoningProviderOptionsSchema
});
const reasoningId = providerOptions2 == null ? void 0 : providerOptions2.itemId;
if ((hasConversation || hasPreviousResponseId) && reasoningId != null) break;
if (reasoningId != null) {
const reasoningMessage = reasoningMessages[reasoningId];
if (store) {
if (reasoningMessage === void 0) {
input.push({
type: "item_reference",
id: reasoningId
});
reasoningMessages[reasoningId] = {
type: "reasoning",
id: reasoningId,
summary: []
};
}
} else {
const summaryParts = [];
if (part.text.length > 0) summaryParts.push({
type: "summary_text",
text: part.text
});
else if (reasoningMessage !== void 0) warnings.push({
type: "other",
message: `Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(part)}.`
});
if (reasoningMessage === void 0) {
reasoningMessages[reasoningId] = {
type: "reasoning",
id: reasoningId,
encrypted_content: providerOptions2 == null ? void 0 : providerOptions2.reasoningEncryptedContent,
summary: summaryParts
};
input.push(reasoningMessages[reasoningId]);
} else {
reasoningMessage.summary.push(...summaryParts);
if ((providerOptions2 == null ? void 0 : providerOptions2.reasoningEncryptedContent) != null) reasoningMessage.encrypted_content = providerOptions2.reasoningEncryptedContent;
}
}
} else {
const encryptedContent = providerOptions2 == null ? void 0 : providerOptions2.reasoningEncryptedContent;
if (encryptedContent != null) {
const summaryParts = [];
if (part.text.length > 0) summaryParts.push({
type: "summary_text",
text: part.text
});
input.push({
type: "reasoning",
encrypted_content: encryptedContent,
summary: summaryParts
});
} else warnings.push({
type: "other",
message: `Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(part)}.`
});
}
break;
}
}
break;
}
case "tool":
for (const part of content) {
if (part.type === "tool-approval-response") {
const approvalResponse = part;
if (processedApprovalIds.has(approvalResponse.approvalId)) continue;
processedApprovalIds.add(approvalResponse.approvalId);
if (store && !hasConversation && !hasPreviousResponseId) input.push({
type: "item_reference",
id: approvalResponse.approvalId
});
input.push({
type: "mcp_approval_response",
approval_request_id: approvalResponse.approvalId,
approve: approvalResponse.approved
});
continue;
}
const parallelToolCallMetadata = getParallelToolCallMetadata({
providerOptions: part.providerOptions,
providerOptionsName
});
const parallelToolResultGroup = parallelToolCallMetadata == null ? void 0 : parallelToolResultGroups.get(parallelToolCallMetadata.toolCallId);
if (parallelToolCallMetadata != null && parallelToolResultGroup != null && hasSameParallelToolCall(parallelToolResultGroup.metadata, parallelToolCallMetadata)) {
if (!emittedParallelToolResults.has(parallelToolResultGroup.metadata.toolCallId)) {
emittedParallelToolResults.add(parallelToolResultGroup.metadata.toolCallId);
const toolOutputs = await Promise.all(parallelToolResultGroup.results.map(async (result) => {
const promptCacheBreakpoint = getScalarToolResultPromptCacheBreakpoint({
output: result.output,
toolResultProviderOptions: result.providerOptions,
providerOptionsName
});
return {
output: await convertFunctionToolResultOutput({
output: result.output,
providerOptionsName,
warnings
}),
promptCacheBreakpoint
};
}));
const serializedToolOutputs = toolOutputs.map(({ output: output2 }) => typeof output2 === "string" ? output2 : JSON.stringify(output2));
const hasPromptCacheBreakpoint = toolOutputs.some(({ promptCacheBreakpoint }) => promptCacheBreakpoint != null);
input.push({
type: "function_call_output",
call_id: parallelToolResultGroup.metadata.toolCallId,
output: hasPromptCacheBreakpoint ? serializedToolOutputs.map((text, index) => ({
type: "input_text",
text: index === 0 ? text : `
${text}`,
...toolOutputs[index].promptCacheBreakpoint != null && { prompt_cache_breakpoint: toolOutputs[index].promptCacheBreakpoint }
})) : serializedToolOutputs.join("\n")
});
}
continue;
}
const output = part.output;
if (output.type === "execution-denied") {
if ((_F = (_E = output.providerOptions) == null ? void 0 : _E.openai) == null ? void 0 : _F.approvalId) continue;
}
const resolvedToolName = toolNameMapping.toProviderToolName(part.toolName);
if (part.toolName === toolSearchToolName && output.type === "json") {
const parsedOutput = await validateTypes$2({
value: output.value,
schema: toolSearchOutputSchema
});
input.push({
type: "tool_search_output",
execution: "client",
call_id: part.toolCallId,
status: "completed",
tools: parsedOutput.tools
});
continue;
}
if (hasLocalShellTool && resolvedToolName === "local_shell" && output.type === "json") {
const parsedOutput = await validateTypes$2({
value: output.value,
schema: localShellOutputSchema
});
input.push({
type: "local_shell_call_output",
call_id: part.toolCallId,
output: parsedOutput.output
});
continue;
}
if (hasShellTool && resolvedToolName === "shell" && output.type === "json") {
const parsedOutput = await validateTypes$2({
value: output.value,
schema: shellOutputSchema
});
input.push({
type: "shell_call_output",
call_id: part.toolCallId,
output: parsedOutput.output.map((item) => ({
stdout: item.stdout,
stderr: item.stderr,
outcome: item.outcome.type === "timeout" ? { type: "timeout" } : {
type: "exit",
exit_code: item.outcome.exitCode
}
}))
});
continue;
}
if (hasApplyPatchTool && part.toolName === "apply_patch" && output.type === "json") {
const parsedOutput = await validateTypes$2({
value: output.value,
schema: applyPatchOutputSchema
});
input.push({
type: "apply_patch_call_output",
call_id: part.toolCallId,
status: parsedOutput.status,
output: parsedOutput.output
});
continue;
}
if (customProviderToolNames == null ? void 0 : customProviderToolNames.has(resolvedToolName)) {
const promptCacheBreakpoint = getScalarToolResultPromptCacheBreakpoint({
output,
toolResultProviderOptions: part.providerOptions,
providerOptionsName
});
const convertScalarOutput = (value) => promptCacheBreakpoint == null ? value : [{
type: "input_text",
text: value,
prompt_cache_breakpoint: promptCacheBreakpoint
}];
let outputValue;
switch (output.type) {
case "text":
case "error-text":
outputValue = convertScalarOutput(output.value);
break;
case "execution-denied":
outputValue = convertScalarOutput((_G = output.reason) != null ? _G : "Tool call execution denied.");
break;
case "json":
case "error-json":
outputValue = convertScalarOutput(JSON.stringify(output.value));
break;
case "content":
outputValue = output.value.map((item) => {
var _a3, _b2, _c2, _d2, _e2;
const promptCacheBreakpoint2 = getPromptCacheBreakpoint2(item.providerOptions, providerOptionsName);
switch (item.type) {
case "text": return {
type: "input_text",
text: item.text,
...promptCacheBreakpoint2 != null && { prompt_cache_breakpoint: promptCacheBreakpoint2 }
};
case "image-data": return {
type: "input_image",
image_url: `data:${item.mediaType};base64,${item.data}`,
detail: (_b2 = (_a3 = item.providerOptions) == null ? void 0 : _a3[providerOptionsName]) == null ? void 0 : _b2.imageDetail,
...promptCacheBreakpoint2 != null && { prompt_cache_breakpoint: promptCacheBreakpoint2 }
};
case "image-url": return {
type: "input_image",
image_url: item.url,
detail: (_d2 = (_c2 = item.providerOptions) == null ? void 0 : _c2[providerOptionsName]) == null ? void 0 : _d2.imageDetail,
...promptCacheBreakpoint2 != null && { prompt_cache_breakpoint: promptCacheBreakpoint2 }
};
case "file-data": return {
type: "input_file",
filename: (_e2 = item.filename) != null ? _e2 : "data",
file_data: `data:${item.mediaType};base64,${item.data}`,
...promptCacheBreakpoint2 != null && { prompt_cache_breakpoint: promptCacheBreakpoint2 }
};
case "file-url": return {
type: "input_file",
file_url: item.url,
...promptCacheBreakpoint2 != null && { prompt_cache_breakpoint: promptCacheBreakpoint2 }
};
default:
warnings.push({
type: "other",
message: `unsupported custom tool content part type: ${item.type}`
});
return;
}
}).filter(isNonNullable);
break;
default: outputValue = "";
}
input.push({
type: "custom_tool_call_output",
call_id: part.toolCallId,
output: outputValue
});
continue;
}
const contentValue = await convertFunctionToolResultOutput({
output,
promptCacheBreakpoint: getScalarToolResultPromptCacheBreakpoint({
output,
toolResultProviderOptions: part.providerOptions,
providerOptionsName
}),
providerOptionsName,
warnings
});
input.push({
type: "function_call_output",
call_id: part.toolCallId,
output: contentValue
});
}
break;
default: throw new Error(`Unsupported role: ${role}`);
}
if (!store && input.some((item) => "type" in item && item.type === "reasoning" && item.encrypted_content == null)) {
warnings.push({
type: "other",
message: "Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."
});
input = input.filter((item) => !("type" in item) || item.type !== "reasoning" || item.encrypted_content != null);
}
return {
input,
warnings
};
}
var openaiResponsesReasoningProviderOptionsSchema = lazySchema$1(() => zodSchema$2(z.object({
itemId: z.string().nullish(),
reasoningEncryptedContent: z.string().nullish()
})));
function mapOpenAIResponseFinishReason({ finishReason, hasFunctionCall }) {
switch (finishReason) {
case void 0:
case null: return hasFunctionCall ? "tool-calls" : "stop";
case "max_output_tokens": return "length";
case "content_filter": return "content-filter";
default: return hasFunctionCall ? "tool-calls" : "other";
}
}
var cachedJsonValueSchema2;
var jsonValueSchema2 = () => cachedJsonValueSchema2 != null ? cachedJsonValueSchema2 : cachedJsonValueSchema2 = z.lazy(() => z.union([
z.string(),
z.number(),
z.boolean(),
z.null(),
z.array(jsonValueSchema2()),
z.record(z.string(), jsonValueSchema2().optional())
]));
var jsonObjectSchema = () => z.record(z.string(), jsonValueSchema2().optional());
var openaiResponsesUsageSchema = () => z.intersection(jsonObjectSchema(), z.object({
input_tokens: z.number(),
input_tokens_details: z.intersection(jsonObjectSchema(), z.object({
cached_tokens: z.number().nullish(),
cache_write_tokens: z.number().nullish(),
cache_write_tokens_details: z.intersection(jsonObjectSchema(), z.object({
ttl_30m_tokens: z.number().nullish(),
ttl_12h_tokens: z.number().nullish()
})).nullish(),
orchestration_input_tokens: z.number().nullish(),
orchestration_input_cached_tokens: z.number().nullish()
})).nullish(),
output_tokens: z.number(),
output_tokens_details: z.intersection(jsonObjectSchema(), z.object({
reasoning_tokens: z.number().nullish(),
orchestration_output_tokens: z.number().nullish()
})).nullish(),
total_tokens: z.number().optional()
}));
function isRecord$1(value) {
return value != null && typeof value === "object" && !Array.isArray(value);
}
var openaiResponsesLocalShellCallSchema = () => z.object({
type: z.literal("local_shell_call"),
id: z.string(),
call_id: z.string(),
action: z.object({
type: z.literal("exec"),
command: z.array(z.string()),
timeout_ms: z.number().optional(),
user: z.string().optional(),
working_directory: z.string().optional(),
env: z.record(z.string(), z.string()).optional()
})
});
var openaiResponsesNestedErrorChunkSchema = () => z.object({
type: z.literal("error"),
sequence_number: z.number(),
error: z.object({
type: z.string(),
code: z.string().nullish(),
message: z.string(),
param: z.string().nullish()
})
});
var openaiResponsesErrorChunkSchema = () => z.object({
type: z.literal("error"),
sequence_number: z.number(),
code: z.string().nullish(),
message: z.string(),
param: z.string().nullish()
});
var openaiResponsesModeledChunkTypes = /* @__PURE__ */ new Set([
"error",
"response.apply_patch_call_operation_diff.delta",
"response.apply_patch_call_operation_diff.done",
"response.code_interpreter_call_code.delta",
"response.code_interpreter_call_code.done",
"response.completed",
"response.created",
"response.custom_tool_call_input.delta",
"response.failed",
"response.function_call_arguments.delta",
"response.function_call_arguments.done",
"response.image_generation_call.partial_image",
"response.incomplete",
"response.output_item.added",
"response.output_item.done",
"response.output_text.annotation.added",
"response.output_text.delta",
"response.reasoning_summary_part.added",
"response.reasoning_summary_part.done",
"response.reasoning_summary_text.delta"
]);
var openaiResponsesModeledOutputItemTypes = /* @__PURE__ */ new Set([
"apply_patch_call",
"code_interpreter_call",
"computer_call",
"custom_tool_call",
"file_search_call",
"function_call",
"image_generation_call",
"local_shell_call",
"mcp_approval_request",
"mcp_call",
"mcp_list_tools",
"message",
"reasoning",
"shell_call",
"shell_call_output",
"tool_search_call",
"tool_search_output",
"web_search_call"
]);
function isModeledOpenAIResponsesChunk(value) {
if (typeof value.type !== "string" || !openaiResponsesModeledChunkTypes.has(value.type)) return false;
if (value.type !== "response.output_item.added" && value.type !== "response.output_item.done") return true;
if (!isRecord$1(value.item) || typeof value.item.type !== "string") return true;
return openaiResponsesModeledOutputItemTypes.has(value.item.type);
}
var openaiResponsesChunkSchema = lazySchema$1(() => zodSchema$2(z.union([
z.object({
type: z.literal("response.output_text.delta"),
item_id: z.string(),
delta: z.string(),
logprobs: z.array(z.object({
token: z.string(),
logprob: z.number(),
top_logprobs: z.array(z.object({
token: z.string(),
logprob: z.number()
}))
})).nullish()
}),
z.object({
type: z.enum(["response.completed", "response.incomplete"]),
response: z.object({
incomplete_details: z.object({ reason: z.string() }).nullish(),
usage: openaiResponsesUsageSchema().nullish(),
reasoning: z.object({ context: z.string().nullish() }).nullish(),
service_tier: z.string().nullish()
})
}),
z.object({
type: z.literal("response.failed"),
sequence_number: z.number(),
response: z.object({
error: z.object({
code: z.string().nullish(),
message: z.string()
}).nullish(),
incomplete_details: z.object({ reason: z.string() }).nullish(),
usage: openaiResponsesUsageSchema().nullish(),
reasoning: z.object({ context: z.string().nullish() }).nullish(),
service_tier: z.string().nullish()
})
}),
z.object({
type: z.literal("response.created"),
response: z.object({
id: z.string(),
created_at: z.number(),
model: z.string(),
service_tier: z.string().nullish()
})
}),
z.object({
type: z.literal("response.output_item.added"),
output_index: z.number(),
item: z.discriminatedUnion("type", [
z.object({
type: z.literal("message"),
id: z.string(),
phase: z.enum(["commentary", "final_answer"]).nullish()
}),
z.object({
type: z.literal("reasoning"),
id: z.string(),
encrypted_content: z.string().nullish()
}),
z.object({
type: z.literal("function_call"),
id: z.string(),
call_id: z.string(),
name: z.string(),
arguments: z.string(),
async: z.boolean().nullish(),
namespace: z.string().nullish()
}),
z.object({
type: z.literal("web_search_call"),
id: z.string(),
status: z.string()
}),
z.object({
type: z.literal("computer_call"),
id: z.string(),
status: z.string()
}),
z.object({
type: z.literal("file_search_call"),
id: z.string()
}),
openaiResponsesLocalShellCallSchema(),
z.object({
type: z.literal("image_generation_call"),
id: z.string()
}),
z.object({
type: z.literal("code_interpreter_call"),
id: z.string(),
container_id: z.string(),
code: z.string().nullable(),
outputs: z.array(z.discriminatedUnion("type", [z.object({
type: z.literal("logs"),
logs: z.string()
}), z.object({
type: z.literal("image"),
url: z.string()
})])).nullable(),
status: z.string()
}),
z.object({
type: z.literal("mcp_call"),
id: z.string(),
status: z.string(),
approval_request_id: z.string().nullish()
}),
z.object({
type: z.literal("mcp_list_tools"),
id: z.string()
}),
z.object({
type: z.literal("mcp_approval_request"),
id: z.string()
}),
z.object({
type: z.literal("apply_patch_call"),
id: z.string(),
call_id: z.string(),
status: z.enum(["in_progress", "completed"]),
operation: z.discriminatedUnion("type", [
z.object({
type: z.literal("create_file"),
path: z.string(),
diff: z.string()
}),
z.object({
type: z.literal("delete_file"),
path: z.string()
}),
z.object({
type: z.literal("update_file"),
path: z.string(),
diff: z.string()
})
])
}),
z.object({
type: z.literal("custom_tool_call"),
id: z.string(),
call_id: z.string(),
name: z.string(),
input: z.string(),
async: z.boolean().nullish()
}),
z.object({
type: z.literal("shell_call"),
id: z.string(),
call_id: z.string(),
status: z.enum([
"in_progress",
"completed",
"incomplete"
]),
action: z.object({ commands: z.array(z.string()) })
}),
z.object({
type: z.literal("shell_call_output"),
id: z.string(),
call_id: z.string(),
status: z.enum([
"in_progress",
"completed",
"incomplete"
]),
output: z.array(z.object({
stdout: z.string(),
stderr: z.string(),
outcome: z.discriminatedUnion("type", [z.object({ type: z.literal("timeout") }), z.object({
type: z.literal("exit"),
exit_code: z.number()
})])
}))
}),
z.object({
type: z.literal("tool_search_call"),
id: z.string(),
execution: z.enum(["server", "client"]),
call_id: z.string().nullable(),
status: z.enum([
"in_progress",
"completed",
"incomplete"
]),
arguments: z.unknown()
}),
z.object({
type: z.literal("tool_search_output"),
id: z.string(),
execution: z.enum(["server", "client"]),
call_id: z.string().nullable(),
status: z.enum([
"in_progress",
"completed",
"incomplete"
]),
tools: z.array(z.record(z.string(), jsonValueSchema2().optional()))
})
])
}),
z.object({
type: z.literal("response.output_item.done"),
output_index: z.number(),
item: z.discriminatedUnion("type", [
z.object({
type: z.literal("message"),
id: z.string(),
phase: z.enum(["commentary", "final_answer"]).nullish()
}),
z.object({
type: z.literal("reasoning"),
id: z.string(),
encrypted_content: z.string().nullish()
}),
z.object({
type: z.literal("function_call"),
id: z.string(),
call_id: z.string(),
name: z.string(),
arguments: z.string(),
async: z.boolean().nullish(),
status: z.enum([
"in_progress",
"completed",
"incomplete"
]),
namespace: z.string().nullish()
}),
z.object({
type: z.literal("custom_tool_call"),
id: z.string(),
call_id: z.string(),
name: z.string(),
input: z.string(),
async: z.boolean().nullish(),
status: z.enum([
"in_progress",
"completed",
"incomplete"
])
}),
z.object({
type: z.literal("code_interpreter_call"),
id: z.string(),
code: z.string().nullable(),
container_id: z.string(),
outputs: z.array(z.discriminatedUnion("type", [z.object({
type: z.literal("logs"),
logs: z.string()
}), z.object({
type: z.literal("image"),
url: z.string()
})])).nullable()
}),
z.object({
type: z.literal("image_generation_call"),
id: z.string(),
result: z.string()
}),
z.object({
type: z.literal("web_search_call"),
id: z.string(),
status: z.string(),
action: z.discriminatedUnion("type", [
z.object({
type: z.literal("search"),
query: z.string().nullish(),
queries: z.array(z.string()).nullish(),
sources: z.array(z.discriminatedUnion("type", [z.object({
type: z.literal("url"),
url: z.string()
}), z.object({
type: z.literal("api"),
name: z.string()
})])).nullish()
}),
z.object({
type: z.literal("open_page"),
url: z.string().nullish()
}),
z.object({
type: z.literal("find_in_page"),
url: z.string().nullish(),
pattern: z.string().nullish()
})
]).nullish()
}),
z.object({
type: z.literal("file_search_call"),
id: z.string(),
queries: z.array(z.string()),
results: z.array(z.object({
attributes: z.record(z.string(), z.union([
z.string(),
z.number(),
z.boolean()
])),
file_id: z.string(),
filename: z.string(),
score: z.number(),
text: z.string()
})).nullish()
}),
openaiResponsesLocalShellCallSchema(),
z.object({
type: z.literal("computer_call"),
id: z.string(),
status: z.literal("completed")
}),
z.object({
type: z.literal("mcp_call"),
id: z.string(),
status: z.string(),
arguments: z.string(),
name: z.string(),
server_label: z.string(),
output: z.string().nullish(),
error: z.union([z.string(), z.object({
type: z.string().optional(),
code: z.union([z.number(), z.string()]).optional(),
message: z.string().optional()
}).loose()]).nullish(),
approval_request_id: z.string().nullish()
}),
z.object({
type: z.literal("mcp_list_tools"),
id: z.string(),
server_label: z.string(),
tools: z.array(z.object({
name: z.string(),
description: z.string().optional(),
input_schema: z.any(),
annotations: z.record(z.string(), z.unknown()).optional()
})),
error: z.union([z.string(), z.object({
type: z.string().optional(),
code: z.union([z.number(), z.string()]).optional(),
message: z.string().optional()
}).loose()]).optional()
}),
z.object({
type: z.literal("mcp_approval_request"),
id: z.string(),
server_label: z.string(),
name: z.string(),
arguments: z.string(),
approval_request_id: z.string().optional()
}),
z.object({
type: z.literal("apply_patch_call"),
id: z.string(),
call_id: z.string(),
status: z.enum(["in_progress", "completed"]),
operation: z.discriminatedUnion("type", [
z.object({
type: z.literal("create_file"),
path: z.string(),
diff: z.string()
}),
z.object({
type: z.literal("delete_file"),
path: z.string()
}),
z.object({
type: z.literal("update_file"),
path: z.string(),
diff: z.string()
})
])
}),
z.object({
type: z.literal("shell_call"),
id: z.string(),
call_id: z.string(),
status: z.enum([
"in_progress",
"completed",
"incomplete"
]),
action: z.object({ commands: z.array(z.string()) })
}),
z.object({
type: z.literal("shell_call_output"),
id: z.string(),
call_id: z.string(),
status: z.enum([
"in_progress",
"completed",
"incomplete"
]),
output: z.array(z.object({
stdout: z.string(),
stderr: z.string(),
outcome: z.discriminatedUnion("type", [z.object({ type: z.literal("timeout") }), z.object({
type: z.literal("exit"),
exit_code: z.number()
})])
}))
}),
z.object({
type: z.literal("tool_search_call"),
id: z.string(),
execution: z.enum(["server", "client"]),
call_id: z.string().nullable(),
status: z.enum([
"in_progress",
"completed",
"incomplete"
]),
arguments: z.unknown()
}),
z.object({
type: z.literal("tool_search_output"),
id: z.string(),
execution: z.enum(["server", "client"]),
call_id: z.string().nullable(),
status: z.enum([
"in_progress",
"completed",
"incomplete"
]),
tools: z.array(z.record(z.string(), jsonValueSchema2().optional()))
})
])
}),
z.object({
type: z.literal("response.function_call_arguments.delta"),
item_id: z.string(),
output_index: z.number(),
delta: z.string()
}),
z.object({
type: z.literal("response.function_call_arguments.done"),
item_id: z.string(),
output_index: z.number(),
arguments: z.string()
}),
z.object({
type: z.literal("response.custom_tool_call_input.delta"),
item_id: z.string(),
output_index: z.number(),
delta: z.string()
}),
z.object({
type: z.literal("response.image_generation_call.partial_image"),
item_id: z.string(),
output_index: z.number(),
partial_image_b64: z.string()
}),
z.object({
type: z.literal("response.code_interpreter_call_code.delta"),
item_id: z.string(),
output_index: z.number(),
delta: z.string()
}),
z.object({
type: z.literal("response.code_interpreter_call_code.done"),
item_id: z.string(),
output_index: z.number(),
code: z.string()
}),
z.object({
type: z.literal("response.output_text.annotation.added"),
annotation: z.discriminatedUnion("type", [
z.object({
type: z.literal("url_citation"),
start_index: z.number(),
end_index: z.number(),
url: z.string(),
title: z.string()
}),
z.object({
type: z.literal("file_citation"),
file_id: z.string(),
filename: z.string(),
index: z.number()
}),
z.object({
type: z.literal("container_file_citation"),
container_id: z.string(),
file_id: z.string(),
filename: z.string(),
start_index: z.number(),
end_index: z.number()
}),
z.object({
type: z.literal("file_path"),
file_id: z.string(),
index: z.number()
})
])
}),
z.object({
type: z.literal("response.reasoning_summary_part.added"),
item_id: z.string(),
summary_index: z.number()
}),
z.object({
type: z.literal("response.reasoning_summary_text.delta"),
item_id: z.string(),
summary_index: z.number(),
delta: z.string()
}),
z.object({
type: z.literal("response.reasoning_summary_part.done"),
item_id: z.string(),
summary_index: z.number()
}),
z.object({
type: z.literal("response.apply_patch_call_operation_diff.delta"),
item_id: z.string(),
output_index: z.number(),
delta: z.string(),
obfuscation: z.string().nullish()
}),
z.object({
type: z.literal("response.apply_patch_call_operation_diff.done"),
item_id: z.string(),
output_index: z.number(),
diff: z.string()
}),
openaiResponsesNestedErrorChunkSchema(),
openaiResponsesErrorChunkSchema(),
z.object({ type: z.string() }).loose().refine((value) => !isModeledOpenAIResponsesChunk(value), { message: "Known response chunk failed schema validation" }).transform((value) => ({
type: "unknown_chunk",
message: value.type
}))
])));
var openaiResponsesResponseSchema = lazySchema$1(() => zodSchema$2(z.object({
id: z.string().optional(),
created_at: z.number().optional(),
error: z.object({
message: z.string(),
type: z.string(),
param: z.string().nullish(),
code: z.string()
}).nullish(),
model: z.string().optional(),
output: z.array(z.discriminatedUnion("type", [
z.object({
type: z.literal("message"),
role: z.literal("assistant"),
id: z.string(),
phase: z.enum(["commentary", "final_answer"]).nullish(),
content: z.array(z.object({
type: z.literal("output_text"),
text: z.string(),
logprobs: z.array(z.object({
token: z.string(),
logprob: z.number(),
top_logprobs: z.array(z.object({
token: z.string(),
logprob: z.number()
}))
})).nullish(),
annotations: z.array(z.discriminatedUnion("type", [
z.object({
type: z.literal("url_citation"),
start_index: z.number(),
end_index: z.number(),
url: z.string(),
title: z.string()
}),
z.object({
type: z.literal("file_citation"),
file_id: z.string(),
filename: z.string(),
index: z.number()
}),
z.object({
type: z.literal("container_file_citation"),
container_id: z.string(),
file_id: z.string(),
filename: z.string(),
start_index: z.number(),
end_index: z.number()
}),
z.object({
type: z.literal("file_path"),
file_id: z.string(),
index: z.number()
})
]))
}))
}),
z.object({
type: z.literal("web_search_call"),
id: z.string(),
status: z.string(),
action: z.discriminatedUnion("type", [
z.object({
type: z.literal("search"),
query: z.string().nullish(),
queries: z.array(z.string()).nullish(),
sources: z.array(z.discriminatedUnion("type", [z.object({
type: z.literal("url"),
url: z.string()
}), z.object({
type: z.literal("api"),
name: z.string()
})])).nullish()
}),
z.object({
type: z.literal("open_page"),
url: z.string().nullish()
}),
z.object({
type: z.literal("find_in_page"),
url: z.string().nullish(),
pattern: z.string().nullish()
})
]).nullish()
}),
z.object({
type: z.literal("file_search_call"),
id: z.string(),
queries: z.array(z.string()),
results: z.array(z.object({
attributes: z.record(z.string(), z.union([
z.string(),
z.number(),
z.boolean()
])),
file_id: z.string(),
filename: z.string(),
score: z.number(),
text: z.string()
})).nullish()
}),
z.object({
type: z.literal("code_interpreter_call"),
id: z.string(),
code: z.string().nullable(),
container_id: z.string(),
outputs: z.array(z.discriminatedUnion("type", [z.object({
type: z.literal("logs"),
logs: z.string()
}), z.object({
type: z.literal("image"),
url: z.string()
})])).nullable()
}),
z.object({
type: z.literal("image_generation_call"),
id: z.string(),
result: z.string()
}),
openaiResponsesLocalShellCallSchema(),
z.object({
type: z.literal("function_call"),
call_id: z.string(),
name: z.string(),
arguments: z.string(),
id: z.string(),
async: z.boolean().nullish(),
namespace: z.string().nullish()
}),
z.object({
type: z.literal("custom_tool_call"),
call_id: z.string(),
name: z.string(),
input: z.string(),
id: z.string(),
async: z.boolean().nullish()
}),
z.object({
type: z.literal("computer_call"),
id: z.string(),
status: z.string().optional()
}),
z.object({
type: z.literal("reasoning"),
id: z.string(),
encrypted_content: z.string().nullish(),
summary: z.array(z.object({
type: z.literal("summary_text"),
text: z.string()
}))
}),
z.object({
type: z.literal("mcp_call"),
id: z.string(),
status: z.string(),
arguments: z.string(),
name: z.string(),
server_label: z.string(),
output: z.string().nullish(),
error: z.union([z.string(), z.object({
type: z.string().optional(),
code: z.union([z.number(), z.string()]).optional(),
message: z.string().optional()
}).loose()]).nullish(),
approval_request_id: z.string().nullish()
}),
z.object({
type: z.literal("mcp_list_tools"),
id: z.string(),
server_label: z.string(),
tools: z.array(z.object({
name: z.string(),
description: z.string().optional(),
input_schema: z.any(),
annotations: z.record(z.string(), z.unknown()).optional()
})),
error: z.union([z.string(), z.object({
type: z.string().optional(),
code: z.union([z.number(), z.string()]).optional(),
message: z.string().optional()
}).loose()]).optional()
}),
z.object({
type: z.literal("mcp_approval_request"),
id: z.string(),
server_label: z.string(),
name: z.string(),
arguments: z.string(),
approval_request_id: z.string().optional()
}),
z.object({
type: z.literal("apply_patch_call"),
id: z.string(),
call_id: z.string(),
status: z.enum(["in_progress", "completed"]),
operation: z.discriminatedUnion("type", [
z.object({
type: z.literal("create_file"),
path: z.string(),
diff: z.string()
}),
z.object({
type: z.literal("delete_file"),
path: z.string()
}),
z.object({
type: z.literal("update_file"),
path: z.string(),
diff: z.string()
})
])
}),
z.object({
type: z.literal("shell_call"),
id: z.string(),
call_id: z.string(),
status: z.enum([
"in_progress",
"completed",
"incomplete"
]),
action: z.object({ commands: z.array(z.string()) })
}),
z.object({
type: z.literal("shell_call_output"),
id: z.string(),
call_id: z.string(),
status: z.enum([
"in_progress",
"completed",
"incomplete"
]),
output: z.array(z.object({
stdout: z.string(),
stderr: z.string(),
outcome: z.discriminatedUnion("type", [z.object({ type: z.literal("timeout") }), z.object({
type: z.literal("exit"),
exit_code: z.number()
})])
}))
}),
z.object({
type: z.literal("tool_search_call"),
id: z.string(),
execution: z.enum(["server", "client"]),
call_id: z.string().nullable(),
status: z.enum([
"in_progress",
"completed",
"incomplete"
]),
arguments: z.unknown()
}),
z.object({
type: z.literal("tool_search_output"),
id: z.string(),
execution: z.enum(["server", "client"]),
call_id: z.string().nullable(),
status: z.enum([
"in_progress",
"completed",
"incomplete"
]),
tools: z.array(z.record(z.string(), jsonValueSchema2().optional()))
})
])).optional(),
service_tier: z.string().nullish(),
reasoning: z.object({ context: z.string().nullish() }).nullish(),
incomplete_details: z.object({ reason: z.string() }).nullish(),
usage: openaiResponsesUsageSchema().nullish()
})));
async function prepareResponsesTools$1({ tools, toolChoice, allowedTools, toolNameMapping, customProviderToolNames, supportsAsyncToolCalling = true, providerOptionsName = "openai" }) {
var _a2, _b, _c, _d, _e, _f;
tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
const toolWarnings = [];
if (tools == null) return {
tools: void 0,
toolChoice: void 0,
toolWarnings
};
const openaiTools2 = [];
const namespaceTools = /* @__PURE__ */ new Map();
const resolvedCustomProviderToolNames = customProviderToolNames != null ? customProviderToolNames : /* @__PURE__ */ new Set();
const allowedToolResolutions = /* @__PURE__ */ new Map();
const allowedToolAliases = /* @__PURE__ */ new Map();
const recordAllowedTool = (toolName, resolution, canonicalName) => {
allowedToolResolutions.set(toolName, resolution);
if (canonicalName == null || canonicalName === toolName) return;
const existingAlias = allowedToolAliases.get(canonicalName);
if (existingAlias == null) allowedToolAliases.set(canonicalName, resolution);
else if (existingAlias !== "ambiguous" && !isSameAllowedTool(existingAlias, resolution)) allowedToolAliases.set(canonicalName, "ambiguous");
};
for (const tool of tools) switch (tool.type) {
case "function": {
const openaiOptions = (_c = (_a2 = tool.providerOptions) == null ? void 0 : _a2[providerOptionsName]) != null ? _c : (_b = tool.providerOptions) == null ? void 0 : _b.openai;
const openaiFunctionTool = prepareFunctionTool({
tool,
options: openaiOptions,
async: resolveAsyncToolOption({
value: openaiOptions == null ? void 0 : openaiOptions.async,
supportsAsyncToolCalling,
toolName: tool.name,
toolWarnings
})
});
const namespace = openaiOptions == null ? void 0 : openaiOptions.namespace;
if (namespace == null) openaiTools2.push(openaiFunctionTool);
else {
let namespaceTool = namespaceTools.get(namespace.name);
if (namespaceTool == null) {
namespaceTool = {
type: "namespace",
name: namespace.name,
description: namespace.description,
tools: []
};
namespaceTools.set(namespace.name, namespaceTool);
openaiTools2.push(namespaceTool);
} else if (namespaceTool.description !== namespace.description) throw new UnsupportedFunctionalityError$2({ functionality: `conflicting descriptions for OpenAI tool namespace "${namespace.name}"` });
namespaceTool.tools.push(openaiFunctionTool);
}
recordAllowedTool(tool.name, namespace != null ? {
supported: false,
reason: "tools inside an OpenAI tool namespace are not visible to tool_choice.allowed_tools"
} : (openaiOptions == null ? void 0 : openaiOptions.deferLoading) === true ? {
supported: false,
reason: "deferred tools are not visible to tool_choice.allowed_tools"
} : {
supported: true,
entry: {
type: "function",
name: tool.name
}
}, void 0);
break;
}
case "provider": {
const openaiToolCountBefore = openaiTools2.length;
switch (tool.id) {
case "openai.file_search": {
const args = await validateTypes$2({
value: tool.args,
schema: fileSearchArgsSchema$2
});
openaiTools2.push({
type: "file_search",
vector_store_ids: args.vectorStoreIds,
max_num_results: args.maxNumResults,
ranking_options: args.ranking ? {
ranker: args.ranking.ranker,
score_threshold: args.ranking.scoreThreshold
} : void 0,
filters: args.filters
});
break;
}
case "openai.local_shell":
openaiTools2.push({ type: "local_shell" });
break;
case "openai.shell": {
const args = await validateTypes$2({
value: tool.args,
schema: shellArgsSchema
});
openaiTools2.push({
type: "shell",
...args.environment && { environment: mapShellEnvironment(args.environment) }
});
break;
}
case "openai.apply_patch":
openaiTools2.push({ type: "apply_patch" });
break;
case "openai.web_search_preview": {
const args = await validateTypes$2({
value: tool.args,
schema: webSearchPreviewArgsSchema
});
openaiTools2.push({
type: "web_search_preview",
search_context_size: args.searchContextSize,
user_location: args.userLocation
});
break;
}
case "openai.web_search": {
const args = await validateTypes$2({
value: tool.args,
schema: webSearchArgsSchema$1
});
openaiTools2.push({
type: "web_search",
filters: args.filters != null ? {
allowed_domains: args.filters.allowedDomains,
blocked_domains: args.filters.blockedDomains
} : void 0,
external_web_access: args.externalWebAccess,
search_context_size: args.searchContextSize,
user_location: args.userLocation
});
break;
}
case "openai.code_interpreter": {
const args = await validateTypes$2({
value: tool.args,
schema: codeInterpreterArgsSchema
});
openaiTools2.push({
type: "code_interpreter",
container: args.container == null ? {
type: "auto",
file_ids: void 0
} : typeof args.container === "string" ? args.container : {
type: "auto",
file_ids: args.container.fileIds
}
});
break;
}
case "openai.image_generation": {
const args = await validateTypes$2({
value: tool.args,
schema: imageGenerationArgsSchema$1
});
openaiTools2.push({
type: "image_generation",
background: args.background,
input_fidelity: args.inputFidelity,
input_image_mask: args.inputImageMask ? {
file_id: args.inputImageMask.fileId,
image_url: args.inputImageMask.imageUrl
} : void 0,
model: args.model,
moderation: args.moderation,
partial_images: args.partialImages,
quality: args.quality,
output_compression: args.outputCompression,
output_format: args.outputFormat,
size: args.size
});
break;
}
case "openai.mcp": {
const args = await validateTypes$2({
value: tool.args,
schema: mcpArgsSchema
});
const mapApprovalFilter = (filter) => ({ tool_names: filter.toolNames });
const requireApproval = args.requireApproval;
const requireApprovalParam = requireApproval == null ? void 0 : typeof requireApproval === "string" ? requireApproval : requireApproval.never != null ? { never: mapApprovalFilter(requireApproval.never) } : void 0;
openaiTools2.push({
type: "mcp",
server_label: args.serverLabel,
allowed_tools: Array.isArray(args.allowedTools) ? args.allowedTools : args.allowedTools ? {
read_only: args.allowedTools.readOnly,
tool_names: args.allowedTools.toolNames
} : void 0,
authorization: args.authorization,
connector_id: args.connectorId,
headers: args.headers,
require_approval: requireApprovalParam != null ? requireApprovalParam : "never",
server_description: args.serverDescription,
server_url: args.serverUrl
});
break;
}
case "openai.custom": {
const args = await validateTypes$2({
value: tool.args,
schema: customArgsSchema
});
openaiTools2.push({
type: "custom",
name: args.name,
description: args.description,
...resolveAsyncToolOption({
value: args.async,
supportsAsyncToolCalling,
toolName: args.name,
toolWarnings
}) != null ? { async: args.async } : {},
format: args.format
});
resolvedCustomProviderToolNames.add(args.name);
break;
}
case "openai.tool_search": {
const args = await validateTypes$2({
value: tool.args,
schema: toolSearchArgsSchema
});
openaiTools2.push({
type: "tool_search",
...args.execution != null ? { execution: args.execution } : {},
...args.description != null ? { description: args.description } : {},
...args.parameters != null ? { parameters: args.parameters } : {}
});
break;
}
}
if (openaiTools2.length > openaiToolCountBefore) {
const openaiTool = openaiTools2[openaiToolCountBefore];
recordAllowedTool(tool.name, toAllowedToolResolution(openaiTool), toolNameMapping == null ? void 0 : toolNameMapping.toProviderToolName(tool.name));
}
break;
}
default: toolWarnings.push({
type: "unsupported",
feature: `function tool ${tool}`
});
}
if (allowedTools != null) {
const allowedToolEntries = [];
const droppedToolNames = [];
for (const name of allowedTools.toolNames) {
const directResolution = allowedToolResolutions.get(name);
const resolution = directResolution != null ? directResolution : allowedToolAliases.get(name);
if (directResolution != null && allowedToolAliases.has(name)) toolWarnings.push({
type: "unsupported",
feature: `allowedTools entry "${name}"`,
details: "this name is both a tool name and the provider tool name of another tool in this request; the tool with this name is allowed"
});
if (resolution === "ambiguous") {
toolWarnings.push({
type: "unsupported",
feature: `allowedTools entry "${name}"`,
details: "several tools in this request share this provider tool name; use the tool name from the tools for this request instead"
});
droppedToolNames.push(name);
continue;
}
if (resolution == null) {
toolWarnings.push({
type: "unsupported",
feature: `allowedTools entry "${name}"`,
details: "the tool is not part of the tools for this request and is sent as a function tool"
});
allowedToolEntries.push({
type: "function",
name: (_d = toolNameMapping == null ? void 0 : toolNameMapping.toProviderToolName(name)) != null ? _d : name
});
continue;
}
if (!resolution.supported) {
toolWarnings.push({
type: "unsupported",
feature: `allowedTools entry "${name}"`,
details: `${resolution.reason}; the tool is removed from the allowed tools`
});
droppedToolNames.push(name);
continue;
}
allowedToolEntries.push(resolution.entry);
}
if (allowedToolEntries.length === 0) throw new UnsupportedFunctionalityError$2({ functionality: `allowedTools with only tools that cannot be allow-listed (${droppedToolNames.join(", ")})` });
return {
tools: openaiTools2,
toolChoice: {
type: "allowed_tools",
mode: (_e = allowedTools.mode) != null ? _e : "auto",
tools: allowedToolEntries
},
toolWarnings
};
}
if (toolChoice == null) return {
tools: openaiTools2,
toolChoice: void 0,
toolWarnings
};
const type = toolChoice.type;
switch (type) {
case "auto":
case "none":
case "required": return {
tools: openaiTools2,
toolChoice: type,
toolWarnings
};
case "tool": {
const resolvedToolName = (_f = toolNameMapping == null ? void 0 : toolNameMapping.toProviderToolName(toolChoice.toolName)) != null ? _f : toolChoice.toolName;
return {
tools: openaiTools2,
toolChoice: resolvedToolName === "code_interpreter" || resolvedToolName === "file_search" || resolvedToolName === "image_generation" || resolvedToolName === "web_search_preview" || resolvedToolName === "web_search" || resolvedToolName === "mcp" || resolvedToolName === "apply_patch" ? { type: resolvedToolName } : resolvedCustomProviderToolNames.has(resolvedToolName) ? {
type: "custom",
name: resolvedToolName
} : {
type: "function",
name: resolvedToolName
},
toolWarnings
};
}
default: throw new UnsupportedFunctionalityError$2({ functionality: `tool choice type: ${type}` });
}
}
function allowedToolKey(entry) {
switch (entry.type) {
case "mcp": return `mcp:${entry.server_label}`;
case "function":
case "custom": return `${entry.type}:${entry.name}`;
default: return entry.type;
}
}
function isSameAllowedTool(a, b) {
if (a.supported && b.supported) return allowedToolKey(a.entry) === allowedToolKey(b.entry);
if (!a.supported && !b.supported) return a.reason === b.reason;
return false;
}
function toAllowedToolResolution(tool) {
switch (tool.type) {
case "custom": return {
supported: true,
entry: {
type: "custom",
name: tool.name
}
};
case "mcp": return {
supported: true,
entry: {
type: "mcp",
server_label: tool.server_label
}
};
case "file_search":
case "web_search":
case "web_search_preview":
case "image_generation":
case "code_interpreter":
case "apply_patch":
case "shell":
case "local_shell": return {
supported: true,
entry: { type: tool.type }
};
default: return {
supported: false,
reason: `OpenAI does not support ${tool.type} tools in tool_choice.allowed_tools`
};
}
}
function prepareFunctionTool({ tool, options, async }) {
const deferLoading = options == null ? void 0 : options.deferLoading;
return {
type: "function",
name: tool.name,
description: tool.description,
parameters: tool.inputSchema,
...async != null ? { async } : {},
...tool.strict != null ? { strict: tool.strict } : {},
...deferLoading != null ? { defer_loading: deferLoading } : {}
};
}
function resolveAsyncToolOption({ value, supportsAsyncToolCalling, toolName, toolWarnings }) {
if (value !== true || supportsAsyncToolCalling) return value;
toolWarnings.push({
type: "unsupported",
feature: `async tool calling for "${toolName}"`,
details: "Async tool calling is only supported by GPT-6 and later models."
});
}
function mapShellEnvironment(environment) {
if (environment.type === "containerReference") return {
type: "container_reference",
container_id: environment.containerId
};
if (environment.type === "containerAuto") {
const env2 = environment;
return {
type: "container_auto",
file_ids: env2.fileIds,
memory_limit: env2.memoryLimit,
network_policy: env2.networkPolicy == null ? void 0 : env2.networkPolicy.type === "disabled" ? { type: "disabled" } : {
type: "allowlist",
allowed_domains: env2.networkPolicy.allowedDomains,
domain_secrets: env2.networkPolicy.domainSecrets
},
skills: mapShellSkills(env2.skills)
};
}
return {
type: "local",
skills: environment.skills
};
}
function mapShellSkills(skills) {
return skills == null ? void 0 : skills.map((skill) => skill.type === "skillReference" ? {
type: "skill_reference",
skill_id: skill.skillId,
version: skill.version
} : {
type: "inline",
name: skill.name,
description: skill.description,
source: {
type: "base64",
media_type: skill.source.mediaType,
data: skill.source.data
}
});
}
function extractApprovalRequestIdToToolCallIdMapping(prompt) {
var _a2, _b;
const mapping = {};
for (const message of prompt) {
if (message.role !== "assistant") continue;
for (const part of message.content) {
if (part.type !== "tool-call") continue;
const approvalRequestId = (_b = (_a2 = part.providerOptions) == null ? void 0 : _a2.openai) == null ? void 0 : _b.approvalRequestId;
if (approvalRequestId != null) mapping[approvalRequestId] = part.toolCallId;
}
}
return mapping;
}
function getConfigurationUpdateUnsupportedReason({ modelCapabilities, options }) {
if (!modelCapabilities.supportsConfigurationUpdate) return "reasoningEffortUpdate is only supported by GPT-6 and later models";
if ((options == null ? void 0 : options.reasoningMode) === "pro" || (options == null ? void 0 : options.truncation) === "auto") return "reasoningEffortUpdate requires standard reasoning mode without automatic truncation";
}
var OpenAIResponsesLanguageModel = class {
constructor(modelId, config) {
this.specificationVersion = "v3";
this.supportedUrls = {
"image/*": [/^https?:\/\/.*$/],
"application/pdf": [/^https?:\/\/.*$/]
};
this.modelId = modelId;
this.config = config;
}
get provider() {
return this.config.provider;
}
async getArgs({ maxOutputTokens, temperature, stopSequences, topP, topK, presencePenalty, frequencyPenalty, seed, prompt, providerOptions, tools, toolChoice, responseFormat }) {
var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
const warnings = [];
const modelCapabilities = getOpenAILanguageModelCapabilities(this.modelId);
if (topK != null) warnings.push({
type: "unsupported",
feature: "topK"
});
if (seed != null) warnings.push({
type: "unsupported",
feature: "seed"
});
if (presencePenalty != null) warnings.push({
type: "unsupported",
feature: "presencePenalty"
});
if (frequencyPenalty != null) warnings.push({
type: "unsupported",
feature: "frequencyPenalty"
});
if (stopSequences != null) warnings.push({
type: "unsupported",
feature: "stopSequences"
});
const providerOptionsName = this.config.provider.includes("azure") ? "azure" : "openai";
let openaiOptions = await parseProviderOptions$1({
provider: providerOptionsName,
providerOptions,
schema: openaiLanguageModelResponsesOptionsSchema
});
if (openaiOptions == null && providerOptionsName !== "openai") openaiOptions = await parseProviderOptions$1({
provider: "openai",
providerOptions,
schema: openaiLanguageModelResponsesOptionsSchema
});
const isReasoningModel = (_a2 = openaiOptions == null ? void 0 : openaiOptions.forceReasoning) != null ? _a2 : modelCapabilities.isReasoningModel;
let resolvedReasoningEffort = openaiOptions == null ? void 0 : openaiOptions.reasoningEffort;
if (resolvedReasoningEffort != null && modelCapabilities.supportedReasoningEfforts != null && !modelCapabilities.supportedReasoningEfforts.includes(resolvedReasoningEffort)) {
warnings.push({
type: "unsupported",
feature: "reasoningEffort",
details: `${this.modelId} only supports the following reasoning efforts: ${modelCapabilities.supportedReasoningEfforts.join(", ")}`
});
resolvedReasoningEffort = void 0;
}
if ((openaiOptions == null ? void 0 : openaiOptions.conversation) && (openaiOptions == null ? void 0 : openaiOptions.previousResponseId)) warnings.push({
type: "unsupported",
feature: "conversation",
details: "conversation and previousResponseId cannot be used together"
});
const toolNameMapping = createToolNameMapping({
tools,
providerToolNames: {
"openai.code_interpreter": "code_interpreter",
"openai.file_search": "file_search",
"openai.image_generation": "image_generation",
"openai.local_shell": "local_shell",
"openai.shell": "shell",
"openai.web_search": "web_search",
"openai.web_search_preview": "web_search_preview",
"openai.mcp": "mcp",
"openai.apply_patch": "apply_patch",
"openai.tool_search": "tool_search"
},
resolveProviderToolName: (tool) => tool.id === "openai.custom" ? tool.args.name : void 0
});
const customProviderToolNames = /* @__PURE__ */ new Set();
const { tools: openaiTools2, toolChoice: openaiToolChoice, toolWarnings } = await prepareResponsesTools$1({
tools,
toolChoice,
allowedTools: (_b = openaiOptions == null ? void 0 : openaiOptions.allowedTools) != null ? _b : void 0,
toolNameMapping,
customProviderToolNames,
supportsAsyncToolCalling: modelCapabilities.supportsAsyncToolCalling,
providerOptionsName
});
const configurationUpdateUnsupportedReason = getConfigurationUpdateUnsupportedReason({
modelCapabilities,
options: openaiOptions
});
const { input, warnings: inputWarnings } = await convertToOpenAIResponsesInput({
prompt,
configurationUpdateUnsupportedReason,
toolNameMapping,
systemMessageMode: (_c = openaiOptions == null ? void 0 : openaiOptions.systemMessageMode) != null ? _c : isReasoningModel ? "developer" : modelCapabilities.systemMessageMode,
providerOptionsName,
explicitMessageItemType: this.config.explicitMessageItemType,
fileIdPrefixes: this.config.fileIdPrefixes,
passThroughUnsupportedFiles: (_d = openaiOptions == null ? void 0 : openaiOptions.passThroughUnsupportedFiles) != null ? _d : false,
store: (_e = openaiOptions == null ? void 0 : openaiOptions.store) != null ? _e : true,
isReasoningModel,
hasConversation: (openaiOptions == null ? void 0 : openaiOptions.conversation) != null,
hasPreviousResponseId: (openaiOptions == null ? void 0 : openaiOptions.previousResponseId) != null,
hasLocalShellTool: hasOpenAITool("openai.local_shell"),
hasShellTool: hasOpenAITool("openai.shell"),
hasApplyPatchTool: hasOpenAITool("openai.apply_patch"),
toolSearchToolName: getOpenAIToolName("openai.tool_search"),
customProviderToolNames: customProviderToolNames.size > 0 ? customProviderToolNames : void 0
});
warnings.push(...inputWarnings);
const reasoningEffortUpdate = openaiOptions == null ? void 0 : openaiOptions.reasoningEffortUpdate;
if (reasoningEffortUpdate != null && configurationUpdateUnsupportedReason != null) warnings.push({
type: "unsupported",
feature: "reasoningEffortUpdate",
details: configurationUpdateUnsupportedReason
});
else if (reasoningEffortUpdate != null) {
const firstItem = input[0];
if ((firstItem == null ? void 0 : firstItem.type) !== "configuration_update" || firstItem.reasoning.effort !== reasoningEffortUpdate) input.unshift({
type: "configuration_update",
reasoning: { effort: reasoningEffortUpdate }
});
}
for (let i = 1; i < input.length; i++) if (input[i - 1].type === "configuration_update" && input[i].type === "configuration_update") throw new UnsupportedFunctionalityError$2({ functionality: "Adjacent reasoning effort configuration updates" });
const strictJsonSchema = (_f = openaiOptions == null ? void 0 : openaiOptions.strictJsonSchema) != null ? _f : true;
let include = openaiOptions == null ? void 0 : openaiOptions.include;
function addInclude(key) {
if (include == null) include = [key];
else if (!include.includes(key)) include = [...include, key];
}
function getOpenAIToolName(id) {
var _a3;
return (_a3 = tools == null ? void 0 : tools.find((tool) => tool.type === "provider" && tool.id === id)) == null ? void 0 : _a3.name;
}
function hasOpenAITool(id) {
return getOpenAIToolName(id) != null;
}
const topLogprobs = typeof (openaiOptions == null ? void 0 : openaiOptions.logprobs) === "number" ? openaiOptions == null ? void 0 : openaiOptions.logprobs : (openaiOptions == null ? void 0 : openaiOptions.logprobs) === true ? TOP_LOGPROBS_MAX : void 0;
if (topLogprobs) addInclude("message.output_text.logprobs");
const webSearchToolName = (_g = tools == null ? void 0 : tools.find((tool) => tool.type === "provider" && (tool.id === "openai.web_search" || tool.id === "openai.web_search_preview"))) == null ? void 0 : _g.name;
if (webSearchToolName) addInclude("web_search_call.action.sources");
if (hasOpenAITool("openai.code_interpreter")) addInclude("code_interpreter_call.outputs");
const store = openaiOptions == null ? void 0 : openaiOptions.store;
if (store === false && isReasoningModel) addInclude("reasoning.encrypted_content");
const baseArgs = {
model: this.modelId,
input,
temperature,
top_p: topP,
max_output_tokens: maxOutputTokens,
...((responseFormat == null ? void 0 : responseFormat.type) === "json" || (openaiOptions == null ? void 0 : openaiOptions.textVerbosity)) && { text: {
...(responseFormat == null ? void 0 : responseFormat.type) === "json" && { format: responseFormat.schema != null ? {
type: "json_schema",
strict: strictJsonSchema,
name: (_h = responseFormat.name) != null ? _h : "response",
description: responseFormat.description,
schema: normalizeOpenAIJsonSchema(responseFormat.schema)
} : { type: "json_object" } },
...(openaiOptions == null ? void 0 : openaiOptions.textVerbosity) && { verbosity: openaiOptions.textVerbosity }
} },
conversation: openaiOptions == null ? void 0 : openaiOptions.conversation,
max_tool_calls: openaiOptions == null ? void 0 : openaiOptions.maxToolCalls,
metadata: openaiOptions == null ? void 0 : openaiOptions.metadata,
parallel_tool_calls: openaiOptions == null ? void 0 : openaiOptions.parallelToolCalls,
previous_response_id: openaiOptions == null ? void 0 : openaiOptions.previousResponseId,
store,
user: openaiOptions == null ? void 0 : openaiOptions.user,
instructions: openaiOptions == null ? void 0 : openaiOptions.instructions,
service_tier: openaiOptions == null ? void 0 : openaiOptions.serviceTier,
include,
prompt_cache_key: openaiOptions == null ? void 0 : openaiOptions.promptCacheKey,
prompt_cache_options: openaiOptions == null ? void 0 : openaiOptions.promptCacheOptions,
prompt_cache_retention: openaiOptions == null ? void 0 : openaiOptions.promptCacheRetention,
safety_identifier: openaiOptions == null ? void 0 : openaiOptions.safetyIdentifier,
top_logprobs: topLogprobs,
truncation: openaiOptions == null ? void 0 : openaiOptions.truncation,
...isReasoningModel && (resolvedReasoningEffort != null || (openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null || (openaiOptions == null ? void 0 : openaiOptions.reasoningMode) != null || (openaiOptions == null ? void 0 : openaiOptions.reasoningContext) != null) && { reasoning: {
...resolvedReasoningEffort != null && { effort: resolvedReasoningEffort },
...(openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null && { summary: openaiOptions.reasoningSummary },
...(openaiOptions == null ? void 0 : openaiOptions.reasoningMode) != null && { mode: openaiOptions.reasoningMode },
...(openaiOptions == null ? void 0 : openaiOptions.reasoningContext) != null && { context: openaiOptions.reasoningContext }
} }
};
if (modelCapabilities.supportsConfigurationUpdate && baseArgs.prompt_cache_retention != null) {
baseArgs.prompt_cache_retention = void 0;
warnings.push({
type: "unsupported",
feature: "promptCacheRetention",
details: "promptCacheRetention is not supported by GPT-6 and later models; use promptCacheOptions instead"
});
}
if (isReasoningModel) {
if (!((openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) === "none" && modelCapabilities.supportsNonReasoningParameters)) {
if (baseArgs.temperature != null) {
baseArgs.temperature = void 0;
warnings.push({
type: "unsupported",
feature: "temperature",
details: "temperature is not supported for reasoning models"
});
}
if (baseArgs.top_p != null) {
baseArgs.top_p = void 0;
warnings.push({
type: "unsupported",
feature: "topP",
details: "topP is not supported for reasoning models"
});
}
}
if (modelCapabilities.supportedReasoningEfforts != null && (baseArgs.top_logprobs != null || ((_i = baseArgs.include) == null ? void 0 : _i.includes("message.output_text.logprobs")))) {
baseArgs.top_logprobs = void 0;
const filteredInclude = (_j = baseArgs.include) == null ? void 0 : _j.filter((value) => value !== "message.output_text.logprobs");
baseArgs.include = filteredInclude != null && filteredInclude.length > 0 ? filteredInclude : void 0;
warnings.push({
type: "unsupported",
feature: "logprobs",
details: "logprobs is not supported for reasoning models"
});
}
} else {
if ((openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) != null) warnings.push({
type: "unsupported",
feature: "reasoningEffort",
details: "reasoningEffort is not supported for non-reasoning models"
});
if ((openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null) warnings.push({
type: "unsupported",
feature: "reasoningSummary",
details: "reasoningSummary is not supported for non-reasoning models"
});
if ((openaiOptions == null ? void 0 : openaiOptions.reasoningMode) != null) warnings.push({
type: "unsupported",
feature: "reasoningMode",
details: "reasoningMode is not supported for non-reasoning models"
});
if ((openaiOptions == null ? void 0 : openaiOptions.reasoningContext) != null) warnings.push({
type: "unsupported",
feature: "reasoningContext",
details: "reasoningContext is not supported for non-reasoning models"
});
}
if ((openaiOptions == null ? void 0 : openaiOptions.serviceTier) === "flex" && !modelCapabilities.supportsFlexProcessing) {
warnings.push({
type: "unsupported",
feature: "serviceTier",
details: "flex processing is only available for o3, o4-mini, and gpt-5 models"
});
delete baseArgs.service_tier;
}
if (((openaiOptions == null ? void 0 : openaiOptions.serviceTier) === "priority" || (openaiOptions == null ? void 0 : openaiOptions.serviceTier) === "fast") && !modelCapabilities.supportsPriorityProcessing) {
warnings.push({
type: "unsupported",
feature: "serviceTier",
details: "priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"
});
delete baseArgs.service_tier;
}
const shellToolEnvType = (_m = (_l = (_k = tools == null ? void 0 : tools.find((tool) => tool.type === "provider" && tool.id === "openai.shell")) == null ? void 0 : _k.args) == null ? void 0 : _l.environment) == null ? void 0 : _m.type;
const isShellProviderExecuted = shellToolEnvType === "containerAuto" || shellToolEnvType === "containerReference";
return {
webSearchToolName,
args: {
...baseArgs,
tools: openaiTools2,
tool_choice: openaiToolChoice
},
warnings: [...warnings, ...toolWarnings],
store,
toolNameMapping,
providerOptionsName,
isShellProviderExecuted
};
}
async doGenerate(options) {
var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E;
const { args: body, warnings, webSearchToolName, toolNameMapping, providerOptionsName, isShellProviderExecuted } = await this.getArgs(options);
const url = this.config.url({
path: "/responses",
modelId: this.modelId
});
const approvalRequestIdToDummyToolCallIdFromPrompt = extractApprovalRequestIdToToolCallIdMapping(options.prompt);
const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi$2({
url,
headers: combineHeaders$2(this.config.headers(), options.headers),
body,
failedResponseHandler: openaiFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$2(openaiResponsesResponseSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
if (response.error) throw new APICallError$2({
message: response.error.message,
url,
requestBodyValues: body,
statusCode: 400,
responseHeaders,
responseBody: rawResponse,
isRetryable: false
});
const content = [];
const logprobs = [];
const functionTools = (_b = (_a2 = options.tools) == null ? void 0 : _a2.filter((tool) => tool.type === "function")) != null ? _b : [];
let hasFunctionCall = false;
const hostedToolSearchCallIds = [];
for (const part of response.output) switch (part.type) {
case "reasoning":
if (part.summary.length === 0) part.summary.push({
type: "summary_text",
text: ""
});
for (const summary of part.summary) content.push({
type: "reasoning",
text: summary.text,
providerMetadata: { [providerOptionsName]: {
itemId: part.id,
reasoningEncryptedContent: (_c = part.encrypted_content) != null ? _c : null
} }
});
break;
case "image_generation_call":
content.push({
type: "tool-call",
toolCallId: part.id,
toolName: toolNameMapping.toCustomToolName("image_generation"),
input: "{}",
providerExecuted: true
});
content.push({
type: "tool-result",
toolCallId: part.id,
toolName: toolNameMapping.toCustomToolName("image_generation"),
result: { result: part.result }
});
break;
case "tool_search_call": {
const toolCallId = (_d = part.call_id) != null ? _d : part.id;
const isHosted = part.execution === "server";
if (isHosted) hostedToolSearchCallIds.push(toolCallId);
content.push({
type: "tool-call",
toolCallId,
toolName: toolNameMapping.toCustomToolName("tool_search"),
input: JSON.stringify({
arguments: part.arguments,
call_id: part.call_id
}),
...isHosted ? { providerExecuted: true } : {},
providerMetadata: { [providerOptionsName]: { itemId: part.id } }
});
break;
}
case "tool_search_output": {
const toolCallId = (_f = (_e = part.call_id) != null ? _e : hostedToolSearchCallIds.shift()) != null ? _f : part.id;
content.push({
type: "tool-result",
toolCallId,
toolName: toolNameMapping.toCustomToolName("tool_search"),
result: { tools: part.tools },
providerMetadata: { [providerOptionsName]: { itemId: part.id } }
});
break;
}
case "local_shell_call":
content.push({
type: "tool-call",
toolCallId: part.call_id,
toolName: toolNameMapping.toCustomToolName("local_shell"),
input: JSON.stringify({ action: part.action }),
providerMetadata: { [providerOptionsName]: { itemId: part.id } }
});
break;
case "shell_call":
content.push({
type: "tool-call",
toolCallId: part.call_id,
toolName: toolNameMapping.toCustomToolName("shell"),
input: JSON.stringify({ action: { commands: part.action.commands } }),
...isShellProviderExecuted && { providerExecuted: true },
providerMetadata: { [providerOptionsName]: { itemId: part.id } }
});
break;
case "shell_call_output":
content.push({
type: "tool-result",
toolCallId: part.call_id,
toolName: toolNameMapping.toCustomToolName("shell"),
result: { output: part.output.map((item) => ({
stdout: item.stdout,
stderr: item.stderr,
outcome: item.outcome.type === "exit" ? {
type: "exit",
exitCode: item.outcome.exit_code
} : { type: "timeout" }
})) }
});
break;
case "message":
for (const contentPart of part.content) {
if (((_h = (_g = options.providerOptions) == null ? void 0 : _g[providerOptionsName]) == null ? void 0 : _h.logprobs) && contentPart.logprobs) logprobs.push(contentPart.logprobs);
const providerMetadata2 = {
itemId: part.id,
...part.phase != null && { phase: part.phase },
...contentPart.annotations.length > 0 && { annotations: contentPart.annotations }
};
content.push({
type: "text",
text: contentPart.text,
providerMetadata: { [providerOptionsName]: providerMetadata2 }
});
for (const annotation of contentPart.annotations) if (annotation.type === "url_citation") content.push({
type: "source",
sourceType: "url",
id: (_k = (_j = (_i = this.config).generateId) == null ? void 0 : _j.call(_i)) != null ? _k : generateId$2(),
url: annotation.url,
title: annotation.title
});
else if (annotation.type === "file_citation") content.push({
type: "source",
sourceType: "document",
id: (_n = (_m = (_l = this.config).generateId) == null ? void 0 : _m.call(_l)) != null ? _n : generateId$2(),
mediaType: "text/plain",
title: annotation.filename,
filename: annotation.filename,
providerMetadata: { [providerOptionsName]: {
type: annotation.type,
fileId: annotation.file_id,
index: annotation.index
} }
});
else if (annotation.type === "container_file_citation") content.push({
type: "source",
sourceType: "document",
id: (_q = (_p = (_o = this.config).generateId) == null ? void 0 : _p.call(_o)) != null ? _q : generateId$2(),
mediaType: "text/plain",
title: annotation.filename,
filename: annotation.filename,
providerMetadata: { [providerOptionsName]: {
type: annotation.type,
fileId: annotation.file_id,
containerId: annotation.container_id
} }
});
else if (annotation.type === "file_path") content.push({
type: "source",
sourceType: "document",
id: (_t = (_s = (_r = this.config).generateId) == null ? void 0 : _s.call(_r)) != null ? _t : generateId$2(),
mediaType: "application/octet-stream",
title: annotation.file_id,
filename: annotation.file_id,
providerMetadata: { [providerOptionsName]: {
type: annotation.type,
fileId: annotation.file_id,
index: annotation.index
} }
});
}
break;
case "function_call": {
hasFunctionCall = true;
const expandedToolCalls = await expandParallelToolCall({
toolCall: {
toolCallId: part.call_id,
toolName: part.name,
input: part.arguments
},
tools: functionTools,
providerOptionsName,
itemId: part.id
});
if (expandedToolCalls != null) {
content.push(...expandedToolCalls);
break;
}
content.push({
type: "tool-call",
toolCallId: part.call_id,
toolName: part.name,
input: part.arguments,
providerMetadata: { [providerOptionsName]: {
itemId: part.id,
...part.async != null && { async: part.async },
...part.namespace != null && { namespace: part.namespace }
} }
});
break;
}
case "custom_tool_call": {
hasFunctionCall = true;
const toolName = toolNameMapping.toCustomToolName(part.name);
content.push({
type: "tool-call",
toolCallId: part.call_id,
toolName,
input: JSON.stringify(part.input),
providerMetadata: { [providerOptionsName]: {
itemId: part.id,
...part.async != null && { async: part.async }
} }
});
break;
}
case "web_search_call":
content.push({
type: "tool-call",
toolCallId: part.id,
toolName: toolNameMapping.toCustomToolName(webSearchToolName != null ? webSearchToolName : "web_search"),
input: JSON.stringify({}),
providerExecuted: true
});
content.push({
type: "tool-result",
toolCallId: part.id,
toolName: toolNameMapping.toCustomToolName(webSearchToolName != null ? webSearchToolName : "web_search"),
...mapWebSearchResult(part)
});
break;
case "mcp_call": {
const toolCallId = part.approval_request_id != null ? (_u = approvalRequestIdToDummyToolCallIdFromPrompt[part.approval_request_id]) != null ? _u : part.id : part.id;
const toolName = `mcp.${part.name}`;
content.push({
type: "tool-call",
toolCallId,
toolName,
input: part.arguments,
providerExecuted: true,
dynamic: true
});
content.push({
type: "tool-result",
toolCallId,
toolName,
result: {
type: "call",
serverLabel: part.server_label,
name: part.name,
arguments: part.arguments,
...part.output != null ? { output: part.output } : {},
...part.error != null ? { error: part.error } : {}
},
providerMetadata: { [providerOptionsName]: { itemId: part.id } }
});
break;
}
case "mcp_list_tools": break;
case "mcp_approval_request": {
const approvalRequestId = (_v = part.approval_request_id) != null ? _v : part.id;
const dummyToolCallId = (_y = (_x = (_w = this.config).generateId) == null ? void 0 : _x.call(_w)) != null ? _y : generateId$2();
const toolName = `mcp.${part.name}`;
content.push({
type: "tool-call",
toolCallId: dummyToolCallId,
toolName,
input: part.arguments,
providerExecuted: true,
dynamic: true
});
content.push({
type: "tool-approval-request",
approvalId: approvalRequestId,
toolCallId: dummyToolCallId
});
break;
}
case "computer_call":
content.push({
type: "tool-call",
toolCallId: part.id,
toolName: toolNameMapping.toCustomToolName("computer_use"),
input: "",
providerExecuted: true
});
content.push({
type: "tool-result",
toolCallId: part.id,
toolName: toolNameMapping.toCustomToolName("computer_use"),
result: {
type: "computer_use_tool_result",
status: part.status || "completed"
}
});
break;
case "file_search_call":
content.push({
type: "tool-call",
toolCallId: part.id,
toolName: toolNameMapping.toCustomToolName("file_search"),
input: "{}",
providerExecuted: true
});
content.push({
type: "tool-result",
toolCallId: part.id,
toolName: toolNameMapping.toCustomToolName("file_search"),
result: {
queries: part.queries,
results: (_A = (_z = part.results) == null ? void 0 : _z.map((result) => ({
attributes: result.attributes,
fileId: result.file_id,
filename: result.filename,
score: result.score,
text: result.text
}))) != null ? _A : null
}
});
break;
case "code_interpreter_call":
content.push({
type: "tool-call",
toolCallId: part.id,
toolName: toolNameMapping.toCustomToolName("code_interpreter"),
input: JSON.stringify({
code: part.code,
containerId: part.container_id
}),
providerExecuted: true
});
content.push({
type: "tool-result",
toolCallId: part.id,
toolName: toolNameMapping.toCustomToolName("code_interpreter"),
result: { outputs: part.outputs }
});
break;
case "apply_patch_call":
hasFunctionCall = true;
content.push({
type: "tool-call",
toolCallId: part.call_id,
toolName: toolNameMapping.toCustomToolName("apply_patch"),
input: JSON.stringify({
callId: part.call_id,
operation: part.operation
}),
providerMetadata: { [providerOptionsName]: { itemId: part.id } }
});
}
const providerMetadata = { [providerOptionsName]: {
responseId: response.id,
...logprobs.length > 0 ? { logprobs } : {},
...typeof response.service_tier === "string" ? { serviceTier: response.service_tier } : {},
...((_B = response.reasoning) == null ? void 0 : _B.context) != null ? { reasoningContext: response.reasoning.context } : {}
} };
const usage = response.usage;
return {
content,
finishReason: {
unified: mapOpenAIResponseFinishReason({
finishReason: (_C = response.incomplete_details) == null ? void 0 : _C.reason,
hasFunctionCall
}),
raw: (_E = (_D = response.incomplete_details) == null ? void 0 : _D.reason) != null ? _E : void 0
},
usage: convertOpenAIResponsesUsage(usage),
request: { body },
response: {
id: response.id,
timestamp: /* @__PURE__ */ new Date(response.created_at * 1e3),
modelId: response.model,
headers: responseHeaders,
body: rawResponse
},
providerMetadata,
warnings
};
}
async doStream(options) {
var _a2, _b;
const { args: body, warnings, webSearchToolName, toolNameMapping, store, providerOptionsName, isShellProviderExecuted } = await this.getArgs(options);
const url = this.config.url({
path: "/responses",
modelId: this.modelId
});
const { responseHeaders, value: response } = await postJsonToApi$2({
url,
headers: combineHeaders$2(this.config.headers(), options.headers),
body: {
...body,
stream: true
},
failedResponseHandler: openaiFailedResponseHandler,
successfulResponseHandler: createEventSourceResponseHandler$2(openaiResponsesChunkSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const checkedResponse = await throwIfOpenAIStreamErrorBeforeOutput({
stream: response,
getError: (chunk) => isErrorChunk(chunk) || isResponseFailedChunk(chunk) && chunk.response.error != null ? chunk : void 0,
isOutputChunk: isResponseOutputChunk,
url,
requestBodyValues: body,
responseHeaders
});
const self = this;
const approvalRequestIdToDummyToolCallIdFromPrompt = extractApprovalRequestIdToToolCallIdMapping(options.prompt);
const functionTools = (_b = (_a2 = options.tools) == null ? void 0 : _a2.filter((tool) => tool.type === "function")) != null ? _b : [];
const approvalRequestIdToDummyToolCallIdFromStream = /* @__PURE__ */ new Map();
let finishReason = {
unified: "other",
raw: void 0
};
let usage = void 0;
const logprobs = [];
let responseId = null;
const ongoingToolCalls = {};
const ongoingAnnotations = [];
let activeMessagePhase;
let hasFunctionCall = false;
const activeReasoning = {};
let serviceTier;
let reasoningContext;
const hostedToolSearchCallIds = [];
let encounteredStreamError = false;
return {
stream: checkedResponse.pipeThrough(new TransformStream({
start(controller) {
controller.enqueue({
type: "stream-start",
warnings
});
},
transform(chunk, controller) {
var _a3, _b2, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P, _Q, _R, _S;
if (options.includeRawChunks) controller.enqueue({
type: "raw",
rawValue: chunk.rawValue
});
if (!chunk.success) {
const error = isOpenAIChatCompletionChunk(chunk.rawValue) ? createOpenAIResponsesChatCompletionsMismatchError({
value: chunk.rawValue,
cause: chunk.error,
url,
requestBodyValues: body,
responseHeaders
}) : chunk.error;
encounteredStreamError = true;
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error
});
return;
}
const value = chunk.value;
if (isResponseOutputItemAddedChunk(value)) {
if (value.item.type === "function_call") {
const suppressInputStreaming = isUndeclaredParallelToolCall({
toolName: value.item.name,
tools: functionTools
});
ongoingToolCalls[value.output_index] = {
toolName: value.item.name,
toolCallId: value.item.call_id,
suppressInputStreaming,
bufferedInputDeltas: suppressInputStreaming ? [] : void 0,
async: value.item.async
};
if (!suppressInputStreaming) controller.enqueue({
type: "tool-input-start",
id: value.item.call_id,
toolName: value.item.name
});
} else if (value.item.type === "custom_tool_call") {
const toolName = toolNameMapping.toCustomToolName(value.item.name);
ongoingToolCalls[value.output_index] = {
toolName,
toolCallId: value.item.call_id,
async: value.item.async
};
controller.enqueue({
type: "tool-input-start",
id: value.item.call_id,
toolName,
inputEncoding: "text"
});
} else if (value.item.type === "web_search_call") {
ongoingToolCalls[value.output_index] = {
toolName: toolNameMapping.toCustomToolName(webSearchToolName != null ? webSearchToolName : "web_search"),
toolCallId: value.item.id
};
controller.enqueue({
type: "tool-input-start",
id: value.item.id,
toolName: toolNameMapping.toCustomToolName(webSearchToolName != null ? webSearchToolName : "web_search"),
providerExecuted: true
});
controller.enqueue({
type: "tool-input-end",
id: value.item.id
});
controller.enqueue({
type: "tool-call",
toolCallId: value.item.id,
toolName: toolNameMapping.toCustomToolName(webSearchToolName != null ? webSearchToolName : "web_search"),
input: JSON.stringify({}),
providerExecuted: true
});
} else if (value.item.type === "computer_call") {
ongoingToolCalls[value.output_index] = {
toolName: toolNameMapping.toCustomToolName("computer_use"),
toolCallId: value.item.id
};
controller.enqueue({
type: "tool-input-start",
id: value.item.id,
toolName: toolNameMapping.toCustomToolName("computer_use"),
providerExecuted: true
});
} else if (value.item.type === "code_interpreter_call") {
ongoingToolCalls[value.output_index] = {
toolName: toolNameMapping.toCustomToolName("code_interpreter"),
toolCallId: value.item.id,
codeInterpreter: { containerId: value.item.container_id }
};
controller.enqueue({
type: "tool-input-start",
id: value.item.id,
toolName: toolNameMapping.toCustomToolName("code_interpreter"),
providerExecuted: true
});
controller.enqueue({
type: "tool-input-delta",
id: value.item.id,
delta: `{"containerId":"${value.item.container_id}","code":"`
});
} else if (value.item.type === "file_search_call") controller.enqueue({
type: "tool-call",
toolCallId: value.item.id,
toolName: toolNameMapping.toCustomToolName("file_search"),
input: "{}",
providerExecuted: true
});
else if (value.item.type === "image_generation_call") controller.enqueue({
type: "tool-call",
toolCallId: value.item.id,
toolName: toolNameMapping.toCustomToolName("image_generation"),
input: "{}",
providerExecuted: true
});
else if (value.item.type === "tool_search_call") {
const toolCallId = value.item.id;
const toolName = toolNameMapping.toCustomToolName("tool_search");
const isHosted = value.item.execution === "server";
ongoingToolCalls[value.output_index] = {
toolName,
toolCallId,
toolSearchExecution: (_a3 = value.item.execution) != null ? _a3 : "server"
};
if (isHosted) controller.enqueue({
type: "tool-input-start",
id: toolCallId,
toolName,
providerExecuted: true
});
} else if (value.item.type === "tool_search_output") {} else if (value.item.type === "mcp_call" || value.item.type === "mcp_list_tools" || value.item.type === "mcp_approval_request") {} else if (value.item.type === "apply_patch_call") {
const { call_id: callId, operation } = value.item;
ongoingToolCalls[value.output_index] = {
toolName: toolNameMapping.toCustomToolName("apply_patch"),
toolCallId: callId,
applyPatch: {
hasDiff: operation.type === "delete_file",
endEmitted: operation.type === "delete_file"
}
};
controller.enqueue({
type: "tool-input-start",
id: callId,
toolName: toolNameMapping.toCustomToolName("apply_patch")
});
if (operation.type === "delete_file") {
const inputString = JSON.stringify({
callId,
operation
});
controller.enqueue({
type: "tool-input-delta",
id: callId,
delta: inputString
});
controller.enqueue({
type: "tool-input-end",
id: callId
});
} else controller.enqueue({
type: "tool-input-delta",
id: callId,
delta: `{"callId":"${escapeJSONDelta(callId)}","operation":{"type":"${escapeJSONDelta(operation.type)}","path":"${escapeJSONDelta(operation.path)}","diff":"`
});
} else if (value.item.type === "shell_call") ongoingToolCalls[value.output_index] = {
toolName: toolNameMapping.toCustomToolName("shell"),
toolCallId: value.item.call_id
};
else if (value.item.type === "shell_call_output") {} else if (value.item.type === "message") {
ongoingAnnotations.splice(0);
activeMessagePhase = (_b2 = value.item.phase) != null ? _b2 : void 0;
controller.enqueue({
type: "text-start",
id: value.item.id,
providerMetadata: { [providerOptionsName]: {
itemId: value.item.id,
...value.item.phase != null && { phase: value.item.phase }
} }
});
} else if (isResponseOutputItemAddedChunk(value) && value.item.type === "reasoning") {
activeReasoning[value.item.id] = {
encryptedContent: value.item.encrypted_content,
summaryParts: { 0: "active" }
};
controller.enqueue({
type: "reasoning-start",
id: `${value.item.id}:0`,
providerMetadata: { [providerOptionsName]: {
itemId: value.item.id,
reasoningEncryptedContent: (_c = value.item.encrypted_content) != null ? _c : null
} }
});
}
} else if (isResponseOutputItemDoneChunk(value)) {
if (value.item.type === "message") {
const phase = (_d = value.item.phase) != null ? _d : activeMessagePhase;
activeMessagePhase = void 0;
controller.enqueue({
type: "text-end",
id: value.item.id,
providerMetadata: { [providerOptionsName]: {
itemId: value.item.id,
...phase != null && { phase },
...ongoingAnnotations.length > 0 && { annotations: ongoingAnnotations }
} }
});
} else if (value.item.type === "function_call") {
const item = value.item;
const ongoingToolCall = ongoingToolCalls[value.output_index];
ongoingToolCalls[value.output_index] = void 0;
hasFunctionCall = true;
const suppressInputStreaming = (_e = ongoingToolCall == null ? void 0 : ongoingToolCall.suppressInputStreaming) != null ? _e : isUndeclaredParallelToolCall({
toolName: item.name,
tools: functionTools
});
const enqueueUnexpandedToolCall = () => {
var _a4;
if (suppressInputStreaming) {
controller.enqueue({
type: "tool-input-start",
id: item.call_id,
toolName: item.name
});
const bufferedInputDeltas = (_a4 = ongoingToolCall == null ? void 0 : ongoingToolCall.bufferedInputDeltas) != null ? _a4 : [];
if (bufferedInputDeltas.length > 0) for (const delta of bufferedInputDeltas) controller.enqueue({
type: "tool-input-delta",
id: item.call_id,
delta
});
else if (item.arguments.length > 0) controller.enqueue({
type: "tool-input-delta",
id: item.call_id,
delta: item.arguments
});
}
controller.enqueue({
type: "tool-input-end",
id: item.call_id,
...item.namespace != null && { providerMetadata: { [providerOptionsName]: { namespace: item.namespace } } }
});
controller.enqueue({
type: "tool-call",
toolCallId: item.call_id,
toolName: item.name,
input: item.arguments,
providerMetadata: { [providerOptionsName]: {
itemId: item.id,
...item.async != null ? { async: item.async } : (ongoingToolCall == null ? void 0 : ongoingToolCall.async) != null ? { async: ongoingToolCall.async } : {},
...item.namespace != null && { namespace: item.namespace }
} }
});
};
if (!suppressInputStreaming) {
enqueueUnexpandedToolCall();
return;
}
return expandParallelToolCall({
toolCall: {
toolCallId: item.call_id,
toolName: item.name,
input: item.arguments
},
tools: functionTools,
providerOptionsName,
itemId: item.id
}).then((expandedToolCalls) => {
if (expandedToolCalls == null) {
enqueueUnexpandedToolCall();
return;
}
for (const toolCall of expandedToolCalls) {
controller.enqueue({
type: "tool-input-start",
id: toolCall.toolCallId,
toolName: toolCall.toolName
});
controller.enqueue({
type: "tool-input-delta",
id: toolCall.toolCallId,
delta: toolCall.input
});
controller.enqueue({
type: "tool-input-end",
id: toolCall.toolCallId
});
controller.enqueue(toolCall);
}
});
} else if (value.item.type === "custom_tool_call") {
const ongoingToolCall = ongoingToolCalls[value.output_index];
ongoingToolCalls[value.output_index] = void 0;
hasFunctionCall = true;
const toolName = toolNameMapping.toCustomToolName(value.item.name);
controller.enqueue({
type: "tool-input-end",
id: value.item.call_id
});
controller.enqueue({
type: "tool-call",
toolCallId: value.item.call_id,
toolName,
input: JSON.stringify(value.item.input),
providerMetadata: { [providerOptionsName]: {
itemId: value.item.id,
...value.item.async != null ? { async: value.item.async } : (ongoingToolCall == null ? void 0 : ongoingToolCall.async) != null ? { async: ongoingToolCall.async } : {}
} }
});
} else if (value.item.type === "web_search_call") {
ongoingToolCalls[value.output_index] = void 0;
controller.enqueue({
type: "tool-result",
toolCallId: value.item.id,
toolName: toolNameMapping.toCustomToolName(webSearchToolName != null ? webSearchToolName : "web_search"),
...mapWebSearchResult(value.item)
});
} else if (value.item.type === "computer_call") {
ongoingToolCalls[value.output_index] = void 0;
controller.enqueue({
type: "tool-input-end",
id: value.item.id
});
controller.enqueue({
type: "tool-call",
toolCallId: value.item.id,
toolName: toolNameMapping.toCustomToolName("computer_use"),
input: "",
providerExecuted: true
});
controller.enqueue({
type: "tool-result",
toolCallId: value.item.id,
toolName: toolNameMapping.toCustomToolName("computer_use"),
result: {
type: "computer_use_tool_result",
status: value.item.status || "completed"
}
});
} else if (value.item.type === "file_search_call") {
ongoingToolCalls[value.output_index] = void 0;
controller.enqueue({
type: "tool-result",
toolCallId: value.item.id,
toolName: toolNameMapping.toCustomToolName("file_search"),
result: {
queries: value.item.queries,
results: (_g = (_f = value.item.results) == null ? void 0 : _f.map((result2) => ({
attributes: result2.attributes,
fileId: result2.file_id,
filename: result2.filename,
score: result2.score,
text: result2.text
}))) != null ? _g : null
}
});
} else if (value.item.type === "code_interpreter_call") {
ongoingToolCalls[value.output_index] = void 0;
controller.enqueue({
type: "tool-result",
toolCallId: value.item.id,
toolName: toolNameMapping.toCustomToolName("code_interpreter"),
result: { outputs: value.item.outputs }
});
} else if (value.item.type === "image_generation_call") controller.enqueue({
type: "tool-result",
toolCallId: value.item.id,
toolName: toolNameMapping.toCustomToolName("image_generation"),
result: { result: value.item.result }
});
else if (value.item.type === "tool_search_call") {
const toolCall = ongoingToolCalls[value.output_index];
const isHosted = value.item.execution === "server";
if (toolCall != null) {
const toolCallId = isHosted ? toolCall.toolCallId : (_h = value.item.call_id) != null ? _h : value.item.id;
if (isHosted) hostedToolSearchCallIds.push(toolCallId);
else controller.enqueue({
type: "tool-input-start",
id: toolCallId,
toolName: toolCall.toolName
});
controller.enqueue({
type: "tool-input-end",
id: toolCallId
});
controller.enqueue({
type: "tool-call",
toolCallId,
toolName: toolCall.toolName,
input: JSON.stringify({
arguments: value.item.arguments,
call_id: isHosted ? null : toolCallId
}),
...isHosted ? { providerExecuted: true } : {},
providerMetadata: { [providerOptionsName]: { itemId: value.item.id } }
});
}
ongoingToolCalls[value.output_index] = void 0;
} else if (value.item.type === "tool_search_output") {
const toolCallId = (_j = (_i = value.item.call_id) != null ? _i : hostedToolSearchCallIds.shift()) != null ? _j : value.item.id;
controller.enqueue({
type: "tool-result",
toolCallId,
toolName: toolNameMapping.toCustomToolName("tool_search"),
result: { tools: value.item.tools },
providerMetadata: { [providerOptionsName]: { itemId: value.item.id } }
});
} else if (value.item.type === "mcp_call") {
ongoingToolCalls[value.output_index] = void 0;
const approvalRequestId = (_k = value.item.approval_request_id) != null ? _k : void 0;
const aliasedToolCallId = approvalRequestId != null ? (_m = (_l = approvalRequestIdToDummyToolCallIdFromStream.get(approvalRequestId)) != null ? _l : approvalRequestIdToDummyToolCallIdFromPrompt[approvalRequestId]) != null ? _m : value.item.id : value.item.id;
const toolName = `mcp.${value.item.name}`;
controller.enqueue({
type: "tool-call",
toolCallId: aliasedToolCallId,
toolName,
input: value.item.arguments,
providerExecuted: true,
dynamic: true
});
controller.enqueue({
type: "tool-result",
toolCallId: aliasedToolCallId,
toolName,
result: {
type: "call",
serverLabel: value.item.server_label,
name: value.item.name,
arguments: value.item.arguments,
...value.item.output != null ? { output: value.item.output } : {},
...value.item.error != null ? { error: value.item.error } : {}
},
providerMetadata: { [providerOptionsName]: { itemId: value.item.id } }
});
} else if (value.item.type === "mcp_list_tools") ongoingToolCalls[value.output_index] = void 0;
else if (value.item.type === "apply_patch_call") {
const toolCall = ongoingToolCalls[value.output_index];
if ((toolCall == null ? void 0 : toolCall.applyPatch) && !toolCall.applyPatch.endEmitted && value.item.operation.type !== "delete_file") {
if (!toolCall.applyPatch.hasDiff) controller.enqueue({
type: "tool-input-delta",
id: toolCall.toolCallId,
delta: escapeJSONDelta(value.item.operation.diff)
});
controller.enqueue({
type: "tool-input-delta",
id: toolCall.toolCallId,
delta: "\"}}"
});
controller.enqueue({
type: "tool-input-end",
id: toolCall.toolCallId
});
toolCall.applyPatch.endEmitted = true;
}
if (toolCall && value.item.status === "completed") {
hasFunctionCall = true;
controller.enqueue({
type: "tool-call",
toolCallId: toolCall.toolCallId,
toolName: toolNameMapping.toCustomToolName("apply_patch"),
input: JSON.stringify({
callId: value.item.call_id,
operation: value.item.operation
}),
providerMetadata: { [providerOptionsName]: { itemId: value.item.id } }
});
}
ongoingToolCalls[value.output_index] = void 0;
} else if (value.item.type === "mcp_approval_request") {
ongoingToolCalls[value.output_index] = void 0;
const dummyToolCallId = (_p = (_o = (_n = self.config).generateId) == null ? void 0 : _o.call(_n)) != null ? _p : generateId$2();
const approvalRequestId = (_q = value.item.approval_request_id) != null ? _q : value.item.id;
approvalRequestIdToDummyToolCallIdFromStream.set(approvalRequestId, dummyToolCallId);
const toolName = `mcp.${value.item.name}`;
controller.enqueue({
type: "tool-call",
toolCallId: dummyToolCallId,
toolName,
input: value.item.arguments,
providerExecuted: true,
dynamic: true
});
controller.enqueue({
type: "tool-approval-request",
approvalId: approvalRequestId,
toolCallId: dummyToolCallId
});
} else if (value.item.type === "local_shell_call") {
ongoingToolCalls[value.output_index] = void 0;
controller.enqueue({
type: "tool-call",
toolCallId: value.item.call_id,
toolName: toolNameMapping.toCustomToolName("local_shell"),
input: JSON.stringify({ action: {
type: "exec",
command: value.item.action.command,
timeoutMs: value.item.action.timeout_ms,
user: value.item.action.user,
workingDirectory: value.item.action.working_directory,
env: value.item.action.env
} }),
providerMetadata: { [providerOptionsName]: { itemId: value.item.id } }
});
} else if (value.item.type === "shell_call") {
ongoingToolCalls[value.output_index] = void 0;
controller.enqueue({
type: "tool-call",
toolCallId: value.item.call_id,
toolName: toolNameMapping.toCustomToolName("shell"),
input: JSON.stringify({ action: { commands: value.item.action.commands } }),
...isShellProviderExecuted && { providerExecuted: true },
providerMetadata: { [providerOptionsName]: { itemId: value.item.id } }
});
} else if (value.item.type === "shell_call_output") controller.enqueue({
type: "tool-result",
toolCallId: value.item.call_id,
toolName: toolNameMapping.toCustomToolName("shell"),
result: { output: value.item.output.map((item) => ({
stdout: item.stdout,
stderr: item.stderr,
outcome: item.outcome.type === "exit" ? {
type: "exit",
exitCode: item.outcome.exit_code
} : { type: "timeout" }
})) }
});
else if (value.item.type === "reasoning") {
const activeReasoningPart = activeReasoning[value.item.id];
const summaryPartIndices = Object.entries(activeReasoningPart.summaryParts).filter(([_, status]) => status === "active" || status === "can-conclude").map(([summaryIndex]) => summaryIndex);
for (const summaryIndex of summaryPartIndices) controller.enqueue({
type: "reasoning-end",
id: `${value.item.id}:${summaryIndex}`,
providerMetadata: { [providerOptionsName]: {
itemId: value.item.id,
reasoningEncryptedContent: (_r = value.item.encrypted_content) != null ? _r : null
} }
});
delete activeReasoning[value.item.id];
}
} else if (isResponseFunctionCallArgumentsDeltaChunk(value)) {
const toolCall = ongoingToolCalls[value.output_index];
if (toolCall != null) {
if (toolCall.suppressInputStreaming) (_s = toolCall.bufferedInputDeltas) == null || _s.push(value.delta);
else controller.enqueue({
type: "tool-input-delta",
id: toolCall.toolCallId,
delta: value.delta
});
}
} else if (isResponseCustomToolCallInputDeltaChunk(value)) {
const toolCall = ongoingToolCalls[value.output_index];
if (toolCall != null) controller.enqueue({
type: "tool-input-delta",
id: toolCall.toolCallId,
delta: value.delta
});
} else if (isResponseApplyPatchCallOperationDiffDeltaChunk(value)) {
const toolCall = ongoingToolCalls[value.output_index];
if (toolCall == null ? void 0 : toolCall.applyPatch) {
controller.enqueue({
type: "tool-input-delta",
id: toolCall.toolCallId,
delta: escapeJSONDelta(value.delta)
});
toolCall.applyPatch.hasDiff = true;
}
} else if (isResponseApplyPatchCallOperationDiffDoneChunk(value)) {
const toolCall = ongoingToolCalls[value.output_index];
if ((toolCall == null ? void 0 : toolCall.applyPatch) && !toolCall.applyPatch.endEmitted) {
if (!toolCall.applyPatch.hasDiff) {
controller.enqueue({
type: "tool-input-delta",
id: toolCall.toolCallId,
delta: escapeJSONDelta(value.diff)
});
toolCall.applyPatch.hasDiff = true;
}
controller.enqueue({
type: "tool-input-delta",
id: toolCall.toolCallId,
delta: "\"}}"
});
controller.enqueue({
type: "tool-input-end",
id: toolCall.toolCallId
});
toolCall.applyPatch.endEmitted = true;
}
} else if (isResponseImageGenerationCallPartialImageChunk(value)) controller.enqueue({
type: "tool-result",
toolCallId: value.item_id,
toolName: toolNameMapping.toCustomToolName("image_generation"),
result: { result: value.partial_image_b64 },
preliminary: true
});
else if (isResponseCodeInterpreterCallCodeDeltaChunk(value)) {
const toolCall = ongoingToolCalls[value.output_index];
if (toolCall != null) controller.enqueue({
type: "tool-input-delta",
id: toolCall.toolCallId,
delta: escapeJSONDelta(value.delta)
});
} else if (isResponseCodeInterpreterCallCodeDoneChunk(value)) {
const toolCall = ongoingToolCalls[value.output_index];
if (toolCall != null) {
controller.enqueue({
type: "tool-input-delta",
id: toolCall.toolCallId,
delta: "\"}"
});
controller.enqueue({
type: "tool-input-end",
id: toolCall.toolCallId
});
controller.enqueue({
type: "tool-call",
toolCallId: toolCall.toolCallId,
toolName: toolNameMapping.toCustomToolName("code_interpreter"),
input: JSON.stringify({
code: value.code,
containerId: toolCall.codeInterpreter.containerId
}),
providerExecuted: true
});
}
} else if (isResponseCreatedChunk(value)) {
responseId = value.response.id;
controller.enqueue({
type: "response-metadata",
id: value.response.id,
timestamp: /* @__PURE__ */ new Date(value.response.created_at * 1e3),
modelId: value.response.model
});
} else if (isTextDeltaChunk(value)) {
controller.enqueue({
type: "text-delta",
id: value.item_id,
delta: value.delta
});
if (((_u = (_t = options.providerOptions) == null ? void 0 : _t[providerOptionsName]) == null ? void 0 : _u.logprobs) && value.logprobs) logprobs.push(value.logprobs);
} else if (value.type === "response.reasoning_summary_part.added") {
if (value.summary_index > 0) {
const activeReasoningPart = activeReasoning[value.item_id];
activeReasoningPart.summaryParts[value.summary_index] = "active";
for (const summaryIndex of Object.keys(activeReasoningPart.summaryParts)) if (activeReasoningPart.summaryParts[summaryIndex] === "can-conclude") {
controller.enqueue({
type: "reasoning-end",
id: `${value.item_id}:${summaryIndex}`,
providerMetadata: { [providerOptionsName]: { itemId: value.item_id } }
});
activeReasoningPart.summaryParts[summaryIndex] = "concluded";
}
controller.enqueue({
type: "reasoning-start",
id: `${value.item_id}:${value.summary_index}`,
providerMetadata: { [providerOptionsName]: {
itemId: value.item_id,
reasoningEncryptedContent: (_w = (_v = activeReasoning[value.item_id]) == null ? void 0 : _v.encryptedContent) != null ? _w : null
} }
});
}
} else if (value.type === "response.reasoning_summary_text.delta") controller.enqueue({
type: "reasoning-delta",
id: `${value.item_id}:${value.summary_index}`,
delta: value.delta,
providerMetadata: { [providerOptionsName]: { itemId: value.item_id } }
});
else if (value.type === "response.reasoning_summary_part.done") {
if (store) {
controller.enqueue({
type: "reasoning-end",
id: `${value.item_id}:${value.summary_index}`,
providerMetadata: { [providerOptionsName]: { itemId: value.item_id } }
});
activeReasoning[value.item_id].summaryParts[value.summary_index] = "concluded";
} else activeReasoning[value.item_id].summaryParts[value.summary_index] = "can-conclude";
} else if (isResponseFinishedChunk(value)) {
if (!encounteredStreamError) finishReason = {
unified: mapOpenAIResponseFinishReason({
finishReason: (_x = value.response.incomplete_details) == null ? void 0 : _x.reason,
hasFunctionCall
}),
raw: (_z = (_y = value.response.incomplete_details) == null ? void 0 : _y.reason) != null ? _z : void 0
};
usage = (_A = value.response.usage) != null ? _A : void 0;
if (typeof value.response.service_tier === "string") serviceTier = value.response.service_tier;
if (((_B = value.response.reasoning) == null ? void 0 : _B.context) != null) reasoningContext = value.response.reasoning.context;
} else if (isResponseFailedChunk(value)) {
const incompleteReason = (_C = value.response.incomplete_details) == null ? void 0 : _C.reason;
finishReason = {
unified: incompleteReason ? mapOpenAIResponseFinishReason({
finishReason: incompleteReason,
hasFunctionCall
}) : "error",
raw: incompleteReason != null ? incompleteReason : "error"
};
usage = (_D = value.response.usage) != null ? _D : void 0;
if (((_E = value.response.reasoning) == null ? void 0 : _E.context) != null) reasoningContext = value.response.reasoning.context;
if (!encounteredStreamError && value.response.error != null) {
encounteredStreamError = true;
const error = {
type: "response.failed",
sequence_number: value.sequence_number,
response: {
error: value.response.error,
incomplete_details: value.response.incomplete_details,
service_tier: value.response.service_tier
}
};
controller.enqueue({
type: "error",
error: (_F = createOpenAIProviderStreamError(error)) != null ? _F : error
});
}
} else if (isResponseAnnotationAddedChunk(value)) {
ongoingAnnotations.push(value.annotation);
if (value.annotation.type === "url_citation") controller.enqueue({
type: "source",
sourceType: "url",
id: (_I = (_H = (_G = self.config).generateId) == null ? void 0 : _H.call(_G)) != null ? _I : generateId$2(),
url: value.annotation.url,
title: value.annotation.title
});
else if (value.annotation.type === "file_citation") controller.enqueue({
type: "source",
sourceType: "document",
id: (_L = (_K = (_J = self.config).generateId) == null ? void 0 : _K.call(_J)) != null ? _L : generateId$2(),
mediaType: "text/plain",
title: value.annotation.filename,
filename: value.annotation.filename,
providerMetadata: { [providerOptionsName]: {
type: value.annotation.type,
fileId: value.annotation.file_id,
index: value.annotation.index
} }
});
else if (value.annotation.type === "container_file_citation") controller.enqueue({
type: "source",
sourceType: "document",
id: (_O = (_N = (_M = self.config).generateId) == null ? void 0 : _N.call(_M)) != null ? _O : generateId$2(),
mediaType: "text/plain",
title: value.annotation.filename,
filename: value.annotation.filename,
providerMetadata: { [providerOptionsName]: {
type: value.annotation.type,
fileId: value.annotation.file_id,
containerId: value.annotation.container_id
} }
});
else if (value.annotation.type === "file_path") controller.enqueue({
type: "source",
sourceType: "document",
id: (_R = (_Q = (_P = self.config).generateId) == null ? void 0 : _Q.call(_P)) != null ? _R : generateId$2(),
mediaType: "application/octet-stream",
title: value.annotation.file_id,
filename: value.annotation.file_id,
providerMetadata: { [providerOptionsName]: {
type: value.annotation.type,
fileId: value.annotation.file_id,
index: value.annotation.index
} }
});
} else if (isErrorChunk(value)) {
encounteredStreamError = true;
finishReason = {
unified: "error",
raw: "error"
};
controller.enqueue({
type: "error",
error: (_S = createOpenAIProviderStreamError(value)) != null ? _S : value
});
}
},
flush(controller) {
var _a3;
for (const toolCall of Object.values(ongoingToolCalls)) {
if (!(toolCall == null ? void 0 : toolCall.suppressInputStreaming)) continue;
controller.enqueue({
type: "tool-input-start",
id: toolCall.toolCallId,
toolName: toolCall.toolName
});
for (const delta of (_a3 = toolCall.bufferedInputDeltas) != null ? _a3 : []) controller.enqueue({
type: "tool-input-delta",
id: toolCall.toolCallId,
delta
});
}
const providerMetadata = { [providerOptionsName]: {
responseId,
...logprobs.length > 0 ? { logprobs } : {},
...serviceTier !== void 0 ? { serviceTier } : {},
...reasoningContext !== void 0 ? { reasoningContext } : {}
} };
controller.enqueue({
type: "finish",
finishReason,
usage: convertOpenAIResponsesUsage(usage),
providerMetadata
});
}
})),
request: { body },
response: { headers: responseHeaders }
};
}
};
function isTextDeltaChunk(chunk) {
return chunk.type === "response.output_text.delta";
}
function isOpenAIChatCompletionChunk(value) {
const chunk = asRecord2(value);
return chunk != null && Array.isArray(chunk.choices) && typeof chunk.type !== "string";
}
function createOpenAIResponsesChatCompletionsMismatchError({ value, cause, url, requestBodyValues, responseHeaders }) {
return new APICallError$2({
message: "Received a Chat Completions stream while using the OpenAI Responses API. The default OpenAI provider model uses the Responses API. If your custom baseURL targets a Chat Completions-compatible endpoint, use openai.chat('model-id') or createOpenAI(...).chat('model-id') instead. You can also use @ai-sdk/openai-compatible for OpenAI-compatible providers.",
url,
requestBodyValues,
responseHeaders,
responseBody: JSON.stringify(value),
cause,
data: value,
isRetryable: false
});
}
function asRecord2(value) {
return typeof value === "object" && value != null ? value : void 0;
}
function isResponseOutputItemDoneChunk(chunk) {
return chunk.type === "response.output_item.done";
}
function isResponseFinishedChunk(chunk) {
return chunk.type === "response.completed" || chunk.type === "response.incomplete";
}
function isResponseFailedChunk(chunk) {
return chunk.type === "response.failed";
}
function isResponseCreatedChunk(chunk) {
return chunk.type === "response.created";
}
function isResponseFunctionCallArgumentsDeltaChunk(chunk) {
return chunk.type === "response.function_call_arguments.delta";
}
function isResponseCustomToolCallInputDeltaChunk(chunk) {
return chunk.type === "response.custom_tool_call_input.delta";
}
function isResponseImageGenerationCallPartialImageChunk(chunk) {
return chunk.type === "response.image_generation_call.partial_image";
}
function isResponseCodeInterpreterCallCodeDeltaChunk(chunk) {
return chunk.type === "response.code_interpreter_call_code.delta";
}
function isResponseCodeInterpreterCallCodeDoneChunk(chunk) {
return chunk.type === "response.code_interpreter_call_code.done";
}
function isResponseApplyPatchCallOperationDiffDeltaChunk(chunk) {
return chunk.type === "response.apply_patch_call_operation_diff.delta";
}
function isResponseApplyPatchCallOperationDiffDoneChunk(chunk) {
return chunk.type === "response.apply_patch_call_operation_diff.done";
}
function isResponseOutputItemAddedChunk(chunk) {
return chunk.type === "response.output_item.added";
}
function isResponseAnnotationAddedChunk(chunk) {
return chunk.type === "response.output_text.annotation.added";
}
function isErrorChunk(chunk) {
return chunk.type === "error";
}
function isResponseOutputChunk(chunk) {
return !(chunk.type === "response.created" || chunk.type === "response.failed" || chunk.type === "error" || chunk.type === "unknown_chunk");
}
function mapWebSearchResult({ action, status }) {
return status === "completed" ? { result: mapWebSearchOutput(action) } : {
isError: true,
result: { status }
};
}
function mapWebSearchOutput(action) {
var _a2;
if (action == null) return {};
switch (action.type) {
case "search": return {
action: {
type: "search",
query: (_a2 = action.query) != null ? _a2 : void 0,
...action.queries != null && { queries: action.queries }
},
...action.sources != null && { sources: action.sources }
};
case "open_page": return { action: {
type: "openPage",
url: action.url
} };
case "find_in_page": return { action: {
type: "findInPage",
url: action.url,
pattern: action.pattern
} };
}
}
function escapeJSONDelta(delta) {
return JSON.stringify(delta).slice(1, -1);
}
var openaiSpeechModelOptionsSchema = lazySchema$1(() => zodSchema$2(z.object({
instructions: z.string().nullish(),
speed: z.number().min(.25).max(4).default(1).nullish()
})));
var OpenAISpeechModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v3";
}
get provider() {
return this.config.provider;
}
async getArgs({ text, voice = "alloy", outputFormat = "mp3", speed, instructions, language, providerOptions }) {
const warnings = [];
const openAIOptions = await parseProviderOptions$1({
provider: "openai",
providerOptions,
schema: openaiSpeechModelOptionsSchema
});
const requestBody = {
model: this.modelId,
input: text,
voice,
response_format: "mp3",
speed,
instructions
};
if (outputFormat) {
if ([
"mp3",
"opus",
"aac",
"flac",
"wav",
"pcm"
].includes(outputFormat)) requestBody.response_format = outputFormat;
else warnings.push({
type: "unsupported",
feature: "outputFormat",
details: `Unsupported output format: ${outputFormat}. Using mp3 instead.`
});
}
if (openAIOptions) {
const speechModelOptions = {};
for (const key in speechModelOptions) {
const value = speechModelOptions[key];
if (value !== void 0) requestBody[key] = value;
}
}
if (language) warnings.push({
type: "unsupported",
feature: "language",
details: `OpenAI speech models do not support language selection. Language parameter "${language}" was ignored.`
});
return {
requestBody,
warnings
};
}
async doGenerate(options) {
var _a2, _b, _c;
const currentDate = (_c = (_b = (_a2 = this.config._internal) == null ? void 0 : _a2.currentDate) == null ? void 0 : _b.call(_a2)) != null ? _c : /* @__PURE__ */ new Date();
const { requestBody, warnings } = await this.getArgs(options);
const { value: audio, responseHeaders, rawValue: rawResponse } = await postJsonToApi$2({
url: this.config.url({
path: "/audio/speech",
modelId: this.modelId
}),
headers: combineHeaders$2(this.config.headers(), options.headers),
body: requestBody,
failedResponseHandler: openaiFailedResponseHandler,
successfulResponseHandler: createBinaryResponseHandler$1(),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
return {
audio,
warnings,
request: { body: JSON.stringify(requestBody) },
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders,
body: rawResponse
}
};
}
};
var openaiTranscriptionResponseSchema = lazySchema$1(() => zodSchema$2(z.object({
text: z.string(),
language: z.string().nullish(),
duration: z.number().nullish(),
words: z.array(z.object({
word: z.string(),
start: z.number(),
end: z.number()
})).nullish(),
segments: z.array(z.object({
id: z.number(),
seek: z.number(),
start: z.number(),
end: z.number(),
text: z.string(),
tokens: z.array(z.number()),
temperature: z.number(),
avg_logprob: z.number(),
compression_ratio: z.number(),
no_speech_prob: z.number()
})).nullish(),
usage: z.object({
type: z.string().nullish(),
seconds: z.number().nullish()
}).nullish().catch(void 0)
})));
var openAITranscriptionModelOptions = lazySchema$1(() => zodSchema$2(z.object({
/**
* Additional information to include in the transcription response.
*/
include: z.array(z.string()).optional(),
/**
* The language of the input audio in ISO-639-1 format.
*/
language: z.string().optional(),
/**
* An optional text to guide the model's style or continue a previous audio segment.
*/
prompt: z.string().optional(),
/**
* The sampling temperature, between 0 and 1.
* @default 0
*/
temperature: z.number().min(0).max(1).default(0).optional(),
/**
* The timestamp granularities to populate for this transcription.
* @default ['segment']
*/
timestampGranularities: z.array(z.enum(["word", "segment"])).default(["segment"]).optional()
})));
var languageMap = {
afrikaans: "af",
arabic: "ar",
armenian: "hy",
azerbaijani: "az",
belarusian: "be",
bosnian: "bs",
bulgarian: "bg",
catalan: "ca",
chinese: "zh",
croatian: "hr",
czech: "cs",
danish: "da",
dutch: "nl",
english: "en",
estonian: "et",
finnish: "fi",
french: "fr",
galician: "gl",
german: "de",
greek: "el",
hebrew: "he",
hindi: "hi",
hungarian: "hu",
icelandic: "is",
indonesian: "id",
italian: "it",
japanese: "ja",
kannada: "kn",
kazakh: "kk",
korean: "ko",
latvian: "lv",
lithuanian: "lt",
macedonian: "mk",
malay: "ms",
marathi: "mr",
maori: "mi",
nepali: "ne",
norwegian: "no",
persian: "fa",
polish: "pl",
portuguese: "pt",
romanian: "ro",
russian: "ru",
serbian: "sr",
slovak: "sk",
slovenian: "sl",
spanish: "es",
swahili: "sw",
swedish: "sv",
tagalog: "tl",
tamil: "ta",
thai: "th",
turkish: "tr",
ukrainian: "uk",
urdu: "ur",
vietnamese: "vi",
welsh: "cy"
};
var OpenAITranscriptionModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v3";
}
get provider() {
return this.config.provider;
}
async getArgs({ audio, mediaType, providerOptions }) {
const warnings = [];
const openAIOptions = await parseProviderOptions$1({
provider: "openai",
providerOptions,
schema: openAITranscriptionModelOptions
});
const formData = new FormData();
const blob = audio instanceof Uint8Array ? new Blob([audio]) : new Blob([convertBase64ToUint8Array$1(audio)]);
formData.append("model", this.modelId);
const fileExtension = mediaTypeToExtension$1(mediaType);
formData.append("file", new File([blob], "audio", { type: mediaType }), `audio.${fileExtension}`);
if (openAIOptions) {
const transcriptionModelOptions = {
include: openAIOptions.include,
language: openAIOptions.language,
prompt: openAIOptions.prompt,
response_format: ["gpt-4o-transcribe", "gpt-4o-mini-transcribe"].includes(this.modelId) || this.modelId.startsWith("gpt-4o-mini-transcribe-") || this.modelId === "gpt-transcribe" || this.modelId.startsWith("gpt-transcribe-") ? "json" : "verbose_json",
temperature: openAIOptions.temperature,
timestamp_granularities: openAIOptions.timestampGranularities
};
for (const [key, value] of Object.entries(transcriptionModelOptions)) if (value != null) {
if (Array.isArray(value)) for (const item of value) formData.append(`${key}[]`, String(item));
else formData.append(key, String(value));
}
}
return {
formData,
warnings
};
}
async doGenerate(options) {
var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j;
const currentDate = (_c = (_b = (_a2 = this.config._internal) == null ? void 0 : _a2.currentDate) == null ? void 0 : _b.call(_a2)) != null ? _c : /* @__PURE__ */ new Date();
const { formData, warnings } = await this.getArgs(options);
const { value: response, responseHeaders, rawValue: rawResponse } = await postFormDataToApi$1({
url: this.config.url({
path: "/audio/transcriptions",
modelId: this.modelId
}),
headers: combineHeaders$2(this.config.headers(), options.headers),
formData,
failedResponseHandler: openaiFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$2(openaiTranscriptionResponseSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const language = response.language != null && response.language in languageMap ? languageMap[response.language] : void 0;
return {
text: response.text,
segments: (_g = (_f = (_d = response.segments) == null ? void 0 : _d.map((segment) => ({
text: segment.text,
startSecond: segment.start,
endSecond: segment.end
}))) != null ? _f : (_e = response.words) == null ? void 0 : _e.map((word) => ({
text: word.word,
startSecond: word.start,
endSecond: word.end
}))) != null ? _g : [],
language,
durationInSeconds: (_j = response.duration) != null ? _j : ((_h = response.usage) == null ? void 0 : _h.type) === "duration" ? (_i = response.usage.seconds) != null ? _i : void 0 : void 0,
warnings,
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders,
body: rawResponse
}
};
}
};
var VERSION$13 = "3.0.135";
function createOpenAI(options = {}) {
var _a2, _b;
const baseURL = (_a2 = withoutTrailingSlash$2(loadOptionalSetting({
settingValue: options.baseURL,
environmentVariableName: "OPENAI_BASE_URL"
}))) != null ? _a2 : "https://api.openai.com/v1";
const providerName = (_b = options.name) != null ? _b : "openai";
const getHeaders = () => withUserAgentSuffix$2({
Authorization: `Bearer ${loadApiKey$2({
apiKey: options.apiKey,
environmentVariableName: "OPENAI_API_KEY",
description: "OpenAI"
})}`,
"OpenAI-Organization": options.organization,
"OpenAI-Project": options.project,
...options.headers
}, `ai-sdk/openai/${VERSION$13}`);
const createChatModel = (modelId) => new OpenAIChatLanguageModel(modelId, {
provider: `${providerName}.chat`,
url: ({ path }) => `${baseURL}${path}`,
headers: getHeaders,
fetch: options.fetch
});
const createCompletionModel = (modelId) => new OpenAICompletionLanguageModel(modelId, {
provider: `${providerName}.completion`,
url: ({ path }) => `${baseURL}${path}`,
headers: getHeaders,
fetch: options.fetch
});
const createEmbeddingModel = (modelId) => new OpenAIEmbeddingModel(modelId, {
provider: `${providerName}.embedding`,
url: ({ path }) => `${baseURL}${path}`,
headers: getHeaders,
fetch: options.fetch
});
const createImageModel = (modelId) => new OpenAIImageModel(modelId, {
provider: `${providerName}.image`,
url: ({ path }) => `${baseURL}${path}`,
headers: getHeaders,
fetch: options.fetch
});
const createTranscriptionModel = (modelId) => new OpenAITranscriptionModel(modelId, {
provider: `${providerName}.transcription`,
url: ({ path }) => `${baseURL}${path}`,
headers: getHeaders,
fetch: options.fetch
});
const createSpeechModel = (modelId) => new OpenAISpeechModel(modelId, {
provider: `${providerName}.speech`,
url: ({ path }) => `${baseURL}${path}`,
headers: getHeaders,
fetch: options.fetch
});
const createLanguageModel = (modelId) => {
if (new.target) throw new Error("The OpenAI model function cannot be called with the new keyword.");
return createResponsesModel(modelId);
};
const createResponsesModel = (modelId) => {
return new OpenAIResponsesLanguageModel(modelId, {
provider: `${providerName}.responses`,
url: ({ path }) => `${baseURL}${path}`,
headers: getHeaders,
fetch: options.fetch,
fileIdPrefixes: ["file-"]
});
};
const provider = function(modelId) {
return createLanguageModel(modelId);
};
provider.specificationVersion = "v3";
provider.languageModel = createLanguageModel;
provider.chat = createChatModel;
provider.completion = createCompletionModel;
provider.responses = createResponsesModel;
provider.embedding = createEmbeddingModel;
provider.embeddingModel = createEmbeddingModel;
provider.textEmbedding = createEmbeddingModel;
provider.textEmbeddingModel = createEmbeddingModel;
provider.image = createImageModel;
provider.imageModel = createImageModel;
provider.transcription = createTranscriptionModel;
provider.transcriptionModel = createTranscriptionModel;
provider.speech = createSpeechModel;
provider.speechModel = createSpeechModel;
provider.tools = openaiTools;
return provider;
}
createOpenAI();
// src/llm/model/gateways/base.ts
/** @internal Stream transport handle attached by gateways that own custom streaming transports. */
const MASTRA_GATEWAY_STREAM_TRANSPORT = Symbol.for("@mastra/core.gatewayStreamTransport");
var MastraModelGateway = class {
getId() {
return this.id;
}
shouldEnable() {
return true;
}
handlesModel(_modelId) {
return false;
}
serializeForSpan() {
return {
id: this.id,
name: this.name
};
}
};
// src/llm/model/capability-file.ts
function getCapabilityFileName(provider) {
return `${encodeURIComponent(provider)}.json`;
}
// src/llm/model/gateways/gateway-helpers.ts
function getGatewayId(gateway) {
return gateway.getId?.() ?? gateway.id;
}
function shouldEnableGateway(gateway) {
return gateway.shouldEnable?.() ?? true;
}
function hasAuthCredentials(auth) {
return Boolean(auth?.apiKey || auth?.bearerToken || auth?.headers && Object.keys(auth.headers).length > 0);
}
/**
* Find the gateway the model router would use for a model ID.
* Disabled gateways are skipped. A gateway ID is used as the prefix (e.g.,
* "netlify" for netlify gateway); gateways may also claim a model through
* `handlesModel`. models.dev is a provider registry and doesn't use a prefix.
*/
function findGatewayForModel(modelId, allGateways) {
const gateways = allGateways.filter(shouldEnableGateway);
const prefixedGateway = gateways.find((g) => {
const id = getGatewayId(g);
return id !== "models.dev" && (id === modelId || modelId.startsWith(`${id}/`));
});
if (prefixedGateway) return prefixedGateway;
const claimingGateway = gateways.find((g) => getGatewayId(g) !== "models.dev" && g.handlesModel?.(modelId) === true);
if (claimingGateway) return claimingGateway;
const modelsDevGateway = gateways.find((g) => getGatewayId(g) === "models.dev");
if (modelsDevGateway) return modelsDevGateway;
throw new MastraError({
id: "MODEL_ROUTER_NO_GATEWAY_FOUND",
category: "USER",
domain: "MODEL_ROUTER",
text: `No Mastra model router gateway found for model id ${modelId}`
});
}
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/anthropic/3.0.137/14a45de3f6c7c815ad75cef123394be704072e1b6b1ccb21eeb105b30d8f1a4c/node_modules/@ai-sdk/anthropic/dist/index.mjs
var VERSION$12 = "3.0.137";
var anthropicFailedResponseHandler = createJsonErrorResponseHandler$2({
errorSchema: lazySchema$1(() => zodSchema$2(z.object({
type: z.literal("error"),
error: z.object({
type: z.string(),
message: z.string()
})
}))),
errorToMessage: (data) => data.error.message
});
var anthropicStopDetailsSchema = () => z.object({
type: z.string(),
category: z.string().nullish(),
explanation: z.string().nullish(),
recommended_model: z.string().nullish()
});
var anthropicSafeguardResultSchema = () => z.object({
type: z.string(),
status: z.object({
type: z.string(),
tool_uses: z.record(z.string(), z.object({
type: z.string(),
outcome: z.string().nullish(),
explanation: z.string().nullish()
})).nullish()
})
});
var anthropicToolCallCallerSchema = () => z.union([
z.object({
type: z.literal("code_execution_20250825"),
tool_id: z.string()
}),
z.object({
type: z.literal("code_execution_20260120"),
tool_id: z.string()
}),
z.object({ type: z.literal("direct") })
]);
var anthropicInputTransformationSchema = () => z.object({
type: z.string(),
path: z.string(),
reason: z.string()
});
var anthropicMessagesResponseSchema = lazySchema$1(() => zodSchema$2(z.object({
type: z.literal("message"),
id: z.string().nullish(),
model: z.string().nullish(),
content: z.array(z.discriminatedUnion("type", [
z.object({
type: z.literal("text"),
text: z.string(),
citations: z.array(z.discriminatedUnion("type", [
z.object({
type: z.literal("web_search_result_location"),
cited_text: z.string(),
url: z.string(),
title: z.string(),
encrypted_index: z.string()
}),
z.object({
type: z.literal("page_location"),
cited_text: z.string(),
document_index: z.number(),
document_title: z.string().nullable(),
start_page_number: z.number(),
end_page_number: z.number()
}),
z.object({
type: z.literal("char_location"),
cited_text: z.string(),
document_index: z.number(),
document_title: z.string().nullable(),
start_char_index: z.number(),
end_char_index: z.number()
})
])).optional()
}),
z.object({
type: z.literal("thinking"),
thinking: z.string(),
signature: z.string()
}),
z.object({
type: z.literal("redacted_thinking"),
data: z.string()
}),
z.object({
type: z.literal("compaction"),
content: z.string()
}),
z.object({
type: z.literal("tool_use"),
id: z.string(),
name: z.string(),
input: z.unknown(),
caller: anthropicToolCallCallerSchema().optional(),
toolset_name: z.string().nullish()
}),
z.object({
type: z.literal("server_tool_use"),
id: z.string(),
name: z.string(),
input: z.record(z.string(), z.unknown()).nullish(),
caller: anthropicToolCallCallerSchema().optional()
}),
z.object({
type: z.literal("mcp_tool_use"),
id: z.string(),
name: z.string(),
input: z.unknown(),
server_name: z.string()
}),
z.object({
type: z.literal("mcp_tool_result"),
tool_use_id: z.string(),
is_error: z.boolean(),
content: z.array(z.union([z.string(), z.object({
type: z.literal("text"),
text: z.string()
})]))
}),
z.object({
type: z.literal("web_fetch_tool_result"),
tool_use_id: z.string(),
caller: anthropicToolCallCallerSchema().optional(),
content: z.union([z.object({
type: z.literal("web_fetch_result"),
url: z.string(),
retrieved_at: z.string(),
content: z.object({
type: z.literal("document"),
title: z.string().nullable(),
citations: z.object({ enabled: z.boolean() }).optional(),
source: z.union([z.object({
type: z.literal("base64"),
media_type: z.literal("application/pdf"),
data: z.string()
}), z.object({
type: z.literal("text"),
media_type: z.literal("text/plain"),
data: z.string()
})])
})
}), z.object({
type: z.literal("web_fetch_tool_result_error"),
error_code: z.string()
})])
}),
z.object({
type: z.literal("web_search_tool_result"),
tool_use_id: z.string(),
caller: anthropicToolCallCallerSchema().optional(),
content: z.union([z.array(z.object({
type: z.literal("web_search_result"),
url: z.string(),
title: z.string(),
encrypted_content: z.string(),
page_age: z.string().nullish()
})), z.object({
type: z.literal("web_search_tool_result_error"),
error_code: z.string()
})])
}),
z.object({
type: z.literal("code_execution_tool_result"),
tool_use_id: z.string(),
content: z.union([
z.object({
type: z.literal("code_execution_result"),
stdout: z.string(),
stderr: z.string(),
return_code: z.number(),
content: z.array(z.object({
type: z.literal("code_execution_output"),
file_id: z.string()
})).optional().default([])
}),
z.object({
type: z.literal("encrypted_code_execution_result"),
encrypted_stdout: z.string(),
stderr: z.string(),
return_code: z.number(),
content: z.array(z.object({
type: z.literal("code_execution_output"),
file_id: z.string()
})).optional().default([])
}),
z.object({
type: z.literal("code_execution_tool_result_error"),
error_code: z.string()
})
])
}),
z.object({
type: z.literal("bash_code_execution_tool_result"),
tool_use_id: z.string(),
content: z.discriminatedUnion("type", [z.object({
type: z.literal("bash_code_execution_result"),
content: z.array(z.object({
type: z.literal("bash_code_execution_output"),
file_id: z.string()
})),
stdout: z.string(),
stderr: z.string(),
return_code: z.number()
}), z.object({
type: z.literal("bash_code_execution_tool_result_error"),
error_code: z.string()
})])
}),
z.object({
type: z.literal("text_editor_code_execution_tool_result"),
tool_use_id: z.string(),
content: z.discriminatedUnion("type", [
z.object({
type: z.literal("text_editor_code_execution_tool_result_error"),
error_code: z.string()
}),
z.object({
type: z.literal("text_editor_code_execution_view_result"),
content: z.string(),
file_type: z.string(),
num_lines: z.number().nullable(),
start_line: z.number().nullable(),
total_lines: z.number().nullable()
}),
z.object({
type: z.literal("text_editor_code_execution_create_result"),
is_file_update: z.boolean()
}),
z.object({
type: z.literal("text_editor_code_execution_str_replace_result"),
lines: z.array(z.string()).nullable(),
new_lines: z.number().nullable(),
new_start: z.number().nullable(),
old_lines: z.number().nullable(),
old_start: z.number().nullable()
})
])
}),
z.object({
type: z.literal("tool_search_tool_result"),
tool_use_id: z.string(),
content: z.union([z.object({
type: z.literal("tool_search_tool_search_result"),
tool_references: z.array(z.object({
type: z.literal("tool_reference"),
tool_name: z.string()
}))
}), z.object({
type: z.literal("tool_search_tool_result_error"),
error_code: z.string()
})])
}),
z.object({
type: z.literal("advisor_tool_result"),
tool_use_id: z.string(),
content: z.discriminatedUnion("type", [
z.object({
type: z.literal("advisor_result"),
text: z.string()
}),
z.object({
type: z.literal("advisor_redacted_result"),
encrypted_content: z.string()
}),
z.object({
type: z.literal("advisor_tool_result_error"),
error_code: z.string()
})
])
}),
z.object({ type: z.literal("fallback") })
])),
stop_reason: z.string().nullish(),
stop_sequence: z.string().nullish(),
stop_details: anthropicStopDetailsSchema().nullish(),
input_transformations: z.array(anthropicInputTransformationSchema()).nullish(),
safeguard_results: z.array(anthropicSafeguardResultSchema()).nullish(),
usage: z.looseObject({
input_tokens: z.number(),
output_tokens: z.number(),
output_tokens_details: z.object({ thinking_tokens: z.number().nullish() }).nullish(),
cache_creation_input_tokens: z.number().nullish(),
cache_read_input_tokens: z.number().nullish(),
iterations: z.array(z.object({
type: z.union([
z.literal("compaction"),
z.literal("message"),
z.literal("advisor_message"),
z.literal("fallback_message")
]),
model: z.string().nullish(),
input_tokens: z.number(),
output_tokens: z.number(),
cache_creation_input_tokens: z.number().nullish(),
cache_read_input_tokens: z.number().nullish()
})).nullish()
}),
container: z.object({
expires_at: z.string(),
id: z.string(),
skills: z.array(z.object({
type: z.union([z.literal("anthropic"), z.literal("custom")]),
skill_id: z.string(),
version: z.string()
})).nullish()
}).nullish(),
context_management: z.object({ applied_edits: z.array(z.union([
z.object({
type: z.literal("clear_tool_uses_20250919"),
cleared_tool_uses: z.number(),
cleared_input_tokens: z.number()
}),
z.object({
type: z.literal("clear_thinking_20251015"),
cleared_thinking_turns: z.number(),
cleared_input_tokens: z.number()
}),
z.object({ type: z.literal("compact_20260112") })
])) }).nullish()
})));
var anthropicMessagesChunkSchema = lazySchema$1(() => zodSchema$2(z.discriminatedUnion("type", [
z.object({
type: z.literal("message_start"),
message: z.object({
id: z.string().nullish(),
model: z.string().nullish(),
role: z.string().nullish(),
usage: z.looseObject({
input_tokens: z.number(),
cache_creation_input_tokens: z.number().nullish(),
cache_read_input_tokens: z.number().nullish()
}),
content: z.array(z.discriminatedUnion("type", [z.object({
type: z.literal("tool_use"),
id: z.string(),
name: z.string(),
input: z.unknown(),
caller: anthropicToolCallCallerSchema().optional(),
toolset_name: z.string().nullish()
})])).nullish(),
stop_reason: z.string().nullish(),
input_transformations: z.array(anthropicInputTransformationSchema()).nullish(),
container: z.object({
expires_at: z.string(),
id: z.string()
}).nullish()
})
}),
z.object({
type: z.literal("content_block_start"),
index: z.number(),
content_block: z.discriminatedUnion("type", [
z.object({
type: z.literal("text"),
text: z.string()
}),
z.object({
type: z.literal("thinking"),
thinking: z.string()
}),
z.object({
type: z.literal("tool_use"),
id: z.string(),
name: z.string(),
input: z.record(z.string(), z.unknown()).optional(),
caller: anthropicToolCallCallerSchema().optional(),
toolset_name: z.string().nullish()
}),
z.object({
type: z.literal("redacted_thinking"),
data: z.string()
}),
z.object({
type: z.literal("compaction"),
content: z.string().nullish()
}),
z.object({
type: z.literal("server_tool_use"),
id: z.string(),
name: z.string(),
input: z.record(z.string(), z.unknown()).nullish(),
caller: anthropicToolCallCallerSchema().optional()
}),
z.object({
type: z.literal("mcp_tool_use"),
id: z.string(),
name: z.string(),
input: z.unknown(),
server_name: z.string()
}),
z.object({
type: z.literal("mcp_tool_result"),
tool_use_id: z.string(),
is_error: z.boolean(),
content: z.array(z.union([z.string(), z.object({
type: z.literal("text"),
text: z.string()
})]))
}),
z.object({
type: z.literal("web_fetch_tool_result"),
tool_use_id: z.string(),
caller: anthropicToolCallCallerSchema().optional(),
content: z.union([z.object({
type: z.literal("web_fetch_result"),
url: z.string(),
retrieved_at: z.string(),
content: z.object({
type: z.literal("document"),
title: z.string().nullable(),
citations: z.object({ enabled: z.boolean() }).optional(),
source: z.union([z.object({
type: z.literal("base64"),
media_type: z.literal("application/pdf"),
data: z.string()
}), z.object({
type: z.literal("text"),
media_type: z.literal("text/plain"),
data: z.string()
})])
})
}), z.object({
type: z.literal("web_fetch_tool_result_error"),
error_code: z.string()
})])
}),
z.object({
type: z.literal("web_search_tool_result"),
tool_use_id: z.string(),
caller: anthropicToolCallCallerSchema().optional(),
content: z.union([z.array(z.object({
type: z.literal("web_search_result"),
url: z.string(),
title: z.string(),
encrypted_content: z.string(),
page_age: z.string().nullish()
})), z.object({
type: z.literal("web_search_tool_result_error"),
error_code: z.string()
})])
}),
z.object({
type: z.literal("code_execution_tool_result"),
tool_use_id: z.string(),
content: z.union([
z.object({
type: z.literal("code_execution_result"),
stdout: z.string(),
stderr: z.string(),
return_code: z.number(),
content: z.array(z.object({
type: z.literal("code_execution_output"),
file_id: z.string()
})).optional().default([])
}),
z.object({
type: z.literal("encrypted_code_execution_result"),
encrypted_stdout: z.string(),
stderr: z.string(),
return_code: z.number(),
content: z.array(z.object({
type: z.literal("code_execution_output"),
file_id: z.string()
})).optional().default([])
}),
z.object({
type: z.literal("code_execution_tool_result_error"),
error_code: z.string()
})
])
}),
z.object({
type: z.literal("bash_code_execution_tool_result"),
tool_use_id: z.string(),
content: z.discriminatedUnion("type", [z.object({
type: z.literal("bash_code_execution_result"),
content: z.array(z.object({
type: z.literal("bash_code_execution_output"),
file_id: z.string()
})),
stdout: z.string(),
stderr: z.string(),
return_code: z.number()
}), z.object({
type: z.literal("bash_code_execution_tool_result_error"),
error_code: z.string()
})])
}),
z.object({
type: z.literal("text_editor_code_execution_tool_result"),
tool_use_id: z.string(),
content: z.discriminatedUnion("type", [
z.object({
type: z.literal("text_editor_code_execution_tool_result_error"),
error_code: z.string()
}),
z.object({
type: z.literal("text_editor_code_execution_view_result"),
content: z.string(),
file_type: z.string(),
num_lines: z.number().nullable(),
start_line: z.number().nullable(),
total_lines: z.number().nullable()
}),
z.object({
type: z.literal("text_editor_code_execution_create_result"),
is_file_update: z.boolean()
}),
z.object({
type: z.literal("text_editor_code_execution_str_replace_result"),
lines: z.array(z.string()).nullable(),
new_lines: z.number().nullable(),
new_start: z.number().nullable(),
old_lines: z.number().nullable(),
old_start: z.number().nullable()
})
])
}),
z.object({
type: z.literal("tool_search_tool_result"),
tool_use_id: z.string(),
content: z.union([z.object({
type: z.literal("tool_search_tool_search_result"),
tool_references: z.array(z.object({
type: z.literal("tool_reference"),
tool_name: z.string()
}))
}), z.object({
type: z.literal("tool_search_tool_result_error"),
error_code: z.string()
})])
}),
z.object({
type: z.literal("advisor_tool_result"),
tool_use_id: z.string(),
content: z.discriminatedUnion("type", [
z.object({
type: z.literal("advisor_result"),
text: z.string()
}),
z.object({
type: z.literal("advisor_redacted_result"),
encrypted_content: z.string()
}),
z.object({
type: z.literal("advisor_tool_result_error"),
error_code: z.string()
})
])
}),
z.object({ type: z.literal("fallback") })
])
}),
z.object({
type: z.literal("content_block_delta"),
index: z.number(),
delta: z.discriminatedUnion("type", [
z.object({
type: z.literal("input_json_delta"),
partial_json: z.string()
}),
z.object({
type: z.literal("text_delta"),
text: z.string()
}),
z.object({
type: z.literal("thinking_delta"),
thinking: z.string()
}),
z.object({
type: z.literal("signature_delta"),
signature: z.string()
}),
z.object({
type: z.literal("compaction_delta"),
content: z.string().nullish()
}),
z.object({
type: z.literal("citations_delta"),
citation: z.discriminatedUnion("type", [
z.object({
type: z.literal("web_search_result_location"),
cited_text: z.string(),
url: z.string(),
title: z.string(),
encrypted_index: z.string()
}),
z.object({
type: z.literal("page_location"),
cited_text: z.string(),
document_index: z.number(),
document_title: z.string().nullable(),
start_page_number: z.number(),
end_page_number: z.number()
}),
z.object({
type: z.literal("char_location"),
cited_text: z.string(),
document_index: z.number(),
document_title: z.string().nullable(),
start_char_index: z.number(),
end_char_index: z.number()
})
])
})
])
}),
z.object({
type: z.literal("content_block_stop"),
index: z.number()
}),
z.object({
type: z.literal("error"),
error: z.object({
type: z.string(),
message: z.string()
})
}),
z.object({
type: z.literal("message_delta"),
delta: z.object({
stop_reason: z.string().nullish(),
stop_sequence: z.string().nullish(),
stop_details: anthropicStopDetailsSchema().nullish(),
safeguard_results: z.array(anthropicSafeguardResultSchema()).nullish(),
container: z.object({
expires_at: z.string(),
id: z.string(),
skills: z.array(z.object({
type: z.union([z.literal("anthropic"), z.literal("custom")]),
skill_id: z.string(),
version: z.string()
})).nullish()
}).nullish()
}),
usage: z.looseObject({
input_tokens: z.number().nullish(),
output_tokens: z.number(),
output_tokens_details: z.object({ thinking_tokens: z.number().nullish() }).nullish(),
cache_creation_input_tokens: z.number().nullish(),
cache_read_input_tokens: z.number().nullish(),
iterations: z.array(z.object({
type: z.union([
z.literal("compaction"),
z.literal("message"),
z.literal("advisor_message"),
z.literal("fallback_message")
]),
model: z.string().nullish(),
input_tokens: z.number(),
output_tokens: z.number(),
cache_creation_input_tokens: z.number().nullish(),
cache_read_input_tokens: z.number().nullish()
})).nullish()
}),
input_transformations: z.array(anthropicInputTransformationSchema()).nullish(),
context_management: z.object({ applied_edits: z.array(z.union([
z.object({
type: z.literal("clear_tool_uses_20250919"),
cleared_tool_uses: z.number(),
cleared_input_tokens: z.number()
}),
z.object({
type: z.literal("clear_thinking_20251015"),
cleared_thinking_turns: z.number(),
cleared_input_tokens: z.number()
}),
z.object({ type: z.literal("compact_20260112") })
])) }).nullish()
}),
z.object({ type: z.literal("message_stop") }),
z.object({ type: z.literal("ping") })
])));
var anthropicReasoningMetadataSchema = lazySchema$1(() => zodSchema$2(z.object({
signature: z.string().optional(),
redactedData: z.string().optional()
})));
var anthropicFilePartProviderOptions = lazySchema$1(() => zodSchema$2(z.object({
/**
* Citation configuration for this document.
* When enabled, this document will generate citations in the response.
*/
citations: z.object({
/**
* Enable citations for this document
*/
enabled: z.boolean() }).optional(),
/**
* Custom title for the document.
* If not provided, the filename will be used.
*/
title: z.string().optional(),
/**
* Context about the document that will be passed to the model
* but not used towards cited content.
* Useful for storing document metadata as text or stringified JSON.
*/
context: z.string().optional()
})));
var anthropicSystemMessageProviderOptions = lazySchema$1(() => zodSchema$2(z.object({
/**
* Clears this mid-conversation system message after the current turn.
*
* Requires the `mid-conversation-system-clear-at-2026-08-21` beta,
* which is added automatically.
*/
clearAt: z.literal("next_user_message").optional(),
/**
* Sets the model effort from the next user turn until a later message
* changes it. An effort-only system message with empty content can appear
* first. The required `mid-conversation-output-config-2026-07-01` beta is
* added automatically.
*/
effort: z.enum([
"low",
"medium",
"high",
"xhigh",
"max"
]).optional(),
/**
* Mid-conversation tool changes. Adds or removes tools from the
* conversation's tool set between turns without invalidating the prompt
* cache.
*
* Only supported on system messages that appear mid-conversation (not the
* initial system prompt). A system message carrying tool changes must come
* right before an assistant message or at the end of the messages.
*
* Tools referenced by a `tool_addition` must be declared in the `tools`
* option (typically with `deferLoading: true` so they are not loaded until
* the addition surfaces them). The required
* `mid-conversation-tool-changes-2026-07-01` beta is added automatically.
*/
toolChanges: z.array(z.discriminatedUnion("type", [z.object({
type: z.literal("tool_addition"),
toolName: z.string()
}), z.object({
type: z.literal("tool_removal"),
toolName: z.string()
})])).optional()
})));
var anthropicLanguageModelOptions = lazySchema$1(() => {
const anthropicThinkingBlockBinding = z.object({ prefixMismatchBehavior: z.enum(["error", "drop_block"]) });
return zodSchema$2(z.object({
/**
* Whether to send reasoning to the model.
*
* This allows you to deactivate reasoning inputs for models that do not support them.
*/
sendReasoning: z.boolean().optional(),
/**
* Determines how structured outputs are generated.
*
* - `outputFormat`: Use the `output_config.format` parameter to specify the structured output format.
* - `jsonTool`: Use a special 'json' tool to specify the structured output format.
* - `auto`: Use 'outputFormat' when supported, otherwise use 'jsonTool' (default).
*/
structuredOutputMode: z.enum([
"outputFormat",
"jsonTool",
"auto"
]).optional(),
/**
* Configuration for enabling Claude's extended thinking.
*
* When enabled, responses include thinking content blocks showing Claude's thinking process before the final answer.
* Requires a minimum budget of 1,024 tokens and counts towards the `max_tokens` limit.
*
* Models that always use adaptive thinking (e.g. `claude-opus-5-5`,
* `claude-fable-5-1`) reject `enabled` and `disabled`. For those models the
* provider drops the unsupported setting, emits a warning, and sends an
* adaptive thinking request. Use `effort` to control how much they think.
*
* `claude-sonnet-5-5` supports `between_tools`, its lowest thinking setting,
* and the provider uses it in place of `disabled` for that model.
*/
thinking: z.union([z.discriminatedUnion("type", [
z.object({
/** for Sonnet 4.6, Opus 4.6, and newer models */
type: z.literal("adaptive"),
/**
* Controls whether thinking content is included in the response.
* - `"omitted"`: Thinking blocks are present but text is empty (default for Opus 4.7+).
* - `"summarized"`: Thinking content is returned. Required to see reasoning output.
* - `"updates"`: Thinking updates are returned between tool calls.
*/
display: z.enum([
"omitted",
"summarized",
"updates"
]).optional(),
/**
* Controls how thinking blocks are bound to an assistant prefix.
*
* Requires the `thinking-binding-controls-2026-08-01` beta,
* which is added automatically.
*/
blockBinding: anthropicThinkingBlockBinding.optional()
}),
z.object({
/** for models before Opus 4.6, except Sonnet 4.6 still supports it */
type: z.literal("enabled"),
budgetTokens: z.number().optional()
}),
z.object({ type: z.literal("disabled") }),
z.object({
/**
* for `claude-sonnet-5-5`: no upfront thinking, but progress notes
* between tool calls are returned as summarized thinking blocks.
* Only supported at `low`, `medium`, and `high` effort.
*/
type: z.literal("between_tools") })
]), z.object({ blockBinding: anthropicThinkingBlockBinding })]).optional(),
/**
* Whether to disable parallel function calling during tool use. Default is false.
* When set to true, Claude will use at most one tool per response.
*/
disableParallelToolUse: z.boolean().optional(),
/**
* Cache control settings for this message.
* See https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
*/
cacheControl: z.object({
type: z.literal("ephemeral"),
ttl: z.union([z.literal("5m"), z.literal("1h")]).optional()
}).optional(),
/**
* Metadata to include with the request.
*
* See https://platform.claude.com/docs/en/api/messages/create for details.
*/
metadata: z.object({
/**
* An external identifier for the user associated with the request.
*
* Should be a UUID, hash value, or other opaque identifier.
* Must not contain PII (name, email, phone number, etc.).
*/
userId: z.string().optional() }).optional(),
/**
* MCP servers to be utilized in this request.
*/
mcpServers: z.array(z.object({
type: z.literal("url"),
name: z.string(),
url: z.string(),
authorizationToken: z.string().nullish(),
toolConfiguration: z.object({
enabled: z.boolean().nullish(),
allowedTools: z.array(z.string()).nullish()
}).nullish()
})).optional(),
/**
* Agent Skills configuration. Skills enable Claude to perform specialized tasks
* like document processing (PPTX, DOCX, PDF, XLSX) and data analysis.
* Requires code execution tool to be enabled.
*/
container: z.object({
id: z.string().optional(),
skills: z.array(z.object({
type: z.union([z.literal("anthropic"), z.literal("custom")]),
skillId: z.string(),
version: z.string().optional()
})).optional()
}).optional(),
/**
* Whether to enable fine-grained (eager) streaming of tool call inputs
* and structured outputs for every function tool in the request. When
* true (the default), each function tool receives a default of
* `eager_input_streaming: true` unless it explicitly sets
* `providerOptions.anthropic.eagerInputStreaming`.
*
* @default true
*/
toolStreaming: z.boolean().optional(),
/**
* Controls how much effort the model spends on thinking, text responses,
* and tool calls. On models that always use adaptive thinking
* (e.g. `claude-opus-5-5`), effort is the main lever for latency and cost.
*
* The API default is `high` for most models and `medium` for `claude-opus-5-5`.
*/
effort: z.enum([
"low",
"medium",
"high",
"xhigh",
"max"
]).optional(),
/**
* Task budget for agentic turns. Informs the model of the total token budget
* available for the current task, allowing it to prioritize work and wind down
* gracefully as the budget is consumed.
*
* Advisory only — does not enforce a hard token limit.
*/
taskBudget: z.object({
type: z.literal("tokens"),
total: z.number().int().min(2e4),
remaining: z.number().int().min(0).optional()
}).optional(),
/**
* Enable fast mode for faster inference (2.5x faster output token speeds).
* Only supported with claude-opus-4-6.
*/
speed: z.enum(["fast", "standard"]).optional(),
/**
* Controls where model inference runs for this request.
*
* - `"global"`: Inference may run in any available geography (default).
* - `"us"`: Inference runs only in US-based infrastructure.
*
* See https://platform.claude.com/docs/en/build-with-claude/data-residency
*/
inferenceGeo: z.enum(["us", "global"]).optional(),
/**
* Server-side fallback configuration.
*
* When the primary model's safety classifiers block a turn, the API
* automatically retries it server-side on a fallback model. A
* `content-filter` finish reason means the fallback(s) refused as well.
*
* - `'default'` (recommended): the API routes the retry to Anthropic's
* recommended fallback model based on the refusal category. Requires the
* `server-side-fallback-2026-07-01` beta, which is added automatically.
* - Array form: an explicit fallback chain. Each entry is merged into the
* request as a direct request to that entry's model, so it must be
* formatted accordingly: `model` is required, and an entry may
* additionally override `max_tokens`, `thinking`, `output_config`, and
* `speed` for that attempt only (`speed` additionally requires the speed
* beta). The value is passed through to the API as-is, and the
* `server-side-fallback-2026-06-01` beta is added automatically.
*/
fallbacks: z.union([z.literal("default"), z.array(z.object({
model: z.string(),
max_tokens: z.number().int().optional(),
thinking: z.record(z.string(), z.unknown()).optional(),
output_config: z.record(z.string(), z.unknown()).optional(),
speed: z.enum(["fast", "standard"]).optional()
}))]).optional(),
/**
* A set of beta features to enable.
* Allow a provider to receive the full `betas` set if it needs it.
*/
anthropicBeta: z.array(z.string()).optional(),
/**
* Server-side safeguards to run as part of the request.
*
* `dangerous_tool_use` asks the API to classify every `tool_use` block in
* the response for dangerous actions (the check Claude Code's auto mode
* relies on). The per-call verdicts are returned in
* `providerMetadata.anthropic.safeguardResults`, keyed by tool call id.
* `classifierContext` is passed through to the API as `classifier_context`.
* The `dangerous-tool-use-2026-09-03` beta is added automatically.
*/
safeguards: z.array(z.object({
type: z.literal("dangerous_tool_use"),
classifierContext: z.record(z.string(), z.unknown()).optional()
})).optional(),
contextManagement: z.object({ edits: z.array(z.discriminatedUnion("type", [
z.object({
type: z.literal("clear_tool_uses_20250919"),
trigger: z.discriminatedUnion("type", [z.object({
type: z.literal("input_tokens"),
value: z.number()
}), z.object({
type: z.literal("tool_uses"),
value: z.number()
})]).optional(),
keep: z.object({
type: z.literal("tool_uses"),
value: z.number()
}).optional(),
clearAtLeast: z.object({
type: z.literal("input_tokens"),
value: z.number()
}).optional(),
clearToolInputs: z.boolean().optional(),
excludeTools: z.array(z.string()).optional()
}),
z.object({
type: z.literal("clear_thinking_20251015"),
keep: z.union([z.literal("all"), z.object({
type: z.literal("thinking_turns"),
value: z.number()
})]).optional()
}),
z.object({
type: z.literal("compact_20260112"),
trigger: z.object({
type: z.literal("input_tokens"),
value: z.number()
}).optional(),
pauseAfterCompaction: z.boolean().optional(),
instructions: z.string().optional()
})
])) }).optional()
}));
});
var MAX_CACHE_BREAKPOINTS$1 = 4;
function getCacheControl$2(providerMetadata, providerOptionsName) {
var _a, _b, _c;
const custom = providerMetadata == null ? void 0 : providerMetadata[providerOptionsName];
const anthropic2 = providerMetadata == null ? void 0 : providerMetadata.anthropic;
return (_c = (_b = (_a = custom == null ? void 0 : custom.cacheControl) != null ? _a : custom == null ? void 0 : custom.cache_control) != null ? _b : anthropic2 == null ? void 0 : anthropic2.cacheControl) != null ? _c : anthropic2 == null ? void 0 : anthropic2.cache_control;
}
var CacheControlValidator$1 = class {
constructor(providerOptionsName = "anthropic") {
this.providerOptionsName = providerOptionsName;
this.breakpointCount = 0;
this.warnings = [];
}
getCacheControl(providerMetadata, context) {
const cacheControlValue = getCacheControl$2(providerMetadata, this.providerOptionsName);
if (!cacheControlValue) return;
if (!context.canCache) {
this.warnings.push({
type: "unsupported",
feature: "cache_control on non-cacheable context",
details: `cache_control cannot be set on ${context.type}. It will be ignored.`
});
return;
}
this.breakpointCount++;
if (this.breakpointCount > MAX_CACHE_BREAKPOINTS$1) {
this.warnings.push({
type: "unsupported",
feature: "cacheControl breakpoint limit",
details: `Maximum ${MAX_CACHE_BREAKPOINTS$1} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`
});
return;
}
return cacheControlValue;
}
getWarnings() {
return this.warnings;
}
};
var advisor_20260301ArgsSchema = lazySchema$1(() => zodSchema$2(z.object({
model: z.string(),
maxUses: z.number().optional(),
caching: z.object({
type: z.literal("ephemeral"),
ttl: z.union([z.literal("5m"), z.literal("1h")])
}).optional()
})));
var advisor_20260301OutputSchema = lazySchema$1(() => zodSchema$2(z.discriminatedUnion("type", [
z.object({
type: z.literal("advisor_result"),
text: z.string()
}),
z.object({
type: z.literal("advisor_redacted_result"),
encryptedContent: z.string()
}),
z.object({
type: z.literal("advisor_tool_result_error"),
errorCode: z.string()
})
])));
var factory = createProviderToolFactoryWithOutputSchema({
id: "anthropic.advisor_20260301",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({}).strict())),
outputSchema: advisor_20260301OutputSchema,
supportsDeferredResults: true
});
var advisor_20260301 = (args) => {
return factory(args);
};
var computerToolset_20260801Members = [
"screenshot",
"zoom",
"left_click",
"right_click",
"middle_click",
"double_click",
"triple_click",
"left_click_drag",
"mouse_move",
"left_mouse_down",
"left_mouse_up",
"cursor_position",
"scroll",
"type",
"key",
"hold_key",
"wait"
];
var computerToolset_20260801InputSchema = lazySchema$1(() => zodSchema$2(z.object({
action: z.enum(computerToolset_20260801Members),
coordinate: z.tuple([z.number().int(), z.number().int()]).optional(),
duration: z.number().optional(),
region: z.tuple([
z.number().int(),
z.number().int(),
z.number().int(),
z.number().int()
]).optional(),
repeat: z.number().int().optional(),
scroll_amount: z.number().optional(),
scroll_direction: z.enum([
"up",
"down",
"left",
"right"
]).optional(),
start_coordinate: z.tuple([z.number().int(), z.number().int()]).optional(),
text: z.string().optional()
})));
var computerToolset_20260801ArgsSchema = lazySchema$1(() => zodSchema$2(z.object({ configs: z.partialRecord(z.enum(computerToolset_20260801Members), z.object({
enabled: z.boolean().optional(),
deferLoading: z.boolean().optional()
})).optional() })));
var computerToolset_20260801 = createProviderToolFactory$1({
id: "anthropic.computer_toolset_20260801",
inputSchema: computerToolset_20260801InputSchema
});
var textEditor_20250728ArgsSchema = lazySchema$1(() => zodSchema$2(z.object({ maxCharacters: z.number().optional() })));
var factory2 = createProviderToolFactory$1({
id: "anthropic.text_editor_20250728",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({
command: z.enum([
"view",
"create",
"str_replace",
"insert"
]),
path: z.string(),
file_text: z.string().optional(),
insert_line: z.number().int().optional(),
new_str: z.string().optional(),
insert_text: z.string().optional(),
old_str: z.string().optional(),
view_range: z.array(z.number().int()).optional()
})))
});
var textEditor_20250728 = (args = {}) => {
return factory2(args);
};
var webSearch_20260209ArgsSchema = lazySchema$1(() => zodSchema$2(z.object({
maxUses: z.number().optional(),
allowedDomains: z.array(z.string()).optional(),
blockedDomains: z.array(z.string()).optional(),
userLocation: z.object({
type: z.literal("approximate"),
city: z.string().optional(),
region: z.string().optional(),
country: z.string().optional(),
timezone: z.string().optional()
}).optional()
})));
var webSearch_20260209OutputSchema = lazySchema$1(() => zodSchema$2(z.array(z.object({
url: z.string(),
title: z.string().nullable(),
pageAge: z.string().nullable(),
encryptedContent: z.string(),
type: z.literal("web_search_result")
}))));
var factory3 = createProviderToolFactoryWithOutputSchema({
id: "anthropic.web_search_20260209",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({ query: z.string() }))),
outputSchema: webSearch_20260209OutputSchema,
supportsDeferredResults: true
});
var webSearch_20260209 = (args = {}) => {
return factory3(args);
};
var webSearch_20250305ArgsSchema = lazySchema$1(() => zodSchema$2(z.object({
maxUses: z.number().optional(),
allowedDomains: z.array(z.string()).optional(),
blockedDomains: z.array(z.string()).optional(),
userLocation: z.object({
type: z.literal("approximate"),
city: z.string().optional(),
region: z.string().optional(),
country: z.string().optional(),
timezone: z.string().optional()
}).optional()
})));
var webSearch_20250305OutputSchema = lazySchema$1(() => zodSchema$2(z.array(z.object({
url: z.string(),
title: z.string().nullable(),
pageAge: z.string().nullable(),
encryptedContent: z.string(),
type: z.literal("web_search_result")
}))));
var factory4 = createProviderToolFactoryWithOutputSchema({
id: "anthropic.web_search_20250305",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({ query: z.string() }))),
outputSchema: webSearch_20250305OutputSchema,
supportsDeferredResults: true
});
var webSearch_20250305 = (args = {}) => {
return factory4(args);
};
var webFetch_20260209ArgsSchema = lazySchema$1(() => zodSchema$2(z.object({
maxUses: z.number().optional(),
allowedDomains: z.array(z.string()).optional(),
blockedDomains: z.array(z.string()).optional(),
citations: z.object({ enabled: z.boolean() }).optional(),
maxContentTokens: z.number().optional()
})));
var webFetch_20260209OutputSchema = lazySchema$1(() => zodSchema$2(z.object({
type: z.literal("web_fetch_result"),
url: z.string(),
content: z.object({
type: z.literal("document"),
title: z.string().nullable(),
citations: z.object({ enabled: z.boolean() }).optional(),
source: z.union([z.object({
type: z.literal("base64"),
mediaType: z.literal("application/pdf"),
data: z.string()
}), z.object({
type: z.literal("text"),
mediaType: z.literal("text/plain"),
data: z.string()
})])
}),
retrievedAt: z.string().nullable()
})));
var factory5 = createProviderToolFactoryWithOutputSchema({
id: "anthropic.web_fetch_20260209",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({ url: z.string() }))),
outputSchema: webFetch_20260209OutputSchema,
supportsDeferredResults: true
});
var webFetch_20260209 = (args = {}) => {
return factory5(args);
};
var webFetch_20250910ArgsSchema = lazySchema$1(() => zodSchema$2(z.object({
maxUses: z.number().optional(),
allowedDomains: z.array(z.string()).optional(),
blockedDomains: z.array(z.string()).optional(),
citations: z.object({ enabled: z.boolean() }).optional(),
maxContentTokens: z.number().optional()
})));
var webFetch_20250910OutputSchema = lazySchema$1(() => zodSchema$2(z.object({
type: z.literal("web_fetch_result"),
url: z.string(),
content: z.object({
type: z.literal("document"),
title: z.string().nullable(),
citations: z.object({ enabled: z.boolean() }).optional(),
source: z.union([z.object({
type: z.literal("base64"),
mediaType: z.literal("application/pdf"),
data: z.string()
}), z.object({
type: z.literal("text"),
mediaType: z.literal("text/plain"),
data: z.string()
})])
}),
retrievedAt: z.string().nullable()
})));
var factory6 = createProviderToolFactoryWithOutputSchema({
id: "anthropic.web_fetch_20250910",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({ url: z.string() }))),
outputSchema: webFetch_20250910OutputSchema,
supportsDeferredResults: true
});
var webFetch_20250910 = (args = {}) => {
return factory6(args);
};
async function prepareTools$6({ tools, toolChoice, disableParallelToolUse, cacheControlValidator, supportsStructuredOutput, supportsStrictTools, defaultEagerInputStreaming = false, rejectsForcedToolUse = false }) {
var _a, _b;
tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
const toolWarnings = [];
const betas = /* @__PURE__ */ new Set();
const validator = cacheControlValidator || new CacheControlValidator$1();
if (tools == null) return {
tools: void 0,
toolChoice: void 0,
toolWarnings,
betas
};
const anthropicTools2 = [];
for (const tool of tools) switch (tool.type) {
case "function": {
const cacheControl = validator.getCacheControl(tool.providerOptions, {
type: "tool definition",
canCache: true
});
const anthropicOptions = (_a = tool.providerOptions) == null ? void 0 : _a.anthropic;
const eagerInputStreaming = (_b = anthropicOptions == null ? void 0 : anthropicOptions.eagerInputStreaming) != null ? _b : defaultEagerInputStreaming;
const deferLoading = anthropicOptions == null ? void 0 : anthropicOptions.deferLoading;
const allowedCallers = anthropicOptions == null ? void 0 : anthropicOptions.allowedCallers;
if (!supportsStrictTools && tool.strict != null) toolWarnings.push({
type: "unsupported",
feature: "strict",
details: `Tool '${tool.name}' has strict: ${tool.strict}, but strict mode is not supported by this provider. The strict property will be ignored.`
});
anthropicTools2.push({
name: tool.name,
description: tool.description,
input_schema: tool.inputSchema,
cache_control: cacheControl,
...eagerInputStreaming ? { eager_input_streaming: true } : {},
...supportsStrictTools === true && tool.strict != null ? { strict: tool.strict } : {},
...deferLoading != null ? { defer_loading: deferLoading } : {},
...allowedCallers != null ? { allowed_callers: allowedCallers } : {},
...tool.inputExamples != null ? { input_examples: tool.inputExamples.map((example) => example.input) } : {}
});
if (supportsStructuredOutput === true) betas.add("structured-outputs-2025-11-13");
if (tool.inputExamples != null || allowedCallers != null) betas.add("advanced-tool-use-2025-11-20");
break;
}
case "provider":
switch (tool.id) {
case "anthropic.code_execution_20250522":
betas.add("code-execution-2025-05-22");
anthropicTools2.push({
type: "code_execution_20250522",
name: "code_execution",
cache_control: void 0
});
break;
case "anthropic.code_execution_20250825":
betas.add("code-execution-2025-08-25");
anthropicTools2.push({
type: "code_execution_20250825",
name: "code_execution"
});
break;
case "anthropic.code_execution_20260120":
anthropicTools2.push({
type: "code_execution_20260120",
name: "code_execution"
});
break;
case "anthropic.computer_20250124":
betas.add("computer-use-2025-01-24");
anthropicTools2.push({
name: "computer",
type: "computer_20250124",
display_width_px: tool.args.displayWidthPx,
display_height_px: tool.args.displayHeightPx,
display_number: tool.args.displayNumber,
cache_control: void 0
});
break;
case "anthropic.computer_20251124":
betas.add("computer-use-2025-11-24");
anthropicTools2.push({
name: "computer",
type: "computer_20251124",
display_width_px: tool.args.displayWidthPx,
display_height_px: tool.args.displayHeightPx,
display_number: tool.args.displayNumber,
enable_zoom: tool.args.enableZoom,
cache_control: void 0
});
break;
case "anthropic.computer_toolset_20260801": {
const args = await validateTypes$2({
value: tool.args,
schema: computerToolset_20260801ArgsSchema
});
const configs = args.configs != null ? Object.fromEntries(Object.entries(args.configs).map(([member, config]) => [member, {
...(config == null ? void 0 : config.enabled) != null && { enabled: config.enabled },
...(config == null ? void 0 : config.deferLoading) != null && { defer_loading: config.deferLoading }
}])) : void 0;
anthropicTools2.push({
type: "computer_toolset_20260801",
...configs != null && { configs },
cache_control: void 0
});
break;
}
case "anthropic.computer_20241022":
betas.add("computer-use-2024-10-22");
anthropicTools2.push({
name: "computer",
type: "computer_20241022",
display_width_px: tool.args.displayWidthPx,
display_height_px: tool.args.displayHeightPx,
display_number: tool.args.displayNumber,
cache_control: void 0
});
break;
case "anthropic.text_editor_20250124":
betas.add("computer-use-2025-01-24");
anthropicTools2.push({
name: "str_replace_editor",
type: "text_editor_20250124",
cache_control: void 0
});
break;
case "anthropic.text_editor_20241022":
betas.add("computer-use-2024-10-22");
anthropicTools2.push({
name: "str_replace_editor",
type: "text_editor_20241022",
cache_control: void 0
});
break;
case "anthropic.text_editor_20250429":
betas.add("computer-use-2025-01-24");
anthropicTools2.push({
name: "str_replace_based_edit_tool",
type: "text_editor_20250429",
cache_control: void 0
});
break;
case "anthropic.text_editor_20250728": {
const args = await validateTypes$2({
value: tool.args,
schema: textEditor_20250728ArgsSchema
});
anthropicTools2.push({
name: "str_replace_based_edit_tool",
type: "text_editor_20250728",
max_characters: args.maxCharacters,
cache_control: void 0
});
break;
}
case "anthropic.bash_20250124":
betas.add("computer-use-2025-01-24");
anthropicTools2.push({
name: "bash",
type: "bash_20250124",
cache_control: void 0
});
break;
case "anthropic.bash_20241022":
betas.add("computer-use-2024-10-22");
anthropicTools2.push({
name: "bash",
type: "bash_20241022",
cache_control: void 0
});
break;
case "anthropic.memory_20250818":
betas.add("context-management-2025-06-27");
anthropicTools2.push({
name: "memory",
type: "memory_20250818"
});
break;
case "anthropic.web_fetch_20250910": {
betas.add("web-fetch-2025-09-10");
const args = await validateTypes$2({
value: tool.args,
schema: webFetch_20250910ArgsSchema
});
anthropicTools2.push({
type: "web_fetch_20250910",
name: "web_fetch",
max_uses: args.maxUses,
allowed_domains: args.allowedDomains,
blocked_domains: args.blockedDomains,
citations: args.citations,
max_content_tokens: args.maxContentTokens,
cache_control: void 0
});
break;
}
case "anthropic.web_fetch_20260209": {
betas.add("code-execution-web-tools-2026-02-09");
const args = await validateTypes$2({
value: tool.args,
schema: webFetch_20260209ArgsSchema
});
anthropicTools2.push({
type: "web_fetch_20260209",
name: "web_fetch",
max_uses: args.maxUses,
allowed_domains: args.allowedDomains,
blocked_domains: args.blockedDomains,
citations: args.citations,
max_content_tokens: args.maxContentTokens,
cache_control: void 0
});
break;
}
case "anthropic.web_search_20250305": {
const args = await validateTypes$2({
value: tool.args,
schema: webSearch_20250305ArgsSchema
});
anthropicTools2.push({
type: "web_search_20250305",
name: "web_search",
max_uses: args.maxUses,
allowed_domains: args.allowedDomains,
blocked_domains: args.blockedDomains,
user_location: args.userLocation,
cache_control: void 0
});
break;
}
case "anthropic.web_search_20260209": {
betas.add("code-execution-web-tools-2026-02-09");
const args = await validateTypes$2({
value: tool.args,
schema: webSearch_20260209ArgsSchema
});
anthropicTools2.push({
type: "web_search_20260209",
name: "web_search",
max_uses: args.maxUses,
allowed_domains: args.allowedDomains,
blocked_domains: args.blockedDomains,
user_location: args.userLocation,
cache_control: void 0
});
break;
}
case "anthropic.tool_search_regex_20251119":
anthropicTools2.push({
type: "tool_search_tool_regex_20251119",
name: "tool_search_tool_regex"
});
break;
case "anthropic.tool_search_bm25_20251119":
anthropicTools2.push({
type: "tool_search_tool_bm25_20251119",
name: "tool_search_tool_bm25"
});
break;
case "anthropic.advisor_20260301": {
betas.add("advisor-tool-2026-03-01");
const args = await validateTypes$2({
value: tool.args,
schema: advisor_20260301ArgsSchema
});
anthropicTools2.push({
type: "advisor_20260301",
name: "advisor",
model: args.model,
...args.maxUses !== void 0 && { max_uses: args.maxUses },
...args.caching !== void 0 && { caching: args.caching }
});
break;
}
default: toolWarnings.push({
type: "unsupported",
feature: `provider-defined tool ${tool.id}`
});
}
break;
default: toolWarnings.push({
type: "unsupported",
feature: `tool ${tool}`
});
}
if (toolChoice == null) return {
tools: anthropicTools2,
toolChoice: disableParallelToolUse ? {
type: "auto",
disable_parallel_tool_use: disableParallelToolUse
} : void 0,
toolWarnings,
betas
};
const type = toolChoice.type;
switch (type) {
case "auto": return {
tools: anthropicTools2,
toolChoice: {
type: "auto",
disable_parallel_tool_use: disableParallelToolUse
},
toolWarnings,
betas
};
case "required":
if (rejectsForcedToolUse) {
toolWarnings.push({
type: "unsupported",
feature: "toolChoice",
details: `toolChoice 'required' is not supported with this model or thinking configuration. Using 'auto' instead. Instruct the model to use a tool in the prompt and verify that a tool call was made.`
});
return {
tools: anthropicTools2,
toolChoice: {
type: "auto",
disable_parallel_tool_use: disableParallelToolUse
},
toolWarnings,
betas
};
}
return {
tools: anthropicTools2,
toolChoice: {
type: "any",
disable_parallel_tool_use: disableParallelToolUse
},
toolWarnings,
betas
};
case "none": return {
tools: anthropicTools2,
toolChoice: { type: "none" },
toolWarnings,
betas
};
case "tool":
if (rejectsForcedToolUse) {
toolWarnings.push({
type: "unsupported",
feature: "toolChoice",
details: `toolChoice 'tool' is not supported with this model or thinking configuration. Only the '${toolChoice.toolName}' tool is sent with 'auto' tool choice. Instruct the model to use the tool in the prompt and verify that a tool call was made.`
});
return {
tools: anthropicTools2.filter((tool) => "name" in tool && tool.name === toolChoice.toolName),
toolChoice: {
type: "auto",
disable_parallel_tool_use: disableParallelToolUse
},
toolWarnings,
betas
};
}
return {
tools: anthropicTools2,
toolChoice: {
type: "tool",
name: toolChoice.toolName,
disable_parallel_tool_use: disableParallelToolUse
},
toolWarnings,
betas
};
default: throw new UnsupportedFunctionalityError$2({ functionality: `tool choice type: ${type}` });
}
}
function convertAnthropicMessagesUsage({ usage, rawUsage }) {
var _a, _b, _c, _d, _e;
const cacheCreationTokens = (_a = usage.cache_creation_input_tokens) != null ? _a : 0;
const cacheReadTokens = (_b = usage.cache_read_input_tokens) != null ? _b : 0;
const reasoningTokens = (_d = (_c = usage.output_tokens_details) == null ? void 0 : _c.thinking_tokens) != null ? _d : void 0;
let inputTokens;
let outputTokens;
const servedByFallback = (_e = usage.iterations) == null ? void 0 : _e.some((iter) => iter.type === "fallback_message");
if (usage.iterations && usage.iterations.length > 0 && !servedByFallback) {
const executorIterations = usage.iterations.filter((iter) => iter.type === "compaction" || iter.type === "message");
if (executorIterations.length > 0) {
const totals = executorIterations.reduce((acc, iter) => ({
input: acc.input + iter.input_tokens,
output: acc.output + iter.output_tokens
}), {
input: 0,
output: 0
});
inputTokens = totals.input;
outputTokens = totals.output;
} else {
inputTokens = usage.input_tokens;
outputTokens = usage.output_tokens;
}
} else {
inputTokens = usage.input_tokens;
outputTokens = usage.output_tokens;
}
return {
inputTokens: {
total: inputTokens + cacheCreationTokens + cacheReadTokens,
noCache: inputTokens,
cacheRead: cacheReadTokens,
cacheWrite: cacheCreationTokens
},
outputTokens: {
total: outputTokens,
text: reasoningTokens == null ? void 0 : outputTokens - reasoningTokens,
reasoning: reasoningTokens
},
raw: rawUsage != null ? rawUsage : usage
};
}
var codeExecution_20250522OutputSchema = lazySchema$1(() => zodSchema$2(z.object({
type: z.literal("code_execution_result"),
stdout: z.string(),
stderr: z.string(),
return_code: z.number(),
content: z.array(z.object({
type: z.literal("code_execution_output"),
file_id: z.string()
})).optional().default([])
})));
var factory7 = createProviderToolFactoryWithOutputSchema({
id: "anthropic.code_execution_20250522",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({ code: z.string() }))),
outputSchema: codeExecution_20250522OutputSchema
});
var codeExecution_20250522 = (args = {}) => {
return factory7(args);
};
var codeExecution_20250825OutputSchema = lazySchema$1(() => zodSchema$2(z.discriminatedUnion("type", [
z.object({
type: z.literal("code_execution_result"),
stdout: z.string(),
stderr: z.string(),
return_code: z.number(),
content: z.array(z.object({
type: z.literal("code_execution_output"),
file_id: z.string()
})).optional().default([])
}),
z.object({
type: z.literal("bash_code_execution_result"),
content: z.array(z.object({
type: z.literal("bash_code_execution_output"),
file_id: z.string()
})),
stdout: z.string(),
stderr: z.string(),
return_code: z.number()
}),
z.object({
type: z.literal("bash_code_execution_tool_result_error"),
error_code: z.string()
}),
z.object({
type: z.literal("text_editor_code_execution_tool_result_error"),
error_code: z.string()
}),
z.object({
type: z.literal("text_editor_code_execution_view_result"),
content: z.string(),
file_type: z.string(),
num_lines: z.number().nullable(),
start_line: z.number().nullable(),
total_lines: z.number().nullable()
}),
z.object({
type: z.literal("text_editor_code_execution_create_result"),
is_file_update: z.boolean()
}),
z.object({
type: z.literal("text_editor_code_execution_str_replace_result"),
lines: z.array(z.string()).nullable(),
new_lines: z.number().nullable(),
new_start: z.number().nullable(),
old_lines: z.number().nullable(),
old_start: z.number().nullable()
})
])));
var factory8 = createProviderToolFactoryWithOutputSchema({
id: "anthropic.code_execution_20250825",
inputSchema: lazySchema$1(() => zodSchema$2(z.discriminatedUnion("type", [
z.object({
type: z.literal("programmatic-tool-call"),
code: z.string()
}),
z.object({
type: z.literal("bash_code_execution"),
command: z.string()
}),
z.discriminatedUnion("command", [
z.object({
type: z.literal("text_editor_code_execution"),
command: z.literal("view"),
path: z.string()
}),
z.object({
type: z.literal("text_editor_code_execution"),
command: z.literal("create"),
path: z.string(),
file_text: z.string().nullish()
}),
z.object({
type: z.literal("text_editor_code_execution"),
command: z.literal("str_replace"),
path: z.string(),
old_str: z.string(),
new_str: z.string()
})
])
]))),
outputSchema: codeExecution_20250825OutputSchema,
supportsDeferredResults: true
});
var codeExecution_20250825 = (args = {}) => {
return factory8(args);
};
var codeExecution_20260120OutputSchema = lazySchema$1(() => zodSchema$2(z.discriminatedUnion("type", [
z.object({
type: z.literal("code_execution_result"),
stdout: z.string(),
stderr: z.string(),
return_code: z.number(),
content: z.array(z.object({
type: z.literal("code_execution_output"),
file_id: z.string()
})).optional().default([])
}),
z.object({
type: z.literal("encrypted_code_execution_result"),
encrypted_stdout: z.string(),
stderr: z.string(),
return_code: z.number(),
content: z.array(z.object({
type: z.literal("code_execution_output"),
file_id: z.string()
})).optional().default([])
}),
z.object({
type: z.literal("bash_code_execution_result"),
content: z.array(z.object({
type: z.literal("bash_code_execution_output"),
file_id: z.string()
})),
stdout: z.string(),
stderr: z.string(),
return_code: z.number()
}),
z.object({
type: z.literal("bash_code_execution_tool_result_error"),
error_code: z.string()
}),
z.object({
type: z.literal("text_editor_code_execution_tool_result_error"),
error_code: z.string()
}),
z.object({
type: z.literal("text_editor_code_execution_view_result"),
content: z.string(),
file_type: z.string(),
num_lines: z.number().nullable(),
start_line: z.number().nullable(),
total_lines: z.number().nullable()
}),
z.object({
type: z.literal("text_editor_code_execution_create_result"),
is_file_update: z.boolean()
}),
z.object({
type: z.literal("text_editor_code_execution_str_replace_result"),
lines: z.array(z.string()).nullable(),
new_lines: z.number().nullable(),
new_start: z.number().nullable(),
old_lines: z.number().nullable(),
old_start: z.number().nullable()
})
])));
var factory9 = createProviderToolFactoryWithOutputSchema({
id: "anthropic.code_execution_20260120",
inputSchema: lazySchema$1(() => zodSchema$2(z.discriminatedUnion("type", [
z.object({
type: z.literal("programmatic-tool-call"),
code: z.string()
}),
z.object({
type: z.literal("bash_code_execution"),
command: z.string()
}),
z.discriminatedUnion("command", [
z.object({
type: z.literal("text_editor_code_execution"),
command: z.literal("view"),
path: z.string()
}),
z.object({
type: z.literal("text_editor_code_execution"),
command: z.literal("create"),
path: z.string(),
file_text: z.string().nullish()
}),
z.object({
type: z.literal("text_editor_code_execution"),
command: z.literal("str_replace"),
path: z.string(),
old_str: z.string(),
new_str: z.string()
})
])
]))),
outputSchema: codeExecution_20260120OutputSchema,
supportsDeferredResults: true
});
var codeExecution_20260120 = (args = {}) => {
return factory9(args);
};
var toolSearchRegex_20251119OutputSchema = lazySchema$1(() => zodSchema$2(z.array(z.object({
type: z.literal("tool_reference"),
toolName: z.string()
}))));
var factory10 = createProviderToolFactoryWithOutputSchema({
id: "anthropic.tool_search_regex_20251119",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({
/**
* A regex pattern to search for tools.
* Uses Python re.search() syntax. Maximum 200 characters.
*
* Examples:
* - "weather" - matches tool names/descriptions containing "weather"
* - "get_.*_data" - matches tools like get_user_data, get_weather_data
* - "database.*query|query.*database" - OR patterns for flexibility
* - "(?i)slack" - case-insensitive search
*/
pattern: z.string(),
/**
* Maximum number of tools to return. Optional.
*/
limit: z.number().optional()
}))),
outputSchema: toolSearchRegex_20251119OutputSchema,
supportsDeferredResults: true
});
var toolSearchRegex_20251119 = (args = {}) => {
return factory10(args);
};
function convertToString(data) {
if (typeof data === "string") return new TextDecoder().decode(convertBase64ToUint8Array$1(data));
if (data instanceof Uint8Array) return new TextDecoder().decode(data);
if (data instanceof URL) throw new UnsupportedFunctionalityError$2({ functionality: "URL-based text documents are not supported for citations" });
throw new UnsupportedFunctionalityError$2({ functionality: `unsupported data type for text documents: ${typeof data}` });
}
function isUrlData(data) {
return data instanceof URL || isUrlString(data);
}
function isUrlString(data) {
return typeof data === "string" && /^https?:\/\//i.test(data);
}
function getUrlString(data) {
return data instanceof URL ? data.toString() : data;
}
async function extractErrorValue(value) {
if (typeof value === "string") {
const result = await safeParseJSON$2({ text: value });
if (result.success && typeof result.value === "object" && result.value !== null) return result.value;
return { errorCode: "unavailable" };
}
if (typeof value === "object" && value !== null) return value;
return {};
}
async function convertToAnthropicMessagesPrompt({ prompt, sendReasoning, warnings, cacheControlValidator, toolNameMapping, toolsetNames = {}, convertMediaPart }) {
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v;
const betas = /* @__PURE__ */ new Set();
const blocks = groupIntoBlocks(prompt);
const validator = cacheControlValidator || new CacheControlValidator$1();
let system = void 0;
const messages = [];
let lastUserMessageIndex = -1;
async function shouldEnableCitations(providerMetadata) {
var _a2, _b2;
const anthropicOptions = await parseProviderOptions$1({
provider: "anthropic",
providerOptions: providerMetadata,
schema: anthropicFilePartProviderOptions
});
return (_b2 = (_a2 = anthropicOptions == null ? void 0 : anthropicOptions.citations) == null ? void 0 : _a2.enabled) != null ? _b2 : false;
}
async function getDocumentMetadata(providerMetadata) {
const anthropicOptions = await parseProviderOptions$1({
provider: "anthropic",
providerOptions: providerMetadata,
schema: anthropicFilePartProviderOptions
});
return {
title: anthropicOptions == null ? void 0 : anthropicOptions.title,
context: anthropicOptions == null ? void 0 : anthropicOptions.context
};
}
for (let i = 0; i < blocks.length; i++) {
const block = blocks[i];
const isLastBlock = i === blocks.length - 1;
const type = block.type;
switch (type) {
case "system": {
const systemMessages = [];
let toolChangeCount = 0;
let hasMidConversationOptions = false;
for (const { content: text, providerOptions } of block.messages) {
const systemMessageOptions = await parseProviderOptions$1({
provider: "anthropic",
providerOptions,
schema: anthropicSystemMessageProviderOptions
});
const toolChanges = (_a = systemMessageOptions == null ? void 0 : systemMessageOptions.toolChanges) != null ? _a : [];
const clearAt = systemMessageOptions == null ? void 0 : systemMessageOptions.clearAt;
const effort = systemMessageOptions == null ? void 0 : systemMessageOptions.effort;
const content = [];
if (text !== "" || toolChanges.length === 0 && clearAt == null && effort == null) content.push({
type: "text",
text,
cache_control: validator.getCacheControl(providerOptions, {
type: "system message",
canCache: true
})
});
for (const toolChange of toolChanges) {
toolChangeCount++;
content.push({
type: toolChange.type,
tool: {
type: "tool_reference",
name: toolNameMapping.toProviderToolName(toolChange.toolName)
}
});
}
hasMidConversationOptions || (hasMidConversationOptions = clearAt != null || effort != null);
systemMessages.push({
role: "system",
content,
...clearAt != null && { clear_at: clearAt },
...effort != null && { output_config: { effort } }
});
}
if (i === 0 || system == null && toolChangeCount === 0 && !hasMidConversationOptions) {
if (toolChangeCount > 0) warnings.push({
type: "other",
message: "tool changes on the initial system message are not supported by Anthropic. Configure the initial tool set via the tools option instead. The tool changes have been ignored."
});
for (const message of systemMessages) if (message.content.length === 0 && message.clear_at == null && message.output_config != null) {
messages.push(message);
betas.add("mid-conversation-output-config-2026-07-01");
} else if (message.clear_at != null || message.output_config != null) warnings.push({
type: "other",
message: "clearAt and effort on this initial system message are not supported by Anthropic. Use a separate effort-only system message with empty content to set effort. These options have been ignored."
});
system = systemMessages.flatMap((message) => message.content.filter((part) => part.type === "text"));
} else {
messages.push(...systemMessages);
betas.add("mid-conversation-system-2026-04-07");
if (toolChangeCount > 0) betas.add("mid-conversation-tool-changes-2026-07-01");
if (systemMessages.some((message) => message.clear_at != null)) betas.add("mid-conversation-system-clear-at-2026-08-21");
if (systemMessages.some((message) => message.output_config != null)) betas.add("mid-conversation-output-config-2026-07-01");
}
break;
}
case "user": {
const anthropicContent = [];
for (const message of block.messages) {
const { role, content } = message;
switch (role) {
case "user":
if (content.length > 0) lastUserMessageIndex = messages.length;
for (let j = 0; j < content.length; j++) {
const part = content[j];
const isLastPart = j === content.length - 1;
const cacheControl = (_b = validator.getCacheControl(part.providerOptions, {
type: "user message part",
canCache: true
})) != null ? _b : isLastPart ? validator.getCacheControl(message.providerOptions, {
type: "user message",
canCache: true
}) : void 0;
switch (part.type) {
case "text":
anthropicContent.push({
type: "text",
text: part.text,
cache_control: cacheControl
});
break;
case "file": {
const customContent = await (convertMediaPart == null ? void 0 : convertMediaPart(part));
if (customContent != null) {
anthropicContent.push({
...customContent,
cache_control: cacheControl
});
break;
}
if (part.mediaType.startsWith("image/")) anthropicContent.push({
type: "image",
source: isUrlData(part.data) ? {
type: "url",
url: getUrlString(part.data)
} : {
type: "base64",
media_type: part.mediaType === "image/*" ? "image/jpeg" : part.mediaType,
data: convertToBase64$1(part.data)
},
cache_control: cacheControl
});
else if (part.mediaType === "application/pdf") {
betas.add("pdfs-2024-09-25");
const enableCitations = await shouldEnableCitations(part.providerOptions);
const metadata = await getDocumentMetadata(part.providerOptions);
anthropicContent.push({
type: "document",
source: isUrlData(part.data) ? {
type: "url",
url: getUrlString(part.data)
} : {
type: "base64",
media_type: "application/pdf",
data: convertToBase64$1(part.data)
},
title: (_c = metadata.title) != null ? _c : part.filename,
...metadata.context && { context: metadata.context },
...enableCitations && { citations: { enabled: true } },
cache_control: cacheControl
});
} else if (part.mediaType === "text/plain") {
const enableCitations = await shouldEnableCitations(part.providerOptions);
const metadata = await getDocumentMetadata(part.providerOptions);
anthropicContent.push({
type: "document",
source: isUrlData(part.data) ? {
type: "url",
url: getUrlString(part.data)
} : {
type: "text",
media_type: "text/plain",
data: convertToString(part.data)
},
title: (_d = metadata.title) != null ? _d : part.filename,
...metadata.context && { context: metadata.context },
...enableCitations && { citations: { enabled: true } },
cache_control: cacheControl
});
} else throw new UnsupportedFunctionalityError$2({ functionality: `media type: ${part.mediaType}` });
break;
}
}
}
break;
case "tool":
for (let i2 = 0; i2 < content.length; i2++) {
const part = content[i2];
if (part.type === "tool-approval-response") continue;
const output = part.output;
const outputProviderOptions = "providerOptions" in output ? output.providerOptions : output.type === "content" ? (_e = output.value.find((contentPart) => contentPart.providerOptions != null)) == null ? void 0 : _e.providerOptions : void 0;
const isLastPart = i2 === content.length - 1;
const cacheControl = (_g = (_f = validator.getCacheControl(part.providerOptions, {
type: "tool result part",
canCache: true
})) != null ? _f : validator.getCacheControl(outputProviderOptions, {
type: "tool result output",
canCache: true
})) != null ? _g : isLastPart ? validator.getCacheControl(message.providerOptions, {
type: "tool result message",
canCache: true
}) : void 0;
let contentValue;
switch (output.type) {
case "content":
contentValue = output.value.map((contentPart) => {
var _a2;
switch (contentPart.type) {
case "text": return {
type: "text",
text: contentPart.text
};
case "image-data": return {
type: "image",
source: {
type: "base64",
media_type: contentPart.mediaType,
data: contentPart.data
}
};
case "image-url": return {
type: "image",
source: {
type: "url",
url: contentPart.url
}
};
case "file-url": return {
type: "document",
source: {
type: "url",
url: contentPart.url
}
};
case "file-data":
if (contentPart.mediaType === "application/pdf") {
betas.add("pdfs-2024-09-25");
return {
type: "document",
source: {
type: "base64",
media_type: contentPart.mediaType,
data: contentPart.data
}
};
}
warnings.push({
type: "other",
message: `unsupported tool content part type: ${contentPart.type} with media type: ${contentPart.mediaType}`
});
return;
case "custom": {
const anthropicOptions = (_a2 = contentPart.providerOptions) == null ? void 0 : _a2.anthropic;
if ((anthropicOptions == null ? void 0 : anthropicOptions.type) === "tool-reference") return {
type: "tool_reference",
tool_name: anthropicOptions.toolName
};
warnings.push({
type: "other",
message: `unsupported custom tool content part`
});
return;
}
default:
warnings.push({
type: "other",
message: `unsupported tool content part type: ${contentPart.type}`
});
return;
}
}).filter(isNonNullable);
break;
case "text":
case "error-text":
contentValue = output.value;
break;
case "execution-denied":
contentValue = (_h = output.reason) != null ? _h : "Tool call execution denied.";
break;
default: contentValue = JSON.stringify(output.value);
}
const toolsetName = getAnthropicToolsetName({
toolName: part.toolName,
providerOptions: part.providerOptions,
toolsetNames
});
anthropicContent.push({
type: "tool_result",
tool_use_id: part.toolCallId,
...toolsetName != null && { toolset_name: toolsetName },
content: contentValue,
is_error: output.type === "error-text" || output.type === "error-json" ? true : void 0,
cache_control: cacheControl
});
}
break;
default: throw new Error(`Unsupported role: ${role}`);
}
}
messages.push({
role: "user",
content: anthropicContent
});
break;
}
case "assistant": {
const anthropicContent = [];
const mcpToolUseIds = /* @__PURE__ */ new Set();
for (let j = 0; j < block.messages.length; j++) {
const message = block.messages[j];
const isLastMessage = j === block.messages.length - 1;
const { content } = message;
for (let k = 0; k < content.length; k++) {
const part = content[k];
const isLastContentPart = k === content.length - 1;
const cacheControl = (_i = validator.getCacheControl(part.providerOptions, {
type: "assistant message part",
canCache: true
})) != null ? _i : isLastContentPart ? validator.getCacheControl(message.providerOptions, {
type: "assistant message",
canCache: true
}) : void 0;
switch (part.type) {
case "text": {
const textMetadata = (_j = part.providerOptions) == null ? void 0 : _j.anthropic;
if ((textMetadata == null ? void 0 : textMetadata.type) === "compaction") anthropicContent.push({
type: "compaction",
content: part.text,
cache_control: cacheControl
});
else anthropicContent.push({
type: "text",
text: isLastBlock && isLastMessage && isLastContentPart ? part.text.trim() : part.text,
...(textMetadata == null ? void 0 : textMetadata.citations) != null && { citations: textMetadata.citations },
cache_control: cacheControl
});
break;
}
case "reasoning":
if (sendReasoning) {
const reasoningMetadata = await parseProviderOptions$1({
provider: "anthropic",
providerOptions: part.providerOptions,
schema: anthropicReasoningMetadataSchema
});
if (reasoningMetadata != null) {
if (reasoningMetadata.signature != null) {
validator.getCacheControl(part.providerOptions, {
type: "thinking block",
canCache: false
});
anthropicContent.push({
type: "thinking",
thinking: part.text,
signature: reasoningMetadata.signature
});
} else if (reasoningMetadata.redactedData != null) {
validator.getCacheControl(part.providerOptions, {
type: "redacted thinking block",
canCache: false
});
anthropicContent.push({
type: "redacted_thinking",
data: reasoningMetadata.redactedData
});
} else warnings.push({
type: "other",
message: "unsupported reasoning metadata"
});
} else warnings.push({
type: "other",
message: "unsupported reasoning metadata"
});
} else warnings.push({
type: "other",
message: "sending reasoning content is disabled for this model"
});
break;
case "tool-call": {
const caller = getAnthropicCaller(part.providerOptions);
if (part.providerExecuted) {
const providerToolName = toolNameMapping.toProviderToolName(part.toolName);
if (((_l = (_k = part.providerOptions) == null ? void 0 : _k.anthropic) == null ? void 0 : _l.type) === "mcp-tool-use") {
mcpToolUseIds.add(part.toolCallId);
const serverName = (_n = (_m = part.providerOptions) == null ? void 0 : _m.anthropic) == null ? void 0 : _n.serverName;
if (serverName == null || typeof serverName !== "string") {
warnings.push({
type: "other",
message: "mcp tool use server name is required and must be a string"
});
break;
}
anthropicContent.push({
type: "mcp_tool_use",
id: part.toolCallId,
name: part.toolName,
input: part.input,
server_name: serverName,
cache_control: cacheControl
});
} else if (providerToolName === "code_execution" && part.input != null && typeof part.input === "object" && "type" in part.input && typeof part.input.type === "string" && (part.input.type === "bash_code_execution" || part.input.type === "text_editor_code_execution")) {
const { type: subtoolName, ...input } = part.input;
anthropicContent.push({
type: "server_tool_use",
id: part.toolCallId,
name: subtoolName,
input,
...caller && { caller },
cache_control: cacheControl
});
} else if (providerToolName === "code_execution" && part.input != null && typeof part.input === "object" && "type" in part.input && part.input.type === "programmatic-tool-call") {
const { type: _, ...inputWithoutType } = part.input;
anthropicContent.push({
type: "server_tool_use",
id: part.toolCallId,
name: "code_execution",
input: inputWithoutType,
...caller && { caller },
cache_control: cacheControl
});
} else if (providerToolName === "code_execution" || providerToolName === "web_fetch" || providerToolName === "web_search") anthropicContent.push({
type: "server_tool_use",
id: part.toolCallId,
name: providerToolName,
input: part.input,
...caller && { caller },
cache_control: cacheControl
});
else if (providerToolName === "tool_search_tool_regex" || providerToolName === "tool_search_tool_bm25") anthropicContent.push({
type: "server_tool_use",
id: part.toolCallId,
name: providerToolName,
input: part.input,
...caller && { caller },
cache_control: cacheControl
});
else if (providerToolName === "advisor") anthropicContent.push({
type: "server_tool_use",
id: part.toolCallId,
name: "advisor",
input: {},
...caller && { caller },
cache_control: cacheControl
});
else warnings.push({
type: "other",
message: `provider executed tool call for tool ${part.toolName} is not supported`
});
break;
}
const toolsetName = getAnthropicToolsetName({
toolName: part.toolName,
providerOptions: part.providerOptions,
toolsetNames
});
if (toolsetName != null) {
const { action, ...memberInput } = typeof part.input === "object" && part.input !== null && !Array.isArray(part.input) ? part.input : {};
if (typeof action !== "string") {
warnings.push({
type: "other",
message: `toolset tool call for tool ${part.toolName} is missing the action`
});
break;
}
anthropicContent.push({
type: "tool_use",
id: part.toolCallId,
name: action,
toolset_name: toolsetName,
input: memberInput,
...caller && { caller },
cache_control: cacheControl
});
break;
}
anthropicContent.push({
type: "tool_use",
id: part.toolCallId,
name: part.toolName,
input: part.input,
...caller && { caller },
cache_control: cacheControl
});
break;
}
case "tool-result": {
const providerToolName = toolNameMapping.toProviderToolName(part.toolName);
const caller = getAnthropicCaller(part.providerOptions);
if (mcpToolUseIds.has(part.toolCallId)) {
const output = part.output;
if (output.type !== "json" && output.type !== "error-json") {
warnings.push({
type: "other",
message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`
});
break;
}
anthropicContent.push({
type: "mcp_tool_result",
tool_use_id: part.toolCallId,
is_error: output.type === "error-json",
content: output.value,
cache_control: cacheControl
});
} else if (providerToolName === "code_execution") {
const output = part.output;
if (output.type === "error-text" || output.type === "error-json") {
let errorInfo = {};
try {
if (typeof output.value === "string") errorInfo = secureJsonParse$2(output.value);
else if (typeof output.value === "object" && output.value !== null) errorInfo = output.value;
} catch (e) {}
if (errorInfo.type === "code_execution_tool_result_error") anthropicContent.push({
type: "code_execution_tool_result",
tool_use_id: part.toolCallId,
content: {
type: "code_execution_tool_result_error",
error_code: (_o = errorInfo.errorCode) != null ? _o : "unknown"
},
cache_control: cacheControl
});
else anthropicContent.push({
type: "bash_code_execution_tool_result",
tool_use_id: part.toolCallId,
cache_control: cacheControl,
content: {
type: "bash_code_execution_tool_result_error",
error_code: (_p = errorInfo.errorCode) != null ? _p : "unknown"
}
});
break;
}
if (output.type !== "json") {
warnings.push({
type: "other",
message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`
});
break;
}
if (output.value == null || typeof output.value !== "object" || !("type" in output.value) || typeof output.value.type !== "string") {
warnings.push({
type: "other",
message: `provider executed tool result output value is not a valid code execution result for tool ${part.toolName}`
});
break;
}
if (output.value.type === "code_execution_result") {
const codeExecutionOutput = await validateTypes$2({
value: output.value,
schema: codeExecution_20250522OutputSchema
});
anthropicContent.push({
type: "code_execution_tool_result",
tool_use_id: part.toolCallId,
content: {
type: codeExecutionOutput.type,
stdout: codeExecutionOutput.stdout,
stderr: codeExecutionOutput.stderr,
return_code: codeExecutionOutput.return_code,
content: (_q = codeExecutionOutput.content) != null ? _q : []
},
cache_control: cacheControl
});
} else if (output.value.type === "encrypted_code_execution_result") {
const codeExecutionOutput = await validateTypes$2({
value: output.value,
schema: codeExecution_20260120OutputSchema
});
if (codeExecutionOutput.type === "encrypted_code_execution_result") anthropicContent.push({
type: "code_execution_tool_result",
tool_use_id: part.toolCallId,
content: {
type: codeExecutionOutput.type,
encrypted_stdout: codeExecutionOutput.encrypted_stdout,
stderr: codeExecutionOutput.stderr,
return_code: codeExecutionOutput.return_code,
content: (_r = codeExecutionOutput.content) != null ? _r : []
},
cache_control: cacheControl
});
} else {
const codeExecutionOutput = await validateTypes$2({
value: output.value,
schema: codeExecution_20250825OutputSchema
});
if (codeExecutionOutput.type === "code_execution_result") anthropicContent.push({
type: "code_execution_tool_result",
tool_use_id: part.toolCallId,
content: {
type: codeExecutionOutput.type,
stdout: codeExecutionOutput.stdout,
stderr: codeExecutionOutput.stderr,
return_code: codeExecutionOutput.return_code,
content: (_s = codeExecutionOutput.content) != null ? _s : []
},
cache_control: cacheControl
});
else if (codeExecutionOutput.type === "bash_code_execution_result" || codeExecutionOutput.type === "bash_code_execution_tool_result_error") anthropicContent.push({
type: "bash_code_execution_tool_result",
tool_use_id: part.toolCallId,
cache_control: cacheControl,
content: codeExecutionOutput.type === "bash_code_execution_result" ? {
type: codeExecutionOutput.type,
stdout: codeExecutionOutput.stdout,
stderr: codeExecutionOutput.stderr,
return_code: codeExecutionOutput.return_code,
content: codeExecutionOutput.content
} : codeExecutionOutput
});
else anthropicContent.push({
type: "text_editor_code_execution_tool_result",
tool_use_id: part.toolCallId,
cache_control: cacheControl,
content: codeExecutionOutput
});
}
break;
}
if (providerToolName === "web_fetch") {
const output = part.output;
if (output.type === "error-json") {
anthropicContent.push({
type: "web_fetch_tool_result",
tool_use_id: part.toolCallId,
content: {
type: "web_fetch_tool_result_error",
error_code: (_t = (await extractErrorValue(output.value)).errorCode) != null ? _t : "unavailable"
},
...caller && { caller },
cache_control: cacheControl
});
break;
}
if (output.type !== "json") {
warnings.push({
type: "other",
message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`
});
break;
}
const webFetchOutput = await validateTypes$2({
value: output.value,
schema: webFetch_20250910OutputSchema
});
anthropicContent.push({
type: "web_fetch_tool_result",
tool_use_id: part.toolCallId,
content: {
type: "web_fetch_result",
url: webFetchOutput.url,
retrieved_at: webFetchOutput.retrievedAt,
content: {
type: "document",
title: webFetchOutput.content.title,
citations: webFetchOutput.content.citations,
source: {
type: webFetchOutput.content.source.type,
media_type: webFetchOutput.content.source.mediaType,
data: webFetchOutput.content.source.data
}
}
},
...caller && { caller },
cache_control: cacheControl
});
break;
}
if (providerToolName === "web_search") {
const output = part.output;
if (output.type === "error-json") {
anthropicContent.push({
type: "web_search_tool_result",
tool_use_id: part.toolCallId,
content: {
type: "web_search_tool_result_error",
error_code: (_u = (await extractErrorValue(output.value)).errorCode) != null ? _u : "unavailable"
},
...caller && { caller },
cache_control: cacheControl
});
break;
}
if (output.type !== "json") {
warnings.push({
type: "other",
message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`
});
break;
}
const webSearchOutput = await validateTypes$2({
value: output.value,
schema: webSearch_20250305OutputSchema
});
anthropicContent.push({
type: "web_search_tool_result",
tool_use_id: part.toolCallId,
content: webSearchOutput.map((result) => ({
url: result.url,
title: result.title,
page_age: result.pageAge,
encrypted_content: result.encryptedContent,
type: result.type
})),
...caller && { caller },
cache_control: cacheControl
});
break;
}
if (providerToolName === "tool_search_tool_regex" || providerToolName === "tool_search_tool_bm25") {
const output = part.output;
if (output.type === "error-json" || output.type === "json" && output.value != null && typeof output.value === "object" && !Array.isArray(output.value) && "type" in output.value && output.value.type === "tool_search_tool_result_error") {
anthropicContent.push({
type: "tool_search_tool_result",
tool_use_id: part.toolCallId,
content: {
type: "tool_search_tool_result_error",
error_code: (_v = (await extractErrorValue(output.value)).errorCode) != null ? _v : "unavailable"
},
cache_control: cacheControl
});
break;
}
if (output.type !== "json") {
warnings.push({
type: "other",
message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`
});
break;
}
const toolReferences = (await validateTypes$2({
value: output.value,
schema: toolSearchRegex_20251119OutputSchema
})).map((ref) => ({
type: "tool_reference",
tool_name: ref.toolName
}));
anthropicContent.push({
type: "tool_search_tool_result",
tool_use_id: part.toolCallId,
content: {
type: "tool_search_tool_search_result",
tool_references: toolReferences
},
cache_control: cacheControl
});
break;
}
if (providerToolName === "advisor") {
const output = part.output;
if (output.type !== "json" && output.type !== "error-json") {
warnings.push({
type: "other",
message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`
});
break;
}
const advisorOutput = await validateTypes$2({
value: output.value,
schema: advisor_20260301OutputSchema
});
if (advisorOutput.type === "advisor_result") anthropicContent.push({
type: "advisor_tool_result",
tool_use_id: part.toolCallId,
content: {
type: "advisor_result",
text: advisorOutput.text
},
cache_control: cacheControl
});
else if (advisorOutput.type === "advisor_redacted_result") anthropicContent.push({
type: "advisor_tool_result",
tool_use_id: part.toolCallId,
content: {
type: "advisor_redacted_result",
encrypted_content: advisorOutput.encryptedContent
},
cache_control: cacheControl
});
else anthropicContent.push({
type: "advisor_tool_result",
tool_use_id: part.toolCallId,
content: {
type: "advisor_tool_result_error",
error_code: advisorOutput.errorCode
},
cache_control: cacheControl
});
break;
}
warnings.push({
type: "other",
message: `provider executed tool result for tool ${part.toolName} is not supported`
});
break;
}
}
}
}
messages.push({
role: "assistant",
content: moveToolUseBlocksToEnd(anthropicContent)
});
break;
}
default: throw new Error(`content type: ${type}`);
}
}
const codeExecutionToolCallIds = /* @__PURE__ */ new Set();
for (const message of messages) {
if (message.role !== "assistant") continue;
for (const part of message.content) if (part.type === "server_tool_use" && part.name === "code_execution") codeExecutionToolCallIds.add(part.id);
}
const warnedToolCallIds = /* @__PURE__ */ new Set();
for (let i = 0; i < lastUserMessageIndex; i++) {
const message = messages[i];
if (message.role !== "assistant") continue;
for (const part of message.content) {
if (!("caller" in part)) continue;
const caller = part.caller;
if (caller == null || caller.type === "direct" || codeExecutionToolCallIds.has(caller.tool_id)) continue;
const toolCallId = "id" in part ? part.id : part.tool_use_id;
delete part.caller;
if (!warnedToolCallIds.has(toolCallId)) {
warnedToolCallIds.add(toolCallId);
warnings.push({
type: "other",
message: `Omitted caller metadata for tool ${toolCallId} because source code execution tool ${caller.tool_id} is missing from the conversation history.`
});
}
}
}
return {
prompt: {
system,
messages
},
betas
};
}
function groupIntoBlocks(prompt) {
const blocks = [];
let currentBlock = void 0;
for (const message of prompt) {
const { role } = message;
switch (role) {
case "system":
if ((currentBlock == null ? void 0 : currentBlock.type) !== "system") {
currentBlock = {
type: "system",
messages: []
};
blocks.push(currentBlock);
}
currentBlock.messages.push(message);
break;
case "assistant":
if ((currentBlock == null ? void 0 : currentBlock.type) !== "assistant") {
currentBlock = {
type: "assistant",
messages: []
};
blocks.push(currentBlock);
}
currentBlock.messages.push(message);
break;
case "user":
if ((currentBlock == null ? void 0 : currentBlock.type) !== "user") {
currentBlock = {
type: "user",
messages: []
};
blocks.push(currentBlock);
}
currentBlock.messages.push(message);
break;
case "tool":
if ((currentBlock == null ? void 0 : currentBlock.type) !== "user") {
currentBlock = {
type: "user",
messages: []
};
blocks.push(currentBlock);
}
currentBlock.messages.push(message);
break;
default: throw new Error(`Unsupported role: ${role}`);
}
}
return blocks;
}
function moveToolUseBlocksToEnd(content) {
const result = [];
let segment = [];
function flushSegment() {
result.push(...segment.filter((part) => part.type !== "tool_use"), ...segment.filter((part) => part.type === "tool_use"));
segment = [];
}
for (const part of content) if (part.type === "thinking" || part.type === "redacted_thinking") {
flushSegment();
result.push(part);
} else segment.push(part);
flushSegment();
return result;
}
function getAnthropicToolsetName({ toolName, providerOptions, toolsetNames }) {
var _a;
const fromTools = toolsetNames[toolName];
if (fromTools != null) return fromTools;
const fromMetadata = (_a = providerOptions == null ? void 0 : providerOptions.anthropic) == null ? void 0 : _a.toolsetName;
return typeof fromMetadata === "string" ? fromMetadata : void 0;
}
function getAnthropicCaller(providerOptions) {
var _a;
const caller = (_a = providerOptions == null ? void 0 : providerOptions.anthropic) == null ? void 0 : _a.caller;
if (((caller == null ? void 0 : caller.type) === "code_execution_20250825" || (caller == null ? void 0 : caller.type) === "code_execution_20260120") && caller.toolId) return {
type: caller.type,
tool_id: caller.toolId
};
return (caller == null ? void 0 : caller.type) === "direct" ? { type: "direct" } : void 0;
}
function mapAnthropicStopReason({ finishReason, isJsonResponseFromTool }) {
switch (finishReason) {
case "pause_turn":
case "end_turn":
case "stop_sequence": return "stop";
case "refusal": return "content-filter";
case "tool_use": return isJsonResponseFromTool ? "stop" : "tool-calls";
case "max_tokens":
case "model_context_window_exceeded": return "length";
case "compaction": return "other";
default: return "other";
}
}
var SUPPORTED_STRING_FORMATS = /* @__PURE__ */ new Set([
"date-time",
"time",
"date",
"duration",
"email",
"hostname",
"uri",
"ipv4",
"ipv6",
"uuid"
]);
var DESCRIPTION_CONSTRAINT_KEYS = [
"minimum",
"maximum",
"exclusiveMinimum",
"exclusiveMaximum",
"multipleOf",
"minLength",
"maxLength",
"pattern",
"minItems",
"maxItems",
"uniqueItems",
"minProperties",
"maxProperties",
"not"
];
function sanitizeJsonSchema(schema) {
return sanitizeSchema(schema);
}
function sanitizeDefinition(definition) {
if (typeof definition === "boolean" || !isPlainObject(definition)) return definition;
return sanitizeSchema(definition);
}
function sanitizeSchema(schema) {
const result = {};
if (schema.$ref != null) return {
$ref: schema.$ref,
...sanitizeSchemaDefinitions(schema)
};
if (schema.$schema != null) result.$schema = schema.$schema;
if (schema.$id != null) result.$id = schema.$id;
if (schema.title != null) result.title = schema.title;
if (schema.description != null) result.description = schema.description;
if (schema.default !== void 0) result.default = schema.default;
if (schema.const !== void 0) result.const = schema.const;
if (schema.enum != null) result.enum = schema.enum;
if (schema.type != null) result.type = schema.type;
if (schema.anyOf != null) result.anyOf = schema.anyOf.map(sanitizeDefinition);
else if (schema.oneOf != null) result.anyOf = schema.oneOf.map(sanitizeDefinition);
if (schema.allOf != null) result.allOf = schema.allOf.map(sanitizeDefinition);
Object.assign(result, sanitizeSchemaDefinitions(schema));
if (schema.type === "object" || schema.properties != null) {
if (schema.properties != null) result.properties = Object.fromEntries(Object.entries(schema.properties).map(([name, definition]) => [name, sanitizeDefinition(definition)]));
result.additionalProperties = false;
if (schema.required != null) result.required = schema.required;
}
if (schema.items != null) result.items = Array.isArray(schema.items) ? schema.items.map(sanitizeDefinition) : sanitizeDefinition(schema.items);
if (typeof schema.format === "string" && SUPPORTED_STRING_FORMATS.has(schema.format)) result.format = schema.format;
const constraintDescription = getConstraintDescription(schema);
if (constraintDescription != null) result.description = result.description == null ? constraintDescription : `${result.description}
${constraintDescription}`;
return result;
}
function sanitizeSchemaDefinitions(schema) {
const { $defs } = schema;
const sanitizeAll = (definitions) => Object.fromEntries(Object.entries(definitions).map(([name, definition]) => [name, sanitizeDefinition(definition)]));
return {
...schema.definitions != null && { definitions: sanitizeAll(schema.definitions) },
...$defs != null && { $defs: sanitizeAll($defs) }
};
}
function getConstraintDescription(schema) {
const descriptions = DESCRIPTION_CONSTRAINT_KEYS.flatMap((key) => {
const value = schema[key];
if (value == null || value === false) return [];
return `${formatConstraintName(key)}: ${formatConstraintValue(value)}`;
});
if (typeof schema.format === "string" && !SUPPORTED_STRING_FORMATS.has(schema.format)) descriptions.push(`format: ${schema.format}`);
return descriptions.length === 0 ? void 0 : `${descriptions.join("; ")}.`;
}
function formatConstraintName(key) {
return key.replace(/[A-Z]/g, (match) => ` ${match.toLowerCase()}`);
}
function formatConstraintValue(value) {
if (typeof value === "string") return value;
return JSON.stringify(value);
}
function isPlainObject(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
var SCHEMA_MAP_KEYWORDS = /* @__PURE__ */ new Set([
"dependentSchemas",
"patternProperties",
"properties"
]);
var DATA_KEYWORDS = /* @__PURE__ */ new Set([
"const",
"default",
"enum",
"examples"
]);
function hasCircularSchemaReference(schema) {
const visiting = /* @__PURE__ */ new Set();
const visited = /* @__PURE__ */ new Set();
const visit = (pointer) => {
if (visiting.has(pointer)) return true;
if (visited.has(pointer)) return false;
const target = resolveSchemaPointer(schema, pointer);
if (target === void 0) return false;
visiting.add(pointer);
const isCircular = collectLocalRefs(target).some(visit);
visiting.delete(pointer);
visited.add(pointer);
return isCircular;
};
return visit("#");
}
function collectLocalRefs(node, refs = []) {
if (Array.isArray(node)) {
for (const item of node) collectLocalRefs(item, refs);
return refs;
}
if (!isRecord(node)) return refs;
for (const [key, value] of Object.entries(node)) if (key === "$ref") {
if (typeof value === "string" && value.startsWith("#")) refs.push(value);
} else if (SCHEMA_MAP_KEYWORDS.has(key) && isRecord(value)) for (const subschema of Object.values(value)) collectLocalRefs(subschema, refs);
else if (key !== "$defs" && key !== "definitions" && !DATA_KEYWORDS.has(key)) collectLocalRefs(value, refs);
return refs;
}
function resolveSchemaPointer(schema, pointer) {
if (pointer === "#") return schema;
if (!pointer.startsWith("#/")) return;
let decodedPointer;
try {
decodedPointer = decodeURIComponent(pointer.slice(2));
} catch (e) {
return;
}
let current = schema;
for (const rawSegment of decodedPointer.split("/")) {
const segment = rawSegment.replace(/~1/g, "/").replace(/~0/g, "~");
if (Array.isArray(current)) current = current[Number(segment)];
else if (isRecord(current)) current = current[segment];
else return;
}
return current;
}
function isRecord(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
var MAX_OPTIONAL_PROPERTIES = 10;
var SUBSCHEMA_KEYWORDS = [
"additionalProperties",
"contains",
"else",
"if",
"items",
"not",
"then"
];
var SUBSCHEMA_LIST_KEYWORDS = [
"allOf",
"anyOf",
"oneOf",
"prefixItems"
];
var SUBSCHEMA_MAP_KEYWORDS = [
"dependentSchemas",
"patternProperties",
"properties"
];
function supportsNativeStructuredOutputSchema(schema) {
if (hasCircularSchemaReference(schema)) return false;
const { optionalProperties, hasOpenObject } = getSchemaStats(schema, schema, /* @__PURE__ */ new Map());
return !hasOpenObject && optionalProperties <= MAX_OPTIONAL_PROPERTIES;
}
function getSchemaStats(node, root, refStats) {
const stats = {
optionalProperties: 0,
hasOpenObject: false
};
if (!isRecord(node)) return stats;
const add = (child) => {
const childStats = getSchemaStats(child, root, refStats);
stats.optionalProperties += childStats.optionalProperties;
stats.hasOpenObject || (stats.hasOpenObject = childStats.hasOpenObject);
};
if (typeof node.$ref === "string" && node.$ref.startsWith("#")) {
let resolved = refStats.get(node.$ref);
if (resolved == null) {
resolved = getSchemaStats(resolveSchemaPointer(root, node.$ref), root, refStats);
refStats.set(node.$ref, resolved);
}
stats.optionalProperties += resolved.optionalProperties;
stats.hasOpenObject || (stats.hasOpenObject = resolved.hasOpenObject);
}
if (isOpenObject(node)) stats.hasOpenObject = true;
if (isRecord(node.properties)) {
const required = new Set(Array.isArray(node.required) ? node.required : []);
stats.optionalProperties += Object.keys(node.properties).filter((name) => !required.has(name)).length;
}
for (const keyword of SUBSCHEMA_KEYWORDS) {
const value = node[keyword];
if (Array.isArray(value)) value.forEach(add);
else add(value);
}
for (const keyword of SUBSCHEMA_LIST_KEYWORDS) {
const value = node[keyword];
if (Array.isArray(value)) value.forEach(add);
}
for (const keyword of SUBSCHEMA_MAP_KEYWORDS) {
const value = node[keyword];
if (isRecord(value)) Object.values(value).forEach(add);
}
return stats;
}
function isOpenObject(node) {
const { additionalProperties, patternProperties, properties, type } = node;
if (additionalProperties === true || isRecord(additionalProperties)) return true;
if (isRecord(patternProperties) && Object.keys(patternProperties).length > 0) return true;
return (type === "object" || Array.isArray(type) && type.includes("object")) && properties == null && additionalProperties !== false;
}
function createCitationSource(citation, citationDocuments, generateId3) {
var _a;
if (citation.type === "web_search_result_location") return {
type: "source",
sourceType: "url",
id: generateId3(),
url: citation.url,
title: citation.title,
providerMetadata: { anthropic: {
citedText: citation.cited_text,
encryptedIndex: citation.encrypted_index
} }
};
if (citation.type !== "page_location" && citation.type !== "char_location") return;
const documentInfo = citationDocuments[citation.document_index];
if (!documentInfo) return;
return {
type: "source",
sourceType: "document",
id: generateId3(),
mediaType: documentInfo.mediaType,
title: (_a = citation.document_title) != null ? _a : documentInfo.title,
filename: documentInfo.filename,
providerMetadata: { anthropic: citation.type === "page_location" ? {
citedText: citation.cited_text,
startPageNumber: citation.start_page_number,
endPageNumber: citation.end_page_number
} : {
citedText: citation.cited_text,
startCharIndex: citation.start_char_index,
endCharIndex: citation.end_char_index
} }
};
}
function getAnthropicCallerInfo(caller) {
return caller == null ? void 0 : {
type: caller.type,
toolId: "tool_id" in caller ? caller.tool_id : void 0
};
}
function getAnthropicCallerMetadata(caller) {
const callerInfo = getAnthropicCallerInfo(caller);
return callerInfo == null ? {} : { providerMetadata: { anthropic: { caller: callerInfo } } };
}
function getAnthropicToolsetNames(tools) {
const toolsetNames = {};
for (const tool of tools != null ? tools : []) if (tool.type === "provider" && tool.id === "anthropic.computer_toolset_20260801") toolsetNames[tool.name] = "computer";
return toolsetNames;
}
function toToolsetMemberInput({ memberName, input }) {
return {
action: memberName,
...typeof input === "object" && input !== null && !Array.isArray(input) ? input : {}
};
}
var TEXT_OR_THINKING_BLOCK_TYPES = /* @__PURE__ */ new Set([
"redacted_thinking",
"text",
"thinking"
]);
function isContinuationStopReason(stopReason) {
return stopReason === "pause_turn" || stopReason === "tool_use";
}
function getJsonResponseToolFallbackText(content, stopReason) {
const text = /* @__PURE__ */ new Set();
if (isContinuationStopReason(stopReason)) return text;
for (const part of content) {
if (part.type === "tool_use" && part.name === "json") return /* @__PURE__ */ new Set();
if (part.type === "text") text.add(part);
else if (!TEXT_OR_THINKING_BLOCK_TYPES.has(part.type)) text.clear();
}
return text;
}
var AnthropicMessagesLanguageModel = class {
constructor(modelId, config) {
this.specificationVersion = "v3";
var _a;
this.modelId = modelId;
this.config = config;
this.generateId = (_a = config.generateId) != null ? _a : generateId$2;
}
supportsUrl(url) {
return url.protocol === "https:";
}
get provider() {
return this.config.provider;
}
/**
* Extracts the dynamic provider name from the config.provider string.
* e.g., 'my-custom-anthropic.messages' -> 'my-custom-anthropic'
*/
get providerOptionsName() {
const provider = this.config.provider;
const dotIndex = provider.indexOf(".");
return dotIndex === -1 ? provider : provider.substring(0, dotIndex);
}
get supportedUrls() {
var _a, _b, _c;
return (_c = (_b = (_a = this.config).supportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {};
}
async getArgs({ userSuppliedBetas, prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, responseFormat, seed, tools, toolChoice, providerOptions, stream }) {
var _a, _b, _c, _d, _e, _f, _g, _h;
const warnings = [];
if (frequencyPenalty != null) warnings.push({
type: "unsupported",
feature: "frequencyPenalty"
});
if (presencePenalty != null) warnings.push({
type: "unsupported",
feature: "presencePenalty"
});
if (seed != null) warnings.push({
type: "unsupported",
feature: "seed"
});
const maxTemperature = (_a = this.config.maxTemperature) != null ? _a : 1;
const temperatureProvider = this.config.maxTemperature == null ? "anthropic" : this.providerOptionsName;
if (temperature != null && temperature > maxTemperature) {
warnings.push({
type: "unsupported",
feature: "temperature",
details: `${temperature} exceeds ${temperatureProvider} maximum of ${maxTemperature.toFixed(1)}. clamped to ${maxTemperature.toFixed(1)}`
});
temperature = maxTemperature;
} else if (temperature != null && temperature < 0) {
warnings.push({
type: "unsupported",
feature: "temperature",
details: `${temperature} is below ${temperatureProvider} minimum of 0. clamped to 0`
});
temperature = 0;
}
if ((responseFormat == null ? void 0 : responseFormat.type) === "json") {
if (responseFormat.schema == null) warnings.push({
type: "unsupported",
feature: "responseFormat",
details: "JSON response format requires a schema. The response format is ignored."
});
}
const providerOptionsName = this.providerOptionsName;
const canonicalOptions = await parseProviderOptions$1({
provider: "anthropic",
providerOptions,
schema: anthropicLanguageModelOptions
});
const customProviderOptions = providerOptionsName !== "anthropic" ? await parseProviderOptions$1({
provider: providerOptionsName,
providerOptions,
schema: anthropicLanguageModelOptions
}) : null;
const usedCustomProviderKey = customProviderOptions != null;
const anthropicOptions = Object.assign({}, canonicalOptions != null ? canonicalOptions : {}, customProviderOptions != null ? customProviderOptions : {});
const { maxOutputTokens: maxOutputTokensForModel, supportsStructuredOutput: modelSupportsStructuredOutput, rejectsSamplingParameters, rejectsThinkingDisabledAboveHighEffort, rejectsThinkingDisabled, rejectsBudgetThinking, rejectsForcedToolUse, supportsBetweenToolsThinking, isKnownModel } = getModelCapabilities(this.modelId);
if (!isKnownModel && maxOutputTokens == null) warnings.push({
type: "compatibility",
feature: "maxOutputTokens",
details: `The model "${this.modelId}" is unknown. The max output tokens have been limited to ${maxOutputTokensForModel}. Set maxOutputTokens explicitly to override this limit.`
});
if (rejectsSamplingParameters) {
if (temperature != null) {
warnings.push({
type: "unsupported",
feature: "temperature",
details: `temperature is not supported by ${this.modelId} and will be ignored`
});
temperature = void 0;
}
if (topK != null) {
warnings.push({
type: "unsupported",
feature: "topK",
details: `topK is not supported by ${this.modelId} and will be ignored`
});
topK = void 0;
}
if (topP != null) {
warnings.push({
type: "unsupported",
feature: "topP",
details: `topP is not supported by ${this.modelId} and will be ignored`
});
topP = void 0;
}
}
const isAnthropicModel = isKnownModel || this.modelId.includes("claude-");
const supportsStructuredOutput = ((_b = this.config.supportsNativeStructuredOutput) != null ? _b : true) && modelSupportsStructuredOutput;
const supportsStrictTools = ((_c = this.config.supportsStrictTools) != null ? _c : true) && modelSupportsStructuredOutput;
const structureOutputMode = (_d = anthropicOptions == null ? void 0 : anthropicOptions.structuredOutputMode) != null ? _d : "auto";
let useStructuredOutput = structureOutputMode === "outputFormat" || structureOutputMode === "auto" && supportsStructuredOutput;
if (!useStructuredOutput && rejectsForcedToolUse && modelSupportsStructuredOutput && (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && supportsNativeStructuredOutputSchema(responseFormat.schema)) {
warnings.push({
type: "unsupported",
feature: "providerOptions.anthropic.structuredOutputMode",
details: `structuredOutputMode 'jsonTool' is not supported by ${this.modelId} because it rejects forced tool use. Using 'outputFormat' instead.`
});
useStructuredOutput = true;
}
const jsonResponseTool = (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && !useStructuredOutput ? {
type: "function",
name: "json",
description: "Respond with a JSON object.",
inputSchema: responseFormat.schema
} : void 0;
if (jsonResponseTool != null && (anthropicOptions == null ? void 0 : anthropicOptions.disableParallelToolUse) === false) warnings.push({
type: "unsupported",
feature: "providerOptions.anthropic.disableParallelToolUse",
details: "`disableParallelToolUse: false` is ignored when using the JSON response tool. Parallel tool use is disabled to ensure a single coherent JSON tool call."
});
const contextManagement = anthropicOptions == null ? void 0 : anthropicOptions.contextManagement;
const cacheControlValidator = new CacheControlValidator$1(this.config.cacheControlProviderOptionsName);
const toolNameMapping = createToolNameMapping({
tools,
providerToolNames: {
"anthropic.code_execution_20250522": "code_execution",
"anthropic.code_execution_20250825": "code_execution",
"anthropic.code_execution_20260120": "code_execution",
"anthropic.computer_20241022": "computer",
"anthropic.computer_20250124": "computer",
"anthropic.computer_20251124": "computer",
"anthropic.computer_toolset_20260801": "computer",
"anthropic.text_editor_20241022": "str_replace_editor",
"anthropic.text_editor_20250124": "str_replace_editor",
"anthropic.text_editor_20250429": "str_replace_based_edit_tool",
"anthropic.text_editor_20250728": "str_replace_based_edit_tool",
"anthropic.bash_20241022": "bash",
"anthropic.bash_20250124": "bash",
"anthropic.memory_20250818": "memory",
"anthropic.web_search_20250305": "web_search",
"anthropic.web_search_20260209": "web_search",
"anthropic.web_fetch_20250910": "web_fetch",
"anthropic.web_fetch_20260209": "web_fetch",
"anthropic.tool_search_regex_20251119": "tool_search_tool_regex",
"anthropic.tool_search_bm25_20251119": "tool_search_tool_bm25",
"anthropic.advisor_20260301": "advisor"
}
});
const toolsetNames = getAnthropicToolsetNames(tools);
const { prompt: messagesPrompt, betas } = await convertToAnthropicMessagesPrompt({
prompt,
sendReasoning: (_e = anthropicOptions == null ? void 0 : anthropicOptions.sendReasoning) != null ? _e : true,
warnings,
cacheControlValidator,
toolNameMapping,
toolsetNames,
convertMediaPart: this.config.convertMediaPart
});
if (rejectsThinkingDisabled && (anthropicOptions == null ? void 0 : anthropicOptions.thinking) != null) {
const requestedThinking = anthropicOptions.thinking;
const requestedType = "type" in requestedThinking ? requestedThinking.type : void 0;
if (requestedType === "disabled" && supportsBetweenToolsThinking) {
warnings.push({
type: "unsupported",
feature: "providerOptions.anthropic.thinking",
details: `thinking cannot be disabled for ${this.modelId}. Using 'between_tools' thinking, the lowest thinking setting, instead.`
});
anthropicOptions.thinking = { type: "between_tools" };
} else if (requestedType === "disabled") {
warnings.push({
type: "unsupported",
feature: "providerOptions.anthropic.thinking",
details: `thinking cannot be disabled for ${this.modelId}; it always uses adaptive thinking. The thinking setting has been removed. Lower 'effort' to reduce thinking.`
});
anthropicOptions.thinking = void 0;
}
}
if (rejectsBudgetThinking && (anthropicOptions == null ? void 0 : anthropicOptions.thinking) != null && "type" in anthropicOptions.thinking && anthropicOptions.thinking.type === "enabled") {
warnings.push({
type: "unsupported",
feature: "providerOptions.anthropic.thinking",
details: rejectsThinkingDisabled ? `budget-based thinking is not supported by ${this.modelId}; it always uses adaptive thinking. Using adaptive thinking instead. Use 'effort' to control how much the model thinks.` : `budget-based thinking is not supported by ${this.modelId}. Using adaptive thinking instead. Use 'effort' to control how much the model thinks.`
});
anthropicOptions.thinking = { type: "adaptive" };
}
const thinking = anthropicOptions == null ? void 0 : anthropicOptions.thinking;
const thinkingType = thinking != null && "type" in thinking ? thinking.type : void 0;
if (rejectsThinkingDisabledAboveHighEffort && thinkingType === "disabled" && (anthropicOptions.effort === "xhigh" || anthropicOptions.effort === "max")) {
warnings.push({
type: "unsupported",
feature: "providerOptions.anthropic.effort",
details: `effort '${anthropicOptions.effort}' is not supported by ${this.modelId} when thinking is disabled. The effort has been lowered to 'high'.`
});
anthropicOptions.effort = "high";
}
if (thinkingType === "between_tools" && (anthropicOptions.effort === "xhigh" || anthropicOptions.effort === "max")) {
warnings.push({
type: "unsupported",
feature: "providerOptions.anthropic.effort",
details: `effort '${anthropicOptions.effort}' is not supported with 'between_tools' thinking. The effort has been lowered to 'high'.`
});
anthropicOptions.effort = "high";
}
const isThinking = thinkingType === "enabled" || thinkingType === "adaptive" || thinkingType === "between_tools";
const sendThinking = isThinking || thinkingType === "disabled";
let thinkingBudget = thinkingType === "enabled" && thinking != null && "budgetTokens" in thinking ? thinking.budgetTokens : void 0;
const thinkingDisplay = thinkingType === "adaptive" && thinking != null && "display" in thinking ? thinking.display : void 0;
const thinkingBlockBinding = thinking != null && "blockBinding" in thinking ? thinking.blockBinding : void 0;
const sendThinkingConfig = sendThinking || thinkingBlockBinding != null;
const maxTokens = maxOutputTokens != null ? maxOutputTokens : maxOutputTokensForModel;
const baseArgs = {
model: this.modelId,
max_tokens: maxTokens,
temperature,
top_k: topK,
top_p: topP,
stop_sequences: stopSequences,
...sendThinkingConfig && { thinking: {
...thinkingType != null && { type: thinkingType },
...thinkingBudget != null && { budget_tokens: thinkingBudget },
...thinkingDisplay != null && { display: thinkingDisplay },
...thinkingBlockBinding != null && { block_binding: { prefix_mismatch_behavior: thinkingBlockBinding.prefixMismatchBehavior } }
} },
...((anthropicOptions == null ? void 0 : anthropicOptions.effort) || (anthropicOptions == null ? void 0 : anthropicOptions.taskBudget) || useStructuredOutput && (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null) && { output_config: {
...(anthropicOptions == null ? void 0 : anthropicOptions.effort) && { effort: anthropicOptions.effort },
...(anthropicOptions == null ? void 0 : anthropicOptions.taskBudget) && { task_budget: {
type: anthropicOptions.taskBudget.type,
total: anthropicOptions.taskBudget.total,
...anthropicOptions.taskBudget.remaining != null && { remaining: anthropicOptions.taskBudget.remaining }
} },
...useStructuredOutput && (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && { format: {
type: "json_schema",
schema: sanitizeJsonSchema(responseFormat.schema)
} }
} },
...(anthropicOptions == null ? void 0 : anthropicOptions.speed) && { speed: anthropicOptions.speed },
...(anthropicOptions == null ? void 0 : anthropicOptions.inferenceGeo) && { inference_geo: anthropicOptions.inferenceGeo },
...(anthropicOptions == null ? void 0 : anthropicOptions.fallbacks) != null && (anthropicOptions.fallbacks === "default" || anthropicOptions.fallbacks.length > 0) && { fallbacks: anthropicOptions.fallbacks },
...(anthropicOptions == null ? void 0 : anthropicOptions.cacheControl) && { cache_control: anthropicOptions.cacheControl },
...((_f = anthropicOptions == null ? void 0 : anthropicOptions.metadata) == null ? void 0 : _f.userId) != null && { metadata: { user_id: anthropicOptions.metadata.userId } },
...(anthropicOptions == null ? void 0 : anthropicOptions.mcpServers) && anthropicOptions.mcpServers.length > 0 && { mcp_servers: anthropicOptions.mcpServers.map((server) => ({
type: server.type,
name: server.name,
url: server.url,
authorization_token: server.authorizationToken,
tool_configuration: server.toolConfiguration ? {
allowed_tools: server.toolConfiguration.allowedTools,
enabled: server.toolConfiguration.enabled
} : void 0
})) },
...(anthropicOptions == null ? void 0 : anthropicOptions.container) && { container: anthropicOptions.container.skills && anthropicOptions.container.skills.length > 0 ? {
id: anthropicOptions.container.id,
skills: anthropicOptions.container.skills.map((skill) => ({
type: skill.type,
skill_id: skill.skillId,
version: skill.version
}))
} : anthropicOptions.container.id },
system: messagesPrompt.system,
messages: messagesPrompt.messages,
...(anthropicOptions == null ? void 0 : anthropicOptions.safeguards) && anthropicOptions.safeguards.length > 0 && { safeguards: anthropicOptions.safeguards.map((safeguard) => ({
type: safeguard.type,
...safeguard.classifierContext !== void 0 && { classifier_context: safeguard.classifierContext }
})) },
...contextManagement && { context_management: { edits: contextManagement.edits.map((edit) => {
const strategy = edit.type;
switch (strategy) {
case "clear_tool_uses_20250919": return {
type: edit.type,
...edit.trigger !== void 0 && { trigger: edit.trigger },
...edit.keep !== void 0 && { keep: edit.keep },
...edit.clearAtLeast !== void 0 && { clear_at_least: edit.clearAtLeast },
...edit.clearToolInputs !== void 0 && { clear_tool_inputs: edit.clearToolInputs },
...edit.excludeTools !== void 0 && { exclude_tools: edit.excludeTools }
};
case "clear_thinking_20251015": return {
type: edit.type,
...edit.keep !== void 0 && { keep: edit.keep }
};
case "compact_20260112": return {
type: edit.type,
...edit.trigger !== void 0 && { trigger: edit.trigger },
...edit.pauseAfterCompaction !== void 0 && { pause_after_compaction: edit.pauseAfterCompaction },
...edit.instructions !== void 0 && { instructions: edit.instructions }
};
default:
warnings.push({
type: "other",
message: `Unknown context management strategy: ${strategy}`
});
return;
}
}).filter((edit) => edit !== void 0) } }
};
if (isThinking) {
if (thinkingType === "enabled" && thinkingBudget == null) {
warnings.push({
type: "compatibility",
feature: "extended thinking",
details: "thinking budget is required when thinking is enabled. using default budget of 1024 tokens."
});
baseArgs.thinking = {
type: "enabled",
budget_tokens: 1024
};
thinkingBudget = 1024;
}
if (baseArgs.temperature != null && !this.config.supportsTemperatureAndTopPWithThinking) {
baseArgs.temperature = void 0;
warnings.push({
type: "unsupported",
feature: "temperature",
details: "temperature is not supported when thinking is enabled"
});
}
if (topK != null) {
baseArgs.top_k = void 0;
warnings.push({
type: "unsupported",
feature: "topK",
details: "topK is not supported when thinking is enabled"
});
}
if (topP != null && !this.config.supportsTemperatureAndTopPWithThinking) {
baseArgs.top_p = void 0;
warnings.push({
type: "unsupported",
feature: "topP",
details: "topP is not supported when thinking is enabled"
});
}
baseArgs.max_tokens = maxTokens + (thinkingBudget != null ? thinkingBudget : 0);
} else if (isAnthropicModel && topP != null && temperature != null) {
warnings.push({
type: "unsupported",
feature: "topP",
details: `topP is not supported when temperature is set. topP is ignored.`
});
baseArgs.top_p = void 0;
}
if (isKnownModel && baseArgs.max_tokens > maxOutputTokensForModel) {
if (maxOutputTokens != null) warnings.push({
type: "unsupported",
feature: "maxOutputTokens",
details: `${baseArgs.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${maxOutputTokensForModel} max output tokens. The max output tokens have been limited to ${maxOutputTokensForModel}.`
});
baseArgs.max_tokens = maxOutputTokensForModel;
}
if ((anthropicOptions == null ? void 0 : anthropicOptions.mcpServers) && anthropicOptions.mcpServers.length > 0) betas.add("mcp-client-2025-04-04");
if ((anthropicOptions == null ? void 0 : anthropicOptions.safeguards) && anthropicOptions.safeguards.length > 0) betas.add("dangerous-tool-use-2026-09-03");
if (contextManagement) {
betas.add("context-management-2025-06-27");
if (contextManagement.edits.some((e) => e.type === "compact_20260112")) betas.add("compact-2026-01-12");
}
if ((anthropicOptions == null ? void 0 : anthropicOptions.container) && anthropicOptions.container.skills && anthropicOptions.container.skills.length > 0) {
betas.add("code-execution-2025-08-25");
betas.add("skills-2025-10-02");
betas.add("files-api-2025-04-14");
if (!(tools == null ? void 0 : tools.some((tool) => tool.type === "provider" && (tool.id === "anthropic.code_execution_20250825" || tool.id === "anthropic.code_execution_20260120")))) warnings.push({
type: "other",
message: "code execution tool is required when using skills"
});
}
if (anthropicOptions == null ? void 0 : anthropicOptions.taskBudget) betas.add("task-budgets-2026-03-13");
if (thinkingDisplay === "updates") betas.add("thinking-display-updates-2026-08-18");
if (thinkingBlockBinding != null) betas.add("thinking-binding-controls-2026-08-01");
if ((anthropicOptions == null ? void 0 : anthropicOptions.speed) === "fast") betas.add("fast-mode-2026-02-01");
if ((anthropicOptions == null ? void 0 : anthropicOptions.fallbacks) === "default") betas.add("server-side-fallback-2026-07-01");
else if ((anthropicOptions == null ? void 0 : anthropicOptions.fallbacks) && anthropicOptions.fallbacks.length > 0) betas.add("server-side-fallback-2026-06-01");
const defaultEagerInputStreaming = stream && ((_g = anthropicOptions == null ? void 0 : anthropicOptions.toolStreaming) != null ? _g : true);
const { tools: anthropicTools2, toolChoice: anthropicToolChoice, toolWarnings, betas: toolsBetas } = await prepareTools$6(jsonResponseTool != null ? {
tools: [...tools != null ? tools : [], jsonResponseTool],
toolChoice: { type: "required" },
disableParallelToolUse: true,
cacheControlValidator,
supportsStructuredOutput: false,
supportsStrictTools,
defaultEagerInputStreaming,
rejectsForcedToolUse: rejectsForcedToolUse || thinkingType === "enabled"
} : {
tools: tools != null ? tools : [],
toolChoice,
disableParallelToolUse: anthropicOptions == null ? void 0 : anthropicOptions.disableParallelToolUse,
cacheControlValidator,
supportsStructuredOutput,
supportsStrictTools,
defaultEagerInputStreaming,
rejectsForcedToolUse: rejectsForcedToolUse || thinkingType === "enabled"
});
const cacheWarnings = cacheControlValidator.getWarnings();
return {
args: {
...baseArgs,
tools: anthropicTools2,
tool_choice: anthropicToolChoice,
stream: stream === true ? true : void 0
},
warnings: [
...warnings,
...toolWarnings,
...cacheWarnings
],
betas: /* @__PURE__ */ new Set([
...betas,
...toolsBetas,
...userSuppliedBetas,
...(_h = anthropicOptions == null ? void 0 : anthropicOptions.anthropicBeta) != null ? _h : []
]),
usesJsonResponseTool: jsonResponseTool != null,
toolNameMapping,
providerOptionsName,
usedCustomProviderKey
};
}
async getHeaders({ betas, headers }) {
return combineHeaders$2(await resolve$1(this.config.headers), headers, betas.size > 0 ? { "anthropic-beta": Array.from(betas).join(",") } : {});
}
async getBetasFromHeaders(requestHeaders) {
var _a, _b;
const configBetaHeader = (_a = (await resolve$1(this.config.headers))["anthropic-beta"]) != null ? _a : "";
const requestBetaHeader = (_b = requestHeaders == null ? void 0 : requestHeaders["anthropic-beta"]) != null ? _b : "";
return new Set([...configBetaHeader.toLowerCase().split(","), ...requestBetaHeader.toLowerCase().split(",")].map((beta) => beta.trim()).filter((beta) => beta !== ""));
}
buildRequestUrl(isStreaming) {
var _a, _b, _c;
return (_c = (_b = (_a = this.config).buildRequestUrl) == null ? void 0 : _b.call(_a, this.config.baseURL, isStreaming)) != null ? _c : `${this.config.baseURL}/messages`;
}
transformRequestBody(args, betas) {
var _a, _b, _c;
return (_c = (_b = (_a = this.config).transformRequestBody) == null ? void 0 : _b.call(_a, args, betas)) != null ? _c : args;
}
extractCitationDocuments(prompt) {
const isCitationPart = (part) => {
var _a, _b;
if (part.type !== "file") return false;
if (part.mediaType !== "application/pdf" && part.mediaType !== "text/plain") return false;
const anthropic2 = (_a = part.providerOptions) == null ? void 0 : _a.anthropic;
const citationsConfig = anthropic2 == null ? void 0 : anthropic2.citations;
return (_b = citationsConfig == null ? void 0 : citationsConfig.enabled) != null ? _b : false;
};
return prompt.filter((message) => message.role === "user").flatMap((message) => message.content).filter(isCitationPart).map((part) => {
var _a;
const filePart = part;
return {
title: (_a = filePart.filename) != null ? _a : "Untitled Document",
filename: filePart.filename,
mediaType: filePart.mediaType
};
});
}
async doGenerate(options) {
var _a, _b, _c, _d, _e, _f, _g, _h, _i;
const { args, warnings, betas, usesJsonResponseTool, toolNameMapping, providerOptionsName, usedCustomProviderKey } = await this.getArgs({
...options,
stream: false,
userSuppliedBetas: await this.getBetasFromHeaders(options.headers)
});
const citationDocuments = [...this.extractCitationDocuments(options.prompt)];
const markCodeExecutionDynamic = hasWebTool20260209WithoutCodeExecution(args.tools);
const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi$2({
url: this.buildRequestUrl(false),
headers: await this.getHeaders({
betas,
headers: options.headers
}),
body: this.transformRequestBody(args, betas),
failedResponseHandler: anthropicFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$2(anthropicMessagesResponseSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const content = [];
const mcpToolCalls = {};
const serverToolCalls = {};
let isJsonResponseFromTool = false;
const jsonResponseToolFallbackText = usesJsonResponseTool ? getJsonResponseToolFallbackText(response.content, response.stop_reason) : void 0;
for (const part of response.content) switch (part.type) {
case "text":
if (jsonResponseToolFallbackText == null || jsonResponseToolFallbackText.has(part)) {
const webSearchCitations = (_a = part.citations) == null ? void 0 : _a.filter((citation) => citation.type === "web_search_result_location");
content.push({
type: "text",
text: part.text,
...webSearchCitations != null && webSearchCitations.length > 0 && { providerMetadata: { anthropic: { citations: webSearchCitations } } }
});
if (part.citations) for (const citation of part.citations) {
const source = createCitationSource(citation, citationDocuments, this.generateId);
if (source) content.push(source);
}
}
break;
case "thinking":
content.push({
type: "reasoning",
text: part.thinking,
providerMetadata: { anthropic: { signature: part.signature } }
});
break;
case "redacted_thinking":
content.push({
type: "reasoning",
text: "",
providerMetadata: { anthropic: { redactedData: part.data } }
});
break;
case "compaction":
content.push({
type: "text",
text: part.content,
providerMetadata: { anthropic: { type: "compaction" } }
});
break;
case "tool_use":
if (usesJsonResponseTool && part.name === "json") {
isJsonResponseFromTool = true;
content.push({
type: "text",
text: JSON.stringify(part.input)
});
} else if (part.toolset_name != null) content.push({
type: "tool-call",
toolCallId: part.id,
toolName: toolNameMapping.toCustomToolName(part.toolset_name),
input: JSON.stringify(toToolsetMemberInput({
memberName: part.name,
input: part.input
})),
providerMetadata: { anthropic: {
toolsetName: part.toolset_name,
...(_b = getAnthropicCallerMetadata(part.caller).providerMetadata) == null ? void 0 : _b.anthropic
} }
});
else content.push({
type: "tool-call",
toolCallId: part.id,
toolName: part.name,
input: JSON.stringify(part.input),
...getAnthropicCallerMetadata(part.caller)
});
break;
case "server_tool_use":
if (part.name === "text_editor_code_execution" || part.name === "bash_code_execution") content.push({
type: "tool-call",
toolCallId: part.id,
toolName: toolNameMapping.toCustomToolName("code_execution"),
input: JSON.stringify({
type: part.name,
...part.input
}),
providerExecuted: true,
...markCodeExecutionDynamic && true ? { dynamic: true } : {},
...getAnthropicCallerMetadata(part.caller)
});
else if (part.name === "web_search" || part.name === "code_execution" || part.name === "web_fetch") {
const inputToSerialize = part.name === "code_execution" && part.input != null && typeof part.input === "object" && "code" in part.input && !("type" in part.input) ? {
type: "programmatic-tool-call",
...part.input
} : part.input;
content.push({
type: "tool-call",
toolCallId: part.id,
toolName: toolNameMapping.toCustomToolName(part.name),
input: JSON.stringify(inputToSerialize),
providerExecuted: true,
...markCodeExecutionDynamic && part.name === "code_execution" ? { dynamic: true } : {},
...getAnthropicCallerMetadata(part.caller)
});
} else if (part.name === "tool_search_tool_regex" || part.name === "tool_search_tool_bm25") {
serverToolCalls[part.id] = part.name;
content.push({
type: "tool-call",
toolCallId: part.id,
toolName: toolNameMapping.toCustomToolName(part.name),
input: JSON.stringify(part.input),
providerExecuted: true,
...getAnthropicCallerMetadata(part.caller)
});
} else if (part.name === "advisor") content.push({
type: "tool-call",
toolCallId: part.id,
toolName: toolNameMapping.toCustomToolName("advisor"),
input: JSON.stringify(part.input),
providerExecuted: true,
...getAnthropicCallerMetadata(part.caller)
});
break;
case "mcp_tool_use":
mcpToolCalls[part.id] = {
type: "tool-call",
toolCallId: part.id,
toolName: part.name,
input: JSON.stringify(part.input),
providerExecuted: true,
dynamic: true,
providerMetadata: { anthropic: {
type: "mcp-tool-use",
serverName: part.server_name
} }
};
content.push(mcpToolCalls[part.id]);
break;
case "mcp_tool_result":
content.push({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: mcpToolCalls[part.tool_use_id].toolName,
isError: part.is_error,
result: part.content,
dynamic: true,
providerMetadata: mcpToolCalls[part.tool_use_id].providerMetadata
});
break;
case "web_fetch_tool_result":
if (part.content.type === "web_fetch_result") {
citationDocuments.push({
title: (_c = part.content.content.title) != null ? _c : part.content.url,
mediaType: part.content.content.source.media_type
});
content.push({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: toolNameMapping.toCustomToolName("web_fetch"),
result: {
type: "web_fetch_result",
url: part.content.url,
retrievedAt: part.content.retrieved_at,
content: {
type: part.content.content.type,
title: part.content.content.title,
citations: part.content.content.citations,
source: {
type: part.content.content.source.type,
mediaType: part.content.content.source.media_type,
data: part.content.content.source.data
}
}
},
...getAnthropicCallerMetadata(part.caller)
});
} else if (part.content.type === "web_fetch_tool_result_error") content.push({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: toolNameMapping.toCustomToolName("web_fetch"),
isError: true,
result: {
type: "web_fetch_tool_result_error",
errorCode: part.content.error_code
},
...getAnthropicCallerMetadata(part.caller)
});
break;
case "web_search_tool_result":
if (Array.isArray(part.content)) {
content.push({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: toolNameMapping.toCustomToolName("web_search"),
result: part.content.map((result) => {
var _a2;
return {
url: result.url,
title: result.title,
pageAge: (_a2 = result.page_age) != null ? _a2 : null,
encryptedContent: result.encrypted_content,
type: result.type
};
}),
...getAnthropicCallerMetadata(part.caller)
});
for (const result of part.content) content.push({
type: "source",
sourceType: "url",
id: this.generateId(),
url: result.url,
title: result.title,
providerMetadata: { anthropic: { pageAge: (_d = result.page_age) != null ? _d : null } }
});
} else content.push({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: toolNameMapping.toCustomToolName("web_search"),
isError: true,
result: {
type: "web_search_tool_result_error",
errorCode: part.content.error_code
},
...getAnthropicCallerMetadata(part.caller)
});
break;
case "code_execution_tool_result":
if (part.content.type === "code_execution_result") content.push({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: toolNameMapping.toCustomToolName("code_execution"),
result: {
type: part.content.type,
stdout: part.content.stdout,
stderr: part.content.stderr,
return_code: part.content.return_code,
content: (_e = part.content.content) != null ? _e : []
}
});
else if (part.content.type === "encrypted_code_execution_result") content.push({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: toolNameMapping.toCustomToolName("code_execution"),
result: {
type: part.content.type,
encrypted_stdout: part.content.encrypted_stdout,
stderr: part.content.stderr,
return_code: part.content.return_code,
content: (_f = part.content.content) != null ? _f : []
}
});
else if (part.content.type === "code_execution_tool_result_error") content.push({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: toolNameMapping.toCustomToolName("code_execution"),
isError: true,
result: {
type: "code_execution_tool_result_error",
errorCode: part.content.error_code
}
});
break;
case "bash_code_execution_tool_result":
case "text_editor_code_execution_tool_result":
content.push({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: toolNameMapping.toCustomToolName("code_execution"),
result: part.content
});
break;
case "tool_search_tool_result": {
let providerToolName = serverToolCalls[part.tool_use_id];
if (providerToolName == null) {
const bm25CustomName = toolNameMapping.toCustomToolName("tool_search_tool_bm25");
const regexCustomName = toolNameMapping.toCustomToolName("tool_search_tool_regex");
if (bm25CustomName !== "tool_search_tool_bm25") providerToolName = "tool_search_tool_bm25";
else if (regexCustomName !== "tool_search_tool_regex") providerToolName = "tool_search_tool_regex";
else providerToolName = "tool_search_tool_regex";
}
if (part.content.type === "tool_search_tool_search_result") content.push({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: toolNameMapping.toCustomToolName(providerToolName),
result: part.content.tool_references.map((ref) => ({
type: ref.type,
toolName: ref.tool_name
}))
});
else content.push({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: toolNameMapping.toCustomToolName(providerToolName),
isError: true,
result: {
type: "tool_search_tool_result_error",
errorCode: part.content.error_code
}
});
break;
}
case "advisor_tool_result": {
const advisorToolName = toolNameMapping.toCustomToolName("advisor");
if (part.content.type === "advisor_result") content.push({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: advisorToolName,
result: {
type: "advisor_result",
text: part.content.text
}
});
else if (part.content.type === "advisor_redacted_result") content.push({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: advisorToolName,
result: {
type: "advisor_redacted_result",
encryptedContent: part.content.encrypted_content
}
});
else content.push({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: advisorToolName,
isError: true,
result: {
type: "advisor_tool_result_error",
errorCode: part.content.error_code
}
});
break;
}
}
return {
content,
finishReason: {
unified: mapAnthropicStopReason({
finishReason: response.stop_reason,
isJsonResponseFromTool
}),
raw: (_g = response.stop_reason) != null ? _g : void 0
},
usage: convertAnthropicMessagesUsage({ usage: response.usage }),
request: { body: args },
response: {
id: (_h = response.id) != null ? _h : void 0,
modelId: (_i = response.model) != null ? _i : void 0,
headers: responseHeaders,
body: rawResponse
},
warnings,
providerMetadata: (() => {
var _a2, _b2, _c2, _d2, _e2;
const stopDetails = mapAnthropicStopDetails(response.stop_details);
const anthropicMetadata = {
usage: response.usage,
cacheCreationInputTokens: (_a2 = response.usage.cache_creation_input_tokens) != null ? _a2 : null,
stopSequence: (_b2 = response.stop_sequence) != null ? _b2 : null,
...stopDetails != null ? { stopDetails } : {},
...response.input_transformations != null ? { inputTransformations: response.input_transformations } : {},
...response.safeguard_results != null ? { safeguardResults: response.safeguard_results } : {},
iterations: response.usage.iterations ? response.usage.iterations.map((iter) => ({
type: iter.type,
...iter.model != null ? { model: iter.model } : {},
inputTokens: iter.input_tokens,
outputTokens: iter.output_tokens,
...iter.cache_creation_input_tokens ? { cacheCreationInputTokens: iter.cache_creation_input_tokens } : {},
...iter.cache_read_input_tokens ? { cacheReadInputTokens: iter.cache_read_input_tokens } : {}
})) : null,
container: response.container ? {
expiresAt: response.container.expires_at,
id: response.container.id,
skills: (_d2 = (_c2 = response.container.skills) == null ? void 0 : _c2.map((skill) => ({
type: skill.type,
skillId: skill.skill_id,
version: skill.version
}))) != null ? _d2 : null
} : null,
contextManagement: (_e2 = mapAnthropicResponseContextManagement(response.context_management)) != null ? _e2 : null
};
const providerMetadata = { anthropic: anthropicMetadata };
if (usedCustomProviderKey && providerOptionsName !== "anthropic") providerMetadata[providerOptionsName] = anthropicMetadata;
return providerMetadata;
})()
};
}
async doStream(options) {
var _a, _b;
const { args: body, warnings, betas, usesJsonResponseTool, toolNameMapping, providerOptionsName, usedCustomProviderKey } = await this.getArgs({
...options,
stream: true,
userSuppliedBetas: await this.getBetasFromHeaders(options.headers)
});
const citationDocuments = [...this.extractCitationDocuments(options.prompt)];
const markCodeExecutionDynamic = hasWebTool20260209WithoutCodeExecution(body.tools);
const url = this.buildRequestUrl(true);
const { responseHeaders, value: response } = await postJsonToApi$2({
url,
headers: await this.getHeaders({
betas,
headers: options.headers
}),
body: this.transformRequestBody(body, betas),
failedResponseHandler: anthropicFailedResponseHandler,
successfulResponseHandler: createEventSourceResponseHandler$2(anthropicMessagesChunkSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
let finishReason = {
unified: "other",
raw: void 0
};
const usage = {
input_tokens: 0,
output_tokens: 0,
cache_creation_input_tokens: 0,
cache_read_input_tokens: 0,
iterations: null
};
const contentBlocks = {};
const mcpToolCalls = {};
const serverToolCalls = {};
let contextManagement = null;
let rawUsage = void 0;
let cacheCreationInputTokens = null;
let stopSequence = null;
let stopDetails = void 0;
let inputTransformations;
let safeguardResults;
let container = null;
let isJsonResponseFromTool = false;
const heldBackText = [];
const heldBackTextByIndex = /* @__PURE__ */ new Map();
const createTextEnd = (id, citations) => ({
type: "text-end",
id,
...citations.length > 0 && { providerMetadata: { anthropic: { citations } } }
});
let isMessageOpen = false;
let activeMessageId;
let hasInvalidMessageSequence = false;
let blockType = void 0;
const generateId3 = this.generateId;
const [streamForFirstChunk, streamForConsumer] = response.pipeThrough(new TransformStream({
start(controller) {
controller.enqueue({
type: "stream-start",
warnings
});
},
transform(chunk, controller) {
var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
if (hasInvalidMessageSequence) return;
if (options.includeRawChunks) controller.enqueue({
type: "raw",
rawValue: chunk.rawValue
});
if (!chunk.success) {
controller.enqueue({
type: "error",
error: chunk.error
});
return;
}
const value = chunk.value;
switch (value.type) {
case "ping": return;
case "content_block_start": {
const part = value.content_block;
const contentBlockType = part.type;
if (contentBlockType === "fallback") return;
blockType = contentBlockType;
if (!TEXT_OR_THINKING_BLOCK_TYPES.has(contentBlockType)) heldBackText.length = 0;
switch (contentBlockType) {
case "text":
if (usesJsonResponseTool) {
const entry = {
id: String(value.index),
text: "",
citations: []
};
heldBackText.push(entry);
heldBackTextByIndex.set(value.index, entry);
return;
}
contentBlocks[value.index] = {
type: "text",
citations: []
};
controller.enqueue({
type: "text-start",
id: String(value.index)
});
return;
case "thinking":
contentBlocks[value.index] = { type: "reasoning" };
controller.enqueue({
type: "reasoning-start",
id: String(value.index)
});
return;
case "redacted_thinking":
contentBlocks[value.index] = { type: "reasoning" };
controller.enqueue({
type: "reasoning-start",
id: String(value.index),
providerMetadata: { anthropic: { redactedData: part.data } }
});
return;
case "compaction":
contentBlocks[value.index] = {
type: "text",
citations: []
};
controller.enqueue({
type: "text-start",
id: String(value.index),
providerMetadata: { anthropic: { type: "compaction" } }
});
return;
case "tool_use":
if (usesJsonResponseTool && part.name === "json") {
isJsonResponseFromTool = true;
contentBlocks[value.index] = {
type: "text",
citations: []
};
controller.enqueue({
type: "text-start",
id: String(value.index)
});
} else if (part.toolset_name != null) {
const callerInfo = getAnthropicCallerInfo(part.caller);
const customToolName = toolNameMapping.toCustomToolName(part.toolset_name);
const hasNonEmptyInput = part.input && Object.keys(part.input).length > 0;
contentBlocks[value.index] = {
type: "tool-call",
toolCallId: part.id,
toolName: customToolName,
input: hasNonEmptyInput ? JSON.stringify(part.input) : "",
firstDelta: true,
toolset: {
name: part.toolset_name,
memberName: part.name
},
...callerInfo && { caller: callerInfo }
};
controller.enqueue({
type: "tool-input-start",
id: part.id,
toolName: customToolName
});
} else {
const callerInfo = getAnthropicCallerInfo(part.caller);
const initialInput = part.input && Object.keys(part.input).length > 0 ? JSON.stringify(part.input) : "";
contentBlocks[value.index] = {
type: "tool-call",
toolCallId: part.id,
toolName: part.name,
input: initialInput,
firstDelta: initialInput.length === 0,
...callerInfo && { caller: callerInfo }
};
controller.enqueue({
type: "tool-input-start",
id: part.id,
toolName: part.name
});
}
return;
case "server_tool_use": {
const callerInfo = getAnthropicCallerInfo(part.caller);
if ([
"web_fetch",
"web_search",
"code_execution",
"text_editor_code_execution",
"bash_code_execution"
].includes(part.name)) {
const providerToolName = part.name === "text_editor_code_execution" || part.name === "bash_code_execution" ? "code_execution" : part.name;
const providerToolInputType = part.name === "text_editor_code_execution" || part.name === "bash_code_execution" ? part.name : part.name === "code_execution" ? "programmatic-tool-call" : void 0;
const customToolName = toolNameMapping.toCustomToolName(providerToolName);
const finalInput = part.input != null && typeof part.input === "object" && Object.keys(part.input).length > 0 ? JSON.stringify(part.input) : "";
contentBlocks[value.index] = {
type: "tool-call",
toolCallId: part.id,
toolName: customToolName,
input: finalInput,
providerExecuted: true,
...markCodeExecutionDynamic && providerToolName === "code_execution" ? { dynamic: true } : {},
firstDelta: finalInput.length === 0,
providerToolName,
providerToolInputType,
...callerInfo && { caller: callerInfo }
};
controller.enqueue({
type: "tool-input-start",
id: part.id,
toolName: customToolName,
providerExecuted: true,
...markCodeExecutionDynamic && providerToolName === "code_execution" ? { dynamic: true } : {}
});
} else if (part.name === "tool_search_tool_regex" || part.name === "tool_search_tool_bm25") {
serverToolCalls[part.id] = part.name;
const customToolName = toolNameMapping.toCustomToolName(part.name);
contentBlocks[value.index] = {
type: "tool-call",
toolCallId: part.id,
toolName: customToolName,
input: "",
providerExecuted: true,
firstDelta: true,
providerToolName: part.name,
...callerInfo && { caller: callerInfo }
};
controller.enqueue({
type: "tool-input-start",
id: part.id,
toolName: customToolName,
providerExecuted: true
});
} else if (part.name === "advisor") {
const customToolName = toolNameMapping.toCustomToolName("advisor");
contentBlocks[value.index] = {
type: "tool-call",
toolCallId: part.id,
toolName: customToolName,
input: "{}",
providerExecuted: true,
firstDelta: true,
providerToolName: part.name,
...callerInfo && { caller: callerInfo }
};
controller.enqueue({
type: "tool-input-start",
id: part.id,
toolName: customToolName,
providerExecuted: true
});
}
return;
}
case "web_fetch_tool_result":
if (part.content.type === "web_fetch_result") {
citationDocuments.push({
title: (_a2 = part.content.content.title) != null ? _a2 : part.content.url,
mediaType: part.content.content.source.media_type
});
controller.enqueue({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: toolNameMapping.toCustomToolName("web_fetch"),
result: {
type: "web_fetch_result",
url: part.content.url,
retrievedAt: part.content.retrieved_at,
content: {
type: part.content.content.type,
title: part.content.content.title,
citations: part.content.content.citations,
source: {
type: part.content.content.source.type,
mediaType: part.content.content.source.media_type,
data: part.content.content.source.data
}
}
},
...getAnthropicCallerMetadata(part.caller)
});
} else if (part.content.type === "web_fetch_tool_result_error") controller.enqueue({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: toolNameMapping.toCustomToolName("web_fetch"),
isError: true,
result: {
type: "web_fetch_tool_result_error",
errorCode: part.content.error_code
},
...getAnthropicCallerMetadata(part.caller)
});
return;
case "web_search_tool_result":
if (Array.isArray(part.content)) {
controller.enqueue({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: toolNameMapping.toCustomToolName("web_search"),
result: part.content.map((result) => {
var _a3;
return {
url: result.url,
title: result.title,
pageAge: (_a3 = result.page_age) != null ? _a3 : null,
encryptedContent: result.encrypted_content,
type: result.type
};
}),
...getAnthropicCallerMetadata(part.caller)
});
for (const result of part.content) controller.enqueue({
type: "source",
sourceType: "url",
id: generateId3(),
url: result.url,
title: result.title,
providerMetadata: { anthropic: { pageAge: (_b2 = result.page_age) != null ? _b2 : null } }
});
} else controller.enqueue({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: toolNameMapping.toCustomToolName("web_search"),
isError: true,
result: {
type: "web_search_tool_result_error",
errorCode: part.content.error_code
},
...getAnthropicCallerMetadata(part.caller)
});
return;
case "code_execution_tool_result":
if (part.content.type === "code_execution_result") controller.enqueue({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: toolNameMapping.toCustomToolName("code_execution"),
result: {
type: part.content.type,
stdout: part.content.stdout,
stderr: part.content.stderr,
return_code: part.content.return_code,
content: (_c = part.content.content) != null ? _c : []
}
});
else if (part.content.type === "encrypted_code_execution_result") controller.enqueue({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: toolNameMapping.toCustomToolName("code_execution"),
result: {
type: part.content.type,
encrypted_stdout: part.content.encrypted_stdout,
stderr: part.content.stderr,
return_code: part.content.return_code,
content: (_d = part.content.content) != null ? _d : []
}
});
else if (part.content.type === "code_execution_tool_result_error") controller.enqueue({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: toolNameMapping.toCustomToolName("code_execution"),
isError: true,
result: {
type: "code_execution_tool_result_error",
errorCode: part.content.error_code
}
});
return;
case "bash_code_execution_tool_result":
case "text_editor_code_execution_tool_result":
controller.enqueue({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: toolNameMapping.toCustomToolName("code_execution"),
result: part.content
});
return;
case "tool_search_tool_result": {
let providerToolName = serverToolCalls[part.tool_use_id];
if (providerToolName == null) {
const bm25CustomName = toolNameMapping.toCustomToolName("tool_search_tool_bm25");
const regexCustomName = toolNameMapping.toCustomToolName("tool_search_tool_regex");
if (bm25CustomName !== "tool_search_tool_bm25") providerToolName = "tool_search_tool_bm25";
else if (regexCustomName !== "tool_search_tool_regex") providerToolName = "tool_search_tool_regex";
else providerToolName = "tool_search_tool_regex";
}
if (part.content.type === "tool_search_tool_search_result") controller.enqueue({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: toolNameMapping.toCustomToolName(providerToolName),
result: part.content.tool_references.map((ref) => ({
type: ref.type,
toolName: ref.tool_name
}))
});
else controller.enqueue({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: toolNameMapping.toCustomToolName(providerToolName),
isError: true,
result: {
type: "tool_search_tool_result_error",
errorCode: part.content.error_code
}
});
return;
}
case "advisor_tool_result": {
const advisorToolName = toolNameMapping.toCustomToolName("advisor");
if (part.content.type === "advisor_result") controller.enqueue({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: advisorToolName,
result: {
type: "advisor_result",
text: part.content.text
}
});
else if (part.content.type === "advisor_redacted_result") controller.enqueue({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: advisorToolName,
result: {
type: "advisor_redacted_result",
encryptedContent: part.content.encrypted_content
}
});
else controller.enqueue({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: advisorToolName,
isError: true,
result: {
type: "advisor_tool_result_error",
errorCode: part.content.error_code
}
});
return;
}
case "mcp_tool_use":
mcpToolCalls[part.id] = {
type: "tool-call",
toolCallId: part.id,
toolName: part.name,
input: JSON.stringify(part.input),
providerExecuted: true,
dynamic: true,
providerMetadata: { anthropic: {
type: "mcp-tool-use",
serverName: part.server_name
} }
};
controller.enqueue(mcpToolCalls[part.id]);
return;
case "mcp_tool_result":
controller.enqueue({
type: "tool-result",
toolCallId: part.tool_use_id,
toolName: mcpToolCalls[part.tool_use_id].toolName,
isError: part.is_error,
result: part.content,
dynamic: true,
providerMetadata: mcpToolCalls[part.tool_use_id].providerMetadata
});
return;
default: throw new Error(`Unsupported content block type: ${contentBlockType}`);
}
}
case "content_block_stop":
if (contentBlocks[value.index] != null) {
const contentBlock = contentBlocks[value.index];
switch (contentBlock.type) {
case "text":
controller.enqueue(createTextEnd(String(value.index), contentBlock.citations));
break;
case "reasoning":
controller.enqueue({
type: "reasoning-end",
id: String(value.index)
});
break;
case "tool-call": if (!(usesJsonResponseTool && contentBlock.toolName === "json")) {
if (contentBlock.toolset != null) {
let memberInput = {};
try {
memberInput = contentBlock.input === "" ? {} : secureJsonParse$2(contentBlock.input);
} catch (e) {
memberInput = void 0;
}
contentBlock.input = memberInput === void 0 ? contentBlock.input : JSON.stringify(toToolsetMemberInput({
memberName: contentBlock.toolset.memberName,
input: memberInput
}));
controller.enqueue({
type: "tool-input-delta",
id: contentBlock.toolCallId,
delta: contentBlock.input
});
}
controller.enqueue({
type: "tool-input-end",
id: contentBlock.toolCallId
});
let finalInput = contentBlock.input === "" ? "{}" : contentBlock.input;
if (contentBlock.providerToolName === "code_execution") try {
const parsed = secureJsonParse$2(finalInput);
if (parsed != null && typeof parsed === "object" && "code" in parsed && !("type" in parsed)) finalInput = JSON.stringify({
type: "programmatic-tool-call",
...parsed
});
} catch (e) {}
controller.enqueue({
type: "tool-call",
toolCallId: contentBlock.toolCallId,
toolName: contentBlock.toolName,
input: finalInput,
providerExecuted: contentBlock.providerExecuted,
...markCodeExecutionDynamic && contentBlock.providerToolName === "code_execution" ? { dynamic: true } : {},
...(contentBlock.caller || contentBlock.toolset) && { providerMetadata: { anthropic: {
...contentBlock.toolset && { toolsetName: contentBlock.toolset.name },
...contentBlock.caller && { caller: contentBlock.caller }
} } }
});
}
}
delete contentBlocks[value.index];
}
blockType = void 0;
return;
case "content_block_delta": {
const deltaType = value.delta.type;
switch (deltaType) {
case "text_delta":
if (usesJsonResponseTool) {
const entry = heldBackTextByIndex.get(value.index);
if (entry != null) entry.text += value.delta.text;
return;
}
controller.enqueue({
type: "text-delta",
id: String(value.index),
delta: value.delta.text
});
return;
case "thinking_delta":
controller.enqueue({
type: "reasoning-delta",
id: String(value.index),
delta: value.delta.thinking
});
return;
case "signature_delta":
if (blockType === "thinking") controller.enqueue({
type: "reasoning-delta",
id: String(value.index),
delta: "",
providerMetadata: { anthropic: { signature: value.delta.signature } }
});
return;
case "compaction_delta":
if (value.delta.content != null) controller.enqueue({
type: "text-delta",
id: String(value.index),
delta: value.delta.content
});
return;
case "input_json_delta": {
const contentBlock = contentBlocks[value.index];
let delta = value.delta.partial_json;
if (delta.length === 0) return;
if (isJsonResponseFromTool) {
if ((contentBlock == null ? void 0 : contentBlock.type) !== "text") return;
controller.enqueue({
type: "text-delta",
id: String(value.index),
delta
});
} else {
if ((contentBlock == null ? void 0 : contentBlock.type) !== "tool-call") return;
if (contentBlock.toolset != null) {
contentBlock.input += delta;
return;
}
if (contentBlock.firstDelta && contentBlock.providerToolInputType != null) delta = `{"type": "${contentBlock.providerToolInputType}",${delta.substring(1)}`;
controller.enqueue({
type: "tool-input-delta",
id: contentBlock.toolCallId,
delta
});
contentBlock.input += delta;
contentBlock.firstDelta = false;
}
return;
}
case "citations_delta": {
const citation = value.delta.citation;
const contentBlock = contentBlocks[value.index];
if (citation.type === "web_search_result_location") {
if ((contentBlock == null ? void 0 : contentBlock.type) === "text") contentBlock.citations.push(citation);
(_e = heldBackTextByIndex.get(value.index)) == null || _e.citations.push(citation);
}
const source = createCitationSource(citation, citationDocuments, generateId3);
if (source) controller.enqueue(source);
return;
}
default: throw new Error(`Unsupported delta type: ${deltaType}`);
}
}
case "message_start":
if (isMessageOpen) {
if (activeMessageId === value.message.id) return;
hasInvalidMessageSequence = true;
controller.enqueue({
type: "error",
error: new InvalidResponseDataError$2({
data: value,
message: `Received message_start for message ${JSON.stringify(value.message.id)} while message ${JSON.stringify(activeMessageId)} is still open.`
})
});
return;
}
isMessageOpen = true;
activeMessageId = value.message.id;
heldBackTextByIndex.clear();
usage.input_tokens = value.message.usage.input_tokens;
usage.cache_read_input_tokens = (_f = value.message.usage.cache_read_input_tokens) != null ? _f : 0;
usage.cache_creation_input_tokens = (_g = value.message.usage.cache_creation_input_tokens) != null ? _g : 0;
rawUsage = { ...value.message.usage };
cacheCreationInputTokens = (_h = value.message.usage.cache_creation_input_tokens) != null ? _h : null;
if (value.message.input_transformations != null) inputTransformations = value.message.input_transformations;
if (value.message.container != null) container = {
expiresAt: value.message.container.expires_at,
id: value.message.container.id,
skills: null
};
if (value.message.stop_reason != null) finishReason = {
unified: mapAnthropicStopReason({
finishReason: value.message.stop_reason,
isJsonResponseFromTool
}),
raw: value.message.stop_reason
};
controller.enqueue({
type: "response-metadata",
id: (_i = value.message.id) != null ? _i : void 0,
modelId: (_j = value.message.model) != null ? _j : void 0
});
if (value.message.content != null) for (let contentIndex = 0; contentIndex < value.message.content.length; contentIndex++) {
const part = value.message.content[contentIndex];
if (part.type === "tool_use") {
const callerInfo = getAnthropicCallerInfo(part.caller);
controller.enqueue({
type: "tool-input-start",
id: part.id,
toolName: part.name
});
const inputStr = JSON.stringify((_k = part.input) != null ? _k : {});
controller.enqueue({
type: "tool-input-delta",
id: part.id,
delta: inputStr
});
controller.enqueue({
type: "tool-input-end",
id: part.id
});
controller.enqueue({
type: "tool-call",
toolCallId: part.id,
toolName: part.name,
input: inputStr,
...callerInfo && { providerMetadata: { anthropic: { caller: callerInfo } } }
});
}
}
return;
case "message_delta":
if (value.usage.input_tokens != null && usage.input_tokens !== value.usage.input_tokens) usage.input_tokens = value.usage.input_tokens;
usage.output_tokens = value.usage.output_tokens;
if (value.usage.output_tokens_details != null) usage.output_tokens_details = value.usage.output_tokens_details;
if (value.usage.cache_read_input_tokens != null) usage.cache_read_input_tokens = value.usage.cache_read_input_tokens;
if (value.usage.cache_creation_input_tokens != null) {
usage.cache_creation_input_tokens = value.usage.cache_creation_input_tokens;
cacheCreationInputTokens = value.usage.cache_creation_input_tokens;
}
if (value.usage.iterations != null) usage.iterations = value.usage.iterations;
finishReason = {
unified: mapAnthropicStopReason({
finishReason: value.delta.stop_reason,
isJsonResponseFromTool
}),
raw: (_l = value.delta.stop_reason) != null ? _l : void 0
};
stopSequence = (_m = value.delta.stop_sequence) != null ? _m : null;
stopDetails = mapAnthropicStopDetails(value.delta.stop_details);
container = value.delta.container != null ? {
expiresAt: value.delta.container.expires_at,
id: value.delta.container.id,
skills: (_o = (_n = value.delta.container.skills) == null ? void 0 : _n.map((skill) => ({
type: skill.type,
skillId: skill.skill_id,
version: skill.version
}))) != null ? _o : null
} : null;
if (value.context_management) contextManagement = mapAnthropicResponseContextManagement(value.context_management);
if (value.input_transformations != null) inputTransformations = value.input_transformations;
if (value.delta.safeguard_results != null) safeguardResults = value.delta.safeguard_results;
rawUsage = {
...rawUsage,
...value.usage
};
return;
case "message_stop": {
isMessageOpen = false;
activeMessageId = void 0;
const anthropicMetadata = {
usage: rawUsage != null ? rawUsage : null,
cacheCreationInputTokens,
stopSequence,
...stopDetails != null ? { stopDetails } : {},
...inputTransformations != null ? { inputTransformations } : {},
...safeguardResults != null ? { safeguardResults } : {},
iterations: usage.iterations ? usage.iterations.map((iter) => ({
type: iter.type,
...iter.model != null ? { model: iter.model } : {},
inputTokens: iter.input_tokens,
outputTokens: iter.output_tokens,
...iter.cache_creation_input_tokens ? { cacheCreationInputTokens: iter.cache_creation_input_tokens } : {},
...iter.cache_read_input_tokens ? { cacheReadInputTokens: iter.cache_read_input_tokens } : {}
})) : null,
container,
contextManagement
};
const providerMetadata = { anthropic: anthropicMetadata };
if (usedCustomProviderKey && providerOptionsName !== "anthropic") providerMetadata[providerOptionsName] = anthropicMetadata;
if (!isJsonResponseFromTool && !isContinuationStopReason(finishReason.raw)) for (const { id, text, citations } of heldBackText) {
if (text.length === 0) continue;
controller.enqueue({
type: "text-start",
id
});
controller.enqueue({
type: "text-delta",
id,
delta: text
});
controller.enqueue(createTextEnd(id, citations));
}
heldBackText.length = 0;
controller.enqueue({
type: "finish",
finishReason,
usage: convertAnthropicMessagesUsage({
usage,
rawUsage
}),
providerMetadata
});
return;
}
case "error":
controller.enqueue({
type: "error",
error: value.error
});
return;
default: throw new Error(`Unsupported chunk type: ${value}`);
}
}
})).tee();
const firstChunkReader = streamForFirstChunk.getReader();
try {
await firstChunkReader.read();
let result = await firstChunkReader.read();
if (((_a = result.value) == null ? void 0 : _a.type) === "raw") result = await firstChunkReader.read();
if (((_b = result.value) == null ? void 0 : _b.type) === "error") {
const error = result.value.error;
throw new APICallError$2({
message: error.message,
url,
requestBodyValues: body,
statusCode: error.type === "overloaded_error" ? 529 : 500,
responseHeaders,
responseBody: JSON.stringify(error),
isRetryable: error.type === "overloaded_error"
});
}
} finally {
firstChunkReader.cancel().catch(() => {});
firstChunkReader.releaseLock();
}
return {
stream: streamForConsumer,
request: { body },
response: { headers: responseHeaders }
};
}
};
function getModelCapabilities(modelId) {
if (modelId.includes("claude-sonnet-5-5")) return {
maxOutputTokens: 128e3,
supportsStructuredOutput: true,
rejectsSamplingParameters: true,
rejectsThinkingDisabledAboveHighEffort: true,
rejectsThinkingDisabled: true,
rejectsBudgetThinking: true,
rejectsForcedToolUse: true,
supportsBetweenToolsThinking: true,
isKnownModel: true
};
else if (modelId.includes("claude-opus-5-5")) return {
maxOutputTokens: 128e3,
supportsStructuredOutput: true,
rejectsSamplingParameters: true,
rejectsThinkingDisabledAboveHighEffort: true,
rejectsThinkingDisabled: true,
rejectsBudgetThinking: true,
rejectsForcedToolUse: true,
supportsBetweenToolsThinking: false,
isKnownModel: true
};
else if (modelId.includes("claude-haiku-5-5")) return {
maxOutputTokens: 128e3,
supportsStructuredOutput: true,
rejectsSamplingParameters: true,
rejectsThinkingDisabledAboveHighEffort: true,
rejectsThinkingDisabled: false,
rejectsBudgetThinking: true,
rejectsForcedToolUse: false,
supportsBetweenToolsThinking: false,
isKnownModel: true
};
else if (modelId.includes("claude-opus-5")) return {
maxOutputTokens: 128e3,
supportsStructuredOutput: true,
rejectsSamplingParameters: true,
rejectsThinkingDisabledAboveHighEffort: true,
rejectsThinkingDisabled: false,
rejectsBudgetThinking: false,
rejectsForcedToolUse: false,
supportsBetweenToolsThinking: false,
isKnownModel: true
};
else if (modelId.includes("claude-fable-5-1")) return {
maxOutputTokens: 128e3,
supportsStructuredOutput: true,
rejectsSamplingParameters: true,
rejectsThinkingDisabledAboveHighEffort: false,
rejectsThinkingDisabled: true,
rejectsBudgetThinking: true,
rejectsForcedToolUse: true,
supportsBetweenToolsThinking: false,
isKnownModel: true
};
else if (modelId.includes("claude-fable-5")) return {
maxOutputTokens: 128e3,
supportsStructuredOutput: true,
rejectsSamplingParameters: true,
rejectsThinkingDisabledAboveHighEffort: false,
rejectsThinkingDisabled: true,
rejectsBudgetThinking: true,
rejectsForcedToolUse: false,
supportsBetweenToolsThinking: false,
isKnownModel: true
};
else if (modelId.includes("claude-opus-4-8") || modelId.includes("claude-opus-4-7") || modelId.includes("claude-sonnet-5")) return {
maxOutputTokens: 128e3,
supportsStructuredOutput: true,
rejectsSamplingParameters: true,
rejectsThinkingDisabledAboveHighEffort: false,
rejectsThinkingDisabled: false,
rejectsBudgetThinking: false,
rejectsForcedToolUse: false,
supportsBetweenToolsThinking: false,
isKnownModel: true
};
else if (modelId.includes("claude-sonnet-4-6") || modelId.includes("claude-opus-4-6")) return {
maxOutputTokens: 128e3,
supportsStructuredOutput: true,
rejectsSamplingParameters: false,
rejectsThinkingDisabledAboveHighEffort: false,
rejectsThinkingDisabled: false,
rejectsBudgetThinking: false,
rejectsForcedToolUse: false,
supportsBetweenToolsThinking: false,
isKnownModel: true
};
else if (modelId.includes("claude-sonnet-4-5") || modelId.includes("claude-opus-4-5") || modelId.includes("claude-haiku-4-5")) return {
maxOutputTokens: 64e3,
supportsStructuredOutput: true,
rejectsSamplingParameters: false,
rejectsThinkingDisabledAboveHighEffort: false,
rejectsThinkingDisabled: false,
rejectsBudgetThinking: false,
rejectsForcedToolUse: false,
supportsBetweenToolsThinking: false,
isKnownModel: true
};
else if (modelId.includes("claude-opus-4-1")) return {
maxOutputTokens: 32e3,
supportsStructuredOutput: true,
rejectsSamplingParameters: false,
rejectsThinkingDisabledAboveHighEffort: false,
rejectsThinkingDisabled: false,
rejectsBudgetThinking: false,
rejectsForcedToolUse: false,
supportsBetweenToolsThinking: false,
isKnownModel: true
};
else if (modelId.includes("claude-sonnet-4-")) return {
maxOutputTokens: 64e3,
supportsStructuredOutput: false,
rejectsSamplingParameters: false,
rejectsThinkingDisabledAboveHighEffort: false,
rejectsThinkingDisabled: false,
rejectsBudgetThinking: false,
rejectsForcedToolUse: false,
supportsBetweenToolsThinking: false,
isKnownModel: true
};
else if (modelId.includes("claude-opus-4-")) return {
maxOutputTokens: 32e3,
supportsStructuredOutput: false,
rejectsSamplingParameters: false,
rejectsThinkingDisabledAboveHighEffort: false,
rejectsThinkingDisabled: false,
rejectsBudgetThinking: false,
rejectsForcedToolUse: false,
supportsBetweenToolsThinking: false,
isKnownModel: true
};
else if (modelId.includes("claude-3-haiku")) return {
maxOutputTokens: 4096,
supportsStructuredOutput: false,
rejectsSamplingParameters: false,
rejectsThinkingDisabledAboveHighEffort: false,
rejectsThinkingDisabled: false,
rejectsBudgetThinking: false,
rejectsForcedToolUse: false,
supportsBetweenToolsThinking: false,
isKnownModel: true
};
else if (/claude-(?:instant(?:-|$)|v?2(?=$|[-.:])|3(?=$|[-.]))/.test(modelId)) return {
maxOutputTokens: 4096,
supportsStructuredOutput: false,
rejectsSamplingParameters: false,
rejectsThinkingDisabledAboveHighEffort: false,
rejectsThinkingDisabled: false,
rejectsBudgetThinking: false,
rejectsForcedToolUse: false,
supportsBetweenToolsThinking: false,
isKnownModel: false
};
else if (modelId.includes("claude-")) return {
maxOutputTokens: 128e3,
supportsStructuredOutput: true,
rejectsSamplingParameters: true,
rejectsThinkingDisabledAboveHighEffort: true,
rejectsThinkingDisabled: false,
rejectsBudgetThinking: false,
rejectsForcedToolUse: false,
supportsBetweenToolsThinking: false,
isKnownModel: false
};
else return {
maxOutputTokens: 4096,
supportsStructuredOutput: false,
rejectsSamplingParameters: false,
rejectsThinkingDisabledAboveHighEffort: false,
rejectsThinkingDisabled: false,
rejectsBudgetThinking: false,
rejectsForcedToolUse: false,
supportsBetweenToolsThinking: false,
isKnownModel: false
};
}
function hasWebTool20260209WithoutCodeExecution(tools) {
if (!tools) return false;
let hasWebTool20260209 = false;
let hasCodeExecutionTool = false;
for (const tool of tools) {
if ("type" in tool && (tool.type === "web_fetch_20260209" || tool.type === "web_search_20260209")) {
hasWebTool20260209 = true;
continue;
}
if ("name" in tool && tool.name === "code_execution") {
hasCodeExecutionTool = true;
break;
}
}
return hasWebTool20260209 && !hasCodeExecutionTool;
}
function mapAnthropicResponseContextManagement(contextManagement) {
return contextManagement ? { appliedEdits: contextManagement.applied_edits.map((edit) => {
switch (edit.type) {
case "clear_tool_uses_20250919": return {
type: edit.type,
clearedToolUses: edit.cleared_tool_uses,
clearedInputTokens: edit.cleared_input_tokens
};
case "clear_thinking_20251015": return {
type: edit.type,
clearedThinkingTurns: edit.cleared_thinking_turns,
clearedInputTokens: edit.cleared_input_tokens
};
case "compact_20260112": return { type: edit.type };
}
}).filter((edit) => edit !== void 0) } : null;
}
function mapAnthropicStopDetails(stopDetails) {
if (stopDetails == null) return;
return {
type: stopDetails.type,
...stopDetails.category != null ? { category: stopDetails.category } : {},
...stopDetails.explanation != null ? { explanation: stopDetails.explanation } : {},
...stopDetails.recommended_model != null ? { recommendedModel: stopDetails.recommended_model } : {}
};
}
var bash_20241022 = createProviderToolFactory$1({
id: "anthropic.bash_20241022",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({
command: z.string(),
restart: z.boolean().optional()
})))
});
var bash_20250124 = createProviderToolFactory$1({
id: "anthropic.bash_20250124",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({
command: z.string(),
restart: z.boolean().optional()
})))
});
var computer_20241022 = createProviderToolFactory$1({
id: "anthropic.computer_20241022",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({
action: z.enum([
"key",
"type",
"mouse_move",
"left_click",
"left_click_drag",
"right_click",
"middle_click",
"double_click",
"screenshot",
"cursor_position"
]),
coordinate: z.array(z.number().int()).optional(),
text: z.string().optional()
})))
});
var computer_20250124 = createProviderToolFactory$1({
id: "anthropic.computer_20250124",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({
action: z.enum([
"key",
"hold_key",
"type",
"cursor_position",
"mouse_move",
"left_mouse_down",
"left_mouse_up",
"left_click",
"left_click_drag",
"right_click",
"middle_click",
"double_click",
"triple_click",
"scroll",
"wait",
"screenshot"
]),
coordinate: z.tuple([z.number().int(), z.number().int()]).optional(),
duration: z.number().optional(),
scroll_amount: z.number().optional(),
scroll_direction: z.enum([
"up",
"down",
"left",
"right"
]).optional(),
start_coordinate: z.tuple([z.number().int(), z.number().int()]).optional(),
text: z.string().optional()
})))
});
var computer_20251124 = createProviderToolFactory$1({
id: "anthropic.computer_20251124",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({
action: z.enum([
"key",
"hold_key",
"type",
"cursor_position",
"mouse_move",
"left_mouse_down",
"left_mouse_up",
"left_click",
"left_click_drag",
"right_click",
"middle_click",
"double_click",
"triple_click",
"scroll",
"wait",
"screenshot",
"zoom"
]),
coordinate: z.tuple([z.number().int(), z.number().int()]).optional(),
duration: z.number().optional(),
region: z.tuple([
z.number().int(),
z.number().int(),
z.number().int(),
z.number().int()
]).optional(),
scroll_amount: z.number().optional(),
scroll_direction: z.enum([
"up",
"down",
"left",
"right"
]).optional(),
start_coordinate: z.tuple([z.number().int(), z.number().int()]).optional(),
text: z.string().optional()
})))
});
var memory_20250818 = createProviderToolFactory$1({
id: "anthropic.memory_20250818",
inputSchema: lazySchema$1(() => zodSchema$2(z.discriminatedUnion("command", [
z.object({
command: z.literal("view"),
path: z.string(),
view_range: z.tuple([z.number(), z.number()]).optional()
}),
z.object({
command: z.literal("create"),
path: z.string(),
file_text: z.string()
}),
z.object({
command: z.literal("str_replace"),
path: z.string(),
old_str: z.string(),
new_str: z.string()
}),
z.object({
command: z.literal("insert"),
path: z.string(),
insert_line: z.number(),
insert_text: z.string()
}),
z.object({
command: z.literal("delete"),
path: z.string()
}),
z.object({
command: z.literal("rename"),
old_path: z.string(),
new_path: z.string()
})
])))
});
var textEditor_20241022 = createProviderToolFactory$1({
id: "anthropic.text_editor_20241022",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({
command: z.enum([
"view",
"create",
"str_replace",
"insert",
"undo_edit"
]),
path: z.string(),
file_text: z.string().optional(),
insert_line: z.number().int().optional(),
new_str: z.string().optional(),
insert_text: z.string().optional(),
old_str: z.string().optional(),
view_range: z.array(z.number().int()).optional()
})))
});
var textEditor_20250124 = createProviderToolFactory$1({
id: "anthropic.text_editor_20250124",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({
command: z.enum([
"view",
"create",
"str_replace",
"insert",
"undo_edit"
]),
path: z.string(),
file_text: z.string().optional(),
insert_line: z.number().int().optional(),
new_str: z.string().optional(),
insert_text: z.string().optional(),
old_str: z.string().optional(),
view_range: z.array(z.number().int()).optional()
})))
});
var textEditor_20250429 = createProviderToolFactory$1({
id: "anthropic.text_editor_20250429",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({
command: z.enum([
"view",
"create",
"str_replace",
"insert"
]),
path: z.string(),
file_text: z.string().optional(),
insert_line: z.number().int().optional(),
new_str: z.string().optional(),
insert_text: z.string().optional(),
old_str: z.string().optional(),
view_range: z.array(z.number().int()).optional()
})))
});
var toolSearchBm25_20251119OutputSchema = lazySchema$1(() => zodSchema$2(z.array(z.object({
type: z.literal("tool_reference"),
toolName: z.string()
}))));
var factory11 = createProviderToolFactoryWithOutputSchema({
id: "anthropic.tool_search_bm25_20251119",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({
/**
* A natural language query to search for tools.
* Claude will use BM25 text search to find relevant tools.
*/
query: z.string(),
/**
* Maximum number of tools to return. Optional.
*/
limit: z.number().optional()
}))),
outputSchema: toolSearchBm25_20251119OutputSchema,
supportsDeferredResults: true
});
var toolSearchBm25_20251119 = (args = {}) => {
return factory11(args);
};
var anthropicTools = {
/**
* Pairs a faster executor model with a higher-intelligence advisor model
* that provides strategic guidance mid-generation.
*
* The advisor lets a faster, lower-cost executor model consult a
* higher-intelligence advisor model server-side. The advisor reads the
* executor's full transcript and produces a plan or course correction;
* the executor continues with the task, informed by the advice. All of
* this happens inside a single `/v1/messages` request.
*
* Beta header `advisor-tool-2026-03-01` is added automatically when this
* tool is included.
*
* Multi-turn conversations: pass the full assistant content (including
* `advisor_tool_result` blocks) back to the API on subsequent turns. If
* you omit the advisor tool from `tools` on a follow-up turn while the
* message history still contains `advisor_tool_result` blocks, the API
* returns a `400 invalid_request_error`.
*
* Supported executor models: Claude Haiku 4.5, Sonnet 4.6, Opus 4.6,
* Opus 4.7. The advisor must be at least as capable as the executor.
*
* @param model - The advisor model ID (required), e.g. `"claude-opus-4-8"`.
* @param maxUses - Maximum advisor calls per request (per-request cap).
* @param caching - Enables prompt caching for the advisor's transcript
* across calls within a conversation. Worthwhile from ~3 advisor calls
* per conversation.
*/
advisor_20260301,
/**
* The bash tool enables Claude to execute shell commands in a persistent bash session,
* allowing system operations, script execution, and command-line automation.
*
* Image results are supported.
*/
bash_20241022,
/**
* The bash tool enables Claude to execute shell commands in a persistent bash session,
* allowing system operations, script execution, and command-line automation.
*
* Image results are supported.
*/
bash_20250124,
/**
* Claude can analyze data, create visualizations, perform complex calculations,
* run system commands, create and edit files, and process uploaded files directly within
* the API conversation.
*
* The code execution tool allows Claude to run Bash commands and manipulate files,
* including writing code, in a secure, sandboxed environment.
*/
codeExecution_20250522,
/**
* Claude can analyze data, create visualizations, perform complex calculations,
* run system commands, create and edit files, and process uploaded files directly within
* the API conversation.
*
* The code execution tool allows Claude to run both Python and Bash commands and manipulate files,
* including writing code, in a secure, sandboxed environment.
*
* This is the latest version with enhanced Bash support and file operations.
*/
codeExecution_20250825,
/**
* Claude can analyze data, create visualizations, perform complex calculations,
* run system commands, create and edit files, and process uploaded files directly within
* the API conversation.
*
* The code execution tool allows Claude to run both Python and Bash commands and manipulate files,
* including writing code, in a secure, sandboxed environment.
*
* This is the recommended version. Does not require a beta header.
*
* Supported models: Claude Opus 4.6, Sonnet 4.6, Sonnet 4.5, Opus 4.5
*/
codeExecution_20260120,
/**
* Claude can interact with computer environments through the computer use tool, which
* provides screenshot capabilities and mouse/keyboard control for autonomous desktop interaction.
*
* Image results are supported.
*
* @param displayWidthPx - The width of the display being controlled by the model in pixels.
* @param displayHeightPx - The height of the display being controlled by the model in pixels.
* @param displayNumber - The display number to control (only relevant for X11 environments). If specified, the tool will be provided a display number in the tool definition.
*/
computer_20241022,
/**
* Claude can interact with computer environments through the computer use tool, which
* provides screenshot capabilities and mouse/keyboard control for autonomous desktop interaction.
*
* Image results are supported.
*
* @param displayWidthPx - The width of the display being controlled by the model in pixels.
* @param displayHeightPx - The height of the display being controlled by the model in pixels.
* @param displayNumber - The display number to control (only relevant for X11 environments). If specified, the tool will be provided a display number in the tool definition.
*/
computer_20250124,
/**
* Claude can interact with computer environments through the computer use tool, which
* provides screenshot capabilities and mouse/keyboard control for autonomous desktop interaction.
*
* This version adds the zoom action for detailed screen region inspection.
*
* Image results are supported.
*
* Supported models: Claude Opus 4.5
*
* @param displayWidthPx - The width of the display being controlled by the model in pixels.
* @param displayHeightPx - The height of the display being controlled by the model in pixels.
* @param displayNumber - The display number to control (only relevant for X11 environments). If specified, the tool will be provided a display number in the tool definition.
* @param enableZoom - Enable zoom action. Set to true to allow Claude to zoom into specific screen regions. Default: false.
*/
computer_20251124,
/**
* The computer toolset lets Claude control a computer through screenshots,
* mouse, and keyboard. It replaces the versioned computer tools
* (`computer_20251124` and earlier) on newer models.
*
* The API returns each computer action as its own `tool_use` block with
* `toolset_name: 'computer'`. The AI SDK maps every member call to this tool
* and exposes the member name as `action`, so `execute` receives the same
* input shape as the older computer tools. Claude may return several actions
* in one turn.
*
* Coordinates are always in the pixel space of the screenshots you return;
* there are no display size parameters. Zoom is enabled by default.
*
* Does not require a beta header.
*
* Supported models: Claude Opus 5.5 (required; older computer tool types
* are rejected), Opus 5, Sonnet 5, Fable 5, Fable 5.1, Opus 4.8.
*
* @param configs - Per-member settings keyed by member name, e.g.
* `{ zoom: { enabled: false } }`. Omitted members keep their defaults.
*/
computerToolset_20260801,
/**
* The memory tool enables Claude to store and retrieve information across conversations through a memory file directory.
* Claude can create, read, update, and delete files that persist between sessions,
* allowing it to build knowledge over time without keeping everything in the context window.
* The memory tool operates client-side—you control where and how the data is stored through your own infrastructure.
*
* Supported models: Claude Sonnet 4.5, Claude Sonnet 4, Claude Opus 4.1, Claude Opus 4.
*/
memory_20250818,
/**
* Claude can use an Anthropic-defined text editor tool to view and modify text files,
* helping you debug, fix, and improve your code or other text documents. This allows Claude
* to directly interact with your files, providing hands-on assistance rather than just suggesting changes.
*
* Supported models: Claude Sonnet 3.5
*/
textEditor_20241022,
/**
* Claude can use an Anthropic-defined text editor tool to view and modify text files,
* helping you debug, fix, and improve your code or other text documents. This allows Claude
* to directly interact with your files, providing hands-on assistance rather than just suggesting changes.
*
* Supported models: Claude Sonnet 3.7
*/
textEditor_20250124,
/**
* Claude can use an Anthropic-defined text editor tool to view and modify text files,
* helping you debug, fix, and improve your code or other text documents. This allows Claude
* to directly interact with your files, providing hands-on assistance rather than just suggesting changes.
*
* Note: This version does not support the "undo_edit" command.
*
* @deprecated Use textEditor_20250728 instead
*/
textEditor_20250429,
/**
* Claude can use an Anthropic-defined text editor tool to view and modify text files,
* helping you debug, fix, and improve your code or other text documents. This allows Claude
* to directly interact with your files, providing hands-on assistance rather than just suggesting changes.
*
* Note: This version does not support the "undo_edit" command and adds optional max_characters parameter.
*
* Supported models: Claude Sonnet 4, Opus 4, and Opus 4.1
*
* @param maxCharacters - Optional maximum number of characters to view in the file
*/
textEditor_20250728,
/**
* Creates a web fetch tool that gives Claude direct access to real-time web content.
*
* @param maxUses - The max_uses parameter limits the number of web fetches performed
* @param allowedDomains - Only fetch from these domains
* @param blockedDomains - Never fetch from these domains
* @param citations - Unlike web search where citations are always enabled, citations are optional for web fetch. Set "citations": {"enabled": true} to enable Claude to cite specific passages from fetched documents.
* @param maxContentTokens - The max_content_tokens parameter limits the amount of content that will be included in the context.
*/
webFetch_20250910,
/**
* Creates a web fetch tool that gives Claude direct access to real-time web content.
*
* @param maxUses - The max_uses parameter limits the number of web fetches performed
* @param allowedDomains - Only fetch from these domains
* @param blockedDomains - Never fetch from these domains
* @param citations - Unlike web search where citations are always enabled, citations are optional for web fetch. Set "citations": {"enabled": true} to enable Claude to cite specific passages from fetched documents.
* @param maxContentTokens - The max_content_tokens parameter limits the amount of content that will be included in the context.
*/
webFetch_20260209,
/**
* Creates a web search tool that gives Claude direct access to real-time web content.
*
* @param maxUses - Maximum number of web searches Claude can perform during the conversation.
* @param allowedDomains - Optional list of domains that Claude is allowed to search.
* @param blockedDomains - Optional list of domains that Claude should avoid when searching.
* @param userLocation - Optional user location information to provide geographically relevant search results.
*/
webSearch_20250305,
/**
* Creates a web search tool that gives Claude direct access to real-time web content.
*
* @param maxUses - Maximum number of web searches Claude can perform during the conversation.
* @param allowedDomains - Optional list of domains that Claude is allowed to search.
* @param blockedDomains - Optional list of domains that Claude should avoid when searching.
* @param userLocation - Optional user location information to provide geographically relevant search results.
*/
webSearch_20260209,
/**
* Creates a tool search tool that uses regex patterns to find tools.
*
* The tool search tool enables Claude to work with hundreds or thousands of tools
* by dynamically discovering and loading them on-demand. Instead of loading all
* tool definitions into the context window upfront, Claude searches your tool
* catalog and loads only the tools it needs.
*
* Use `providerOptions: { anthropic: { deferLoading: true } }` on other tools
* to mark them for deferred loading.
*
* Supported models: Claude Opus 4.5, Claude Sonnet 4.5
*/
toolSearchRegex_20251119,
/**
* Creates a tool search tool that uses BM25 (natural language) to find tools.
*
* The tool search tool enables Claude to work with hundreds or thousands of tools
* by dynamically discovering and loading them on-demand. Instead of loading all
* tool definitions into the context window upfront, Claude searches your tool
* catalog and loads only the tools it needs.
*
* Use `providerOptions: { anthropic: { deferLoading: true } }` on other tools
* to mark them for deferred loading.
*
* Supported models: Claude Opus 4.5, Claude Sonnet 4.5
*/
toolSearchBm25_20251119
};
var ANTHROPIC_API_URL = "https://api.anthropic.com";
var ANTHROPIC_API_VERSIONED_URL = `${ANTHROPIC_API_URL}/v1`;
function normalizeBaseURL(baseURL) {
const baseURLWithoutTrailingSlash = withoutTrailingSlash$2(baseURL);
return baseURLWithoutTrailingSlash === ANTHROPIC_API_URL ? ANTHROPIC_API_VERSIONED_URL : baseURLWithoutTrailingSlash;
}
function createAnthropic(options = {}) {
var _a, _b;
const baseURL = (_a = normalizeBaseURL(loadOptionalSetting({
settingValue: options.baseURL,
environmentVariableName: "ANTHROPIC_BASE_URL"
}))) != null ? _a : ANTHROPIC_API_VERSIONED_URL;
const providerName = (_b = options.name) != null ? _b : "anthropic.messages";
if (options.apiKey && options.authToken) throw new InvalidArgumentError$2({
argument: "apiKey/authToken",
message: "Both apiKey and authToken were provided. Please use only one authentication method."
});
const getHeaders = () => {
return withUserAgentSuffix$2({
"anthropic-version": "2023-06-01",
...options.authToken ? { Authorization: `Bearer ${options.authToken}` } : { "x-api-key": loadApiKey$2({
apiKey: options.apiKey,
environmentVariableName: "ANTHROPIC_API_KEY",
description: "Anthropic"
}) },
...options.headers
}, `ai-sdk/anthropic/${VERSION$12}`);
};
const createChatModel = (modelId) => {
var _a2;
return new AnthropicMessagesLanguageModel(modelId, {
provider: providerName,
baseURL,
headers: getHeaders,
fetch: options.fetch,
generateId: (_a2 = options.generateId) != null ? _a2 : generateId$2,
supportedUrls: () => ({
"image/*": [/^https?:\/\/.*$/],
"application/pdf": [/^https?:\/\/.*$/]
})
});
};
const provider = function(modelId) {
if (new.target) throw new Error("The Anthropic model function cannot be called with the new keyword.");
return createChatModel(modelId);
};
provider.specificationVersion = "v3";
provider.languageModel = createChatModel;
provider.chat = createChatModel;
provider.messages = createChatModel;
provider.embeddingModel = (modelId) => {
throw new NoSuchModelError$1({
modelId,
modelType: "embeddingModel"
});
};
provider.textEmbeddingModel = provider.embeddingModel;
provider.imageModel = (modelId) => {
throw new NoSuchModelError$1({
modelId,
modelType: "imageModel"
});
};
provider.tools = anthropicTools;
return provider;
}
createAnthropic();
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@openrouter/ai-sdk-provider/2.10.0/fe7a784499db3b65cf38b322ecc530d9838876359332081cbef953596975467b/node_modules/@openrouter/ai-sdk-provider/dist/index.mjs
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
enumerable: true,
configurable: true,
writable: true,
value
}) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols) {
for (var prop of __getOwnPropSymbols(b)) if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __objRest = (source, exclude) => {
var target = {};
for (var prop in source) if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0) target[prop] = source[prop];
if (source != null && __getOwnPropSymbols) {
for (var prop of __getOwnPropSymbols(source)) if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop)) target[prop] = source[prop];
}
return target;
};
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var marker$13 = "vercel.ai.error";
var symbol$12 = Symbol.for(marker$13);
var _a$1;
var _b;
var AISDKError$1 = class _AISDKError extends (_b = Error, _a$1 = symbol$12, _b) {
/**
* Creates an AI SDK Error.
*
* @param {Object} params - The parameters for creating the error.
* @param {string} params.name - The name of the error.
* @param {string} params.message - The error message.
* @param {unknown} [params.cause] - The underlying cause of the error.
*/
constructor({ name: name142, message, cause }) {
super(message);
this[_a$1] = true;
this.name = name142;
this.cause = cause;
}
/**
* Checks if the given error is an AI SDK Error.
* @param {unknown} error - The error to check.
* @returns {boolean} True if the error is an AI SDK Error, false otherwise.
*/
static isInstance(error) {
return _AISDKError.hasMarker(error, marker$13);
}
static hasMarker(error, marker152) {
const markerSymbol = Symbol.for(marker152);
return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
}
};
var name$5 = "AI_APICallError";
var marker2 = `vercel.ai.error.${name$5}`;
var symbol2 = Symbol.for(marker2);
var _a2;
var _b2;
var APICallError$1 = class extends (_b2 = AISDKError$1, _a2 = symbol2, _b2) {
constructor({ message, url, requestBodyValues, statusCode, responseHeaders, responseBody, cause, isRetryable = statusCode != null && (statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500), data }) {
super({
name: name$5,
message,
cause
});
this[_a2] = true;
this.url = url;
this.requestBodyValues = requestBodyValues;
this.statusCode = statusCode;
this.responseHeaders = responseHeaders;
this.responseBody = responseBody;
this.isRetryable = isRetryable;
this.data = data;
}
static isInstance(error) {
return AISDKError$1.hasMarker(error, marker2);
}
};
var name2 = "AI_EmptyResponseBodyError";
var marker3 = `vercel.ai.error.${name2}`;
var symbol3 = Symbol.for(marker3);
var _a3;
var _b3;
var EmptyResponseBodyError$1 = class extends (_b3 = AISDKError$1, _a3 = symbol3, _b3) {
constructor({ message = "Empty response body" } = {}) {
super({
name: name2,
message
});
this[_a3] = true;
}
static isInstance(error) {
return AISDKError$1.hasMarker(error, marker3);
}
};
function getErrorMessage$1(error) {
if (error == null) return "unknown error";
if (typeof error === "string") return error;
if (error instanceof Error) return error.message;
return JSON.stringify(error);
}
var name3 = "AI_InvalidArgumentError";
var marker4 = `vercel.ai.error.${name3}`;
var symbol4 = Symbol.for(marker4);
var _a4;
var _b4;
var InvalidArgumentError$1 = class extends (_b4 = AISDKError$1, _a4 = symbol4, _b4) {
constructor({ message, cause, argument }) {
super({
name: name3,
message,
cause
});
this[_a4] = true;
this.argument = argument;
}
static isInstance(error) {
return AISDKError$1.hasMarker(error, marker4);
}
};
var name4 = "AI_InvalidPromptError";
var marker5 = `vercel.ai.error.${name4}`;
var symbol5 = Symbol.for(marker5);
var _a5;
var _b5;
var InvalidPromptError$1 = class extends (_b5 = AISDKError$1, _a5 = symbol5, _b5) {
constructor({ prompt, message, cause }) {
super({
name: name4,
message: `Invalid prompt: ${message}`,
cause
});
this[_a5] = true;
this.prompt = prompt;
}
static isInstance(error) {
return AISDKError$1.hasMarker(error, marker5);
}
};
var name5 = "AI_InvalidResponseDataError";
var marker6 = `vercel.ai.error.${name5}`;
var symbol6 = Symbol.for(marker6);
var _a6;
var _b6;
var InvalidResponseDataError$1 = class extends (_b6 = AISDKError$1, _a6 = symbol6, _b6) {
constructor({ data, message = `Invalid response data: ${JSON.stringify(data)}.` }) {
super({
name: name5,
message
});
this[_a6] = true;
this.data = data;
}
static isInstance(error) {
return AISDKError$1.hasMarker(error, marker6);
}
};
var name6 = "AI_JSONParseError";
var marker7 = `vercel.ai.error.${name6}`;
var symbol7 = Symbol.for(marker7);
var _a7;
var _b7;
var JSONParseError$1 = class extends (_b7 = AISDKError$1, _a7 = symbol7, _b7) {
constructor({ text, cause }) {
super({
name: name6,
message: `JSON parsing failed: Text: ${text}.
Error message: ${getErrorMessage$1(cause)}`,
cause
});
this[_a7] = true;
this.text = text;
}
static isInstance(error) {
return AISDKError$1.hasMarker(error, marker7);
}
};
var name7 = "AI_LoadAPIKeyError";
var marker8 = `vercel.ai.error.${name7}`;
var symbol8 = Symbol.for(marker8);
var _a8;
var _b8;
var LoadAPIKeyError$1 = class extends (_b8 = AISDKError$1, _a8 = symbol8, _b8) {
constructor({ message }) {
super({
name: name7,
message
});
this[_a8] = true;
}
static isInstance(error) {
return AISDKError$1.hasMarker(error, marker8);
}
};
var name9 = "AI_NoContentGeneratedError";
var marker10 = `vercel.ai.error.${name9}`;
var symbol10 = Symbol.for(marker10);
var _a10;
var _b10;
var NoContentGeneratedError = class extends (_b10 = AISDKError$1, _a10 = symbol10, _b10) {
constructor({ message = "No content generated." } = {}) {
super({
name: name9,
message
});
this[_a10] = true;
}
static isInstance(error) {
return AISDKError$1.hasMarker(error, marker10);
}
};
var name12 = "AI_TypeValidationError";
var marker13 = `vercel.ai.error.${name12}`;
var symbol13 = Symbol.for(marker13);
var _a13;
var _b13;
var TypeValidationError$1 = class _TypeValidationError extends (_b13 = AISDKError$1, _a13 = symbol13, _b13) {
constructor({ value, cause, context }) {
let contextPrefix = "Type validation failed";
if (context == null ? void 0 : context.field) contextPrefix += ` for ${context.field}`;
if ((context == null ? void 0 : context.entityName) || (context == null ? void 0 : context.entityId)) {
contextPrefix += " (";
const parts = [];
if (context.entityName) parts.push(context.entityName);
if (context.entityId) parts.push(`id: "${context.entityId}"`);
contextPrefix += parts.join(", ");
contextPrefix += ")";
}
super({
name: name12,
message: `${contextPrefix}: Value: ${JSON.stringify(value)}.
Error message: ${getErrorMessage$1(cause)}`,
cause
});
this[_a13] = true;
this.value = value;
this.context = context;
}
static isInstance(error) {
return AISDKError$1.hasMarker(error, marker13);
}
/**
* Wraps an error into a TypeValidationError.
* If the cause is already a TypeValidationError with the same value and context, it returns the cause.
* Otherwise, it creates a new TypeValidationError.
*
* @param {Object} params - The parameters for wrapping the error.
* @param {unknown} params.value - The value that failed validation.
* @param {unknown} params.cause - The original error or cause of the validation failure.
* @param {TypeValidationContext} params.context - Optional context about what is being validated.
* @returns {TypeValidationError} A TypeValidationError instance.
*/
static wrap({ value, cause, context }) {
var _a152, _b152, _c;
if (_TypeValidationError.isInstance(cause) && cause.value === value && ((_a152 = cause.context) == null ? void 0 : _a152.field) === (context == null ? void 0 : context.field) && ((_b152 = cause.context) == null ? void 0 : _b152.entityName) === (context == null ? void 0 : context.entityName) && ((_c = cause.context) == null ? void 0 : _c.entityId) === (context == null ? void 0 : context.entityId)) return cause;
return new _TypeValidationError({
value,
cause,
context
});
}
};
var name13 = "AI_UnsupportedFunctionalityError";
var marker14 = `vercel.ai.error.${name13}`;
var symbol14 = Symbol.for(marker14);
var _a14;
var _b14;
var UnsupportedFunctionalityError$1 = class extends (_b14 = AISDKError$1, _a14 = symbol14, _b14) {
constructor({ functionality, message = `'${functionality}' functionality not supported.` }) {
super({
name: name13,
message
});
this[_a14] = true;
this.functionality = functionality;
}
static isInstance(error) {
return AISDKError$1.hasMarker(error, marker14);
}
};
var ParseError = class extends Error {
constructor(message, options) {
super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
}
};
function noop(_arg) {}
function createParser(callbacks) {
if (typeof callbacks == "function") throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");
const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
function feed(newChunk) {
const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
for (const line of complete) parseLine(line);
incompleteLine = incomplete, isFirstChunk = false;
}
function parseLine(line) {
if (line === "") {
dispatchEvent();
return;
}
if (line.startsWith(":")) {
onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
return;
}
const fieldSeparatorIndex = line.indexOf(":");
if (fieldSeparatorIndex !== -1) {
const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1;
processField(field, line.slice(fieldSeparatorIndex + offset), line);
return;
}
processField(line, "", line);
}
function processField(field, value, line) {
switch (field) {
case "event":
eventType = value;
break;
case "data":
data = `${data}${value}
`;
break;
case "id":
id = value.includes("\0") ? void 0 : value;
break;
case "retry":
/^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(new ParseError(`Invalid \`retry\` value: "${value}"`, {
type: "invalid-retry",
value,
line
}));
break;
default: onError(new ParseError(`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, {
type: "unknown-field",
field,
value,
line
}));
}
}
function dispatchEvent() {
data.length > 0 && onEvent({
id,
event: eventType || void 0,
data: data.endsWith(`
`) ? data.slice(0, -1) : data
}), id = void 0, data = "", eventType = "";
}
function reset(options = {}) {
incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
}
return {
feed,
reset
};
}
function splitLines(chunk) {
const lines = [];
let incompleteLine = "", searchIndex = 0;
for (; searchIndex < chunk.length;) {
const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
`, searchIndex);
let lineEnd = -1;
if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
incompleteLine = chunk.slice(searchIndex);
break;
} else {
const line = chunk.slice(searchIndex, lineEnd);
lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
` && searchIndex++;
}
}
return [lines, incompleteLine];
}
var EventSourceParserStream = class extends TransformStream {
constructor({ onError, onRetry, onComment } = {}) {
let parser;
super({
start(controller) {
parser = createParser({
onEvent: (event) => {
controller.enqueue(event);
},
onError(error) {
onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
},
onRetry,
onComment
});
},
transform(chunk) {
parser.feed(chunk);
}
});
}
};
function combineHeaders$1(...headers) {
return headers.reduce((combinedHeaders, currentHeaders) => __spreadValues(__spreadValues({}, combinedHeaders), currentHeaders != null ? currentHeaders : {}), {});
}
async function delay$1(delayInMs, options) {
if (delayInMs == null) return Promise.resolve();
const signal = options == null ? void 0 : options.abortSignal;
return new Promise((resolve2, reject) => {
if (signal == null ? void 0 : signal.aborted) {
reject(createAbortError$1());
return;
}
const timeoutId = setTimeout(() => {
cleanup();
resolve2();
}, delayInMs);
const cleanup = () => {
clearTimeout(timeoutId);
signal?.removeEventListener("abort", onAbort);
};
const onAbort = () => {
cleanup();
reject(createAbortError$1());
};
signal?.addEventListener("abort", onAbort);
});
}
function createAbortError$1() {
return new DOMException("Delay was aborted", "AbortError");
}
function extractResponseHeaders$1(response) {
return Object.fromEntries([...response.headers]);
}
var { btoa: btoa$1, atob: atob$1 } = globalThis;
function convertUint8ArrayToBase64$1(array) {
let latin1string = "";
for (let i = 0; i < array.length; i++) latin1string += String.fromCodePoint(array[i]);
return btoa$1(latin1string);
}
var createIdGenerator$1 = ({ prefix, size = 16, alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", separator = "-" } = {}) => {
const generator = () => {
const alphabetLength = alphabet.length;
const chars = new Array(size);
for (let i = 0; i < size; i++) chars[i] = alphabet[Math.random() * alphabetLength | 0];
return chars.join("");
};
if (prefix == null) return generator;
if (alphabet.includes(separator)) throw new InvalidArgumentError$1({
argument: "separator",
message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
});
return () => `${prefix}${separator}${generator()}`;
};
var generateId$1 = createIdGenerator$1();
function isAbortError$1(error) {
return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || error.name === "TimeoutError");
}
var FETCH_FAILED_ERROR_MESSAGES$1 = ["fetch failed", "failed to fetch"];
var BUN_ERROR_CODES = [
"ConnectionRefused",
"ConnectionClosed",
"FailedToOpenSocket",
"ECONNRESET",
"ECONNREFUSED",
"ETIMEDOUT",
"EPIPE"
];
function isBunNetworkError(error) {
if (!(error instanceof Error)) return false;
const code = error.code;
if (typeof code === "string" && BUN_ERROR_CODES.includes(code)) return true;
return false;
}
function handleFetchError$1({ error, url, requestBodyValues }) {
if (isAbortError$1(error)) return error;
if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES$1.includes(error.message.toLowerCase())) {
const cause = error.cause;
if (cause != null) return new APICallError$1({
message: `Cannot connect to API: ${cause.message}`,
cause,
url,
requestBodyValues,
isRetryable: true
});
}
if (isBunNetworkError(error)) return new APICallError$1({
message: `Cannot connect to API: ${error.message}`,
cause: error,
url,
requestBodyValues,
isRetryable: true
});
return error;
}
function getRuntimeEnvironmentUserAgent$1(globalThisAny = globalThis) {
var _a22, _b22, _c;
if (globalThisAny.window) return `runtime/browser`;
if ((_a22 = globalThisAny.navigator) == null ? void 0 : _a22.userAgent) return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
if ((_c = (_b22 = globalThisAny.process) == null ? void 0 : _b22.versions) == null ? void 0 : _c.node) return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
if (globalThisAny.EdgeRuntime) return `runtime/vercel-edge`;
return "runtime/unknown";
}
function normalizeHeaders$1(headers) {
if (headers == null) return {};
const normalized = {};
if (headers instanceof Headers) headers.forEach((value, key) => {
normalized[key.toLowerCase()] = value;
});
else {
if (!Array.isArray(headers)) headers = Object.entries(headers);
for (const [key, value] of headers) if (value != null) normalized[key.toLowerCase()] = value;
}
return normalized;
}
function withUserAgentSuffix$1(headers, ...userAgentSuffixParts) {
const normalizedHeaders = new Headers(normalizeHeaders$1(headers));
const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
normalizedHeaders.set("user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" "));
return Object.fromEntries(normalizedHeaders.entries());
}
var VERSION$11 = "4.0.23";
var getOriginalFetch$5 = () => globalThis.fetch;
var getFromApi$1 = async ({ url, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch$5() }) => {
try {
const response = await fetch2(url, {
method: "GET",
headers: withUserAgentSuffix$1(headers, `ai-sdk/provider-utils/${VERSION$11}`, getRuntimeEnvironmentUserAgent$1()),
signal: abortSignal
});
const responseHeaders = extractResponseHeaders$1(response);
if (!response.ok) {
let errorInformation;
try {
errorInformation = await failedResponseHandler({
response,
url,
requestBodyValues: {}
});
} catch (error) {
if (isAbortError$1(error) || APICallError$1.isInstance(error)) throw error;
throw new APICallError$1({
message: "Failed to process error response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: {}
});
}
throw errorInformation.value;
}
try {
return await successfulResponseHandler({
response,
url,
requestBodyValues: {}
});
} catch (error) {
if (error instanceof Error) {
if (isAbortError$1(error) || APICallError$1.isInstance(error)) throw error;
}
throw new APICallError$1({
message: "Failed to process successful response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: {}
});
}
} catch (error) {
throw handleFetchError$1({
error,
url,
requestBodyValues: {}
});
}
};
function loadApiKey$1({ apiKey, environmentVariableName, apiKeyParameterName = "apiKey", description }) {
if (typeof apiKey === "string") return apiKey;
if (apiKey != null) throw new LoadAPIKeyError$1({ message: `${description} API key must be a string.` });
if (typeof process === "undefined") throw new LoadAPIKeyError$1({ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables are not supported in this environment.` });
apiKey = process.env[environmentVariableName];
if (apiKey == null) throw new LoadAPIKeyError$1({ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.` });
if (typeof apiKey !== "string") throw new LoadAPIKeyError$1({ message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.` });
return apiKey;
}
var suspectProtoRx$1 = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
var suspectConstructorRx$1 = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
function _parse$1(text) {
const obj = JSON.parse(text);
if (obj === null || typeof obj !== "object") return obj;
if (suspectProtoRx$1.test(text) === false && suspectConstructorRx$1.test(text) === false) return obj;
return filter$1(obj);
}
function filter$1(obj) {
let next = [obj];
while (next.length) {
const nodes = next;
next = [];
for (const node of nodes) {
if (Object.prototype.hasOwnProperty.call(node, "__proto__")) throw new SyntaxError("Object contains forbidden prototype property");
if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) throw new SyntaxError("Object contains forbidden prototype property");
for (const key in node) {
const value = node[key];
if (value && typeof value === "object") next.push(value);
}
}
}
return obj;
}
function secureJsonParse$1(text) {
const { stackTraceLimit } = Error;
try {
Error.stackTraceLimit = 0;
} catch (e) {
return _parse$1(text);
}
try {
return _parse$1(text);
} finally {
Error.stackTraceLimit = stackTraceLimit;
}
}
function addAdditionalPropertiesToJsonSchema$1(jsonSchema2) {
if (jsonSchema2.type === "object" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes("object")) {
jsonSchema2.additionalProperties = false;
const { properties } = jsonSchema2;
if (properties != null) for (const key of Object.keys(properties)) properties[key] = visit$1(properties[key]);
}
if (jsonSchema2.items != null) jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit$1) : visit$1(jsonSchema2.items);
if (jsonSchema2.anyOf != null) jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit$1);
if (jsonSchema2.allOf != null) jsonSchema2.allOf = jsonSchema2.allOf.map(visit$1);
if (jsonSchema2.oneOf != null) jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit$1);
const { definitions } = jsonSchema2;
if (definitions != null) for (const key of Object.keys(definitions)) definitions[key] = visit$1(definitions[key]);
return jsonSchema2;
}
function visit$1(def) {
if (typeof def === "boolean") return def;
return addAdditionalPropertiesToJsonSchema$1(def);
}
var ignoreOverride$1 = /* @__PURE__ */ Symbol("Let zodToJsonSchema decide on which parser to use");
var defaultOptions$1 = {
name: void 0,
$refStrategy: "root",
basePath: ["#"],
effectStrategy: "input",
pipeStrategy: "all",
dateStrategy: "format:date-time",
mapStrategy: "entries",
removeAdditionalStrategy: "passthrough",
allowedAdditionalProperties: true,
rejectedAdditionalProperties: false,
definitionPath: "definitions",
strictUnions: false,
definitions: {},
errorMessages: false,
patternStrategy: "escape",
applyRegexFlags: false,
emailStrategy: "format:email",
base64Strategy: "contentEncoding:base64",
nameStrategy: "ref"
};
var getDefaultOptions$1 = (options) => typeof options === "string" ? __spreadProps(__spreadValues({}, defaultOptions$1), { name: options }) : __spreadValues(__spreadValues({}, defaultOptions$1), options);
function parseAnyDef$1() {
return {};
}
function parseArrayDef$1(def, refs) {
var _a22, _b22, _c;
const res = { type: "array" };
if (((_a22 = def.type) == null ? void 0 : _a22._def) && ((_c = (_b22 = def.type) == null ? void 0 : _b22._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) res.items = parseDef$1(def.type._def, __spreadProps(__spreadValues({}, refs), { currentPath: [...refs.currentPath, "items"] }));
if (def.minLength) res.minItems = def.minLength.value;
if (def.maxLength) res.maxItems = def.maxLength.value;
if (def.exactLength) {
res.minItems = def.exactLength.value;
res.maxItems = def.exactLength.value;
}
return res;
}
function parseBigintDef$1(def) {
const res = {
type: "integer",
format: "int64"
};
if (!def.checks) return res;
for (const check of def.checks) switch (check.kind) {
case "min":
if (check.inclusive) res.minimum = check.value;
else res.exclusiveMinimum = check.value;
break;
case "max":
if (check.inclusive) res.maximum = check.value;
else res.exclusiveMaximum = check.value;
break;
case "multipleOf": res.multipleOf = check.value;
}
return res;
}
function parseBooleanDef$1() {
return { type: "boolean" };
}
function parseBrandedDef$1(_def, refs) {
return parseDef$1(_def.type._def, refs);
}
var parseCatchDef$1 = (def, refs) => {
return parseDef$1(def.innerType._def, refs);
};
function parseDateDef$1(def, refs, overrideDateStrategy) {
const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
if (Array.isArray(strategy)) return { anyOf: strategy.map((item, i) => parseDateDef$1(def, refs, item)) };
switch (strategy) {
case "string":
case "format:date-time": return {
type: "string",
format: "date-time"
};
case "format:date": return {
type: "string",
format: "date"
};
case "integer": return integerDateParser$1(def);
}
}
var integerDateParser$1 = (def) => {
const res = {
type: "integer",
format: "unix-time"
};
for (const check of def.checks) switch (check.kind) {
case "min":
res.minimum = check.value;
break;
case "max": res.maximum = check.value;
}
return res;
};
function parseDefaultDef$1(_def, refs) {
return __spreadProps(__spreadValues({}, parseDef$1(_def.innerType._def, refs)), { default: _def.defaultValue() });
}
function parseEffectsDef$1(_def, refs) {
return refs.effectStrategy === "input" ? parseDef$1(_def.schema._def, refs) : parseAnyDef$1();
}
function parseEnumDef$1(def) {
return {
type: "string",
enum: Array.from(def.values)
};
}
var isJsonSchema7AllOfType$1 = (type) => {
if ("type" in type && type.type === "string") return false;
return "allOf" in type;
};
function parseIntersectionDef$1(def, refs) {
const allOf = [parseDef$1(def.left._def, __spreadProps(__spreadValues({}, refs), { currentPath: [
...refs.currentPath,
"allOf",
"0"
] })), parseDef$1(def.right._def, __spreadProps(__spreadValues({}, refs), { currentPath: [
...refs.currentPath,
"allOf",
"1"
] }))].filter((x) => !!x);
const mergedAllOf = [];
allOf.forEach((schema) => {
if (isJsonSchema7AllOfType$1(schema)) mergedAllOf.push(...schema.allOf);
else {
let nestedSchema = schema;
if ("additionalProperties" in schema && schema.additionalProperties === false) {
const _a16 = schema, { additionalProperties } = _a16;
nestedSchema = __objRest(_a16, ["additionalProperties"]);
}
mergedAllOf.push(nestedSchema);
}
});
return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
}
function parseLiteralDef$1(def) {
const parsedType = typeof def.value;
if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") return { type: Array.isArray(def.value) ? "array" : "object" };
return {
type: parsedType === "bigint" ? "integer" : parsedType,
const: def.value
};
}
var emojiRegex$1 = void 0;
var zodPatterns$1 = {
/**
* `c` was changed to `[cC]` to replicate /i flag
*/
cuid: /^[cC][^\s-]{8,}$/,
cuid2: /^[0-9a-z]+$/,
ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
/**
* `a-z` was added to replicate /i flag
*/
email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
/**
* Constructed a valid Unicode RegExp
*
* Lazily instantiate since this type of regex isn't supported
* in all envs (e.g. React Native).
*
* See:
* https://github.com/colinhacks/zod/issues/2433
* Fix in Zod:
* https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
*/
emoji: () => {
if (emojiRegex$1 === void 0) emojiRegex$1 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
return emojiRegex$1;
},
/**
* Unused
*/
uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
/**
* Unused
*/
ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
/**
* Unused
*/
ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
nanoid: /^[a-zA-Z0-9_-]{21}$/,
jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
};
function parseStringDef$1(def, refs) {
const res = { type: "string" };
if (def.checks) for (const check of def.checks) switch (check.kind) {
case "min":
res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
break;
case "max":
res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
break;
case "email":
switch (refs.emailStrategy) {
case "format:email":
addFormat$1(res, "email", check.message, refs);
break;
case "format:idn-email":
addFormat$1(res, "idn-email", check.message, refs);
break;
case "pattern:zod": addPattern$1(res, zodPatterns$1.email, check.message, refs);
}
break;
case "url":
addFormat$1(res, "uri", check.message, refs);
break;
case "uuid":
addFormat$1(res, "uuid", check.message, refs);
break;
case "regex":
addPattern$1(res, check.regex, check.message, refs);
break;
case "cuid":
addPattern$1(res, zodPatterns$1.cuid, check.message, refs);
break;
case "cuid2":
addPattern$1(res, zodPatterns$1.cuid2, check.message, refs);
break;
case "startsWith":
addPattern$1(res, RegExp(`^${escapeLiteralCheckValue$1(check.value, refs)}`), check.message, refs);
break;
case "endsWith":
addPattern$1(res, RegExp(`${escapeLiteralCheckValue$1(check.value, refs)}$`), check.message, refs);
break;
case "datetime":
addFormat$1(res, "date-time", check.message, refs);
break;
case "date":
addFormat$1(res, "date", check.message, refs);
break;
case "time":
addFormat$1(res, "time", check.message, refs);
break;
case "duration":
addFormat$1(res, "duration", check.message, refs);
break;
case "length":
res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
break;
case "includes":
addPattern$1(res, RegExp(escapeLiteralCheckValue$1(check.value, refs)), check.message, refs);
break;
case "ip":
if (check.version !== "v6") addFormat$1(res, "ipv4", check.message, refs);
if (check.version !== "v4") addFormat$1(res, "ipv6", check.message, refs);
break;
case "base64url":
addPattern$1(res, zodPatterns$1.base64url, check.message, refs);
break;
case "jwt":
addPattern$1(res, zodPatterns$1.jwt, check.message, refs);
break;
case "cidr":
if (check.version !== "v6") addPattern$1(res, zodPatterns$1.ipv4Cidr, check.message, refs);
if (check.version !== "v4") addPattern$1(res, zodPatterns$1.ipv6Cidr, check.message, refs);
break;
case "emoji":
addPattern$1(res, zodPatterns$1.emoji(), check.message, refs);
break;
case "ulid":
addPattern$1(res, zodPatterns$1.ulid, check.message, refs);
break;
case "base64":
switch (refs.base64Strategy) {
case "format:binary":
addFormat$1(res, "binary", check.message, refs);
break;
case "contentEncoding:base64":
res.contentEncoding = "base64";
break;
case "pattern:zod": addPattern$1(res, zodPatterns$1.base64, check.message, refs);
}
break;
case "nanoid": addPattern$1(res, zodPatterns$1.nanoid, check.message, refs);
}
return res;
}
function escapeLiteralCheckValue$1(literal, refs) {
return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric$1(literal) : literal;
}
var ALPHA_NUMERIC$1 = /* @__PURE__ */ new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
function escapeNonAlphaNumeric$1(source) {
let result = "";
for (let i = 0; i < source.length; i++) {
if (!ALPHA_NUMERIC$1.has(source[i])) result += "\\";
result += source[i];
}
return result;
}
function addFormat$1(schema, value, message, refs) {
var _a22;
if (schema.format || ((_a22 = schema.anyOf) == null ? void 0 : _a22.some((x) => x.format))) {
if (!schema.anyOf) schema.anyOf = [];
if (schema.format) {
schema.anyOf.push({ format: schema.format });
delete schema.format;
}
schema.anyOf.push(__spreadValues({ format: value }, message && refs.errorMessages && { errorMessage: { format: message } }));
} else schema.format = value;
}
function addPattern$1(schema, regex, message, refs) {
var _a22;
if (schema.pattern || ((_a22 = schema.allOf) == null ? void 0 : _a22.some((x) => x.pattern))) {
if (!schema.allOf) schema.allOf = [];
if (schema.pattern) {
schema.allOf.push({ pattern: schema.pattern });
delete schema.pattern;
}
schema.allOf.push(__spreadValues({ pattern: stringifyRegExpWithFlags$1(regex, refs) }, message && refs.errorMessages && { errorMessage: { pattern: message } }));
} else schema.pattern = stringifyRegExpWithFlags$1(regex, refs);
}
function stringifyRegExpWithFlags$1(regex, refs) {
var _a22;
if (!refs.applyRegexFlags || !regex.flags) return regex.source;
const flags = {
i: regex.flags.includes("i"),
m: regex.flags.includes("m"),
s: regex.flags.includes("s")
};
const source = flags.i ? regex.source.toLowerCase() : regex.source;
let pattern = "";
let isEscaped = false;
let inCharGroup = false;
let inCharRange = false;
for (let i = 0; i < source.length; i++) {
if (isEscaped) {
pattern += source[i];
isEscaped = false;
continue;
}
if (flags.i) {
if (inCharGroup) {
if (source[i].match(/[a-z]/)) {
if (inCharRange) {
pattern += source[i];
pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
inCharRange = false;
} else if (source[i + 1] === "-" && ((_a22 = source[i + 2]) == null ? void 0 : _a22.match(/[a-z]/))) {
pattern += source[i];
inCharRange = true;
} else pattern += `${source[i]}${source[i].toUpperCase()}`;
continue;
}
} else if (source[i].match(/[a-z]/)) {
pattern += `[${source[i]}${source[i].toUpperCase()}]`;
continue;
}
}
if (flags.m) {
if (source[i] === "^") {
pattern += `(^|(?<=[\r
]))`;
continue;
} else if (source[i] === "$") {
pattern += `($|(?=[\r
]))`;
continue;
}
}
if (flags.s && source[i] === ".") {
pattern += inCharGroup ? `${source[i]}\r
` : `[${source[i]}\r
]`;
continue;
}
pattern += source[i];
if (source[i] === "\\") isEscaped = true;
else if (inCharGroup && source[i] === "]") inCharGroup = false;
else if (!inCharGroup && source[i] === "[") inCharGroup = true;
}
try {
new RegExp(pattern);
} catch (e) {
console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
return regex.source;
}
return pattern;
}
function parseRecordDef$1(def, refs) {
var _a22, _b22, _c, _d, _e, _f;
const schema = {
type: "object",
additionalProperties: (_a22 = parseDef$1(def.valueType._def, __spreadProps(__spreadValues({}, refs), { currentPath: [...refs.currentPath, "additionalProperties"] }))) != null ? _a22 : refs.allowedAdditionalProperties
};
if (((_b22 = def.keyType) == null ? void 0 : _b22._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
const _a16 = parseStringDef$1(def.keyType._def, refs), { type } = _a16, keyType = __objRest(_a16, ["type"]);
return __spreadProps(__spreadValues({}, schema), { propertyNames: keyType });
} else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind.ZodEnum) return __spreadProps(__spreadValues({}, schema), { propertyNames: { enum: def.keyType._def.values } });
else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
const _b16 = parseBrandedDef$1(def.keyType._def, refs), { type } = _b16, keyType = __objRest(_b16, ["type"]);
return __spreadProps(__spreadValues({}, schema), { propertyNames: keyType });
}
return schema;
}
function parseMapDef$1(def, refs) {
if (refs.mapStrategy === "record") return parseRecordDef$1(def, refs);
return {
type: "array",
maxItems: 125,
items: {
type: "array",
items: [parseDef$1(def.keyType._def, __spreadProps(__spreadValues({}, refs), { currentPath: [
...refs.currentPath,
"items",
"items",
"0"
] })) || parseAnyDef$1(), parseDef$1(def.valueType._def, __spreadProps(__spreadValues({}, refs), { currentPath: [
...refs.currentPath,
"items",
"items",
"1"
] })) || parseAnyDef$1()],
minItems: 2,
maxItems: 2
}
};
}
function parseNativeEnumDef$1(def) {
const object = def.values;
const actualValues = Object.keys(def.values).filter((key) => {
return typeof object[object[key]] !== "number";
}).map((key) => object[key]);
const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
return {
type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
enum: actualValues
};
}
function parseNeverDef$1() {
return { not: parseAnyDef$1() };
}
function parseNullDef$1() {
return { type: "null" };
}
var primitiveMappings$1 = {
ZodString: "string",
ZodNumber: "number",
ZodBigInt: "integer",
ZodBoolean: "boolean",
ZodNull: "null"
};
function parseUnionDef$1(def, refs) {
const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
if (options.every((x) => x._def.typeName in primitiveMappings$1 && (!x._def.checks || !x._def.checks.length))) {
const types = options.reduce((types2, x) => {
const type = primitiveMappings$1[x._def.typeName];
return type && !types2.includes(type) ? [...types2, type] : types2;
}, []);
return { type: types.length > 1 ? types : types[0] };
} else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
const types = options.reduce((acc, x) => {
const type = typeof x._def.value;
switch (type) {
case "string":
case "number":
case "boolean": return [...acc, type];
case "bigint": return [...acc, "integer"];
case "object": if (x._def.value === null) return [...acc, "null"];
default: return acc;
}
}, []);
if (types.length === options.length) {
const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
return {
type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
enum: options.reduce((acc, x) => {
return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
}, [])
};
}
} else if (options.every((x) => x._def.typeName === "ZodEnum")) return {
type: "string",
enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x2) => !acc.includes(x2))], [])
};
return asAnyOf$1(def, refs);
}
var asAnyOf$1 = (def, refs) => {
const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef$1(x._def, __spreadProps(__spreadValues({}, refs), { currentPath: [
...refs.currentPath,
"anyOf",
`${i}`
] }))).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
return anyOf.length ? { anyOf } : void 0;
};
function parseNullableDef$1(def, refs) {
if ([
"ZodString",
"ZodNumber",
"ZodBigInt",
"ZodBoolean",
"ZodNull"
].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) return { type: [primitiveMappings$1[def.innerType._def.typeName], "null"] };
const base = parseDef$1(def.innerType._def, __spreadProps(__spreadValues({}, refs), { currentPath: [
...refs.currentPath,
"anyOf",
"0"
] }));
return base && { anyOf: [base, { type: "null" }] };
}
function parseNumberDef$1(def) {
const res = { type: "number" };
if (!def.checks) return res;
for (const check of def.checks) switch (check.kind) {
case "int":
res.type = "integer";
break;
case "min":
if (check.inclusive) res.minimum = check.value;
else res.exclusiveMinimum = check.value;
break;
case "max":
if (check.inclusive) res.maximum = check.value;
else res.exclusiveMaximum = check.value;
break;
case "multipleOf": res.multipleOf = check.value;
}
return res;
}
function parseObjectDef$1(def, refs) {
const result = {
type: "object",
properties: {}
};
const required = [];
const shape = def.shape();
for (const propName in shape) {
let propDef = shape[propName];
if (propDef === void 0 || propDef._def === void 0) continue;
const propOptional = safeIsOptional$1(propDef);
const parsedDef = parseDef$1(propDef._def, __spreadProps(__spreadValues({}, refs), {
currentPath: [
...refs.currentPath,
"properties",
propName
],
propertyPath: [
...refs.currentPath,
"properties",
propName
]
}));
if (parsedDef === void 0) continue;
result.properties[propName] = parsedDef;
if (!propOptional) required.push(propName);
}
if (required.length) result.required = required;
const additionalProperties = decideAdditionalProperties$1(def, refs);
if (additionalProperties !== void 0) result.additionalProperties = additionalProperties;
return result;
}
function decideAdditionalProperties$1(def, refs) {
if (def.catchall._def.typeName !== "ZodNever") return parseDef$1(def.catchall._def, __spreadProps(__spreadValues({}, refs), { currentPath: [...refs.currentPath, "additionalProperties"] }));
switch (def.unknownKeys) {
case "passthrough": return refs.allowedAdditionalProperties;
case "strict": return refs.rejectedAdditionalProperties;
case "strip": return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
}
}
function safeIsOptional$1(schema) {
try {
return schema.isOptional();
} catch (e) {
return true;
}
}
var parseOptionalDef$1 = (def, refs) => {
var _a22;
if (refs.currentPath.toString() === ((_a22 = refs.propertyPath) == null ? void 0 : _a22.toString())) return parseDef$1(def.innerType._def, refs);
const innerSchema = parseDef$1(def.innerType._def, __spreadProps(__spreadValues({}, refs), { currentPath: [
...refs.currentPath,
"anyOf",
"1"
] }));
return innerSchema ? { anyOf: [{ not: parseAnyDef$1() }, innerSchema] } : parseAnyDef$1();
};
var parsePipelineDef$1 = (def, refs) => {
if (refs.pipeStrategy === "input") return parseDef$1(def.in._def, refs);
else if (refs.pipeStrategy === "output") return parseDef$1(def.out._def, refs);
const a = parseDef$1(def.in._def, __spreadProps(__spreadValues({}, refs), { currentPath: [
...refs.currentPath,
"allOf",
"0"
] }));
return { allOf: [a, parseDef$1(def.out._def, __spreadProps(__spreadValues({}, refs), { currentPath: [
...refs.currentPath,
"allOf",
a ? "1" : "0"
] }))].filter((x) => x !== void 0) };
};
function parsePromiseDef$1(def, refs) {
return parseDef$1(def.type._def, refs);
}
function parseSetDef$1(def, refs) {
const schema = {
type: "array",
uniqueItems: true,
items: parseDef$1(def.valueType._def, __spreadProps(__spreadValues({}, refs), { currentPath: [...refs.currentPath, "items"] }))
};
if (def.minSize) schema.minItems = def.minSize.value;
if (def.maxSize) schema.maxItems = def.maxSize.value;
return schema;
}
function parseTupleDef$1(def, refs) {
if (def.rest) return {
type: "array",
minItems: def.items.length,
items: def.items.map((x, i) => parseDef$1(x._def, __spreadProps(__spreadValues({}, refs), { currentPath: [
...refs.currentPath,
"items",
`${i}`
] }))).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),
additionalItems: parseDef$1(def.rest._def, __spreadProps(__spreadValues({}, refs), { currentPath: [...refs.currentPath, "additionalItems"] }))
};
else return {
type: "array",
minItems: def.items.length,
maxItems: def.items.length,
items: def.items.map((x, i) => parseDef$1(x._def, __spreadProps(__spreadValues({}, refs), { currentPath: [
...refs.currentPath,
"items",
`${i}`
] }))).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])
};
}
function parseUndefinedDef$1() {
return { not: parseAnyDef$1() };
}
function parseUnknownDef$1() {
return parseAnyDef$1();
}
var parseReadonlyDef$1 = (def, refs) => {
return parseDef$1(def.innerType._def, refs);
};
var selectParser$1 = (def, typeName, refs) => {
switch (typeName) {
case ZodFirstPartyTypeKind.ZodString: return parseStringDef$1(def, refs);
case ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef$1(def);
case ZodFirstPartyTypeKind.ZodObject: return parseObjectDef$1(def, refs);
case ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef$1(def);
case ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef$1();
case ZodFirstPartyTypeKind.ZodDate: return parseDateDef$1(def, refs);
case ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef$1();
case ZodFirstPartyTypeKind.ZodNull: return parseNullDef$1();
case ZodFirstPartyTypeKind.ZodArray: return parseArrayDef$1(def, refs);
case ZodFirstPartyTypeKind.ZodUnion:
case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef$1(def, refs);
case ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef$1(def, refs);
case ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef$1(def, refs);
case ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef$1(def, refs);
case ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef$1(def);
case ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef$1(def);
case ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef$1(def);
case ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef$1(def, refs);
case ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef$1(def, refs);
case ZodFirstPartyTypeKind.ZodMap: return parseMapDef$1(def, refs);
case ZodFirstPartyTypeKind.ZodSet: return parseSetDef$1(def, refs);
case ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def;
case ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef$1(def, refs);
case ZodFirstPartyTypeKind.ZodNaN:
case ZodFirstPartyTypeKind.ZodNever: return parseNeverDef$1();
case ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef$1(def, refs);
case ZodFirstPartyTypeKind.ZodAny: return parseAnyDef$1();
case ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef$1();
case ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef$1(def, refs);
case ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef$1(def, refs);
case ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef$1(def, refs);
case ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef$1(def, refs);
case ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef$1(def, refs);
case ZodFirstPartyTypeKind.ZodFunction:
case ZodFirstPartyTypeKind.ZodVoid:
case ZodFirstPartyTypeKind.ZodSymbol: return;
default: return /* @__PURE__ */ ((_) => void 0)(typeName);
}
};
var getRelativePath$1 = (pathA, pathB) => {
let i = 0;
for (; i < pathA.length && i < pathB.length; i++) if (pathA[i] !== pathB[i]) break;
return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
};
function parseDef$1(def, refs, forceResolution = false) {
var _a22;
const seenItem = refs.seen.get(def);
if (refs.override) {
const overrideResult = (_a22 = refs.override) == null ? void 0 : _a22.call(refs, def, refs, seenItem, forceResolution);
if (overrideResult !== ignoreOverride$1) return overrideResult;
}
if (seenItem && !forceResolution) {
const seenSchema = get$ref$1(seenItem, refs);
if (seenSchema !== void 0) return seenSchema;
}
const newItem = {
def,
path: refs.currentPath,
jsonSchema: void 0
};
refs.seen.set(def, newItem);
const jsonSchemaOrGetter = selectParser$1(def, def.typeName, refs);
const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef$1(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
if (jsonSchema2) addMeta$1(def, refs, jsonSchema2);
if (refs.postProcess) {
const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
newItem.jsonSchema = jsonSchema2;
return postProcessResult;
}
newItem.jsonSchema = jsonSchema2;
return jsonSchema2;
}
var get$ref$1 = (item, refs) => {
switch (refs.$refStrategy) {
case "root": return { $ref: item.path.join("/") };
case "relative": return { $ref: getRelativePath$1(refs.currentPath, item.path) };
case "none":
case "seen":
if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
return parseAnyDef$1();
}
return refs.$refStrategy === "seen" ? parseAnyDef$1() : void 0;
}
};
var addMeta$1 = (def, refs, jsonSchema2) => {
if (def.description) jsonSchema2.description = def.description;
return jsonSchema2;
};
var getRefs$1 = (options) => {
const _options = getDefaultOptions$1(options);
const currentPath = _options.name !== void 0 ? [
..._options.basePath,
_options.definitionPath,
_options.name
] : _options.basePath;
return __spreadProps(__spreadValues({}, _options), {
currentPath,
propertyPath: void 0,
seen: new Map(Object.entries(_options.definitions).map(([name22, def]) => [def._def, {
def: def._def,
path: [
..._options.basePath,
_options.definitionPath,
name22
],
jsonSchema: void 0
}]))
});
};
var zod3ToJsonSchema$1 = (schema, options) => {
var _a22;
const refs = getRefs$1(options);
let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name32, schema2]) => {
var _a32;
return __spreadProps(__spreadValues({}, acc), { [name32]: (_a32 = parseDef$1(schema2._def, __spreadProps(__spreadValues({}, refs), { currentPath: [
...refs.basePath,
refs.definitionPath,
name32
] }), true)) != null ? _a32 : parseAnyDef$1() });
}, {}) : void 0;
const name22 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
const main = (_a22 = parseDef$1(schema._def, name22 === void 0 ? refs : __spreadProps(__spreadValues({}, refs), { currentPath: [
...refs.basePath,
refs.definitionPath,
name22
] }), false)) != null ? _a22 : parseAnyDef$1();
const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
if (title !== void 0) main.title = title;
const combined = name22 === void 0 ? definitions ? __spreadProps(__spreadValues({}, main), { [refs.definitionPath]: definitions }) : main : {
$ref: [
...refs.$refStrategy === "relative" ? [] : refs.basePath,
refs.definitionPath,
name22
].join("/"),
[refs.definitionPath]: __spreadProps(__spreadValues({}, definitions), { [name22]: main })
};
combined.$schema = "http://json-schema.org/draft-07/schema#";
return combined;
};
var schemaSymbol$1 = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
function jsonSchema$1(jsonSchema2, { validate } = {}) {
return {
[schemaSymbol$1]: true,
_type: void 0,
get jsonSchema() {
if (typeof jsonSchema2 === "function") jsonSchema2 = jsonSchema2();
return jsonSchema2;
},
validate
};
}
function isSchema$1(value) {
return typeof value === "object" && value !== null && schemaSymbol$1 in value && value[schemaSymbol$1] === true && "jsonSchema" in value && "validate" in value;
}
function asSchema$1(schema) {
return schema == null ? jsonSchema$1({
properties: {},
additionalProperties: false
}) : isSchema$1(schema) ? schema : "~standard" in schema ? schema["~standard"].vendor === "zod" ? zodSchema$1(schema) : standardSchema$1(schema) : schema();
}
function standardSchema$1(standardSchema2) {
return jsonSchema$1(() => addAdditionalPropertiesToJsonSchema$1(standardSchema2["~standard"].jsonSchema.input({ target: "draft-07" })), { validate: async (value) => {
const result = await standardSchema2["~standard"].validate(value);
return "value" in result ? {
success: true,
value: result.value
} : {
success: false,
error: new TypeValidationError$1({
value,
cause: result.issues
})
};
} });
}
function zod3Schema$1(zodSchema2, options) {
var _a22;
const useReferences = (_a22 = options == null ? void 0 : options.useReferences) != null ? _a22 : false;
return jsonSchema$1(() => zod3ToJsonSchema$1(zodSchema2, { $refStrategy: useReferences ? "root" : "none" }), { validate: async (value) => {
const result = await zodSchema2.safeParseAsync(value);
return result.success ? {
success: true,
value: result.data
} : {
success: false,
error: result.error
};
} });
}
function zod4Schema$1(zodSchema2, options) {
var _a22;
const useReferences = (_a22 = options == null ? void 0 : options.useReferences) != null ? _a22 : false;
return jsonSchema$1(() => addAdditionalPropertiesToJsonSchema$1(z4.toJSONSchema(zodSchema2, {
target: "draft-7",
io: "input",
reused: useReferences ? "ref" : "inline"
})), { validate: async (value) => {
const result = await z4.safeParseAsync(zodSchema2, value);
return result.success ? {
success: true,
value: result.data
} : {
success: false,
error: result.error
};
} });
}
function isZod4Schema$1(zodSchema2) {
return "_zod" in zodSchema2;
}
function zodSchema$1(zodSchema2, options) {
if (isZod4Schema$1(zodSchema2)) return zod4Schema$1(zodSchema2, options);
else return zod3Schema$1(zodSchema2, options);
}
async function validateTypes$1({ value, schema, context }) {
const result = await safeValidateTypes$1({
value,
schema,
context
});
if (!result.success) throw TypeValidationError$1.wrap({
value,
cause: result.error,
context
});
return result.value;
}
async function safeValidateTypes$1({ value, schema, context }) {
const actualSchema = asSchema$1(schema);
try {
if (actualSchema.validate == null) return {
success: true,
value,
rawValue: value
};
const result = await actualSchema.validate(value);
if (result.success) return {
success: true,
value: result.value,
rawValue: value
};
return {
success: false,
error: TypeValidationError$1.wrap({
value,
cause: result.error,
context
}),
rawValue: value
};
} catch (error) {
return {
success: false,
error: TypeValidationError$1.wrap({
value,
cause: error,
context
}),
rawValue: value
};
}
}
async function parseJSON$1({ text, schema }) {
try {
const value = secureJsonParse$1(text);
if (schema == null) return value;
return validateTypes$1({
value,
schema
});
} catch (error) {
if (JSONParseError$1.isInstance(error) || TypeValidationError$1.isInstance(error)) throw error;
throw new JSONParseError$1({
text,
cause: error
});
}
}
async function safeParseJSON$1({ text, schema }) {
try {
const value = secureJsonParse$1(text);
if (schema == null) return {
success: true,
value,
rawValue: value
};
return await safeValidateTypes$1({
value,
schema
});
} catch (error) {
return {
success: false,
error: JSONParseError$1.isInstance(error) ? error : new JSONParseError$1({
text,
cause: error
}),
rawValue: void 0
};
}
}
function isParsableJson(input) {
try {
secureJsonParse$1(input);
return true;
} catch (e) {
return false;
}
}
function parseJsonEventStream$1({ stream, schema }) {
return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(new TransformStream({ async transform({ data }, controller) {
if (data === "[DONE]") return;
controller.enqueue(await safeParseJSON$1({
text: data,
schema
}));
} }));
}
var getOriginalFetch2 = () => globalThis.fetch;
var postJsonToApi$1 = async ({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }) => postToApi$1({
url,
headers: __spreadValues({ "Content-Type": "application/json" }, headers),
body: {
content: JSON.stringify(body),
values: body
},
failedResponseHandler,
successfulResponseHandler,
abortSignal,
fetch: fetch2
});
var postToApi$1 = async ({ url, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch2() }) => {
try {
const response = await fetch2(url, {
method: "POST",
headers: withUserAgentSuffix$1(headers, `ai-sdk/provider-utils/${VERSION$11}`, getRuntimeEnvironmentUserAgent$1()),
body: body.content,
signal: abortSignal
});
const responseHeaders = extractResponseHeaders$1(response);
if (!response.ok) {
let errorInformation;
try {
errorInformation = await failedResponseHandler({
response,
url,
requestBodyValues: body.values
});
} catch (error) {
if (isAbortError$1(error) || APICallError$1.isInstance(error)) throw error;
throw new APICallError$1({
message: "Failed to process error response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: body.values
});
}
throw errorInformation.value;
}
try {
return await successfulResponseHandler({
response,
url,
requestBodyValues: body.values
});
} catch (error) {
if (error instanceof Error) {
if (isAbortError$1(error) || APICallError$1.isInstance(error)) throw error;
}
throw new APICallError$1({
message: "Failed to process successful response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: body.values
});
}
} catch (error) {
throw handleFetchError$1({
error,
url,
requestBodyValues: body.values
});
}
};
function tool$1(tool2) {
return tool2;
}
function createProviderToolFactory({ id, inputSchema }) {
return (_a16) => {
var _b16 = _a16, { execute, outputSchema, needsApproval, toModelOutput, onInputStart, onInputDelta, onInputAvailable } = _b16;
return tool$1({
type: "provider",
id,
args: __objRest(_b16, [
"execute",
"outputSchema",
"needsApproval",
"toModelOutput",
"onInputStart",
"onInputDelta",
"onInputAvailable"
]),
inputSchema,
outputSchema,
execute,
needsApproval,
toModelOutput,
onInputStart,
onInputDelta,
onInputAvailable
});
};
}
var createJsonErrorResponseHandler$1 = ({ errorSchema, errorToMessage, isRetryable }) => async ({ response, url, requestBodyValues }) => {
const responseBody = await response.text();
const responseHeaders = extractResponseHeaders$1(response);
if (responseBody.trim() === "") return {
responseHeaders,
value: new APICallError$1({
message: response.statusText,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody,
isRetryable: isRetryable == null ? void 0 : isRetryable(response)
})
};
try {
const parsedError = await parseJSON$1({
text: responseBody,
schema: errorSchema
});
return {
responseHeaders,
value: new APICallError$1({
message: errorToMessage(parsedError),
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody,
data: parsedError,
isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
})
};
} catch (parseError) {
return {
responseHeaders,
value: new APICallError$1({
message: response.statusText,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody,
isRetryable: isRetryable == null ? void 0 : isRetryable(response)
})
};
}
};
var createEventSourceResponseHandler$1 = (chunkSchema) => async ({ response }) => {
const responseHeaders = extractResponseHeaders$1(response);
if (response.body == null) throw new EmptyResponseBodyError$1({});
return {
responseHeaders,
value: parseJsonEventStream$1({
stream: response.body,
schema: chunkSchema
})
};
};
var createJsonResponseHandler$1 = (responseSchema) => async ({ response, url, requestBodyValues }) => {
const responseBody = await response.text();
const parsedResult = await safeParseJSON$1({
text: responseBody,
schema: responseSchema
});
const responseHeaders = extractResponseHeaders$1(response);
if (!parsedResult.success) throw new APICallError$1({
message: "Invalid JSON response",
cause: parsedResult.error,
statusCode: response.status,
responseHeaders,
responseBody,
url,
requestBodyValues
});
return {
responseHeaders,
value: parsedResult.value,
rawValue: parsedResult.rawValue
};
};
function withoutTrailingSlash$1(url) {
return url == null ? void 0 : url.replace(/\/$/, "");
}
function isDefinedOrNotNull(value) {
return value !== null && value !== void 0;
}
var ReasoningFormat = /* @__PURE__ */ ((ReasoningFormat2) => {
ReasoningFormat2["Unknown"] = "unknown";
ReasoningFormat2["OpenAIResponsesV1"] = "openai-responses-v1";
ReasoningFormat2["AzureOpenAIResponsesV1"] = "azure-openai-responses-v1";
ReasoningFormat2["XAIResponsesV1"] = "xai-responses-v1";
ReasoningFormat2["AnthropicClaudeV1"] = "anthropic-claude-v1";
ReasoningFormat2["GoogleGeminiV1"] = "google-gemini-v1";
return ReasoningFormat2;
})(ReasoningFormat || {});
var DEFAULT_REASONING_FORMAT = "anthropic-claude-v1";
var CommonReasoningDetailSchema = z.object({
id: z.string().nullish(),
format: z.enum(ReasoningFormat).nullish(),
index: z.number().optional()
}).loose();
var ReasoningDetailSummarySchema = z.object({
type: z.literal("reasoning.summary"),
summary: z.string()
}).extend(CommonReasoningDetailSchema.shape);
var ReasoningDetailEncryptedSchema = z.object({
type: z.literal("reasoning.encrypted"),
data: z.string()
}).extend(CommonReasoningDetailSchema.shape);
var ReasoningDetailTextSchema = z.object({
type: z.literal("reasoning.text"),
text: z.string().nullish(),
signature: z.string().nullish()
}).extend(CommonReasoningDetailSchema.shape);
var ReasoningDetailUnionSchema = z.union([
ReasoningDetailSummarySchema,
ReasoningDetailEncryptedSchema,
ReasoningDetailTextSchema
]);
var ReasoningDetailsWithUnknownSchema = z.union([ReasoningDetailUnionSchema, z.unknown().transform(() => null)]);
var ReasoningDetailArraySchema = z.array(ReasoningDetailsWithUnknownSchema).transform((d) => d.filter((d2) => !!d2));
z.union([
z.object({ delta: z.object({ reasoning_details: z.array(ReasoningDetailsWithUnknownSchema) }) }).transform((data) => data.delta.reasoning_details.filter(isDefinedOrNotNull)),
z.object({ message: z.object({ reasoning_details: z.array(ReasoningDetailsWithUnknownSchema) }) }).transform((data) => data.message.reasoning_details.filter(isDefinedOrNotNull)),
z.object({
text: z.string(),
reasoning_details: z.array(ReasoningDetailsWithUnknownSchema)
}).transform((data) => data.reasoning_details.filter(isDefinedOrNotNull))
]);
var OpenRouterErrorResponseSchema = z.object({ error: z.object({
code: z.union([z.string(), z.number()]).nullable().optional().default(null),
message: z.string(),
type: z.string().nullable().optional().default(null),
param: z.any().nullable().optional().default(null)
}).passthrough() }).passthrough();
function extractErrorMessage(data) {
const metadata = data.error.metadata;
if (!metadata) return data.error.message;
const parts = [];
if (typeof metadata.provider_name === "string" && metadata.provider_name) parts.push(`[${metadata.provider_name}]`);
const raw = metadata.raw;
const rawMessage = extractRawMessage(raw);
if (rawMessage && rawMessage !== data.error.message) parts.push(rawMessage);
else parts.push(data.error.message);
return parts.join(" ");
}
function extractRawMessage(raw) {
if (typeof raw === "string") try {
const parsed = JSON.parse(raw);
if (typeof parsed === "object" && parsed !== null) return extractRawMessage(parsed);
return raw;
} catch (e) {
return raw;
}
if (typeof raw !== "object" || raw === null) return;
const obj = raw;
for (const field of [
"message",
"error",
"detail",
"details",
"msg"
]) {
const value = obj[field];
if (typeof value === "string" && value.length > 0) return value;
if (typeof value === "object" && value !== null) {
const nested = extractRawMessage(value);
if (nested) return nested;
}
}
}
var openrouterFailedResponseHandler = createJsonErrorResponseHandler$1({
errorSchema: OpenRouterErrorResponseSchema,
errorToMessage: extractErrorMessage
});
var FileAnnotationSchema = z.object({
type: z.literal("file"),
file: z.object({
hash: z.string(),
name: z.string(),
content: z.array(z.object({
type: z.string(),
text: z.string().optional()
}).catchall(z.any())).optional()
}).catchall(z.any())
}).catchall(z.any());
var OpenRouterProviderMetadataSchema = z.object({
provider: z.string(),
reasoning_details: z.array(ReasoningDetailUnionSchema).optional(),
annotations: z.array(FileAnnotationSchema).optional(),
usage: z.object({
promptTokens: z.number(),
promptTokensDetails: z.object({ cachedTokens: z.number() }).catchall(z.any()).optional(),
completionTokens: z.number(),
completionTokensDetails: z.object({ reasoningTokens: z.number() }).catchall(z.any()).optional(),
totalTokens: z.number(),
cost: z.number().optional(),
costDetails: z.object({ upstreamInferenceCost: z.number() }).catchall(z.any()).optional()
}).catchall(z.any())
}).catchall(z.any());
var OpenRouterProviderOptionsSchema = z.object({ openrouter: z.object({
reasoning_details: ReasoningDetailArraySchema.optional(),
annotations: z.array(FileAnnotationSchema).optional()
}).optional() }).optional();
function computeTokenUsage(usage) {
var _a16, _b16, _c, _d, _e, _f, _g, _h;
const promptTokens = (_a16 = usage.prompt_tokens) != null ? _a16 : 0;
const completionTokens = (_b16 = usage.completion_tokens) != null ? _b16 : 0;
const cacheReadTokens = (_d = (_c = usage.prompt_tokens_details) == null ? void 0 : _c.cached_tokens) != null ? _d : 0;
const cacheWriteTokens = (_f = (_e = usage.prompt_tokens_details) == null ? void 0 : _e.cache_write_tokens) != null ? _f : void 0;
const reasoningTokens = (_h = (_g = usage.completion_tokens_details) == null ? void 0 : _g.reasoning_tokens) != null ? _h : 0;
return {
inputTokens: {
total: promptTokens,
noCache: promptTokens - cacheReadTokens,
cacheRead: cacheReadTokens,
cacheWrite: cacheWriteTokens
},
outputTokens: {
total: completionTokens,
text: completionTokens - reasoningTokens,
reasoning: reasoningTokens
},
raw: usage
};
}
function emptyUsage() {
return {
inputTokens: {
total: 0,
noCache: void 0,
cacheRead: void 0,
cacheWrite: void 0
},
outputTokens: {
total: 0,
text: void 0,
reasoning: void 0
},
raw: void 0
};
}
function mapToUnified(finishReason) {
switch (finishReason) {
case "stop": return "stop";
case "length": return "length";
case "content_filter": return "content-filter";
case "function_call":
case "tool_calls": return "tool-calls";
default: return "other";
}
}
function mapOpenRouterFinishReason(finishReason) {
return {
unified: mapToUnified(finishReason),
raw: finishReason != null ? finishReason : void 0
};
}
function createFinishReason(unified, raw) {
return {
unified,
raw
};
}
function withStreamErrorHandling(source, onError) {
const reader = source.getReader();
return new ReadableStream({
async pull(controller) {
try {
const { done, value } = await reader.read();
if (done) controller.close();
else controller.enqueue(value);
} catch (err) {
onError(err);
reader.cancel().catch(() => {});
controller.close();
}
},
cancel(reason) {
reader.cancel(reason);
}
});
}
function deterministicStringify(value) {
return JSON.stringify(sortKeys(value));
}
function sortKeys(value) {
if (value === null || value === void 0) return value;
if (Array.isArray(value)) return value.map(sortKeys);
if (typeof value === "object") {
const sorted = {};
const entries = Object.entries(value);
entries.sort(([a], [b]) => a.localeCompare(b));
for (const [key, val] of entries) sorted[key] = sortKeys(val);
return sorted;
}
return value;
}
var _seenKeys;
var ReasoningDetailsDuplicateTracker = class {
constructor() {
__privateAdd(this, _seenKeys, /* @__PURE__ */ new Set());
}
/**
* Attempts to track a detail.
* Returns true if this is a NEW detail (not seen before and has valid key),
* false if it was skipped (no valid key) or already seen (duplicate).
*/
upsert(detail) {
const key = this.getCanonicalKey(detail);
if (key === null) return false;
if (__privateGet(this, _seenKeys).has(key)) return false;
__privateGet(this, _seenKeys).add(key);
return true;
}
getCanonicalKey(detail) {
switch (detail.type) {
case "reasoning.summary": return detail.summary;
case "reasoning.encrypted":
if (detail.id) return detail.id;
return detail.data;
case "reasoning.text":
if (detail.text) return detail.text;
if (detail.signature) return detail.signature;
return null;
default: return null;
}
}
};
_seenKeys = /* @__PURE__ */ new WeakMap();
var OPENROUTER_AUDIO_FORMATS = [
"wav",
"mp3",
"aiff",
"aac",
"ogg",
"flac",
"m4a",
"pcm16",
"pcm24"
];
function isUrl({ url, protocols }) {
try {
const urlObj = new URL(url);
return protocols.has(urlObj.protocol);
} catch (_) {
return false;
}
}
function buildFileDataUrl({ data, mediaType, defaultMediaType }) {
if (data instanceof Uint8Array) {
const base64 = convertUint8ArrayToBase64$1(data);
return `data:${mediaType != null ? mediaType : defaultMediaType};base64,${base64}`;
}
const stringData = data.toString();
if (isUrl({
url: stringData,
protocols: /* @__PURE__ */ new Set(["http:", "https:"])
})) return stringData;
return stringData.startsWith("data:") ? stringData : `data:${mediaType != null ? mediaType : defaultMediaType};base64,${stringData}`;
}
function getFileUrl({ part, defaultMediaType }) {
return buildFileDataUrl({
data: part.data instanceof URL ? part.data.toString() : part.data,
mediaType: part.mediaType,
defaultMediaType
});
}
function getMediaType(dataUrl, defaultMediaType) {
var _a16;
const match = dataUrl.match(/^data:([^;]+)/);
return match ? (_a16 = match[1]) != null ? _a16 : defaultMediaType : defaultMediaType;
}
function getBase64FromDataUrl(dataUrl) {
const match = dataUrl.match(/^data:[^;]*;base64,(.+)$/);
return match ? match[1] : dataUrl;
}
var MIME_TO_FORMAT = {
mpeg: "mp3",
mp3: "mp3",
"x-wav": "wav",
wave: "wav",
wav: "wav",
ogg: "ogg",
vorbis: "ogg",
aac: "aac",
"x-aac": "aac",
m4a: "m4a",
"x-m4a": "m4a",
mp4: "m4a",
aiff: "aiff",
"x-aiff": "aiff",
flac: "flac",
"x-flac": "flac",
pcm16: "pcm16",
pcm24: "pcm24"
};
function getInputAudioData(part) {
const fileData = getFileUrl({
part,
defaultMediaType: "audio/mpeg"
});
if (isUrl({
url: fileData,
protocols: /* @__PURE__ */ new Set(["http:", "https:"])
})) throw new Error(`Audio files cannot be provided as URLs.
OpenRouter requires audio to be base64-encoded. Please:
1. Download the audio file locally
2. Read it as a Buffer or Uint8Array
3. Pass it as the data parameter
The AI SDK will automatically handle base64 encoding.
Learn more: https://openrouter.ai/docs/features/multimodal/audio`);
const data = getBase64FromDataUrl(fileData);
const mediaType = part.mediaType || "audio/mpeg";
const format = MIME_TO_FORMAT[mediaType.replace("audio/", "")];
if (format === void 0) {
const supportedList = OPENROUTER_AUDIO_FORMATS.join(", ");
throw new Error(`Unsupported audio format: "${mediaType}"
OpenRouter supports the following audio formats: ${supportedList}
Learn more: https://openrouter.ai/docs/features/multimodal/audio`);
}
return {
data,
format
};
}
function getCacheControl$1(providerMetadata) {
var _a16, _b16, _c;
const anthropic = providerMetadata == null ? void 0 : providerMetadata.anthropic;
const openrouter2 = providerMetadata == null ? void 0 : providerMetadata.openrouter;
return (_c = (_b16 = (_a16 = openrouter2 == null ? void 0 : openrouter2.cacheControl) != null ? _a16 : openrouter2 == null ? void 0 : openrouter2.cache_control) != null ? _b16 : anthropic == null ? void 0 : anthropic.cacheControl) != null ? _c : anthropic == null ? void 0 : anthropic.cache_control;
}
function convertToOpenRouterChatMessages(prompt) {
var _a16, _b16, _c, _d, _e, _f, _g, _h;
const messages = [];
const reasoningDetailsTracker = new ReasoningDetailsDuplicateTracker();
for (const { role, content, providerOptions } of prompt) switch (role) {
case "system": {
const cacheControl = getCacheControl$1(providerOptions);
messages.push({
role: "system",
content: [__spreadValues({
type: "text",
text: content
}, cacheControl && { cache_control: cacheControl })]
});
break;
}
case "user": {
if (content.length === 1 && ((_a16 = content[0]) == null ? void 0 : _a16.type) === "text") {
const cacheControl = (_b16 = getCacheControl$1(providerOptions)) != null ? _b16 : getCacheControl$1(content[0].providerOptions);
const contentWithCacheControl = cacheControl ? [{
type: "text",
text: content[0].text,
cache_control: cacheControl
}] : content[0].text;
messages.push({
role: "user",
content: contentWithCacheControl
});
break;
}
const messageCacheControl = getCacheControl$1(providerOptions);
let lastTextPartIndex = -1;
for (let i = content.length - 1; i >= 0; i--) if (((_c = content[i]) == null ? void 0 : _c.type) === "text") {
lastTextPartIndex = i;
break;
}
const contentParts = content.map((part, index) => {
var _a17, _b17, _c2, _d2, _e2, _f2, _g2;
const isLastTextPart = part.type === "text" && index === lastTextPartIndex;
const partCacheControl = getCacheControl$1(part.providerOptions);
const cacheControl = part.type === "text" ? partCacheControl != null ? partCacheControl : isLastTextPart ? messageCacheControl : void 0 : partCacheControl;
switch (part.type) {
case "text": return __spreadValues({
type: "text",
text: part.text
}, cacheControl && { cache_control: cacheControl });
case "file": {
if ((_a17 = part.mediaType) == null ? void 0 : _a17.startsWith("image/")) return __spreadValues({
type: "image_url",
image_url: { url: getFileUrl({
part,
defaultMediaType: "image/jpeg"
}) }
}, cacheControl && { cache_control: cacheControl });
if ((_b17 = part.mediaType) == null ? void 0 : _b17.startsWith("video/")) return __spreadValues({
type: "video_url",
video_url: { url: getFileUrl({
part,
defaultMediaType: "video/mp4"
}) }
}, cacheControl && { cache_control: cacheControl });
if ((_c2 = part.mediaType) == null ? void 0 : _c2.startsWith("audio/")) return __spreadValues({
type: "input_audio",
input_audio: getInputAudioData(part)
}, cacheControl && { cache_control: cacheControl });
const fileName = String((_g2 = (_f2 = (_e2 = (_d2 = part.providerOptions) == null ? void 0 : _d2.openrouter) == null ? void 0 : _e2.filename) != null ? _f2 : part.filename) != null ? _g2 : "");
const fileData = getFileUrl({
part,
defaultMediaType: "application/pdf"
});
if (isUrl({
url: fileData,
protocols: /* @__PURE__ */ new Set(["http:", "https:"])
})) return {
type: "file",
file: {
filename: fileName,
file_data: fileData
}
};
return __spreadValues({
type: "file",
file: {
filename: fileName,
file_data: fileData
}
}, cacheControl && { cache_control: cacheControl });
}
default: return __spreadValues({
type: "text",
text: ""
}, cacheControl && { cache_control: cacheControl });
}
});
messages.push({
role: "user",
content: contentParts
});
break;
}
case "assistant": {
let text = "";
let reasoning = "";
const toolCalls = [];
for (const part of content) switch (part.type) {
case "text":
text += part.text;
break;
case "tool-call":
toolCalls.push({
id: part.toolCallId,
type: "function",
function: {
name: part.toolName,
arguments: deterministicStringify(part.input)
}
});
break;
case "reasoning": reasoning += part.text;
}
const parsedProviderOptions = OpenRouterProviderOptionsSchema.safeParse(providerOptions);
const messageReasoningDetails = parsedProviderOptions.success ? (_e = (_d = parsedProviderOptions.data) == null ? void 0 : _d.openrouter) == null ? void 0 : _e.reasoning_details : void 0;
const messageAnnotations = parsedProviderOptions.success ? (_g = (_f = parsedProviderOptions.data) == null ? void 0 : _f.openrouter) == null ? void 0 : _g.annotations : void 0;
const candidateReasoningDetails = messageReasoningDetails && Array.isArray(messageReasoningDetails) ? messageReasoningDetails : findFirstReasoningDetails(content);
let finalReasoningDetails;
if (candidateReasoningDetails) {
const validDetails = candidateReasoningDetails.filter((detail) => {
var _a17;
if (detail.type !== "reasoning.text") return true;
const format = (_a17 = detail.format) != null ? _a17 : DEFAULT_REASONING_FORMAT;
if (format !== "anthropic-claude-v1" && format !== "google-gemini-v1") return true;
return !!detail.signature;
});
if (validDetails.length < candidateReasoningDetails.length) {
const logger = globalThis.AI_SDK_LOG_WARNINGS;
if (logger !== false && typeof logger !== "function") console.warn("[openrouter] Some reasoning_details entries were removed because they were missing signatures. See https://github.com/OpenRouterTeam/ai-sdk-provider/issues/423 and https://github.com/OpenRouterTeam/ai-sdk-provider/issues/418 for more details.");
}
const uniqueDetails = [];
for (const detail of validDetails) if (reasoningDetailsTracker.upsert(detail)) uniqueDetails.push(detail);
finalReasoningDetails = uniqueDetails;
}
const effectiveReasoning = reasoning && finalReasoningDetails && finalReasoningDetails.length > 0 ? reasoning : void 0;
messages.push({
role: "assistant",
content: text || null,
tool_calls: toolCalls.length > 0 ? toolCalls : void 0,
reasoning: effectiveReasoning,
reasoning_details: finalReasoningDetails,
annotations: messageAnnotations,
cache_control: getCacheControl$1(providerOptions)
});
break;
}
case "tool": for (const toolResponse of content) {
if (toolResponse.type === "tool-approval-response") continue;
const content2 = getToolResultContent(toolResponse);
messages.push({
role: "tool",
tool_call_id: toolResponse.toolCallId,
content: content2,
name: toolResponse.toolName,
cache_control: (_h = getCacheControl$1(providerOptions)) != null ? _h : getCacheControl$1(toolResponse.providerOptions)
});
}
}
return messages;
}
function getToolResultContent(input) {
var _a16;
switch (input.output.type) {
case "text":
case "error-text": return input.output.value;
case "json":
case "error-json": return JSON.stringify(input.output.value);
case "content": return mapToolResultContentParts(input.output.value);
case "execution-denied": return (_a16 = input.output.reason) != null ? _a16 : "Tool execution denied";
}
}
function mapToolResultContentParts(parts) {
return parts.map((part) => {
var _a16, _b16, _c, _d;
switch (part.type) {
case "text": return {
type: "text",
text: part.text
};
case "image-data": return {
type: "image_url",
image_url: { url: buildFileDataUrl({
data: part.data,
mediaType: part.mediaType,
defaultMediaType: "image/jpeg"
}) }
};
case "image-url": return {
type: "image_url",
image_url: { url: part.url }
};
case "file-data": {
const dataUrl = buildFileDataUrl({
data: part.data,
mediaType: part.mediaType,
defaultMediaType: "application/octet-stream"
});
if ((_a16 = part.mediaType) == null ? void 0 : _a16.startsWith("image/")) return {
type: "image_url",
image_url: { url: dataUrl }
};
if ((_b16 = part.mediaType) == null ? void 0 : _b16.startsWith("video/")) return {
type: "video_url",
video_url: { url: dataUrl }
};
if ((_c = part.mediaType) == null ? void 0 : _c.startsWith("audio/")) {
const format = MIME_TO_FORMAT[part.mediaType.replace("audio/", "")];
if (format !== void 0) return {
type: "input_audio",
input_audio: {
data: getBase64FromDataUrl(dataUrl),
format
}
};
}
return {
type: "file",
file: {
filename: (_d = part.filename) != null ? _d : "",
file_data: dataUrl
}
};
}
case "file-url":
if (looksLikeImageUrl(part.url)) return {
type: "image_url",
image_url: { url: part.url }
};
return {
type: "file",
file: {
filename: filenameFromUrl(part.url),
file_data: part.url
}
};
case "file-id":
case "image-file-id":
case "custom": return {
type: "text",
text: JSON.stringify(part)
};
default: return {
type: "text",
text: JSON.stringify(part)
};
}
});
}
var IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([
"jpg",
"jpeg",
"png",
"gif",
"webp",
"svg",
"bmp",
"ico",
"tif",
"tiff",
"avif"
]);
function looksLikeImageUrl(url) {
var _a16;
try {
const ext = (_a16 = new URL(url).pathname.split(".").pop()) == null ? void 0 : _a16.toLowerCase();
return ext !== void 0 && IMAGE_EXTENSIONS.has(ext);
} catch (e) {
return false;
}
}
function filenameFromUrl(url) {
try {
const last = new URL(url).pathname.split("/").pop();
return (last == null ? void 0 : last.includes(".")) ? last : "";
} catch (e) {
return "";
}
}
function findFirstReasoningDetails(content) {
var _a16, _b16, _c, _d;
for (const part of content) if (part.type === "tool-call") {
const parsed = OpenRouterProviderOptionsSchema.safeParse(part.providerOptions);
if (parsed.success && ((_b16 = (_a16 = parsed.data) == null ? void 0 : _a16.openrouter) == null ? void 0 : _b16.reasoning_details) && parsed.data.openrouter.reasoning_details.length > 0) return parsed.data.openrouter.reasoning_details;
}
for (const part of content) if (part.type === "reasoning") {
const parsed = OpenRouterProviderOptionsSchema.safeParse(part.providerOptions);
if (parsed.success && ((_d = (_c = parsed.data) == null ? void 0 : _c.openrouter) == null ? void 0 : _d.reasoning_details) && parsed.data.openrouter.reasoning_details.length > 0) return parsed.data.openrouter.reasoning_details;
}
}
z.union([
z.literal("auto"),
z.literal("none"),
z.literal("required"),
z.object({
type: z.literal("function"),
function: z.object({ name: z.string() })
})
]);
function getChatCompletionToolChoice(toolChoice) {
switch (toolChoice.type) {
case "auto":
case "none":
case "required": return toolChoice.type;
case "tool": return {
type: "function",
function: { name: toolChoice.toolName }
};
default: throw new InvalidArgumentError$1({
argument: "toolChoice",
message: `Invalid tool choice type: ${JSON.stringify(toolChoice)}`
});
}
}
var ImageResponseSchema = z.object({
type: z.literal("image_url"),
image_url: z.object({ url: z.string() }).passthrough()
}).passthrough();
var ImageResponseWithUnknownSchema = z.union([ImageResponseSchema, z.unknown().transform(() => null)]);
var ImageResponseArraySchema = z.array(ImageResponseWithUnknownSchema).transform((d) => d.filter((d2) => !!d2));
var OpenRouterChatCompletionBaseResponseSchema = z.object({
id: z.string().optional(),
model: z.string().optional(),
provider: z.string().optional(),
usage: z.object({
prompt_tokens: z.number(),
prompt_tokens_details: z.object({
cached_tokens: z.number(),
cache_write_tokens: z.number().nullish()
}).passthrough().nullish(),
completion_tokens: z.number(),
completion_tokens_details: z.object({ reasoning_tokens: z.number() }).passthrough().nullish(),
total_tokens: z.number(),
cost: z.number().optional(),
cost_details: z.object({ upstream_inference_cost: z.number().nullish() }).passthrough().nullish()
}).passthrough().nullish()
}).passthrough();
var OpenRouterNonStreamChatCompletionResponseSchema = z.union([OpenRouterChatCompletionBaseResponseSchema.extend({ choices: z.array(z.object({
message: z.object({
role: z.literal("assistant"),
content: z.string().nullable().optional(),
reasoning: z.string().nullable().optional(),
reasoning_details: ReasoningDetailArraySchema.nullish(),
images: ImageResponseArraySchema.nullish(),
tool_calls: z.array(z.object({
id: z.string().optional().nullable(),
type: z.literal("function"),
function: z.object({
name: z.string(),
arguments: z.string().optional()
}).passthrough()
}).passthrough()).optional(),
annotations: z.array(z.union([
z.object({
type: z.literal("url_citation"),
url_citation: z.object({
url: z.string(),
title: z.string().optional(),
start_index: z.number().optional(),
end_index: z.number().optional(),
content: z.string().optional()
}).passthrough()
}).passthrough(),
z.object({
type: z.literal("file_annotation"),
file_annotation: z.object({
file_id: z.string(),
quote: z.string().optional()
}).passthrough()
}).passthrough(),
z.object({
type: z.literal("file"),
file: z.object({
hash: z.string(),
name: z.string(),
content: z.array(z.object({
type: z.string(),
text: z.string().optional()
}).passthrough()).optional()
}).passthrough()
}).passthrough()
])).nullish()
}).passthrough(),
index: z.number().nullish(),
logprobs: z.object({ content: z.array(z.object({
token: z.string(),
logprob: z.number(),
top_logprobs: z.array(z.object({
token: z.string(),
logprob: z.number()
}).passthrough())
}).passthrough()).nullable() }).passthrough().nullable().optional(),
finish_reason: z.string().optional().nullable()
}).passthrough()) }), OpenRouterErrorResponseSchema.extend({ user_id: z.string().optional() })]);
var OpenRouterStreamChatCompletionChunkSchema = z.union([OpenRouterChatCompletionBaseResponseSchema.extend({ choices: z.array(z.object({
delta: z.object({
role: z.enum(["assistant"]).optional(),
content: z.string().nullish(),
reasoning: z.string().nullish().optional(),
reasoning_details: ReasoningDetailArraySchema.nullish(),
images: ImageResponseArraySchema.nullish(),
tool_calls: z.array(z.object({
index: z.number().nullish(),
id: z.string().nullish(),
type: z.literal("function").optional(),
function: z.object({
name: z.string().nullish(),
arguments: z.string().nullish()
}).passthrough()
}).passthrough()).nullish(),
annotations: z.array(z.union([
z.object({
type: z.literal("url_citation"),
url_citation: z.object({
url: z.string(),
title: z.string().optional(),
start_index: z.number().optional(),
end_index: z.number().optional(),
content: z.string().optional()
}).passthrough()
}).passthrough(),
z.object({
type: z.literal("file_annotation"),
file_annotation: z.object({
file_id: z.string(),
quote: z.string().optional()
}).passthrough()
}).passthrough(),
z.object({
type: z.literal("file"),
file: z.object({
hash: z.string(),
name: z.string(),
content: z.array(z.object({
type: z.string(),
text: z.string().optional()
}).passthrough()).optional()
}).passthrough()
}).passthrough()
])).nullish()
}).passthrough().nullish(),
logprobs: z.object({ content: z.array(z.object({
token: z.string(),
logprob: z.number(),
top_logprobs: z.array(z.object({
token: z.string(),
logprob: z.number()
}).passthrough())
}).passthrough()).nullable() }).passthrough().nullish(),
finish_reason: z.string().nullable().optional(),
index: z.number().nullish()
}).passthrough()) }), OpenRouterErrorResponseSchema]);
var OpenRouterChatLanguageModel = class {
constructor(modelId, settings, config) {
this.specificationVersion = "v3";
this.provider = "openrouter";
this.defaultObjectGenerationMode = "tool";
this.supportsImageUrls = true;
this.supportedUrls = {
"image/*": [/^data:image\/[a-zA-Z]+;base64,/, /^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)(?:[?#].*)?$/i],
"application/*": [/^data:application\//, /^https?:\/\/.+$/]
};
this.modelId = modelId;
this.settings = settings;
this.config = config;
}
getArgs({ prompt, maxOutputTokens, temperature, topP, frequencyPenalty, presencePenalty, seed, stopSequences, responseFormat, topK, tools, toolChoice }) {
var _a16, _b16, _c, _d;
const baseArgs = __spreadValues(__spreadValues({
model: this.modelId,
models: this.settings.models,
logit_bias: this.settings.logitBias,
logprobs: this.settings.logprobs === true || typeof this.settings.logprobs === "number" ? true : void 0,
top_logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0,
user: this.settings.user,
parallel_tool_calls: this.settings.parallelToolCalls,
max_tokens: maxOutputTokens != null ? maxOutputTokens : this.settings.maxTokens,
temperature: temperature != null ? temperature : this.settings.temperature,
top_p: topP != null ? topP : this.settings.topP,
frequency_penalty: frequencyPenalty != null ? frequencyPenalty : this.settings.frequencyPenalty,
presence_penalty: presencePenalty != null ? presencePenalty : this.settings.presencePenalty,
seed,
stop: stopSequences,
response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? responseFormat.schema != null ? {
type: "json_schema",
json_schema: __spreadValues({
schema: responseFormat.schema,
strict: (_b16 = (_a16 = this.settings.structuredOutputs) == null ? void 0 : _a16.strict) != null ? _b16 : true,
name: (_c = responseFormat.name) != null ? _c : "response"
}, responseFormat.description && { description: responseFormat.description })
} : { type: "json_object" } : void 0,
top_k: topK != null ? topK : this.settings.topK,
messages: convertToOpenRouterChatMessages(prompt),
include_reasoning: this.settings.includeReasoning,
reasoning: this.settings.reasoning,
usage: this.settings.usage,
plugins: this.settings.plugins,
web_search_options: this.settings.web_search_options,
provider: this.settings.provider,
debug: this.settings.debug,
cache_control: this.settings.cache_control
}, this.config.extraBody), this.settings.extraBody);
if (tools && tools.length > 0) {
const mappedTools = [];
for (const tool2 of tools) if (tool2.type === "function") {
const openrouterOptions = (_d = tool2.providerOptions) == null ? void 0 : _d.openrouter;
const eagerInputStreaming = openrouterOptions == null ? void 0 : openrouterOptions.eager_input_streaming;
mappedTools.push(__spreadValues({
type: "function",
function: {
name: tool2.name,
description: tool2.description,
parameters: tool2.inputSchema
}
}, eagerInputStreaming != null && { eager_input_streaming: eagerInputStreaming }));
} else if (tool2.type === "provider") mappedTools.push(mapProviderTool(tool2));
return __spreadProps(__spreadValues({}, baseArgs), {
tools: mappedTools,
tool_choice: toolChoice ? getChatCompletionToolChoice(toolChoice) : void 0
});
}
return baseArgs;
}
async doGenerate(options) {
var _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v;
const _a16 = (options.providerOptions || {}).openrouter || {}, { cacheControl } = _a16, restOpenrouterOptions = __objRest(_a16, ["cacheControl"]);
const args = __spreadValues(__spreadValues(__spreadValues({}, this.getArgs(options)), restOpenrouterOptions), cacheControl != null && !("cache_control" in restOpenrouterOptions) ? { cache_control: cacheControl } : {});
const { value: responseValue, responseHeaders } = await postJsonToApi$1({
url: this.config.url({
path: "/chat/completions",
modelId: this.modelId
}),
headers: combineHeaders$1(this.config.headers(), options.headers),
body: args,
failedResponseHandler: openrouterFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$1(OpenRouterNonStreamChatCompletionResponseSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
if ("error" in responseValue) {
const errorData = responseValue.error;
throw new APICallError$1({
message: errorData.message,
url: this.config.url({
path: "/chat/completions",
modelId: this.modelId
}),
requestBodyValues: args,
statusCode: 200,
responseHeaders,
data: errorData
});
}
const response = responseValue;
const choice = response.choices[0];
if (!choice) throw new NoContentGeneratedError({ message: "No choice in response" });
const usageInfo = response.usage ? computeTokenUsage(response.usage) : emptyUsage();
const reasoningDetails = (_b16 = choice.message.reasoning_details) != null ? _b16 : [];
const reasoning = reasoningDetails.length > 0 ? reasoningDetails.map((detail) => {
switch (detail.type) {
case "reasoning.text":
if (detail.text) return {
type: "reasoning",
text: detail.text,
providerMetadata: { openrouter: { reasoning_details: [detail] } }
};
break;
case "reasoning.summary": if (detail.summary) return {
type: "reasoning",
text: detail.summary,
providerMetadata: { openrouter: { reasoning_details: [detail] } }
};
}
return null;
}).filter((p) => p !== null) : choice.message.reasoning ? [{
type: "reasoning",
text: choice.message.reasoning
}] : [];
const content = [];
content.push(...reasoning);
if (choice.message.content) content.push({
type: "text",
text: choice.message.content
});
if (choice.message.tool_calls) {
let reasoningDetailsAttachedToToolCall = false;
const seenToolCallIds = /* @__PURE__ */ new Set();
for (const toolCall of choice.message.tool_calls) {
let toolCallId = toolCall.id;
if (!toolCallId || seenToolCallIds.has(toolCallId)) toolCallId = generateId$1();
seenToolCallIds.add(toolCallId);
content.push({
type: "tool-call",
toolCallId,
toolName: toolCall.function.name,
input: (_c = toolCall.function.arguments) != null ? _c : "{}",
providerMetadata: !reasoningDetailsAttachedToToolCall ? { openrouter: { reasoning_details: reasoningDetails } } : void 0
});
reasoningDetailsAttachedToToolCall = true;
}
}
if (choice.message.images) for (const image of choice.message.images) content.push({
type: "file",
mediaType: getMediaType(image.image_url.url, "image/jpeg"),
data: getBase64FromDataUrl(image.image_url.url)
});
if (choice.message.annotations) {
for (const annotation of choice.message.annotations) if (annotation.type === "url_citation") content.push({
type: "source",
sourceType: "url",
id: annotation.url_citation.url,
url: annotation.url_citation.url,
title: (_d = annotation.url_citation.title) != null ? _d : "",
providerMetadata: { openrouter: {
content: (_e = annotation.url_citation.content) != null ? _e : "",
startIndex: (_f = annotation.url_citation.start_index) != null ? _f : 0,
endIndex: (_g = annotation.url_citation.end_index) != null ? _g : 0
} }
});
}
const fileAnnotations = (_h = choice.message.annotations) == null ? void 0 : _h.filter((a) => a.type === "file");
const hasToolCalls = choice.message.tool_calls && choice.message.tool_calls.length > 0;
const hasEncryptedReasoning = reasoningDetails.some((d) => d.type === "reasoning.encrypted" && d.data);
const mappedFinishReason = hasToolCalls && hasEncryptedReasoning && choice.finish_reason === "stop" ? createFinishReason("tool-calls", (_i = choice.finish_reason) != null ? _i : void 0) : mapOpenRouterFinishReason(choice.finish_reason);
return {
content,
finishReason: hasToolCalls && mappedFinishReason.unified === "other" ? createFinishReason("tool-calls", mappedFinishReason.raw) : mappedFinishReason,
usage: usageInfo,
warnings: [],
providerMetadata: { openrouter: OpenRouterProviderMetadataSchema.parse({
provider: (_j = response.provider) != null ? _j : "",
reasoning_details: (_k = choice.message.reasoning_details) != null ? _k : [],
annotations: fileAnnotations && fileAnnotations.length > 0 ? fileAnnotations : void 0,
usage: __spreadValues(__spreadValues(__spreadValues(__spreadValues({
promptTokens: (_l = usageInfo.inputTokens.total) != null ? _l : 0,
completionTokens: (_m = usageInfo.outputTokens.total) != null ? _m : 0,
totalTokens: ((_n = usageInfo.inputTokens.total) != null ? _n : 0) + ((_o = usageInfo.outputTokens.total) != null ? _o : 0)
}, ((_p = response.usage) == null ? void 0 : _p.cost) != null ? { cost: response.usage.cost } : {}), ((_r = (_q = response.usage) == null ? void 0 : _q.prompt_tokens_details) == null ? void 0 : _r.cached_tokens) != null ? { promptTokensDetails: { cachedTokens: response.usage.prompt_tokens_details.cached_tokens } } : {}), ((_t = (_s = response.usage) == null ? void 0 : _s.completion_tokens_details) == null ? void 0 : _t.reasoning_tokens) != null ? { completionTokensDetails: { reasoningTokens: response.usage.completion_tokens_details.reasoning_tokens } } : {}), ((_v = (_u = response.usage) == null ? void 0 : _u.cost_details) == null ? void 0 : _v.upstream_inference_cost) != null ? { costDetails: { upstreamInferenceCost: response.usage.cost_details.upstream_inference_cost } } : {})
}) },
request: { body: args },
response: {
id: response.id,
modelId: response.model,
headers: responseHeaders,
body: response
}
};
}
async doStream(options) {
var _b16;
const _a16 = (options.providerOptions || {}).openrouter || {}, { cacheControl } = _a16, restOpenrouterOptions = __objRest(_a16, ["cacheControl"]);
const args = __spreadValues(__spreadValues(__spreadValues({}, this.getArgs(options)), restOpenrouterOptions), cacheControl != null && !("cache_control" in restOpenrouterOptions) ? { cache_control: cacheControl } : {});
const { value: response, responseHeaders } = await postJsonToApi$1({
url: this.config.url({
path: "/chat/completions",
modelId: this.modelId
}),
headers: combineHeaders$1(this.config.headers(), options.headers),
body: __spreadProps(__spreadValues({}, args), {
stream: true,
stream_options: this.config.compatibility === "strict" ? __spreadValues({ include_usage: true }, ((_b16 = this.settings.usage) == null ? void 0 : _b16.include) ? { include_usage: true } : {}) : void 0
}),
failedResponseHandler: openrouterFailedResponseHandler,
successfulResponseHandler: createEventSourceResponseHandler$1(OpenRouterStreamChatCompletionChunkSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
let streamError;
const safeResponse = withStreamErrorHandling(response, (err) => {
streamError = err;
});
const toolCalls = [];
const seenToolCallIds = /* @__PURE__ */ new Set();
let finishReason = createFinishReason("other");
const usage = {
inputTokens: {
total: void 0,
noCache: void 0,
cacheRead: void 0,
cacheWrite: void 0
},
outputTokens: {
total: void 0,
text: void 0,
reasoning: void 0
},
raw: void 0
};
const openrouterUsage = {};
let rawUsage;
const accumulatedReasoningDetails = [];
let reasoningDetailsAttachedToToolCall = false;
const accumulatedFileAnnotations = [];
let textStarted = false;
let reasoningStarted = false;
let textId;
let reasoningId;
let openrouterResponseId;
let provider;
return {
stream: safeResponse.pipeThrough(new TransformStream({
transform(chunk, controller) {
var _a17, _b17, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u;
if (options.includeRawChunks) controller.enqueue({
type: "raw",
rawValue: chunk.rawValue
});
if (!chunk.success) {
finishReason = createFinishReason("error");
controller.enqueue({
type: "error",
error: chunk.error
});
return;
}
const value = chunk.value;
if ("error" in value) {
finishReason = createFinishReason("error");
controller.enqueue({
type: "error",
error: value.error
});
return;
}
if (value.provider) provider = value.provider;
if (value.id) {
openrouterResponseId = value.id;
controller.enqueue({
type: "response-metadata",
id: value.id
});
}
if (value.model) controller.enqueue({
type: "response-metadata",
modelId: value.model
});
if (value.usage != null) {
const computed = computeTokenUsage(value.usage);
Object.assign(usage.inputTokens, computed.inputTokens);
Object.assign(usage.outputTokens, computed.outputTokens);
rawUsage = value.usage;
const promptTokens = (_a17 = value.usage.prompt_tokens) != null ? _a17 : 0;
const completionTokens = (_b17 = value.usage.completion_tokens) != null ? _b17 : 0;
openrouterUsage.promptTokens = promptTokens;
if (value.usage.prompt_tokens_details) openrouterUsage.promptTokensDetails = { cachedTokens: (_c = value.usage.prompt_tokens_details.cached_tokens) != null ? _c : 0 };
openrouterUsage.completionTokens = completionTokens;
if (value.usage.completion_tokens_details) openrouterUsage.completionTokensDetails = { reasoningTokens: (_d = value.usage.completion_tokens_details.reasoning_tokens) != null ? _d : 0 };
if (value.usage.cost != null) openrouterUsage.cost = value.usage.cost;
openrouterUsage.totalTokens = value.usage.total_tokens;
const upstreamInferenceCost = (_e = value.usage.cost_details) == null ? void 0 : _e.upstream_inference_cost;
if (upstreamInferenceCost != null) openrouterUsage.costDetails = { upstreamInferenceCost };
}
const choice = value.choices[0];
if ((choice == null ? void 0 : choice.finish_reason) != null) finishReason = mapOpenRouterFinishReason(choice.finish_reason);
if ((choice == null ? void 0 : choice.delta) == null) return;
const delta = choice.delta;
const emitReasoningChunk = (chunkText) => {
if (!reasoningStarted) {
reasoningId = generateId$1();
controller.enqueue({
type: "reasoning-start",
id: reasoningId
});
reasoningStarted = true;
}
controller.enqueue({
type: "reasoning-delta",
delta: chunkText,
id: reasoningId || generateId$1()
});
};
if (delta.reasoning_details && delta.reasoning_details.length > 0) {
for (const detail of delta.reasoning_details) if (detail.type === "reasoning.text") {
const lastDetail = accumulatedReasoningDetails[accumulatedReasoningDetails.length - 1];
if ((lastDetail == null ? void 0 : lastDetail.type) === "reasoning.text") {
lastDetail.text = (lastDetail.text || "") + (detail.text || "");
lastDetail.signature = lastDetail.signature || detail.signature;
lastDetail.format = lastDetail.format || detail.format;
} else accumulatedReasoningDetails.push(__spreadValues({}, detail));
} else accumulatedReasoningDetails.push(detail);
if (!textStarted) for (const detail of delta.reasoning_details) switch (detail.type) {
case "reasoning.text":
emitReasoningChunk(detail.text || "");
break;
case "reasoning.encrypted": break;
case "reasoning.summary": if (detail.summary) emitReasoningChunk(detail.summary);
}
} else if (delta.reasoning && !textStarted) emitReasoningChunk(delta.reasoning);
if (delta.content) {
if (reasoningStarted && !textStarted) {
controller.enqueue({
type: "reasoning-end",
id: reasoningId || generateId$1(),
providerMetadata: { openrouter: { reasoning_details: accumulatedReasoningDetails } }
});
reasoningStarted = false;
}
if (!textStarted) {
textId = openrouterResponseId || generateId$1();
controller.enqueue({
type: "text-start",
id: textId
});
textStarted = true;
}
controller.enqueue({
type: "text-delta",
delta: delta.content,
id: textId || generateId$1()
});
}
if (delta.annotations) {
for (const annotation of delta.annotations) if (annotation.type === "url_citation") controller.enqueue({
type: "source",
sourceType: "url",
id: annotation.url_citation.url,
url: annotation.url_citation.url,
title: (_f = annotation.url_citation.title) != null ? _f : "",
providerMetadata: { openrouter: {
content: (_g = annotation.url_citation.content) != null ? _g : "",
startIndex: (_h = annotation.url_citation.start_index) != null ? _h : 0,
endIndex: (_i = annotation.url_citation.end_index) != null ? _i : 0
} }
});
else if (annotation.type === "file") {
const file = annotation.file;
if (file && typeof file === "object" && "hash" in file && "name" in file) accumulatedFileAnnotations.push(annotation);
}
}
if (delta.tool_calls != null) for (const toolCallDelta of delta.tool_calls) {
const index = (_j = toolCallDelta.index) != null ? _j : toolCalls.length - 1;
if (toolCalls[index] == null) {
if (toolCallDelta.type !== "function") throw new InvalidResponseDataError$1({
data: toolCallDelta,
message: `Expected 'function' type.`
});
if (((_k = toolCallDelta.function) == null ? void 0 : _k.name) == null) throw new InvalidResponseDataError$1({
data: toolCallDelta,
message: `Expected 'function.name' to be a string.`
});
let toolCallId = (_l = toolCallDelta.id) != null ? _l : "";
if (!toolCallId || seenToolCallIds.has(toolCallId)) toolCallId = generateId$1();
seenToolCallIds.add(toolCallId);
toolCalls[index] = {
id: toolCallId,
type: "function",
function: {
name: toolCallDelta.function.name,
arguments: (_m = toolCallDelta.function.arguments) != null ? _m : ""
},
inputStarted: false,
sent: false
};
const toolCall2 = toolCalls[index];
if (toolCall2 == null) throw new InvalidResponseDataError$1({
data: {
index,
toolCallsLength: toolCalls.length
},
message: `Tool call at index ${index} is missing after creation.`
});
if (((_n = toolCall2.function) == null ? void 0 : _n.name) != null && ((_o = toolCall2.function) == null ? void 0 : _o.arguments) != null && isParsableJson(toolCall2.function.arguments)) {
toolCall2.inputStarted = true;
controller.enqueue({
type: "tool-input-start",
id: toolCall2.id,
toolName: toolCall2.function.name
});
controller.enqueue({
type: "tool-input-delta",
id: toolCall2.id,
delta: toolCall2.function.arguments
});
controller.enqueue({
type: "tool-input-end",
id: toolCall2.id
});
controller.enqueue({
type: "tool-call",
toolCallId: toolCall2.id,
toolName: toolCall2.function.name,
input: toolCall2.function.arguments,
providerMetadata: !reasoningDetailsAttachedToToolCall ? { openrouter: { reasoning_details: accumulatedReasoningDetails } } : void 0
});
reasoningDetailsAttachedToToolCall = true;
toolCall2.sent = true;
}
continue;
}
const toolCall = toolCalls[index];
if (toolCall == null) throw new InvalidResponseDataError$1({
data: {
index,
toolCallsLength: toolCalls.length,
toolCallDelta
},
message: `Tool call at index ${index} is missing during merge.`
});
if (!toolCall.inputStarted) {
toolCall.inputStarted = true;
controller.enqueue({
type: "tool-input-start",
id: toolCall.id,
toolName: toolCall.function.name
});
if (toolCall.function.arguments) controller.enqueue({
type: "tool-input-delta",
id: toolCall.id,
delta: toolCall.function.arguments
});
}
if (((_p = toolCallDelta.function) == null ? void 0 : _p.arguments) != null) toolCall.function.arguments += (_r = (_q = toolCallDelta.function) == null ? void 0 : _q.arguments) != null ? _r : "";
controller.enqueue({
type: "tool-input-delta",
id: toolCall.id,
delta: (_s = toolCallDelta.function.arguments) != null ? _s : ""
});
if (!toolCall.sent && ((_t = toolCall.function) == null ? void 0 : _t.name) != null && ((_u = toolCall.function) == null ? void 0 : _u.arguments) != null && isParsableJson(toolCall.function.arguments)) {
controller.enqueue({
type: "tool-input-end",
id: toolCall.id
});
controller.enqueue({
type: "tool-call",
toolCallId: toolCall.id,
toolName: toolCall.function.name,
input: toolCall.function.arguments,
providerMetadata: !reasoningDetailsAttachedToToolCall ? { openrouter: { reasoning_details: accumulatedReasoningDetails } } : void 0
});
reasoningDetailsAttachedToToolCall = true;
toolCall.sent = true;
}
}
if (delta.images != null) for (const image of delta.images) controller.enqueue({
type: "file",
mediaType: getMediaType(image.image_url.url, "image/jpeg"),
data: getBase64FromDataUrl(image.image_url.url)
});
},
flush(controller) {
const hasToolCalls = toolCalls.length > 0;
if (streamError != null) {
finishReason = createFinishReason("error");
controller.enqueue({
type: "error",
error: streamError
});
}
const hasEncryptedReasoning = accumulatedReasoningDetails.some((d) => d.type === "reasoning.encrypted" && d.data);
if (hasToolCalls && hasEncryptedReasoning && finishReason.unified === "stop") finishReason = createFinishReason("tool-calls", finishReason.raw);
if (hasToolCalls && finishReason.unified === "other") finishReason = createFinishReason("tool-calls", finishReason.raw);
if (finishReason.unified === "tool-calls") {
for (const toolCall of toolCalls) if (toolCall && !toolCall.sent) {
const input = isParsableJson(toolCall.function.arguments) ? toolCall.function.arguments : "{}";
if (!toolCall.inputStarted) {
controller.enqueue({
type: "tool-input-start",
id: toolCall.id,
toolName: toolCall.function.name
});
controller.enqueue({
type: "tool-input-delta",
id: toolCall.id,
delta: input
});
}
controller.enqueue({
type: "tool-input-end",
id: toolCall.id
});
controller.enqueue({
type: "tool-call",
toolCallId: toolCall.id,
toolName: toolCall.function.name,
input,
providerMetadata: !reasoningDetailsAttachedToToolCall ? { openrouter: { reasoning_details: accumulatedReasoningDetails } } : void 0
});
reasoningDetailsAttachedToToolCall = true;
toolCall.sent = true;
}
}
if (reasoningStarted) controller.enqueue({
type: "reasoning-end",
id: reasoningId || generateId$1(),
providerMetadata: { openrouter: { reasoning_details: accumulatedReasoningDetails } }
});
if (textStarted) controller.enqueue({
type: "text-end",
id: textId || generateId$1()
});
const openrouterMetadata = { usage: openrouterUsage };
if (provider !== void 0) openrouterMetadata.provider = provider;
openrouterMetadata.reasoning_details = accumulatedReasoningDetails;
if (accumulatedFileAnnotations.length > 0) openrouterMetadata.annotations = accumulatedFileAnnotations;
if (usage.inputTokens.total === void 0 && openrouterUsage.promptTokens !== void 0) usage.inputTokens.total = openrouterUsage.promptTokens;
if (usage.outputTokens.total === void 0 && openrouterUsage.completionTokens !== void 0) usage.outputTokens.total = openrouterUsage.completionTokens;
usage.raw = rawUsage;
controller.enqueue({
type: "finish",
finishReason,
usage,
providerMetadata: { openrouter: openrouterMetadata }
});
}
})),
warnings: [],
request: { body: args },
response: { headers: responseHeaders }
};
}
};
function mapProviderTool(tool2) {
const [provider, toolName] = tool2.id.split(".");
const apiToolType = `${provider}:${toolName}`;
const mappedArgs = {};
for (const [key, value] of Object.entries(tool2.args)) if (value !== void 0) mappedArgs[camelToSnake(key)] = value;
return __spreadValues({ type: apiToolType }, mappedArgs);
}
function camelToSnake(str) {
return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
}
function convertToOpenRouterCompletionPrompt({ prompt, inputFormat, user = "user", assistant = "assistant" }) {
if (inputFormat === "prompt" && prompt.length === 1 && prompt[0] && prompt[0].role === "user" && prompt[0].content.length === 1 && prompt[0].content[0] && prompt[0].content[0].type === "text") return { prompt: prompt[0].content[0].text };
let text = "";
if (prompt[0] && prompt[0].role === "system") {
text += `${prompt[0].content}
`;
prompt = prompt.slice(1);
}
for (const { role, content } of prompt) switch (role) {
case "system": throw new InvalidPromptError$1({
message: `Unexpected system message in prompt: ${content}`,
prompt
});
case "user": {
const userMessage = content.map((part) => {
switch (part.type) {
case "text": return part.text;
case "file": throw new UnsupportedFunctionalityError$1({ functionality: "file attachments" });
default: return "";
}
}).join("");
text += `${user}:
${userMessage}
`;
break;
}
case "assistant": {
const assistantMessage = content.map((part) => {
switch (part.type) {
case "text": return part.text;
case "tool-call": throw new UnsupportedFunctionalityError$1({ functionality: "tool-call messages" });
case "tool-result": throw new UnsupportedFunctionalityError$1({ functionality: "tool-result messages" });
case "reasoning": throw new UnsupportedFunctionalityError$1({ functionality: "reasoning messages" });
case "file": throw new UnsupportedFunctionalityError$1({ functionality: "file attachments" });
default: return "";
}
}).join("");
text += `${assistant}:
${assistantMessage}
`;
break;
}
case "tool": throw new UnsupportedFunctionalityError$1({ functionality: "tool messages" });
}
text += `${assistant}:
`;
return { prompt: text };
}
var OpenRouterCompletionChunkSchema = z.union([z.object({
id: z.string().optional(),
model: z.string().optional(),
provider: z.string().optional(),
choices: z.array(z.object({
text: z.string(),
reasoning: z.string().nullish().optional(),
reasoning_details: ReasoningDetailArraySchema.nullish(),
finish_reason: z.string().nullish(),
index: z.number().nullish(),
logprobs: z.object({
tokens: z.array(z.string()),
token_logprobs: z.array(z.number()),
top_logprobs: z.array(z.record(z.string(), z.number())).nullable()
}).passthrough().nullable().optional()
}).passthrough()),
usage: z.object({
prompt_tokens: z.number(),
prompt_tokens_details: z.object({
cached_tokens: z.number(),
cache_write_tokens: z.number().nullish()
}).passthrough().nullish(),
completion_tokens: z.number(),
completion_tokens_details: z.object({ reasoning_tokens: z.number() }).passthrough().nullish(),
total_tokens: z.number(),
cost: z.number().optional(),
cost_details: z.object({ upstream_inference_cost: z.number().nullish() }).passthrough().nullish()
}).passthrough().nullish()
}).passthrough(), OpenRouterErrorResponseSchema]);
var OpenRouterCompletionLanguageModel = class {
constructor(modelId, settings, config) {
this.specificationVersion = "v3";
this.provider = "openrouter";
this.supportsImageUrls = true;
this.supportedUrls = {
"image/*": [/^data:image\/[a-zA-Z]+;base64,/, /^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)(?:[?#].*)?$/i],
"text/*": [/^data:text\//, /^https?:\/\/.+$/],
"application/*": [/^data:application\//, /^https?:\/\/.+$/]
};
this.defaultObjectGenerationMode = void 0;
this.modelId = modelId;
this.settings = settings;
this.config = config;
}
getArgs({ prompt, maxOutputTokens, temperature, topP, frequencyPenalty, presencePenalty, seed, responseFormat, topK, stopSequences, tools, toolChoice }) {
const { prompt: completionPrompt } = convertToOpenRouterCompletionPrompt({
prompt,
inputFormat: "prompt"
});
if (tools == null ? void 0 : tools.length) throw new UnsupportedFunctionalityError$1({ functionality: "tools" });
if (toolChoice) throw new UnsupportedFunctionalityError$1({ functionality: "toolChoice" });
return __spreadValues(__spreadValues({
model: this.modelId,
models: this.settings.models,
logit_bias: this.settings.logitBias,
logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0,
suffix: this.settings.suffix,
user: this.settings.user,
max_tokens: maxOutputTokens != null ? maxOutputTokens : this.settings.maxTokens,
temperature: temperature != null ? temperature : this.settings.temperature,
top_p: topP != null ? topP : this.settings.topP,
frequency_penalty: frequencyPenalty != null ? frequencyPenalty : this.settings.frequencyPenalty,
presence_penalty: presencePenalty != null ? presencePenalty : this.settings.presencePenalty,
seed,
stop: stopSequences,
response_format: responseFormat,
top_k: topK != null ? topK : this.settings.topK,
prompt: completionPrompt,
include_reasoning: this.settings.includeReasoning,
reasoning: this.settings.reasoning
}, this.config.extraBody), this.settings.extraBody);
}
async doGenerate(options) {
var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
const openrouterOptions = (options.providerOptions || {}).openrouter || {};
const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
const { value: response, responseHeaders } = await postJsonToApi$1({
url: this.config.url({
path: "/completions",
modelId: this.modelId
}),
headers: combineHeaders$1(this.config.headers(), options.headers),
body: args,
failedResponseHandler: openrouterFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$1(OpenRouterCompletionChunkSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
if ("error" in response) {
const errorData = response.error;
throw new APICallError$1({
message: errorData.message,
url: this.config.url({
path: "/completions",
modelId: this.modelId
}),
requestBodyValues: args,
statusCode: 200,
responseHeaders,
data: errorData
});
}
const choice = response.choices[0];
if (!choice) throw new NoContentGeneratedError({ message: "No choice in OpenRouter completion response" });
return {
content: [{
type: "text",
text: (_a16 = choice.text) != null ? _a16 : ""
}],
finishReason: mapOpenRouterFinishReason(choice.finish_reason),
usage: response.usage ? computeTokenUsage(response.usage) : emptyUsage(),
warnings: [],
providerMetadata: { openrouter: OpenRouterProviderMetadataSchema.parse({
provider: (_b16 = response.provider) != null ? _b16 : "",
usage: __spreadValues(__spreadValues(__spreadValues(__spreadValues({
promptTokens: (_d = (_c = response.usage) == null ? void 0 : _c.prompt_tokens) != null ? _d : 0,
completionTokens: (_f = (_e = response.usage) == null ? void 0 : _e.completion_tokens) != null ? _f : 0,
totalTokens: ((_h = (_g = response.usage) == null ? void 0 : _g.prompt_tokens) != null ? _h : 0) + ((_j = (_i = response.usage) == null ? void 0 : _i.completion_tokens) != null ? _j : 0)
}, ((_k = response.usage) == null ? void 0 : _k.cost) != null ? { cost: response.usage.cost } : {}), ((_m = (_l = response.usage) == null ? void 0 : _l.prompt_tokens_details) == null ? void 0 : _m.cached_tokens) != null ? { promptTokensDetails: { cachedTokens: response.usage.prompt_tokens_details.cached_tokens } } : {}), ((_o = (_n = response.usage) == null ? void 0 : _n.completion_tokens_details) == null ? void 0 : _o.reasoning_tokens) != null ? { completionTokensDetails: { reasoningTokens: response.usage.completion_tokens_details.reasoning_tokens } } : {}), ((_q = (_p = response.usage) == null ? void 0 : _p.cost_details) == null ? void 0 : _q.upstream_inference_cost) != null ? { costDetails: { upstreamInferenceCost: response.usage.cost_details.upstream_inference_cost } } : {})
}) },
response: { headers: responseHeaders }
};
}
async doStream(options) {
const openrouterOptions = (options.providerOptions || {}).openrouter || {};
const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
const { value: response, responseHeaders } = await postJsonToApi$1({
url: this.config.url({
path: "/completions",
modelId: this.modelId
}),
headers: combineHeaders$1(this.config.headers(), options.headers),
body: __spreadProps(__spreadValues({}, args), {
stream: true,
stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
}),
failedResponseHandler: openrouterFailedResponseHandler,
successfulResponseHandler: createEventSourceResponseHandler$1(OpenRouterCompletionChunkSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
let streamError;
const safeResponse = withStreamErrorHandling(response, (err) => {
streamError = err;
});
let finishReason = createFinishReason("other");
const usage = {
inputTokens: {
total: void 0,
noCache: void 0,
cacheRead: void 0,
cacheWrite: void 0
},
outputTokens: {
total: void 0,
text: void 0,
reasoning: void 0
},
raw: void 0
};
const openrouterUsage = {};
let provider;
let rawUsage;
return {
stream: safeResponse.pipeThrough(new TransformStream({
transform(chunk, controller) {
var _a16, _b16, _c, _d, _e;
if (options.includeRawChunks) controller.enqueue({
type: "raw",
rawValue: chunk.rawValue
});
if (!chunk.success) {
finishReason = createFinishReason("error");
controller.enqueue({
type: "error",
error: chunk.error
});
return;
}
const value = chunk.value;
if ("error" in value) {
finishReason = createFinishReason("error");
controller.enqueue({
type: "error",
error: value.error
});
return;
}
if (value.provider) provider = value.provider;
if (value.usage != null) {
const computed = computeTokenUsage(value.usage);
Object.assign(usage.inputTokens, computed.inputTokens);
Object.assign(usage.outputTokens, computed.outputTokens);
rawUsage = value.usage;
const promptTokens = (_a16 = value.usage.prompt_tokens) != null ? _a16 : 0;
const completionTokens = (_b16 = value.usage.completion_tokens) != null ? _b16 : 0;
openrouterUsage.promptTokens = promptTokens;
if (value.usage.prompt_tokens_details) openrouterUsage.promptTokensDetails = { cachedTokens: (_c = value.usage.prompt_tokens_details.cached_tokens) != null ? _c : 0 };
openrouterUsage.completionTokens = completionTokens;
if (value.usage.completion_tokens_details) openrouterUsage.completionTokensDetails = { reasoningTokens: (_d = value.usage.completion_tokens_details.reasoning_tokens) != null ? _d : 0 };
if (value.usage.cost != null) openrouterUsage.cost = value.usage.cost;
openrouterUsage.totalTokens = value.usage.total_tokens;
const upstreamInferenceCost = (_e = value.usage.cost_details) == null ? void 0 : _e.upstream_inference_cost;
if (upstreamInferenceCost != null) openrouterUsage.costDetails = { upstreamInferenceCost };
}
const choice = value.choices[0];
if ((choice == null ? void 0 : choice.finish_reason) != null) finishReason = mapOpenRouterFinishReason(choice.finish_reason);
if ((choice == null ? void 0 : choice.text) != null) controller.enqueue({
type: "text-delta",
delta: choice.text,
id: generateId$1()
});
},
flush(controller) {
if (streamError != null) {
finishReason = createFinishReason("error");
controller.enqueue({
type: "error",
error: streamError
});
}
usage.raw = rawUsage;
const openrouterMetadata = { usage: openrouterUsage };
if (provider !== void 0) openrouterMetadata.provider = provider;
controller.enqueue({
type: "finish",
finishReason,
usage,
providerMetadata: { openrouter: openrouterMetadata }
});
}
})),
response: { headers: responseHeaders }
};
}
};
var openrouterEmbeddingUsageSchema = z.object({
prompt_tokens: z.number(),
total_tokens: z.number(),
cost: z.number().optional()
});
var openrouterEmbeddingDataSchema = z.object({
object: z.literal("embedding"),
embedding: z.array(z.number()),
index: z.number().optional()
});
var OpenRouterEmbeddingResponseSchema = z.object({
id: z.string().optional(),
object: z.literal("list"),
data: z.array(openrouterEmbeddingDataSchema),
model: z.string(),
provider: z.string().optional(),
usage: openrouterEmbeddingUsageSchema.optional()
});
var OpenRouterEmbeddingModel = class {
constructor(modelId, settings, config) {
this.specificationVersion = "v3";
this.provider = "openrouter";
this.maxEmbeddingsPerCall = void 0;
this.supportsParallelCalls = true;
this.modelId = modelId;
this.settings = settings;
this.config = config;
}
async doEmbed(options) {
var _a16, _b16, _c, _d, _e, _f;
const { values, abortSignal, headers } = options;
const args = __spreadValues(__spreadValues({
model: this.modelId,
input: values,
user: this.settings.user,
provider: this.settings.provider
}, this.config.extraBody), this.settings.extraBody);
const { value: responseValue, responseHeaders } = await postJsonToApi$1({
url: this.config.url({
path: "/embeddings",
modelId: this.modelId
}),
headers: combineHeaders$1(this.config.headers(), headers),
body: args,
failedResponseHandler: openrouterFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$1(OpenRouterEmbeddingResponseSchema),
abortSignal,
fetch: this.config.fetch
});
return {
embeddings: responseValue.data.map((item) => item.embedding),
usage: responseValue.usage ? { tokens: responseValue.usage.prompt_tokens } : void 0,
providerMetadata: { openrouter: OpenRouterProviderMetadataSchema.parse({
provider: (_a16 = responseValue.provider) != null ? _a16 : "",
usage: __spreadValues({
promptTokens: (_c = (_b16 = responseValue.usage) == null ? void 0 : _b16.prompt_tokens) != null ? _c : 0,
completionTokens: 0,
totalTokens: (_e = (_d = responseValue.usage) == null ? void 0 : _d.total_tokens) != null ? _e : 0
}, ((_f = responseValue.usage) == null ? void 0 : _f.cost) != null ? { cost: responseValue.usage.cost } : {})
}) },
response: {
headers: responseHeaders,
body: responseValue
},
warnings: []
};
}
};
var OpenRouterImageResponseSchema = z.object({
created: z.number().optional(),
data: z.array(z.object({ b64_json: z.string() }).passthrough()),
usage: z.object({
prompt_tokens: z.number(),
completion_tokens: z.number(),
total_tokens: z.number()
}).passthrough().optional()
}).passthrough();
var OpenRouterImageModel = class {
constructor(modelId, settings, config) {
this.specificationVersion = "v3";
this.provider = "openrouter";
this.maxImagesPerCall = 10;
this.modelId = modelId;
this.settings = settings;
this.config = config;
}
async doGenerate(options) {
const { prompt, n, size, aspectRatio, seed, files, mask, abortSignal, headers, providerOptions } = options;
const openrouterOptions = (providerOptions == null ? void 0 : providerOptions.openrouter) || {};
const warnings = [];
if (mask !== void 0) throw new UnsupportedFunctionalityError$1({ functionality: "image inpainting (mask parameter)" });
const inputReferences = files !== void 0 && files.length > 0 ? files.map((file) => convertFileToInputReference(file)) : void 0;
const body = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
model: this.modelId,
prompt: prompt != null ? prompt : ""
}, n !== void 0 && { n }), size !== void 0 && { size }), aspectRatio !== void 0 && { aspect_ratio: aspectRatio }), seed !== void 0 && { seed }), inputReferences !== void 0 && { input_references: inputReferences }), this.settings.user !== void 0 && { user: this.settings.user }), this.settings.provider !== void 0 && { provider: this.settings.provider }), this.config.extraBody), this.settings.extraBody), openrouterOptions);
const { value: responseValue, responseHeaders } = await postJsonToApi$1({
url: this.config.url({
path: "/images",
modelId: this.modelId
}),
headers: combineHeaders$1(this.config.headers(), headers),
body,
failedResponseHandler: openrouterFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$1(OpenRouterImageResponseSchema),
abortSignal,
fetch: this.config.fetch
});
if (!responseValue.data || responseValue.data.length === 0) throw new NoContentGeneratedError({ message: "No images in response" });
const images = responseValue.data.map((item) => item.b64_json);
const usage = responseValue.usage ? {
inputTokens: responseValue.usage.prompt_tokens,
outputTokens: responseValue.usage.completion_tokens,
totalTokens: responseValue.usage.total_tokens
} : void 0;
return {
images,
warnings,
response: {
timestamp: /* @__PURE__ */ new Date(),
modelId: this.modelId,
headers: responseHeaders
},
usage
};
}
};
var DEFAULT_IMAGE_MEDIA_TYPE = "image/png";
function convertFileToInputReference(file) {
if (file.type === "url") return {
type: "image_url",
image_url: { url: file.url }
};
return {
type: "image_url",
image_url: { url: buildFileDataUrl({
data: file.data,
mediaType: file.mediaType,
defaultMediaType: DEFAULT_IMAGE_MEDIA_TYPE
}) }
};
}
var webSearch$1 = createProviderToolFactory({
id: "openrouter.web_search",
inputSchema: z.object({
/** Search results returned by the server tool */
results: z.array(z.unknown()).optional() })
});
function removeUndefinedEntries$1(record) {
return Object.fromEntries(Object.entries(record).filter(([, value]) => value != null));
}
function normalizeHeaders2(headers) {
if (!headers) return {};
if (headers instanceof Headers) return Object.fromEntries(headers.entries());
if (Array.isArray(headers)) return Object.fromEntries(headers);
return headers;
}
function findHeaderKey(headers, targetKey) {
const lowerTarget = targetKey.toLowerCase();
return Object.keys(headers).find((key) => key.toLowerCase() === lowerTarget);
}
function withUserAgentSuffix2(headers, ...userAgentSuffixParts) {
const cleanedHeaders = removeUndefinedEntries$1(normalizeHeaders2(headers));
const existingUserAgentKey = findHeaderKey(cleanedHeaders, "user-agent");
const existingUserAgentValue = existingUserAgentKey ? cleanedHeaders[existingUserAgentKey] : void 0;
const userAgent = (existingUserAgentValue == null ? void 0 : existingUserAgentValue.trim()) ? existingUserAgentValue : userAgentSuffixParts.filter(Boolean).join(" ");
return __spreadProps(__spreadValues({}, Object.fromEntries(Object.entries(cleanedHeaders).filter(([key]) => key.toLowerCase() !== "user-agent"))), { "user-agent": userAgent });
}
var VERSION2 = "2.10.0";
var VideoGenerationSubmitResponseSchema = z.object({
id: z.string(),
generation_id: z.string().optional(),
polling_url: z.string(),
status: z.string()
}).passthrough();
var VideoGenerationPollResponseSchema = z.object({
id: z.string(),
generation_id: z.string().optional(),
polling_url: z.string(),
status: z.string(),
unsigned_urls: z.array(z.string()).optional(),
usage: z.object({
cost: z.number().optional(),
is_byok: z.boolean().optional()
}).passthrough().optional(),
error: z.string().optional()
}).passthrough();
var DEFAULT_POLL_INTERVAL_MS = 2e3;
var DEFAULT_MAX_POLL_TIME_MS = 6e5;
var OpenRouterVideoModel = class {
constructor(modelId, settings, config) {
this.specificationVersion = "v3";
this.provider = "openrouter";
this.maxVideosPerCall = 1;
this.modelId = modelId;
this.settings = settings;
this.config = config;
}
async doGenerate(options) {
var _a16, _b16, _c, _d, _e;
const { prompt, n, aspectRatio, resolution, duration, seed, image, abortSignal, headers, providerOptions } = options;
const warnings = [];
if (n > 1) warnings.push({
type: "unsupported",
feature: "n > 1",
details: `OpenRouter video generation returns 1 video per call. Requested ${n} videos.`
});
const body = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
model: this.modelId,
prompt: prompt != null ? prompt : ""
}, aspectRatio !== void 0 && { aspect_ratio: aspectRatio }), resolution !== void 0 && { size: resolution }), duration !== void 0 && { duration }), seed !== void 0 && { seed }), this.settings.generateAudio !== void 0 && { generate_audio: this.settings.generateAudio }), image !== void 0 && { frame_images: [convertImageToFrameImage(image)] }), this.config.extraBody), this.settings.extraBody), providerOptions.openrouter);
const mergedHeaders = combineHeaders$1(this.config.headers(), headers);
const { value: submitResponse, responseHeaders } = await postJsonToApi$1({
url: this.config.url({
path: "/videos",
modelId: this.modelId
}),
headers: mergedHeaders,
body,
failedResponseHandler: openrouterFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$1(VideoGenerationSubmitResponseSchema),
abortSignal,
fetch: this.config.fetch
});
const pollIntervalMs = (_a16 = this.settings.pollIntervalMs) != null ? _a16 : DEFAULT_POLL_INTERVAL_MS;
const maxPollTimeMs = (_b16 = this.settings.maxPollTimeMs) != null ? _b16 : DEFAULT_MAX_POLL_TIME_MS;
const pollResult = await this.pollUntilComplete({
jobId: submitResponse.id,
headers: mergedHeaders,
abortSignal,
pollIntervalMs,
maxPollTimeMs
});
const videos = [];
if (pollResult.unsigned_urls) for (const url of pollResult.unsigned_urls) videos.push({
type: "url",
url,
mediaType: "video/mp4"
});
return {
videos,
warnings,
providerMetadata: { openrouter: {
generationId: (_c = pollResult.generation_id) != null ? _c : null,
cost: (_e = (_d = pollResult.usage) == null ? void 0 : _d.cost) != null ? _e : null
} },
response: {
timestamp: /* @__PURE__ */ new Date(),
modelId: this.modelId,
headers: responseHeaders
}
};
}
async pollUntilComplete({ jobId, headers, abortSignal, pollIntervalMs, maxPollTimeMs }) {
var _a16;
const startTime = Date.now();
while (Date.now() - startTime < maxPollTimeMs) {
abortSignal?.throwIfAborted();
await delay$1(pollIntervalMs);
abortSignal?.throwIfAborted();
const { value: pollResponse } = await getFromApi$1({
url: this.config.url({
path: `/videos/${jobId}`,
modelId: this.modelId
}),
headers,
failedResponseHandler: openrouterFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$1(VideoGenerationPollResponseSchema),
abortSignal,
fetch: this.config.fetch
});
if (pollResponse.status === "completed") return {
generation_id: pollResponse.generation_id,
unsigned_urls: pollResponse.unsigned_urls,
usage: pollResponse.usage
};
if (pollResponse.status === "failed" || pollResponse.status === "dead" || pollResponse.status === "cancelled" || pollResponse.status === "expired") throw new APICallError$1({
message: (_a16 = pollResponse.error) != null ? _a16 : `Video generation failed with status: ${pollResponse.status}`,
url: this.config.url({
path: `/videos/${jobId}`,
modelId: this.modelId
}),
requestBodyValues: {},
statusCode: 500,
isRetryable: false
});
}
throw new APICallError$1({
message: `Video generation timed out after ${maxPollTimeMs}ms`,
url: this.config.url({
path: `/videos/${jobId}`,
modelId: this.modelId
}),
requestBodyValues: {},
statusCode: 408,
isRetryable: true
});
}
};
function convertImageToFrameImage(file) {
if (file.type === "url") return {
type: "image_url",
image_url: { url: file.url },
frame_type: "first_frame"
};
return {
type: "image_url",
image_url: { url: buildFileDataUrl({
data: file.data,
mediaType: file.mediaType,
defaultMediaType: "image/png"
}) },
frame_type: "first_frame"
};
}
function createOpenRouter(options = {}) {
var _a16, _b16, _c;
const baseURL = (_b16 = withoutTrailingSlash$1((_a16 = options.baseURL) != null ? _a16 : options.baseUrl)) != null ? _b16 : "https://openrouter.ai/api/v1";
const compatibility = (_c = options.compatibility) != null ? _c : "compatible";
const getHeaders = () => withUserAgentSuffix2(__spreadValues(__spreadValues(__spreadValues(__spreadValues({ Authorization: `Bearer ${loadApiKey$1({
apiKey: options.apiKey,
environmentVariableName: "OPENROUTER_API_KEY",
description: "OpenRouter"
})}` }, options.appName && { "X-OpenRouter-Title": options.appName }), options.appUrl && { "HTTP-Referer": options.appUrl }), options.headers), options.api_keys && Object.keys(options.api_keys).length > 0 && { "X-Provider-API-Keys": JSON.stringify(options.api_keys) }), `ai-sdk/openrouter/${VERSION2}`);
const createChatModel = (modelId, settings = {}) => new OpenRouterChatLanguageModel(modelId, settings, {
provider: "openrouter.chat",
url: ({ path }) => `${baseURL}${path}`,
headers: getHeaders,
compatibility,
fetch: options.fetch,
extraBody: options.extraBody
});
const createCompletionModel = (modelId, settings = {}) => new OpenRouterCompletionLanguageModel(modelId, settings, {
provider: "openrouter.completion",
url: ({ path }) => `${baseURL}${path}`,
headers: getHeaders,
compatibility,
fetch: options.fetch,
extraBody: options.extraBody
});
const createEmbeddingModel = (modelId, settings = {}) => new OpenRouterEmbeddingModel(modelId, settings, {
provider: "openrouter.embedding",
url: ({ path }) => `${baseURL}${path}`,
headers: getHeaders,
fetch: options.fetch,
extraBody: options.extraBody
});
const createImageModel = (modelId, settings = {}) => new OpenRouterImageModel(modelId, settings, {
provider: "openrouter.image",
url: ({ path }) => `${baseURL}${path}`,
headers: getHeaders,
fetch: options.fetch,
extraBody: options.extraBody
});
const createVideoModel = (modelId, settings = {}) => new OpenRouterVideoModel(modelId, settings, {
provider: "openrouter.video",
url: ({ path }) => `${baseURL}${path}`,
headers: getHeaders,
fetch: options.fetch,
extraBody: options.extraBody
});
const createLanguageModel = (modelId, settings) => {
if (new.target) throw new Error("The OpenRouter model function cannot be called with the new keyword.");
if (modelId === "openai/gpt-3.5-turbo-instruct") return createCompletionModel(modelId, settings);
return createChatModel(modelId, settings);
};
const provider = (modelId, settings) => createLanguageModel(modelId, settings);
provider.languageModel = createLanguageModel;
provider.chat = createChatModel;
provider.completion = createCompletionModel;
provider.textEmbeddingModel = createEmbeddingModel;
provider.embedding = createEmbeddingModel;
provider.imageModel = createImageModel;
provider.videoModel = createVideoModel;
provider.tools = { webSearch: webSearch$1 };
return provider;
}
createOpenRouter({ compatibility: "strict" });
// src/llm/model/gateways/constants.ts
const MASTRA_USER_AGENT = `mastra/1.85.0`;
const PROVIDERS_WITH_INSTALLED_PACKAGES = [
"anthropic",
"cerebras",
"deepinfra",
"deepseek",
"google",
"groq",
"mistral",
"openai",
"openrouter",
"perplexity",
"togetherai",
"vercel",
"xai"
];
const EXCLUDED_PROVIDERS = ["github-copilot"];
const GATEWAY_AUTH_HEADER = "X-Memory-Gateway-Authorization";
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/provider/4.0.38/e664e4f4a2f64bc01469ef66c795af801494dcfe68f16e0722387d5cb8fc483e/node_modules/@ai-sdk/provider/dist/index.js
/**
* Symbol used for identifying AI SDK Error instances.
* Enables checking if an error is an instance of AISDKError across package versions.
*/
const marker$18 = "vercel.ai.error";
const symbol$18 = Symbol.for(marker$18);
/**
* Custom error class for AI SDK related errors.
* @extends Error
*/
var AISDKError = class AISDKError extends Error {
/**
* Creates an AI SDK Error.
*
* @param {Object} params - The parameters for creating the error.
* @param {string} params.name - The name of the error.
* @param {string} params.message - The error message.
* @param {unknown} [params.cause] - The underlying cause of the error.
*/
constructor({ name, message, cause }) {
super(message);
this[symbol$18] = true;
this.name = name;
this.cause = cause;
}
/**
* Checks if the given error is an AI SDK Error.
* @param {unknown} error - The error to check.
* @returns {boolean} True if the error is an AI SDK Error, false otherwise.
*/
static isInstance(error) {
return AISDKError.hasMarker(error, marker$18);
}
static hasMarker(error, marker) {
const markerSymbol = Symbol.for(marker);
return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
}
};
const name$16 = "AI_APICallError";
const marker$16 = `vercel.ai.error.${name$16}`;
const symbol$16 = Symbol.for(marker$16);
var APICallError = class extends AISDKError {
constructor({ message, url, requestBodyValues, statusCode, responseHeaders, responseBody, cause, isRetryable = statusCode != null && (statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500), data }) {
super({
name: name$16,
message,
cause
});
this[symbol$16] = true;
this.url = url;
this.requestBodyValues = requestBodyValues;
this.statusCode = statusCode;
this.responseHeaders = responseHeaders;
this.responseBody = responseBody;
this.isRetryable = isRetryable;
this.data = data;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker$16);
}
};
const name$15 = "AI_EmptyResponseBodyError";
const marker$15 = `vercel.ai.error.${name$15}`;
const symbol$15 = Symbol.for(marker$15);
var EmptyResponseBodyError = class extends AISDKError {
constructor({ message = "Empty response body" } = {}) {
super({
name: name$15,
message
});
this[symbol$15] = true;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker$15);
}
};
function getErrorMessage(error) {
if (error == null) return "unknown error";
if (typeof error === "string") return error;
if (error instanceof Error) return error.toString();
return JSON.stringify(error);
}
const name$11 = "AI_InvalidArgumentError";
const marker$11 = `vercel.ai.error.${name$11}`;
const symbol$11 = Symbol.for(marker$11);
/**
* A function argument is invalid.
*/
var InvalidArgumentError = class extends AISDKError {
constructor({ message, cause, argument }) {
super({
name: name$11,
message,
cause
});
this[symbol$11] = true;
this.argument = argument;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker$11);
}
};
const name$10 = "AI_InvalidPromptError";
const marker$10 = `vercel.ai.error.${name$10}`;
const symbol$10 = Symbol.for(marker$10);
/**
* A prompt is invalid. This error should be thrown by providers when they cannot
* process a prompt.
*/
var InvalidPromptError = class extends AISDKError {
constructor({ prompt, message, cause }) {
super({
name: name$10,
message: `Invalid prompt: ${message}`,
cause
});
this[symbol$10] = true;
this.prompt = prompt;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker$10);
}
};
const name$9 = "AI_InvalidResponseDataError";
const marker$9 = `vercel.ai.error.${name$9}`;
const symbol$9 = Symbol.for(marker$9);
/**
* Server returned a response with invalid data content.
* This should be thrown by providers when they cannot parse the response from the API.
*/
var InvalidResponseDataError = class extends AISDKError {
constructor({ data, message = `Invalid response data: ${JSON.stringify(data)}.` }) {
super({
name: name$9,
message
});
this[symbol$9] = true;
this.data = data;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker$9);
}
};
const name$8 = "AI_JSONParseError";
const marker$8 = `vercel.ai.error.${name$8}`;
const symbol$8 = Symbol.for(marker$8);
var JSONParseError = class extends AISDKError {
constructor({ text, cause }) {
super({
name: name$8,
message: `JSON parsing failed: Text: ${text}.\nError message: ${getErrorMessage(cause)}`,
cause
});
this[symbol$8] = true;
this.text = text;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker$8);
}
};
const name$7 = "AI_LoadAPIKeyError";
const marker$7 = `vercel.ai.error.${name$7}`;
const symbol$7 = Symbol.for(marker$7);
var LoadAPIKeyError = class extends AISDKError {
constructor({ message }) {
super({
name: name$7,
message
});
this[symbol$7] = true;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker$7);
}
};
const name$4 = "AI_NoSuchModelError";
const marker$4 = `vercel.ai.error.${name$4}`;
const symbol$4 = Symbol.for(marker$4);
var NoSuchModelError = class extends AISDKError {
constructor({ errorName = name$4, modelId, modelType, message = `No such ${modelType}: ${modelId}` }) {
super({
name: errorName,
message
});
this[symbol$4] = true;
this.modelId = modelId;
this.modelType = modelType;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker$4);
}
};
const name$3 = "AI_NoSuchProviderReferenceError";
const marker$3 = `vercel.ai.error.${name$3}`;
const symbol$3 = Symbol.for(marker$3);
/**
* Thrown when a provider reference cannot be resolved because the specified
* provider is not found in the provider reference mapping.
*/
var NoSuchProviderReferenceError = class extends AISDKError {
constructor({ provider, reference, message = `No provider reference found for provider '${provider}'. Available providers: ${Object.keys(reference).join(", ")}` }) {
super({
name: name$3,
message
});
this[symbol$3] = true;
this.provider = provider;
this.reference = reference;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker$3);
}
};
const name$2 = "AI_TooManyEmbeddingValuesForCallError";
const marker$2$1 = `vercel.ai.error.${name$2}`;
const symbol$2 = Symbol.for(marker$2$1);
var TooManyEmbeddingValuesForCallError = class extends AISDKError {
constructor(options) {
super({
name: name$2,
message: `Too many values for a single embedding call. The ${options.provider} model "${options.modelId}" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`
});
this[symbol$2] = true;
this.provider = options.provider;
this.modelId = options.modelId;
this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;
this.values = options.values;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker$2$1);
}
};
const name$1$1 = "AI_TypeValidationError";
const marker$1$1 = `vercel.ai.error.${name$1$1}`;
const symbol$1$1 = Symbol.for(marker$1$1);
var TypeValidationError = class TypeValidationError extends AISDKError {
constructor({ value, cause, context }) {
let contextPrefix = "Type validation failed";
if (context?.field) contextPrefix += ` for ${context.field}`;
if (context?.entityName || context?.entityId) {
contextPrefix += " (";
const parts = [];
if (context.entityName) parts.push(context.entityName);
if (context.entityId) parts.push(`id: "${context.entityId}"`);
contextPrefix += parts.join(", ");
contextPrefix += ")";
}
super({
name: name$1$1,
message: `${contextPrefix}: Value: ${JSON.stringify(value)}.\nError message: ${getErrorMessage(cause)}`,
cause
});
this[symbol$1$1] = true;
this.value = value;
this.context = context;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker$1$1);
}
/**
* Wraps an error into a TypeValidationError.
* If the cause is already a TypeValidationError with the same value and context, it returns the cause.
* Otherwise, it creates a new TypeValidationError.
*
* @param {Object} params - The parameters for wrapping the error.
* @param {unknown} params.value - The value that failed validation.
* @param {unknown} params.cause - The original error or cause of the validation failure.
* @param {TypeValidationContext} params.context - Optional context about what is being validated.
* @returns {TypeValidationError} A TypeValidationError instance.
*/
static wrap({ value, cause, context }) {
if (TypeValidationError.isInstance(cause) && cause.value === value && cause.context?.field === context?.field && cause.context?.entityName === context?.entityName && cause.context?.entityId === context?.entityId) return cause;
return new TypeValidationError({
value,
cause,
context
});
}
};
const name$18 = "AI_UnsupportedFunctionalityError";
const marker$19 = `vercel.ai.error.${name$18}`;
const symbol$19 = Symbol.for(marker$19);
var UnsupportedFunctionalityError = class extends AISDKError {
constructor({ functionality, message = `'${functionality}' functionality not supported.` }) {
super({
name: name$18,
message
});
this[symbol$19] = true;
this.functionality = functionality;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker$19);
}
};
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@workflow/serde/4.1.0/261fd96db91ae08052ff2d7ce2a9dc7ec2871d6a9ad311cee344b4f0d349e5bf/node_modules/@workflow/serde/dist/index.js
/**
* Symbol used to define custom serialization for user-defined class instances.
* The static method should accept an instance and return serializable data.
*
* @example
* ```ts
* import { WORKFLOW_SERIALIZE, WORKFLOW_DESERIALIZE } from '@workflow/serde';
*
* class MyClass {
* constructor(public value: string) {}
*
* static [WORKFLOW_SERIALIZE](instance: MyClass) {
* return { value: instance.value };
* }
*
* static [WORKFLOW_DESERIALIZE](data: { value: string }) {
* return new MyClass(data.value);
* }
* }
* ```
*/
const WORKFLOW_SERIALIZE = Symbol.for("workflow-serialize");
/**
* Symbol used to define custom deserialization for user-defined class instances.
* The static method should accept serialized data and return a class instance.
*
* @see WORKFLOW_SERIALIZE for usage example
*/
const WORKFLOW_DESERIALIZE = Symbol.for("workflow-deserialize");
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/provider-utils/5.0.81/3fe99b0b1a12e8ff07f54d06d435091d33858c41c659323e4db790d385895181/node_modules/@ai-sdk/provider-utils/dist/index.js
function combineHeaders(...headers) {
return headers.reduce((combinedHeaders, currentHeaders) => ({
...combinedHeaders,
...currentHeaders
}), {});
}
/**
* Removes entries from a record where the value is null or undefined.
* @param record - The input object whose entries may be null or undefined.
* @returns A new object containing only entries with non-null and non-undefined values.
*/
function removeUndefinedEntries(record) {
return Object.fromEntries(Object.entries(record).filter(([_key, value]) => value != null));
}
/**
* Creates a Promise that resolves after a specified delay
* @param delayInMs - The delay duration in milliseconds. If null or undefined, resolves immediately.
* @param signal - Optional AbortSignal to cancel the delay
* @returns A Promise that resolves after the specified delay
* @throws {DOMException} When the signal is aborted
*/
async function delay(delayInMs, options) {
if (delayInMs == null) return;
const signal = options?.abortSignal;
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(createAbortError());
return;
}
const timeoutId = setTimeout(() => {
cleanup();
resolve();
}, delayInMs);
const cleanup = () => {
clearTimeout(timeoutId);
signal?.removeEventListener("abort", onAbort);
};
const onAbort = () => {
cleanup();
reject(createAbortError());
};
signal?.addEventListener("abort", onAbort);
});
}
function createAbortError() {
return new DOMException("Delay was aborted", "AbortError");
}
function getWebSocketConstructor(webSocket) {
const WebSocketConstructor = webSocket ?? globalThis.WebSocket;
if (WebSocketConstructor == null) throw new Error("No WebSocket implementation available.");
return WebSocketConstructor;
}
/**
* Converts an http(s) URL to the corresponding ws(s) URL.
*/
function toWebSocketUrl(url) {
const wsUrl = new URL(url);
if (wsUrl.protocol === "http:") wsUrl.protocol = "ws:";
else if (wsUrl.protocol === "https:") wsUrl.protocol = "wss:";
return wsUrl;
}
const textDecoder$1$1 = new TextDecoder();
/**
* Reads WebSocket message data as text, handling string, binary,
* and Blob payloads.
*/
async function readWebSocketMessageText(data) {
if (typeof data === "string") return data;
if (data instanceof ArrayBuffer) return textDecoder$1$1.decode(data);
if (ArrayBuffer.isView(data)) return textDecoder$1$1.decode(data);
if (typeof Blob !== "undefined" && data instanceof Blob) return data.text();
return String(data);
}
const WEBSOCKET_OPEN_STATE = 1;
/**
* Waits until the socket's send buffer drains below `highWaterMark` bytes.
* No-op for implementations that do not expose `bufferedAmount`. There is no
* portable drain event, so this polls. Returns as soon as the socket is no
* longer open or the signal aborts — `bufferedAmount` never drains on a
* closed socket, so waiting on would poll forever.
*/
async function waitForWebSocketBufferDrain(socket, { highWaterMark = 1048576, pollIntervalMs = 20, abortSignal } = {}) {
while (socket.readyState === WEBSOCKET_OPEN_STATE && (socket.bufferedAmount ?? 0) > highWaterMark) {
if (abortSignal?.aborted === true) return;
await delay(pollIntervalMs);
}
}
/**
* Opens a WebSocket for a provider model, owning the transport-generic layer
* (analogous to `postToApi` for HTTP): constructor resolution, header hygiene,
* abort wiring, and message decoding. Callers own the URL, the auth channel
* (subprotocols vs headers), and the wire protocol.
*/
function connectToWebSocket({ url, protocols, headers, webSocket, abortSignal, onOpen, onMessageText, onProcessingError, onSocketError, onClose, onAbort }) {
let socket;
let abortListener;
const close = (code) => {
if (abortListener != null) {
abortSignal?.removeEventListener("abort", abortListener);
abortListener = void 0;
}
try {
socket?.close(code);
} catch {}
};
if (abortSignal?.aborted) {
onAbort?.(abortSignal.reason ?? /* @__PURE__ */ new Error("Aborted"));
return {
socket: void 0,
close
};
}
try {
socket = new (getWebSocketConstructor(webSocket))(url, protocols, { headers: removeUndefinedEntries(headers ?? {}) });
} catch (error) {
onProcessingError(error);
return {
socket: void 0,
close
};
}
if (abortSignal != null && onAbort != null) {
abortListener = () => onAbort(abortSignal.reason ?? /* @__PURE__ */ new Error("Aborted"));
abortSignal.addEventListener("abort", abortListener, { once: true });
}
const openedSocket = socket;
socket.onopen = () => {
try {
onOpen?.(openedSocket);
} catch (error) {
onProcessingError(error);
}
};
let tail = Promise.resolve();
socket.onmessage = (event) => {
tail = tail.then(() => readWebSocketMessageText(event.data)).then((text) => onMessageText(text)).catch(onProcessingError);
};
socket.onerror = () => {
tail = tail.then(() => onSocketError?.()).catch(onProcessingError);
};
socket.onclose = (event) => {
const closeEvent = event;
const code = typeof closeEvent?.code === "number" ? closeEvent.code : void 0;
const reason = typeof closeEvent?.reason === "string" ? closeEvent.reason : void 0;
tail = tail.then(() => onClose?.({
code,
reason
})).catch(onProcessingError);
};
return {
socket,
close
};
}
/**
* Converts an AsyncIterator to a ReadableStream.
*
* @template T - The type of elements produced by the AsyncIterator.
* @param { <T>} iterator - The AsyncIterator to convert.
* @returns {ReadableStream<T>} - A ReadableStream that provides the same data as the AsyncIterator.
*/
function convertAsyncIteratorToReadableStream(iterator) {
let cancelled = false;
return new ReadableStream({
/**
* Called when the consumer wants to pull more data from the stream.
*
* @param {ReadableStreamDefaultController<T>} controller - The controller to enqueue data into the stream.
* @returns {Promise<void>}
*/
async pull(controller) {
if (cancelled) return;
try {
const { value, done } = await iterator.next();
if (done) controller.close();
else controller.enqueue(value);
} catch (error) {
controller.error(error);
}
},
/**
* Called when the consumer cancels the stream.
*/
async cancel(reason) {
cancelled = true;
if (iterator.return) try {
await iterator.return(reason);
} catch {}
}
});
}
const { btoa, atob } = globalThis;
function convertBase64ToUint8Array(base64String) {
const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/");
const latin1string = atob(base64Url);
const bytes = new Uint8Array(latin1string.length);
for (let i = 0; i < latin1string.length; i++) bytes[i] = latin1string.charCodeAt(i);
return bytes;
}
function convertUint8ArrayToBase64(array) {
if (typeof globalThis.Buffer?.from === "function") return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString("base64");
const chunks = [];
const chunkSize = 4096;
for (let i = 0; i < array.length; i += chunkSize) chunks.push(String.fromCodePoint(...array.subarray(i, i + chunkSize)));
return btoa(chunks.join(""));
}
const typedArrayTag = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
const arrayBufferByteLength = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
function isUint8Array(value) {
return ArrayBuffer.isView(value) && typedArrayTag.call(value) === "Uint8Array";
}
function isArrayBuffer(value) {
if (typeof value !== "object" || value === null || !("byteLength" in value)) return false;
try {
arrayBufferByteLength.call(value);
return true;
} catch {
return false;
}
}
function convertToBase64(value) {
return isUint8Array(value) ? convertUint8ArrayToBase64(value) : value;
}
/**
* Converts inline file data (a tagged `data` or `text` shape) into raw bytes.
*
* - `{ type: 'text', text }` → UTF-8 encoded bytes
* - `{ type: 'data', data: Uint8Array | Buffer }` → returned as-is
* - `{ type: 'data', data: ArrayBuffer }` → wrapped in a `Uint8Array`
* - `{ type: 'data', data: string }` → decoded as base64
*
* `{ type: 'stream' }` data is rejected: providers without streaming upload
* support funnel here and surface a clear `UnsupportedFunctionalityError`.
*/
function convertInlineFileDataToUint8Array(data) {
if (data.type === "stream") {
const error = new UnsupportedFunctionalityError({ functionality: "streaming file upload" });
data.stream.cancel(error).catch(() => {});
throw error;
}
if (data.type === "text") return new TextEncoder().encode(data.text);
if (data.data instanceof Uint8Array) return data.data;
if (isUint8Array(data.data)) return new Uint8Array(data.data.buffer, data.data.byteOffset, data.data.byteLength);
if (isArrayBuffer(data.data)) return new Uint8Array(data.data);
return convertBase64ToUint8Array(data.data);
}
/**
* Convert an ImageModelV4File to a URL or data URI string.
*
* If the file is a URL, it returns the URL as-is.
* If the file is base64 data, it returns a data URI with the base64 data.
* If the file is a Uint8Array, it converts it to base64 and returns a data URI.
*/
function convertImageModelFileToDataUri(file) {
if (file.type === "url") return file.url;
return `data:${file.mediaType};base64,${typeof file.data === "string" ? file.data : convertUint8ArrayToBase64(file.data)}`;
}
/**
* Providers that cannot use native structured output for a request can use a
* JSON response tool instead. This utility converts that tool's streamed input
* into text events so the SDK can parse it as structured output.
*
* Conversational text is suppressed. Application tool calls pass through so the
* caller can execute them. A response containing only the JSON tool finishes
* with `stop`; a response containing application calls keeps its finish reason.
*/
function convertJsonResponseToolStream(toolName) {
const responseToolIds = /* @__PURE__ */ new Set();
const responseToolsWithDeltas = /* @__PURE__ */ new Set();
let hasResponseTool = false;
let hasApplicationTool = false;
return new TransformStream({ transform(part, controller) {
switch (part.type) {
case "text-start":
case "text-delta":
case "text-end": return;
case "tool-input-start":
if (part.toolName === toolName) {
responseToolIds.add(part.id);
controller.enqueue({
type: "text-start",
id: part.id,
...part.providerMetadata && { providerMetadata: part.providerMetadata }
});
return;
}
break;
case "tool-input-delta":
if (responseToolIds.has(part.id)) {
if (part.delta.length > 0) responseToolsWithDeltas.add(part.id);
controller.enqueue({
type: "text-delta",
id: part.id,
delta: part.delta,
...part.providerMetadata && { providerMetadata: part.providerMetadata }
});
return;
}
break;
case "tool-input-end":
if (responseToolIds.has(part.id)) return;
break;
case "tool-call":
if (part.toolName === toolName) {
if (!responseToolsWithDeltas.has(part.toolCallId)) controller.enqueue({
type: "text-delta",
id: part.toolCallId,
delta: part.input,
...part.providerMetadata && { providerMetadata: part.providerMetadata }
});
controller.enqueue({
type: "text-end",
id: part.toolCallId,
...part.providerMetadata && { providerMetadata: part.providerMetadata }
});
hasResponseTool = true;
return;
}
if (!part.providerExecuted) hasApplicationTool = true;
break;
case "finish": if (hasResponseTool && !hasApplicationTool && part.finishReason.unified === "tool-calls") {
controller.enqueue({
...part,
finishReason: {
...part.finishReason,
unified: "stop"
}
});
return;
}
}
controller.enqueue(part);
} });
}
/**
* Converts an input object to FormData for multipart/form-data requests.
*
* Handles the following cases:
* - `null` or `undefined` values are skipped
* - Arrays with a single element are appended as a single value
* - Arrays with multiple elements are appended with `[]` suffix (e.g., `image[]`)
* unless `useArrayBrackets` is set to `false`
* - All other values are appended directly
*
* @param input - The input object to convert. Use a generic type for type validation.
* @param options - Optional configuration object.
* @param options.useArrayBrackets - Whether to add `[]` suffix for multi-element arrays.
* Defaults to `true`. Set to `false` for APIs that expect repeated keys without brackets.
* @returns A FormData object containing the input values.
*
* @example
* ```ts
* type MyInput = {
* model: string;
* prompt: string;
* images: Blob[];
* };
*
* const formData = convertToFormData<MyInput>({
* model: 'gpt-image-1',
* prompt: 'A cat',
* images: [blob1, blob2],
* });
* ```
*/
function convertToFormData(input, options = {}) {
const { useArrayBrackets = true } = options;
const formData = new FormData();
for (const [key, value] of Object.entries(input)) {
if (value == null) continue;
if (Array.isArray(value)) {
if (value.length === 1) {
formData.append(key, value[0]);
continue;
}
const arrayKey = useArrayBrackets ? `${key}[]` : key;
for (const item of value) formData.append(arrayKey, item);
continue;
}
formData.append(key, value);
}
return formData;
}
/**
* Converts common provider response fields into language model response
* metadata.
*/
function createLanguageModelResponseMetadata({ id, model, created }) {
return {
id: id ?? void 0,
modelId: model ?? void 0,
timestamp: created != null ? /* @__PURE__ */ new Date(created * 1e3) : void 0
};
}
/**
* Creates an empty language model usage result for unavailable usage data.
*/
function createNullLanguageModelUsage() {
return {
inputTokens: {
total: void 0,
noCache: void 0,
cacheRead: void 0,
cacheWrite: void 0
},
outputTokens: {
total: void 0,
text: void 0,
reasoning: void 0
},
raw: void 0
};
}
const marker$2 = Symbol.for("vercel.ai.providerStreamError");
/**
* Adds provider-owned status and retry metadata to a stream error payload
* without requiring provider packages to depend on AI SDK Core.
*/
function createProviderStreamError({ message, type, code, statusCode, isRetryable, data }) {
const error = {
message,
type,
code,
statusCode,
isRetryable,
data
};
Object.defineProperty(error, marker$2, { value: true });
return error;
}
/**
* Extracts the headers from a response object and returns them as a key-value object.
*
* @param response - The response object to extract headers from.
* @returns The headers as a key-value object.
*/
function extractResponseHeaders(response) {
return Object.fromEntries([...response.headers]);
}
function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
if (globalThisAny.navigator?.userAgent) return globalThisAny.navigator.userAgent.toLowerCase();
if (globalThisAny.process?.versions?.node) return `node.js/${globalThisAny.process.version}`;
if (globalThisAny.EdgeRuntime) return "vercel-edge";
return "";
}
function isAbortError(error) {
return (error instanceof Error || typeof DOMException === "function" && error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || error.name === "TimeoutError");
}
const FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
const RETRYABLE_NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
"ConnectionRefused",
"ConnectionClosed",
"FailedToOpenSocket",
"ECONNRESET",
"ECONNREFUSED",
"ETIMEDOUT",
"EPIPE",
"UND_ERR_SOCKET",
"UND_ERR_HEADERS_TIMEOUT",
"UND_ERR_BODY_TIMEOUT",
"UND_ERR_CONNECT_TIMEOUT"
]);
function findNetworkError(error) {
const visited = /* @__PURE__ */ new Set();
let current = error;
while (current instanceof Error && !visited.has(current)) {
visited.add(current);
const errorWithCode = current;
if (typeof errorWithCode.code === "string" && RETRYABLE_NETWORK_ERROR_CODES.has(errorWithCode.code)) return errorWithCode;
current = current.cause;
}
}
function handleFetchError({ error, url, requestBodyValues }) {
if (isAbortError(error)) return error;
if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {
const cause = error.cause;
if (cause != null) return new APICallError({
message: `Cannot connect to API: ${cause.message}`,
cause,
url,
requestBodyValues,
isRetryable: true
});
}
const networkError = findNetworkError(error);
if (networkError != null) {
if (APICallError.isInstance(error)) return new APICallError({
message: error.message,
cause: error.cause,
url: error.url,
requestBodyValues: error.requestBodyValues,
statusCode: error.statusCode,
responseHeaders: error.responseHeaders,
responseBody: error.responseBody,
data: error.data,
isRetryable: true
});
return new APICallError({
message: `Cannot connect to API: ${error instanceof Error ? error.message : networkError.message}`,
cause: error,
url,
requestBodyValues,
isRetryable: true
});
}
return error;
}
const VERSION$10 = "5.0.81";
/**
* Normalizes different header inputs into a plain record with lower-case keys.
* Entries with `undefined` or `null` values are removed.
*
* @param headers - Input headers (`Headers`, tuples array, plain record) to normalize.
* @returns A record containing the normalized header entries.
*/
function normalizeHeaders(headers) {
if (headers == null) return {};
const normalized = {};
if (headers instanceof Headers) headers.forEach((value, key) => {
normalized[key.toLowerCase()] = value;
});
else {
if (!Array.isArray(headers)) headers = Object.entries(headers);
for (const [key, value] of headers) if (value != null) normalized[key.toLowerCase()] = value;
}
return normalized;
}
/**
* Appends suffix parts to the `user-agent` header.
* If a `user-agent` header already exists, the suffix parts are appended to it.
* If no `user-agent` header exists, a new one is created with the suffix parts.
* Automatically removes undefined entries from the headers.
*
* @param headers - The original headers.
* @param userAgentSuffixParts - The parts to append to the `user-agent` header.
* @returns The new headers with the `user-agent` header set or updated.
*/
function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
const normalizedHeaders = new Headers(normalizeHeaders(headers));
const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
normalizedHeaders.set("user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" "));
return Object.fromEntries(normalizedHeaders.entries());
}
const getOriginalFetch$3 = () => globalThis.fetch;
/**
* Sends a DELETE request. For URLs built from developer-configured endpoints
* only — there is no untrusted-URL validation path (use `getFromApi` with
* `validateUrl` for response-supplied URLs).
*/
const deleteFromApi = async ({ url, headers = {}, failedResponseHandler, successfulResponseHandler, abortSignal, fetch = getOriginalFetch$3() }) => {
try {
const response = await fetch(url, {
method: "DELETE",
headers: withUserAgentSuffix(headers, `ai-sdk-provider-utils/${VERSION$10}`, getRuntimeEnvironmentUserAgent()),
signal: abortSignal
});
const responseHeaders = extractResponseHeaders(response);
if (!response.ok) {
let errorInformation;
try {
errorInformation = await failedResponseHandler({
response,
url,
requestBodyValues: {}
});
} catch (error) {
if (isAbortError(error) || APICallError.isInstance(error)) throw error;
throw new APICallError({
message: "Failed to process error response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: {}
});
}
throw errorInformation.value;
}
try {
return await successfulResponseHandler({
response,
url,
requestBodyValues: {}
});
} catch (error) {
if (error instanceof Error) {
if (isAbortError(error) || APICallError.isInstance(error)) throw error;
}
throw new APICallError({
message: "Failed to process successful response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: {}
});
}
} catch (error) {
throw handleFetchError({
error,
url,
requestBodyValues: {}
});
}
};
const imageMediaTypeSignatures = [
{
mediaType: "image/gif",
bytesPrefix: [
71,
73,
70,
56,
55,
97
]
},
{
mediaType: "image/gif",
bytesPrefix: [
71,
73,
70,
56,
57,
97
]
},
{
mediaType: "image/png",
bytesPrefix: [
137,
80,
78,
71
]
},
{
mediaType: "image/jpeg",
bytesPrefix: [255, 216]
},
{
mediaType: "image/webp",
bytesPrefix: [
82,
73,
70,
70,
null,
null,
null,
null,
87,
69,
66,
80
]
},
{
mediaType: "image/bmp",
bytesPrefix: [
66,
77,
null,
null,
null,
null,
0,
0,
0,
0
]
},
{
mediaType: "image/tiff",
bytesPrefix: [
73,
73,
42,
0
]
},
{
mediaType: "image/tiff",
bytesPrefix: [
77,
77,
0,
42
]
},
{
mediaType: "image/avif",
bytesPrefix: [
0,
0,
0,
null,
102,
116,
121,
112,
97,
118,
105,
102
]
},
{
mediaType: "image/heic",
bytesPrefix: [
0,
0,
0,
null,
102,
116,
121,
112,
104,
101,
105,
99
]
}
];
const documentMediaTypeSignatures = [{
mediaType: "application/pdf",
bytesPrefix: [
37,
80,
68,
70
]
}];
const audioMediaTypeSignaturesWithoutMp4 = [
{
mediaType: "audio/aac",
bytesPrefix: [255, 240]
},
{
mediaType: "audio/aac",
bytesPrefix: [255, 241]
},
{
mediaType: "audio/aac",
bytesPrefix: [255, 248]
},
{
mediaType: "audio/aac",
bytesPrefix: [255, 249]
},
{
mediaType: "audio/mpeg",
bytesPrefix: [255, 251]
},
{
mediaType: "audio/mpeg",
bytesPrefix: [255, 250]
},
{
mediaType: "audio/mpeg",
bytesPrefix: [255, 243]
},
{
mediaType: "audio/mpeg",
bytesPrefix: [255, 242]
},
{
mediaType: "audio/mpeg",
bytesPrefix: [255, 227]
},
{
mediaType: "audio/mpeg",
bytesPrefix: [255, 226]
},
{
mediaType: "audio/wav",
bytesPrefix: [
82,
73,
70,
70,
null,
null,
null,
null,
87,
65,
86,
69
]
},
{
mediaType: "audio/ogg",
bytesPrefix: [
79,
103,
103,
83
]
},
{
mediaType: "audio/flac",
bytesPrefix: [
102,
76,
97,
67
]
},
{
mediaType: "audio/aac",
bytesPrefix: [
64,
21,
0,
0
]
},
{
mediaType: "audio/webm",
bytesPrefix: [
26,
69,
223,
163
]
}
];
const audioMediaTypeSignatures = [...audioMediaTypeSignaturesWithoutMp4, {
mediaType: "audio/mp4",
bytesPrefix: [
0,
0,
0,
null,
102,
116,
121,
112
]
}];
const videoMediaTypeSignatures = [
{
mediaType: "video/mp4",
bytesPrefix: [
0,
0,
0,
null,
102,
116,
121,
112
]
},
{
mediaType: "video/webm",
bytesPrefix: [
26,
69,
223,
163
]
},
{
mediaType: "video/quicktime",
bytesPrefix: [
0,
0,
0,
20,
102,
116,
121,
112,
113,
116
]
},
{
mediaType: "video/x-msvideo",
bytesPrefix: [
82,
73,
70,
70
]
}
];
const DEFAULT_SNIFF_BYTES = 18;
const ID3_SCAN_BYTES = 131084;
function decodePrefix(data, maxBytes) {
if (typeof data !== "string") return data.length > maxBytes ? data.subarray(0, maxBytes) : data;
const maxChars = Math.ceil(maxBytes / 3) * 4;
const bytes = convertBase64ToUint8Array(data.substring(0, Math.min(data.length, maxChars)));
return bytes.length > maxBytes ? bytes.subarray(0, maxBytes) : bytes;
}
function hasID3(bytes) {
return bytes.length > 10 && bytes[0] === 73 && bytes[1] === 68 && bytes[2] === 51;
}
const stripID3 = (bytes) => {
const id3Size = (bytes[6] & 127) << 21 | (bytes[7] & 127) << 14 | (bytes[8] & 127) << 7 | bytes[9] & 127;
return bytes.subarray(id3Size + 10);
};
function detectMediaTypeBySignatures({ data, signatures }) {
let bytes = decodePrefix(data, DEFAULT_SNIFF_BYTES);
if (hasID3(bytes)) bytes = stripID3(decodePrefix(data, ID3_SCAN_BYTES));
for (const signature of signatures) if (bytes.length >= signature.bytesPrefix.length && signature.bytesPrefix.every((byte, index) => byte === null || bytes[index] === byte)) return signature.mediaType;
}
const topLevelSignatureTables = {
image: imageMediaTypeSignatures,
audio: audioMediaTypeSignatures,
video: videoMediaTypeSignatures,
application: documentMediaTypeSignatures
};
/**
* Detect the IANA media type of a file from its raw bytes or base64 string.
*
* - When `topLevelType` is omitted, every known signature is considered
* (image, audio, video, and application). Returns `undefined` when the
* bytes do not match any known signature.
* - When `topLevelType` is provided, only signatures for that top-level
* segment are considered. Returns `undefined` for unsupported segments
* (e.g. `"text"`) or when no signature matches.
*/
function detectMediaType({ data, topLevelType }) {
if (topLevelType === void 0) return detectMediaTypeBySignatures({
data,
signatures: [
...imageMediaTypeSignatures,
...documentMediaTypeSignatures,
...audioMediaTypeSignaturesWithoutMp4,
...videoMediaTypeSignatures
]
});
if (!Object.prototype.hasOwnProperty.call(topLevelSignatureTables, topLevelType)) return;
return detectMediaTypeBySignatures({
data,
signatures: topLevelSignatureTables[topLevelType]
});
}
/**
* Returns the top-level segment of a media type (the portion before `/`).
*
* Examples:
* - `"image/png"` -> `"image"`
* - `"image/*"` -> `"image"`
* - `"image"` -> `"image"`
* - `"image/"` -> `"image"`
* - `""` -> `""`
* - `"/"` -> `""`
*/
function getTopLevelMediaType$2(mediaType) {
const slashIndex = mediaType.indexOf("/");
return slashIndex === -1 ? mediaType : mediaType.substring(0, slashIndex);
}
/**
* Returns `true` only when the given media type has a non-empty, non-wildcard
* subtype (i.e. matches the form `type/subtype`, and `subtype` is not `*`).
*
* Examples:
* - `"image/png"` -> `true`
* - `"image/*"` -> `false`
* - `"image"` -> `false`
* - `"image/"` -> `false`
* - `""` -> `false`
* - `"/"` -> `false`
*/
function isFullMediaType$1(mediaType) {
const slashIndex = mediaType.indexOf("/");
if (slashIndex === -1) return false;
const subtype = mediaType.substring(slashIndex + 1);
return subtype.length > 0 && subtype !== "*";
}
/**
* Cancels a response body to release the underlying connection.
*
* When a fetch Response is rejected without consuming its body (e.g. a failed
* status code, an open-redirect rejection, or a Content-Length that exceeds the
* size limit), the underlying TCP socket is not returned to the connection pool
* and may stay open until the process runs out of file descriptors. Cancelling
* the body avoids this leak.
*
* Errors thrown while cancelling are ignored: the body may already be locked,
* disturbed, or absent, none of which should mask the original rejection.
*/
async function cancelResponseBody(response) {
try {
await response.body?.cancel();
} catch {}
}
const name$1 = "AI_DownloadError";
const marker$1 = `vercel.ai.error.${name$1}`;
const symbol$1 = Symbol.for(marker$1);
var DownloadError = class extends AISDKError {
constructor({ url, statusCode, statusText, cause, message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}` }) {
super({
name: name$1,
message,
cause
});
this[symbol$1] = true;
this.url = url;
this.statusCode = statusCode;
this.statusText = statusText;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker$1);
}
};
/**
* Returns `true` when running in a browser.
*
* Detection keys on the presence of a global `window`, matching the browser
* check used elsewhere in this package (see `getRuntimeEnvironmentUserAgent`)
* so the SDK has a single, consistent definition of "browser". Server runtimes
* (Node.js, Deno, Bun, edge/workers) do not define `window`.
*/
function isBrowserRuntime(globalThisAny = globalThis) {
return globalThisAny.window != null;
}
/**
* Returns true when `url` has the same origin (scheme + host + port) as
* `baseUrl`.
*
* Used to decide whether provider credentials may be attached to a request to a
* URL taken from a provider response (e.g. a polling or media-download URL).
* Credentials must only be sent to the provider's own origin; a response that
* names a foreign host (a CDN, or an attacker-controlled host if the response
* is tampered with) must not receive the API key.
*
* Returns false if either value is not a valid absolute URL (fail-closed).
*/
function isSameOrigin(url, baseUrl) {
try {
return new URL(url).origin === new URL(baseUrl).origin;
} catch {
return false;
}
}
/**
* Request headers stripped before fetching an untrusted URL: host/virtual-host
* routing, proxy/origin spoofing, cloud-metadata, cookies, and hop-by-hop
* transport headers (RFC 7230 §6.1).
*
* `Authorization` and other credential-bearing caller headers (e.g. `x-key`)
* are intentionally not listed because trusted provider requests may need
* them. `fetchUntrustedUrl` separately restricts an untrusted first hop to an
* explicit allowlist of non-credential request metadata. Both it and
* `fetchWithValidatedRedirects` drop all caller headers except the user-agent
* on a cross-origin redirect.
*/
const BLOCKED_REQUEST_HEADERS = [
"connection",
"keep-alive",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"host",
"forwarded",
"proxy-authorization",
"via",
"x-forwarded-for",
"x-forwarded-host",
"x-forwarded-proto",
"x-real-ip",
"metadata",
"metadata-flavor",
"x-aws-ec2-metadata-token",
"x-metadata-token",
"cookie",
"set-cookie"
];
/**
* Returns a fresh `Headers` built from `input` with {@link BLOCKED_REQUEST_HEADERS}
* removed. The input is never mutated.
*/
function sanitizeRequestHeaders(input) {
const headers = new Headers(input);
for (const name of BLOCKED_REQUEST_HEADERS) headers.delete(name);
return headers;
}
/**
* Validates that a URL is safe to download from, blocking private/internal addresses
* to prevent SSRF attacks.
*
* This function performs string/literal-IP checks only. DNS validation must
* be provided by the fetch transport or network egress controls.
*
* @param url - The URL string to validate.
* @throws DownloadError if the URL is unsafe.
*/
function validateDownloadUrl(url) {
let parsed;
try {
parsed = new URL(url);
} catch {
throw new DownloadError({
url,
message: `Invalid URL: ${url}`
});
}
if (parsed.protocol === "data:") return;
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new DownloadError({
url,
message: `URL scheme must be http, https, or data, got ${parsed.protocol}`
});
const hostname = parsed.hostname.toLowerCase().replace(/\.+$/, "");
if (!hostname) throw new DownloadError({
url,
message: `URL must have a hostname`
});
if (hostname === "localhost" || hostname.endsWith(".local") || hostname.endsWith(".localhost") || hostname.endsWith(".internal")) throw new DownloadError({
url,
message: `URL with hostname ${hostname} is not allowed`
});
if (hostname.startsWith("[") && hostname.endsWith("]")) {
if (isPrivateIPv6(hostname.slice(1, -1))) throw new DownloadError({
url,
message: `URL with IPv6 address ${hostname} is not allowed`
});
return;
}
if (isIPv4(hostname)) {
if (isPrivateIPv4(hostname)) throw new DownloadError({
url,
message: `URL with IP address ${hostname} is not allowed`
});
}
}
function isIPv4(hostname) {
const parts = hostname.split(".");
if (parts.length !== 4) return false;
return parts.every((part) => {
const num = Number(part);
return Number.isInteger(num) && num >= 0 && num <= 255 && String(num) === part;
});
}
function isPrivateIPv4(ip) {
const [a, b, c] = ip.split(".").map(Number);
if (a === 0) return true;
if (a === 10) return true;
if (a === 100 && b >= 64 && b <= 127) return true;
if (a === 127) return true;
if (a === 169 && b === 254) return true;
if (a === 172 && b >= 16 && b <= 31) return true;
if (a === 192 && b === 0 && c === 0) return true;
if (a === 192 && b === 0 && c === 2) return true;
if (a === 192 && b === 168) return true;
if (a === 198 && (b === 18 || b === 19)) return true;
if (a === 198 && b === 51 && c === 100) return true;
if (a === 203 && b === 0 && c === 113) return true;
if (a >= 224) return true;
return false;
}
/**
* Expands an IPv6 address string into its 8 16-bit groups, handling `::`
* compression and an optional dotted-decimal IPv4 tail (e.g. `::ffff:127.0.0.1`).
*
* @returns the 8 groups, or null if the input is not a parseable IPv6 address.
*/
function parseIPv6(ip) {
let address = ip.toLowerCase();
const zoneIndex = address.indexOf("%");
if (zoneIndex !== -1) address = address.slice(0, zoneIndex);
const halves = address.split("::");
if (halves.length > 2) return null;
const toGroups = (segment) => {
if (segment === "") return [];
const groups = [];
const parts = segment.split(":");
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (part.includes(".")) {
if (i !== parts.length - 1 || !isIPv4(part)) return null;
const [a, b, c, d] = part.split(".").map(Number);
groups.push(a << 8 | b, c << 8 | d);
continue;
}
if (!/^[0-9a-f]{1,4}$/.test(part)) return null;
groups.push(parseInt(part, 16));
}
return groups;
};
const head = toGroups(halves[0]);
if (head === null) return null;
if (halves.length === 2) {
const tail = toGroups(halves[1]);
if (tail === null) return null;
const fill = 8 - head.length - tail.length;
if (fill < 0) return null;
return [
...head,
...new Array(fill).fill(0),
...tail
];
}
return head.length === 8 ? head : null;
}
function isPrivateIPv6(ip) {
const groups = parseIPv6(ip);
if (groups === null) return true;
const topZero = (count) => groups.slice(0, count).every((group) => group === 0);
if (topZero(7) && (groups[7] === 0 || groups[7] === 1)) return true;
if ((groups[0] & 65024) === 64512) return true;
if ((groups[0] & 65472) === 65152) return true;
if ((groups[0] & 65472) === 65216) return true;
if ((groups[0] & 65280) === 65280) return true;
if (groups[0] === 8193 && groups[1] === 3512) return true;
if (groups[0] === 16383 && (groups[1] & 61440) === 0) return true;
if (topZero(6) || topZero(5) && groups[5] === 65535 || topZero(4) && groups[4] === 65535 && groups[5] === 0 || groups[0] === 100 && groups[1] === 65435 && groups[2] === 0 && groups[3] === 0 && groups[4] === 0 && groups[5] === 0 || groups[0] === 100 && groups[1] === 65435 && groups[2] === 1) return isPrivateIPv4(`${groups[6] >> 8 & 255}.${groups[6] & 255}.${groups[7] >> 8 & 255}.${groups[7] & 255}`);
return false;
}
const MAX_DOWNLOAD_REDIRECTS = 10;
const REDIRECT_STATUS_CODES = /* @__PURE__ */ new Set([
301,
302,
303,
307,
308
]);
/**
* Fetches a URL while enforcing the download guard on every hop.
*
* Redirects are followed manually (`redirect: 'manual'`) so each hop is
* validated with {@link validateDownloadUrl} *before* it is requested. Relying
* on the default `redirect: 'follow'` would issue the request to a redirect
* target (e.g. an internal address) before we ever see its URL, defeating the
* guard.
*
* Manually followed redirects from HTTPS to HTTP are rejected before requesting
* the target.
*
* Request headers are also protected: {@link sanitizeRequestHeaders} strips
* proxy/metadata/cookie/hop-by-hop headers before the first request, and all
* caller headers except `User-Agent` are dropped on a cross-origin redirect.
* Credentials and custom headers are preserved on the first hop for backwards
* compatibility. The caller must ensure that the initial URL may receive them.
* Use `fetchUntrustedUrl` for URLs that require first-hop credential isolation.
* The fetch spec only strips `Authorization` on cross-origin redirects because
* in a browser, CORS preflighting protects custom headers; there is no CORS on
* the server, so provider API keys carried in custom headers (e.g. `x-key`)
* must be dropped here as well.
*
* A `redirect: 'manual'` request yields an unreadable opaque response in the
* browser (and in other spec-compliant fetch implementations), so the redirect
* target cannot be validated here. In a real browser this is safe to follow
* natively because reaching an internal network is not possible (fetch is
* constrained by CORS and cannot reach a server's internal network or
* cloud-metadata). On any other runtime we cannot validate the hop, so we fail
* closed rather than follow it blindly and bypass the guard.
*
* A hop that is same-origin with `trustedOrigin` (the developer-configured
* provider endpoint) skips target validation: that origin is exactly what an
* unvalidated, config-derived request would fetch anyway, and validating it
* would break legitimate self-hosted / localhost deployments whose response
* URLs point back at the configured host. Hops on any other origin are always
* validated.
*
* The returned response is the final (non-redirect) response. The caller is
* responsible for checking `response.ok` and reading the body.
*
* URL validation does not resolve DNS. Use guarded-fetch on Node.js
* for connection-time DNS validation, or enforce network egress restrictions.
*
* @throws DownloadError if a hop is unsafe, the redirect limit is exceeded, or
* a redirect cannot be validated on a non-browser runtime.
*/
async function fetchWithValidatedRedirects({ url, headers, abortSignal, maxRedirects = MAX_DOWNLOAD_REDIRECTS, fetch: customFetch, trustedOrigin }) {
let currentHeaders = headers === void 0 ? void 0 : sanitizeRequestHeaders(headers);
const perHopInit = (redirect) => {
const init = {
signal: abortSignal,
redirect
};
if (currentHeaders !== void 0) init.headers = new Headers(currentHeaders);
return init;
};
let currentUrl = url;
for (let redirectCount = 0; redirectCount <= maxRedirects; redirectCount++) {
if (!(trustedOrigin !== void 0 && isSameOrigin(currentUrl, trustedOrigin))) validateDownloadUrl(currentUrl);
const fetch = customFetch ?? globalThis.fetch;
const response = await fetch(currentUrl, perHopInit("manual"));
if (response.type === "opaqueredirect") {
if (!isBrowserRuntime()) throw new DownloadError({
url,
message: `Redirect from ${currentUrl} could not be validated and was blocked`
});
return await fetch(currentUrl, perHopInit("follow"));
}
const location = response.headers?.get("location");
if (REDIRECT_STATUS_CODES.has(response.status) && location) {
cancelResponseBody(response);
const nextUrl = new URL(location, currentUrl).toString();
if (new URL(currentUrl).protocol === "https:" && new URL(nextUrl).protocol === "http:") throw new DownloadError({
url,
message: "Redirect from HTTPS to HTTP was blocked"
});
if (currentHeaders !== void 0 && !isSameOrigin(nextUrl, currentUrl)) {
const userAgent = currentHeaders.get("user-agent");
currentHeaders = new Headers(userAgent == null ? void 0 : { "user-agent": userAgent });
}
currentUrl = nextUrl;
continue;
}
return response;
}
throw new DownloadError({
url,
message: `Too many redirects (max ${maxRedirects})`
});
}
const SAFE_UNTRUSTED_FIRST_HOP_HEADERS = /* @__PURE__ */ new Set([
"accept",
"accept-language",
"baggage",
"cache-control",
"idempotency-key",
"if-match",
"if-modified-since",
"if-none-match",
"if-range",
"if-unmodified-since",
"pragma",
"range",
"traceparent",
"tracestate",
"user-agent",
"x-correlation-id",
"x-request-id"
]);
/**
* Fetches an untrusted URL with first-hop credential isolation and validated
* redirects. Uses the URL validation, runtime fetch transport, redirect
* limits, and cross-origin header stripping of {@link fetchWithValidatedRedirects}.
* Inject guarded-fetch on Node.js for connect-time DNS validation.
*
* Without a matching `credentialedOrigin` (or `trustedOrigin` when it is
* omitted), only allowlisted request metadata is sent on the first hop.
* Arbitrary caller headers require an explicit matching origin because vendor
* credential names cannot be inferred safely. Proxy, metadata, cookie, and
* hop-by-hop headers are sanitized even for a matching origin.
*
* `trustedOrigin` also exempts same-origin hops from URL validation, allowing
* developer-configured private endpoints. Both origin options must come from
* developer configuration, never from untrusted response data.
*
* This is an opt-in alternative to `fetchWithValidatedRedirects`, whose
* existing first-hop header behavior is preserved for compatibility.
*/
async function fetchUntrustedUrl({ headers, credentialedOrigin, untrustedFirstHopHeaders, ...options }) {
let firstHopHeaders;
if (headers !== void 0) {
firstHopHeaders = sanitizeRequestHeaders(headers);
const origin = credentialedOrigin ?? options.trustedOrigin;
if (origin === void 0 || !isSameOrigin(options.url, origin)) {
const allowedHeaders = /* @__PURE__ */ new Set([...SAFE_UNTRUSTED_FIRST_HOP_HEADERS, ...(untrustedFirstHopHeaders ?? []).map((name) => name.toLowerCase())]);
firstHopHeaders = new Headers([...firstHopHeaders].filter(([name]) => allowedHeaders.has(name)));
}
}
return fetchWithValidatedRedirects({
...options,
headers: firstHopHeaders
});
}
/**
* Default maximum download size: 2 GiB.
*
* `fetch().arrayBuffer()` has ~2x peak memory overhead (undici buffers the
* body internally, then creates the JS ArrayBuffer), so very large downloads
* risk exceeding the default V8 heap limit on 64-bit systems and terminating
* the process with an out-of-memory error.
*
* Setting this limit converts an unrecoverable OOM crash into a catchable
* `DownloadError`.
*/
const DEFAULT_MAX_DOWNLOAD_SIZE = 2147483648;
/**
* Reads a fetch Response body with a size limit to prevent memory exhaustion.
*
* Checks the Content-Length header for early rejection, then reads the body
* incrementally via ReadableStream and aborts with a DownloadError when the
* limit is exceeded.
*
* @param response - The fetch Response to read.
* @param url - The URL being downloaded (used in error messages).
* @param maxBytes - Maximum allowed bytes. Defaults to DEFAULT_MAX_DOWNLOAD_SIZE.
* @param onChunk - Optional. Receives each chunk instead of the chunks being
* collected, so the body is not held in memory, and the returned array is empty.
* The chunk may be a view on a larger buffer, copy what you keep.
* @returns A Uint8Array containing the response body.
* @throws DownloadError if the response exceeds maxBytes.
*/
async function readResponseWithSizeLimit({ response, url, maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE, onChunk }) {
const contentLength = response.headers.get("content-length");
if (contentLength != null) {
const length = parseInt(contentLength, 10);
if (!isNaN(length) && length > maxBytes) {
await cancelResponseBody(response);
throw new DownloadError({
url,
message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes (Content-Length: ${length}).`
});
}
}
const body = response.body;
if (body == null) return /* @__PURE__ */ new Uint8Array(0);
const reader = body.getReader();
const chunks = [];
let totalBytes = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
totalBytes += value.length;
if (totalBytes > maxBytes) throw new DownloadError({
url,
message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.`
});
if (onChunk != null) {
onChunk(value);
continue;
}
chunks.push(value.byteLength < value.buffer.byteLength ? new Uint8Array(value) : value);
}
} finally {
try {
await reader.cancel();
} catch {} finally {
reader.releaseLock();
}
}
const result = new Uint8Array(onChunk != null ? 0 : totalBytes);
let offset = 0;
for (const chunk of chunks) {
result.set(chunk, offset);
offset += chunk.length;
}
return result;
}
/**
* Download a file from a URL and return it as a Blob.
*
* @param url - The URL to download from.
* @param options - Optional settings for the download.
* @param options.maxBytes - Maximum allowed download size in bytes. Defaults to 100 MiB.
* @param options.abortSignal - An optional abort signal to cancel the download.
* @param options.fetch - Fetch transport, e.g. guarded-fetch for DNS validation on Node.js.
* @returns A Promise that resolves to the downloaded Blob.
*
* @throws DownloadError if the download fails or exceeds maxBytes.
*/
async function downloadBlob(url, options) {
try {
const response = await fetchUntrustedUrl({
url,
abortSignal: options?.abortSignal,
fetch: options?.fetch
});
if (!response.ok) {
await cancelResponseBody(response);
throw new DownloadError({
url,
statusCode: response.status,
statusText: response.statusText
});
}
const data = await readResponseWithSizeLimit({
response,
url,
maxBytes: options?.maxBytes ?? 2147483648
});
const contentType = response.headers.get("content-type") ?? void 0;
return new Blob([data], contentType ? { type: contentType } : void 0);
} catch (error) {
if (DownloadError.isInstance(error)) throw error;
throw new DownloadError({
url,
cause: error
});
}
}
/**
* Encodes a raw identifier as one URL path segment, including standalone dot
* segments that URL parsers would otherwise normalize. Pass unencoded values;
* for resource paths with intentional slashes, encode each segment separately.
*/
function encodePathSegment(value) {
const encodedValue = encodeURIComponent(value);
return encodedValue === "." ? "%252E" : encodedValue === ".." ? "%252E%252E" : encodedValue;
}
/**
* Creates an ID generator.
* The total length of the ID is the sum of the prefix, separator, and random part length.
* Not cryptographically secure.
*
* @param alphabet - The alphabet to use for the ID. Default: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.
* @param prefix - The prefix of the ID to generate. Optional.
* @param separator - The separator between the prefix and the random part of the ID. Default: '-'.
* @param size - The size of the random part of the ID to generate. Default: 16.
*/
const createIdGenerator = ({ prefix, size = 16, alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", separator = "-" } = {}) => {
const generator = () => {
const alphabetLength = alphabet.length;
const chars = new Array(size);
for (let i = 0; i < size; i++) chars[i] = alphabet[Math.random() * alphabetLength | 0];
return chars.join("");
};
if (prefix == null) return generator;
if (alphabet.includes(separator)) throw new InvalidArgumentError({
argument: "separator",
message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
});
return () => `${prefix}${separator}${generator()}`;
};
/**
* Generates a 16-character random string to use for IDs.
* Not cryptographically secure.
*/
const generateId = createIdGenerator();
const getOriginalFetch$2 = () => globalThis.fetch;
const getFromApi = async ({ url, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, validateUrl, credentialedOrigin, trustedOrigin }) => {
try {
const requestFetch = fetch ?? getOriginalFetch$2();
const requestHeaders = withUserAgentSuffix(credentialedOrigin !== void 0 && !isSameOrigin(url, credentialedOrigin) ? {} : headers, `ai-sdk-provider-utils/${VERSION$10}`, getRuntimeEnvironmentUserAgent());
const response = validateUrl ? await fetchWithValidatedRedirects({
url,
headers: requestHeaders,
abortSignal,
fetch,
trustedOrigin
}) : await requestFetch(url, {
method: "GET",
headers: requestHeaders,
signal: abortSignal
});
const responseHeaders = extractResponseHeaders(response);
if (!response.ok) {
let errorInformation;
try {
errorInformation = await failedResponseHandler({
response,
url,
requestBodyValues: {}
});
} catch (error) {
if (isAbortError(error) || APICallError.isInstance(error)) throw error;
throw new APICallError({
message: "Failed to process error response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: {}
});
}
throw errorInformation.value;
}
try {
return await successfulResponseHandler({
response,
url,
requestBodyValues: {}
});
} catch (error) {
if (error instanceof Error) {
if (isAbortError(error) || APICallError.isInstance(error)) throw error;
}
throw new APICallError({
message: "Failed to process successful response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: {}
});
}
} catch (error) {
throw handleFetchError({
error,
url,
requestBodyValues: {}
});
}
};
const DEFAULT_SCHEMA_PREFIX = "JSON schema:";
const DEFAULT_SCHEMA_SUFFIX = "You MUST answer with a JSON object that matches the JSON schema above.";
const DEFAULT_GENERIC_SUFFIX = "You MUST answer with JSON.";
function injectJsonInstruction({ prompt, schema, schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX : void 0, schemaSuffix = schema != null ? DEFAULT_SCHEMA_SUFFIX : DEFAULT_GENERIC_SUFFIX }) {
return [
prompt != null && prompt.length > 0 ? prompt : void 0,
prompt != null && prompt.length > 0 ? "" : void 0,
schemaPrefix,
schema != null ? JSON.stringify(schema) : void 0,
schemaSuffix
].filter((line) => line != null).join("\n");
}
function injectJsonInstructionIntoMessages({ messages, schema, schemaPrefix, schemaSuffix }) {
const systemMessage = messages[0]?.role === "system" ? { ...messages[0] } : {
role: "system",
content: ""
};
systemMessage.content = injectJsonInstruction({
prompt: systemMessage.content,
schema,
schemaPrefix,
schemaSuffix
});
return [systemMessage, ...messages[0]?.role === "system" ? messages.slice(1) : messages];
}
function loadApiKey({ apiKey, environmentVariableName, apiKeyParameterName = "apiKey", description }) {
if (typeof apiKey === "string") return apiKey;
if (apiKey != null) throw new LoadAPIKeyError({ message: `${description} API key must be a string.` });
if (typeof process === "undefined") throw new LoadAPIKeyError({ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables are not supported in this environment.` });
apiKey = process.env[environmentVariableName];
if (apiKey == null) throw new LoadAPIKeyError({ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.` });
if (typeof apiKey !== "string") throw new LoadAPIKeyError({ message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.` });
return apiKey;
}
/**
* Reasoning levels in ascending order.
*/
const REASONING_LEVELS = [
"minimal",
"low",
"medium",
"high",
"xhigh",
"max"
];
function isCustomReasoning(reasoning) {
return reasoning !== void 0 && reasoning !== "provider-default";
}
/**
* Maps a top-level reasoning value to a provider-specific effort string.
*
* A `providerOptionsEffort` (the reasoning effort set in provider options) is
* returned unchanged. Otherwise, `undefined` and `'provider-default'` return
* `undefined`, and other reasoning values are mapped with the effort map.
*
* The effort map should only contain the values that the model supports. An
* unsupported value maps to the next lower supported level, or the next higher
* one if there is no lower level. `'none'` is never used as a fallback, so an
* unsupported `'none'` maps to the lowest supported level.
*
* Pushes a compatibility warning if the effort that is sent differs from the
* requested value, or an unsupported warning if the effort map is empty.
*
* @returns The provider options effort, the mapped effort string, or
* `undefined` if no effort should be sent.
*/
function mapReasoningToProviderEffort({ reasoning, effortMap, providerOptionsEffort, warnings }) {
if (providerOptionsEffort != null) return providerOptionsEffort;
if (!isCustomReasoning(reasoning)) return;
const index = REASONING_LEVELS.indexOf(reasoning);
const level = [
reasoning,
...REASONING_LEVELS.slice(0, Math.max(index, 0)).reverse(),
...REASONING_LEVELS.slice(index + 1)
].find((candidate) => effortMap[candidate] != null);
if (level == null) {
warnings.push({
type: "unsupported",
feature: "reasoning",
details: `reasoning "${reasoning}" is not supported by this model.`
});
return;
}
const mapped = effortMap[level];
if (mapped !== reasoning) warnings.push({
type: "compatibility",
feature: "reasoning",
details: `reasoning "${reasoning}" is not directly supported by this model. mapped to effort "${mapped}".`
});
return mapped;
}
const DEFAULT_REASONING_BUDGET_PERCENTAGES = {
minimal: .02,
low: .1,
medium: .3,
high: .6,
xhigh: .9,
max: .95
};
/**
* Maps a top-level reasoning value to an absolute token budget by multiplying
* the model's max output tokens by a percentage for the level. Levels missing
* from `budgetPercentages` use the default percentages. The result is clamped
* between `minReasoningBudget` (default 1024) and `maxReasoningBudget`.
*
* Handle `'none'` before calling this function when the model can disable
* reasoning. Otherwise, `'none'` maps to `minReasoningBudget` with a
* compatibility warning.
*
* @returns The computed token budget.
*/
function mapReasoningToProviderBudget({ reasoning, maxOutputTokens, maxReasoningBudget, minReasoningBudget = 1024, budgetPercentages, warnings }) {
if (reasoning === "none") {
warnings.push({
type: "compatibility",
feature: "reasoning",
details: `reasoning "none" is not supported by this model. mapped to the minimum reasoning budget of ${minReasoningBudget} tokens.`
});
return minReasoningBudget;
}
const percentage = budgetPercentages?.[reasoning] ?? DEFAULT_REASONING_BUDGET_PERCENTAGES[reasoning];
return Math.min(maxReasoningBudget, Math.max(minReasoningBudget, Math.round(maxOutputTokens * percentage)));
}
/**
* Maps a media type to its corresponding file extension.
* It was originally introduced to set a filename for audio file uploads
* in https://github.com/vercel/ai/pull/8159.
*
* @param mediaType The media type to map.
* @returns The corresponding file extension
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types/Common_types
*/
function mediaTypeToExtension(mediaType) {
const [_type, subtype = ""] = mediaType.toLowerCase().split("/");
return {
mpeg: "mp3",
"x-wav": "wav",
opus: "ogg",
mp4: "m4a",
"x-m4a": "m4a"
}[subtype] ?? subtype;
}
/**
* Normalizes complete batch request counts.
*
* Returns `undefined` when any count is missing, is not a non-negative safe
* integer, or when the item counts do not add up to the total.
*/
function normalizeBatchRequestCounts({ total, pending, completed, failed }) {
if (isNonNegativeSafeInteger(total) && isNonNegativeSafeInteger(pending) && isNonNegativeSafeInteger(completed) && isNonNegativeSafeInteger(failed) && pending + completed + failed === total) return {
total,
pending,
completed,
failed
};
}
function isNonNegativeSafeInteger(value) {
return value != null && Number.isSafeInteger(value) && value >= 0;
}
const suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
const suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
function _parse(text) {
const obj = JSON.parse(text);
if (obj === null || typeof obj !== "object") return obj;
if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) return obj;
return filter(obj);
}
function filter(obj) {
let next = [obj];
while (next.length) {
const nodes = next;
next = [];
for (const node of nodes) {
if (Object.prototype.hasOwnProperty.call(node, "__proto__")) throw new SyntaxError("Object contains forbidden prototype property");
if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) throw new SyntaxError("Object contains forbidden prototype property");
for (const key in node) {
const value = node[key];
if (value && typeof value === "object") next.push(value);
}
}
}
return obj;
}
function secureJsonParse(text) {
const { stackTraceLimit } = Error;
try {
Error.stackTraceLimit = 0;
} catch {
return _parse(text);
}
try {
return _parse(text);
} finally {
Error.stackTraceLimit = stackTraceLimit;
}
}
/**
* Recursively adds additionalProperties: false to object schemas that do not
* define a schema for their additional properties. This is necessary because
* some providers (e.g. OpenAI) do not support additionalProperties: true.
*/
function addAdditionalPropertiesToJsonSchema(jsonSchema) {
if (jsonSchema.type === "object" || Array.isArray(jsonSchema.type) && jsonSchema.type.includes("object")) {
const { additionalProperties } = jsonSchema;
jsonSchema.additionalProperties = additionalProperties != null && typeof additionalProperties !== "boolean" ? visit(additionalProperties) : false;
const { properties } = jsonSchema;
if (properties != null) for (const key of Object.keys(properties)) properties[key] = visit(properties[key]);
}
if (jsonSchema.items != null) jsonSchema.items = Array.isArray(jsonSchema.items) ? jsonSchema.items.map(visit) : visit(jsonSchema.items);
if (jsonSchema.anyOf != null) jsonSchema.anyOf = jsonSchema.anyOf.map(visit);
if (jsonSchema.allOf != null) jsonSchema.allOf = jsonSchema.allOf.map(visit);
if (jsonSchema.oneOf != null) jsonSchema.oneOf = jsonSchema.oneOf.map(visit);
const { definitions } = jsonSchema;
if (definitions != null) for (const key of Object.keys(definitions)) definitions[key] = visit(definitions[key]);
return jsonSchema;
}
function visit(def) {
if (typeof def === "boolean") return def;
return addAdditionalPropertiesToJsonSchema(def);
}
const ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
const defaultOptions = {
name: void 0,
$refStrategy: "root",
basePath: ["#"],
effectStrategy: "input",
pipeStrategy: "all",
dateStrategy: "format:date-time",
mapStrategy: "entries",
removeAdditionalStrategy: "passthrough",
allowedAdditionalProperties: true,
rejectedAdditionalProperties: false,
definitionPath: "definitions",
strictUnions: false,
definitions: {},
errorMessages: false,
patternStrategy: "escape",
applyRegexFlags: false,
emailStrategy: "format:email",
base64Strategy: "contentEncoding:base64",
nameStrategy: "ref"
};
const getDefaultOptions = (options) => typeof options === "string" ? {
...defaultOptions,
name: options
} : {
...defaultOptions,
...options
};
function parseAnyDef() {
return {};
}
function parseArrayDef(def, refs) {
const res = { type: "array" };
if (def.type?._def && def.type?._def?.typeName !== "ZodAny") res.items = parseDef(def.type._def, {
...refs,
currentPath: [...refs.currentPath, "items"]
});
if (def.minLength) res.minItems = def.minLength.value;
if (def.maxLength) res.maxItems = def.maxLength.value;
if (def.exactLength) {
res.minItems = def.exactLength.value;
res.maxItems = def.exactLength.value;
}
return res;
}
function parseBigintDef(def) {
const res = {
type: "integer",
format: "int64"
};
if (!def.checks) return res;
for (const check of def.checks) switch (check.kind) {
case "min":
if (check.inclusive) res.minimum = check.value;
else res.exclusiveMinimum = check.value;
break;
case "max":
if (check.inclusive) res.maximum = check.value;
else res.exclusiveMaximum = check.value;
break;
case "multipleOf": res.multipleOf = check.value;
}
return res;
}
function parseBooleanDef() {
return { type: "boolean" };
}
function parseBrandedDef(_def, refs) {
return parseDef(_def.type._def, refs);
}
const parseCatchDef = (def, refs) => {
return parseDef(def.innerType._def, refs);
};
function parseDateDef(def, refs, overrideDateStrategy) {
const strategy = overrideDateStrategy ?? refs.dateStrategy;
if (Array.isArray(strategy)) return { anyOf: strategy.map((item) => parseDateDef(def, refs, item)) };
switch (strategy) {
case "string":
case "format:date-time": return {
type: "string",
format: "date-time"
};
case "format:date": return {
type: "string",
format: "date"
};
case "integer": return integerDateParser(def);
}
}
const integerDateParser = (def) => {
const res = {
type: "integer",
format: "unix-time"
};
for (const check of def.checks) switch (check.kind) {
case "min":
res.minimum = check.value;
break;
case "max": res.maximum = check.value;
}
return res;
};
function parseDefaultDef(_def, refs) {
return {
...parseDef(_def.innerType._def, refs),
default: _def.defaultValue()
};
}
function parseEffectsDef(_def, refs) {
return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
}
function parseEnumDef(def) {
return {
type: "string",
enum: Array.from(def.values)
};
}
const isJsonSchema7AllOfType = (type) => {
if ("type" in type && type.type === "string") return false;
return "allOf" in type;
};
function parseIntersectionDef(def, refs) {
const allOf = [parseDef(def.left._def, {
...refs,
currentPath: [
...refs.currentPath,
"allOf",
"0"
]
}), parseDef(def.right._def, {
...refs,
currentPath: [
...refs.currentPath,
"allOf",
"1"
]
})].filter((x) => !!x);
const mergedAllOf = [];
allOf.forEach((schema) => {
if (isJsonSchema7AllOfType(schema)) mergedAllOf.push(...schema.allOf);
else {
let nestedSchema = schema;
if ("additionalProperties" in schema && schema.additionalProperties === false) {
const { additionalProperties: _additionalProperties, ...rest } = schema;
nestedSchema = rest;
}
mergedAllOf.push(nestedSchema);
}
});
return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
}
function parseLiteralDef(def) {
const parsedType = typeof def.value;
if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") return { type: Array.isArray(def.value) ? "array" : "object" };
return {
type: parsedType === "bigint" ? "integer" : parsedType,
const: def.value
};
}
let emojiRegex = void 0;
/**
* Generated from the regular expressions found here as of 2024-05-22:
* https://github.com/colinhacks/zod/blob/master/src/types.ts.
*
* Expressions with /i flag have been changed accordingly.
*/
const zodPatterns = {
/**
* `c` was changed to `[cC]` to replicate /i flag
*/
cuid: /^[cC][^\s-]{8,}$/,
cuid2: /^[0-9a-z]+$/,
ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
/**
* `a-z` was added to replicate /i flag
*/
email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9-]*\.)+[a-zA-Z]{2,}$/,
/**
* Constructed a valid Unicode RegExp
*
* Lazily instantiate since this type of regex isn't supported
* in all envs (e.g. React Native).
*
* See:
* https://github.com/colinhacks/zod/issues/2433
* Fix in Zod:
* https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
*/
emoji: () => {
if (emojiRegex === void 0) emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
return emojiRegex;
},
/**
* Unused
*/
uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
/**
* Unused
*/
ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
/**
* Unused
*/
ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
nanoid: /^[a-zA-Z0-9_-]{21}$/,
jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
};
function parseStringDef(def, refs) {
const res = { type: "string" };
if (def.checks) for (const check of def.checks) switch (check.kind) {
case "min":
res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
break;
case "max":
res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
break;
case "email":
switch (refs.emailStrategy) {
case "format:email":
addFormat(res, "email", check.message, refs);
break;
case "format:idn-email":
addFormat(res, "idn-email", check.message, refs);
break;
case "pattern:zod": addPattern(res, zodPatterns.email, check.message, refs);
}
break;
case "url":
addFormat(res, "uri", check.message, refs);
break;
case "uuid":
addFormat(res, "uuid", check.message, refs);
break;
case "regex":
addPattern(res, check.regex, check.message, refs);
break;
case "cuid":
addPattern(res, zodPatterns.cuid, check.message, refs);
break;
case "cuid2":
addPattern(res, zodPatterns.cuid2, check.message, refs);
break;
case "startsWith":
addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);
break;
case "endsWith":
addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);
break;
case "datetime":
addFormat(res, "date-time", check.message, refs);
break;
case "date":
addFormat(res, "date", check.message, refs);
break;
case "time":
addFormat(res, "time", check.message, refs);
break;
case "duration":
addFormat(res, "duration", check.message, refs);
break;
case "length":
res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
break;
case "includes":
addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);
break;
case "ip":
if (check.version !== "v6") addFormat(res, "ipv4", check.message, refs);
if (check.version !== "v4") addFormat(res, "ipv6", check.message, refs);
break;
case "base64url":
addPattern(res, zodPatterns.base64url, check.message, refs);
break;
case "jwt":
addPattern(res, zodPatterns.jwt, check.message, refs);
break;
case "cidr":
if (check.version !== "v6") addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
if (check.version !== "v4") addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
break;
case "emoji":
addPattern(res, zodPatterns.emoji(), check.message, refs);
break;
case "ulid":
addPattern(res, zodPatterns.ulid, check.message, refs);
break;
case "base64":
switch (refs.base64Strategy) {
case "format:binary":
addFormat(res, "binary", check.message, refs);
break;
case "contentEncoding:base64":
res.contentEncoding = "base64";
break;
case "pattern:zod": addPattern(res, zodPatterns.base64, check.message, refs);
}
break;
case "nanoid": addPattern(res, zodPatterns.nanoid, check.message, refs);
}
return res;
}
function escapeLiteralCheckValue(literal, refs) {
return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
}
const ALPHA_NUMERIC = /* @__PURE__ */ new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
function escapeNonAlphaNumeric(source) {
let result = "";
for (let i = 0; i < source.length; i++) {
if (!ALPHA_NUMERIC.has(source[i])) result += "\\";
result += source[i];
}
return result;
}
function addFormat(schema, value, message, refs) {
if (schema.format || schema.anyOf?.some((x) => x.format)) {
if (!schema.anyOf) schema.anyOf = [];
if (schema.format) {
schema.anyOf.push({ format: schema.format });
delete schema.format;
}
schema.anyOf.push({
format: value,
...message && refs.errorMessages && { errorMessage: { format: message } }
});
} else schema.format = value;
}
function addPattern(schema, regex, message, refs) {
if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
if (!schema.allOf) schema.allOf = [];
if (schema.pattern) {
schema.allOf.push({ pattern: schema.pattern });
delete schema.pattern;
}
schema.allOf.push({
pattern: stringifyRegExpWithFlags(regex, refs),
...message && refs.errorMessages && { errorMessage: { pattern: message } }
});
} else schema.pattern = stringifyRegExpWithFlags(regex, refs);
}
function stringifyRegExpWithFlags(regex, refs) {
if (!refs.applyRegexFlags || !regex.flags) return regex.source;
const flags = {
i: regex.flags.includes("i"),
m: regex.flags.includes("m"),
s: regex.flags.includes("s")
};
const source = flags.i ? regex.source.toLowerCase() : regex.source;
let pattern = "";
let isEscaped = false;
let inCharGroup = false;
let inCharRange = false;
for (let i = 0; i < source.length; i++) {
if (isEscaped) {
pattern += source[i];
isEscaped = false;
continue;
}
if (flags.i) {
if (inCharGroup) {
if (source[i].match(/[a-z]/)) {
if (inCharRange) {
pattern += source[i];
pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
inCharRange = false;
} else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) {
pattern += source[i];
inCharRange = true;
} else pattern += `${source[i]}${source[i].toUpperCase()}`;
continue;
}
} else if (source[i].match(/[a-z]/)) {
pattern += `[${source[i]}${source[i].toUpperCase()}]`;
continue;
}
}
if (flags.m) {
if (source[i] === "^") {
pattern += `(^|(?<=[\r\n]))`;
continue;
} else if (source[i] === "$") {
pattern += `($|(?=[\r\n]))`;
continue;
}
}
if (flags.s && source[i] === ".") {
pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`;
continue;
}
pattern += source[i];
if (source[i] === "\\") isEscaped = true;
else if (inCharGroup && source[i] === "]") inCharGroup = false;
else if (!inCharGroup && source[i] === "[") inCharGroup = true;
}
try {
new RegExp(pattern);
} catch {
console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
return regex.source;
}
return pattern;
}
function parseRecordDef(def, refs) {
const schema = {
type: "object",
additionalProperties: parseDef(def.valueType._def, {
...refs,
currentPath: [...refs.currentPath, "additionalProperties"]
}) ?? refs.allowedAdditionalProperties
};
if (def.keyType?._def.typeName === "ZodString" && def.keyType._def.checks?.length) {
const { type: _type, ...keyType } = parseStringDef(def.keyType._def, refs);
return {
...schema,
propertyNames: keyType
};
} else if (def.keyType?._def.typeName === "ZodEnum") return {
...schema,
propertyNames: { enum: def.keyType._def.values }
};
else if (def.keyType?._def.typeName === "ZodBranded" && def.keyType._def.type._def.typeName === "ZodString" && def.keyType._def.type._def.checks?.length) {
const { type: _type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
return {
...schema,
propertyNames: keyType
};
}
return schema;
}
function parseMapDef(def, refs) {
if (refs.mapStrategy === "record") return parseRecordDef(def, refs);
return {
type: "array",
maxItems: 125,
items: {
type: "array",
items: [parseDef(def.keyType._def, {
...refs,
currentPath: [
...refs.currentPath,
"items",
"items",
"0"
]
}) || parseAnyDef(), parseDef(def.valueType._def, {
...refs,
currentPath: [
...refs.currentPath,
"items",
"items",
"1"
]
}) || parseAnyDef()],
minItems: 2,
maxItems: 2
}
};
}
function parseNativeEnumDef(def) {
const object = def.values;
const actualValues = Object.keys(def.values).filter((key) => {
return typeof object[object[key]] !== "number";
}).map((key) => object[key]);
const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
return {
type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
enum: actualValues
};
}
function parseNeverDef() {
return { not: parseAnyDef() };
}
function parseNullDef() {
return { type: "null" };
}
const primitiveMappings = {
ZodString: "string",
ZodNumber: "number",
ZodBigInt: "integer",
ZodBoolean: "boolean",
ZodNull: "null"
};
function parseUnionDef(def, refs) {
const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {
const types = options.reduce((types, x) => {
const type = primitiveMappings[x._def.typeName];
return type && !types.includes(type) ? [...types, type] : types;
}, []);
return { type: types.length > 1 ? types : types[0] };
} else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
const types = options.reduce((acc, x) => {
const type = typeof x._def.value;
switch (type) {
case "string":
case "number":
case "boolean": return [...acc, type];
case "bigint": return [...acc, "integer"];
case "object": if (x._def.value === null) return [...acc, "null"];
default: return acc;
}
}, []);
if (types.length === options.length) {
const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
return {
type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
enum: options.reduce((acc, x) => {
return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
}, [])
};
}
} else if (options.every((x) => x._def.typeName === "ZodEnum")) return {
type: "string",
enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x) => !acc.includes(x))], [])
};
return asAnyOf(def, refs);
}
const asAnyOf = (def, refs) => {
const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, {
...refs,
currentPath: [
...refs.currentPath,
"anyOf",
`${i}`
]
})).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
return anyOf.length ? { anyOf } : void 0;
};
function parseNullableDef(def, refs) {
if ([
"ZodString",
"ZodNumber",
"ZodBigInt",
"ZodBoolean",
"ZodNull"
].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) return { type: [primitiveMappings[def.innerType._def.typeName], "null"] };
const base = parseDef(def.innerType._def, {
...refs,
currentPath: [
...refs.currentPath,
"anyOf",
"0"
]
});
return base && { anyOf: [base, { type: "null" }] };
}
function parseNumberDef(def) {
const res = { type: "number" };
if (!def.checks) return res;
for (const check of def.checks) switch (check.kind) {
case "int":
res.type = "integer";
break;
case "min":
if (check.inclusive) res.minimum = check.value;
else res.exclusiveMinimum = check.value;
break;
case "max":
if (check.inclusive) res.maximum = check.value;
else res.exclusiveMaximum = check.value;
break;
case "multipleOf": res.multipleOf = check.value;
}
return res;
}
function parseObjectDef(def, refs) {
const result = {
type: "object",
properties: {}
};
const required = [];
const shape = def.shape();
for (const propName in shape) {
let propDef = shape[propName];
if (propDef === void 0 || propDef._def === void 0) continue;
const propOptional = safeIsOptional(propDef);
const parsedDef = parseDef(propDef._def, {
...refs,
currentPath: [
...refs.currentPath,
"properties",
propName
],
propertyPath: [
...refs.currentPath,
"properties",
propName
]
});
if (parsedDef === void 0) continue;
result.properties[propName] = parsedDef;
if (!propOptional) required.push(propName);
}
if (required.length) result.required = required;
const additionalProperties = decideAdditionalProperties(def, refs);
if (additionalProperties !== void 0) result.additionalProperties = additionalProperties;
return result;
}
function decideAdditionalProperties(def, refs) {
if (def.catchall._def.typeName !== "ZodNever") return parseDef(def.catchall._def, {
...refs,
currentPath: [...refs.currentPath, "additionalProperties"]
});
switch (def.unknownKeys) {
case "passthrough": return refs.allowedAdditionalProperties;
case "strict": return refs.rejectedAdditionalProperties;
case "strip": return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
}
}
function safeIsOptional(schema) {
try {
return schema.isOptional();
} catch {
return true;
}
}
const parseOptionalDef = (def, refs) => {
if (refs.currentPath.toString() === refs.propertyPath?.toString()) return parseDef(def.innerType._def, refs);
const innerSchema = parseDef(def.innerType._def, {
...refs,
currentPath: [
...refs.currentPath,
"anyOf",
"1"
]
});
return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
};
const parsePipelineDef = (def, refs) => {
if (refs.pipeStrategy === "input") return parseDef(def.in._def, refs);
else if (refs.pipeStrategy === "output") return parseDef(def.out._def, refs);
const inputSchema = parseDef(def.in._def, {
...refs,
currentPath: [
...refs.currentPath,
"allOf",
"0"
]
});
return { allOf: [inputSchema, parseDef(def.out._def, {
...refs,
currentPath: [
...refs.currentPath,
"allOf",
inputSchema ? "1" : "0"
]
})].filter((schema) => schema !== void 0) };
};
function parsePromiseDef(def, refs) {
return parseDef(def.type._def, refs);
}
function parseSetDef(def, refs) {
const schema = {
type: "array",
uniqueItems: true,
items: parseDef(def.valueType._def, {
...refs,
currentPath: [...refs.currentPath, "items"]
})
};
if (def.minSize) schema.minItems = def.minSize.value;
if (def.maxSize) schema.maxItems = def.maxSize.value;
return schema;
}
function parseTupleDef(def, refs) {
if (def.rest) return {
type: "array",
minItems: def.items.length,
items: def.items.map((x, i) => parseDef(x._def, {
...refs,
currentPath: [
...refs.currentPath,
"items",
`${i}`
]
})).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),
additionalItems: parseDef(def.rest._def, {
...refs,
currentPath: [...refs.currentPath, "additionalItems"]
})
};
else return {
type: "array",
minItems: def.items.length,
maxItems: def.items.length,
items: def.items.map((x, i) => parseDef(x._def, {
...refs,
currentPath: [
...refs.currentPath,
"items",
`${i}`
]
})).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])
};
}
function parseUndefinedDef() {
return { not: parseAnyDef() };
}
function parseUnknownDef() {
return parseAnyDef();
}
const parseReadonlyDef = (def, refs) => {
return parseDef(def.innerType._def, refs);
};
const selectParser = (def, typeName, refs) => {
switch (typeName) {
case "ZodString": return parseStringDef(def, refs);
case "ZodNumber": return parseNumberDef(def);
case "ZodObject": return parseObjectDef(def, refs);
case "ZodBigInt": return parseBigintDef(def);
case "ZodBoolean": return parseBooleanDef();
case "ZodDate": return parseDateDef(def, refs);
case "ZodUndefined": return parseUndefinedDef();
case "ZodNull": return parseNullDef();
case "ZodArray": return parseArrayDef(def, refs);
case "ZodUnion":
case "ZodDiscriminatedUnion": return parseUnionDef(def, refs);
case "ZodIntersection": return parseIntersectionDef(def, refs);
case "ZodTuple": return parseTupleDef(def, refs);
case "ZodRecord": return parseRecordDef(def, refs);
case "ZodLiteral": return parseLiteralDef(def);
case "ZodEnum": return parseEnumDef(def);
case "ZodNativeEnum": return parseNativeEnumDef(def);
case "ZodNullable": return parseNullableDef(def, refs);
case "ZodOptional": return parseOptionalDef(def, refs);
case "ZodMap": return parseMapDef(def, refs);
case "ZodSet": return parseSetDef(def, refs);
case "ZodLazy": return () => def.getter()._def;
case "ZodPromise": return parsePromiseDef(def, refs);
case "ZodNaN":
case "ZodNever": return parseNeverDef();
case "ZodEffects": return parseEffectsDef(def, refs);
case "ZodAny": return parseAnyDef();
case "ZodUnknown": return parseUnknownDef();
case "ZodDefault": return parseDefaultDef(def, refs);
case "ZodBranded": return parseBrandedDef(def, refs);
case "ZodReadonly": return parseReadonlyDef(def, refs);
case "ZodCatch": return parseCatchDef(def, refs);
case "ZodPipeline": return parsePipelineDef(def, refs);
case "ZodFunction":
case "ZodVoid":
case "ZodSymbol": return;
default:
/* c8 ignore next */
return ((_) => void 0)(typeName);
}
};
const getRelativePath = (pathA, pathB) => {
let i = 0;
for (; i < pathA.length && i < pathB.length; i++) if (pathA[i] !== pathB[i]) break;
return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
};
function parseDef(def, refs, forceResolution = false) {
const seenItem = refs.seen.get(def);
if (refs.override) {
const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
if (overrideResult !== ignoreOverride) return overrideResult;
}
if (seenItem && !forceResolution) {
const seenSchema = get$ref(seenItem, refs);
if (seenSchema !== void 0) return seenSchema;
}
const newItem = {
def,
path: refs.currentPath,
jsonSchema: void 0
};
refs.seen.set(def, newItem);
const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
if (jsonSchema) addMeta(def, refs, jsonSchema);
if (refs.postProcess) {
const postProcessResult = refs.postProcess(jsonSchema, def, refs);
newItem.jsonSchema = jsonSchema;
return postProcessResult;
}
newItem.jsonSchema = jsonSchema;
return jsonSchema;
}
const get$ref = (item, refs) => {
switch (refs.$refStrategy) {
case "root": return { $ref: item.path.join("/") };
case "relative": return { $ref: getRelativePath(refs.currentPath, item.path) };
case "none":
case "seen":
if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
return parseAnyDef();
}
return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
}
};
const addMeta = (def, refs, jsonSchema) => {
if (def.description) jsonSchema.description = def.description;
return jsonSchema;
};
const getRefs = (options) => {
const _options = getDefaultOptions(options);
const currentPath = _options.name !== void 0 ? [
..._options.basePath,
_options.definitionPath,
_options.name
] : _options.basePath;
return {
..._options,
currentPath,
propertyPath: void 0,
seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [def._def, {
def: def._def,
path: [
..._options.basePath,
_options.definitionPath,
name
],
jsonSchema: void 0
}]))
};
};
const zod3ToJsonSchema = (schema, options) => {
const refs = getRefs(options);
let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({
...acc,
[name]: parseDef(schema._def, {
...refs,
currentPath: [
...refs.basePath,
refs.definitionPath,
name
]
}, true) ?? parseAnyDef()
}), {}) : void 0;
const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name;
const main = parseDef(schema._def, name === void 0 ? refs : {
...refs,
currentPath: [
...refs.basePath,
refs.definitionPath,
name
]
}, false) ?? parseAnyDef();
const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
if (title !== void 0) main.title = title;
const combined = name === void 0 ? definitions ? {
...main,
[refs.definitionPath]: definitions
} : main : {
$ref: [
...refs.$refStrategy === "relative" ? [] : refs.basePath,
refs.definitionPath,
name
].join("/"),
[refs.definitionPath]: {
...definitions,
[name]: main
}
};
combined.$schema = "http://json-schema.org/draft-07/schema#";
return combined;
};
/**
* Used to mark schemas so we can support both Zod and custom schemas.
*/
const schemaSymbol = Symbol.for("vercel.ai.schema");
/**
* Creates a schema with deferred creation.
* This is important to reduce the startup time of the library
* and to avoid initializing unused validators.
*
* @param createValidator A function that creates a schema.
* @returns A function that returns a schema.
*/
function lazySchema(createSchema) {
let schema;
return () => {
if (schema == null) schema = createSchema();
return schema;
};
}
/**
* Create a schema using a JSON Schema.
*
* @param jsonSchema The JSON Schema for the schema.
* @param options.validate Optional. A validation function for the schema.
*/
function jsonSchema(jsonSchema, { validate } = {}) {
return {
[schemaSymbol]: true,
_type: void 0,
get jsonSchema() {
if (typeof jsonSchema === "function") jsonSchema = jsonSchema();
return jsonSchema;
},
validate
};
}
function isSchema(value) {
return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
}
function asSchema(schema) {
return schema == null ? jsonSchema({
type: "object",
properties: {},
additionalProperties: false
}) : isSchema(schema) ? schema : "~standard" in schema ? schema["~standard"].vendor === "zod" ? zodSchema(schema) : standardSchema(schema) : schema();
}
function standardSchema(standardSchema) {
return jsonSchema(() => {
if (!hasStandardJsonSchema(standardSchema)) throw new Error(`Standard schema vendor '${standardSchema["~standard"].vendor}' does not support JSON Schema conversion.`);
return addAdditionalPropertiesToJsonSchema(standardSchema["~standard"].jsonSchema.input({ target: "draft-07" }));
}, { validate: async (value) => {
const result = await standardSchema["~standard"].validate(value);
return "value" in result ? {
success: true,
value: result.value
} : {
success: false,
error: new TypeValidationError({
value,
cause: result.issues
})
};
} });
}
function hasStandardJsonSchema(schema) {
return schema["~standard"].jsonSchema != null;
}
function zod3Schema(zodSchema, options) {
const useReferences = options?.useReferences ?? false;
return jsonSchema(() => zod3ToJsonSchema(zodSchema, { $refStrategy: useReferences ? "root" : "none" }), { validate: async (value) => {
const result = await zodSchema.safeParseAsync(value);
return result.success ? {
success: true,
value: result.data
} : {
success: false,
error: result.error
};
} });
}
function zod4Schema(zodSchema, options) {
if (!config().localeError) config(en());
const useReferences = options?.useReferences ?? false;
return jsonSchema(() => addAdditionalPropertiesToJsonSchema(toJSONSchema(zodSchema, {
target: "draft-7",
io: "input",
reused: useReferences ? "ref" : "inline"
})), { validate: async (value) => {
const result = await safeParseAsync(zodSchema, value);
return result.success ? {
success: true,
value: result.data
} : {
success: false,
error: result.error
};
} });
}
function isZod4Schema(zodSchema) {
return "_zod" in zodSchema;
}
function zodSchema(zodSchema, options) {
if (isZod4Schema(zodSchema)) return zod4Schema(zodSchema, options);
else return zod3Schema(zodSchema, options);
}
/**
* Validates the types of an unknown object using a schema and
* return a strongly-typed object.
*
* @template T - The type of the object to validate.
* @param {string} options.value - The object to validate.
* @param {Validator<T>} options.schema - The schema to use for validating the JSON.
* @param {TypeValidationContext} options.context - Optional context about what is being validated.
* @returns {Promise<T>} - The typed object.
*/
async function validateTypes({ value, schema, context }) {
const result = await safeValidateTypes({
value,
schema,
context
});
if (!result.success) throw TypeValidationError.wrap({
value,
cause: result.error,
context
});
return result.value;
}
/**
* Safely validates the types of an unknown object using a schema and
* return a strongly-typed object.
*
* @template T - The type of the object to validate.
* @param {string} options.value - The JSON object to validate.
* @param {Validator<T>} options.schema - The schema to use for validating the JSON.
* @param {TypeValidationContext} options.context - Optional context about what is being validated.
* @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.
*/
async function safeValidateTypes({ value, schema, context }) {
const actualSchema = asSchema(schema);
try {
if (actualSchema.validate == null) return {
success: true,
value,
rawValue: value
};
const result = await actualSchema.validate(value);
if (result.success) return {
success: true,
value: result.value,
rawValue: value
};
return {
success: false,
error: TypeValidationError.wrap({
value,
cause: result.error,
context
}),
rawValue: value
};
} catch (error) {
return {
success: false,
error: TypeValidationError.wrap({
value,
cause: error,
context
}),
rawValue: value
};
}
}
async function parseJSON({ text, schema }) {
try {
const value = secureJsonParse(text);
if (schema == null) return value;
return await validateTypes({
value,
schema
});
} catch (error) {
if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) throw error;
throw new JSONParseError({
text,
cause: error
});
}
}
async function safeParseJSON({ text, schema }) {
try {
const value = secureJsonParse(text);
if (schema == null) return {
success: true,
value,
rawValue: value
};
return await safeValidateTypes({
value,
schema
});
} catch (error) {
return {
success: false,
error: JSONParseError.isInstance(error) ? error : new JSONParseError({
text,
cause: error
}),
rawValue: void 0
};
}
}
/**
* Parses a JSON event stream into a stream of parsed JSON objects.
*/
function parseJsonEventStream({ stream, schema }) {
return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream$1()).pipeThrough(new TransformStream({ async transform({ data }, controller) {
if (data === "[DONE]") return;
controller.enqueue(await safeParseJSON({
text: data,
schema
}));
} }));
}
async function parseProviderOptions({ provider, providerOptions, schema }) {
if (providerOptions?.[provider] == null) return;
const parsedProviderOptions = await safeValidateTypes({
value: providerOptions[provider],
schema
});
if (!parsedProviderOptions.success) throw new InvalidArgumentError({
argument: "providerOptions",
message: `invalid ${provider} provider options`,
cause: parsedProviderOptions.error
});
return parsedProviderOptions.value;
}
const getOriginalFetch$1 = () => globalThis.fetch;
function escapeMultipartHeaderValue(value) {
return value.replace(/[\r\n]/g, "").replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
}
function createMultipartBody(parts, boundary) {
const encoder = new TextEncoder();
let disposed = false;
let activeReader;
const enteredStreams = /* @__PURE__ */ new Set();
async function* emitParts() {
for (const part of parts) {
if (disposed) return;
const disposition = `--${boundary}\r\nContent-Disposition: form-data; name="${escapeMultipartHeaderValue(part.name)}"`;
if (part.type === "field") {
yield encoder.encode(`${disposition}\r\n\r\n${part.value}\r\n`);
continue;
}
const filenameParameter = `; filename="${escapeMultipartHeaderValue(part.filename ?? "blob")}"`;
const mediaType = (part.mediaType ?? "application/octet-stream").replace(/[\r\n]/g, "");
yield encoder.encode(`${disposition}${filenameParameter}\r\nContent-Type: ${mediaType}\r\n\r\n`);
if (part.content instanceof Uint8Array) yield part.content;
else {
const reader = part.content.getReader();
activeReader = reader;
enteredStreams.add(part.content);
let finished = false;
try {
while (true) {
const { done, value } = await reader.read();
if (done || disposed) {
finished = done;
break;
}
yield value;
}
} finally {
activeReader = void 0;
if (!finished) await reader.cancel().catch(() => {});
reader.releaseLock();
}
if (disposed) return;
}
yield encoder.encode("\r\n");
}
yield encoder.encode(`--${boundary}--\r\n`);
}
return {
stream: convertAsyncIteratorToReadableStream(emitParts()),
async dispose(reason) {
if (disposed) return;
disposed = true;
const reader = activeReader;
if (reader != null) await reader.cancel(reason).catch(() => {});
for (const part of parts) if (part.type === "file" && !(part.content instanceof Uint8Array) && !enteredStreams.has(part.content)) await part.content.cancel(reason).catch(() => {});
}
};
}
/**
* POSTs a multipart/form-data body as a request stream, so file parts backed
* by a `ReadableStream` are sent without buffering the full file in memory.
*
* Requires a fetch implementation that supports streaming request bodies
* (`duplex: 'half'`). Callers with fully buffered payloads can keep using
* `postFormDataToApi`.
*/
const postMultipartStreamToApi = async ({ url, headers = {}, parts, failedResponseHandler, successfulResponseHandler, abortSignal, fetch = getOriginalFetch$1() }) => {
const boundary = `ai-sdk-multipart-${generateId()}`;
const requestBodyValues = Object.fromEntries(parts.map((part) => [part.name, part.type === "field" ? part.value : `<file:${part.filename ?? part.name}>`]));
const body = createMultipartBody(parts, boundary);
try {
const response = await fetch(url, {
method: "POST",
headers: withUserAgentSuffix({
...headers,
"Content-Type": `multipart/form-data; boundary=${boundary}`
}, `ai-sdk-provider-utils/${VERSION$10}`, getRuntimeEnvironmentUserAgent()),
body: body.stream,
duplex: "half",
signal: abortSignal
});
const responseHeaders = extractResponseHeaders(response);
if (!response.ok) {
let errorInformation;
try {
errorInformation = await failedResponseHandler({
response,
url,
requestBodyValues
});
} catch (error) {
if (isAbortError(error) || APICallError.isInstance(error)) throw error;
throw new APICallError({
message: "Failed to process error response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues
});
}
throw errorInformation.value;
}
try {
return await successfulResponseHandler({
response,
url,
requestBodyValues
});
} catch (error) {
if (error instanceof Error) {
if (isAbortError(error) || APICallError.isInstance(error)) throw error;
}
throw new APICallError({
message: "Failed to process successful response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues
});
}
} catch (error) {
await body.dispose(error);
throw handleFetchError({
error,
url,
requestBodyValues
});
}
};
const getOriginalFetch$4 = () => globalThis.fetch;
const postJsonToApi = async ({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch }) => await postToApi({
url,
headers: {
"Content-Type": "application/json",
...headers
},
body: {
content: JSON.stringify(body),
values: body
},
failedResponseHandler,
successfulResponseHandler,
abortSignal,
fetch
});
const postFormDataToApi = async ({ url, headers, formData, failedResponseHandler, successfulResponseHandler, abortSignal, fetch }) => await postToApi({
url,
headers,
body: {
content: formData,
values: Object.fromEntries(formData.entries())
},
failedResponseHandler,
successfulResponseHandler,
abortSignal,
fetch
});
const postToApi = async ({ url, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch = getOriginalFetch$4() }) => {
try {
const response = await fetch(url, {
method: "POST",
headers: withUserAgentSuffix(headers, `ai-sdk-provider-utils/${VERSION$10}`, getRuntimeEnvironmentUserAgent()),
body: body.content,
signal: abortSignal
});
const responseHeaders = extractResponseHeaders(response);
if (!response.ok) {
let errorInformation;
try {
errorInformation = await failedResponseHandler({
response,
url,
requestBodyValues: body.values
});
} catch (error) {
if (isAbortError(error) || APICallError.isInstance(error)) throw error;
throw new APICallError({
message: "Failed to process error response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: body.values
});
}
throw errorInformation.value;
}
try {
return await successfulResponseHandler({
response,
url,
requestBodyValues: body.values
});
} catch (error) {
if (error instanceof Error) {
if (isAbortError(error) || APICallError.isInstance(error)) throw error;
}
throw new APICallError({
message: "Failed to process successful response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: body.values
});
}
} catch (error) {
throw handleFetchError({
error,
url,
requestBodyValues: body.values
});
}
};
function tool(tool) {
return tool;
}
const telemetryRedaction = Symbol.for("vercel.ai.telemetry.redact");
/**
* Attach a provider-owned telemetry view without changing the original value.
* The annotation is not serialized or included in enumerable application data.
* Keep the annotated object when forwarding tool arguments or provider metadata.
*/
function withTelemetryRedaction(value, redact) {
return Object.create(Object.getPrototypeOf(value), {
...Object.getOwnPropertyDescriptors(value),
[telemetryRedaction]: {
value: redact,
configurable: true
}
});
}
function createProviderExecutedToolFactory({ id, inputSchema, outputSchema, supportsDeferredResults, redactArgs }) {
return ({ onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({
type: "provider",
isProviderExecuted: true,
id,
args: redactArgs == null ? args : withTelemetryRedaction(args, redactArgs),
inputSchema,
outputSchema,
onInputStart,
onInputDelta,
onInputAvailable,
supportsDeferredResults
});
}
/**
* Resolves a value that could be a raw value, a Promise, a function returning a value,
* or a function returning a Promise.
*/
async function resolve(value) {
if (typeof value === "function") value = value();
return value;
}
/**
* Resolves and transforms a value, preserving synchronous results. This allows
* synchronous credentials to remain usable by workflow serialization while
* asynchronous credentials are awaited by request handlers.
*/
function resolveWith(value, transform) {
const resolved = typeof value === "function" ? value() : value;
if (resolved != null && (typeof resolved === "object" || typeof resolved === "function") && typeof resolved.then === "function") return Promise.resolve(resolved).then(transform);
return transform(resolved);
}
/**
* Resolves a file part's media type to a full `type/subtype` form required by
* providers whose API demands the full IANA media type.
*
* - If `part.mediaType` is already a full media type (e.g. `image/png`), it is
* returned as-is.
* - Otherwise, when inline bytes are available (`part.data.type === 'data'`),
* the subtype is sniffed from the bytes using the signature table that
* corresponds to the top-level segment.
* - When neither applies (e.g. top-level-only with a URL source, or bytes that
* cannot be detected), an `UnsupportedFunctionalityError` is thrown.
*/
function resolveFullMediaType({ part }) {
if (isFullMediaType$1(part.mediaType)) return part.mediaType;
if (part.data.type === "data") {
const detected = detectMediaType({
data: part.data.data,
topLevelType: getTopLevelMediaType$2(part.mediaType)
});
if (detected) return detected;
throw new UnsupportedFunctionalityError({ functionality: `file of media type "${part.mediaType}" must specify subtype since it could not be auto-detected` });
}
throw new UnsupportedFunctionalityError({ functionality: `file of media type "${part.mediaType}" must specify subtype since it is not passed as inline bytes` });
}
/**
* Resolves a provider reference to the provider-specific identifier for the
* given provider. Throws `NoSuchProviderReferenceError` if the provider is not
* found in the reference mapping.
*/
function resolveProviderReference({ reference, provider }) {
const id = reference[provider];
if (id != null) return id;
throw new NoSuchProviderReferenceError({
provider,
reference
});
}
/**
* Streaming extraction of large base64 strings from a JSON response body.
*
* A JSON response that carries an image or a file is mostly one very long
* base64 string. The regular pipeline (collect chunks, concatenate, decode to
* text, `JSON.parse`, decode base64) holds about four copies of that string at
* once. The scanner reads the body chunk by chunk instead: strings at the
* configured paths are decoded to bytes while they stream in, and the text that
* is handed to `JSON.parse` (the "skeleton") holds a short placeholder in their
* place.
*
* - The skeleton is the original body except for the extracted strings, so
* `secureJsonParse` still sees every key (a base64 string cannot contain a
* quote, so it cannot hide one).
* - A string is extracted only if it is canonical standard-alphabet base64
* (length divisible by 4, `=` only as the final padding, zero trailing bits,
* no escape sequences or whitespace). The bytes are then exactly what `atob`
* gives for it. Everything else stays a string. What was decoded before a
* string turned out not to qualify is encoded back, which gives the original
* characters.
*/
/** Strings that decode to fewer bytes stay strings. */
const DEFAULT_BINARY_FIELD_MIN_BYTES = 65536;
const QUOTE = 34;
const BACKSLASH = 92;
const EQUALS = 61;
const COMMA = 44;
const COLON = 58;
const LEFT_BRACE = 123;
const RIGHT_BRACE = 125;
const LEFT_BRACKET = 91;
const RIGHT_BRACKET = 93;
const OUTSIDE = 0;
const KEY = 1;
const SKIP = 2;
const BLOB = 3;
/**
* Compiles paths such as `images[*]` or `content[*].data.data`: plain object
* keys (letters, digits, `_` and `-`) joined by `.`, and `[*]` for every
* element of an array. Keys are compared with the raw bytes of the key in the
* body, so a key written with an escape sequence never matches.
*/
function compileBinaryFieldPaths(paths) {
const root = /* @__PURE__ */ new Map();
for (const path of paths) {
if (!/^(?:[\w-]+|\[\*])(?:\.[\w-]+|\[\*])*$/.test(path)) throw new InvalidArgumentError({
argument: "experimental_binaryFields",
message: `Invalid binary field path "${path}"`
});
let node = root;
for (const segment of path.match(/\[\*]|[\w-]+/g)) {
const edges = segment === "[*]" ? [null] : new TextEncoder().encode(`${segment}"`);
for (const edge of edges) {
let next = node.get(edge);
if (next === void 0) node.set(edge, next = /* @__PURE__ */ new Map());
node = next;
}
}
node.set(true, node);
}
return root;
}
function join(parts, length) {
const bytes = new Uint8Array(length);
let at = 0;
for (const part of parts) {
bytes.set(part, at);
at += part.length;
}
return bytes;
}
function createJsonBinaryFieldScanner(paths, minBytes = DEFAULT_BINARY_FIELD_MIN_BYTES) {
const sextet = (/* @__PURE__ */ new Uint8Array(256)).fill(64);
for (let index = 0; index < 64; index++) sextet["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(index)] = index;
const encoder = new TextEncoder();
const pieces = [];
let piece = /* @__PURE__ */ new Uint8Array(65536);
let pieceLength = 0;
let size = 0;
const binaries = /* @__PURE__ */ new Map();
const frames = [];
let skipped = 0;
let mode = OUTSIDE;
let escaped = false;
let last = 0;
let key;
let segments = [];
let segment = /* @__PURE__ */ new Uint8Array(0);
let at = 0;
let total = 0;
let bits = 0;
let chars = 0;
let padding = 0;
const add = (bytes) => {
for (let offset = 0; offset < bytes.length;) {
const length = Math.min(piece.length - pieceLength, bytes.length - offset);
piece.set(bytes.subarray(offset, offset + length), pieceLength);
pieceLength += length;
offset += length;
size += length;
if (pieceLength === piece.length) {
pieces.push(piece);
piece = /* @__PURE__ */ new Uint8Array(65536);
pieceLength = 0;
}
}
};
const emit = (chunk, start, end) => add(chunk.subarray(start, end));
const reset = () => {
segments = [];
segment = /* @__PURE__ */ new Uint8Array(0);
at = 0;
total = 0;
bits = 0;
chars = 0;
padding = 0;
};
const grow = () => {
if (at > 0) segments.push(segment.subarray(0, at));
segment = new Uint8Array(Math.min(Math.max(total, 4096), 4 << 20));
at = 0;
};
const rest = () => bits << (4 - chars) * 6;
const restore = () => {
for (const part of [...segments, segment.subarray(0, at)]) add(encoder.encode(convertUint8ArrayToBase64(part)));
const group = rest();
add(encoder.encode(convertUint8ArrayToBase64(Uint8Array.of(group >> 16, group >> 8, group)).slice(0, chars) + "=".repeat(padding)));
reset();
};
const closeBlob = () => {
mode = OUTSIDE;
const tail = chars && chars - 1;
if (padding === (4 - chars) % 4 && !(bits & (1 << (4 - chars) * 2) - 1) && total + tail >= minBytes) {
const group = rest();
const bytes = join([...segments, segment.subarray(0, at)], total + tail);
for (let index = 0; index < tail; index++) bytes[total + index] = group >> 16 - 8 * index;
const placeholder = `[binary data: ${bytes.length} bytes; ref ${crypto.getRandomValues(/* @__PURE__ */ new Uint32Array(2)).join("-")}]`;
binaries.set(placeholder, bytes);
add(encoder.encode(placeholder));
reset();
} else restore();
};
const push = (chunk) => {
let from = 0;
const { length } = chunk;
for (let index = 0; index < length; index++) {
let byte = chunk[index];
if (mode === BLOB) {
if (padding === 0) {
let pending = bits;
let count = chars;
for (let value; index < length && (value = sextet[chunk[index]]) < 64; index++) {
pending = pending << 6 | value;
if (++count === 4) {
if (at + 3 > segment.length) grow();
segment[at++] = pending >> 16;
segment[at++] = pending >> 8;
segment[at++] = pending;
total += 3;
pending = 0;
count = 0;
}
}
bits = pending;
chars = count;
}
if (index >= length) break;
byte = chunk[index];
if (byte === QUOTE) {
closeBlob();
from = index;
} else if (byte === EQUALS && chars > 1 && padding < 4 - chars) padding++;
else {
restore();
mode = SKIP;
from = index--;
}
} else if (mode !== OUTSIDE) {
if (mode === KEY) key = key?.get(byte);
if (escaped) escaped = false;
else if (byte === BACKSLASH) escaped = true;
else if (byte === QUOTE) {
if (mode === KEY) frames.at(-1).next = key;
mode = OUTSIDE;
}
} else if (byte === QUOTE) {
const frame = frames.at(-1);
if (skipped > 0) mode = SKIP;
else if (frame?.keys && (last === LEFT_BRACE || last === COMMA)) {
mode = KEY;
key = frame.keys;
} else if ((frame ? frame.next : paths)?.get(true)) {
mode = BLOB;
emit(chunk, from, index + 1);
} else mode = SKIP;
} else if (byte === LEFT_BRACE || byte === LEFT_BRACKET) {
last = byte;
const frame = frames.at(-1);
const node = skipped > 0 ? void 0 : frame ? frame.next : paths;
const items = node?.get(null);
if (byte === LEFT_BRACE && node) frames.push({ keys: node });
else if (byte === LEFT_BRACKET && items) frames.push({
keys: null,
next: items
});
else skipped++;
} else if (byte === RIGHT_BRACE || byte === RIGHT_BRACKET) {
if (skipped > 0) skipped--;
else frames.pop();
} else if (byte === COMMA || byte === COLON) last = byte;
}
if (mode !== BLOB) emit(chunk, from, length);
};
const finish = () => {
if (mode === BLOB) restore();
return {
text: new TextDecoder().decode(join([...pieces, piece.subarray(0, pieceLength)], size)),
binaries
};
};
return {
push,
finish
};
}
/**
* Replaces the placeholders in a parsed value with the bytes they stand for.
* Objects and arrays are copied, the parsed value is not modified. A
* placeholder holds a random number, so a string that equals one is ours.
*/
function replaceBinaryFieldPlaceholders(value, binaries) {
if (typeof value === "string") return binaries.get(value) ?? value;
if (Array.isArray(value)) return value.map((item) => replaceBinaryFieldPlaceholders(item, binaries));
if (value != null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, replaceBinaryFieldPlaceholders(item, binaries)]));
return value;
}
/**
* Makes `JSON.stringify` give the placeholder for each of the arrays, instead
* of `{"0":…,"1":…}` with an entry for every byte: 24 MiB of bytes would
* become a string of more than 300 MB. That is what a validator, or the code
* that reports its issues, does with a value it puts into an error message.
* The property is not enumerable, so the arrays look the same otherwise.
* Returns the function that removes it again.
*/
function maskBinariesInJson(binaries) {
for (const [placeholder, bytes] of binaries) Object.defineProperty(bytes, "toJSON", {
value: () => placeholder,
configurable: true
});
return () => {
for (const bytes of binaries.values()) Reflect.deleteProperty(bytes, "toJSON");
};
}
/**
* Wraps a schema so that it validates the extracted bytes in place of their
* placeholders. The value parsed from the skeleton, and the value of the
* validation error of the response, keep the placeholders: reporting an error
* never prints the bytes.
*
* The errors of the schema itself may hold the bytes: a Standard Schema
* validator wraps the value it was given into an error, and the issues it
* reports may carry the offending input. So that their messages do not grow
* with the image, the arrays stringify as their placeholders, and keep doing
* so as long as an error can refer to them. When the validation succeeds the
* arrays are plain again, for whoever receives them.
*/
function withBinaryFields(schema, binaries) {
if (binaries.size === 0) return schema;
const actualSchema = asSchema(schema);
return jsonSchema({}, { validate: async (value) => {
const replaced = replaceBinaryFieldPlaceholders(value, binaries);
const unmask = maskBinariesInJson(binaries);
const result = actualSchema.validate ? await actualSchema.validate(replaced) : {
success: true,
value: replaced
};
if (result.success) unmask();
return result;
} });
}
const textDecoder$2 = new TextDecoder();
function wrapResponseBodyStream({ stream, url, requestBodyValues, statusCode, responseHeaders }) {
const reader = stream.getReader();
let readerReleased = false;
const releaseReader = () => {
if (!readerReleased) {
reader.releaseLock();
readerReleased = true;
}
};
return new ReadableStream({
async pull(controller) {
try {
const { done, value } = await reader.read();
if (done) {
releaseReader();
controller.close();
} else controller.enqueue(value);
} catch (error) {
releaseReader();
if (isAbortError(error)) {
controller.error(error);
return;
}
controller.error(handleFetchError({
error: new APICallError({
message: "Failed to process successful response",
cause: error,
statusCode,
url,
responseHeaders,
requestBodyValues
}),
url,
requestBodyValues
}));
}
},
async cancel(reason) {
try {
await reader.cancel(reason);
} finally {
releaseReader();
}
}
});
}
async function readResponseBodyAsText({ response, url }) {
return textDecoder$2.decode(await readResponseWithSizeLimit({
response,
url
}));
}
const createJsonErrorResponseHandler = ({ errorSchema, errorToMessage, isRetryable }) => async ({ response, url, requestBodyValues }) => {
const responseBody = await readResponseBodyAsText({
response,
url
});
const responseHeaders = extractResponseHeaders(response);
if (responseBody.trim() === "") return {
responseHeaders,
value: new APICallError({
message: response.statusText,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody,
isRetryable: isRetryable?.(response)
})
};
try {
const parsedError = await parseJSON({
text: responseBody,
schema: errorSchema
});
return {
responseHeaders,
value: new APICallError({
message: errorToMessage(parsedError),
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody,
data: parsedError,
isRetryable: isRetryable?.(response, parsedError)
})
};
} catch {
return {
responseHeaders,
value: new APICallError({
message: response.statusText,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody,
isRetryable: isRetryable?.(response)
})
};
}
};
const createEventSourceResponseHandler = (chunkSchema) => async ({ response, url, requestBodyValues }) => {
const responseHeaders = extractResponseHeaders(response);
if (response.body == null) throw new EmptyResponseBodyError({});
return {
responseHeaders,
value: parseJsonEventStream({
stream: wrapResponseBodyStream({
stream: response.body,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders
}),
schema: chunkSchema
})
};
};
const createJsonResponseHandler = (responseSchema, { experimental_binaryFields } = {}) => {
const binaryFieldPaths = experimental_binaryFields?.length ? compileBinaryFieldPaths(experimental_binaryFields) : void 0;
return async ({ response, url, requestBodyValues }) => {
let responseBody;
let schema = responseSchema;
if (binaryFieldPaths == null) responseBody = await readResponseBodyAsText({
response,
url
});
else {
const scanner = createJsonBinaryFieldScanner(binaryFieldPaths);
await readResponseWithSizeLimit({
response,
url,
onChunk: scanner.push
});
const scanned = scanner.finish();
responseBody = scanned.text;
schema = withBinaryFields(responseSchema, scanned.binaries);
}
const parsedResult = await safeParseJSON({
text: responseBody,
schema
});
const responseHeaders = extractResponseHeaders(response);
if (!parsedResult.success) throw new APICallError({
message: "Invalid JSON response",
cause: parsedResult.error,
statusCode: response.status,
responseHeaders,
responseBody,
url,
requestBodyValues
});
return {
responseHeaders,
value: parsedResult.value,
rawValue: parsedResult.rawValue
};
};
};
const createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => {
const responseHeaders = extractResponseHeaders(response);
if (!response.body) throw new APICallError({
message: "Response body is empty",
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody: void 0
});
try {
const buffer = await response.arrayBuffer();
return {
responseHeaders,
value: new Uint8Array(buffer)
};
} catch (error) {
throw new APICallError({
message: "Failed to read response as array buffer",
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody: void 0,
cause: error
});
}
};
/**
* Passes the response body through as a `ReadableStream<Uint8Array>` without
* buffering it (unlike `createBinaryResponseHandler`). The consumer is
* responsible for draining or cancelling the stream.
*/
const createBinaryStreamResponseHandler = () => async ({ response, url, requestBodyValues }) => {
const responseHeaders = extractResponseHeaders(response);
if (response.body == null) throw new EmptyResponseBodyError({});
return {
responseHeaders,
value: wrapResponseBodyStream({
stream: response.body,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders
})
};
};
const createStatusCodeErrorResponseHandler = () => async ({ response, url, requestBodyValues }) => {
const responseHeaders = extractResponseHeaders(response);
const responseBody = await readResponseBodyAsText({
response,
url
});
return {
responseHeaders,
value: new APICallError({
message: response.statusText,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody
})
};
};
/**
* Checks whether a value can cross a workflow serialization boundary.
*
* The check accepts JSON-like primitives, arrays, and plain objects whose
* nested values are also serializable. It rejects functions, symbols,
* bigints, and non-plain objects such as class instances, dates, and regexes.
*/
function isJSONSerializable(value) {
if (value === null || value === void 0) return true;
const type = typeof value;
if (type === "string" || type === "number" || type === "boolean") return true;
if (type === "function" || type === "symbol" || type === "bigint") return false;
if (Array.isArray(value)) return value.every(isJSONSerializable);
if (Object.getPrototypeOf(value) === Object.prototype) return Object.values(value).every(isJSONSerializable);
return false;
}
const name = "AI_SerializationError";
const marker = `vercel.ai.error.${name}`;
const symbol = Symbol.for(marker);
var SerializationError = class extends AISDKError {
constructor({ message = "Failed to serialize value.", cause } = {}) {
super({
name,
message,
cause
});
this[symbol] = true;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker);
}
};
/**
* Serializes a model instance for workflow step boundaries.
* Returns the `modelId` plus the JSON-serializable config properties.
*
* Non-serializable values are omitted. As a special case, a
* function-valued `headers` property is resolved during serialization
* and included if the returned value is JSON-serializable.
*
* Used as the body of `static [WORKFLOW_SERIALIZE]` in provider models.
*
* @example
* ```ts
* static [WORKFLOW_SERIALIZE](model: MyLanguageModel) {
* return serializeModelOptions({
* modelId: model.modelId,
* config: model.config,
* });
* }
* ```
*/
function serializeModelOptions(options) {
const serializableConfig = {};
for (const [key, value] of Object.entries(options.config)) if (key === "headers") {
const resolvedHeaders = resolveSync(value);
if (isJSONSerializable(resolvedHeaders)) serializableConfig[key] = resolvedHeaders;
} else if (isJSONSerializable(value)) serializableConfig[key] = value;
return {
modelId: options.modelId,
config: serializableConfig
};
}
function resolveSync(value) {
let next = value;
if (typeof value === "function") next = value();
if (next instanceof Promise) throw new SerializationError({ message: "Cannot serialize asynchronous model options." });
return next;
}
function startsWithStructuredValue(value) {
if (typeof value !== "string") return false;
const firstCharacter = value.trimStart()[0];
return firstCharacter === "{" || firstCharacter === "[";
}
/**
* Incrementally tracks whether streamed tool-call arguments contain a complete
* structured JSON value. This is intentionally structural rather than a JSON
* parse: a currently parsable scalar can still be the prefix of a later value.
*/
var StreamingToolCallArgumentState = class {
constructor(initialValue = "") {
this.structure = { kind: "undetermined" };
this.append(initialValue);
}
get hasCompleteStructuredValue() {
return this.structure.kind === "structured" && this.structure.complete === true;
}
append(delta) {
let nextStructure = this.structure;
for (const character of delta) {
if (nextStructure.kind === "undetermined") {
if (/\s/.test(character)) continue;
if (character !== "{" && character !== "[") {
nextStructure = { kind: "other" };
continue;
}
nextStructure = {
kind: "structured",
stack: [character],
inString: false,
escaped: false,
complete: false
};
continue;
}
if (nextStructure.kind !== "structured" || nextStructure.complete) continue;
if (nextStructure.inString) {
if (nextStructure.escaped) nextStructure.escaped = false;
else if (character === "\\") nextStructure.escaped = true;
else if (character === "\"") nextStructure.inString = false;
continue;
}
if (character === "\"") nextStructure.inString = true;
else if (character === "{" || character === "[") nextStructure.stack.push(character);
else if (character === "}" || character === "]") {
const expectedOpening = character === "}" ? "{" : "[";
if (nextStructure.stack.at(-1) !== expectedOpening) {
nextStructure = { kind: "other" };
continue;
}
nextStructure.stack.pop();
if (nextStructure.stack.length === 0) nextStructure.complete = true;
}
}
this.structure = nextStructure;
}
};
/**
* Tracks streaming tool call state across multiple deltas from an
* OpenAI-compatible chat completion stream. Handles argument accumulation,
* emits tool-input-start/delta/end and tool-call events, and finalizes
* unfinished tool calls on flush.
*
* Used by openai, openai-compatible, groq, deepseek, alibaba, mistral, and
* moonshotai providers.
*/
var StreamingToolCallTracker = class {
constructor(controller, options = {}) {
this.toolCalls = [];
this.toolCallsById = /* @__PURE__ */ new Map();
this.toolCallsByIndex = /* @__PURE__ */ new Map();
this.usedToolCallIds = /* @__PURE__ */ new Set();
this.nextGeneratedIdSuffixes = /* @__PURE__ */ new Map();
this.controller = controller;
this._generateId = options.generateId ?? generateId;
this.typeValidation = options.typeValidation ?? "none";
this.extractMetadata = options.extractMetadata;
this.buildToolCallProviderMetadata = options.buildToolCallProviderMetadata;
}
/**
* Process a tool call delta from a streaming response chunk.
* Emits tool-input-start, tool-input-delta, tool-input-end, and tool-call
* events as appropriate.
*/
processDelta(toolCallDelta) {
const wireName = toolCallDelta.function?.name;
const hasBlankName = typeof wireName === "string" && wireName.trim().length === 0;
const wireId = this.getNonBlankString(toolCallDelta.id);
const name = this.getNonBlankString(wireName);
const argumentsDelta = toolCallDelta.function?.arguments;
const { index } = toolCallDelta;
const resolution = this.resolveToolCall({
wireId,
index,
name,
hasExplicitCallStart: name != null && startsWithStructuredValue(argumentsDelta),
hasEmptyArguments: argumentsDelta == null || argumentsDelta.trim().length === 0
});
if (resolution.kind === "ambiguous") return;
let toolCall;
if (resolution.kind === "new") {
if (hasBlankName) return;
toolCall = this.processNewToolCall(toolCallDelta, {
wireId,
index,
name
});
} else {
toolCall = resolution.toolCall;
if (wireId != null) this.associateWireId(toolCall, wireId);
this.processExistingToolCall(toolCall, toolCallDelta);
}
if (index != null) this.associateIndex(toolCall, index);
}
/**
* Finalize any unfinished tool calls. Should be called during the stream's
* flush handler to ensure all tool calls are properly completed.
*/
flush() {
const toolCalls = this.toolCalls.every((toolCall) => toolCall.index != null) ? [...this.toolCalls].sort((a, b) => a.index - b.index || a.sequence - b.sequence) : this.toolCalls;
for (const toolCall of toolCalls) if (!toolCall.hasFinished) this.finishToolCall(toolCall);
}
/**
* Correlation precedence for streamed deltas:
*
* | ID evidence | index/name evidence | start evidence | resolution |
* | --- | --- | --- | --- |
* | known | matching | any | matching call, new call, or ambiguity |
* | known | conflicting | named | new call |
* | unseen | matching | structured start | new call |
* | unseen | matching | named empty arguments | incomplete call, new call, or ambiguity |
* | unseen | matching | continuation | matching call or ambiguity |
* | absent | matching | any | matching call, new call, or ambiguity |
* | absent | absent | named | new call |
* | absent | absent | unnamed | sole unfinished call, new call, or ambiguity |
*/
resolveToolCall({ wireId, index, name, hasExplicitCallStart, hasEmptyArguments }) {
const indexedToolCalls = index != null ? this.toolCallsByIndex.get(index) : void 0;
const matchingIndexedToolCalls = this.filterToolCallsByName(indexedToolCalls, name);
if (wireId != null) {
const toolCallsWithId = this.toolCallsById.get(wireId);
if (toolCallsWithId != null) {
if (index != null) {
const matchingToolCalls = matchingIndexedToolCalls.filter((toolCall) => toolCallsWithId.has(toolCall));
const matchingToolCall = this.resolveMatchingToolCall(matchingToolCalls, hasExplicitCallStart);
if (matchingToolCall.kind !== "new") return matchingToolCall;
if (name != null) return { kind: "new" };
if (indexedToolCalls != null) return { kind: "ambiguous" };
return this.resolveMatchingToolCall([...toolCallsWithId], false);
}
if (name != null) {
const matchingToolCalls = [...toolCallsWithId].filter((toolCall) => toolCall.function.name === name);
return this.resolveMatchingToolCall(matchingToolCalls, hasExplicitCallStart);
}
return this.resolveMatchingToolCall([...toolCallsWithId], false);
}
if (matchingIndexedToolCalls.length > 0) return hasExplicitCallStart ? { kind: "new" } : this.resolveMatchingToolCall(matchingIndexedToolCalls, name != null && hasEmptyArguments);
return { kind: "new" };
}
if (indexedToolCalls != null) return this.resolveMatchingToolCall(matchingIndexedToolCalls, hasExplicitCallStart);
if (name != null) return { kind: "new" };
const unfinishedToolCalls = this.toolCalls.filter((toolCall) => !toolCall.hasFinished);
return this.resolveMatchingToolCall(unfinishedToolCalls, false);
}
filterToolCallsByName(toolCalls, name) {
if (toolCalls == null) return [];
return [...toolCalls].filter((toolCall) => name == null || toolCall.function.name === name);
}
resolveMatchingToolCall(toolCalls, hasExplicitCallStart) {
if (toolCalls.length === 0) return { kind: "new" };
const continuableToolCalls = toolCalls.filter((toolCall) => !toolCall.argumentState.hasCompleteStructuredValue);
if (!hasExplicitCallStart && toolCalls.length === 1) return {
kind: "existing",
toolCall: toolCalls[0]
};
if (continuableToolCalls.length === 1) return {
kind: "existing",
toolCall: continuableToolCalls[0]
};
if (continuableToolCalls.length > 1 || !hasExplicitCallStart) return { kind: "ambiguous" };
return { kind: "new" };
}
processNewToolCall(toolCallDelta, { wireId, index, name }) {
if (this.typeValidation === "required") {
if (toolCallDelta.type !== "function") throw new InvalidResponseDataError({
data: toolCallDelta,
message: `Expected 'function' type.`
});
} else if (this.typeValidation === "if-present") {
if (toolCallDelta.type != null && toolCallDelta.type !== "function") throw new InvalidResponseDataError({
data: toolCallDelta,
message: `Expected 'function' type.`
});
}
if (name == null) throw new InvalidResponseDataError({
data: toolCallDelta,
message: `Expected 'function.name' to be a string.`
});
const id = this.createToolCallId(wireId);
this.controller.enqueue({
type: "tool-input-start",
id,
toolName: name
});
const metadata = this.extractMetadata?.(toolCallDelta);
const initialArguments = toolCallDelta.function?.arguments ?? "";
const toolCall = {
id,
index: index ?? void 0,
sequence: this.toolCalls.length,
type: "function",
function: {
name,
arguments: initialArguments
},
argumentState: new StreamingToolCallArgumentState(initialArguments),
hasFinished: false,
metadata
};
this.toolCalls.push(toolCall);
if (wireId != null) this.associateWireId(toolCall, wireId);
if (toolCall.function.arguments.length > 0) this.controller.enqueue({
type: "tool-input-delta",
id: toolCall.id,
delta: toolCall.function.arguments
});
return toolCall;
}
associateWireId(toolCall, wireId) {
let toolCallsWithId = this.toolCallsById.get(wireId);
if (toolCallsWithId == null) {
toolCallsWithId = /* @__PURE__ */ new Set();
this.toolCallsById.set(wireId, toolCallsWithId);
}
toolCallsWithId.add(toolCall);
}
associateIndex(toolCall, index) {
let toolCallsWithIndex = this.toolCallsByIndex.get(index);
if (toolCallsWithIndex == null) {
toolCallsWithIndex = /* @__PURE__ */ new Set();
this.toolCallsByIndex.set(index, toolCallsWithIndex);
}
toolCallsWithIndex.add(toolCall);
}
createToolCallId(wireId) {
if (wireId != null && !this.usedToolCallIds.has(wireId)) {
this.usedToolCallIds.add(wireId);
return wireId;
}
const generatedId = this.getNonBlankString(this._generateId()) ?? "tool-call";
if (!this.usedToolCallIds.has(generatedId)) {
this.usedToolCallIds.add(generatedId);
return generatedId;
}
const initialSuffix = this.nextGeneratedIdSuffixes.get(generatedId) ?? 1;
const maximumSuffix = initialSuffix + this.usedToolCallIds.size;
for (let suffix = initialSuffix; suffix <= maximumSuffix; suffix++) {
const suffixedId = `${generatedId}-${suffix}`;
if (!this.usedToolCallIds.has(suffixedId)) {
this.usedToolCallIds.add(suffixedId);
this.nextGeneratedIdSuffixes.set(generatedId, suffix + 1);
return suffixedId;
}
}
throw new Error("Failed to create a unique tool call ID.");
}
getNonBlankString(value) {
return value != null && value.trim().length > 0 ? value : void 0;
}
processExistingToolCall(toolCall, toolCallDelta) {
if (toolCall.hasFinished) return;
if (toolCallDelta.function?.arguments != null) {
toolCall.argumentState.append(toolCallDelta.function.arguments);
toolCall.function.arguments += toolCallDelta.function.arguments;
this.controller.enqueue({
type: "tool-input-delta",
id: toolCall.id,
delta: toolCallDelta.function.arguments
});
}
}
finishToolCall(toolCall) {
this.controller.enqueue({
type: "tool-input-end",
id: toolCall.id
});
const providerMetadata = this.buildToolCallProviderMetadata?.(toolCall.metadata);
this.controller.enqueue({
type: "tool-call",
toolCallId: toolCall.id,
toolName: toolCall.function.name,
input: toolCall.function.arguments,
...providerMetadata ? { providerMetadata } : {}
});
toolCall.hasFinished = true;
}
};
function withoutTrailingSlash(url) {
return url?.replace(/\/$/, "");
}
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/alibaba/2.0.80/157a27a4a81ef46a40e6cb379e449e9428d5f4d03b0abf9b80e75e59cdbeda2e/node_modules/@ai-sdk/alibaba/dist/index.js
const alibabaLanguageModelChatOptions = lazySchema(() => zodSchema(z.object({
/**
* Enable thinking/reasoning mode for supported models.
* When enabled, the model generates reasoning content before the response.
*
* @default false
*/
enableThinking: z.boolean().optional(),
/**
* Maximum number of reasoning tokens to generate.
*/
thinkingBudget: z.number().positive().optional(),
/**
* Whether to preserve reasoning from previous assistant messages.
*
* When enabled, historical reasoning is sent separately as
* `reasoning_content` and Alibaba receives `preserve_thinking: true`.
* Defaults to `true` for models that support preserved thinking; set to
* `false` to opt out.
*/
preserveThinking: z.boolean().optional(),
/**
* Whether to enable parallel function calling during tool use.
*
* @default true
*/
parallelToolCalls: z.boolean().optional()
})));
const alibabaFailedResponseHandler = createJsonErrorResponseHandler({
errorSchema: lazySchema(() => zodSchema(z.object({ error: z.object({
message: z.string(),
code: z.string().nullish(),
type: z.string().nullish()
}) }))),
errorToMessage: (data) => data.error.message
});
function prepareTools$5({ tools, toolChoice }) {
tools = tools?.length ? tools : void 0;
const toolWarnings = [];
if (tools == null) return {
tools: void 0,
toolChoice: void 0,
toolWarnings
};
const alibabaTools = [];
for (const tool of tools) if (tool.type === "provider") toolWarnings.push({
type: "unsupported",
feature: `provider-defined tool ${tool.id}`
});
else alibabaTools.push({
type: "function",
function: {
name: tool.name,
description: tool.description,
parameters: tool.inputSchema,
...tool.strict != null ? { strict: tool.strict } : {}
}
});
if (toolChoice == null) return {
tools: alibabaTools,
toolChoice: void 0,
toolWarnings
};
const type = toolChoice.type;
switch (type) {
case "auto":
case "none":
case "required": return {
tools: alibabaTools,
toolChoice: type,
toolWarnings
};
case "tool": return {
tools: alibabaTools,
toolChoice: {
type: "function",
function: { name: toolChoice.toolName }
},
toolWarnings
};
default: throw new UnsupportedFunctionalityError({ functionality: `tool choice type: ${type}` });
}
}
function convertAlibabaUsage(usage) {
if (usage == null) return createNullLanguageModelUsage();
const promptTokens = usage.prompt_tokens ?? 0;
const completionTokens = usage.completion_tokens ?? 0;
const cacheReadTokens = usage.prompt_tokens_details?.cached_tokens ?? 0;
const cacheWriteTokens = usage.prompt_tokens_details?.cache_creation_input_tokens ?? 0;
const reasoningTokens = usage.completion_tokens_details?.reasoning_tokens ?? 0;
return {
inputTokens: {
total: promptTokens,
noCache: promptTokens - cacheReadTokens - cacheWriteTokens,
cacheRead: cacheReadTokens,
cacheWrite: cacheWriteTokens
},
outputTokens: {
total: completionTokens,
text: Math.max(0, completionTokens - reasoningTokens),
reasoning: reasoningTokens
},
raw: usage
};
}
function formatImageUrl({ part }) {
if (part.data.type === "url") return part.data.url.toString();
if (part.data.type === "data") return `data:${resolveFullMediaType({ part })};base64,${convertToBase64(part.data.data)}`;
throw new UnsupportedFunctionalityError({ functionality: `file part data type ${part.data.type}` });
}
function convertToAlibabaChatMessages({ prompt, cacheControlValidator, preserveThinking = false }) {
const messages = [];
let lastUserMessageIndex = -1;
for (let i = prompt.length - 1; i >= 0; i--) if (prompt[i].role === "user") {
lastUserMessageIndex = i;
break;
}
let index = -1;
for (const { role, content, ...message } of prompt) {
index++;
const messageCacheControl = cacheControlValidator?.getCacheControl(message.providerOptions);
switch (role) {
case "system":
if (messageCacheControl) messages.push({
role: "system",
content: [{
type: "text",
text: content,
cache_control: messageCacheControl
}]
});
else messages.push({
role: "system",
content
});
break;
case "user":
messages.push({
role: "user",
content: content.map((part, index) => {
const isLastPart = index === content.length - 1;
const partCacheControl = cacheControlValidator?.getCacheControl(part.providerOptions) ?? (isLastPart ? messageCacheControl : void 0);
switch (part.type) {
case "text": return {
type: "text",
text: part.text,
...partCacheControl ? { cache_control: partCacheControl } : {}
};
case "file": switch (part.data.type) {
case "reference": throw new UnsupportedFunctionalityError({ functionality: "file parts with provider references" });
case "text": throw new UnsupportedFunctionalityError({ functionality: "text file parts" });
case "url":
case "data": if (getTopLevelMediaType$2(part.mediaType) === "image") return {
type: "image_url",
image_url: { url: formatImageUrl({ part }) },
...partCacheControl ? { cache_control: partCacheControl } : {}
};
else throw new UnsupportedFunctionalityError({ functionality: "Only image file parts are supported" });
}
}
})
});
break;
case "assistant": {
let text = "";
let reasoningContent = "";
const toolCalls = [];
for (const part of content) switch (part.type) {
case "text":
text += part.text;
break;
case "tool-call":
toolCalls.push({
id: part.toolCallId,
type: "function",
function: {
name: part.toolName,
arguments: JSON.stringify(part.input)
}
});
break;
case "reasoning": if (preserveThinking || index > lastUserMessageIndex) reasoningContent += part.text;
}
if (text.length === 0 && toolCalls.length === 0 && reasoningContent.length === 0) break;
messages.push({
role: "assistant",
content: text.length === 0 && toolCalls.length === 0 && reasoningContent.length > 0 ? null : messageCacheControl ? [{
type: "text",
text,
cache_control: messageCacheControl
}] : text || null,
...reasoningContent.length > 0 ? { reasoning_content: reasoningContent } : {},
tool_calls: toolCalls.length > 0 ? toolCalls : void 0
});
break;
}
case "tool": {
const toolResponses = content.filter((r) => r.type !== "tool-approval-response");
for (let i = 0; i < toolResponses.length; i++) {
const toolResponse = toolResponses[i];
const output = toolResponse.output;
const isLastPart = i === toolResponses.length - 1;
const partCacheControl = cacheControlValidator?.getCacheControl(toolResponse.providerOptions) ?? (isLastPart ? messageCacheControl : void 0);
let contentValue;
switch (output.type) {
case "text":
case "error-text":
contentValue = output.value;
break;
case "execution-denied":
contentValue = output.reason ?? "Tool call execution denied.";
break;
case "content":
case "json":
case "error-json": contentValue = JSON.stringify(output.value);
}
messages.push({
role: "tool",
tool_call_id: toolResponse.toolCallId,
content: partCacheControl ? [{
type: "text",
text: contentValue,
cache_control: partCacheControl
}] : contentValue
});
}
break;
}
default: throw new Error(`Unsupported role: ${role}`);
}
}
return messages;
}
const MAX_CACHE_BREAKPOINTS = 4;
function getCacheControl(providerMetadata) {
const alibaba = providerMetadata?.alibaba;
return alibaba?.cacheControl ?? alibaba?.cache_control;
}
var CacheControlValidator = class {
constructor() {
this.breakpointCount = 0;
this.warnings = [];
}
getCacheControl(providerMetadata) {
const cacheControlValue = getCacheControl(providerMetadata);
if (!cacheControlValue) return;
this.breakpointCount++;
if (this.breakpointCount > MAX_CACHE_BREAKPOINTS) this.warnings.push({
type: "other",
message: `Max breakpoint limit exceeded. Only the last ${MAX_CACHE_BREAKPOINTS} cache markers will take effect.`
});
return cacheControlValue;
}
getWarnings() {
return this.warnings;
}
};
function mapAlibabaFinishReason(finishReason) {
switch (finishReason) {
case "stop": return "stop";
case "length": return "length";
case "content_filter": return "content-filter";
case "function_call":
case "tool_calls": return "tool-calls";
default: return "other";
}
}
const JSON_SCHEMA_MODEL_PREFIXES = [
"qwen3.7-plus",
"qwen3.7-flash",
"qwen3.7-max",
"qwen3.8-max",
"qwen3.8-flash"
];
function supportsJsonSchemaOutput(modelId) {
return JSON_SCHEMA_MODEL_PREFIXES.some((prefix) => modelId === prefix || modelId.startsWith(`${prefix}-`));
}
/**
* Whether a model id supports Alibaba's preserved-thinking mode
* (`preserve_thinking`), which replays assistant `reasoning_content` from
* previous turns.
*
* Supported models per Alibaba's documentation:
* https://docs.qwencloud.com/developer-guides/text-generation/thinking#preserve-thinking-in-multi-turn
*/
const preservedThinkingModelIds = /* @__PURE__ */ new Set([
"kimi-k2.7-code",
"qwen3.6-max-preview",
"qwen3.6-plus",
"qwen3.6-plus-2026-04-02",
"qwen3.7-flash",
"qwen3.7-flash-2026-07-15",
"qwen3.7-max",
"qwen3.7-max-2026-05-17",
"qwen3.7-max-2026-05-20",
"qwen3.7-max-2026-06-08",
"qwen3.7-max-preview",
"qwen3.7-plus",
"qwen3.7-plus-2026-05-26",
"qwen3.8-flash",
"qwen3.8-max",
"qwen3.8-max-0902"
]);
function supportsPreservedThinking(modelId) {
return preservedThinkingModelIds.has(modelId);
}
/**
* Alibaba language model implementation.
*
* Implements LanguageModelV4 interface for Alibaba Cloud's Qwen models.
* Supports OpenAI-compatible chat completions API with Alibaba-specific features:
* - Reasoning/thinking mode (enable_thinking, reasoning_content)
* - Thinking budget control (thinking_budget)
* - Prompt caching (cached_tokens tracking)
*/
var AlibabaChatLanguageModel = class AlibabaChatLanguageModel {
static [WORKFLOW_SERIALIZE](model) {
return serializeModelOptions({
modelId: model.modelId,
config: model.config
});
}
static [WORKFLOW_DESERIALIZE](options) {
return new AlibabaChatLanguageModel(options.modelId, options.config);
}
constructor(modelId, config) {
this.specificationVersion = "v4";
this.supportedUrls = { "image/*": [/^https?:\/\/.*$/] };
this.modelId = modelId;
this.config = config;
}
get provider() {
return this.config.provider;
}
/**
* Builds request arguments for Alibaba API call.
* Converts AI SDK options to Alibaba API format.
*/
async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, responseFormat, seed, reasoning, providerOptions, tools, toolChoice }) {
const warnings = [];
const cacheControlValidator = new CacheControlValidator();
const alibabaOptions = await parseProviderOptions({
provider: "alibaba",
providerOptions,
schema: alibabaLanguageModelChatOptions
});
if (frequencyPenalty != null) warnings.push({
type: "unsupported",
feature: "frequencyPenalty"
});
const preserveThinking = alibabaOptions?.preserveThinking ?? (supportsPreservedThinking(this.modelId) ? true : void 0);
const useJsonSchema = responseFormat?.type === "json" && responseFormat.schema != null && supportsJsonSchemaOutput(this.modelId);
const useJsonObject = responseFormat?.type === "json" && !useJsonSchema;
if (useJsonObject && responseFormat.schema != null) warnings.push({
type: "compatibility",
feature: "responseFormat JSON schema",
details: `Alibaba does not support JSON Schema output for model ${this.modelId}. JSON Object mode is used instead. The schema was injected into the system message and will only be validated locally.`
});
const resolvedPrompt = useJsonObject ? injectJsonInstructionIntoMessages({
messages: prompt,
schema: responseFormat.schema
}) : prompt;
const baseArgs = {
model: this.modelId,
max_tokens: maxOutputTokens,
temperature,
top_p: topP,
top_k: topK,
presence_penalty: presencePenalty,
stop: stopSequences,
seed,
response_format: responseFormat?.type === "json" ? useJsonSchema ? {
type: "json_schema",
json_schema: {
schema: responseFormat.schema,
name: responseFormat.name ?? "response",
description: responseFormat.description
}
} : { type: "json_object" } : void 0,
...resolveAlibabaThinking({
reasoning,
alibabaOptions,
warnings
}),
...preserveThinking != null ? { preserve_thinking: preserveThinking } : {},
messages: convertToAlibabaChatMessages({
prompt: resolvedPrompt,
cacheControlValidator,
preserveThinking: preserveThinking ?? false
})
};
const { tools: alibabaTools, toolChoice: alibabaToolChoice, toolWarnings } = prepareTools$5({
tools,
toolChoice
});
warnings.push(...cacheControlValidator.getWarnings());
return {
args: {
...baseArgs,
tools: alibabaTools,
tool_choice: alibabaToolChoice,
...alibabaTools != null && alibabaOptions?.parallelToolCalls !== void 0 ? { parallel_tool_calls: alibabaOptions.parallelToolCalls } : {}
},
warnings: [...warnings, ...toolWarnings]
};
}
async doGenerate(options) {
const { args, warnings } = await this.getArgs(options);
const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({
url: `${this.config.baseURL}/chat/completions`,
headers: combineHeaders(await resolve(this.config.headers), options.headers),
body: args,
failedResponseHandler: alibabaFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler(alibabaChatResponseSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const choice = response.choices[0];
const content = [];
const reasoning = choice.message.reasoning_content;
if (reasoning != null && reasoning.length > 0) content.push({
type: "reasoning",
text: reasoning
});
const text = choice.message.content;
if (text != null && text.length > 0) content.push({
type: "text",
text
});
if (choice.message.tool_calls != null) for (const toolCall of choice.message.tool_calls) content.push({
type: "tool-call",
toolCallId: toolCall.id || generateId(),
toolName: toolCall.function.name,
input: toolCall.function.arguments
});
return {
content,
finishReason: {
unified: mapAlibabaFinishReason(choice.finish_reason),
raw: choice.finish_reason ?? void 0
},
usage: convertAlibabaUsage(response.usage),
request: { body: JSON.stringify(args) },
response: {
...createLanguageModelResponseMetadata(response),
headers: responseHeaders,
body: rawResponse
},
warnings
};
}
async doStream(options) {
const { args, warnings } = await this.getArgs(options);
const body = {
...args,
stream: true,
stream_options: this.config.includeUsage ? { include_usage: true } : void 0
};
const { responseHeaders, value: response } = await postJsonToApi({
url: `${this.config.baseURL}/chat/completions`,
headers: combineHeaders(await resolve(this.config.headers), options.headers),
body,
failedResponseHandler: alibabaFailedResponseHandler,
successfulResponseHandler: createEventSourceResponseHandler(alibabaChatChunkSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
let finishReason = {
unified: "interrupted",
raw: void 0
};
let usage = void 0;
let isFirstChunk = true;
let activeText = false;
let activeReasoningId = null;
let toolCallTracker;
return {
stream: response.pipeThrough(new TransformStream({
start(controller) {
toolCallTracker = new StreamingToolCallTracker(controller, { generateId });
controller.enqueue({
type: "stream-start",
warnings
});
},
transform(chunk, controller) {
if (options.includeRawChunks) controller.enqueue({
type: "raw",
rawValue: chunk.rawValue
});
if (!chunk.success) {
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error: chunk.error
});
return;
}
const value = chunk.value;
if (isFirstChunk) {
isFirstChunk = false;
controller.enqueue({
type: "response-metadata",
...createLanguageModelResponseMetadata(value)
});
}
if (value.usage != null) usage = value.usage;
if (value.choices.length === 0) return;
const choice = value.choices[0];
const delta = choice.delta;
if (delta.reasoning_content != null && delta.reasoning_content.length > 0) {
if (activeReasoningId == null) {
if (activeText) {
controller.enqueue({
type: "text-end",
id: "0"
});
activeText = false;
}
activeReasoningId = generateId();
controller.enqueue({
type: "reasoning-start",
id: activeReasoningId
});
}
controller.enqueue({
type: "reasoning-delta",
id: activeReasoningId,
delta: delta.reasoning_content
});
}
if (delta.content != null && delta.content.length > 0) {
if (activeReasoningId != null) {
controller.enqueue({
type: "reasoning-end",
id: activeReasoningId
});
activeReasoningId = null;
}
if (!activeText) {
controller.enqueue({
type: "text-start",
id: "0"
});
activeText = true;
}
controller.enqueue({
type: "text-delta",
id: "0",
delta: delta.content
});
}
if (delta.tool_calls != null && delta.tool_calls.length > 0) {
if (activeReasoningId != null) {
controller.enqueue({
type: "reasoning-end",
id: activeReasoningId
});
activeReasoningId = null;
}
if (activeText) {
controller.enqueue({
type: "text-end",
id: "0"
});
activeText = false;
}
for (const toolCallDelta of delta.tool_calls) toolCallTracker.processDelta(toolCallDelta);
}
if (choice.finish_reason != null) finishReason = {
unified: mapAlibabaFinishReason(choice.finish_reason),
raw: choice.finish_reason
};
},
flush(controller) {
if (activeReasoningId != null) controller.enqueue({
type: "reasoning-end",
id: activeReasoningId
});
if (activeText) controller.enqueue({
type: "text-end",
id: "0"
});
toolCallTracker.flush();
controller.enqueue({
type: "finish",
finishReason,
usage: convertAlibabaUsage(usage)
});
}
})),
request: { body: JSON.stringify(body) },
response: { headers: responseHeaders }
};
}
};
function resolveAlibabaThinking({ reasoning, alibabaOptions, warnings }) {
if (alibabaOptions?.enableThinking != null || alibabaOptions?.thinkingBudget != null) return {
...alibabaOptions.enableThinking != null ? { enable_thinking: alibabaOptions.enableThinking } : {},
...alibabaOptions.thinkingBudget != null ? { thinking_budget: alibabaOptions.thinkingBudget } : {}
};
if (!isCustomReasoning(reasoning)) return {};
if (reasoning === "none") return { enable_thinking: false };
return {
enable_thinking: true,
thinking_budget: mapReasoningToProviderBudget({
reasoning,
maxOutputTokens: 16384,
maxReasoningBudget: 16384,
warnings
})
};
}
/**
* Reference for schemas below:
* https://www.alibabacloud.com/help/en/model-studio/qwen-api-via-openai-chat-completions
*/
const alibabaUsageSchema = () => z.looseObject({
prompt_tokens: z.number(),
completion_tokens: z.number(),
total_tokens: z.number(),
prompt_tokens_details: z.looseObject({
cached_tokens: z.number().nullish(),
cache_creation_input_tokens: z.number().nullish(),
cache_type: z.string().nullish()
}).nullish(),
completion_tokens_details: z.looseObject({ reasoning_tokens: z.number().nullish() }).nullish()
});
const alibabaChatResponseSchema = lazySchema(() => zodSchema(z.object({
id: z.string().nullish(),
created: z.number().nullish(),
model: z.string().nullish(),
choices: z.array(z.object({
message: z.object({
role: z.literal("assistant").nullish(),
content: z.string().nullish(),
reasoning_content: z.string().nullish(),
tool_calls: z.array(z.object({
id: z.string(),
type: z.literal("function"),
function: z.object({
name: z.string(),
arguments: z.string()
})
})).nullish()
}),
finish_reason: z.string().nullish(),
index: z.number()
})),
usage: alibabaUsageSchema().nullish()
})));
const alibabaChatChunkSchema = lazySchema(() => zodSchema(z.object({
id: z.string().nullish(),
created: z.number().nullish(),
model: z.string().nullish(),
choices: z.array(z.object({
delta: z.object({
role: z.enum(["assistant"]).nullish(),
content: z.string().nullish(),
reasoning_content: z.string().nullish(),
tool_calls: z.array(z.object({
index: z.number().nullish(),
id: z.string().nullish(),
type: z.literal("function").nullish(),
function: z.object({
name: z.string().nullish(),
arguments: z.string().nullish()
}).nullish()
})).nullish()
}),
finish_reason: z.string().nullish(),
index: z.number()
})),
usage: alibabaUsageSchema().nullish()
})));
const alibabaEmbeddingModelOptions = lazySchema(() => zodSchema(z.object({
/**
* Differentiates query text from document text for asymmetric retrieval tasks.
* Defaults to `document`.
*/
textType: z.enum(["query", "document"]).optional(),
/**
* The dimension of the output embedding vectors. Defaults to 1024.
*
* `text-embedding-v4` also supports 1536 and 2048 dimensions.
*/
dimension: z.number().optional(),
/**
* The output vector type. Defaults to `dense`.
*
* Sparse-only output is not supported by the AI SDK embedding interface,
* which requires dense number arrays.
*/
outputType: z.enum([
"dense",
"sparse",
"dense&sparse"
]).optional()
})));
const alibabaEmbeddingFailedResponseHandler = createJsonErrorResponseHandler({
errorSchema: z.object({
code: z.string().nullish(),
message: z.string(),
request_id: z.string().nullish()
}),
errorToMessage: (data) => data.message
});
var AlibabaEmbeddingModel = class AlibabaEmbeddingModel {
static [WORKFLOW_SERIALIZE](model) {
return serializeModelOptions({
modelId: model.modelId,
config: model.config
});
}
static [WORKFLOW_DESERIALIZE](options) {
return new AlibabaEmbeddingModel(options.modelId, options.config);
}
constructor(modelId, config) {
this.specificationVersion = "v4";
this.maxEmbeddingsPerCall = 10;
this.supportsParallelCalls = false;
this.modelId = modelId;
this.config = config;
}
get provider() {
return this.config.provider;
}
async doEmbed({ values, dimensions, headers, abortSignal, providerOptions }) {
if (values.length > this.maxEmbeddingsPerCall) throw new TooManyEmbeddingValuesForCallError({
provider: this.provider,
modelId: this.modelId,
maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
values
});
const alibabaOptions = await parseProviderOptions({
provider: "alibaba",
providerOptions,
schema: alibabaEmbeddingModelOptions
});
if (alibabaOptions?.outputType === "sparse") throw new UnsupportedFunctionalityError({
functionality: "Alibaba embedding outputType 'sparse'",
message: "Alibaba embedding outputType 'sparse' is not supported because AI SDK embeddings require dense number arrays. Use 'dense' or 'dense&sparse' instead."
});
const { responseHeaders, value: response, rawValue } = await postJsonToApi({
url: `${this.config.baseURL}/services/embeddings/text-embedding/text-embedding`,
headers: combineHeaders(await resolve(this.config.headers), headers),
body: {
model: this.modelId,
input: { texts: values },
parameters: {
text_type: alibabaOptions?.textType,
dimension: alibabaOptions?.dimension ?? dimensions,
output_type: alibabaOptions?.outputType
}
},
failedResponseHandler: alibabaEmbeddingFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler(alibabaTextEmbeddingResponseSchema),
abortSignal,
fetch: this.config.fetch
});
const sortedEmbeddings = response.output.embeddings.sort((a, b) => a.text_index - b.text_index);
const sparseEmbeddings = sortedEmbeddings.map((item) => item.sparse_embedding == null ? void 0 : {
textIndex: item.text_index,
sparseEmbedding: item.sparse_embedding
}).filter((item) => item != null);
return {
warnings: [],
embeddings: sortedEmbeddings.map((item) => item.embedding),
usage: response.usage ? { tokens: response.usage.total_tokens } : void 0,
providerMetadata: sparseEmbeddings.length > 0 ? { alibaba: { sparseEmbeddings } } : void 0,
response: {
headers: responseHeaders,
body: rawValue
}
};
}
};
const alibabaTextEmbeddingSparseEmbeddingSchema = () => z.object({
index: z.number(),
value: z.number(),
token: z.string().nullish()
});
const alibabaTextEmbeddingResponseSchema = lazySchema(() => zodSchema(z.object({
output: z.object({ embeddings: z.array(z.object({
embedding: z.array(z.number()),
text_index: z.number(),
sparse_embedding: z.array(alibabaTextEmbeddingSparseEmbeddingSchema()).nullish()
})) }),
usage: z.object({ total_tokens: z.number() }).nullish()
})));
const alibabaVideoModelOptionsSchema = lazySchema(() => zodSchema(z.looseObject({
negativePrompt: z.string().nullish(),
audioUrl: z.string().nullish(),
promptExtend: z.boolean().nullish(),
shotType: z.enum(["single", "multi"]).nullish(),
watermark: z.boolean().nullish(),
audio: z.boolean().nullish(),
referenceUrls: z.array(z.string()).nullish(),
media: z.array(z.object({
type: z.enum([
"reference_image",
"reference_video",
"reference_audio",
"first_frame",
"last_frame",
"file",
"link"
]),
url: z.string(),
referenceVoice: z.string().nullish()
})).nullish(),
ratio: z.enum([
"adaptive",
"16:9",
"9:16",
"1:1",
"4:3",
"3:4"
]).nullish(),
pollIntervalMs: z.number().positive().nullish(),
pollTimeoutMs: z.number().positive().nullish()
})));
const alibabaVideoFailedResponseHandler = createJsonErrorResponseHandler({
errorSchema: lazySchema(() => zodSchema(z.object({
code: z.string().nullish(),
message: z.string(),
request_id: z.string().nullish()
}))),
errorToMessage: (data) => data.message
});
const alibabaVideoCreateTaskSchema = lazySchema(() => zodSchema(z.object({
output: z.object({
task_status: z.string(),
task_id: z.string()
}).nullish(),
request_id: z.string().nullish()
})));
const alibabaVideoTaskStatusSchema = lazySchema(() => zodSchema(z.object({
output: z.object({
task_id: z.string(),
task_status: z.string(),
video_url: z.string().nullish(),
submit_time: z.string().nullish(),
scheduled_time: z.string().nullish(),
end_time: z.string().nullish(),
orig_prompt: z.string().nullish(),
actual_prompt: z.string().nullish(),
code: z.string().nullish(),
message: z.string().nullish()
}).nullish(),
usage: z.object({
duration: z.number().nullish(),
output_video_duration: z.number().nullish(),
input_video_duration: z.number().nullish(),
fps: z.number().nullish(),
SR: z.number().nullish(),
size: z.string().nullish(),
ratio: z.string().nullish()
}).nullish(),
request_id: z.string().nullish()
})));
function detectMode(modelId) {
if (modelId.includes("-i2v")) return "i2v";
if (modelId.includes("-r2v")) return "r2v";
return "t2v";
}
function detectProtocol(modelId) {
const version = /^wanx?(\d+)(?:\.(\d+))?(?=[.-]|$)/.exec(modelId);
if (version != null) {
const major = Number(version[1]);
const minor = Number(version[2] ?? 0);
if (major < 2 || major === 2 && minor < 7) return "legacy";
if (major === 2) return "wan27";
}
return "wan3";
}
const resolutionTierMap = {
"1280x720": "720P",
"720x1280": "720P",
"960x960": "720P",
"1088x832": "720P",
"832x1088": "720P",
"1920x1080": "1080P",
"1080x1920": "1080P",
"1440x1440": "1080P",
"1632x1248": "1080P",
"1248x1632": "1080P",
"832x480": "480P",
"480x832": "480P",
"624x624": "480P"
};
const supportedRatios = /* @__PURE__ */ new Set([
"16:9",
"9:16",
"1:1",
"4:3",
"3:4"
]);
function deriveRatioFromResolution(resolution) {
const [width, height] = resolution.split("x").map(Number);
if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) return;
let a = width;
let b = height;
while (b !== 0) [a, b] = [b, a % b];
const ratio = `${width / a}:${height / a}`;
return supportedRatios.has(ratio) ? ratio : void 0;
}
function fileToImageString(file) {
if (file.type === "url") return file.url;
return typeof file.data === "string" ? file.data : convertUint8ArrayToBase64(file.data);
}
function getFirstFrameImage$2(options) {
return options.frameImages?.find((frame) => frame.frameType === "first_frame")?.image;
}
function getLastFrameImage$2(options) {
return options.frameImages?.find((frame) => frame.frameType === "last_frame")?.image;
}
function resolveStartImage$2(options) {
return getFirstFrameImage$2(options) ?? options.image;
}
function isVideoUrl(url) {
return /\.(mp4|mov)([?#]|$)/i.test(url);
}
function resolveMedia(options, alibabaOptions, warnings, frames) {
if (alibabaOptions?.media != null && alibabaOptions.media.length > 0) return alibabaOptions.media.map((item) => ({
type: item.type,
url: item.url,
...item.referenceVoice != null ? { reference_voice: item.referenceVoice } : {}
}));
const media = [];
for (const reference of options.inputReferences ?? []) if (reference.type === "url") media.push({
type: isVideoUrl(reference.url) ? "reference_video" : "reference_image",
url: reference.url
});
else if (reference.mediaType.startsWith("image/")) media.push({
type: "reference_image",
url: convertImageModelFileToDataUri(reference)
});
else warnings.push({
type: "unsupported",
feature: "inputReferences",
details: "Alibaba reference-to-video requires URL references for videos. Non-URL video reference was skipped."
});
if (frames.first != null) media.push({
type: "first_frame",
url: convertImageModelFileToDataUri(frames.first)
});
if (frames.last != null) media.push({
type: "last_frame",
url: convertImageModelFileToDataUri(frames.last)
});
return media.length > 0 ? media : void 0;
}
function resolveReferenceUrls(options, alibabaOptions, warnings) {
if (options.frameImages != null && options.frameImages.length > 0) return;
if (options.inputReferences != null && options.inputReferences.length > 0) {
const urls = [];
for (const reference of options.inputReferences) if (reference.type === "url") urls.push(reference.url);
else warnings.push({
type: "unsupported",
feature: "inputReferences",
details: "Alibaba reference-to-video requires URL references. Non-URL reference was skipped."
});
return urls.length > 0 ? urls : void 0;
}
return alibabaOptions?.referenceUrls ?? void 0;
}
var AlibabaVideoModel = class {
get provider() {
return this.config.provider;
}
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
this.maxVideosPerCall = 1;
}
async buildRequest(options) {
const warnings = [];
const mode = detectMode(this.modelId);
const alibabaOptions = await parseProviderOptions({
provider: "alibaba",
providerOptions: options.providerOptions,
schema: alibabaVideoModelOptionsSchema
});
const input = {};
if (options.prompt != null) input.prompt = options.prompt;
if (alibabaOptions?.negativePrompt != null) input.negative_prompt = alibabaOptions.negativePrompt;
if (alibabaOptions?.audioUrl != null) input.audio_url = alibabaOptions.audioUrl;
const startImage = resolveStartImage$2(options);
const protocol = detectProtocol(this.modelId);
const wan27 = protocol === "wan27";
const wan3 = protocol === "wan3";
const tieredProtocol = wan27 || wan3;
const supportsRatio = wan3 || wan27 && mode !== "i2v";
if (!wan3 && mode === "i2v" && startImage != null) input.img_url = fileToImageString(startImage);
if (wan3) {
const media = resolveMedia(options, alibabaOptions, warnings, {
first: startImage,
last: getLastFrameImage$2(options)
});
if (media != null) input.media = media;
} else if (mode === "r2v") {
if (wan27) {
const media = resolveMedia(options, alibabaOptions, warnings, { first: getFirstFrameImage$2(options) });
if (media != null) input.media = media;
} else {
const referenceUrls = resolveReferenceUrls(options, alibabaOptions, warnings);
if (referenceUrls != null && referenceUrls.length > 0) input.reference_urls = referenceUrls;
}
}
if (getLastFrameImage$2(options) != null && !wan3) warnings.push({
type: "unsupported",
feature: "frameImages",
details: "This model does not support last_frame. The last frame image was ignored."
});
if (options.inputReferences != null && options.inputReferences.length > 0 && mode !== "r2v" && !wan3) warnings.push({
type: "unsupported",
feature: "inputReferences",
details: "Alibaba only supports inputReferences (reference-to-video) on reference-to-video models. The reference images were ignored."
});
const parameters = {};
if (options.duration != null) parameters.duration = options.duration;
if (options.seed != null) parameters.seed = options.seed;
if (options.resolution != null) {
if (mode === "i2v" || tieredProtocol) {
const resolutionTier = resolutionTierMap[options.resolution] || options.resolution;
const supportedTiers = wan3 ? [
"480P",
"720P",
"1080P"
] : ["720P", "1080P"];
if (tieredProtocol && !supportedTiers.includes(resolutionTier)) warnings.push({
type: "unsupported",
feature: "resolution",
details: `${wan3 ? "wan3" : "wan2.7"} models only support the ${supportedTiers.join(", ")} resolution tiers. The resolution "${options.resolution}" was ignored.`
});
else parameters.resolution = resolutionTier;
} else parameters.size = options.resolution.replace("x", "*");
}
if (supportsRatio) {
const ratio = alibabaOptions?.ratio ?? options.aspectRatio ?? (options.resolution != null ? deriveRatioFromResolution(options.resolution) : void 0);
if (ratio != null) parameters.ratio = ratio;
}
if (alibabaOptions?.promptExtend != null) parameters.prompt_extend = alibabaOptions.promptExtend;
if (alibabaOptions?.shotType != null) {
if (tieredProtocol) warnings.push({
type: "unsupported",
feature: "shotType",
details: `${wan3 ? "wan3" : "wan2.7"} models do not support the shotType option. Describe the shot structure in the prompt instead.`
});
else parameters.shot_type = alibabaOptions.shotType;
}
if (alibabaOptions?.watermark != null) parameters.watermark = alibabaOptions.watermark;
const audio = options.generateAudio ?? alibabaOptions?.audio;
if (audio != null) {
if (wan27) warnings.push({
type: "unsupported",
feature: "generateAudio",
details: "wan2.7 models always generate audio. The audio option was ignored."
});
else parameters.audio = audio;
}
if (options.aspectRatio && !supportsRatio) warnings.push({
type: "unsupported",
feature: "aspectRatio",
details: "Alibaba video models use explicit size/resolution dimensions. Use the resolution option or providerOptions.alibaba for size control."
});
if (options.fps) warnings.push({
type: "unsupported",
feature: "fps",
details: "Alibaba video models do not support custom FPS."
});
if (options.n != null && options.n > 1) warnings.push({
type: "unsupported",
feature: "n",
details: "Alibaba video models only support generating 1 video per call."
});
return {
input,
parameters,
warnings,
alibabaOptions
};
}
buildCompletedResult(statusResponse, responseHeaders, warnings, currentDate) {
const taskId = statusResponse.output?.task_id;
const videoUrl = statusResponse.output?.video_url;
if (!videoUrl) throw new AISDKError({
name: "ALIBABA_VIDEO_GENERATION_ERROR",
message: `No video URL in response. Task ID: ${taskId}`
});
return {
status: "completed",
videos: [{
type: "url",
url: videoUrl,
mediaType: "video/mp4"
}],
warnings,
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders
},
providerMetadata: { alibaba: {
taskId,
videoUrl,
...statusResponse.output?.actual_prompt ? { actualPrompt: statusResponse.output.actual_prompt } : {},
...statusResponse.usage ? { usage: {
duration: statusResponse.usage.duration,
outputVideoDuration: statusResponse.usage.output_video_duration,
resolution: statusResponse.usage.SR,
size: statusResponse.usage.size,
...statusResponse.usage.input_video_duration != null ? { inputVideoDuration: statusResponse.usage.input_video_duration } : {},
...statusResponse.usage.fps != null ? { fps: statusResponse.usage.fps } : {},
...statusResponse.usage.ratio != null ? { ratio: statusResponse.usage.ratio } : {}
} } : {}
} }
};
}
async doStart(options) {
const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
const { input, parameters, warnings } = await this.buildRequest(options);
const { value: createResponse, responseHeaders } = await postJsonToApi({
url: `${this.config.baseURL}/api/v1/services/aigc/video-generation/video-synthesis`,
headers: combineHeaders(await resolve(this.config.headers), options.headers, { "X-DashScope-Async": "enable" }),
body: {
model: this.modelId,
input,
parameters
},
successfulResponseHandler: createJsonResponseHandler(alibabaVideoCreateTaskSchema),
failedResponseHandler: alibabaVideoFailedResponseHandler,
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const taskId = createResponse.output?.task_id;
if (!taskId) throw new AISDKError({
name: "ALIBABA_VIDEO_GENERATION_ERROR",
message: `No task_id returned from Alibaba API. Response: ${JSON.stringify(createResponse)}`
});
return {
operation: { taskId },
warnings,
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders
}
};
}
async doStatus(options) {
const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
const { taskId } = options.operation;
const { value: statusResponse, responseHeaders } = await getFromApi({
url: `${this.config.baseURL}/api/v1/tasks/${encodePathSegment(taskId)}`,
validateUrl: false,
headers: combineHeaders(await resolve(this.config.headers), options.headers),
successfulResponseHandler: createJsonResponseHandler(alibabaVideoTaskStatusSchema),
failedResponseHandler: alibabaVideoFailedResponseHandler,
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const taskStatus = statusResponse.output?.task_status;
if (taskStatus === "SUCCEEDED") return this.buildCompletedResult(statusResponse, responseHeaders, [], currentDate);
if (taskStatus === "FAILED" || taskStatus === "CANCELED") return {
status: "error",
error: `Video generation ${taskStatus.toLowerCase()}. Task ID: ${taskId}. ${statusResponse.output?.message ?? ""}`.trim(),
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders
}
};
return {
status: "pending",
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders
}
};
}
};
const VERSION$9 = "2.0.80";
/**
* Create an Alibaba Cloud (Qwen) provider instance.
*/
function createAlibaba(options = {}) {
const baseURL = withoutTrailingSlash(options.baseURL) ?? "https://dashscope-intl.aliyuncs.com/compatible-mode/v1";
const videoBaseURL = withoutTrailingSlash(options.videoBaseURL) ?? "https://dashscope-intl.aliyuncs.com";
const embeddingBaseURL = withoutTrailingSlash(options.embeddingBaseURL) ?? "https://dashscope-intl.aliyuncs.com/api/v1";
const getHeaders = () => resolveWith(options.apiKey, (apiKey) => withUserAgentSuffix({
Authorization: `Bearer ${loadApiKey({
apiKey,
environmentVariableName: "ALIBABA_API_KEY",
description: "Alibaba Cloud (DashScope)"
})}`,
...options.headers
}, `ai-sdk-alibaba/${VERSION$9}`));
const createLanguageModel = (modelId) => new AlibabaChatLanguageModel(modelId, {
provider: "alibaba.chat",
baseURL,
headers: getHeaders,
fetch: options.fetch,
includeUsage: options.includeUsage ?? true
});
const createEmbeddingModel = (modelId) => new AlibabaEmbeddingModel(modelId, {
provider: "alibaba.embedding",
baseURL: embeddingBaseURL,
headers: getHeaders,
fetch: options.fetch
});
const createVideoModel = (modelId) => new AlibabaVideoModel(modelId, {
provider: "alibaba.video",
baseURL: videoBaseURL,
headers: getHeaders,
fetch: options.fetch
});
const provider = function(modelId) {
if (new.target) throw new Error("The Alibaba model function cannot be called with the new keyword.");
return createLanguageModel(modelId);
};
provider.specificationVersion = "v4";
provider.languageModel = createLanguageModel;
provider.chatModel = createLanguageModel;
provider.embedding = createEmbeddingModel;
provider.embeddingModel = createEmbeddingModel;
provider.video = createVideoModel;
provider.videoModel = createVideoModel;
provider.imageModel = (modelId) => {
throw new NoSuchModelError({
modelId,
modelType: "imageModel"
});
};
return provider;
}
createAlibaba();
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/openai-compatible/3.0.82/289166821eb0ef6abaef37d462322e62e80fb0ef3032014cdf6e51924280a758/node_modules/@ai-sdk/openai-compatible/dist/index.js
function toCamelCase(str) {
return str.replace(/[_-]([a-z])/g, (g) => g[1].toUpperCase());
}
/**
Resolves which key to use for providerMetadata based on what the caller
passed in providerOptions. Returns the camelCase variant when the caller
supplied it, otherwise falls back to the raw name.
*/
function resolveProviderOptionsKey(rawName, providerOptions) {
const camelName = toCamelCase(rawName);
if (camelName !== rawName && providerOptions?.[camelName] != null) return camelName;
return rawName;
}
/**
Pushes a deprecation warning when the user supplies providerOptions under a non-camelCase key
*/
function warnIfDeprecatedProviderOptionsKey({ rawName, providerOptions, warnings }) {
const camelName = toCamelCase(rawName);
if (camelName !== rawName && providerOptions?.[rawName] != null) warnings.push({
type: "deprecated",
setting: `providerOptions key '${rawName}'`,
message: `Use '${camelName}' instead.`
});
}
const defaultOpenAICompatibleErrorStructure = {
errorSchema: z.object({ error: z.object({
message: z.string(),
type: z.string().nullish(),
param: z.any().nullish(),
code: z.union([z.string(), z.number()]).nullish()
}) }),
errorToMessage: (data) => data.error.message
};
function convertOpenAICompatibleChatUsage(usage) {
if (usage == null) return createNullLanguageModelUsage();
const promptTokens = usage.prompt_tokens ?? 0;
const completionTokens = usage.completion_tokens ?? 0;
const cacheReadTokens = usage.prompt_tokens_details?.cached_tokens ?? 0;
const reasoningTokens = usage.completion_tokens_details?.reasoning_tokens ?? 0;
return {
inputTokens: {
total: promptTokens,
noCache: promptTokens - cacheReadTokens,
cacheRead: cacheReadTokens,
cacheWrite: void 0
},
outputTokens: {
total: completionTokens,
text: Math.max(0, completionTokens - reasoningTokens),
reasoning: reasoningTokens
},
raw: usage
};
}
function getOpenAIMetadata(message) {
return message?.providerOptions?.openaiCompatible ?? {};
}
function getAudioFormat(mediaType) {
switch (mediaType) {
case "audio/wav": return "wav";
case "audio/mp3":
case "audio/mpeg": return "mp3";
default: return null;
}
}
function convertToOpenAICompatibleContentPart(part, provider) {
const partMetadata = getOpenAIMetadata(part);
switch (part.type) {
case "text": return {
type: "text",
text: part.text,
...partMetadata
};
case "file": switch (part.data.type) {
case "reference": return {
type: "file",
file: { file_id: resolveProviderReference({
reference: part.data.reference,
provider
}) },
...partMetadata
};
case "text": throw new UnsupportedFunctionalityError({ functionality: "text file parts" });
case "url":
case "data": {
const topLevel = getTopLevelMediaType$2(part.mediaType);
if (topLevel === "image") return {
type: "image_url",
image_url: { url: part.data.type === "url" ? part.data.url.toString() : `data:${resolveFullMediaType({ part })};base64,${convertToBase64(part.data.data)}` },
...partMetadata
};
if (topLevel === "video") return {
type: "video_url",
video_url: { url: part.data.type === "url" ? part.data.url.toString() : `data:${resolveFullMediaType({ part })};base64,${convertToBase64(part.data.data)}` },
...partMetadata
};
if (topLevel === "audio") {
if (part.data.type === "url") throw new UnsupportedFunctionalityError({ functionality: "audio file parts with URLs" });
const fullMediaType = resolveFullMediaType({ part });
const format = getAudioFormat(fullMediaType);
if (format === null) throw new UnsupportedFunctionalityError({ functionality: `audio media type ${fullMediaType}` });
return {
type: "input_audio",
input_audio: {
data: convertToBase64(part.data.data),
format
},
...partMetadata
};
}
if (topLevel === "application") {
if (part.data.type === "url") throw new UnsupportedFunctionalityError({ functionality: "PDF file parts with URLs" });
const fullMediaType = resolveFullMediaType({ part });
if (fullMediaType !== "application/pdf") throw new UnsupportedFunctionalityError({ functionality: `file part media type ${fullMediaType}` });
return {
type: "file",
file: {
filename: part.filename ?? "document.pdf",
file_data: `data:application/pdf;base64,${convertToBase64(part.data.data)}`
},
...partMetadata
};
}
if (topLevel === "text") return {
type: "text",
text: part.data.type === "url" ? part.data.url.toString() : typeof part.data.data === "string" ? new TextDecoder().decode(convertBase64ToUint8Array(part.data.data)) : new TextDecoder().decode(part.data.data),
...partMetadata
};
throw new UnsupportedFunctionalityError({ functionality: `file part media type ${part.mediaType}` });
}
}
}
}
function convertToolContentPart(part, provider) {
if (part.type === "custom") throw new UnsupportedFunctionalityError({ functionality: "custom tool content parts" });
return convertToOpenAICompatibleContentPart(part, provider);
}
function convertToOpenAICompatibleChatMessages(prompt, { provider = "openaiCompatible", providerOptionsKey = "google", supportsMultiPartToolContent = false } = {}) {
const messages = [];
for (const { role, content, ...message } of prompt) {
const metadata = getOpenAIMetadata({ ...message });
switch (role) {
case "system":
messages.push({
role: "system",
content,
...metadata
});
break;
case "user":
if (content.length === 1 && content[0].type === "text") {
messages.push({
role: "user",
content: content[0].text,
...getOpenAIMetadata(content[0])
});
break;
}
messages.push({
role: "user",
content: content.map((part) => convertToOpenAICompatibleContentPart(part, provider)),
...metadata
});
break;
case "assistant": {
let text = "";
let reasoning = "";
const toolCalls = [];
for (const part of content) {
const partMetadata = getOpenAIMetadata(part);
switch (part.type) {
case "text":
text += part.text;
break;
case "reasoning":
reasoning += part.text;
break;
case "tool-call": {
const thoughtSignature = part.providerOptions?.[providerOptionsKey]?.thoughtSignature ?? part.providerOptions?.google?.thoughtSignature;
toolCalls.push({
id: part.toolCallId,
type: "function",
function: {
name: part.toolName,
arguments: JSON.stringify(part.input)
},
...partMetadata,
...thoughtSignature ? { extra_content: { google: { thought_signature: String(thoughtSignature) } } } : {}
});
break;
}
}
}
messages.push({
role: "assistant",
content: toolCalls.length > 0 ? text || null : text,
...reasoning.length > 0 ? { reasoning_content: reasoning } : {},
tool_calls: toolCalls.length > 0 ? toolCalls : void 0,
...metadata
});
break;
}
case "tool":
for (const toolResponse of content) {
if (toolResponse.type === "tool-approval-response") continue;
const output = toolResponse.output;
let contentValue;
switch (output.type) {
case "text":
case "error-text":
contentValue = output.value;
break;
case "execution-denied":
contentValue = output.reason ?? "Tool call execution denied.";
break;
case "json":
case "error-json":
contentValue = JSON.stringify(output.value);
break;
case "content": contentValue = supportsMultiPartToolContent ? output.value.map((part) => convertToolContentPart(part, provider)) : JSON.stringify(output.value);
}
const toolResponseMetadata = getOpenAIMetadata(toolResponse);
messages.push({
role: "tool",
tool_call_id: toolResponse.toolCallId,
content: contentValue,
...toolResponseMetadata
});
}
break;
default: throw new Error(`Unsupported role: ${role}`);
}
}
return messages;
}
function getResponseMetadata$1$1({ id, model, created }) {
return createLanguageModelResponseMetadata({
id,
model,
created: created || void 0
});
}
function mapOpenAICompatibleFinishReason$1(finishReason) {
switch (finishReason) {
case "stop": return "stop";
case "length": return "length";
case "content_filter": return "content-filter";
case "function_call":
case "tool_calls": return "tool-calls";
default: return "other";
}
}
const openaiCompatibleLanguageModelChatOptions = z.object({
/**
* A unique identifier representing your end-user, which can help the provider to
* monitor and detect abuse.
*/
user: z.string().optional(),
/**
* Reasoning effort for reasoning models. Defaults to `medium`.
*/
reasoningEffort: z.string().optional(),
/**
* Controls the verbosity of the generated text. Defaults to `medium`.
*/
textVerbosity: z.string().optional(),
/**
* Whether to use strict JSON schema validation.
* When true, the model uses constrained decoding to guarantee schema compliance.
* Only used when the provider supports structured outputs and a schema is provided.
*
* @default true
*/
strictJsonSchema: z.boolean().optional()
});
function prepareTools$4({ tools, toolChoice }) {
tools = tools?.length ? tools : void 0;
const toolWarnings = [];
if (tools == null) return {
tools: void 0,
toolChoice: void 0,
toolWarnings
};
const openaiCompatTools = [];
for (const tool of tools) if (tool.type === "provider") toolWarnings.push({
type: "unsupported",
feature: `provider-defined tool ${tool.id}`
});
else openaiCompatTools.push({
type: "function",
function: {
name: tool.name,
description: tool.description,
parameters: tool.inputSchema,
...tool.strict != null ? { strict: tool.strict } : {}
}
});
if (toolChoice == null) return {
tools: openaiCompatTools,
toolChoice: void 0,
toolWarnings
};
const type = toolChoice.type;
switch (type) {
case "auto":
case "none":
case "required": return {
tools: openaiCompatTools,
toolChoice: type,
toolWarnings
};
case "tool": return {
tools: openaiCompatTools,
toolChoice: {
type: "function",
function: { name: toolChoice.toolName }
},
toolWarnings
};
default: throw new UnsupportedFunctionalityError({ functionality: `tool choice type: ${type}` });
}
}
var OpenAICompatibleChatLanguageModel = class OpenAICompatibleChatLanguageModel {
static [WORKFLOW_SERIALIZE](model) {
return serializeModelOptions({
modelId: model.modelId,
config: model.config
});
}
static [WORKFLOW_DESERIALIZE](options) {
return new OpenAICompatibleChatLanguageModel(options.modelId, options.config);
}
constructor(modelId, config) {
this.specificationVersion = "v4";
this.modelId = modelId;
this.config = config;
const errorStructure = config.errorStructure ?? defaultOpenAICompatibleErrorStructure;
this.chunkSchema = createOpenAICompatibleChatChunkSchema(errorStructure.errorSchema);
this.failedResponseHandler = createJsonErrorResponseHandler(errorStructure);
this.supportsStructuredOutputs = config.supportsStructuredOutputs ?? false;
}
get provider() {
return this.config.provider;
}
get providerOptionsName() {
return this.config.provider.split(".")[0].trim();
}
get supportedUrls() {
return this.config.supportedUrls?.() ?? {};
}
transformRequestBody(args, warnings) {
return this.config.transformRequestBody?.(args, warnings) ?? args;
}
convertUsage(usage) {
return this.config.convertUsage?.(usage) ?? convertOpenAICompatibleChatUsage(usage);
}
async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, reasoning, providerOptions, stopSequences, responseFormat, seed, toolChoice, tools }) {
const warnings = [];
const deprecatedOptions = await parseProviderOptions({
provider: "openai-compatible",
providerOptions,
schema: openaiCompatibleLanguageModelChatOptions
});
if (deprecatedOptions != null) warnings.push({
type: "deprecated",
setting: "providerOptions key 'openai-compatible'",
message: "Use 'openaiCompatible' instead."
});
warnIfDeprecatedProviderOptionsKey({
rawName: this.providerOptionsName,
providerOptions,
warnings
});
const compatibleOptions = Object.assign(deprecatedOptions ?? {}, await parseProviderOptions({
provider: "openaiCompatible",
providerOptions,
schema: openaiCompatibleLanguageModelChatOptions
}) ?? {}, await parseProviderOptions({
provider: this.providerOptionsName,
providerOptions,
schema: openaiCompatibleLanguageModelChatOptions
}) ?? {}, await parseProviderOptions({
provider: toCamelCase(this.providerOptionsName),
providerOptions,
schema: openaiCompatibleLanguageModelChatOptions
}) ?? {});
const strictJsonSchema = compatibleOptions?.strictJsonSchema ?? true;
if (topK != null) warnings.push({
type: "unsupported",
feature: "topK"
});
if (responseFormat?.type === "json" && responseFormat.schema != null && !this.supportsStructuredOutputs) warnings.push({
type: "unsupported",
feature: "responseFormat",
details: "JSON response format schema is only supported with structuredOutputs"
});
const { tools: openaiTools, toolChoice: openaiToolChoice, toolWarnings } = prepareTools$4({
tools,
toolChoice
});
const metadataKey = resolveProviderOptionsKey(this.providerOptionsName, providerOptions);
return {
metadataKey,
args: {
model: this.modelId,
user: compatibleOptions.user,
max_tokens: maxOutputTokens,
temperature,
top_p: topP,
frequency_penalty: frequencyPenalty,
presence_penalty: presencePenalty,
response_format: responseFormat?.type === "json" ? this.supportsStructuredOutputs === true && responseFormat.schema != null ? {
type: "json_schema",
json_schema: {
schema: responseFormat.schema,
strict: strictJsonSchema,
name: responseFormat.name ?? "response",
description: responseFormat.description
}
} : { type: "json_object" } : void 0,
stop: stopSequences,
seed,
...Object.fromEntries(Object.entries({
...providerOptions?.[this.providerOptionsName],
...providerOptions?.[toCamelCase(this.providerOptionsName)]
}).filter(([key]) => !Object.keys(openaiCompatibleLanguageModelChatOptions.shape).includes(key))),
reasoning_effort: compatibleOptions.reasoningEffort ?? (isCustomReasoning(reasoning) ? this.config.mapReasoning != null ? this.config.mapReasoning({
reasoning,
warnings
}) : reasoning : void 0),
verbosity: compatibleOptions.textVerbosity,
messages: convertToOpenAICompatibleChatMessages(prompt, {
provider: this.providerOptionsName,
providerOptionsKey: metadataKey,
supportsMultiPartToolContent: this.config.supportsMultiPartToolContent
}),
tools: openaiTools,
tool_choice: openaiToolChoice
},
warnings: [...warnings, ...toolWarnings]
};
}
async doGenerate(options) {
const { args, warnings, metadataKey } = await this.getArgs({ ...options });
const transformedBody = this.transformRequestBody(args, warnings);
const body = JSON.stringify(transformedBody);
const { responseHeaders, value: responseBody, rawValue: rawResponse } = await postJsonToApi({
url: this.config.url({
path: "/chat/completions",
modelId: this.modelId
}),
headers: combineHeaders(await resolve(this.config.headers), options.headers),
body: transformedBody,
failedResponseHandler: this.failedResponseHandler,
successfulResponseHandler: createJsonResponseHandler(OpenAICompatibleChatResponseSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const choice = responseBody.choices[0];
if (choice == null) throw new InvalidResponseDataError({
data: rawResponse,
message: "Response did not contain any choices."
});
const content = [];
const reasoning = choice.message.reasoning_content ?? choice.message.reasoning;
if (reasoning != null && reasoning.length > 0) content.push({
type: "reasoning",
text: reasoning
});
content.push(...convertOpenAICompatibleContent(choice.message.content));
if (choice.message.tool_calls != null) for (const toolCall of choice.message.tool_calls) {
const thoughtSignature = toolCall.extra_content?.google?.thought_signature;
content.push({
type: "tool-call",
toolCallId: toolCall.id || generateId(),
toolName: toolCall.function.name,
input: toolCall.function.arguments,
...thoughtSignature ? { providerMetadata: { [metadataKey]: { thoughtSignature } } } : {}
});
}
const providerMetadata = {
[metadataKey]: {},
...await this.config.metadataExtractor?.extractMetadata?.({ parsedBody: rawResponse })
};
const completionTokenDetails = responseBody.usage?.completion_tokens_details;
if (completionTokenDetails?.accepted_prediction_tokens != null) providerMetadata[metadataKey].acceptedPredictionTokens = completionTokenDetails?.accepted_prediction_tokens;
if (completionTokenDetails?.rejected_prediction_tokens != null) providerMetadata[metadataKey].rejectedPredictionTokens = completionTokenDetails?.rejected_prediction_tokens;
return {
content,
finishReason: {
unified: mapOpenAICompatibleFinishReason$1(choice.finish_reason),
raw: choice.finish_reason ?? void 0
},
usage: this.convertUsage(responseBody.usage),
providerMetadata,
request: { body },
response: {
...getResponseMetadata$1$1(responseBody),
headers: responseHeaders,
body: rawResponse
},
warnings
};
}
async doStream(options) {
const { args, warnings, metadataKey } = await this.getArgs({ ...options });
const body = this.transformRequestBody({
...args,
stream: true,
stream_options: this.config.includeUsage ? { include_usage: true } : void 0
}, warnings);
const metadataExtractor = this.config.metadataExtractor?.createStreamExtractor();
const { responseHeaders, value: response } = await postJsonToApi({
url: this.config.url({
path: "/chat/completions",
modelId: this.modelId
}),
headers: combineHeaders(await resolve(this.config.headers), options.headers),
body,
failedResponseHandler: this.failedResponseHandler,
successfulResponseHandler: createEventSourceResponseHandler(this.chunkSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const providerOptionsName = metadataKey;
let toolCallTracker;
const pendingToolCalls = /* @__PURE__ */ new Map();
const forwardedToolCallIndices = /* @__PURE__ */ new Set();
const processToolCallDelta = (toolCallDelta) => {
const index = toolCallDelta.index;
if (index == null || forwardedToolCallIndices.has(index)) {
toolCallTracker.processDelta(toolCallDelta);
return;
}
let pending = pendingToolCalls.get(index);
if (pending == null) {
pending = {
id: toolCallDelta.id ?? null,
bufferedArguments: "",
extraContent: toolCallDelta.extra_content ?? null
};
pendingToolCalls.set(index, pending);
} else {
if (pending.id == null && toolCallDelta.id != null) pending.id = toolCallDelta.id;
if (pending.extraContent == null && toolCallDelta.extra_content != null) pending.extraContent = toolCallDelta.extra_content;
}
const argumentsDelta = toolCallDelta.function?.arguments;
if (argumentsDelta != null) pending.bufferedArguments += argumentsDelta;
const name = toolCallDelta.function?.name;
if (name != null) {
const forwardDelta = {
index,
id: pending.id,
function: {
name,
arguments: pending.bufferedArguments
},
extra_content: pending.extraContent ?? void 0
};
toolCallTracker.processDelta(forwardDelta);
pendingToolCalls.delete(index);
forwardedToolCallIndices.add(index);
}
};
let finishReason;
let usage = void 0;
let metadataExtracted = false;
let isActiveReasoning = false;
let isActiveText = false;
const convertUsage = (usage) => this.convertUsage(usage);
return {
stream: response.pipeThrough(new TransformStream({
start(controller) {
toolCallTracker = new StreamingToolCallTracker(controller, {
generateId,
extractMetadata: (delta) => {
const thoughtSignature = delta.extra_content?.google?.thought_signature;
return thoughtSignature ? { [providerOptionsName]: { thoughtSignature } } : void 0;
},
buildToolCallProviderMetadata: (metadata) => metadata
});
controller.enqueue({
type: "stream-start",
warnings
});
},
transform(chunk, controller) {
if (options.includeRawChunks) controller.enqueue({
type: "raw",
rawValue: chunk.rawValue
});
if (!chunk.success) {
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error: chunk.error
});
return;
}
metadataExtractor?.processChunk(chunk.rawValue);
if ("error" in chunk.value) {
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error: chunk.value.error
});
return;
}
const value = chunk.value;
if (!metadataExtracted) {
const metadata = getResponseMetadata$1$1(value);
if (Object.values(metadata).some(Boolean)) {
metadataExtracted = true;
controller.enqueue({
type: "response-metadata",
...metadata
});
}
}
if (value.usage != null) usage = value.usage;
const choice = value.choices[0];
if (choice?.finish_reason != null) finishReason = {
unified: mapOpenAICompatibleFinishReason$1(choice.finish_reason),
raw: choice.finish_reason ?? void 0
};
if (choice?.delta == null) return;
const delta = choice.delta;
const enqueueReasoningDelta = (reasoningDelta) => {
if (isActiveText) {
controller.enqueue({
type: "text-end",
id: "txt-0"
});
isActiveText = false;
}
if (!isActiveReasoning) {
controller.enqueue({
type: "reasoning-start",
id: "reasoning-0"
});
isActiveReasoning = true;
}
controller.enqueue({
type: "reasoning-delta",
id: "reasoning-0",
delta: reasoningDelta
});
};
const enqueueTextDelta = (textDelta) => {
if (isActiveReasoning) {
controller.enqueue({
type: "reasoning-end",
id: "reasoning-0"
});
isActiveReasoning = false;
}
if (!isActiveText) {
controller.enqueue({
type: "text-start",
id: "txt-0"
});
isActiveText = true;
}
controller.enqueue({
type: "text-delta",
id: "txt-0",
delta: textDelta
});
};
const reasoningContent = delta.reasoning_content ?? delta.reasoning;
if (reasoningContent) enqueueReasoningDelta(reasoningContent);
for (const contentPart of convertOpenAICompatibleContent(delta.content)) if (contentPart.type === "reasoning") enqueueReasoningDelta(contentPart.text);
else enqueueTextDelta(contentPart.text);
if (delta.tool_calls != null && delta.tool_calls.length > 0) {
if (isActiveReasoning) {
controller.enqueue({
type: "reasoning-end",
id: "reasoning-0"
});
isActiveReasoning = false;
}
for (const toolCallDelta of delta.tool_calls) processToolCallDelta(toolCallDelta);
}
},
flush(controller) {
if (isActiveReasoning) controller.enqueue({
type: "reasoning-end",
id: "reasoning-0"
});
if (isActiveText) controller.enqueue({
type: "text-end",
id: "txt-0"
});
for (const [index, pending] of pendingToolCalls) toolCallTracker.processDelta({
index,
id: pending.id,
function: { arguments: pending.bufferedArguments }
});
pendingToolCalls.clear();
toolCallTracker.flush();
if (finishReason == null) {
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error: new InvalidResponseDataError({
data: void 0,
message: "Response stream ended without a finish reason."
})
});
}
const providerMetadata = {
[providerOptionsName]: {},
...metadataExtractor?.buildMetadata()
};
if (usage?.completion_tokens_details?.accepted_prediction_tokens != null) providerMetadata[providerOptionsName].acceptedPredictionTokens = usage?.completion_tokens_details?.accepted_prediction_tokens;
if (usage?.completion_tokens_details?.rejected_prediction_tokens != null) providerMetadata[providerOptionsName].rejectedPredictionTokens = usage?.completion_tokens_details?.rejected_prediction_tokens;
controller.enqueue({
type: "finish",
finishReason,
usage: convertUsage(usage),
providerMetadata
});
}
})),
request: { body },
response: { headers: responseHeaders }
};
}
};
const openaiCompatibleTokenUsageSchema = () => z.looseObject({
prompt_tokens: z.number().nullish(),
completion_tokens: z.number().nullish(),
total_tokens: z.number().nullish(),
prompt_tokens_details: z.looseObject({ cached_tokens: z.number().nullish() }).nullish(),
completion_tokens_details: z.looseObject({
reasoning_tokens: z.number().nullish(),
accepted_prediction_tokens: z.number().nullish(),
rejected_prediction_tokens: z.number().nullish()
}).nullish()
}).nullish();
const openAICompatibleContentSchema = () => z.union([z.string(), z.array(z.looseObject({ type: z.string() }))]).nullish();
function convertOpenAICompatibleContent(content) {
if (content == null) return [];
if (typeof content === "string") return content.length > 0 ? [{
type: "text",
text: content
}] : [];
const result = [];
for (const part of content) if (part.type === "text" && typeof part.text === "string") {
if (part.text.length > 0) result.push({
type: "text",
text: part.text
});
} else if (part.type === "thinking" && Array.isArray(part.thinking)) {
const reasoningText = part.thinking.filter((chunk) => chunk != null && typeof chunk === "object" && "type" in chunk && chunk.type === "text" && "text" in chunk && typeof chunk.text === "string").map((chunk) => chunk.text).join("");
if (reasoningText.length > 0) result.push({
type: "reasoning",
text: reasoningText
});
}
return result;
}
const OpenAICompatibleChatResponseSchema = lazySchema(() => zodSchema(z.looseObject({
id: z.string().nullish(),
created: z.number().nullish(),
model: z.string().nullish(),
choices: z.array(z.object({
message: z.object({
role: z.literal("assistant").nullish(),
content: openAICompatibleContentSchema(),
reasoning_content: z.string().nullish(),
reasoning: z.string().nullish(),
tool_calls: z.array(z.object({
id: z.string().nullish(),
function: z.object({
name: z.string(),
arguments: z.string()
}),
extra_content: z.object({ google: z.object({ thought_signature: z.string().nullish() }).nullish() }).nullish()
})).nullish()
}),
finish_reason: z.string().nullish()
})),
usage: openaiCompatibleTokenUsageSchema()
})));
const chunkBaseSchema = () => z.looseObject({
id: z.string().nullish(),
created: z.number().nullish(),
model: z.string().nullish(),
choices: z.array(z.object({
delta: z.object({
role: z.enum(["assistant", ""]).nullish(),
content: openAICompatibleContentSchema(),
reasoning_content: z.string().nullish(),
reasoning: z.string().nullish(),
tool_calls: z.array(z.object({
index: z.number().nullish(),
id: z.string().nullish(),
function: z.object({
name: z.string().nullish(),
arguments: z.string().nullish()
}),
extra_content: z.object({ google: z.object({ thought_signature: z.string().nullish() }).nullish() }).nullish()
})).nullish()
}).nullish(),
finish_reason: z.string().nullish()
})),
usage: openaiCompatibleTokenUsageSchema()
});
const createOpenAICompatibleChatChunkSchema = (errorSchema) => z.union([chunkBaseSchema(), errorSchema]);
function convertOpenAICompatibleCompletionUsage(usage) {
if (usage == null) return createNullLanguageModelUsage();
const promptTokens = usage.prompt_tokens ?? 0;
const completionTokens = usage.completion_tokens ?? 0;
return {
inputTokens: {
total: promptTokens,
noCache: promptTokens,
cacheRead: void 0,
cacheWrite: void 0
},
outputTokens: {
total: completionTokens,
text: completionTokens,
reasoning: void 0
},
raw: usage
};
}
function convertToOpenAICompatibleCompletionPrompt({ prompt, user = "user", assistant = "assistant" }) {
let text = "";
if (prompt[0].role === "system") {
text += `${prompt[0].content}\n\n`;
prompt = prompt.slice(1);
}
for (const { role, content } of prompt) switch (role) {
case "system": throw new InvalidPromptError({
message: `Unexpected system message in prompt: ${content}`,
prompt
});
case "user": {
const userMessage = content.map((part) => {
switch (part.type) {
case "text": return part.text;
}
}).filter(Boolean).join("");
text += `${user}:\n${userMessage}\n\n`;
break;
}
case "assistant": {
const assistantMessage = content.map((part) => {
switch (part.type) {
case "text": return part.text;
case "tool-call": throw new UnsupportedFunctionalityError({ functionality: "tool-call messages" });
}
}).join("");
text += `${assistant}:\n${assistantMessage}\n\n`;
break;
}
case "tool": throw new UnsupportedFunctionalityError({ functionality: "tool messages" });
default: throw new Error(`Unsupported role: ${role}`);
}
text += `${assistant}:\n`;
return {
prompt: text,
stopSequences: [`\n${user}:`]
};
}
function mapOpenAICompatibleFinishReason(finishReason) {
switch (finishReason) {
case "stop": return "stop";
case "length": return "length";
case "content_filter": return "content-filter";
case "function_call":
case "tool_calls": return "tool-calls";
default: return "other";
}
}
const openaiCompatibleLanguageModelCompletionOptions = lazySchema(() => zodSchema(z.object({
/**
* Echo back the prompt in addition to the completion.
*/
echo: z.boolean().optional(),
/**
* Modify the likelihood of specified tokens appearing in the completion.
*
* Accepts a JSON object that maps tokens (specified by their token ID in
* the GPT tokenizer) to an associated bias value from -100 to 100.
*/
logitBias: z.record(z.string(), z.number()).optional(),
/**
* The suffix that comes after a completion of inserted text.
*/
suffix: z.string().optional(),
/**
* A unique identifier representing your end-user, which can help providers to
* monitor and detect abuse.
*/
user: z.string().optional()
})));
var OpenAICompatibleCompletionLanguageModel = class OpenAICompatibleCompletionLanguageModel {
static [WORKFLOW_SERIALIZE](model) {
return serializeModelOptions({
modelId: model.modelId,
config: model.config
});
}
static [WORKFLOW_DESERIALIZE](options) {
return new OpenAICompatibleCompletionLanguageModel(options.modelId, options.config);
}
constructor(modelId, config) {
this.specificationVersion = "v4";
this.modelId = modelId;
this.config = config;
const errorStructure = config.errorStructure ?? defaultOpenAICompatibleErrorStructure;
this.chunkSchema = createOpenAICompatibleCompletionChunkSchema(errorStructure.errorSchema);
this.failedResponseHandler = createJsonErrorResponseHandler(errorStructure);
}
get provider() {
return this.config.provider;
}
get providerOptionsName() {
return this.config.provider.split(".")[0].trim();
}
get supportedUrls() {
return this.config.supportedUrls?.() ?? {};
}
async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences: userStopSequences, responseFormat, seed, providerOptions, tools, toolChoice }) {
const warnings = [];
warnIfDeprecatedProviderOptionsKey({
rawName: this.providerOptionsName,
providerOptions,
warnings
});
const completionOptions = Object.assign(await parseProviderOptions({
provider: this.providerOptionsName,
providerOptions,
schema: openaiCompatibleLanguageModelCompletionOptions
}) ?? {}, await parseProviderOptions({
provider: toCamelCase(this.providerOptionsName),
providerOptions,
schema: openaiCompatibleLanguageModelCompletionOptions
}) ?? {});
if (topK != null) warnings.push({
type: "unsupported",
feature: "topK"
});
if (tools?.length) warnings.push({
type: "unsupported",
feature: "tools"
});
if (toolChoice != null) warnings.push({
type: "unsupported",
feature: "toolChoice"
});
if (responseFormat != null && responseFormat.type !== "text") warnings.push({
type: "unsupported",
feature: "responseFormat",
details: "JSON response format is not supported."
});
const { prompt: completionPrompt, stopSequences } = convertToOpenAICompatibleCompletionPrompt({ prompt });
const stop = [...stopSequences ?? [], ...userStopSequences ?? []];
return {
args: {
model: this.modelId,
echo: completionOptions.echo,
logit_bias: completionOptions.logitBias,
suffix: completionOptions.suffix,
user: completionOptions.user,
max_tokens: maxOutputTokens,
temperature,
top_p: topP,
frequency_penalty: frequencyPenalty,
presence_penalty: presencePenalty,
seed,
...providerOptions?.[this.providerOptionsName],
...providerOptions?.[toCamelCase(this.providerOptionsName)],
prompt: completionPrompt,
stop: stop.length > 0 ? stop : void 0
},
warnings
};
}
async doGenerate(options) {
const { args, warnings } = await this.getArgs(options);
const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({
url: this.config.url({
path: "/completions",
modelId: this.modelId
}),
headers: combineHeaders(await resolve(this.config.headers), options.headers),
body: args,
failedResponseHandler: this.failedResponseHandler,
successfulResponseHandler: createJsonResponseHandler(openaiCompatibleCompletionResponseSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const choice = response.choices[0];
const content = [];
if (choice.text != null && choice.text.length > 0) content.push({
type: "text",
text: choice.text
});
return {
content,
usage: convertOpenAICompatibleCompletionUsage(response.usage),
finishReason: {
unified: mapOpenAICompatibleFinishReason(choice.finish_reason),
raw: choice.finish_reason
},
request: { body: args },
response: {
...createLanguageModelResponseMetadata(response),
headers: responseHeaders,
body: rawResponse
},
warnings
};
}
async doStream(options) {
const { args, warnings } = await this.getArgs(options);
const body = {
...args,
stream: true,
stream_options: this.config.includeUsage ? { include_usage: true } : void 0
};
const { responseHeaders, value: response } = await postJsonToApi({
url: this.config.url({
path: "/completions",
modelId: this.modelId
}),
headers: combineHeaders(await resolve(this.config.headers), options.headers),
body,
failedResponseHandler: this.failedResponseHandler,
successfulResponseHandler: createEventSourceResponseHandler(this.chunkSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
let finishReason = {
unified: "other",
raw: void 0
};
let usage = void 0;
let isFirstChunk = true;
return {
stream: response.pipeThrough(new TransformStream({
start(controller) {
controller.enqueue({
type: "stream-start",
warnings
});
},
transform(chunk, controller) {
if (options.includeRawChunks) controller.enqueue({
type: "raw",
rawValue: chunk.rawValue
});
if (!chunk.success) {
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error: chunk.error
});
return;
}
const value = chunk.value;
if ("error" in value) {
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error: value.error
});
return;
}
if (isFirstChunk) {
isFirstChunk = false;
controller.enqueue({
type: "response-metadata",
...createLanguageModelResponseMetadata(value)
});
controller.enqueue({
type: "text-start",
id: "0"
});
}
if (value.usage != null) usage = value.usage;
const choice = value.choices[0];
if (choice?.finish_reason != null) finishReason = {
unified: mapOpenAICompatibleFinishReason(choice.finish_reason),
raw: choice.finish_reason ?? void 0
};
if (choice?.text != null) controller.enqueue({
type: "text-delta",
id: "0",
delta: choice.text
});
},
flush(controller) {
if (!isFirstChunk) controller.enqueue({
type: "text-end",
id: "0"
});
controller.enqueue({
type: "finish",
finishReason,
usage: convertOpenAICompatibleCompletionUsage(usage)
});
}
})),
request: { body },
response: { headers: responseHeaders }
};
}
};
const usageSchema$1 = () => z.looseObject({
prompt_tokens: z.number(),
completion_tokens: z.number(),
total_tokens: z.number()
});
const openaiCompatibleCompletionResponseSchema = lazySchema(() => zodSchema(z.object({
id: z.string().nullish(),
created: z.number().nullish(),
model: z.string().nullish(),
choices: z.array(z.object({
text: z.string(),
finish_reason: z.string()
})),
usage: usageSchema$1().nullish()
})));
const createOpenAICompatibleCompletionChunkSchema = (errorSchema) => z.union([z.object({
id: z.string().nullish(),
created: z.number().nullish(),
model: z.string().nullish(),
choices: z.array(z.object({
text: z.string(),
finish_reason: z.string().nullish(),
index: z.number()
})),
usage: usageSchema$1().nullish()
}), errorSchema]);
const openaiCompatibleEmbeddingModelOptions = lazySchema(() => zodSchema(z.object({
/**
* The number of dimensions the resulting output embeddings should have.
* Only supported in text-embedding-3 and later models.
*/
dimensions: z.number().optional(),
/**
* A unique identifier representing your end-user, which can help providers to
* monitor and detect abuse.
*/
user: z.string().optional()
})));
var OpenAICompatibleEmbeddingModel = class OpenAICompatibleEmbeddingModel {
get provider() {
return this.config.provider;
}
get maxEmbeddingsPerCall() {
return this.config.maxEmbeddingsPerCall ?? 2048;
}
get supportsParallelCalls() {
return this.config.supportsParallelCalls ?? true;
}
static [WORKFLOW_SERIALIZE](model) {
return serializeModelOptions({
modelId: model.modelId,
config: model.config
});
}
static [WORKFLOW_DESERIALIZE](options) {
return new OpenAICompatibleEmbeddingModel(options.modelId, options.config);
}
constructor(modelId, config) {
this.specificationVersion = "v4";
this.modelId = modelId;
this.config = config;
}
get providerOptionsName() {
return this.config.provider.split(".")[0].trim();
}
async doEmbed({ values, dimensions, headers, abortSignal, providerOptions }) {
const warnings = [];
const deprecatedOptions = await parseProviderOptions({
provider: "openai-compatible",
providerOptions,
schema: openaiCompatibleEmbeddingModelOptions
});
if (deprecatedOptions != null) warnings.push({
type: "deprecated",
setting: "providerOptions key 'openai-compatible'",
message: "Use 'openaiCompatible' instead."
});
warnIfDeprecatedProviderOptionsKey({
rawName: this.providerOptionsName,
providerOptions,
warnings
});
const compatibleOptions = Object.assign(deprecatedOptions ?? {}, await parseProviderOptions({
provider: "openaiCompatible",
providerOptions,
schema: openaiCompatibleEmbeddingModelOptions
}) ?? {}, await parseProviderOptions({
provider: this.providerOptionsName,
providerOptions,
schema: openaiCompatibleEmbeddingModelOptions
}) ?? {});
if (values.length > this.maxEmbeddingsPerCall) throw new TooManyEmbeddingValuesForCallError({
provider: this.provider,
modelId: this.modelId,
maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
values
});
const { responseHeaders, value: response, rawValue } = await postJsonToApi({
url: this.config.url({
path: "/embeddings",
modelId: this.modelId
}),
headers: combineHeaders(await resolve(this.config.headers), headers),
body: {
model: this.modelId,
input: values,
encoding_format: "float",
dimensions: compatibleOptions.dimensions ?? dimensions,
user: compatibleOptions.user
},
failedResponseHandler: createJsonErrorResponseHandler(this.config.errorStructure ?? defaultOpenAICompatibleErrorStructure),
successfulResponseHandler: createJsonResponseHandler(openaiTextEmbeddingResponseSchema),
abortSignal,
fetch: this.config.fetch
});
return {
warnings,
embeddings: response.data.map((item) => item.embedding),
usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0,
providerMetadata: response.providerMetadata,
response: {
headers: responseHeaders,
body: rawValue
}
};
}
};
const openaiTextEmbeddingResponseSchema = lazySchema(() => zodSchema(z.object({
data: z.array(z.object({ embedding: z.array(z.number()) })),
usage: z.object({ prompt_tokens: z.number() }).nullish(),
providerMetadata: z.record(z.string(), z.record(z.string(), z.any())).optional()
})));
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/cerebras/3.0.82/f109ec8918e0841442adbcf0c9d637b3318992b66615579531298e388b43b810/node_modules/@ai-sdk/cerebras/dist/index.js
function isStructuredOutputWithToolCallsFinishReason({ rawFinishReason, hasText, responseFormatType }) {
return responseFormatType === "json" && rawFinishReason === "tool_calls" && hasText;
}
var CerebrasChatLanguageModel = class CerebrasChatLanguageModel extends OpenAICompatibleChatLanguageModel {
static [WORKFLOW_SERIALIZE](model) {
return serializeModelOptions({
modelId: model.modelId,
config: model.config
});
}
static [WORKFLOW_DESERIALIZE](options) {
return new CerebrasChatLanguageModel(options.modelId, options.config);
}
async doGenerate(options) {
const result = await super.doGenerate(options);
if (!isStructuredOutputWithToolCallsFinishReason({
rawFinishReason: result.finishReason.raw,
hasText: result.content.some((part) => part.type === "text" && part.text.length > 0),
responseFormatType: options.responseFormat?.type
})) return result;
return {
...result,
content: result.content.filter((part) => part.type !== "tool-call"),
finishReason: {
...result.finishReason,
unified: "stop"
}
};
}
async doStream(options) {
const result = await super.doStream(options);
let hasText = false;
return {
...result,
stream: result.stream.pipeThrough(new TransformStream({ transform(part, controller) {
if (part.type === "text-delta" && part.delta.length > 0) hasText = true;
if (part.type === "finish" && isStructuredOutputWithToolCallsFinishReason({
rawFinishReason: part.finishReason.raw,
hasText,
responseFormatType: options.responseFormat?.type
})) {
controller.enqueue({
...part,
finishReason: {
...part.finishReason,
unified: "stop"
}
});
return;
}
if (options.responseFormat?.type === "json" && hasText && (part.type === "tool-input-start" || part.type === "tool-input-delta" || part.type === "tool-input-end" || part.type === "tool-call")) return;
controller.enqueue(part);
} }))
};
}
};
const VERSION$8 = "3.0.82";
const cerebrasErrorStructure = {
errorSchema: z.object({
message: z.string(),
type: z.string(),
param: z.string(),
code: z.string()
}),
errorToMessage: (data) => data.message
};
/**
* Cerebras expects assistant reasoning history in the `reasoning` field, while
* the shared OpenAI-compatible converter serializes it as `reasoning_content`.
*/
function transformCerebrasRequestBody(args) {
const { max_tokens: maxTokens, parallelToolCalls, topLogprobs, logitBias, serviceTier, reasoningFormat, promptCacheKey, ...restArgs } = args;
return {
...restArgs,
...maxTokens !== void 0 && { max_completion_tokens: maxTokens },
...parallelToolCalls !== void 0 && { parallel_tool_calls: parallelToolCalls },
...topLogprobs !== void 0 && { top_logprobs: topLogprobs },
...logitBias !== void 0 && { logit_bias: logitBias },
...serviceTier !== void 0 && { service_tier: serviceTier },
...reasoningFormat !== void 0 && { reasoning_format: reasoningFormat },
...promptCacheKey !== void 0 && { prompt_cache_key: promptCacheKey },
messages: Array.isArray(args.messages) ? args.messages.map((message) => {
if (message == null || typeof message !== "object" || message.role !== "assistant" || !("reasoning_content" in message)) return message;
const { reasoning_content, ...rest } = message;
return {
...rest,
...!("reasoning" in rest) && reasoning_content !== void 0 ? { reasoning: reasoning_content } : {}
};
}) : args.messages
};
}
function createCerebras(options = {}) {
const baseURL = withoutTrailingSlash(options.baseURL ?? "https://api.cerebras.ai/v1");
const getHeaders = () => resolveWith(options.apiKey, (apiKey) => withUserAgentSuffix({
Authorization: `Bearer ${loadApiKey({
apiKey,
environmentVariableName: "CEREBRAS_API_KEY",
description: "Cerebras API key"
})}`,
...options.headers
}, `ai-sdk-cerebras/${VERSION$8}`));
const createLanguageModel = (modelId) => {
return new CerebrasChatLanguageModel(modelId, {
provider: `cerebras.chat`,
url: ({ path }) => `${baseURL}${path}`,
headers: getHeaders,
fetch: options.fetch,
errorStructure: cerebrasErrorStructure,
supportsStructuredOutputs: true,
transformRequestBody: transformCerebrasRequestBody
});
};
const provider = (modelId) => createLanguageModel(modelId);
provider.specificationVersion = "v4";
provider.languageModel = createLanguageModel;
provider.chat = createLanguageModel;
provider.embeddingModel = (modelId) => {
throw new NoSuchModelError({
modelId,
modelType: "embeddingModel"
});
};
provider.textEmbeddingModel = provider.embeddingModel;
provider.imageModel = (modelId) => {
throw new NoSuchModelError({
modelId,
modelType: "imageModel"
});
};
return provider;
}
createCerebras();
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/deepinfra/3.0.82/2102c81af44fdb1b674f87eed6ed515931510425680c717d4d0c3f08ba629eaa/node_modules/@ai-sdk/deepinfra/dist/index.js
const deepInfraImageModelOptionsSchema = lazySchema(() => zodSchema(z.looseObject({
negative_prompt: z.string().nullish(),
num_inference_steps: z.number().nullish(),
guidance_scale: z.number().nullish(),
guidance: z.number().nullish(),
response_format: z.enum(["b64_json"]).nullish(),
quality: z.string().nullish(),
style: z.string().nullish(),
user: z.string().nullish()
})));
var DeepInfraImageModel = class DeepInfraImageModel {
get supportsFileInputs() {
return [
"stabilityai/sd3.5",
"black-forest-labs/FLUX-1.1-pro",
"black-forest-labs/FLUX-1-schnell",
"black-forest-labs/FLUX-1-dev",
"black-forest-labs/FLUX-pro",
"black-forest-labs/FLUX.1-Kontext-dev",
"black-forest-labs/FLUX.1-Kontext-pro",
"Qwen/Qwen-Image-Edit",
"stabilityai/sd3.5-medium",
"stabilityai/sdxl-turbo"
].includes(this.modelId) ? true : void 0;
}
get supportsMaskInputs() {
return this.supportsFileInputs;
}
get provider() {
return this.config.provider;
}
static [WORKFLOW_SERIALIZE](model) {
return serializeModelOptions({
modelId: model.modelId,
config: model.config
});
}
static [WORKFLOW_DESERIALIZE](options) {
return new DeepInfraImageModel(options.modelId, options.config);
}
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
this.maxImagesPerCall = 1;
}
async doGenerate({ prompt, n, size, aspectRatio, seed, providerOptions, headers, abortSignal, files, mask }) {
const warnings = [];
const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
const deepInfraOptions = await parseProviderOptions({
provider: "deepinfra",
providerOptions,
schema: deepInfraImageModelOptionsSchema
});
if (files != null && files.length > 0) {
const { value: response, responseHeaders } = await postFormDataToApi({
url: this.getEditUrl(),
headers: combineHeaders(await resolve(this.config.headers), headers),
formData: convertToFormData({
model: this.modelId,
prompt,
image: await Promise.all(files.map((file) => fileToBlob(file))),
mask: mask != null ? await fileToBlob(mask) : void 0,
n,
size,
...deepInfraOptions
}, { useArrayBrackets: false }),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: deepInfraEditErrorSchema,
errorToMessage: (error) => error.error?.message ?? "Unknown error"
}),
successfulResponseHandler: createJsonResponseHandler(deepInfraEditResponseSchema),
abortSignal,
fetch: this.config.fetch
});
return {
images: response.data.map((item) => item.b64_json),
warnings,
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders
}
};
}
const splitSize = size?.split("x");
const { value: response, responseHeaders } = await postJsonToApi({
url: `${this.config.baseURL}/${this.modelId}`,
headers: combineHeaders(await resolve(this.config.headers), headers),
body: {
prompt,
num_images: n,
...aspectRatio && { aspect_ratio: aspectRatio },
...splitSize && {
width: splitSize[0],
height: splitSize[1]
},
...seed != null && { seed },
...deepInfraOptions
},
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: deepInfraErrorSchema,
errorToMessage: (error) => error.detail.error
}),
successfulResponseHandler: createJsonResponseHandler(deepInfraImageResponseSchema),
abortSignal,
fetch: this.config.fetch
});
return {
images: response.images.map((image) => image.replace(/^data:image\/\w+;base64,/, "")),
warnings,
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders
}
};
}
getEditUrl() {
return `${this.config.baseURL.replace("/inference", "/openai")}/images/edits`;
}
};
const deepInfraErrorSchema = z.object({ detail: z.object({ error: z.string() }) });
const deepInfraImageResponseSchema = z.object({ images: z.array(z.string()) });
const deepInfraEditErrorSchema = z.object({ error: z.object({ message: z.string() }).optional() });
const deepInfraEditResponseSchema = z.object({ data: z.array(z.object({ b64_json: z.string() })) });
async function fileToBlob(file) {
if (file.type === "url") return downloadBlob(file.url);
const data = file.data instanceof Uint8Array ? file.data : convertBase64ToUint8Array(file.data);
return new Blob([data], { type: file.mediaType });
}
var DeepInfraChatLanguageModel = class DeepInfraChatLanguageModel extends OpenAICompatibleChatLanguageModel {
static [WORKFLOW_SERIALIZE](model) {
return serializeModelOptions({
modelId: model.modelId,
config: model.config
});
}
static [WORKFLOW_DESERIALIZE](options) {
return new DeepInfraChatLanguageModel(options.modelId, options.config);
}
/**
* Fixes incorrect token usage for Gemini/Gemma models from DeepInfra.
*
* DeepInfra's API returns completion_tokens that don't include reasoning_tokens
* for Gemini/Gemma models, which violates the OpenAI-compatible spec.
* According to the spec, completion_tokens should include reasoning_tokens.
*
* Example of incorrect data from DeepInfra:
* {
* "completion_tokens": 84, // text-only tokens
* "completion_tokens_details": {
* "reasoning_tokens": 1081 // reasoning tokens not included above
* }
* }
*
* This would result in negative text tokens: 84 - 1081 = -997
*
* The fix: If reasoning_tokens > completion_tokens, add reasoning_tokens
* to completion_tokens: 84 + 1081 = 1165
*/
fixUsageForGeminiModels(usage) {
if (!usage || !usage.completion_tokens_details?.reasoning_tokens) return usage;
const completionTokens = usage.completion_tokens ?? 0;
const reasoningTokens = usage.completion_tokens_details.reasoning_tokens;
if (reasoningTokens > completionTokens) {
const correctedCompletionTokens = completionTokens + reasoningTokens;
return {
...usage,
completion_tokens: correctedCompletionTokens,
total_tokens: usage.total_tokens != null ? usage.total_tokens + reasoningTokens : void 0
};
}
return usage;
}
async doGenerate(options) {
const result = await super.doGenerate(options);
if (result.usage?.raw) {
const fixedRawUsage = this.fixUsageForGeminiModels(result.usage.raw);
if (fixedRawUsage !== result.usage.raw) {
const promptTokens = fixedRawUsage.prompt_tokens ?? 0;
const completionTokens = fixedRawUsage.completion_tokens ?? 0;
const cacheReadTokens = fixedRawUsage.prompt_tokens_details?.cached_tokens ?? 0;
const reasoningTokens = fixedRawUsage.completion_tokens_details?.reasoning_tokens ?? 0;
return {
...result,
usage: {
inputTokens: {
total: promptTokens,
noCache: promptTokens - cacheReadTokens,
cacheRead: cacheReadTokens,
cacheWrite: void 0
},
outputTokens: {
total: completionTokens,
text: completionTokens - reasoningTokens,
reasoning: reasoningTokens
},
raw: fixedRawUsage
}
};
}
}
return result;
}
async doStream(options) {
const result = await super.doStream(options);
const originalStream = result.stream;
const fixUsage = this.fixUsageForGeminiModels.bind(this);
const transformedStream = new ReadableStream({ async start(controller) {
const reader = originalStream.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (value.type === "finish" && value.usage?.raw) {
const fixedRawUsage = fixUsage(value.usage.raw);
if (fixedRawUsage !== value.usage.raw) {
const promptTokens = fixedRawUsage.prompt_tokens ?? 0;
const completionTokens = fixedRawUsage.completion_tokens ?? 0;
const cacheReadTokens = fixedRawUsage.prompt_tokens_details?.cached_tokens ?? 0;
const reasoningTokens = fixedRawUsage.completion_tokens_details?.reasoning_tokens ?? 0;
controller.enqueue({
...value,
usage: {
inputTokens: {
total: promptTokens,
noCache: promptTokens - cacheReadTokens,
cacheRead: cacheReadTokens,
cacheWrite: void 0
},
outputTokens: {
total: completionTokens,
text: completionTokens - reasoningTokens,
reasoning: reasoningTokens
},
raw: fixedRawUsage
}
});
} else controller.enqueue(value);
} else controller.enqueue(value);
}
controller.close();
} catch (error) {
controller.error(error);
}
} });
return {
...result,
stream: transformedStream
};
}
};
const VERSION$7 = "3.0.82";
function createDeepInfra(options = {}) {
const baseURL = withoutTrailingSlash(options.baseURL ?? "https://api.deepinfra.com/v1");
const getHeaders = () => resolveWith(options.apiKey, (apiKey) => withUserAgentSuffix({
Authorization: `Bearer ${loadApiKey({
apiKey,
environmentVariableName: "DEEPINFRA_API_KEY",
description: "DeepInfra's API key"
})}`,
...options.headers
}, `ai-sdk-deepinfra/${VERSION$7}`));
const getCommonModelConfig = (modelType) => ({
provider: `deepinfra.${modelType}`,
url: ({ path }) => `${baseURL}/openai${path}`,
headers: getHeaders,
fetch: options.fetch
});
const createChatModel = (modelId) => {
return new DeepInfraChatLanguageModel(modelId, {
...getCommonModelConfig("chat"),
supportsStructuredOutputs: true
});
};
const createCompletionModel = (modelId) => new OpenAICompatibleCompletionLanguageModel(modelId, getCommonModelConfig("completion"));
const createEmbeddingModel = (modelId) => new OpenAICompatibleEmbeddingModel(modelId, getCommonModelConfig("embedding"));
const createImageModel = (modelId) => new DeepInfraImageModel(modelId, {
...getCommonModelConfig("image"),
baseURL: baseURL ? `${baseURL}/inference` : "https://api.deepinfra.com/v1/inference"
});
const provider = (modelId) => createChatModel(modelId);
provider.specificationVersion = "v4";
provider.completionModel = createCompletionModel;
provider.chatModel = createChatModel;
provider.image = createImageModel;
provider.imageModel = createImageModel;
provider.languageModel = createChatModel;
provider.embeddingModel = createEmbeddingModel;
provider.textEmbeddingModel = createEmbeddingModel;
return provider;
}
createDeepInfra();
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/deepseek/3.0.77/66c57eaea375f099c0d5afc2718953567f99e1f49901a5e0fc26b289c746dee5/node_modules/@ai-sdk/deepseek/dist/index.js
const deepseekFilePartProviderOptions = lazySchema(() => zodSchema(z.object({
/**
* Controls how DeepSeek processes an image sent as an `image_url` part.
*
* @see https://api-docs.deepseek.com/api/create-chat-completion/
*/
imageDetail: z.enum([
"low",
"high",
"original",
"auto"
]).optional(),
/**
* Sends inline image data as a DeepSeek `file` part using `file_data`
* instead of an `image_url` data URL. When set, the file part's filename
* is preserved.
*
* This option only applies to inline image data. It cannot be combined
* with `imageDetail`.
*/
fileData: z.literal(true).optional()
})));
function createDeepseekChatOptionsSchema() {
return z.object({
/**
* Whether to return log probabilities for generated tokens.
*/
logprobs: z.boolean().optional(),
/**
* Number of most likely tokens to return at each token position.
*
* Setting this option automatically enables `logprobs`.
*/
topLogprobs: z.number().int().min(0).max(20).optional(),
/**
* An opaque identifier for the end user. DeepSeek uses this identifier for
* content-safety tracing and request isolation.
*
* Must contain only ASCII letters, numbers, underscores, and hyphens, and
* must be at most 512 characters long.
*/
userId: z.string().regex(/^[a-zA-Z0-9_-]+$/, "userId must match /^[a-zA-Z0-9_-]+$/").max(512, "userId must be at most 512 characters long").optional(),
/**
* Type of thinking to use. Defaults to `enabled`.
*/
thinking: z.object({ type: z.enum([
"adaptive",
"enabled",
"disabled"
]).optional() }).optional(),
/**
* Controls the thinking strength for DeepSeek V4 reasoning models.
*/
reasoningEffort: z.enum([
"low",
"medium",
"high",
"xhigh",
"max"
]).optional(),
/**
* Whether to use strict JSON schema validation for structured outputs.
* Only applies when the serving endpoint supports JSON schema response
* formats (e.g. Azure). Defaults to `true`.
*/
strictJsonSchema: z.boolean().optional()
});
}
let chatOptionsSchema;
function getDeepseekChatOptionsSchema() {
return chatOptionsSchema ??= createDeepseekChatOptionsSchema();
}
const deepseekLanguageModelChatOptions = lazySchema(() => zodSchema(getDeepseekChatOptionsSchema()));
function createDeepseekMessageOptionsSchema() {
return z.object({
/**
* The name of the participant represented by the message.
*
* Supported on system, user, and assistant messages.
*/
name: z.string().optional() });
}
let messageOptionsSchema;
function getDeepseekMessageOptionsSchema() {
return messageOptionsSchema ??= createDeepseekMessageOptionsSchema();
}
function createDeepseekAssistantMessageOptionsSchema() {
return getDeepseekMessageOptionsSchema().extend({
/**
* Whether the assistant message content is a prefix that DeepSeek should
* continue. This beta feature is only supported on the final assistant
* message when using a beta base URL.
*/
prefix: z.literal(true).optional() });
}
let assistantMessageOptionsSchema;
function getDeepseekAssistantMessageOptionsSchema() {
return assistantMessageOptionsSchema ??= createDeepseekAssistantMessageOptionsSchema();
}
const deepseekAssistantMessageProviderOptions = lazySchema(() => zodSchema(getDeepseekAssistantMessageOptionsSchema()));
/**
* Whether a model id uses DeepSeek V4-or-newer behavior (thinking mode on by
* default, `reasoning_content` required on every assistant turn).
*
* DeepSeek publishes V4 models under both versioned ids (`deepseek-v4-pro`,
* `deepseek-v4-flash-*`) and unversioned aliases (`deepseek-flash`, currently
* serving V4.1 Flash). Known legacy aliases and pre-V4 version IDs retain
* their previous behavior; unrecognized IDs inherit the current protocol.
*/
function isDeepSeekV4Model(modelId) {
return !/(^|[/.])deepseek-(?:chat|reasoner|v[1-3](?:\.\d+)?)(?=[-/:.]|$)/.test(modelId);
}
const supportedImageMediaTypes = /* @__PURE__ */ new Set([
"image/gif",
"image/jpeg",
"image/jpg",
"image/png",
"image/webp"
]);
function resolveDeepSeekImageMediaType(part) {
const resolvedMediaType = resolveFullMediaType({ part });
if (!supportedImageMediaTypes.has(resolvedMediaType)) throw new UnsupportedFunctionalityError({
functionality: `DeepSeek image media type ${resolvedMediaType}`,
message: "DeepSeek supports JPEG, PNG, GIF, and WebP image inputs."
});
return resolvedMediaType;
}
function validateDeepSeekImageUrl({ url, prompt }) {
if (url.length > 8192) throw new InvalidPromptError({
prompt,
message: "DeepSeek image URLs must not exceed 8192 characters."
});
}
async function convertToDeepSeekChatMessages({ prompt, responseFormat, modelId, providerOptionsName = "deepseek", supportsAssistantPrefixCompletion = false, supportsStructuredOutputs = false }) {
const isDeepSeekV4 = isDeepSeekV4Model(modelId);
const messages = [];
const warnings = [];
if (responseFormat?.type === "json") {
if (responseFormat.schema == null) messages.push({
role: "system",
content: "Return JSON."
});
else if (!supportsStructuredOutputs) {
messages.push({
role: "system",
content: "Return JSON that conforms to the following schema: " + JSON.stringify(responseFormat.schema)
});
warnings.push({
type: "compatibility",
feature: "responseFormat JSON schema",
details: "JSON response schema is injected into the system message."
});
}
}
let lastUserMessageIndex = -1;
for (let i = prompt.length - 1; i >= 0; i--) if (prompt[i].role === "user") {
lastUserMessageIndex = i;
break;
}
let index = -1;
for (const { role, content, providerOptions } of prompt) {
index++;
const deepseekMessageOptions = await parseProviderOptions({
provider: providerOptionsName,
providerOptions,
schema: deepseekAssistantMessageProviderOptions
});
if (deepseekMessageOptions?.prefix === true && role !== "assistant") throw new InvalidPromptError({
prompt,
message: "DeepSeek assistant prefix completion requires `prefix: true` on an assistant message."
});
switch (role) {
case "system":
messages.push({
role: "system",
content,
...deepseekMessageOptions?.name != null && { name: deepseekMessageOptions.name }
});
break;
case "user": {
if (!content.some((part) => part.type === "file" && (part.data.type === "reference" || part.data.type === "url" || part.data.type === "data") && getTopLevelMediaType$2(part.mediaType) === "image")) {
let userContent = "";
for (const part of content) if (part.type === "text") userContent += part.text;
else warnings.push({
type: "unsupported",
feature: `user message part type: ${part.type}`
});
messages.push({
role: "user",
content: userContent,
...deepseekMessageOptions?.name != null && { name: deepseekMessageOptions.name }
});
break;
}
const userContent = [];
for (const part of content) if (part.type === "text") userContent.push({
type: "text",
text: part.text
});
else if (part.type === "file" && getTopLevelMediaType$2(part.mediaType) === "image") {
const filePartOptions = await parseProviderOptions({
provider: providerOptionsName,
providerOptions: part.providerOptions,
schema: deepseekFilePartProviderOptions
});
if (part.data.type === "reference") userContent.push({
type: "file",
file_id: resolveProviderReference({
reference: part.data.reference,
provider: "deepseek"
})
});
else if (part.data.type === "url" || part.data.type === "data") {
const resolvedMediaType = resolveDeepSeekImageMediaType(part);
if (part.data.type === "url") {
const url = part.data.url.toString();
validateDeepSeekImageUrl({
url,
prompt
});
if (filePartOptions?.fileData === true) throw new InvalidPromptError({
prompt,
message: "DeepSeek `fileData` image parts require inline data, not a URL."
});
userContent.push({
type: "image_url",
image_url: {
url,
...filePartOptions?.imageDetail != null && { detail: filePartOptions.imageDetail }
}
});
} else {
const dataUrl = `data:${resolvedMediaType === "image/jpg" ? "image/jpeg" : resolvedMediaType};base64,${convertToBase64(part.data.data)}`;
if (filePartOptions?.fileData === true) {
if (filePartOptions.imageDetail != null) throw new InvalidPromptError({
prompt,
message: "DeepSeek `imageDetail` cannot be combined with `fileData`."
});
userContent.push({
type: "file",
file_data: dataUrl,
...part.filename != null && { filename: part.filename }
});
} else userContent.push({
type: "image_url",
image_url: {
url: dataUrl,
...filePartOptions?.imageDetail != null && { detail: filePartOptions.imageDetail }
}
});
}
} else warnings.push({
type: "unsupported",
feature: `user message part type: ${part.type}`
});
} else warnings.push({
type: "unsupported",
feature: `user message part type: ${part.type}`
});
messages.push({
role: "user",
content: userContent,
...deepseekMessageOptions?.name != null && { name: deepseekMessageOptions.name }
});
break;
}
case "assistant": {
if (deepseekMessageOptions?.prefix === true) {
if (index !== prompt.length - 1) throw new InvalidPromptError({
prompt,
message: "DeepSeek assistant prefix completion requires the prefixed assistant message to be the final message."
});
if (!supportsAssistantPrefixCompletion) throw new UnsupportedFunctionalityError({
functionality: "DeepSeek assistant prefix completion",
message: "DeepSeek assistant prefix completion requires a beta base URL ending in `/beta`."
});
}
let text = "";
let reasoning;
const toolCalls = [];
for (const part of content) switch (part.type) {
case "text":
text += part.text;
break;
case "reasoning":
if (index <= lastUserMessageIndex && !isDeepSeekV4) break;
if (reasoning == null) reasoning = part.text;
else reasoning += part.text;
break;
case "tool-call": toolCalls.push({
id: part.toolCallId,
type: "function",
function: {
name: part.toolName,
arguments: JSON.stringify(part.input)
}
});
}
messages.push({
role: "assistant",
content: text,
...deepseekMessageOptions?.name != null && { name: deepseekMessageOptions.name },
...deepseekMessageOptions?.prefix === true && { prefix: true },
reasoning_content: reasoning ?? (isDeepSeekV4 ? "" : void 0),
tool_calls: toolCalls.length > 0 ? toolCalls : void 0
});
break;
}
case "tool":
if (deepseekMessageOptions?.name != null) warnings.push({
type: "unsupported",
feature: "message name on tool messages"
});
for (const toolResponse of content) {
if (toolResponse.type === "tool-approval-response") continue;
const output = toolResponse.output;
let contentValue;
switch (output.type) {
case "text":
case "error-text":
contentValue = output.value;
break;
case "execution-denied":
contentValue = output.reason ?? "Tool call execution denied.";
break;
case "json":
case "error-json":
contentValue = JSON.stringify(output.value);
break;
case "content":
if (!output.value.some((part) => part.type === "file" && (part.data.type === "reference" || part.data.type === "url" || part.data.type === "data") && getTopLevelMediaType$2(part.mediaType) === "image")) {
contentValue = JSON.stringify(output.value);
break;
}
contentValue = [];
for (const part of output.value) if (part.type === "text") contentValue.push({
type: "text",
text: part.text
});
else if (part.type === "file" && (part.data.type === "reference" || part.data.type === "url" || part.data.type === "data") && getTopLevelMediaType$2(part.mediaType) === "image") {
if (part.data.type === "reference") {
contentValue.push({
type: "file",
file_id: resolveProviderReference({
reference: part.data.reference,
provider: "deepseek"
})
});
continue;
}
const filePartOptions = await parseProviderOptions({
provider: providerOptionsName,
providerOptions: part.providerOptions,
schema: deepseekFilePartProviderOptions
});
const resolvedMediaType = resolveDeepSeekImageMediaType(part);
let url;
if (part.data.type === "url") {
url = part.data.url.toString();
validateDeepSeekImageUrl({
url,
prompt
});
} else url = `data:${resolvedMediaType === "image/jpg" ? "image/jpeg" : resolvedMediaType};base64,${convertToBase64(part.data.data)}`;
contentValue.push({
type: "image_url",
image_url: {
url,
...filePartOptions?.imageDetail != null && { detail: filePartOptions.imageDetail }
}
});
} else warnings.push({
type: "unsupported",
feature: `tool result content part type: ${part.type}`
});
}
messages.push({
role: "tool",
tool_call_id: toolResponse.toolCallId,
content: contentValue
});
}
break;
default: warnings.push({
type: "unsupported",
feature: `message role: ${role}`
});
}
}
return {
messages,
warnings
};
}
function convertDeepSeekUsage(usage) {
if (usage == null) return createNullLanguageModelUsage();
const promptTokens = usage.prompt_tokens ?? 0;
const completionTokens = usage.completion_tokens ?? 0;
const cacheReadTokens = usage.prompt_cache_hit_tokens ?? usage.prompt_tokens_details?.cached_tokens ?? 0;
const reasoningTokens = usage.completion_tokens_details?.reasoning_tokens ?? 0;
return {
inputTokens: {
total: promptTokens,
noCache: promptTokens - cacheReadTokens,
cacheRead: cacheReadTokens,
cacheWrite: void 0
},
outputTokens: {
total: completionTokens,
text: Math.max(0, completionTokens - reasoningTokens),
reasoning: reasoningTokens
},
raw: usage
};
}
function createTokenUsageSchema() {
return z.looseObject({
prompt_tokens: z.number().nullish(),
completion_tokens: z.number().nullish(),
prompt_cache_hit_tokens: z.number().nullish(),
prompt_cache_miss_tokens: z.number().nullish(),
total_tokens: z.number().nullish(),
prompt_tokens_details: z.looseObject({ cached_tokens: z.number().nullish() }).nullish(),
completion_tokens_details: z.looseObject({ reasoning_tokens: z.number().nullish() }).nullish()
}).nullish();
}
let tokenUsageSchema;
function getTokenUsageSchema() {
return tokenUsageSchema ??= createTokenUsageSchema();
}
function createDeepSeekErrorSchema() {
return z.object({ error: z.object({
message: z.string(),
type: z.string().nullish(),
param: z.any().nullish(),
code: z.union([z.string(), z.number()]).nullish()
}) });
}
let errorSchema;
function getDeepSeekErrorSchema() {
return errorSchema ??= createDeepSeekErrorSchema();
}
const deepSeekErrorSchema = lazySchema(() => zodSchema(getDeepSeekErrorSchema()));
function createDeepseekChatLogprobsSchema() {
const deepseekChatLogprobSchema = z.object({
token: z.string(),
logprob: z.number(),
bytes: z.array(z.number()).nullable(),
top_logprobs: z.array(z.object({
token: z.string(),
logprob: z.number(),
bytes: z.array(z.number()).nullable()
}))
});
return z.object({
content: z.array(deepseekChatLogprobSchema).nullish(),
reasoning_content: z.array(deepseekChatLogprobSchema).nullish()
}).nullish();
}
let logprobsSchema;
function getDeepseekChatLogprobsSchema() {
return logprobsSchema ??= createDeepseekChatLogprobsSchema();
}
const deepseekChatResponseSchema = lazySchema(() => zodSchema(z.object({
id: z.string().nullish(),
created: z.number().nullish(),
model: z.string().nullish(),
object: z.literal("chat.completion").nullish(),
system_fingerprint: z.string().nullish(),
choices: z.array(z.object({
index: z.number().nullish(),
message: z.object({
role: z.literal("assistant").nullish(),
content: z.string().nullish(),
reasoning_content: z.string().nullish(),
tool_calls: z.array(z.object({
id: z.string().nullish(),
type: z.literal("function").nullish(),
function: z.object({
name: z.string(),
arguments: z.string()
})
})).nullish()
}),
logprobs: getDeepseekChatLogprobsSchema(),
finish_reason: z.string().nullish()
})),
usage: getTokenUsageSchema()
})));
const deepseekChatChunkSchema = lazySchema(() => zodSchema(z.union([z.object({
id: z.string().nullish(),
created: z.number().nullish(),
model: z.string().nullish(),
object: z.literal("chat.completion.chunk").nullish(),
system_fingerprint: z.string().nullish(),
choices: z.array(z.object({
index: z.number().nullish(),
delta: z.object({
role: z.enum(["assistant"]).nullish(),
content: z.string().nullish(),
reasoning_content: z.string().nullish(),
tool_calls: z.array(z.object({
index: z.number(),
id: z.string().nullish(),
type: z.literal("function").nullish(),
function: z.object({
name: z.string().nullish(),
arguments: z.string().nullish()
})
})).nullish()
}).nullish(),
logprobs: getDeepseekChatLogprobsSchema(),
finish_reason: z.string().nullish()
})),
usage: getTokenUsageSchema()
}), getDeepSeekErrorSchema()])));
function prepareTools$3({ tools, toolChoice, supportsStrictToolCalls }) {
tools = tools?.length ? tools : void 0;
const toolWarnings = [];
if (tools == null) return {
tools: void 0,
toolChoice: void 0,
toolWarnings
};
const functionTools = tools.filter((tool) => tool.type === "function");
const hasStrictTool = functionTools.some((tool) => tool.strict === true);
if (hasStrictTool && supportsStrictToolCalls === false) throw new UnsupportedFunctionalityError({
functionality: "DeepSeek strict tool calls",
message: "DeepSeek strict tool calls require a beta base URL ending in `/beta`."
});
if (hasStrictTool && supportsStrictToolCalls === true && functionTools.some((tool) => tool.strict !== true)) throw new UnsupportedFunctionalityError({
functionality: "mixed DeepSeek strict and non-strict tool calls",
message: "DeepSeek strict mode requires every function tool in the request to set `strict: true`."
});
const deepseekTools = [];
for (const tool of tools) if (tool.type === "provider") toolWarnings.push({
type: "unsupported",
feature: `provider-defined tool ${tool.id}`
});
else deepseekTools.push({
type: "function",
function: {
name: tool.name,
description: tool.description,
parameters: tool.inputSchema,
...tool.strict != null ? { strict: tool.strict } : {}
}
});
if (toolChoice == null) return {
tools: deepseekTools,
toolChoice: void 0,
toolWarnings
};
const type = toolChoice?.type;
switch (type) {
case "auto":
case "none":
case "required": return {
tools: deepseekTools,
toolChoice: type,
toolWarnings
};
case "tool": return {
tools: deepseekTools,
toolChoice: {
type: "function",
function: { name: toolChoice.toolName }
},
toolWarnings
};
default: return {
tools: deepseekTools,
toolChoice: void 0,
toolWarnings: [...toolWarnings, {
type: "unsupported",
feature: `tool choice type: ${type}`
}]
};
}
}
function mapDeepSeekFinishReason(finishReason) {
switch (finishReason) {
case "stop": return "stop";
case "length": return "length";
case "content_filter": return "content-filter";
case "tool_calls": return "tool-calls";
case "insufficient_system_resource": return "error";
default: return "other";
}
}
function createDeepSeekStreamError(error, data) {
const metadata = getDeepSeekStreamErrorMetadata(error);
return createProviderStreamError({
message: error.message,
type: error.type ?? void 0,
code: error.code ?? void 0,
...metadata,
data
});
}
function getDeepSeekStreamErrorMetadata(error) {
if (error.code === "insufficient_quota" || error.type === "insufficient_quota") return {
statusCode: 429,
isRetryable: false
};
const explicitStatusCode = getHttpStatusCode$1(error.code);
if (explicitStatusCode != null) return {
statusCode: explicitStatusCode,
isRetryable: isRetryableStatusCode$1(explicitStatusCode)
};
for (const discriminator of [error.code, error.type]) switch (discriminator) {
case "rate_limit_exceeded":
case "rate_limit_error": return {
statusCode: 429,
isRetryable: true
};
case "server_error":
case "api_error":
case "internal_server_error": return {
statusCode: 500,
isRetryable: true
};
case "overloaded_error":
case "service_unavailable": return {
statusCode: 503,
isRetryable: true
};
case "timeout":
case "timeout_error": return {
statusCode: 504,
isRetryable: true
};
case "authentication_error":
case "invalid_api_key": return {
statusCode: 401,
isRetryable: false
};
case "permission_error": return {
statusCode: 403,
isRetryable: false
};
case "not_found_error":
case "model_not_found": return {
statusCode: 404,
isRetryable: false
};
case "bad_request":
case "context_length_exceeded":
case "invalid_request_error": return {
statusCode: 400,
isRetryable: false
};
}
return {};
}
function getHttpStatusCode$1(value) {
const statusCode = typeof value === "string" && /^\d{3}$/.test(value) ? Number(value) : value;
return typeof statusCode === "number" && Number.isInteger(statusCode) && statusCode >= 400 && statusCode <= 599 ? statusCode : void 0;
}
function isRetryableStatusCode$1(statusCode) {
return statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500;
}
function mapDeepSeekProviderReasoningEffort({ reasoningEffort, warnings }) {
const mapped = reasoningEffort === "medium" ? "high" : reasoningEffort === "xhigh" ? "max" : reasoningEffort;
if (mapped !== reasoningEffort) warnings.push({
type: "compatibility",
feature: "reasoningEffort",
details: `reasoningEffort "${reasoningEffort}" is not a canonical DeepSeek value. mapped to "${mapped}".`
});
return mapped;
}
var DeepSeekChatLanguageModel = class DeepSeekChatLanguageModel {
static [WORKFLOW_SERIALIZE](model) {
return serializeModelOptions({
modelId: model.modelId,
config: model.config
});
}
static [WORKFLOW_DESERIALIZE](options) {
return new DeepSeekChatLanguageModel(options.modelId, options.config);
}
constructor(modelId, config) {
this.specificationVersion = "v4";
this.supportedUrls = { "image/*": [/^https?:\/\/.*$/] };
this.modelId = modelId;
this.config = config;
this.failedResponseHandler = createJsonErrorResponseHandler({
errorSchema: deepSeekErrorSchema,
errorToMessage: (error) => error.error.message
});
}
get provider() {
return this.config.provider;
}
get providerOptionsName() {
return this.config.provider.split(".")[0].trim();
}
async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, reasoning, providerOptions, stopSequences, responseFormat, seed, toolChoice, tools }) {
const deepseekOptions = await parseProviderOptions({
provider: this.providerOptionsName,
providerOptions,
schema: deepseekLanguageModelChatOptions
}) ?? {};
const supportsStructuredOutputs = this.config.supportsStructuredOutputs === true;
const supportsPenaltySampling = this.config.supportsPenaltySampling === true;
const { messages, warnings } = await convertToDeepSeekChatMessages({
prompt,
responseFormat,
modelId: this.modelId,
providerOptionsName: this.providerOptionsName,
supportsAssistantPrefixCompletion: this.config.supportsAssistantPrefixCompletion,
supportsStructuredOutputs
});
const allWarnings = [...warnings];
if (topK != null) allWarnings.push({
type: "unsupported",
feature: "topK"
});
if (seed != null) allWarnings.push({
type: "unsupported",
feature: "seed"
});
if (!supportsPenaltySampling && frequencyPenalty != null) allWarnings.push({
type: "deprecated",
setting: "frequencyPenalty",
message: "frequencyPenalty is deprecated by DeepSeek and has been omitted. Remove frequencyPenalty from the request."
});
if (!supportsPenaltySampling && presencePenalty != null) allWarnings.push({
type: "deprecated",
setting: "presencePenalty",
message: "presencePenalty is deprecated by DeepSeek and has been omitted. Remove presencePenalty from the request."
});
const { tools: deepseekTools, toolChoice: deepseekToolChoices, toolWarnings } = prepareTools$3({
tools,
toolChoice,
supportsStrictToolCalls: this.config.supportsStrictToolCalls
});
const thinkingType = deepseekOptions.thinking?.type;
if (thinkingType === "adaptive") allWarnings.push({
type: "compatibility",
feature: "thinking.type",
details: "thinking.type \"adaptive\" is not a canonical DeepSeek value. mapped to \"enabled\"."
});
const thinking = this.config.supportsThinking === false ? void 0 : thinkingType != null ? { type: thinkingType === "adaptive" ? "enabled" : thinkingType } : isCustomReasoning(reasoning) ? { type: reasoning === "none" ? "disabled" : "enabled" } : void 0;
const isThinkingEnabled = this.config.supportsThinking !== false && thinking?.type !== "disabled" && (thinking != null || this.modelId === "deepseek-reasoner" || isDeepSeekV4Model(this.modelId));
if (isThinkingEnabled && temperature != null) allWarnings.push({
type: "unsupported",
feature: "temperature",
details: "temperature has no effect when DeepSeek thinking is enabled. Set providerOptions.deepseek.thinking.type to 'disabled' to use temperature."
});
if (isThinkingEnabled && topP != null) allWarnings.push({
type: "unsupported",
feature: "topP",
details: "topP has no effect when DeepSeek thinking is enabled. Set providerOptions.deepseek.thinking.type to 'disabled' to use topP."
});
const reasoningEffort = deepseekOptions.reasoningEffort != null ? mapDeepSeekProviderReasoningEffort({
reasoningEffort: deepseekOptions.reasoningEffort,
warnings: allWarnings
}) : isCustomReasoning(reasoning) && reasoning !== "none" ? mapReasoningToProviderEffort({
reasoning,
effortMap: {
low: "low",
high: "high",
max: "max"
},
warnings: allWarnings
}) : void 0;
return {
args: {
model: this.modelId,
...(deepseekOptions.logprobs === true || deepseekOptions.topLogprobs != null) && { logprobs: true },
...deepseekOptions.topLogprobs != null && { top_logprobs: deepseekOptions.topLogprobs },
max_tokens: maxOutputTokens,
temperature: isThinkingEnabled ? void 0 : temperature,
top_p: isThinkingEnabled ? void 0 : topP,
frequency_penalty: supportsPenaltySampling ? frequencyPenalty : void 0,
presence_penalty: supportsPenaltySampling ? presencePenalty : void 0,
response_format: responseFormat?.type === "json" ? supportsStructuredOutputs && responseFormat.schema != null ? {
type: "json_schema",
json_schema: {
schema: responseFormat.schema,
strict: deepseekOptions.strictJsonSchema ?? true,
name: responseFormat.name ?? "response",
description: responseFormat.description
}
} : { type: "json_object" } : void 0,
stop: stopSequences,
messages,
tools: deepseekTools,
tool_choice: deepseekToolChoices,
thinking,
...deepseekOptions.userId != null && { user_id: deepseekOptions.userId },
...thinking?.type !== "disabled" && reasoningEffort != null && { reasoning_effort: reasoningEffort }
},
warnings: [...allWarnings, ...toolWarnings]
};
}
async doGenerate(options) {
const { args, warnings } = await this.getArgs({ ...options });
const { responseHeaders, value: responseBody, rawValue: rawResponse } = await postJsonToApi({
url: this.config.url({
path: "/chat/completions",
modelId: this.modelId
}),
headers: combineHeaders(await resolve(this.config.headers), options.headers),
body: args,
failedResponseHandler: this.failedResponseHandler,
successfulResponseHandler: createJsonResponseHandler(deepseekChatResponseSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const choice = responseBody.choices[0];
if (choice == null) throw new InvalidResponseDataError({
data: rawResponse,
message: "Response did not contain any choices."
});
const content = [];
const reasoning = choice.message.reasoning_content;
if (reasoning != null && reasoning.length > 0) content.push({
type: "reasoning",
text: reasoning
});
if (choice.message.tool_calls != null) for (const toolCall of choice.message.tool_calls) content.push({
type: "tool-call",
toolCallId: toolCall.id || generateId(),
toolName: toolCall.function.name,
input: toolCall.function.arguments
});
const text = choice.message.content;
if (text != null && text.length > 0) content.push({
type: "text",
text
});
return {
content,
finishReason: {
unified: mapDeepSeekFinishReason(choice.finish_reason),
raw: choice.finish_reason ?? void 0
},
usage: convertDeepSeekUsage(responseBody.usage),
providerMetadata: { [this.providerOptionsName]: {
promptCacheHitTokens: responseBody.usage?.prompt_cache_hit_tokens,
promptCacheMissTokens: responseBody.usage?.prompt_cache_miss_tokens,
...responseBody.object != null && { responseObject: responseBody.object },
...choice.index != null && { choiceIndex: choice.index },
...choice.message.role != null && { messageRole: choice.message.role },
...choice.message.tool_calls != null && { toolCallTypes: choice.message.tool_calls.map((toolCall) => toolCall.type).filter((type) => type != null) },
...choice.logprobs != null && { logprobs: choice.logprobs },
...responseBody.system_fingerprint != null && { systemFingerprint: responseBody.system_fingerprint }
} },
request: { body: args },
response: {
...createLanguageModelResponseMetadata(responseBody),
headers: responseHeaders,
body: rawResponse
},
warnings
};
}
async doStream(options) {
const { args, warnings } = await this.getArgs({ ...options });
const body = {
...args,
stream: true,
stream_options: { include_usage: true }
};
const { responseHeaders, value: response } = await postJsonToApi({
url: this.config.url({
path: "/chat/completions",
modelId: this.modelId
}),
headers: combineHeaders(await resolve(this.config.headers), options.headers),
body,
failedResponseHandler: this.failedResponseHandler,
successfulResponseHandler: createEventSourceResponseHandler(deepseekChatChunkSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
let toolCallTracker;
let finishReason = {
unified: "interrupted",
raw: void 0
};
let usage = void 0;
let systemFingerprint = void 0;
let isFirstChunk = true;
const providerOptionsName = this.providerOptionsName;
let isActiveReasoning = false;
let isActiveText = false;
let responseObject;
let choiceIndex;
let messageRole;
const toolCallTypes = /* @__PURE__ */ new Map();
const contentLogprobs = [];
const reasoningLogprobs = [];
return {
stream: response.pipeThrough(new TransformStream({
start(controller) {
toolCallTracker = new StreamingToolCallTracker(controller, { generateId });
controller.enqueue({
type: "stream-start",
warnings
});
},
transform(chunk, controller) {
if (options.includeRawChunks) controller.enqueue({
type: "raw",
rawValue: chunk.rawValue
});
if (!chunk.success) {
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error: chunk.error
});
return;
}
const value = chunk.value;
if ("error" in value) {
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error: createDeepSeekStreamError(value.error, value)
});
return;
}
if (isFirstChunk) {
isFirstChunk = false;
controller.enqueue({
type: "response-metadata",
...createLanguageModelResponseMetadata(value)
});
}
if (value.usage != null) usage = value.usage;
if (value.object != null) responseObject = value.object;
if (value.system_fingerprint != null) systemFingerprint = value.system_fingerprint;
const choice = value.choices[0];
if (choice?.index != null) choiceIndex = choice.index;
if (choice?.finish_reason != null) finishReason = {
unified: mapDeepSeekFinishReason(choice.finish_reason),
raw: choice.finish_reason
};
if (choice?.logprobs?.content != null) contentLogprobs.push(...choice.logprobs.content);
if (choice?.logprobs?.reasoning_content != null) reasoningLogprobs.push(...choice.logprobs.reasoning_content);
if (choice?.delta == null) return;
const delta = choice.delta;
if (delta.role != null) messageRole = delta.role;
const reasoningContent = delta.reasoning_content;
if (reasoningContent) {
if (!isActiveReasoning) {
controller.enqueue({
type: "reasoning-start",
id: "reasoning-0"
});
isActiveReasoning = true;
}
controller.enqueue({
type: "reasoning-delta",
id: "reasoning-0",
delta: reasoningContent
});
}
if (delta.content) {
if (!isActiveText) {
controller.enqueue({
type: "text-start",
id: "txt-0"
});
isActiveText = true;
}
if (isActiveReasoning) {
controller.enqueue({
type: "reasoning-end",
id: "reasoning-0"
});
isActiveReasoning = false;
}
controller.enqueue({
type: "text-delta",
id: "txt-0",
delta: delta.content
});
}
if (delta.tool_calls != null && delta.tool_calls.length > 0) {
if (isActiveReasoning) {
controller.enqueue({
type: "reasoning-end",
id: "reasoning-0"
});
isActiveReasoning = false;
}
for (const toolCallDelta of delta.tool_calls) {
if (toolCallDelta.type != null) toolCallTypes.set(toolCallDelta.index, toolCallDelta.type);
toolCallTracker.processDelta(toolCallDelta);
}
}
},
flush(controller) {
if (isActiveReasoning) controller.enqueue({
type: "reasoning-end",
id: "reasoning-0"
});
if (isActiveText) controller.enqueue({
type: "text-end",
id: "txt-0"
});
toolCallTracker.flush();
controller.enqueue({
type: "finish",
finishReason,
usage: convertDeepSeekUsage(usage),
providerMetadata: { [providerOptionsName]: {
promptCacheHitTokens: usage?.prompt_cache_hit_tokens ?? void 0,
promptCacheMissTokens: usage?.prompt_cache_miss_tokens ?? void 0,
...responseObject != null && { responseObject },
...choiceIndex != null && { choiceIndex },
...messageRole != null && { messageRole },
...toolCallTypes.size > 0 && { toolCallTypes: [...toolCallTypes.entries()].sort(([left], [right]) => left - right).map(([, type]) => type) },
...(contentLogprobs.length > 0 || reasoningLogprobs.length > 0) && { logprobs: {
...contentLogprobs.length > 0 && { content: contentLogprobs },
...reasoningLogprobs.length > 0 && { reasoning_content: reasoningLogprobs }
} },
...systemFingerprint != null && { systemFingerprint }
} }
});
}
})),
request: { body },
response: { headers: responseHeaders }
};
}
};
const deepSeekFilesResponseSchema = lazySchema(() => zodSchema(z.object({
id: z.string(),
object: z.literal("file").nullish(),
bytes: z.number().int().nonnegative().nullish(),
created_at: z.number().int().nonnegative().nullish(),
filename: z.string().nullish(),
purpose: z.literal("user_data").nullish(),
expires_at: z.number().int().nonnegative().nullish()
})));
const deepSeekFilesOptionsSchema = lazySchema(() => zodSchema(z.object({
/**
* Number of seconds after creation before the file expires.
* Must be between 1 hour and 30 days.
*/
expiresAfter: z.number().int().min(3600).max(2592e3).optional() })));
const deepSeekFailedResponseHandler = createJsonErrorResponseHandler({
errorSchema: deepSeekErrorSchema,
errorToMessage: (error) => error.error.message
});
const MAX_FILE_SIZE_BYTES = 67108864;
const MAX_FILENAME_LENGTH = 512;
const supportedMediaTypes = /* @__PURE__ */ new Set([
"image/gif",
"image/jpeg",
"image/jpg",
"image/png",
"image/webp"
]);
const genericMediaTypes = /* @__PURE__ */ new Set([
"",
"application/binary",
"application/octet-stream",
"binary/octet-stream",
"image",
"image/*"
]);
const supportedFilenameExtensions = /* @__PURE__ */ new Set([
"gif",
"jpeg",
"jpg",
"png",
"webp"
]);
var DeepSeekFiles = class {
get provider() {
return this.config.provider;
}
constructor(config) {
this.config = config;
this.specificationVersion = "v4";
}
async uploadFile({ data, mediaType, filename, abortSignal, headers, providerOptions }) {
const deepSeekOptions = await parseProviderOptions({
provider: "deepseek",
providerOptions,
schema: deepSeekFilesOptionsSchema
});
const fileBytes = convertInlineFileDataToUint8Array(data);
validateFileUpload({
fileBytes,
mediaType,
filename
});
const blob = new Blob([fileBytes], { type: mediaType });
const formData = new FormData();
if (filename != null) formData.append("file", blob, filename);
else formData.append("file", blob);
formData.append("purpose", "user_data");
if (deepSeekOptions?.expiresAfter != null) {
formData.append("expires_after[anchor]", "created_at");
formData.append("expires_after[seconds]", String(deepSeekOptions.expiresAfter));
}
const { value: response } = await postFormDataToApi({
url: `${this.config.baseURL}/files`,
headers: combineHeaders(await resolve(this.config.headers), headers),
formData,
failedResponseHandler: deepSeekFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler(deepSeekFilesResponseSchema),
abortSignal,
fetch: this.config.fetch
});
return {
warnings: [],
providerReference: { deepseek: response.id },
...response.filename ?? filename ? { filename: response.filename ?? filename } : {},
...mediaType != null ? { mediaType } : {},
providerMetadata: { deepseek: {
...response.object != null ? { object: response.object } : {},
...response.filename != null ? { filename: response.filename } : {},
...response.purpose != null ? { purpose: response.purpose } : {},
...response.bytes != null ? { bytes: response.bytes } : {},
...response.created_at != null ? { createdAt: response.created_at } : {},
...response.expires_at != null ? { expiresAt: response.expires_at } : {}
} }
};
}
};
function validateFileUpload({ fileBytes, mediaType, filename }) {
if (fileBytes.length > MAX_FILE_SIZE_BYTES) throw new InvalidArgumentError({
argument: "data",
message: `DeepSeek file uploads must not exceed 64 MiB (${MAX_FILE_SIZE_BYTES.toLocaleString("en-US")} bytes). Received ${fileBytes.length.toLocaleString("en-US")} bytes.`
});
if (filename != null) {
const filenameLength = Array.from(filename).length;
if (filenameLength > MAX_FILENAME_LENGTH) throw new InvalidArgumentError({
argument: "filename",
message: `DeepSeek filenames must not exceed ${MAX_FILENAME_LENGTH} characters. Received ${filenameLength} characters.`
});
}
const normalizedMediaType = normalizeMediaType(mediaType);
const detectedMediaType = detectMediaType({ data: fileBytes });
if (detectedMediaType != null && !supportedMediaTypes.has(detectedMediaType)) throw new InvalidArgumentError({
argument: "data",
message: `DeepSeek file uploads support JPEG, PNG, GIF, and WebP images. Detected unsupported file content type "${detectedMediaType}".`
});
if (supportedMediaTypes.has(normalizedMediaType)) return;
if (!genericMediaTypes.has(normalizedMediaType)) throw new InvalidArgumentError({
argument: "mediaType",
message: `DeepSeek file uploads support JPEG, PNG, GIF, and WebP images. Received unsupported media type "${mediaType}".`
});
if (detectedMediaType != null || hasSupportedFilenameExtension(filename)) return;
throw new InvalidArgumentError({
argument: "mediaType",
message: `DeepSeek file uploads support JPEG, PNG, GIF, and WebP images. Provide a supported media type or a filename ending in .jpg, .jpeg, .png, .gif, or .webp. Received "${mediaType}".`
});
}
function normalizeMediaType(mediaType) {
return mediaType.split(";", 1)[0].trim().toLowerCase();
}
function hasSupportedFilenameExtension(filename) {
if (filename == null) return false;
const extensionSeparatorIndex = filename.lastIndexOf(".");
return extensionSeparatorIndex !== -1 && supportedFilenameExtensions.has(filename.slice(extensionSeparatorIndex + 1).toLowerCase());
}
const VERSION$6 = "3.0.77";
function createDeepSeek(options = {}) {
const baseURL = withoutTrailingSlash(options.baseURL ?? "https://api.deepseek.com") ?? "https://api.deepseek.com";
const getHeaders = () => resolveWith(options.apiKey, (apiKey) => withUserAgentSuffix({
Authorization: `Bearer ${loadApiKey({
apiKey,
environmentVariableName: "DEEPSEEK_API_KEY",
description: "DeepSeek API key"
})}`,
...options.headers
}, `ai-sdk-deepseek/${VERSION$6}`));
const createLanguageModel = (modelId) => {
return new DeepSeekChatLanguageModel(modelId, {
provider: `deepseek.chat`,
url: ({ path }) => `${baseURL}${path}`,
headers: getHeaders,
fetch: options.fetch,
supportsAssistantPrefixCompletion: baseURL.endsWith("/beta"),
supportsStrictToolCalls: baseURL.endsWith("/beta")
});
};
const createFiles = () => new DeepSeekFiles({
provider: "deepseek.files",
baseURL,
headers: getHeaders,
fetch: options.fetch
});
const provider = (modelId) => createLanguageModel(modelId);
provider.specificationVersion = "v4";
provider.languageModel = createLanguageModel;
provider.chat = createLanguageModel;
provider.files = createFiles;
provider.embeddingModel = (modelId) => {
throw new NoSuchModelError({
modelId,
modelType: "embeddingModel"
});
};
provider.textEmbeddingModel = provider.embeddingModel;
provider.imageModel = (modelId) => {
throw new NoSuchModelError({
modelId,
modelType: "imageModel"
});
};
return provider;
}
createDeepSeek();
var googleFailedResponseHandler = createJsonErrorResponseHandler$2({
errorSchema: lazySchema$1(() => zodSchema$2(z.object({ error: z.object({
code: z.number().nullable(),
message: z.string(),
status: z.string(),
details: z.array(z.unknown()).nullish()
}) }))),
errorToMessage: (data) => data.error.message
});
var googleTranscriptionModelOptions = lazySchema$1(() => zodSchema$2(z.object({
/**
* BCP-47 language codes providing hints about the languages present in the
* audio. If omitted or empty, defaults to automatic language detection.
*/
languageCodes: z.array(z.string()).optional(),
/**
* Custom vocabulary phrases, which bias the speech recognition model
* toward recognizing specific terms.
*/
customVocabulary: z.array(z.string()).optional(),
/**
* Enables word-level timestamp generation.
*/
wordTimestamp: z.boolean().optional(),
/**
* Enables speaker diarization.
*/
diarization: z.boolean().optional(),
/**
* Transcription output formatting mode.
*
* - `VERBATIM` (default): exact literal transcript preserving filler
* words, repetitions, and false starts.
* - `SMART`: cleans up and structures the transcript in real time —
* disfluency removal, inline self-corrections, structured formatting
* (lists, numbers, dates, paragraph breaks), and grammar/casing polish.
*/
mode: z.enum(["SMART", "VERBATIM"]).optional()
})));
function isLiveTranscriptionModelId(modelId) {
return modelId.includes("-live");
}
var GoogleTranscriptionModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v3";
}
get provider() {
return this.config.provider;
}
async parseOptions(providerOptions) {
return parseProviderOptions$1({
provider: "google",
providerOptions,
schema: googleTranscriptionModelOptions
});
}
async doGenerate(options) {
var _a2, _b, _c, _d, _e, _f;
if (isLiveTranscriptionModelId(this.modelId)) throw new InvalidArgumentError$2({
argument: "modelId",
message: `Model '${this.modelId}' only supports streaming transcription, which requires AI SDK v7. Use a unary model such as 'gemini-3.5-transcribe'.`
});
const currentDate = (_c = (_b = (_a2 = this.config._internal) == null ? void 0 : _a2.currentDate) == null ? void 0 : _b.call(_a2)) != null ? _c : /* @__PURE__ */ new Date();
const warnings = [];
const transcriptionConfig = buildTranscriptionConfig(await this.parseOptions(options.providerOptions));
const requestBody = {
model: this.modelId,
input: [{
type: "audio",
data: convertToBase64$1(options.audio),
mime_type: options.mediaType
}],
...transcriptionConfig != null ? { generation_config: { transcription_config: transcriptionConfig } } : {}
};
const { value: response, responseHeaders, rawValue: rawResponse } = await postJsonToApi$2({
url: `${this.config.baseURL}/interactions`,
headers: combineHeaders$2(this.config.headers ? await resolve$1(this.config.headers) : void 0, options.headers),
body: requestBody,
failedResponseHandler: googleFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$2(googleInteractionsTranscriptionResponseSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
let text = "";
const segments = [];
for (const step of (_d = response.steps) != null ? _d : []) for (const content of (_e = step.content) != null ? _e : []) {
if (content.type !== "text" || content.text == null) continue;
text += content.text;
for (const annotation of (_f = content.annotations) != null ? _f : []) {
if (annotation.type !== "word_info") continue;
const startSecond = parseOffsetSeconds(annotation.start_offset);
const endSecond = parseOffsetSeconds(annotation.end_offset);
if (annotation.text == null || startSecond == null || endSecond == null) continue;
segments.push({
text: annotation.text,
startSecond,
endSecond
});
}
}
return {
text,
segments,
language: void 0,
durationInSeconds: void 0,
warnings,
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders,
body: rawResponse
},
...response.usage != null ? { providerMetadata: { google: { usage: response.usage } } } : {}
};
}
};
function buildTranscriptionConfig(options) {
var _a2;
if (options == null) return void 0;
const config = {};
if (options.languageCodes != null) config.language_codes = options.languageCodes;
if (options.customVocabulary != null) config.custom_vocabulary = options.customVocabulary;
if (options.mode != null || options.diarization === true || options.wordTimestamp === true) config.mode = {
type: ((_a2 = options.mode) != null ? _a2 : "VERBATIM").toLowerCase(),
...options.diarization === true ? { diarization_mode: "speaker" } : {},
...options.wordTimestamp === true ? { timestamp_granularities: ["word"] } : {}
};
return Object.keys(config).length > 0 ? config : void 0;
}
function parseOffsetSeconds(offset) {
if (offset == null) return void 0;
const parsed = Number.parseFloat(offset);
return Number.isFinite(parsed) ? parsed : void 0;
}
var googleInteractionsWordAnnotationSchema = () => z.object({
type: z.string().nullish(),
text: z.string().nullish(),
speaker: z.string().nullish(),
start_offset: z.string().nullish(),
end_offset: z.string().nullish()
});
var googleInteractionsTranscriptionResponseSchema = lazySchema$1(() => zodSchema$2(z.object({
status: z.string().nullish(),
steps: z.array(z.object({
type: z.string().nullish(),
content: z.array(z.object({
type: z.string().nullish(),
text: z.string().nullish(),
annotations: z.array(googleInteractionsWordAnnotationSchema()).nullish()
})).nullish()
})).nullish(),
usage: z.record(z.string(), z.unknown()).nullish()
})));
var VERSION$5 = "3.0.140";
var googleEmbeddingContentPartSchema = () => z.union([
z.object({ text: z.string() }),
z.object({ inlineData: z.object({
mimeType: z.string(),
data: z.string()
}) }),
z.object({ fileData: z.object({
fileUri: z.string(),
mimeType: z.string()
}) })
]);
var googleEmbeddingModelOptions = lazySchema$1(() => zodSchema$2(z.object({
/**
* Optional. Optional reduced dimension for the output embedding.
* If set, excessive values in the output embedding are truncated from the end.
*/
outputDimensionality: z.number().optional(),
/**
* Optional. Specifies the task type for generating embeddings.
* Supported task types:
* - SEMANTIC_SIMILARITY: Optimized for text similarity.
* - CLASSIFICATION: Optimized for text classification.
* - CLUSTERING: Optimized for clustering texts based on similarity.
* - RETRIEVAL_DOCUMENT: Optimized for document retrieval.
* - RETRIEVAL_QUERY: Optimized for query-based retrieval.
* - QUESTION_ANSWERING: Optimized for answering questions.
* - FACT_VERIFICATION: Optimized for verifying factual information.
* - CODE_RETRIEVAL_QUERY: Optimized for retrieving code blocks based on natural language queries.
*/
taskType: z.enum([
"SEMANTIC_SIMILARITY",
"CLASSIFICATION",
"CLUSTERING",
"RETRIEVAL_DOCUMENT",
"RETRIEVAL_QUERY",
"QUESTION_ANSWERING",
"FACT_VERIFICATION",
"CODE_RETRIEVAL_QUERY"
]).optional(),
/**
* Optional. Per-value multimodal content parts for embedding non-text
* content (images, video, PDF, audio). Each entry corresponds to the
* embedding value at the same index and its parts are merged with the
* text value in the request. Use `null` for entries that are text-only.
*
* The array length must match the number of values being embedded. In
* the case of a single embedding, the array length must be 1.
*/
content: z.array(z.array(googleEmbeddingContentPartSchema()).min(1).nullable()).optional()
})));
var _a = EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER;
var GoogleGenerativeAIEmbeddingModel = class {
constructor(modelId, config) {
this.specificationVersion = "v3";
this.maxEmbeddingsPerCall = 100;
this.supportsParallelCalls = true;
this[_a] = ({ providerOptions, values, startIndex, endIndex }) => {
var _a2;
const multimodalContent = (_a2 = providerOptions == null ? void 0 : providerOptions.google) == null ? void 0 : _a2.content;
if (!Array.isArray(multimodalContent)) return providerOptions;
validateMultimodalContentLength({
multimodalContent,
values
});
return {
...providerOptions,
google: {
...providerOptions == null ? void 0 : providerOptions.google,
content: multimodalContent.slice(startIndex, endIndex)
}
};
};
this.modelId = modelId;
this.config = config;
}
get provider() {
return this.config.provider;
}
async doEmbed({ values, headers, abortSignal, providerOptions }) {
const googleOptions = await parseProviderOptions$1({
provider: "google",
providerOptions,
schema: googleEmbeddingModelOptions
});
if (values.length > this.maxEmbeddingsPerCall) throw new TooManyEmbeddingValuesForCallError$1({
provider: this.provider,
modelId: this.modelId,
maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
values
});
const mergedHeaders = combineHeaders$2(await resolve$1(this.config.headers), headers);
const multimodalContent = googleOptions == null ? void 0 : googleOptions.content;
validateMultimodalContentLength({
multimodalContent,
values
});
if (values.length === 1) {
const valueParts = multimodalContent == null ? void 0 : multimodalContent[0];
const textPart = values[0] ? [{ text: values[0] }] : [];
const parts = valueParts != null ? [...textPart, ...valueParts] : [{ text: values[0] }];
const { responseHeaders: responseHeaders2, value: response2, rawValue: rawValue2 } = await postJsonToApi$2({
url: `${this.config.baseURL}/models/${this.modelId}:embedContent`,
headers: mergedHeaders,
body: {
model: `models/${this.modelId}`,
content: { parts },
outputDimensionality: googleOptions == null ? void 0 : googleOptions.outputDimensionality,
taskType: googleOptions == null ? void 0 : googleOptions.taskType
},
failedResponseHandler: googleFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$2(googleGenerativeAISingleEmbeddingResponseSchema),
abortSignal,
fetch: this.config.fetch
});
return {
warnings: [],
embeddings: [response2.embedding.values],
usage: void 0,
response: {
headers: responseHeaders2,
body: rawValue2
}
};
}
const { responseHeaders, value: response, rawValue } = await postJsonToApi$2({
url: `${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,
headers: mergedHeaders,
body: { requests: values.map((value, index) => {
const valueParts = multimodalContent == null ? void 0 : multimodalContent[index];
const textPart = value ? [{ text: value }] : [];
return {
model: `models/${this.modelId}`,
content: {
role: "user",
parts: valueParts != null ? [...textPart, ...valueParts] : [{ text: value }]
},
outputDimensionality: googleOptions == null ? void 0 : googleOptions.outputDimensionality,
taskType: googleOptions == null ? void 0 : googleOptions.taskType
};
}) },
failedResponseHandler: googleFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$2(googleGenerativeAITextEmbeddingResponseSchema),
abortSignal,
fetch: this.config.fetch
});
return {
warnings: [],
embeddings: response.embeddings.map((item) => item.values),
usage: void 0,
response: {
headers: responseHeaders,
body: rawValue
}
};
}
};
var googleGenerativeAITextEmbeddingResponseSchema = lazySchema$1(() => zodSchema$2(z.object({ embeddings: z.array(z.object({ values: z.array(z.number()) })) })));
var googleGenerativeAISingleEmbeddingResponseSchema = lazySchema$1(() => zodSchema$2(z.object({ embedding: z.object({ values: z.array(z.number()) }) })));
function validateMultimodalContentLength({ multimodalContent, values }) {
if (multimodalContent != null && multimodalContent.length !== values.length) throw new Error(`The number of multimodal content entries (${multimodalContent.length}) must match the number of values (${values.length}).`);
}
function continueGoogleStream({ stream, getContinuationToken, continueStream }) {
let reader = stream.getReader();
let pendingContinuationToken;
return new ReadableStream({
async pull(controller) {
while (true) {
const { done, value } = await reader.read();
if (!done) {
if (value.success) {
const token = getContinuationToken(value.value);
if (token != null) pendingContinuationToken = token;
}
controller.enqueue(value);
return;
}
if (pendingContinuationToken == null) {
controller.close();
return;
}
const continuationToken = pendingContinuationToken;
pendingContinuationToken = void 0;
try {
reader = (await continueStream(continuationToken)).getReader();
} catch (error) {
controller.enqueue({
success: false,
error,
rawValue: void 0
});
controller.close();
return;
}
}
},
async cancel(reason) {
await reader.cancel(reason);
}
});
}
function convertGoogleGenerativeAIUsage(usage) {
var _a2, _b, _c, _d;
if (usage == null) return {
inputTokens: {
total: void 0,
noCache: void 0,
cacheRead: void 0,
cacheWrite: void 0
},
outputTokens: {
total: void 0,
text: void 0,
reasoning: void 0
},
raw: void 0
};
const promptTokens = (_a2 = usage.promptTokenCount) != null ? _a2 : 0;
const candidatesTokens = (_b = usage.candidatesTokenCount) != null ? _b : 0;
const cachedContentTokens = (_c = usage.cachedContentTokenCount) != null ? _c : 0;
const thoughtsTokens = (_d = usage.thoughtsTokenCount) != null ? _d : 0;
return {
inputTokens: {
total: promptTokens,
noCache: promptTokens - cachedContentTokens,
cacheRead: cachedContentTokens,
cacheWrite: void 0
},
outputTokens: {
total: candidatesTokens + thoughtsTokens,
text: candidatesTokens,
reasoning: thoughtsTokens
},
raw: usage
};
}
function addGoogleGenerativeAIUsageMetadata(a, b) {
if (a == null || b == null) return b != null ? b : a;
return {
...a,
...b,
promptTokenCount: addCounts(a.promptTokenCount, b.promptTokenCount),
candidatesTokenCount: addCounts(a.candidatesTokenCount, b.candidatesTokenCount),
toolUsePromptTokenCount: addCounts(a.toolUsePromptTokenCount, b.toolUsePromptTokenCount),
totalTokenCount: addCounts(a.totalTokenCount, b.totalTokenCount),
cachedContentTokenCount: addCounts(a.cachedContentTokenCount, b.cachedContentTokenCount),
thoughtsTokenCount: addCounts(a.thoughtsTokenCount, b.thoughtsTokenCount),
promptTokensDetails: addTokenDetails(a.promptTokensDetails, b.promptTokensDetails),
cacheTokensDetails: addTokenDetails(a.cacheTokensDetails, b.cacheTokensDetails),
candidatesTokensDetails: addTokenDetails(a.candidatesTokensDetails, b.candidatesTokensDetails),
toolUsePromptTokensDetails: addTokenDetails(a.toolUsePromptTokensDetails, b.toolUsePromptTokensDetails)
};
}
function addCounts(a, b) {
return a == null && b == null ? b != null ? b : a : (a != null ? a : 0) + (b != null ? b : 0);
}
function addTokenDetails(a, b) {
var _a2;
if (a == null || b == null) return b != null ? b : a;
const tokenCounts = /* @__PURE__ */ new Map();
for (const { modality, tokenCount } of [...a, ...b]) tokenCounts.set(modality, ((_a2 = tokenCounts.get(modality)) != null ? _a2 : 0) + tokenCount);
return Array.from(tokenCounts, ([modality, tokenCount]) => ({
modality,
tokenCount
}));
}
var recursiveReferenceFunctionalityPrefix = "recursive JSON Schema reference:";
function isRecursiveJSONSchemaReferenceError(error) {
return UnsupportedFunctionalityError$2.isInstance(error) && error.functionality.startsWith(recursiveReferenceFunctionalityPrefix);
}
function convertJSONSchemaToOpenAPISchema(jsonSchema, isRoot = true) {
const rootSchema = typeof jsonSchema === "object" ? jsonSchema : void 0;
return convertJSONSchemaDefinition(jsonSchema, isRoot, {
definitions: rootSchema == null ? void 0 : rootSchema.definitions,
dollarDefinitions: rootSchema == null ? void 0 : rootSchema.$defs,
resolvingReferences: /* @__PURE__ */ new Set()
});
}
function convertJSONSchemaDefinition(jsonSchema, isRoot, referenceContext) {
if (jsonSchema == null) return;
if (typeof jsonSchema === "boolean") return {
type: "boolean",
properties: {}
};
if (jsonSchema.$ref != null) return convertJSONSchemaReference({
jsonSchema,
reference: jsonSchema.$ref,
isRoot,
referenceContext
});
if (isEmptyObjectSchema(jsonSchema)) {
if (isRoot) return;
if (jsonSchema.description) return {
type: "object",
description: jsonSchema.description
};
return { type: "object" };
}
const { type, description, required, properties, items, allOf, anyOf, oneOf, format, const: constValue, minLength, enum: enumValues } = jsonSchema;
const result = {};
if (description) result.description = description;
if (required) result.required = required;
if (format) result.format = format;
if (type) {
if (Array.isArray(type)) {
const hasNull = type.includes("null");
const nonNullTypes = type.filter((t) => t !== "null");
if (nonNullTypes.length === 0) result.type = "null";
else if (nonNullTypes.length === 1) {
result.type = nonNullTypes[0];
if (hasNull) result.nullable = true;
} else {
result.anyOf = nonNullTypes.map((t) => ({ type: t }));
if (hasNull) result.nullable = true;
}
} else result.type = type;
}
const values = enumValues != null ? enumValues : constValue !== void 0 ? [constValue] : void 0;
if (values !== void 0) addEnumToSchema({
values,
type,
result
});
if (properties != null) result.properties = Object.entries(properties).reduce((acc, [key, value]) => {
acc[key] = convertJSONSchemaDefinition(value, false, referenceContext);
return acc;
}, {});
if (items) result.items = Array.isArray(items) ? items.map((item) => convertJSONSchemaDefinition(item, false, referenceContext)) : convertJSONSchemaDefinition(items, false, referenceContext);
if (allOf) result.allOf = allOf.map((item) => convertJSONSchemaDefinition(item, false, referenceContext));
if (anyOf) {
if (anyOf.some((schema) => typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null")) {
const nonNullSchemas = anyOf.filter((schema) => !(typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null"));
if (nonNullSchemas.length === 1) {
const converted = convertJSONSchemaDefinition(nonNullSchemas[0], false, referenceContext);
if (typeof converted === "object") {
result.nullable = true;
Object.assign(result, converted);
}
} else {
result.anyOf = nonNullSchemas.map((item) => convertJSONSchemaDefinition(item, false, referenceContext));
result.nullable = true;
}
} else result.anyOf = anyOf.map((item) => convertJSONSchemaDefinition(item, false, referenceContext));
}
if (oneOf) result.oneOf = oneOf.map((item) => convertJSONSchemaDefinition(item, false, referenceContext));
if (minLength !== void 0) result.minLength = minLength;
return result;
}
function addEnumToSchema({ values, type, result }) {
const nullable = Array.isArray(type) && type.includes("null") || type === void 0 && values.includes(null);
const enumValues = nullable ? values.filter((value) => value !== null) : values;
if (values.length > 0 && values.every((value) => value === null)) {
if (type === void 0 || type === "null" || Array.isArray(type) && type.includes("null")) {
result.type = "null";
if (Array.isArray(type)) delete result.anyOf;
return;
}
}
const enumType = getEnumType({
values: enumValues,
type
});
if (enumType === void 0) throw new UnsupportedFunctionalityError$2({
functionality: "JSON Schema enum with mixed or unsupported values",
message: "Google does not support this JSON Schema enum. Enum values must share one supported primitive type and match the schema type."
});
result.type = enumType;
if (Array.isArray(type)) delete result.anyOf;
if (nullable) result.nullable = true;
if (enumType === "string") result.enum = enumValues;
else {
result.format = "enum";
result.enum = enumValues.map(String);
}
}
function getEnumType({ values, type }) {
if (values.length === 0) return;
const typeAllows = (enumType) => type === void 0 || type === enumType || Array.isArray(type) && type.includes(enumType);
if (typeAllows("string") && values.every((value) => typeof value === "string")) return "string";
if ((typeAllows("number") || typeAllows("integer")) && values.every((value) => typeof value === "number" && Number.isFinite(value))) {
if (typeAllows("number")) return "number";
if (values.every((value) => Number.isInteger(value))) return "integer";
}
if (typeAllows("boolean") && values.every((value) => typeof value === "boolean")) return "boolean";
}
function convertJSONSchemaReference({ jsonSchema, reference, isRoot, referenceContext }) {
const { definition, referenceKey } = getReferencedDefinition(reference, referenceContext);
if (referenceContext.resolvingReferences.has(referenceKey)) throw new UnsupportedFunctionalityError$2({
functionality: `${recursiveReferenceFunctionalityPrefix} ${reference}`,
message: "Google schema conversion does not support recursive JSON Schema references."
});
const resolvingReferences = new Set(referenceContext.resolvingReferences);
resolvingReferences.add(referenceKey);
const { $ref: _reference, ...siblingSchema } = jsonSchema;
return convertJSONSchemaDefinition(typeof definition === "boolean" ? definition ? siblingSchema : false : {
...definition,
...siblingSchema
}, isRoot, {
...referenceContext,
resolvingReferences
});
}
function getReferencedDefinition(reference, referenceContext) {
const source = [{
prefix: "#/$defs/",
definitions: referenceContext.dollarDefinitions
}, {
prefix: "#/definitions/",
definitions: referenceContext.definitions
}].find(({ prefix }) => reference.startsWith(prefix));
const encodedDefinitionName = source ? reference.slice(source.prefix.length) : void 0;
if (source == null || encodedDefinitionName == null || encodedDefinitionName.length === 0 || encodedDefinitionName.includes("/")) throwUnsupportedReference(reference);
let decodedDefinitionName;
try {
decodedDefinitionName = decodeURIComponent(encodedDefinitionName);
} catch (e) {
throwUnsupportedReference(reference);
}
if (decodedDefinitionName.includes("/") || /~(?![01])/u.test(decodedDefinitionName) || source.definitions == null) throwUnsupportedReference(reference);
const definitionName = decodedDefinitionName.replace(/~[01]/g, (match) => match === "~1" ? "/" : "~");
if (!Object.prototype.hasOwnProperty.call(source.definitions, definitionName)) throwUnsupportedReference(reference);
return {
definition: source.definitions[definitionName],
referenceKey: `${source.prefix}${definitionName}`
};
}
function throwUnsupportedReference(reference) {
throw new UnsupportedFunctionalityError$2({
functionality: `JSON Schema reference: ${reference}`,
message: "Google schema conversion only supports references to direct children of root-level $defs or definitions."
});
}
function isEmptyObjectSchema(jsonSchema) {
return jsonSchema != null && typeof jsonSchema === "object" && jsonSchema.type === "object" && (jsonSchema.properties == null || Object.keys(jsonSchema.properties).length === 0) && !jsonSchema.additionalProperties;
}
var googleVideoMetadataSchema = z.object({
/** Start offset as a duration in seconds, e.g. `'3.5s'`. */
startOffset: z.string().optional(),
/** End offset as a duration in seconds, e.g. `'10s'`. */
endOffset: z.string().optional(),
/** Frames per second in the range (0, 24]. Defaults to 1. */
fps: z.number().gt(0).max(24).optional()
});
var SKIP_THOUGHT_SIGNATURE_VALIDATOR = "skip_thought_signature_validator";
function getGoogleProviderOptions(providerOptions, providerOptionsName) {
const namespaces = [
providerOptionsName,
"google",
"googleVertex",
"vertex"
].filter((namespace, index, allNamespaces) => {
return allNamespaces.indexOf(namespace) === index;
});
for (const namespace of namespaces) {
const options = providerOptions == null ? void 0 : providerOptions[namespace];
if (options != null) return options;
}
}
var dataUrlRegex = /^data:([^;,]+);base64,(.+)$/s;
function parseBase64DataUrl(value) {
const match = dataUrlRegex.exec(value);
if (match == null) return;
return {
mediaType: match[1],
data: match[2]
};
}
function convertUrlToolResultPart(url, mediaType, supportedFunctionResponseUrls) {
const parsedDataUrl = parseBase64DataUrl(url);
if (parsedDataUrl != null) return { inlineData: {
mimeType: parsedDataUrl.mediaType,
data: parsedDataUrl.data
} };
return mediaType != null && isUrlSupported({
url,
mediaType,
supportedUrls: supportedFunctionResponseUrls
}) ? { fileData: {
mimeType: mediaType,
fileUri: url
} } : void 0;
}
function appendToolResultParts(parts, toolName, outputValue, toolCallId, includeFunctionCallIds = true, supportedFunctionResponseUrls = {}) {
const functionResponseParts = [];
const responseTextParts = [];
for (const contentPart of outputValue) switch (contentPart.type) {
case "text":
responseTextParts.push(contentPart.text);
break;
case "image-data":
case "file-data":
functionResponseParts.push({ inlineData: {
mimeType: contentPart.mediaType,
data: contentPart.data
} });
break;
case "image-url":
case "file-url": {
const functionResponsePart = convertUrlToolResultPart(contentPart.url, contentPart.mediaType, supportedFunctionResponseUrls);
if (functionResponsePart != null) functionResponseParts.push(functionResponsePart);
else responseTextParts.push(JSON.stringify(contentPart));
break;
}
default: responseTextParts.push(JSON.stringify(contentPart));
}
parts.push({ functionResponse: {
...includeFunctionCallIds && toolCallId != null ? { id: toolCallId } : {},
name: toolName,
response: {
name: toolName,
content: responseTextParts.length > 0 ? responseTextParts.join("\n") : "Tool executed successfully."
},
...functionResponseParts.length > 0 ? { parts: functionResponseParts } : {}
} });
}
function appendLegacyToolResultParts(parts, toolName, outputValue, toolCallId, includeFunctionCallIds = true) {
for (const contentPart of outputValue) switch (contentPart.type) {
case "text":
parts.push({ functionResponse: {
...includeFunctionCallIds && toolCallId != null ? { id: toolCallId } : {},
name: toolName,
response: {
name: toolName,
content: contentPart.text
}
} });
break;
case "image-data":
case "file-data": {
const topLevelMediaType = String(contentPart.mediaType).split("/")[0];
parts.push({ inlineData: {
mimeType: String(contentPart.mediaType),
data: String(contentPart.data)
} }, { text: `Tool executed successfully and returned this ${topLevelMediaType === "image" ? "image" : "file"} as a response` });
break;
}
default: parts.push({ text: JSON.stringify(contentPart) });
}
}
function convertToGoogleGenerativeAIMessages(prompt, options) {
var _a2, _b, _c, _d, _e, _f, _g, _h;
const systemInstructionParts = [];
const contents = [];
let systemMessagesAllowed = true;
const isGemmaModel = (_a2 = options == null ? void 0 : options.isGemmaModel) != null ? _a2 : false;
const isGemini3Model = (_b = options == null ? void 0 : options.isGemini3Model) != null ? _b : false;
const providerOptionsName = (_c = options == null ? void 0 : options.providerOptionsName) != null ? _c : "google";
const supportsFunctionResponseParts = (_d = options == null ? void 0 : options.supportsFunctionResponseParts) != null ? _d : true;
const onWarning = options == null ? void 0 : options.onWarning;
const includeFunctionCallIds = (_e = options == null ? void 0 : options.includeFunctionCallIds) != null ? _e : true;
const supportedFunctionResponseUrls = (_f = options == null ? void 0 : options.supportedFunctionResponseUrls) != null ? _f : {};
let sentinelInjected = false;
const missingSignatureToolNames = [];
const injectSkipSignature = (toolName) => {
missingSignatureToolNames.push(toolName);
sentinelInjected = true;
return SKIP_THOUGHT_SIGNATURE_VALIDATOR;
};
for (const { role, content } of prompt) switch (role) {
case "system":
if (!systemMessagesAllowed) throw new UnsupportedFunctionalityError$2({ functionality: "system messages are only supported at the beginning of the conversation" });
systemInstructionParts.push({ text: content });
break;
case "user": {
systemMessagesAllowed = false;
const parts = [];
for (const part of content) switch (part.type) {
case "text":
parts.push({ text: part.text });
break;
case "file": {
const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
const rawVideoMetadata = (_g = getGoogleProviderOptions(part.providerOptions, providerOptionsName)) == null ? void 0 : _g.videoMetadata;
const videoMetadata = rawVideoMetadata == null ? void 0 : googleVideoMetadataSchema.parse(rawVideoMetadata);
parts.push(part.data instanceof URL ? {
fileData: {
mimeType: mediaType,
fileUri: part.data.protocol === "gs:" && part.originalUrl != null ? part.originalUrl : part.data.toString()
},
...videoMetadata != null ? { videoMetadata } : {}
} : {
inlineData: {
mimeType: mediaType,
data: convertToBase64$1(part.data)
},
...videoMetadata != null ? { videoMetadata } : {}
});
break;
}
}
contents.push({
role: "user",
parts
});
break;
}
case "assistant": {
systemMessagesAllowed = false;
let modelResponseHasSignedFunctionCall = false;
contents.push({
role: "model",
parts: content.map((part) => {
const providerOpts = getGoogleProviderOptions(part.providerOptions, providerOptionsName);
const thoughtSignature = (providerOpts == null ? void 0 : providerOpts.thoughtSignature) != null ? String(providerOpts.thoughtSignature) : void 0;
switch (part.type) {
case "text": return part.text.length === 0 ? void 0 : {
text: part.text,
thoughtSignature
};
case "reasoning": return part.text.length === 0 ? void 0 : {
text: part.text,
thought: true,
thoughtSignature
};
case "file":
if (part.data instanceof URL) throw new UnsupportedFunctionalityError$2({ functionality: "File data URLs in assistant messages are not supported" });
return {
inlineData: {
mimeType: part.mediaType,
data: convertToBase64$1(part.data)
},
...(providerOpts == null ? void 0 : providerOpts.thought) === true ? { thought: true } : {},
thoughtSignature
};
case "tool-call": {
const serverToolCallId = (providerOpts == null ? void 0 : providerOpts.serverToolCallId) != null ? String(providerOpts.serverToolCallId) : void 0;
const serverToolType = (providerOpts == null ? void 0 : providerOpts.serverToolType) != null ? String(providerOpts.serverToolType) : void 0;
const isServerToolCall = serverToolCallId != null && serverToolType != null;
const effectiveThoughtSignature = thoughtSignature != null ? thoughtSignature : isGemini3Model && !(!isServerToolCall && thoughtSignature == null && modelResponseHasSignedFunctionCall) ? injectSkipSignature(part.toolName) : void 0;
if (!isServerToolCall && thoughtSignature != null) modelResponseHasSignedFunctionCall = true;
if (isServerToolCall) return {
toolCall: {
toolType: serverToolType,
args: typeof part.input === "string" ? secureJsonParse$2(part.input) : part.input,
id: serverToolCallId
},
thoughtSignature: effectiveThoughtSignature
};
return {
functionCall: {
...includeFunctionCallIds && part.toolCallId != null ? { id: part.toolCallId } : {},
name: part.toolName,
args: part.input
},
thoughtSignature: effectiveThoughtSignature
};
}
case "tool-result": {
const serverToolCallId = (providerOpts == null ? void 0 : providerOpts.serverToolCallId) != null ? String(providerOpts.serverToolCallId) : void 0;
const serverToolType = (providerOpts == null ? void 0 : providerOpts.serverToolType) != null ? String(providerOpts.serverToolType) : void 0;
if (serverToolCallId && serverToolType) return {
toolResponse: {
toolType: serverToolType,
response: part.output.type === "json" ? part.output.value : {},
id: serverToolCallId
},
thoughtSignature
};
return;
}
}
}).filter((part) => part !== void 0)
});
break;
}
case "tool": {
systemMessagesAllowed = false;
const parts = [];
for (const part of content) {
if (part.type === "tool-approval-response") continue;
const partProviderOpts = getGoogleProviderOptions(part.providerOptions, providerOptionsName);
const serverToolCallId = (partProviderOpts == null ? void 0 : partProviderOpts.serverToolCallId) != null ? String(partProviderOpts.serverToolCallId) : void 0;
const serverToolType = (partProviderOpts == null ? void 0 : partProviderOpts.serverToolType) != null ? String(partProviderOpts.serverToolType) : void 0;
if (serverToolCallId && serverToolType) {
const serverThoughtSignature = (partProviderOpts == null ? void 0 : partProviderOpts.thoughtSignature) != null ? String(partProviderOpts.thoughtSignature) : void 0;
if (contents.length > 0) {
const lastContent = contents[contents.length - 1];
if (lastContent.role === "model") {
lastContent.parts.push({
toolResponse: {
toolType: serverToolType,
response: part.output.type === "json" ? part.output.value : {},
id: serverToolCallId
},
thoughtSignature: serverThoughtSignature
});
continue;
}
}
}
const output = part.output;
if (output.type === "content") {
if (supportsFunctionResponseParts) appendToolResultParts(parts, part.toolName, output.value, part.toolCallId, includeFunctionCallIds, supportedFunctionResponseUrls);
else appendLegacyToolResultParts(parts, part.toolName, output.value, part.toolCallId, includeFunctionCallIds);
} else parts.push({ functionResponse: {
...includeFunctionCallIds && part.toolCallId != null ? { id: part.toolCallId } : {},
name: part.toolName,
response: {
name: part.toolName,
content: output.type === "execution-denied" ? (_h = output.reason) != null ? _h : "Tool call execution denied." : output.value
}
} });
}
contents.push({
role: "user",
parts
});
break;
}
}
if (isGemmaModel && systemInstructionParts.length > 0 && contents.length > 0 && contents[0].role === "user") {
const systemText = systemInstructionParts.map((part) => part.text).join("\n\n");
contents[0].parts.unshift({ text: systemText + "\n\n" });
}
if (sentinelInjected && onWarning != null) {
const uniqueToolNames = Array.from(new Set(missingSignatureToolNames));
onWarning({
type: "other",
message: `Replayed ${missingSignatureToolNames.length} \`functionCall\` part(s) for a Gemini 3 model without a \`thoughtSignature\` (tools: ${uniqueToolNames.map((name) => `\`${name}\``).join(", ")}). Injected the documented \`skip_thought_signature_validator\` sentinel to keep the request from failing with HTTP 400. The likely cause is application code that drops \`providerOptions.google.thoughtSignature\` when persisting or serializing assistant tool-call messages. See https://ai.google.dev/gemini-api/docs/thought-signatures.`
});
}
return {
systemInstruction: systemInstructionParts.length > 0 && !isGemmaModel ? { parts: systemInstructionParts } : void 0,
contents
};
}
async function downloadToolResultFiles(prompt, { abortSignal, supportedUrls = {} }) {
async function downloadOutput(output) {
if (output.type !== "content") return output;
return {
...output,
value: await Promise.all(output.value.map(async (part) => {
var _a2;
if (part.type !== "file-url" && part.type !== "image-url") return part;
if (part.type === "file-url" && part.mediaType != null && isUrlSupported({
url: part.url,
mediaType: part.mediaType,
supportedUrls
})) return part;
const blob = await downloadBlob$1(part.url, { abortSignal });
return {
type: part.type === "file-url" ? "file-data" : "image-data",
data: convertUint8ArrayToBase64$2(new Uint8Array(await blob.arrayBuffer())),
mediaType: blob.type || (part.type === "file-url" ? (_a2 = part.mediaType) != null ? _a2 : "application/octet-stream" : "image/*"),
providerOptions: part.providerOptions
};
}))
};
}
return Promise.all(prompt.map(async (message) => {
switch (message.role) {
case "assistant": return {
...message,
content: await Promise.all(message.content.map(async (part) => part.type === "tool-result" ? {
...part,
output: await downloadOutput(part.output)
} : part))
};
case "tool": return {
...message,
content: await Promise.all(message.content.map(async (part) => part.type === "tool-result" ? {
...part,
output: await downloadOutput(part.output)
} : part))
};
default: return message;
}
}));
}
function getModelPath(modelId) {
return modelId.includes("/") ? modelId : `models/${modelId}`;
}
var googleLanguageModelOptions = lazySchema$1(() => zodSchema$2(z.object({
responseModalities: z.array(z.enum(["TEXT", "IMAGE"])).optional(),
thinkingConfig: z.object({
thinkingBudget: z.number().optional(),
includeThoughts: z.boolean().optional(),
thinkingLevel: z.enum([
"minimal",
"low",
"medium",
"high"
]).optional()
}).optional(),
/**
* Optional.
* The name of the cached content used as context to serve the prediction.
* Format: cachedContents/{cachedContent}
*/
cachedContent: z.string().optional(),
/**
* Optional. Enable structured output. Default is true.
*
* This is useful when the JSON Schema contains elements that are
* not supported by the OpenAPI schema version that
* Google Generative AI uses. You can use this to disable
* structured outputs if you need to.
*/
structuredOutputs: z.boolean().optional(),
/**
* Optional. A list of unique safety settings for blocking unsafe content.
*/
safetySettings: z.array(z.object({
category: z.enum([
"HARM_CATEGORY_UNSPECIFIED",
"HARM_CATEGORY_HATE_SPEECH",
"HARM_CATEGORY_DANGEROUS_CONTENT",
"HARM_CATEGORY_HARASSMENT",
"HARM_CATEGORY_SEXUALLY_EXPLICIT",
"HARM_CATEGORY_CIVIC_INTEGRITY"
]),
threshold: z.enum([
"HARM_BLOCK_THRESHOLD_UNSPECIFIED",
"BLOCK_LOW_AND_ABOVE",
"BLOCK_MEDIUM_AND_ABOVE",
"BLOCK_ONLY_HIGH",
"BLOCK_NONE",
"OFF"
])
})).optional(),
threshold: z.enum([
"HARM_BLOCK_THRESHOLD_UNSPECIFIED",
"BLOCK_LOW_AND_ABOVE",
"BLOCK_MEDIUM_AND_ABOVE",
"BLOCK_ONLY_HIGH",
"BLOCK_NONE",
"OFF"
]).optional(),
/**
* Optional. Enables timestamp understanding for audio-only files.
*
* https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/audio-understanding
*/
audioTimestamp: z.boolean().optional(),
/**
* Optional. Defines labels used in billing reports. Available on Vertex AI only.
*
* https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/add-labels-to-api-calls
*/
labels: z.record(z.string(), z.string()).optional(),
/**
* Optional. If specified, the media resolution specified will be used.
*
* https://ai.google.dev/api/generate-content#MediaResolution
*/
mediaResolution: z.enum([
"MEDIA_RESOLUTION_UNSPECIFIED",
"MEDIA_RESOLUTION_LOW",
"MEDIA_RESOLUTION_MEDIUM",
"MEDIA_RESOLUTION_HIGH"
]).optional(),
/**
* Optional. Configures the image generation aspect ratio for Gemini models.
*
* https://ai.google.dev/gemini-api/docs/image-generation#aspect_ratios
*/
imageConfig: z.object({
aspectRatio: z.enum([
"1:1",
"2:3",
"3:2",
"3:4",
"4:3",
"4:5",
"5:4",
"9:16",
"16:9",
"21:9",
"1:8",
"8:1",
"1:4",
"4:1"
]).optional(),
imageSize: z.enum([
"1K",
"2K",
"4K",
"512"
]).optional(),
/**
* Optional. Controls the generation of people in images.
* Vertex AI only.
*/
personGeneration: z.enum([
"PERSON_GENERATION_UNSPECIFIED",
"ALLOW_ALL",
"ALLOW_ADULT",
"ALLOW_NONE"
]).optional(),
/**
* Optional. Controls whether generation of prominent people
* (celebrities) is allowed. When set together with
* `personGeneration`, `personGeneration` takes precedence.
* Vertex AI only.
*
* https://docs.cloud.google.com/vertex-ai/generative-ai/docs/reference/rest/v1/GenerationConfig
*/
prominentPeople: z.enum([
"PROMINENT_PEOPLE_UNSPECIFIED",
"ALLOW_PROMINENT_PEOPLE",
"BLOCK_PROMINENT_PEOPLE"
]).optional(),
/**
* Optional. The image output format for generated images.
* Vertex AI only.
*/
imageOutputOptions: z.object({
mimeType: z.enum(["image/jpeg", "image/png"]).optional(),
compressionQuality: z.number().optional()
}).optional()
}).optional(),
/**
* Optional. Configuration for grounding retrieval.
* Used to provide location context for Google Maps and Google Search grounding.
*
* https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps
*/
retrievalConfig: z.object({ latLng: z.object({
latitude: z.number(),
longitude: z.number()
}).optional() }).optional(),
/**
* Optional. When set to true, function call arguments will be streamed
* incrementally via partialArgs in streaming responses. Only supported
* on the Vertex AI API (not the Gemini API) and only for Gemini 3+
* models.
*
* @default false
*
* https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc
*/
streamFunctionCallArguments: z.boolean().optional(),
/**
* Optional. The service tier to use for the request. Sent as the
* `serviceTier` body field. Gemini API only.
*/
serviceTier: z.enum([
"standard",
"flex",
"priority"
]).optional(),
/**
* Optional. Resumes a response that stopped with `MAX_TOKENS` because it
* used up its `maxOutputTokens` budget (Gemini 4 long decode). Pass the
* `continuationToken` from the previous response's provider metadata
* together with the original prompt and a higher `maxOutputTokens` (the
* budget is cumulative across requests). Requests that reach the
* per-request cap while budget remains (`CONTINUATION`) are continued
* automatically. Sent as the `continuationToken` body field.
*/
continuationToken: z.string().optional(),
/**
* Optional. Vertex AI only. Sent as the
* `X-Vertex-AI-LLM-Shared-Request-Type` request header to select a
* shared (PayGo) tier. With Provisioned Throughput allocated and
* `requestType` unset, the request falls back to this tier only if
* PT capacity is exhausted.
*
* https://docs.cloud.google.com/vertex-ai/generative-ai/docs/priority-paygo
* https://docs.cloud.google.com/vertex-ai/generative-ai/docs/flex-paygo
*/
sharedRequestType: z.enum([
"priority",
"flex",
"standard"
]).optional(),
/**
* Optional. Vertex AI only. Sent as the `X-Vertex-AI-LLM-Request-Type`
* request header. Set to `'shared'` together with `sharedRequestType`
* to bypass Provisioned Throughput entirely.
*
* https://docs.cloud.google.com/vertex-ai/generative-ai/docs/priority-paygo
*/
requestType: z.enum(["shared"]).optional()
})));
var gemini1ModelPattern = /(^|\/)gemini-1(?:[.-]|$)/i;
var gemini2ModelPattern = /(^|\/)gemini-2(?:[.-]|$)/i;
var gemini25ModelPattern = /(^|\/)gemini-2\.5(?:[.-]|$)/i;
var geminiModelPattern = /(^|\/)gemini-/i;
function isKnownPreGemini2Model(modelId) {
return gemini1ModelPattern.test(modelId) || /(^|\/)gemini-pro(?:-vision)?$/i.test(modelId) || /(^|\/)gemini-robotics-er-1\.5(?:[.-]|$)/i.test(modelId);
}
function getGoogleModelCapabilities(modelId) {
const isGeminiModel2 = geminiModelPattern.test(modelId);
const isGemini2Model = gemini2ModelPattern.test(modelId);
const isKnownPreGemini2 = isKnownPreGemini2Model(modelId);
const usesGemini3Features = isGeminiModel2 && !(isKnownPreGemini2 || isGemini2Model);
return {
supportsGemini2Tools: isGeminiModel2 && !isKnownPreGemini2 || modelId.toLowerCase().includes("nano-banana"),
supportsFileSearch: gemini25ModelPattern.test(modelId) || usesGemini3Features,
usesGemini3Features
};
}
function prepareTools$2({ tools, toolChoice, modelId, isVertexProvider = false }) {
tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
const toolWarnings = [];
const { supportsGemini2Tools, supportsFileSearch, usesGemini3Features } = getGoogleModelCapabilities(modelId);
if (tools == null) return {
tools: void 0,
toolConfig: void 0,
toolWarnings
};
const hasFunctionTools = tools.some((tool) => tool.type === "function");
const hasProviderTools = tools.some((tool) => tool.type === "provider");
if (hasFunctionTools && hasProviderTools && !usesGemini3Features) toolWarnings.push({
type: "unsupported",
feature: `combination of function and provider-defined tools`
});
if (hasProviderTools) {
const googleTools2 = [];
tools.filter((tool) => tool.type === "provider").forEach((tool) => {
switch (tool.id) {
case "google.google_search":
if (supportsGemini2Tools) googleTools2.push({ googleSearch: { ...tool.args } });
else toolWarnings.push({
type: "unsupported",
feature: `provider-defined tool ${tool.id}`,
details: "Google Search requires Gemini 2.0 or newer."
});
break;
case "google.enterprise_web_search":
if (supportsGemini2Tools) googleTools2.push({ enterpriseWebSearch: {} });
else toolWarnings.push({
type: "unsupported",
feature: `provider-defined tool ${tool.id}`,
details: "Enterprise Web Search requires Gemini 2.0 or newer."
});
break;
case "google.url_context":
if (supportsGemini2Tools) googleTools2.push({ urlContext: {} });
else toolWarnings.push({
type: "unsupported",
feature: `provider-defined tool ${tool.id}`,
details: "The URL context tool is not supported with other Gemini models than Gemini 2."
});
break;
case "google.code_execution":
if (supportsGemini2Tools) googleTools2.push({ codeExecution: {} });
else toolWarnings.push({
type: "unsupported",
feature: `provider-defined tool ${tool.id}`,
details: "The code execution tool is not supported with other Gemini models than Gemini 2."
});
break;
case "google.file_search":
if (supportsFileSearch) googleTools2.push({ fileSearch: { ...tool.args } });
else toolWarnings.push({
type: "unsupported",
feature: `provider-defined tool ${tool.id}`,
details: "The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."
});
break;
case "google.vertex_rag_store":
if (supportsGemini2Tools) googleTools2.push({ retrieval: { vertex_rag_store: {
rag_resources: { rag_corpus: tool.args.ragCorpus },
similarity_top_k: tool.args.topK
} } });
else toolWarnings.push({
type: "unsupported",
feature: `provider-defined tool ${tool.id}`,
details: "The RAG store tool is not supported with other Gemini models than Gemini 2."
});
break;
case "google.google_maps":
if (supportsGemini2Tools) googleTools2.push({ googleMaps: {} });
else toolWarnings.push({
type: "unsupported",
feature: `provider-defined tool ${tool.id}`,
details: "The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."
});
break;
default: toolWarnings.push({
type: "unsupported",
feature: `provider-defined tool ${tool.id}`
});
}
});
if (hasFunctionTools && usesGemini3Features && googleTools2.length > 0) {
const functionDeclarations2 = [];
for (const tool of tools) if (tool.type === "function") functionDeclarations2.push(prepareFunctionDeclaration(tool));
const combinedToolConfig = {
functionCallingConfig: { mode: "VALIDATED" },
...!isVertexProvider && { includeServerSideToolInvocations: true }
};
if (toolChoice != null) switch (toolChoice.type) {
case "auto": break;
case "none":
combinedToolConfig.functionCallingConfig = { mode: "NONE" };
break;
case "required":
combinedToolConfig.functionCallingConfig = { mode: "ANY" };
break;
case "tool": combinedToolConfig.functionCallingConfig = {
mode: "ANY",
allowedFunctionNames: [toolChoice.toolName]
};
}
return {
tools: [...googleTools2, { functionDeclarations: functionDeclarations2 }],
toolConfig: combinedToolConfig,
toolWarnings
};
}
return {
tools: googleTools2.length > 0 ? googleTools2 : void 0,
toolConfig: void 0,
toolWarnings
};
}
const functionDeclarations = [];
let hasStrictTools = false;
for (const tool of tools) switch (tool.type) {
case "function":
functionDeclarations.push(prepareFunctionDeclaration(tool));
if (tool.strict === true) hasStrictTools = true;
break;
default: toolWarnings.push({
type: "unsupported",
feature: `function tool ${tool.name}`
});
}
if (toolChoice == null) return {
tools: [{ functionDeclarations }],
toolConfig: hasStrictTools ? { functionCallingConfig: { mode: "VALIDATED" } } : void 0,
toolWarnings
};
const type = toolChoice.type;
switch (type) {
case "auto": return {
tools: [{ functionDeclarations }],
toolConfig: { functionCallingConfig: { mode: hasStrictTools ? "VALIDATED" : "AUTO" } },
toolWarnings
};
case "none": return {
tools: [{ functionDeclarations }],
toolConfig: { functionCallingConfig: { mode: "NONE" } },
toolWarnings
};
case "required": return {
tools: [{ functionDeclarations }],
toolConfig: { functionCallingConfig: { mode: "ANY" } },
toolWarnings
};
case "tool": return {
tools: [{ functionDeclarations }],
toolConfig: { functionCallingConfig: {
mode: "ANY",
allowedFunctionNames: [toolChoice.toolName]
} },
toolWarnings
};
default: throw new UnsupportedFunctionalityError$2({ functionality: `tool choice type: ${type}` });
}
}
function prepareFunctionDeclaration(tool) {
var _a2;
const declaration = {
name: tool.name,
description: (_a2 = tool.description) != null ? _a2 : ""
};
try {
return {
...declaration,
parameters: convertJSONSchemaToOpenAPISchema(tool.inputSchema)
};
} catch (error) {
if (!isRecursiveJSONSchemaReferenceError(error)) throw error;
return {
...declaration,
parametersJsonSchema: tool.inputSchema
};
}
}
var GoogleJSONAccumulator = class {
constructor() {
this.accumulatedArgs = {};
this.jsonText = "";
/**
* Stack representing the currently "open" containers in the JSON output.
* Entry 0 is always the root `{` object once the first value is written.
*/
this.pathStack = [];
/**
* Whether a string value is currently "open" (willContinue was true),
* meaning the closing quote has not yet been emitted.
*/
this.stringOpen = false;
}
/**
* Input: [{jsonPath:"$.brightness",numberValue:50}]
* Output: { currentJSON:{brightness:50}, textDelta:'{"brightness":50' }
*/
processPartialArgs(partialArgs) {
let delta = "";
for (const arg of partialArgs) {
const isArrayTerminator = arg.jsonPath.endsWith("[]");
const rawPath = (isArrayTerminator ? arg.jsonPath.slice(0, -2) : arg.jsonPath).replace(/^\$\./, "");
if (!rawPath || rawPath === "$") continue;
const segments = parsePath(rawPath);
const existingValue = getNestedValue(this.accumulatedArgs, segments);
if (arg.stringValue != null && existingValue !== void 0) {
const escaped = JSON.stringify(arg.stringValue).slice(1, -1);
setNestedValue(this.accumulatedArgs, segments, existingValue + arg.stringValue);
delta += escaped;
continue;
}
const resolved = resolvePartialArgValue(arg);
if (resolved == null) {
if (existingValue !== void 0 || arg.willContinue === true) continue;
setNestedValue(this.accumulatedArgs, segments, isArrayTerminator ? [] : {});
delta += this.emitContainer(segments, isArrayTerminator);
continue;
}
setNestedValue(this.accumulatedArgs, segments, resolved.value);
delta += this.emitNavigationTo(segments, arg, resolved.json);
}
this.jsonText += delta;
return {
currentJSON: this.accumulatedArgs,
textDelta: delta
};
}
/**
* Input: jsonText='{"brightness":50', accumulatedArgs={brightness:50}
* Output: { finalJSON:'{"brightness":50}', closingDelta:'}' }
*/
finalize() {
const finalArgs = JSON.stringify(this.accumulatedArgs);
return {
finalJSON: finalArgs,
closingDelta: finalArgs.slice(this.jsonText.length)
};
}
/**
* Input: pathStack=[] (first call) or pathStack=[root,...] (subsequent calls)
* Output: '{' (first call) or '' (subsequent calls)
*/
ensureRoot() {
if (this.pathStack.length === 0) {
this.pathStack.push({
segment: "",
isArray: false,
childCount: 0
});
return "{";
}
return "";
}
/**
* Emits the JSON text fragment needed to navigate from the current open
* path to the new leaf at `targetSegments`, then writes the value.
*
* Input: targetSegments=["recipe","name"], arg={jsonPath:"$.recipe.name",stringValue:"Lasagna"}, valueJson='"Lasagna"'
* Output: '{"recipe":{"name":"Lasagna"'
*/
emitNavigationTo(targetSegments, arg, valueJson) {
let fragment = "";
if (this.stringOpen) {
fragment += "\"";
this.stringOpen = false;
}
fragment += this.ensureRoot();
const targetContainerSegments = targetSegments.slice(0, -1);
const leafSegment = targetSegments[targetSegments.length - 1];
const commonDepth = this.findCommonStackDepth(targetContainerSegments);
fragment += this.closeDownTo(commonDepth);
fragment += this.openDownTo(targetContainerSegments, leafSegment);
fragment += this.emitLeaf(leafSegment, arg, valueJson);
return fragment;
}
/**
* Navigates to `targetSegments` and opens a container there. The container
* stays open so later entries for its children continue inside it; it is
* closed by subsequent navigation or by `finalize()`.
*
* Input: targetSegments=["nested","tags"], isArray=true
* Output: '{"nested":{"tags":['
*/
emitContainer(targetSegments, isArray) {
let fragment = "";
if (this.stringOpen) {
fragment += "\"";
this.stringOpen = false;
}
fragment += this.ensureRoot();
const commonDepth = this.findCommonStackDepth(targetSegments);
fragment += this.closeDownTo(commonDepth);
fragment += this.openDownTo(targetSegments, isArray ? 0 : "");
return fragment;
}
/**
* Returns the stack depth to preserve when navigating to a new target
* container path. Always >= 1 (the root is never popped).
*
* Input: stack=[root,"recipe","ingredients",0], target=["recipe","ingredients",1]
* Output: 3 (keep root+"recipe"+"ingredients")
*/
findCommonStackDepth(targetContainer) {
const maxDepth = Math.min(this.pathStack.length - 1, targetContainer.length);
let common = 0;
for (let i = 0; i < maxDepth; i++) if (this.pathStack[i + 1].segment === targetContainer[i]) common++;
else break;
return common + 1;
}
/**
* Closes containers from the current stack depth back down to `targetDepth`.
*
* Input: this.pathStack=[root,"recipe","ingredients",0], targetDepth=3
* Output: '}'
*/
closeDownTo(targetDepth) {
let fragment = "";
while (this.pathStack.length > targetDepth) {
const entry = this.pathStack.pop();
fragment += entry.isArray ? "]" : "}";
}
return fragment;
}
/**
* Opens containers from the current stack depth down to the full target
* container path, emitting opening `{`, `[`, keys, and commas as needed.
* `leafSegment` is used to determine if the innermost container is an array.
*
* Input: this.pathStack=[root], targetContainer=["recipe","ingredients"], leafSegment=0
* Output: '"recipe":{"ingredients":['
*/
openDownTo(targetContainer, leafSegment) {
let fragment = "";
const startIdx = this.pathStack.length - 1;
for (let i = startIdx; i < targetContainer.length; i++) {
const seg = targetContainer[i];
const parentEntry = this.pathStack[this.pathStack.length - 1];
if (parentEntry.childCount > 0) fragment += ",";
parentEntry.childCount++;
if (typeof seg === "string") fragment += `${JSON.stringify(seg)}:`;
const isArray = typeof (i + 1 < targetContainer.length ? targetContainer[i + 1] : leafSegment) === "number";
fragment += isArray ? "[" : "{";
this.pathStack.push({
segment: seg,
isArray,
childCount: 0
});
}
return fragment;
}
/**
* Emits the comma, key, and value for a leaf entry in the current container.
*
* Input: leafSegment="name", arg={stringValue:"Lasagna"}, valueJson='"Lasagna"'
* Output: '"name":"Lasagna"' (or ',"name":"Lasagna"' if container.childCount > 0)
*/
emitLeaf(leafSegment, arg, valueJson) {
let fragment = "";
const container = this.pathStack[this.pathStack.length - 1];
if (container.childCount > 0) fragment += ",";
container.childCount++;
if (typeof leafSegment === "string") fragment += `${JSON.stringify(leafSegment)}:`;
if (arg.stringValue != null && arg.willContinue) {
fragment += valueJson.slice(0, -1);
this.stringOpen = true;
} else fragment += valueJson;
return fragment;
}
};
function parsePath(rawPath) {
const segments = [];
for (const part of rawPath.split(".")) {
const bracketIdx = part.indexOf("[");
if (bracketIdx === -1) segments.push(part);
else {
if (bracketIdx > 0) segments.push(part.slice(0, bracketIdx));
for (const m of part.matchAll(/\[(\d+)\]/g)) segments.push(parseInt(m[1], 10));
}
}
return segments;
}
var hasOwn = Object.prototype.hasOwnProperty;
function hasOwnProperty(obj, key) {
return hasOwn.call(obj, key);
}
function defineOwnProperty(obj, key, value) {
Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
}
function getNestedValue(obj, segments) {
let current = obj;
for (const seg of segments) {
if (current == null || typeof current !== "object") return void 0;
const currentRecord = current;
if (!hasOwnProperty(currentRecord, seg)) return void 0;
current = currentRecord[seg];
}
return current;
}
function setNestedValue(obj, segments, value) {
let current = obj;
for (let i = 0; i < segments.length - 1; i++) {
const seg = segments[i];
const nextSeg = segments[i + 1];
if (!hasOwnProperty(current, seg) || current[seg] == null) defineOwnProperty(current, seg, typeof nextSeg === "number" ? [] : {});
current = current[seg];
}
defineOwnProperty(current, segments[segments.length - 1], value);
}
function resolvePartialArgValue(arg) {
var _a2, _b;
const value = (_b = (_a2 = arg.stringValue) != null ? _a2 : arg.numberValue) != null ? _b : arg.boolValue;
if (value != null) return {
value,
json: JSON.stringify(value)
};
if ("nullValue" in arg) return {
value: null,
json: "null"
};
}
function mapGoogleGenerativeAIFinishReason({ finishReason, hasToolCalls }) {
switch (finishReason) {
case "STOP": return hasToolCalls ? "tool-calls" : "stop";
case "MAX_TOKENS":
case "CONTINUATION": return "length";
case "IMAGE_SAFETY":
case "RECITATION":
case "SAFETY":
case "BLOCKLIST":
case "PROHIBITED_CONTENT":
case "SPII": return "content-filter";
case "MALFORMED_FUNCTION_CALL": return "error";
default: return "other";
}
}
var configurableSafetySettingCategories = [
"HARM_CATEGORY_HATE_SPEECH",
"HARM_CATEGORY_DANGEROUS_CONTENT",
"HARM_CATEGORY_HARASSMENT",
"HARM_CATEGORY_SEXUALLY_EXPLICIT"
];
var gemini25ModelPattern2 = /(^|\/)gemini-2\.5(?:[.-]|$)/i;
var googleCloudStorageFunctionResponseUrls = {
"image/png": [/^gs:\/\/.*$/],
"image/jpeg": [/^gs:\/\/.*$/],
"image/webp": [/^gs:\/\/.*$/],
"application/pdf": [/^gs:\/\/.*$/],
"text/plain": [/^gs:\/\/.*$/]
};
var GoogleGenerativeAILanguageModel = class {
constructor(modelId, config) {
this.specificationVersion = "v3";
var _a2;
this.modelId = modelId;
this.config = config;
this.generateId = (_a2 = config.generateId) != null ? _a2 : generateId$2;
}
get provider() {
return this.config.provider;
}
get supportedUrls() {
var _a2, _b, _c;
return (_c = (_b = (_a2 = this.config).supportedUrls) == null ? void 0 : _b.call(_a2)) != null ? _c : {};
}
async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, responseFormat, seed, tools, toolChoice, providerOptions, abortSignal }, { isStreaming = false } = {}) {
var _a2, _b, _c;
const warnings = [];
const providerOptionsName = this.config.provider.includes("vertex") ? "vertex" : "google";
let googleOptions = await parseProviderOptions$1({
provider: providerOptionsName,
providerOptions,
schema: googleLanguageModelOptions
});
if (googleOptions == null && providerOptionsName !== "google") googleOptions = await parseProviderOptions$1({
provider: "google",
providerOptions,
schema: googleLanguageModelOptions
});
const isVertexProvider = this.config.provider.startsWith("google.vertex.");
if ((tools == null ? void 0 : tools.some((tool) => tool.type === "provider" && tool.id === "google.vertex_rag_store")) && !isVertexProvider) warnings.push({
type: "other",
message: `The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`
});
if ((googleOptions == null ? void 0 : googleOptions.streamFunctionCallArguments) && !isVertexProvider) warnings.push({
type: "other",
message: `'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${this.config.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`
});
if ((googleOptions == null ? void 0 : googleOptions.serviceTier) && isVertexProvider) warnings.push({
type: "other",
message: "'serviceTier' is a Gemini API option and is not supported on Vertex AI. Use 'sharedRequestType' (and optionally 'requestType') instead. See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/priority-paygo"
});
if (((googleOptions == null ? void 0 : googleOptions.sharedRequestType) || (googleOptions == null ? void 0 : googleOptions.requestType)) && !isVertexProvider) warnings.push({
type: "other",
message: `'sharedRequestType' and 'requestType' are Vertex AI options and are ignored with the current Google provider (${this.config.provider}).`
});
const vertexPaygoHeaders = isVertexProvider && ((googleOptions == null ? void 0 : googleOptions.sharedRequestType) || (googleOptions == null ? void 0 : googleOptions.requestType)) ? {
...googleOptions.sharedRequestType && { "X-Vertex-AI-LLM-Shared-Request-Type": googleOptions.sharedRequestType },
...googleOptions.requestType && { "X-Vertex-AI-LLM-Request-Type": googleOptions.requestType }
} : void 0;
const bodyServiceTier = isVertexProvider ? void 0 : googleOptions == null ? void 0 : googleOptions.serviceTier;
let imageConfig = googleOptions == null ? void 0 : googleOptions.imageConfig;
if (imageConfig != null && !isVertexProvider) {
const { personGeneration, prominentPeople, imageOutputOptions, ...geminiApiImageConfig } = imageConfig;
const droppedImageConfigFields = Object.entries({
personGeneration,
prominentPeople,
imageOutputOptions
}).filter(([, value]) => value != null).map(([key]) => `'imageConfig.${key}'`);
if (droppedImageConfigFields.length > 0) {
warnings.push({
type: "other",
message: `${droppedImageConfigFields.join(", ")} ${droppedImageConfigFields.length === 1 ? "is a Vertex AI option and is" : "are Vertex AI options and are"} ignored with the current Google provider (${this.config.provider}).`
});
imageConfig = geminiApiImageConfig;
}
}
const isGemmaModel = this.modelId.toLowerCase().startsWith("gemma-");
const isGemini25DeveloperApiModel = !isVertexProvider && gemini25ModelPattern2.test(this.modelId);
if (isGemini25DeveloperApiModel && frequencyPenalty != null) warnings.push({
type: "unsupported",
feature: "frequencyPenalty"
});
if (isGemini25DeveloperApiModel && presencePenalty != null) warnings.push({
type: "unsupported",
feature: "presencePenalty"
});
const { usesGemini3Features } = getGoogleModelCapabilities(this.modelId);
const supportedFunctionResponseUrls = usesGemini3Features && isVertexProvider ? googleCloudStorageFunctionResponseUrls : void 0;
const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages(isVertexProvider ? await downloadToolResultFiles(prompt, {
abortSignal,
supportedUrls: supportedFunctionResponseUrls
}) : prompt, {
isGemmaModel,
isGemini3Model: usesGemini3Features,
providerOptionsName,
supportsFunctionResponseParts: usesGemini3Features,
onWarning: (warning) => warnings.push(warning),
includeFunctionCallIds: !isVertexProvider,
supportedFunctionResponseUrls
});
const { tools: googleTools2, toolConfig: googleToolConfig, toolWarnings } = prepareTools$2({
tools,
toolChoice,
modelId: this.modelId,
isVertexProvider
});
const streamFunctionCallArguments = isStreaming && isVertexProvider ? (_a2 = googleOptions == null ? void 0 : googleOptions.streamFunctionCallArguments) != null ? _a2 : false : void 0;
const safetyThreshold = googleOptions == null ? void 0 : googleOptions.threshold;
const safetySettings = (_b = googleOptions == null ? void 0 : googleOptions.safetySettings) != null ? _b : safetyThreshold != null ? configurableSafetySettingCategories.map((category) => ({
category,
threshold: safetyThreshold
})) : void 0;
const toolConfig = googleToolConfig || streamFunctionCallArguments || (googleOptions == null ? void 0 : googleOptions.retrievalConfig) ? {
...googleToolConfig,
...streamFunctionCallArguments && { functionCallingConfig: {
...googleToolConfig == null ? void 0 : googleToolConfig.functionCallingConfig,
streamFunctionCallArguments: true
} },
...(googleOptions == null ? void 0 : googleOptions.retrievalConfig) && { retrievalConfig: googleOptions.retrievalConfig }
} : void 0;
return {
args: {
generationConfig: {
maxOutputTokens,
temperature,
topK,
topP,
frequencyPenalty: isGemini25DeveloperApiModel ? void 0 : frequencyPenalty,
presencePenalty: isGemini25DeveloperApiModel ? void 0 : presencePenalty,
stopSequences,
seed,
responseMimeType: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? "application/json" : void 0,
responseSchema: (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && ((_c = googleOptions == null ? void 0 : googleOptions.structuredOutputs) != null ? _c : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0,
...(googleOptions == null ? void 0 : googleOptions.audioTimestamp) && { audioTimestamp: googleOptions.audioTimestamp },
responseModalities: googleOptions == null ? void 0 : googleOptions.responseModalities,
thinkingConfig: googleOptions == null ? void 0 : googleOptions.thinkingConfig,
...(googleOptions == null ? void 0 : googleOptions.mediaResolution) && { mediaResolution: googleOptions.mediaResolution },
...imageConfig && { imageConfig }
},
contents,
systemInstruction: isGemmaModel ? void 0 : systemInstruction,
safetySettings,
tools: googleTools2,
toolConfig,
cachedContent: googleOptions == null ? void 0 : googleOptions.cachedContent,
labels: googleOptions == null ? void 0 : googleOptions.labels,
serviceTier: bodyServiceTier,
...(googleOptions == null ? void 0 : googleOptions.continuationToken) != null && { continuationToken: googleOptions.continuationToken }
},
warnings: [...warnings, ...toolWarnings],
providerOptionsName,
extraHeaders: vertexPaygoHeaders
};
}
async doGenerate(options) {
var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B;
const { args, warnings, providerOptionsName, extraHeaders } = await this.getArgs(options);
const mergedHeaders = combineHeaders$2(await resolve$1(this.config.headers), options.headers, extraHeaders);
const generateContent = (body) => postJsonToApi$2({
url: `${this.config.baseURL}/${getModelPath(this.modelId)}:generateContent`,
headers: mergedHeaders,
body,
failedResponseHandler: googleFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$2(responseSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
let { responseHeaders, value: response, rawValue: rawResponse } = await generateContent(args);
const continuedParts = [];
const groundingMetadataPerRequest = [];
let continuedUsageMetadata;
const firstPromptTokenCount = (_a2 = response.usageMetadata) == null ? void 0 : _a2.promptTokenCount;
while (true) {
const candidate2 = (_b = response.candidates) == null ? void 0 : _b[0];
groundingMetadataPerRequest.push((_c = candidate2 == null ? void 0 : candidate2.groundingMetadata) != null ? _c : null);
const continuationToken = (candidate2 == null ? void 0 : candidate2.finishReason) === "CONTINUATION" ? candidate2.continuationToken : void 0;
if (continuationToken == null) break;
continuedParts.push(...(_e = (_d = candidate2 == null ? void 0 : candidate2.content) == null ? void 0 : _d.parts) != null ? _e : []);
continuedUsageMetadata = addGoogleGenerativeAIUsageMetadata(continuedUsageMetadata, (_f = response.usageMetadata) != null ? _f : void 0);
({responseHeaders, value: response, rawValue: rawResponse} = await generateContent({
...args,
continuationToken
}));
}
const candidate = (_g = response.candidates) == null ? void 0 : _g[0];
const promptBlockReason = (_h = response.promptFeedback) == null ? void 0 : _h.blockReason;
const confirmedPromptBlockReason = isConfirmedPromptBlockReason(promptBlockReason) ? promptBlockReason : void 0;
const isPromptBlocked = (candidate == null ? void 0 : candidate.finishReason) == null && confirmedPromptBlockReason != null;
const rawFinishReason = (_i = candidate == null ? void 0 : candidate.finishReason) != null ? _i : confirmedPromptBlockReason;
const content = [];
const parts = [...continuedParts, ...(_k = (_j = candidate == null ? void 0 : candidate.content) == null ? void 0 : _j.parts) != null ? _k : []];
const usageMetadata = addGoogleGenerativeAIUsageMetadata(continuedUsageMetadata, (_l = response.usageMetadata) != null ? _l : void 0);
let lastCodeExecutionToolCallId;
let lastServerToolCallId;
for (const part of parts) if ("executableCode" in part && ((_m = part.executableCode) == null ? void 0 : _m.code)) {
const toolCallId = this.config.generateId();
lastCodeExecutionToolCallId = toolCallId;
content.push({
type: "tool-call",
toolCallId,
toolName: "code_execution",
input: JSON.stringify(part.executableCode),
providerExecuted: true
});
} else if ("codeExecutionResult" in part && part.codeExecutionResult) content.push({
type: "tool-result",
toolCallId: lastCodeExecutionToolCallId,
toolName: "code_execution",
result: {
outcome: part.codeExecutionResult.outcome,
output: (_n = part.codeExecutionResult.output) != null ? _n : ""
}
});
else if ("text" in part && part.text != null) {
const thoughtSignatureMetadata = part.thoughtSignature ? { [providerOptionsName]: { thoughtSignature: part.thoughtSignature } } : void 0;
if (part.text.length === 0) {
if (thoughtSignatureMetadata != null && content.length > 0) {
const lastContent = content[content.length - 1];
lastContent.providerMetadata = thoughtSignatureMetadata;
}
} else content.push({
type: part.thought === true ? "reasoning" : "text",
text: part.text,
providerMetadata: thoughtSignatureMetadata
});
} else if ("functionCall" in part && part.functionCall.name != null) content.push({
type: "tool-call",
toolCallId: (_o = part.functionCall.id) != null ? _o : this.config.generateId(),
toolName: part.functionCall.name,
input: JSON.stringify((_p = part.functionCall.args) != null ? _p : {}),
providerMetadata: part.thoughtSignature ? { [providerOptionsName]: { thoughtSignature: part.thoughtSignature } } : void 0
});
else if ("inlineData" in part) {
const hasThought = part.thought === true;
const hasThoughtSignature = !!part.thoughtSignature;
content.push({
type: "file",
data: part.inlineData.data,
mediaType: part.inlineData.mimeType,
providerMetadata: hasThought || hasThoughtSignature ? { [providerOptionsName]: {
...hasThought ? { thought: true } : {},
...hasThoughtSignature ? { thoughtSignature: part.thoughtSignature } : {}
} } : void 0
});
} else if ("toolCall" in part && part.toolCall) {
const toolCallId = (_q = part.toolCall.id) != null ? _q : this.config.generateId();
lastServerToolCallId = toolCallId;
content.push({
type: "tool-call",
toolCallId,
toolName: `server:${part.toolCall.toolType}`,
input: JSON.stringify((_r = part.toolCall.args) != null ? _r : {}),
providerExecuted: true,
dynamic: true,
providerMetadata: part.thoughtSignature ? { [providerOptionsName]: {
thoughtSignature: part.thoughtSignature,
serverToolCallId: toolCallId,
serverToolType: part.toolCall.toolType
} } : { [providerOptionsName]: {
serverToolCallId: toolCallId,
serverToolType: part.toolCall.toolType
} }
});
} else if ("toolResponse" in part && part.toolResponse) {
const responseToolCallId = (_s = lastServerToolCallId != null ? lastServerToolCallId : part.toolResponse.id) != null ? _s : this.config.generateId();
content.push({
type: "tool-result",
toolCallId: responseToolCallId,
toolName: `server:${part.toolResponse.toolType}`,
result: (_t = part.toolResponse.response) != null ? _t : {},
providerMetadata: part.thoughtSignature ? { [providerOptionsName]: {
thoughtSignature: part.thoughtSignature,
serverToolCallId: responseToolCallId,
serverToolType: part.toolResponse.toolType
} } : { [providerOptionsName]: {
serverToolCallId: responseToolCallId,
serverToolType: part.toolResponse.toolType
} }
});
lastServerToolCallId = void 0;
}
const sources = (_u = extractSources({
groundingMetadata: candidate == null ? void 0 : candidate.groundingMetadata,
generateId: this.config.generateId
})) != null ? _u : [];
for (const source of sources) content.push(source);
return {
content,
finishReason: {
unified: isPromptBlocked ? "content-filter" : mapGoogleGenerativeAIFinishReason({
finishReason: rawFinishReason,
hasToolCalls: content.some((part) => part.type === "tool-call" && !part.providerExecuted)
}),
raw: rawFinishReason
},
usage: convertGoogleGenerativeAIUsage(usageMetadata),
warnings,
providerMetadata: { [providerOptionsName]: {
promptFeedback: (_v = response.promptFeedback) != null ? _v : null,
groundingMetadata: (_w = candidate == null ? void 0 : candidate.groundingMetadata) != null ? _w : null,
...groundingMetadataPerRequest.length > 1 ? { groundingMetadataPerRequest } : {},
urlContextMetadata: (_x = candidate == null ? void 0 : candidate.urlContextMetadata) != null ? _x : null,
safetyRatings: (_y = candidate == null ? void 0 : candidate.safetyRatings) != null ? _y : null,
usageMetadata: usageMetadata != null ? usageMetadata : null,
finishMessage: (_z = candidate == null ? void 0 : candidate.finishMessage) != null ? _z : null,
serviceTier: (_A = usageMetadata == null ? void 0 : usageMetadata.serviceTier) != null ? _A : null,
...(candidate == null ? void 0 : candidate.continuationToken) != null && rawFinishReason === "MAX_TOKENS" ? { continuationToken: candidate.continuationToken } : {},
...continuedUsageMetadata != null && firstPromptTokenCount != null ? { initialPromptTokenCount: firstPromptTokenCount } : {}
} },
request: { body: args },
response: {
id: (_B = response.responseId) != null ? _B : void 0,
headers: responseHeaders,
body: rawResponse
}
};
}
async doStream(options) {
const { args, warnings, providerOptionsName, extraHeaders } = await this.getArgs(options, { isStreaming: true });
const headers = combineHeaders$2(await resolve$1(this.config.headers), options.headers, extraHeaders);
const streamGenerateContent = (body) => postJsonToApi$2({
url: `${this.config.baseURL}/${getModelPath(this.modelId)}:streamGenerateContent?alt=sse`,
headers,
body,
failedResponseHandler: googleFailedResponseHandler,
successfulResponseHandler: createEventSourceResponseHandler$2(chunkSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const { responseHeaders, value: firstResponse } = await streamGenerateContent(args);
const groundingMetadataPerRequest = [];
let requestGroundingMetadata = null;
const response = continueGoogleStream({
stream: firstResponse,
getContinuationToken: (chunk) => {
var _a2, _b;
const candidate = (_a2 = chunk.candidates) == null ? void 0 : _a2[0];
if ((candidate == null ? void 0 : candidate.groundingMetadata) != null) requestGroundingMetadata = candidate.groundingMetadata;
return (candidate == null ? void 0 : candidate.finishReason) === "CONTINUATION" ? (_b = candidate.continuationToken) != null ? _b : void 0 : void 0;
},
continueStream: async (continuationToken) => {
const { value } = await streamGenerateContent({
...args,
continuationToken
});
groundingMetadataPerRequest.push(requestGroundingMetadata);
requestGroundingMetadata = null;
return value;
}
});
let finishReason = {
unified: "other",
raw: void 0
};
let usage = void 0;
let continuedUsage = void 0;
let initialPromptTokenCount = void 0;
let promptFeedback = null;
let lastGroundingMetadata = null;
let lastUrlContextMetadata = null;
let lastSafetyRatings = null;
let lastFinishMessage = null;
let lastContinuationToken = null;
let confirmedPromptBlockReason;
const generateId3 = this.config.generateId;
let hasToolCalls = false;
let hasEmittedResponseMetadata = false;
let currentTextBlockId = null;
let currentReasoningBlockId = null;
let blockCounter = 0;
const emittedSourceUrls = /* @__PURE__ */ new Set();
let lastCodeExecutionToolCallId;
let lastServerToolCallId;
const activeStreamingToolCalls = [];
const finishActiveStreamingToolCall = (controller) => {
const active = activeStreamingToolCalls.pop();
if (active == null) return;
const { finalJSON, closingDelta } = active.accumulator.finalize();
if (closingDelta.length > 0) controller.enqueue({
type: "tool-input-delta",
id: active.toolCallId,
delta: closingDelta,
providerMetadata: active.providerMetadata
});
controller.enqueue({
type: "tool-input-end",
id: active.toolCallId,
providerMetadata: active.providerMetadata
});
controller.enqueue({
type: "tool-call",
toolCallId: active.toolCallId,
toolName: active.toolName,
input: finalJSON,
providerMetadata: active.providerMetadata
});
hasToolCalls = true;
};
return {
stream: response.pipeThrough(new TransformStream({
start(controller) {
controller.enqueue({
type: "stream-start",
warnings
});
},
transform(chunk, controller) {
var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
if (options.includeRawChunks) controller.enqueue({
type: "raw",
rawValue: chunk.rawValue
});
if (!chunk.success) {
controller.enqueue({
type: "error",
error: chunk.error
});
return;
}
const value = chunk.value;
if (!hasEmittedResponseMetadata && value.responseId != null) {
hasEmittedResponseMetadata = true;
controller.enqueue({
type: "response-metadata",
id: value.responseId
});
}
const usageMetadata = value.usageMetadata;
if (usageMetadata != null) usage = usageMetadata;
if (value.promptFeedback != null && confirmedPromptBlockReason == null) {
promptFeedback = value.promptFeedback;
if (isConfirmedPromptBlockReason(value.promptFeedback.blockReason)) {
confirmedPromptBlockReason = value.promptFeedback.blockReason;
finishReason = {
unified: "content-filter",
raw: confirmedPromptBlockReason
};
}
}
const candidate = (_a2 = value.candidates) == null ? void 0 : _a2[0];
if (candidate != null) {
if (candidate.groundingMetadata != null) lastGroundingMetadata = candidate.groundingMetadata;
if (candidate.urlContextMetadata != null) lastUrlContextMetadata = candidate.urlContextMetadata;
if (candidate.safetyRatings != null) lastSafetyRatings = candidate.safetyRatings;
if (candidate.finishMessage != null) lastFinishMessage = candidate.finishMessage;
if (candidate.continuationToken != null) lastContinuationToken = candidate.continuationToken;
}
if (confirmedPromptBlockReason != null || candidate == null) return;
const content = candidate.content;
const sources = extractSources({
groundingMetadata: candidate.groundingMetadata,
generateId: generateId3
});
if (sources != null) {
for (const source of sources) if (source.sourceType === "url" && !emittedSourceUrls.has(source.url)) {
emittedSourceUrls.add(source.url);
controller.enqueue(source);
}
}
if (content != null) {
const parts = (_b = content.parts) != null ? _b : [];
for (const part of parts) if ("executableCode" in part && ((_c = part.executableCode) == null ? void 0 : _c.code)) {
const toolCallId = generateId3();
lastCodeExecutionToolCallId = toolCallId;
controller.enqueue({
type: "tool-call",
toolCallId,
toolName: "code_execution",
input: JSON.stringify(part.executableCode),
providerExecuted: true
});
} else if ("codeExecutionResult" in part && part.codeExecutionResult) {
const toolCallId = lastCodeExecutionToolCallId;
if (toolCallId) controller.enqueue({
type: "tool-result",
toolCallId,
toolName: "code_execution",
result: {
outcome: part.codeExecutionResult.outcome,
output: (_d = part.codeExecutionResult.output) != null ? _d : ""
}
});
} else if ("text" in part && part.text != null) {
const thoughtSignatureMetadata = part.thoughtSignature ? { [providerOptionsName]: { thoughtSignature: part.thoughtSignature } } : void 0;
if (part.text.length === 0) {
if (thoughtSignatureMetadata != null && currentTextBlockId !== null) controller.enqueue({
type: "text-delta",
id: currentTextBlockId,
delta: "",
providerMetadata: thoughtSignatureMetadata
});
} else if (part.thought === true) {
if (currentTextBlockId !== null) {
controller.enqueue({
type: "text-end",
id: currentTextBlockId
});
currentTextBlockId = null;
}
if (currentReasoningBlockId === null) {
currentReasoningBlockId = String(blockCounter++);
controller.enqueue({
type: "reasoning-start",
id: currentReasoningBlockId,
providerMetadata: thoughtSignatureMetadata
});
}
controller.enqueue({
type: "reasoning-delta",
id: currentReasoningBlockId,
delta: part.text,
providerMetadata: thoughtSignatureMetadata
});
} else {
if (currentReasoningBlockId !== null) {
controller.enqueue({
type: "reasoning-end",
id: currentReasoningBlockId
});
currentReasoningBlockId = null;
}
if (currentTextBlockId === null) {
currentTextBlockId = String(blockCounter++);
controller.enqueue({
type: "text-start",
id: currentTextBlockId,
providerMetadata: thoughtSignatureMetadata
});
}
controller.enqueue({
type: "text-delta",
id: currentTextBlockId,
delta: part.text,
providerMetadata: thoughtSignatureMetadata
});
}
} else if ("inlineData" in part) {
if (currentTextBlockId !== null) {
controller.enqueue({
type: "text-end",
id: currentTextBlockId
});
currentTextBlockId = null;
}
if (currentReasoningBlockId !== null) {
controller.enqueue({
type: "reasoning-end",
id: currentReasoningBlockId
});
currentReasoningBlockId = null;
}
const hasThought = part.thought === true;
const hasThoughtSignature = !!part.thoughtSignature;
const fileMeta = hasThought || hasThoughtSignature ? { [providerOptionsName]: {
...hasThought ? { thought: true } : {},
...hasThoughtSignature ? { thoughtSignature: part.thoughtSignature } : {}
} } : void 0;
controller.enqueue({
type: "file",
mediaType: part.inlineData.mimeType,
data: part.inlineData.data,
providerMetadata: fileMeta
});
} else if ("toolCall" in part && part.toolCall) {
const toolCallId = (_e = part.toolCall.id) != null ? _e : generateId3();
lastServerToolCallId = toolCallId;
const serverMeta = { [providerOptionsName]: {
...part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {},
serverToolCallId: toolCallId,
serverToolType: part.toolCall.toolType
} };
controller.enqueue({
type: "tool-call",
toolCallId,
toolName: `server:${part.toolCall.toolType}`,
input: JSON.stringify((_f = part.toolCall.args) != null ? _f : {}),
providerExecuted: true,
dynamic: true,
providerMetadata: serverMeta
});
} else if ("toolResponse" in part && part.toolResponse) {
const responseToolCallId = (_g = lastServerToolCallId != null ? lastServerToolCallId : part.toolResponse.id) != null ? _g : generateId3();
const serverMeta = { [providerOptionsName]: {
...part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {},
serverToolCallId: responseToolCallId,
serverToolType: part.toolResponse.toolType
} };
controller.enqueue({
type: "tool-result",
toolCallId: responseToolCallId,
toolName: `server:${part.toolResponse.toolType}`,
result: (_h = part.toolResponse.response) != null ? _h : {},
providerMetadata: serverMeta
});
lastServerToolCallId = void 0;
}
for (const part of parts) {
if (!("functionCall" in part)) continue;
const providerMeta = part.thoughtSignature ? { [providerOptionsName]: { thoughtSignature: part.thoughtSignature } } : void 0;
const isStreamingChunk = part.functionCall.partialArgs != null || part.functionCall.name != null && part.functionCall.willContinue === true;
const isTerminalChunk = part.functionCall.name == null && part.functionCall.args == null && part.functionCall.partialArgs == null && part.functionCall.willContinue == null;
const isCompleteCall = part.functionCall.name != null && part.functionCall.args != null && part.functionCall.partialArgs == null;
const isNoArgsCompleteCall = part.functionCall.name != null && part.functionCall.args == null && part.functionCall.partialArgs == null && part.functionCall.willContinue !== true;
if (isStreamingChunk) {
if (part.functionCall.name != null) {
const toolCallId = (_i = part.functionCall.id) != null ? _i : generateId3();
const accumulator = new GoogleJSONAccumulator();
activeStreamingToolCalls.push({
toolCallId,
toolName: part.functionCall.name,
accumulator,
providerMetadata: providerMeta
});
controller.enqueue({
type: "tool-input-start",
id: toolCallId,
toolName: part.functionCall.name,
providerMetadata: providerMeta
});
if (part.functionCall.partialArgs != null) {
const partialArgs = part.functionCall.partialArgs;
const { textDelta } = accumulator.processPartialArgs(partialArgs);
if (textDelta.length > 0) controller.enqueue({
type: "tool-input-delta",
id: toolCallId,
delta: textDelta,
providerMetadata: providerMeta
});
if (part.functionCall.willContinue !== true && partialArgs.every((arg) => arg.willContinue !== true)) finishActiveStreamingToolCall(controller);
}
} else if (part.functionCall.partialArgs != null && activeStreamingToolCalls.length > 0) {
const active = activeStreamingToolCalls[activeStreamingToolCalls.length - 1];
const partialArgs = part.functionCall.partialArgs;
const { textDelta } = active.accumulator.processPartialArgs(partialArgs);
if (textDelta.length > 0) controller.enqueue({
type: "tool-input-delta",
id: active.toolCallId,
delta: textDelta,
providerMetadata: providerMeta
});
if (part.functionCall.willContinue !== true && partialArgs.every((arg) => arg.willContinue !== true)) finishActiveStreamingToolCall(controller);
}
} else if (isTerminalChunk && activeStreamingToolCalls.length > 0) finishActiveStreamingToolCall(controller);
else if (isCompleteCall) {
const toolCallId = (_j = part.functionCall.id) != null ? _j : generateId3();
const toolName = part.functionCall.name;
const args2 = typeof part.functionCall.args === "string" ? part.functionCall.args : JSON.stringify((_k = part.functionCall.args) != null ? _k : {});
controller.enqueue({
type: "tool-input-start",
id: toolCallId,
toolName,
providerMetadata: providerMeta
});
controller.enqueue({
type: "tool-input-delta",
id: toolCallId,
delta: args2,
providerMetadata: providerMeta
});
controller.enqueue({
type: "tool-input-end",
id: toolCallId,
providerMetadata: providerMeta
});
controller.enqueue({
type: "tool-call",
toolCallId,
toolName,
input: args2,
providerMetadata: providerMeta
});
hasToolCalls = true;
} else if (isNoArgsCompleteCall) {
const toolCallId = (_l = part.functionCall.id) != null ? _l : generateId3();
const toolName = part.functionCall.name;
controller.enqueue({
type: "tool-input-start",
id: toolCallId,
toolName,
providerMetadata: providerMeta
});
controller.enqueue({
type: "tool-input-end",
id: toolCallId,
providerMetadata: providerMeta
});
controller.enqueue({
type: "tool-call",
toolCallId,
toolName,
input: "{}",
providerMetadata: providerMeta
});
hasToolCalls = true;
}
}
}
if (candidate.finishReason === "CONTINUATION") {
if (continuedUsage == null) initialPromptTokenCount = usage == null ? void 0 : usage.promptTokenCount;
continuedUsage = addGoogleGenerativeAIUsageMetadata(continuedUsage, usage);
usage = void 0;
}
if (candidate.finishReason != null) finishReason = {
unified: mapGoogleGenerativeAIFinishReason({
finishReason: candidate.finishReason,
hasToolCalls
}),
raw: candidate.finishReason
};
},
flush(controller) {
var _a2;
usage = addGoogleGenerativeAIUsageMetadata(continuedUsage, usage);
if (currentTextBlockId !== null) controller.enqueue({
type: "text-end",
id: currentTextBlockId
});
if (currentReasoningBlockId !== null) controller.enqueue({
type: "reasoning-end",
id: currentReasoningBlockId
});
controller.enqueue({
type: "finish",
finishReason,
usage: convertGoogleGenerativeAIUsage(usage),
providerMetadata: { [providerOptionsName]: {
promptFeedback,
groundingMetadata: lastGroundingMetadata,
...groundingMetadataPerRequest.length > 0 ? { groundingMetadataPerRequest: [...groundingMetadataPerRequest, requestGroundingMetadata] } : {},
urlContextMetadata: lastUrlContextMetadata,
safetyRatings: lastSafetyRatings,
usageMetadata: usage != null ? usage : null,
finishMessage: lastFinishMessage,
serviceTier: (_a2 = usage == null ? void 0 : usage.serviceTier) != null ? _a2 : null,
...lastContinuationToken != null && (finishReason.raw === "MAX_TOKENS" || finishReason.raw === "CONTINUATION") ? { continuationToken: lastContinuationToken } : {},
...initialPromptTokenCount != null ? { initialPromptTokenCount } : {}
} }
});
}
})),
response: { headers: responseHeaders },
request: { body: args }
};
}
};
function extractSources({ groundingMetadata, generateId: generateId3 }) {
var _a2, _b, _c, _d, _e, _f;
if (!(groundingMetadata == null ? void 0 : groundingMetadata.groundingChunks)) return;
const sources = [];
for (const chunk of groundingMetadata.groundingChunks) if (chunk.web != null) sources.push({
type: "source",
sourceType: "url",
id: generateId3(),
url: chunk.web.uri,
title: (_a2 = chunk.web.title) != null ? _a2 : void 0
});
else if (chunk.image != null) sources.push({
type: "source",
sourceType: "url",
id: generateId3(),
url: chunk.image.sourceUri,
title: (_b = chunk.image.title) != null ? _b : void 0
});
else if (chunk.retrievedContext != null) {
const uri = chunk.retrievedContext.uri;
const fileSearchStore = chunk.retrievedContext.fileSearchStore;
if (uri && (uri.startsWith("http://") || uri.startsWith("https://"))) sources.push({
type: "source",
sourceType: "url",
id: generateId3(),
url: uri,
title: (_c = chunk.retrievedContext.title) != null ? _c : void 0
});
else if (uri) {
const title = (_d = chunk.retrievedContext.title) != null ? _d : "Unknown Document";
let mediaType = "application/octet-stream";
let filename = void 0;
if (uri.endsWith(".pdf")) {
mediaType = "application/pdf";
filename = uri.split("/").pop();
} else if (uri.endsWith(".txt")) {
mediaType = "text/plain";
filename = uri.split("/").pop();
} else if (uri.endsWith(".docx")) {
mediaType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
filename = uri.split("/").pop();
} else if (uri.endsWith(".doc")) {
mediaType = "application/msword";
filename = uri.split("/").pop();
} else if (uri.match(/\.(md|markdown)$/)) {
mediaType = "text/markdown";
filename = uri.split("/").pop();
} else filename = uri.split("/").pop();
sources.push({
type: "source",
sourceType: "document",
id: generateId3(),
mediaType,
title,
filename
});
} else if (fileSearchStore) {
const title = (_e = chunk.retrievedContext.title) != null ? _e : "Unknown Document";
sources.push({
type: "source",
sourceType: "document",
id: generateId3(),
mediaType: "application/octet-stream",
title,
filename: fileSearchStore.split("/").pop()
});
}
} else if (chunk.maps != null) {
if (chunk.maps.uri) sources.push({
type: "source",
sourceType: "url",
id: generateId3(),
url: chunk.maps.uri,
title: (_f = chunk.maps.title) != null ? _f : void 0
});
}
return sources.length > 0 ? sources : void 0;
}
var getGroundingMetadataSchema = () => z.object({
webSearchQueries: z.array(z.string()).nullish(),
imageSearchQueries: z.array(z.string()).nullish(),
retrievalQueries: z.array(z.string()).nullish(),
searchEntryPoint: z.object({ renderedContent: z.string() }).nullish(),
groundingChunks: z.array(z.object({
web: z.object({
uri: z.string(),
title: z.string().nullish()
}).nullish(),
image: z.object({
sourceUri: z.string(),
imageUri: z.string(),
title: z.string().nullish(),
domain: z.string().nullish()
}).nullish(),
retrievedContext: z.object({
uri: z.string().nullish(),
title: z.string().nullish(),
text: z.string().nullish(),
fileSearchStore: z.string().nullish(),
customMetadata: z.array(z.object({
key: z.string(),
stringValue: z.string().nullish(),
numericValue: z.number().nullish(),
stringListValue: z.object({ values: z.array(z.string()).nullish() }).nullish()
})).nullish()
}).nullish(),
maps: z.object({
uri: z.string().nullish(),
title: z.string().nullish(),
text: z.string().nullish(),
placeId: z.string().nullish()
}).nullish()
})).nullish(),
groundingSupports: z.array(z.object({
segment: z.object({
startIndex: z.number().nullish(),
endIndex: z.number().nullish(),
text: z.string().nullish()
}).nullish(),
segment_text: z.string().nullish(),
groundingChunkIndices: z.array(z.number()).nullish(),
supportChunkIndices: z.array(z.number()).nullish(),
confidenceScores: z.array(z.number()).nullish(),
confidenceScore: z.array(z.number()).nullish()
})).nullish(),
retrievalMetadata: z.union([z.object({ webDynamicRetrievalScore: z.number() }), z.object({})]).nullish()
});
var partialArgSchema = () => z.object({
jsonPath: z.string(),
stringValue: z.string().nullish(),
numberValue: z.number().nullish(),
boolValue: z.boolean().nullish(),
nullValue: z.unknown().nullish(),
willContinue: z.boolean().nullish()
});
var getContentSchema = () => z.object({ parts: z.array(z.union([
z.object({
functionCall: z.object({
id: z.string().nullish(),
name: z.string().nullish(),
args: z.unknown().nullish(),
partialArgs: z.array(partialArgSchema()).nullish(),
willContinue: z.boolean().nullish()
}),
thoughtSignature: z.string().nullish()
}),
z.object({
inlineData: z.object({
mimeType: z.string(),
data: z.string()
}),
thought: z.boolean().nullish(),
thoughtSignature: z.string().nullish()
}),
z.object({
toolCall: z.object({
toolType: z.string(),
args: z.unknown().nullish(),
id: z.string()
}),
thoughtSignature: z.string().nullish()
}),
z.object({
toolResponse: z.object({
toolType: z.string(),
response: z.unknown().nullish(),
id: z.string()
}),
thoughtSignature: z.string().nullish()
}),
z.object({
executableCode: z.object({
language: z.string(),
code: z.string()
}).nullish(),
codeExecutionResult: z.object({
outcome: z.string(),
output: z.string().nullish()
}).nullish(),
text: z.string().nullish(),
thought: z.boolean().nullish(),
thoughtSignature: z.string().nullish()
})
])).nullish() });
var getSafetyRatingSchema = () => z.object({
category: z.string().nullish(),
probability: z.string().nullish(),
probabilityScore: z.number().nullish(),
severity: z.string().nullish(),
severityScore: z.number().nullish(),
blocked: z.boolean().nullish()
});
var tokenDetailsSchema = () => z.array(z.object({
modality: z.string(),
tokenCount: z.number()
}).catchall(z.json())).nullish();
var usageSchema = () => z.object({
cachedContentTokenCount: z.number().nullish(),
thoughtsTokenCount: z.number().nullish(),
promptTokenCount: z.number().nullish(),
candidatesTokenCount: z.number().nullish(),
toolUsePromptTokenCount: z.number().nullish(),
totalTokenCount: z.number().nullish(),
trafficType: z.string().nullish(),
serviceTier: z.string().nullish(),
promptTokensDetails: tokenDetailsSchema(),
cacheTokensDetails: tokenDetailsSchema(),
candidatesTokensDetails: tokenDetailsSchema(),
toolUsePromptTokensDetails: tokenDetailsSchema()
}).catchall(z.json());
var getUrlContextMetadataSchema = () => z.object({ urlMetadata: z.array(z.object({
retrievedUrl: z.string(),
urlRetrievalStatus: z.string()
})).nullish() });
var responseSchema = lazySchema$1(() => zodSchema$2(z.object({
responseId: z.string().nullish(),
candidates: z.array(z.object({
content: getContentSchema().nullish().or(z.object({}).strict()),
finishReason: z.string().nullish(),
finishMessage: z.string().nullish(),
continuationToken: z.string().nullish(),
safetyRatings: z.array(getSafetyRatingSchema()).nullish(),
groundingMetadata: getGroundingMetadataSchema().nullish(),
urlContextMetadata: getUrlContextMetadataSchema().nullish()
})).nullish(),
usageMetadata: usageSchema().nullish(),
promptFeedback: z.object({
blockReason: z.string().nullish(),
safetyRatings: z.array(getSafetyRatingSchema()).nullish()
}).nullish()
})));
var chunkSchema = lazySchema$1(() => zodSchema$2(z.object({
responseId: z.string().nullish(),
candidates: z.array(z.object({
content: getContentSchema().nullish(),
finishReason: z.string().nullish(),
finishMessage: z.string().nullish(),
continuationToken: z.string().nullish(),
safetyRatings: z.array(getSafetyRatingSchema()).nullish(),
groundingMetadata: getGroundingMetadataSchema().nullish(),
urlContextMetadata: getUrlContextMetadataSchema().nullish()
})).nullish(),
usageMetadata: usageSchema().nullish(),
promptFeedback: z.object({
blockReason: z.string().nullish(),
safetyRatings: z.array(getSafetyRatingSchema()).nullish()
}).nullish()
})));
function isConfirmedPromptBlockReason(blockReason) {
return blockReason != null && blockReason !== "" && blockReason !== "BLOCK_REASON_UNSPECIFIED" && blockReason !== "BLOCKED_REASON_UNSPECIFIED";
}
var codeExecution$1 = createProviderToolFactoryWithOutputSchema({
id: "google.code_execution",
inputSchema: z.object({
language: z.string().describe("The programming language of the code."),
code: z.string().describe("The code to be executed.")
}),
outputSchema: z.object({
outcome: z.string().describe("The outcome of the execution (e.g., \"OUTCOME_OK\")."),
output: z.string().describe("The output from the code execution.")
})
});
var enterpriseWebSearch = createProviderToolFactory$1({
id: "google.enterprise_web_search",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({})))
});
var fileSearchArgsBaseSchema = () => z.object({
/** The names of the file_search_stores to retrieve from.
* Example: `fileSearchStores/my-file-search-store-123`
*/
fileSearchStoreNames: z.array(z.string()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),
/** The number of file search retrieval chunks to retrieve. */
topK: z.number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),
/** Metadata filter to apply to the file search retrieval documents.
* See https://google.aip.dev/160 for the syntax of the filter expression.
*/
metadataFilter: z.string().describe("Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression.").optional()
}).passthrough();
var fileSearch$1 = createProviderToolFactory$1({
id: "google.file_search",
inputSchema: lazySchema$1(() => zodSchema$2(fileSearchArgsBaseSchema()))
});
var googleMaps = createProviderToolFactory$1({
id: "google.google_maps",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({})))
});
var googleSearchToolArgsBaseSchema = () => z.object({
searchTypes: z.object({
webSearch: z.object({}).optional(),
imageSearch: z.object({}).optional()
}).optional(),
timeRangeFilter: z.object({
startTime: z.string(),
endTime: z.string()
}).optional()
}).passthrough();
var googleTools = {
/**
* Creates a Google search tool that gives Google direct access to real-time web content.
* Must have name "google_search".
*/
googleSearch: createProviderToolFactory$1({
id: "google.google_search",
inputSchema: lazySchema$1(() => zodSchema$2(googleSearchToolArgsBaseSchema()))
}),
/**
* Creates an Enterprise Web Search tool for grounding responses using a compliance-focused web index.
* Designed for highly-regulated industries (finance, healthcare, public sector).
* Does not log customer data and supports VPC service controls.
* Must have name "enterprise_web_search".
*
* @note Only available on Vertex AI. Requires Gemini 2.0 or newer.
*
* @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/web-grounding-enterprise
*/
enterpriseWebSearch,
/**
* Creates a Google Maps grounding tool that gives the model access to Google Maps data.
* Must have name "google_maps".
*
* @see https://ai.google.dev/gemini-api/docs/maps-grounding
* @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps
*/
googleMaps,
/**
* Creates a URL context tool that gives Google direct access to real-time web content.
* Must have name "url_context".
*/
urlContext: createProviderToolFactory$1({
id: "google.url_context",
inputSchema: lazySchema$1(() => zodSchema$2(z.object({})))
}),
/**
* Enables Retrieval Augmented Generation (RAG) via the Gemini File Search tool.
* Must have name "file_search".
*
* @param fileSearchStoreNames - Fully-qualified File Search store resource names.
* @param metadataFilter - Optional filter expression to restrict the files that can be retrieved.
* @param topK - Optional result limit for the number of chunks returned from File Search.
*
* @see https://ai.google.dev/gemini-api/docs/file-search
*/
fileSearch: fileSearch$1,
/**
* A tool that enables the model to generate and run Python code.
* Must have name "code_execution".
*
* @note Ensure the selected model supports Code Execution.
* Multi-tool usage with the code execution tool is typically compatible with Gemini >=2 models.
*
* @see https://ai.google.dev/gemini-api/docs/code-execution (Google AI)
* @see https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/code-execution-api (Vertex AI)
*/
codeExecution: codeExecution$1,
/**
* Creates a Vertex RAG Store tool that enables the model to perform RAG searches against a Vertex RAG Store.
* Must have name "vertex_rag_store".
*/
vertexRagStore: createProviderToolFactory$1({
id: "google.vertex_rag_store",
inputSchema: z.object({
ragCorpus: z.string(),
topK: z.number().optional()
})
})
};
var GoogleGenerativeAIImageModel = class {
constructor(modelId, settings, config) {
this.modelId = modelId;
this.settings = settings;
this.config = config;
this.specificationVersion = "v3";
}
get maxImagesPerCall() {
if (this.settings.maxImagesPerCall != null) return this.settings.maxImagesPerCall;
if (isGeminiModel(this.modelId)) return 10;
return 4;
}
get provider() {
return this.config.provider;
}
async doGenerate(options) {
if (isGeminiModel(this.modelId)) return this.doGenerateGemini(options);
return this.doGenerateImagen(options);
}
async doGenerateImagen(options) {
var _a2, _b, _c;
const { prompt, n = 1, size, aspectRatio = "1:1", seed, providerOptions, headers, abortSignal, files, mask } = options;
const warnings = [];
if (files != null && files.length > 0) throw new Error("Google Generative AI does not support image editing with Imagen models. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.");
if (mask != null) throw new Error("Google Generative AI does not support image editing with masks. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.");
if (size != null) warnings.push({
type: "unsupported",
feature: "size",
details: "This model does not support the `size` option. Use `aspectRatio` instead."
});
if (seed != null) warnings.push({
type: "unsupported",
feature: "seed",
details: "This model does not support the `seed` option through this provider."
});
const googleOptions = await parseProviderOptions$1({
provider: "google",
providerOptions,
schema: googleImageModelOptionsSchema
});
const currentDate = (_c = (_b = (_a2 = this.config._internal) == null ? void 0 : _a2.currentDate) == null ? void 0 : _b.call(_a2)) != null ? _c : /* @__PURE__ */ new Date();
const parameters = { sampleCount: n };
if (aspectRatio != null) parameters.aspectRatio = aspectRatio;
if (googleOptions) {
const { googleSearch: imagenGoogleSearch, ...imagenOptions } = googleOptions;
if (imagenGoogleSearch != null) warnings.push({
type: "unsupported",
feature: "googleSearch",
details: "Google Search grounding is only supported on Gemini image models."
});
Object.assign(parameters, imagenOptions);
}
const body = {
instances: [{ prompt }],
parameters
};
const { responseHeaders, value: response } = await postJsonToApi$2({
url: `${this.config.baseURL}/models/${this.modelId}:predict`,
headers: combineHeaders$2(await resolve$1(this.config.headers), headers),
body,
failedResponseHandler: googleFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$2(googleImageResponseSchema),
abortSignal,
fetch: this.config.fetch
});
const imagePredictions = response.predictions.filter((prediction) => "bytesBase64Encoded" in prediction);
return {
images: imagePredictions.map(({ bytesBase64Encoded }) => bytesBase64Encoded),
...response.predictions.some((prediction) => "raiFilteredReason" in prediction) && { isRetryable: false },
warnings,
providerMetadata: { google: { images: imagePredictions.map(() => ({})) } },
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders
}
};
}
async doGenerateGemini(options) {
var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
const { prompt, n, size, aspectRatio, seed, providerOptions, headers, abortSignal, files, mask } = options;
const warnings = [];
if (mask != null) throw new Error("Gemini image models do not support mask-based image editing.");
if (n != null && n > 1) throw new Error("Gemini image models do not support generating a set number of images per call. Use n=1 or omit the n parameter.");
if (size != null) warnings.push({
type: "unsupported",
feature: "size",
details: "This model does not support the `size` option. Use `aspectRatio` instead."
});
const userContent = [];
if (prompt != null) userContent.push({
type: "text",
text: prompt
});
if (files != null && files.length > 0) for (const file of files) if (file.type === "url") userContent.push({
type: "file",
data: new URL(file.url),
mediaType: "image/*"
});
else userContent.push({
type: "file",
data: typeof file.data === "string" ? file.data : new Uint8Array(file.data),
mediaType: file.mediaType
});
const languageModelPrompt = [{
role: "user",
content: userContent
}];
const googleImageOptions = await parseProviderOptions$1({
provider: "google",
providerOptions,
schema: googleImageModelOptionsSchema
});
const { googleSearch: _strippedGoogleSearch, ...passthroughGoogleOptions } = (_a2 = providerOptions == null ? void 0 : providerOptions.google) != null ? _a2 : {};
const result = await new GoogleGenerativeAILanguageModel(this.modelId, {
provider: this.config.provider,
baseURL: this.config.baseURL,
headers: (_b = this.config.headers) != null ? _b : {},
fetch: this.config.fetch,
generateId: (_c = this.config.generateId) != null ? _c : generateId$2
}).doGenerate({
prompt: languageModelPrompt,
seed,
providerOptions: { google: {
responseModalities: ["IMAGE"],
imageConfig: aspectRatio ? { aspectRatio } : void 0,
...passthroughGoogleOptions
} },
tools: (googleImageOptions == null ? void 0 : googleImageOptions.googleSearch) != null ? [{
type: "provider",
id: "google.google_search",
name: "google_search",
args: googleImageOptions.googleSearch
}] : void 0,
headers,
abortSignal
});
const currentDate = (_f = (_e = (_d = this.config._internal) == null ? void 0 : _d.currentDate) == null ? void 0 : _e.call(_d)) != null ? _f : /* @__PURE__ */ new Date();
const images = [];
for (const part of result.content) if (part.type === "file" && part.mediaType.startsWith("image/")) images.push(convertToBase64$1(part.data));
const languageModelGoogleMetadata = (_h = (_g = result.providerMetadata) == null ? void 0 : _g.google) != null ? _h : {};
return {
images,
...result.finishReason.unified === "content-filter" ? { isRetryable: false } : {},
warnings,
providerMetadata: { google: {
...languageModelGoogleMetadata,
images: images.map(() => ({}))
} },
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: (_i = result.response) == null ? void 0 : _i.headers
},
usage: result.usage ? {
inputTokens: result.usage.inputTokens.total,
outputTokens: result.usage.outputTokens.total,
totalTokens: ((_j = result.usage.inputTokens.total) != null ? _j : 0) + ((_k = result.usage.outputTokens.total) != null ? _k : 0)
} : void 0
};
}
};
function isGeminiModel(modelId) {
return modelId.startsWith("gemini-");
}
var googleImageResponseSchema = lazySchema$1(() => zodSchema$2(z.object({ predictions: z.array(z.union([z.object({ bytesBase64Encoded: z.string() }), z.object({ raiFilteredReason: z.string() })])).default([]) })));
var googleImageModelOptionsSchema = lazySchema$1(() => zodSchema$2(z.object({
personGeneration: z.enum([
"dont_allow",
"allow_adult",
"allow_all"
]).nullish(),
aspectRatio: z.enum([
"1:1",
"3:4",
"4:3",
"9:16",
"16:9"
]).nullish(),
/**
* Enable Google Search grounding for Gemini image models. The value is
* forwarded as the args of the `google.tools.googleSearch` provider
* tool on the underlying language-model call. Pass `{}` for defaults.
*
* `generateImage` does not accept a `tools` parameter, so this is the
* dedicated escape hatch for grounding image generation the same way
* `generateText` does.
*/
googleSearch: googleSearchToolArgsBaseSchema().optional()
})));
function getFirstFrameImage$1(options) {
var _a2, _b;
return (_b = (_a2 = options.frameImages) == null ? void 0 : _a2.find((frame) => frame.frameType === "first_frame")) == null ? void 0 : _b.image;
}
function resolveStartImage$1(options) {
var _a2;
return (_a2 = getFirstFrameImage$1(options)) != null ? _a2 : options.image;
}
function getLastFrameImage$1(options) {
var _a2, _b;
return (_b = (_a2 = options.frameImages) == null ? void 0 : _a2.find((frame) => frame.frameType === "last_frame")) == null ? void 0 : _b.image;
}
function getInputReferences(options) {
if (options.frameImages != null && options.frameImages.length > 0) return;
return options.inputReferences != null && options.inputReferences.length > 0 ? options.inputReferences : void 0;
}
function convertFileToGoogleImage(file, warnings) {
if (file.type === "url") {
if (file.url.startsWith("gs://")) return {
gcsUri: file.url,
mimeType: "image/png"
};
warnings.push({
type: "unsupported",
feature: "URL-based image input",
details: "Google Generative AI video models require base64-encoded images or GCS URIs. URL will be ignored."
});
return;
}
return {
bytesBase64Encoded: typeof file.data === "string" ? file.data : convertUint8ArrayToBase64$2(file.data),
mimeType: file.mediaType || "image/png"
};
}
function convertProviderReferenceImage(refImg) {
if (refImg.bytesBase64Encoded) return { image: {
bytesBase64Encoded: refImg.bytesBase64Encoded,
mimeType: "image/png"
} };
if (refImg.gcsUri) return { image: {
gcsUri: refImg.gcsUri,
mimeType: "image/png"
} };
return refImg;
}
function convertInputReferenceImage(file, warnings) {
const image = convertFileToGoogleImage(file, warnings);
return image != null ? { image } : void 0;
}
var GoogleGenerativeAIVideoModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v3";
}
get provider() {
return this.config.provider;
}
get maxVideosPerCall() {
return 4;
}
async doGenerate(options) {
var _a2, _b, _c, _d, _e, _f, _g, _h;
const currentDate = (_c = (_b = (_a2 = this.config._internal) == null ? void 0 : _a2.currentDate) == null ? void 0 : _b.call(_a2)) != null ? _c : /* @__PURE__ */ new Date();
const warnings = [];
const googleOptions = await parseProviderOptions$1({
provider: "google",
providerOptions: options.providerOptions,
schema: googleVideoModelOptionsSchema
});
const instances = [{}];
const instance = instances[0];
if (options.prompt != null) instance.prompt = options.prompt;
const startImage = resolveStartImage$1(options);
if (startImage != null) {
const image = convertFileToGoogleImage(startImage, warnings);
if (image != null) instance.image = image;
}
const lastFrameImage = getLastFrameImage$1(options);
if (lastFrameImage != null) {
const lastFrame = convertFileToGoogleImage(lastFrameImage, warnings);
if (lastFrame != null) instance.lastFrame = lastFrame;
}
const inputReferences = getInputReferences(options);
if (inputReferences != null) instance.referenceImages = inputReferences.flatMap((reference) => {
const converted = convertInputReferenceImage(reference, warnings);
return converted != null ? [converted] : [];
});
else if ((googleOptions == null ? void 0 : googleOptions.referenceImages) != null) instance.referenceImages = googleOptions.referenceImages.map((refImg) => convertProviderReferenceImage(refImg));
const parameters = { sampleCount: options.n };
if (options.aspectRatio) parameters.aspectRatio = options.aspectRatio;
if (options.resolution) parameters.resolution = {
"1280x720": "720p",
"1920x1080": "1080p",
"3840x2160": "4k"
}[options.resolution] || options.resolution;
if (options.duration) parameters.durationSeconds = options.duration;
if (options.seed) parameters.seed = options.seed;
if (googleOptions != null) {
const opts = googleOptions;
if (opts.personGeneration !== void 0 && opts.personGeneration !== null) parameters.personGeneration = opts.personGeneration;
if (opts.negativePrompt !== void 0 && opts.negativePrompt !== null) parameters.negativePrompt = opts.negativePrompt;
for (const [key, value] of Object.entries(opts)) if (![
"pollIntervalMs",
"pollTimeoutMs",
"personGeneration",
"negativePrompt",
"referenceImages"
].includes(key)) parameters[key] = value;
}
const { value: operation } = await postJsonToApi$2({
url: `${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,
headers: combineHeaders$2(await resolve$1(this.config.headers), options.headers),
body: {
instances,
parameters
},
successfulResponseHandler: createJsonResponseHandler$2(googleOperationSchema),
failedResponseHandler: googleFailedResponseHandler,
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const operationName = operation.name;
if (!operationName) throw new AISDKError$2({
name: "GOOGLE_VIDEO_GENERATION_ERROR",
message: "No operation name returned from API"
});
const pollIntervalMs = (_d = googleOptions == null ? void 0 : googleOptions.pollIntervalMs) != null ? _d : 1e4;
const pollTimeoutMs = (_e = googleOptions == null ? void 0 : googleOptions.pollTimeoutMs) != null ? _e : 6e5;
const startTime = Date.now();
let finalOperation = operation;
let responseHeaders;
while (!finalOperation.done) {
if (Date.now() - startTime > pollTimeoutMs) throw new AISDKError$2({
name: "GOOGLE_VIDEO_GENERATION_TIMEOUT",
message: `Video generation timed out after ${pollTimeoutMs}ms`
});
await delay$2(pollIntervalMs);
if ((_f = options.abortSignal) == null ? void 0 : _f.aborted) throw new AISDKError$2({
name: "GOOGLE_VIDEO_GENERATION_ABORTED",
message: "Video generation request was aborted"
});
const { value: statusOperation, responseHeaders: pollHeaders } = await getFromApi$2({
url: `${this.config.baseURL}/${operationName}`,
headers: combineHeaders$2(await resolve$1(this.config.headers), options.headers),
successfulResponseHandler: createJsonResponseHandler$2(googleOperationSchema),
failedResponseHandler: googleFailedResponseHandler,
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
finalOperation = statusOperation;
responseHeaders = pollHeaders;
}
if (finalOperation.error) throw new AISDKError$2({
name: "GOOGLE_VIDEO_GENERATION_FAILED",
message: `Video generation failed: ${finalOperation.error.message}`
});
const response = finalOperation.response;
if (!((_g = response == null ? void 0 : response.generateVideoResponse) == null ? void 0 : _g.generatedSamples) || response.generateVideoResponse.generatedSamples.length === 0) throw new AISDKError$2({
name: "GOOGLE_VIDEO_GENERATION_ERROR",
message: `No videos in response. Response: ${JSON.stringify(finalOperation)}`
});
const videos = [];
const videoMetadata = [];
const resolvedHeaders = await resolve$1(this.config.headers);
const apiKey = resolvedHeaders == null ? void 0 : resolvedHeaders["x-goog-api-key"];
for (const generatedSample of response.generateVideoResponse.generatedSamples) if ((_h = generatedSample.video) == null ? void 0 : _h.uri) {
const urlWithAuth = apiKey && isSameOrigin$1(generatedSample.video.uri, this.config.baseURL) ? `${generatedSample.video.uri}${generatedSample.video.uri.includes("?") ? "&" : "?"}key=${apiKey}` : generatedSample.video.uri;
videos.push({
type: "url",
url: urlWithAuth,
mediaType: "video/mp4"
});
videoMetadata.push({ uri: generatedSample.video.uri });
}
if (videos.length === 0) throw new AISDKError$2({
name: "GOOGLE_VIDEO_GENERATION_ERROR",
message: "No valid videos in response"
});
return {
videos,
warnings,
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders
},
providerMetadata: { google: { videos: videoMetadata } }
};
}
};
var googleOperationSchema = lazySchema$1(() => zodSchema$2(z.object({
name: z.string().nullish(),
done: z.boolean().nullish(),
error: z.object({
code: z.number().nullish(),
message: z.string(),
status: z.string().nullish()
}).nullish(),
response: z.object({ generateVideoResponse: z.object({ generatedSamples: z.array(z.object({ video: z.object({ uri: z.string().nullish() }).nullish() })).nullish() }).nullish() }).nullish()
})));
var googleVideoModelOptionsSchema = lazySchema$1(() => zodSchema$2(z.object({
pollIntervalMs: z.number().positive().nullish(),
pollTimeoutMs: z.number().positive().nullish(),
personGeneration: z.enum([
"dont_allow",
"allow_adult",
"allow_all"
]).nullish(),
negativePrompt: z.string().nullish(),
referenceImages: z.array(z.object({
bytesBase64Encoded: z.string().nullish(),
gcsUri: z.string().nullish()
})).nullish()
}).passthrough()));
function convertGoogleInteractionsUsage(usage) {
var _a2, _b, _c, _d, _e, _f, _g, _h;
if (usage == null) return {
inputTokens: {
total: void 0,
noCache: void 0,
cacheRead: void 0,
cacheWrite: void 0
},
outputTokens: {
total: void 0,
text: void 0,
reasoning: void 0
},
raw: void 0
};
const totalInput = (_a2 = usage.total_input_tokens) != null ? _a2 : 0;
const totalOutput = (_b = usage.total_output_tokens) != null ? _b : 0;
const totalThought = (_c = usage.total_thought_tokens) != null ? _c : 0;
const totalCached = (_d = usage.total_cached_tokens) != null ? _d : 0;
return {
inputTokens: {
total: (_e = usage.total_input_tokens) != null ? _e : void 0,
noCache: usage.total_input_tokens == null ? void 0 : totalInput - totalCached,
cacheRead: (_f = usage.total_cached_tokens) != null ? _f : void 0,
cacheWrite: void 0
},
outputTokens: {
total: usage.total_output_tokens == null && usage.total_thought_tokens == null ? void 0 : totalOutput + totalThought,
text: (_g = usage.total_output_tokens) != null ? _g : void 0,
reasoning: (_h = usage.total_thought_tokens) != null ? _h : void 0
},
raw: usage
};
}
function getGoogleInteractionsOutputTokensByModality(usage) {
const byModality = usage == null ? void 0 : usage.output_tokens_by_modality;
if (byModality == null) return;
const result = {};
for (const entry of byModality) if ((entry == null ? void 0 : entry.modality) != null && entry.tokens != null) result[entry.modality] = entry.tokens;
return Object.keys(result).length > 0 ? result : void 0;
}
var KNOWN_DOC_EXTENSIONS = {
pdf: "application/pdf",
txt: "text/plain",
md: "text/markdown",
markdown: "text/markdown",
doc: "application/msword",
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
};
function inferDocMediaType(uriOrName) {
const lower = uriOrName.toLowerCase();
for (const [ext, media] of Object.entries(KNOWN_DOC_EXTENSIONS)) if (lower.endsWith(`.${ext}`)) return media;
return "application/octet-stream";
}
function basename(uriOrName) {
const parts = uriOrName.split("/");
const last = parts[parts.length - 1];
return last && last.length > 0 ? last : void 0;
}
function annotationToSource({ annotation, generateId: generateId3 }) {
var _a2, _b, _c, _d, _e;
switch (annotation.type) {
case "url_citation": {
const a = annotation;
if (a.url == null || a.url.length === 0) return void 0;
return {
type: "source",
sourceType: "url",
id: generateId3(),
url: a.url,
...a.title != null ? { title: a.title } : {}
};
}
case "file_citation": {
const a = annotation;
const uri = (_b = (_a2 = a.url) != null ? _a2 : a.document_uri) != null ? _b : a.file_name;
if (uri == null || uri.length === 0) return void 0;
if (uri.startsWith("http://") || uri.startsWith("https://")) return {
type: "source",
sourceType: "url",
id: generateId3(),
url: uri,
...a.file_name != null ? { title: a.file_name } : {}
};
const filename = (_c = a.file_name) != null ? _c : basename(uri);
const mediaType = inferDocMediaType(uri);
return {
type: "source",
sourceType: "document",
id: generateId3(),
mediaType,
title: (_e = (_d = a.file_name) != null ? _d : filename) != null ? _e : uri,
...filename != null ? { filename } : {}
};
}
case "place_citation": {
const a = annotation;
if (a.url == null || a.url.length === 0) return void 0;
return {
type: "source",
sourceType: "url",
id: generateId3(),
url: a.url,
...a.name != null ? { title: a.name } : {}
};
}
default: return;
}
}
function builtinToolResultToSources({ block, generateId: generateId3 }) {
var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
const sources = [];
switch (block.type) {
case "url_context_result": {
const result = (_a2 = block.result) != null ? _a2 : [];
for (const entry of result) {
if ((entry == null ? void 0 : entry.url) == null || entry.url.length === 0) continue;
if (entry.status != null && entry.status !== "success") continue;
sources.push({
type: "source",
sourceType: "url",
id: generateId3(),
url: entry.url
});
}
break;
}
case "google_search_result": {
const result = (_b = block.result) != null ? _b : [];
for (const entry of result) {
const url = entry == null ? void 0 : entry.url;
if (url == null || url.length === 0) continue;
sources.push({
type: "source",
sourceType: "url",
id: generateId3(),
url,
...entry.title != null ? { title: entry.title } : {}
});
}
break;
}
case "google_maps_result": {
const result = (_c = block.result) != null ? _c : [];
for (const entry of result) for (const place of (_d = entry.places) != null ? _d : []) {
if (place.url == null || place.url.length === 0) continue;
sources.push({
type: "source",
sourceType: "url",
id: generateId3(),
url: place.url,
...place.name != null ? { title: place.name } : {}
});
}
break;
}
case "file_search_result": {
const result = (_e = block.result) != null ? _e : [];
for (const raw of result) {
if (raw == null || typeof raw !== "object") continue;
const entry = raw;
const uri = (_g = (_f = entry.url) != null ? _f : entry.document_uri) != null ? _g : entry.file_name;
if (uri == null || uri.length === 0) continue;
if (uri.startsWith("http://") || uri.startsWith("https://")) {
sources.push({
type: "source",
sourceType: "url",
id: generateId3(),
url: uri,
...entry.title != null ? { title: entry.title } : {}
});
continue;
}
const filename = (_h = entry.file_name) != null ? _h : basename(uri);
const mediaType = inferDocMediaType(uri);
sources.push({
type: "source",
sourceType: "document",
id: generateId3(),
mediaType,
title: (_k = (_j = (_i = entry.title) != null ? _i : entry.file_name) != null ? _j : filename) != null ? _k : uri,
...filename != null ? { filename } : {}
});
}
break;
}
}
return sources;
}
function annotationsToSources({ annotations, generateId: generateId3 }) {
var _a2;
if (annotations == null) return [];
const seen = /* @__PURE__ */ new Set();
const sources = [];
for (const annotation of annotations) {
const source = annotationToSource({
annotation,
generateId: generateId3
});
if (source == null) continue;
const key = source.sourceType === "url" ? `url:${source.url}` : `doc:${(_a2 = source.filename) != null ? _a2 : source.title}`;
if (seen.has(key)) continue;
seen.add(key);
sources.push(source);
}
return sources;
}
function mapGoogleInteractionsFinishReason({ status, hasFunctionCall }) {
switch (status) {
case "completed": return hasFunctionCall ? "tool-calls" : "stop";
case "requires_action": return "tool-calls";
case "failed": return "error";
case "incomplete": return "length";
case "cancelled": return "other";
default: return "other";
}
}
var BUILTIN_TOOL_CALL_TYPES = /* @__PURE__ */ new Set([
"google_search_call",
"code_execution_call",
"url_context_call",
"file_search_call",
"google_maps_call",
"mcp_server_tool_call"
]);
var BUILTIN_TOOL_RESULT_TYPES = /* @__PURE__ */ new Set([
"google_search_result",
"code_execution_result",
"url_context_result",
"file_search_result",
"google_maps_result",
"mcp_server_tool_result"
]);
function builtinToolNameFromCallType(type) {
return type.replace(/_call$/, "");
}
function builtinToolNameFromResultType(type) {
return type.replace(/_result$/, "");
}
function buildGoogleInteractionsStreamTransform({ warnings, generateId: generateId3, includeRawChunks, serviceTier: headerServiceTier }) {
let interactionId;
let usage;
let serviceTier = headerServiceTier;
let finishStatus;
let hasFunctionCall = false;
const openBlocks = /* @__PURE__ */ new Map();
const emittedSourceKeys = /* @__PURE__ */ new Set();
function sourceKey(source) {
var _a2;
return source.sourceType === "url" ? `url:${source.url}` : `doc:${(_a2 = source.filename) != null ? _a2 : source.title}`;
}
return new TransformStream({
start(controller) {
controller.enqueue({
type: "stream-start",
warnings
});
},
transform(chunk, controller) {
var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;
if (includeRawChunks) controller.enqueue({
type: "raw",
rawValue: chunk.rawValue
});
if (!chunk.success) {
finishStatus = "failed";
controller.enqueue({
type: "error",
error: chunk.error
});
return;
}
const value = chunk.value;
const eventType = value.event_type;
switch (eventType) {
case "interaction.created": {
const interaction = value.interaction;
interactionId = (interaction == null ? void 0 : interaction.id) != null && interaction.id.length > 0 ? interaction.id : void 0;
const created = interaction == null ? void 0 : interaction.created;
let timestamp;
if (typeof created === "string") {
const parsed = new Date(created);
if (!Number.isNaN(parsed.getTime())) timestamp = parsed;
}
controller.enqueue({
type: "response-metadata",
...interactionId != null ? { id: interactionId } : {},
modelId: interaction == null ? void 0 : interaction.model,
...timestamp ? { timestamp } : {}
});
break;
}
case "step.start": {
const event = value;
const step = event.step;
const index = event.index;
const blockId = `${interactionId != null ? interactionId : "interaction"}:${index}`;
const stepType = step == null ? void 0 : step.type;
if (stepType === "model_output") {
const initial = (_a2 = step == null ? void 0 : step.content) == null ? void 0 : _a2[0];
if ((initial == null ? void 0 : initial.type) === "text") {
openBlocks.set(index, {
kind: "text",
id: blockId,
emittedSourceKeys: /* @__PURE__ */ new Set()
});
controller.enqueue({
type: "text-start",
id: blockId
});
const initialSources = annotationsToSources({
annotations: initial.annotations,
generateId: generateId3
});
for (const source of initialSources) {
const key = sourceKey(source);
if (emittedSourceKeys.has(key)) continue;
emittedSourceKeys.add(key);
controller.enqueue(source);
}
} else if ((initial == null ? void 0 : initial.type) === "image") openBlocks.set(index, {
kind: "image",
id: blockId,
...initial.data != null ? { data: initial.data } : {},
...initial.mime_type != null ? { mimeType: initial.mime_type } : {},
...initial.uri != null ? { uri: initial.uri } : {}
});
else openBlocks.set(index, {
kind: "pending_model_output",
id: blockId
});
} else if (stepType === "thought") {
const signature = step == null ? void 0 : step.signature;
openBlocks.set(index, {
kind: "reasoning",
id: blockId,
...signature != null ? { signature } : {}
});
controller.enqueue({
type: "reasoning-start",
id: blockId
});
if (Array.isArray(step == null ? void 0 : step.summary)) {
for (const item of step.summary) if ((item == null ? void 0 : item.type) === "text" && typeof item.text === "string") controller.enqueue({
type: "reasoning-delta",
id: blockId,
delta: item.text
});
}
} else if (stepType === "function_call") {
const toolCallId = (_b = step == null ? void 0 : step.id) != null ? _b : blockId;
const toolName = (_c = step == null ? void 0 : step.name) != null ? _c : "unknown";
hasFunctionCall = true;
const state = {
kind: "function_call",
id: blockId,
toolCallId,
toolName,
argumentsAccum: "",
...(step == null ? void 0 : step.signature) != null ? { signature: step.signature } : {}
};
openBlocks.set(index, state);
controller.enqueue({
type: "tool-input-start",
id: toolCallId,
toolName
});
} else if (stepType != null && BUILTIN_TOOL_CALL_TYPES.has(stepType)) {
const toolName = stepType === "mcp_server_tool_call" ? (_d = step == null ? void 0 : step.name) != null ? _d : "mcp_server_tool" : builtinToolNameFromCallType(stepType);
const state = {
kind: "builtin_tool_call",
id: blockId,
blockType: stepType,
toolCallId: (_e = step == null ? void 0 : step.id) != null ? _e : blockId,
toolName,
arguments: (_f = step == null ? void 0 : step.arguments) != null ? _f : {},
callEmitted: false
};
openBlocks.set(index, state);
} else if (stepType != null && BUILTIN_TOOL_RESULT_TYPES.has(stepType)) {
const toolName = stepType === "mcp_server_tool_result" ? (_g = step == null ? void 0 : step.name) != null ? _g : "mcp_server_tool" : builtinToolNameFromResultType(stepType);
const state = {
kind: "builtin_tool_result",
id: blockId,
blockType: stepType,
callId: (_h = step == null ? void 0 : step.call_id) != null ? _h : blockId,
toolName,
result: (_i = step == null ? void 0 : step.result) != null ? _i : null,
...(step == null ? void 0 : step.is_error) != null ? { isError: step.is_error } : {},
resultEmitted: false
};
openBlocks.set(index, state);
} else openBlocks.set(index, {
kind: "unknown",
id: blockId
});
break;
}
case "step.delta": {
const event = value;
let open = openBlocks.get(event.index);
if (open == null) break;
const dtype = (_j = event.delta) == null ? void 0 : _j.type;
if (open.kind === "pending_model_output") {
if (dtype === "text" || dtype === "text_annotation" || dtype === "text_annotation_delta") {
const promoted = {
kind: "text",
id: open.id,
emittedSourceKeys: /* @__PURE__ */ new Set()
};
openBlocks.set(event.index, promoted);
open = promoted;
controller.enqueue({
type: "text-start",
id: promoted.id
});
}
}
if (dtype === "image" && (open.kind === "pending_model_output" || open.kind === "text" || open.kind === "image")) {
const img = event.delta;
const google2 = {};
if (interactionId != null) google2.interactionId = interactionId;
const providerMetadata = Object.keys(google2).length > 0 ? { google: google2 } : void 0;
if ((img == null ? void 0 : img.data) != null && img.data.length > 0) controller.enqueue({
type: "file",
mediaType: (_k = img.mime_type) != null ? _k : "image/png",
data: img.data,
...providerMetadata ? { providerMetadata } : {}
});
else if ((img == null ? void 0 : img.uri) != null && img.uri.length > 0) {
const uriProviderMetadata = { google: {
...interactionId != null ? { interactionId } : {},
imageUri: img.uri
} };
controller.enqueue({
type: "file",
mediaType: (_l = img.mime_type) != null ? _l : "image/png",
data: "",
providerMetadata: uriProviderMetadata
});
}
if (open.kind === "image") {
open.data = void 0;
open.uri = void 0;
}
break;
}
if (dtype === "video" && (open.kind === "pending_model_output" || open.kind === "text")) {
const videoDelta = event.delta;
const google2 = {};
if (interactionId != null) google2.interactionId = interactionId;
const providerMetadata = Object.keys(google2).length > 0 ? { google: google2 } : void 0;
if ((videoDelta == null ? void 0 : videoDelta.data) != null && videoDelta.data.length > 0) controller.enqueue({
type: "file",
mediaType: (_m = videoDelta.mime_type) != null ? _m : "video/mp4",
data: videoDelta.data,
...providerMetadata ? { providerMetadata } : {}
});
else if ((videoDelta == null ? void 0 : videoDelta.uri) != null && videoDelta.uri.length > 0) {
const uriProviderMetadata = { google: {
...interactionId != null ? { interactionId } : {},
videoUri: videoDelta.uri
} };
controller.enqueue({
type: "file",
mediaType: (_n = videoDelta.mime_type) != null ? _n : "video/mp4",
data: "",
providerMetadata: uriProviderMetadata
});
}
break;
}
const delta = event.delta;
if (open.kind === "text" && (delta == null ? void 0 : delta.type) === "text") {
const text = (_o = delta.text) != null ? _o : "";
if (text.length > 0) controller.enqueue({
type: "text-delta",
id: open.id,
delta: text
});
} else if (open.kind === "text" && ((delta == null ? void 0 : delta.type) === "text_annotation" || (delta == null ? void 0 : delta.type) === "text_annotation_delta")) {
const sources = annotationsToSources({
annotations: delta.annotations,
generateId: generateId3
});
for (const source of sources) {
const key = sourceKey(source);
if (emittedSourceKeys.has(key)) continue;
emittedSourceKeys.add(key);
open.emittedSourceKeys.add(key);
controller.enqueue(source);
}
} else if (open.kind === "image" && (delta == null ? void 0 : delta.type) === "image") {
if (delta.data != null) open.data = delta.data;
if (delta.mime_type != null) open.mimeType = delta.mime_type;
if (delta.uri != null) open.uri = delta.uri;
} else if (open.kind === "reasoning") {
if ((delta == null ? void 0 : delta.type) === "thought_summary") {
const item = delta.content;
if ((item == null ? void 0 : item.type) === "text" && typeof item.text === "string") controller.enqueue({
type: "reasoning-delta",
id: open.id,
delta: item.text
});
} else if ((delta == null ? void 0 : delta.type) === "thought_signature") {
const signature = delta.signature;
if (signature != null) open.signature = signature;
}
} else if (open.kind === "function_call" && (delta == null ? void 0 : delta.type) === "arguments_delta") {
const slice = typeof delta.arguments === "string" ? delta.arguments : "";
if (slice.length > 0) {
open.argumentsAccum += slice;
controller.enqueue({
type: "tool-input-delta",
id: open.toolCallId,
delta: slice
});
}
if (delta.id != null) open.toolCallId = delta.id;
if (delta.signature != null) open.signature = delta.signature;
hasFunctionCall = true;
} else if (open.kind === "builtin_tool_call" && (delta == null ? void 0 : delta.type) === open.blockType) {
if (delta.id != null) open.toolCallId = delta.id;
if (delta.arguments != null && typeof delta.arguments === "object") open.arguments = delta.arguments;
if (delta.name != null && open.blockType === "mcp_server_tool_call") open.toolName = delta.name;
} else if (open.kind === "builtin_tool_result" && (delta == null ? void 0 : delta.type) === open.blockType) {
if (delta.call_id != null) open.callId = delta.call_id;
if (delta.result !== void 0) open.result = delta.result;
if (delta.is_error != null) open.isError = delta.is_error;
if (delta.name != null && open.blockType === "mcp_server_tool_result") open.toolName = delta.name;
}
break;
}
case "step.stop": {
const event = value;
const open = openBlocks.get(event.index);
if (open == null) break;
if (open.kind === "text") {
const textProviderMetadata = interactionId != null ? { google: { interactionId } } : void 0;
controller.enqueue({
type: "text-end",
id: open.id,
...textProviderMetadata ? { providerMetadata: textProviderMetadata } : {}
});
} else if (open.kind === "reasoning") {
const google2 = {};
if (open.signature != null) google2.signature = open.signature;
if (interactionId != null) google2.interactionId = interactionId;
const providerMetadata = Object.keys(google2).length > 0 ? { google: google2 } : void 0;
controller.enqueue({
type: "reasoning-end",
id: open.id,
...providerMetadata ? { providerMetadata } : {}
});
} else if (open.kind === "image") {
const google2 = {};
if (interactionId != null) google2.interactionId = interactionId;
const providerMetadata = Object.keys(google2).length > 0 ? { google: google2 } : void 0;
if (open.data != null && open.data.length > 0) controller.enqueue({
type: "file",
mediaType: (_p = open.mimeType) != null ? _p : "image/png",
data: open.data,
...providerMetadata ? { providerMetadata } : {}
});
else if (open.uri != null && open.uri.length > 0) {
const uriProviderMetadata = { google: {
...interactionId != null ? { interactionId } : {},
imageUri: open.uri
} };
controller.enqueue({
type: "file",
mediaType: (_q = open.mimeType) != null ? _q : "image/png",
data: "",
providerMetadata: uriProviderMetadata
});
}
} else if (open.kind === "function_call") {
const accumulated = open.argumentsAccum.length > 0 ? open.argumentsAccum : "{}";
controller.enqueue({
type: "tool-input-end",
id: open.toolCallId
});
const google2 = {};
if (open.signature != null) google2.signature = open.signature;
if (interactionId != null) google2.interactionId = interactionId;
const providerMetadata = Object.keys(google2).length > 0 ? { google: google2 } : void 0;
controller.enqueue({
type: "tool-call",
toolCallId: open.toolCallId,
toolName: open.toolName,
input: accumulated,
...providerMetadata ? { providerMetadata } : {}
});
} else if (open.kind === "builtin_tool_call" && !open.callEmitted) {
controller.enqueue({
type: "tool-call",
toolCallId: open.toolCallId,
toolName: open.toolName,
input: JSON.stringify((_r = open.arguments) != null ? _r : {}),
providerExecuted: true
});
open.callEmitted = true;
} else if (open.kind === "builtin_tool_result" && !open.resultEmitted) {
controller.enqueue({
type: "tool-result",
toolCallId: open.callId,
toolName: open.toolName,
result: (_s = open.result) != null ? _s : null
});
open.resultEmitted = true;
const sources = builtinToolResultToSources({
block: {
type: open.blockType,
call_id: open.callId,
result: open.result
},
generateId: generateId3
});
for (const source of sources) {
const key = sourceKey(source);
if (emittedSourceKeys.has(key)) continue;
emittedSourceKeys.add(key);
controller.enqueue(source);
}
}
openBlocks.delete(event.index);
break;
}
case "interaction.status_update":
case "interaction.in_progress":
case "interaction.requires_action": {
const event = value;
if (event.status != null) finishStatus = event.status;
else if (eventType === "interaction.requires_action") finishStatus = "requires_action";
else finishStatus = "in_progress";
break;
}
case "interaction.completed": {
const interaction = value.interaction;
if ((interaction == null ? void 0 : interaction.id) != null && interaction.id.length > 0) interactionId = interaction.id;
if ((interaction == null ? void 0 : interaction.status) != null) finishStatus = interaction.status;
if ((interaction == null ? void 0 : interaction.usage) != null) usage = interaction.usage;
if ((interaction == null ? void 0 : interaction.service_tier) != null) serviceTier = interaction.service_tier;
break;
}
case "error": {
const event = value;
finishStatus = "failed";
const errorPayload = (_t = event.error) != null ? _t : { message: "Unknown interaction error" };
controller.enqueue({
type: "error",
error: errorPayload
});
break;
}
}
},
flush(controller) {
const finishReason = {
unified: mapGoogleInteractionsFinishReason({
status: finishStatus,
hasFunctionCall
}),
raw: finishStatus
};
const outputTokensByModality = getGoogleInteractionsOutputTokensByModality(usage);
const providerMetadata = { google: {
...interactionId != null ? { interactionId } : {},
...serviceTier != null ? { serviceTier } : {},
...outputTokensByModality != null ? { outputTokensByModality } : {}
} };
controller.enqueue({
type: "finish",
finishReason,
usage: convertGoogleInteractionsUsage(usage),
providerMetadata
});
}
});
}
function getTopLevelMediaType$1(mediaType) {
const slashIndex = mediaType.indexOf("/");
return slashIndex === -1 ? mediaType : mediaType.substring(0, slashIndex);
}
function isFullMediaType(mediaType) {
const slashIndex = mediaType.indexOf("/");
if (slashIndex === -1) return false;
const subtype = mediaType.substring(slashIndex + 1);
return subtype.length > 0 && subtype !== "*";
}
function convertToGoogleInteractionsInput({ prompt, previousInteractionId, store, mediaResolution }) {
var _a2, _b, _c, _d, _e, _f, _g;
const warnings = [];
const incoherentCombo = previousInteractionId != null && store === false;
const shouldCompact = previousInteractionId != null && store !== false;
if (incoherentCombo) warnings.push({
type: "other",
message: "google.interactions: providerOptions.google.previousInteractionId was set together with store: false. These are incoherent (the prior interaction cannot be referenced when nothing was stored on the server); the full history will be sent and previous_interaction_id will still be emitted."
});
const compactedPrompt = shouldCompact ? compactPromptForPreviousInteraction({
prompt,
previousInteractionId
}) : prompt;
const systemTexts = [];
const steps = [];
for (const message of compactedPrompt) switch (message.role) {
case "system":
systemTexts.push(message.content);
break;
case "user": {
const content = [];
for (const part of message.content) if (part.type === "text") content.push({
type: "text",
text: part.text
});
else if (part.type === "file") {
const fileBlock = convertFilePartToContent({
part,
warnings,
mediaResolution
});
if (fileBlock != null) content.push(fileBlock);
}
const merged = mergeAdjacentTextContent(content);
if (merged.length > 0) steps.push({
type: "user_input",
content: merged
});
break;
}
case "assistant": {
let pendingModelOutput = [];
const flushModelOutput = () => {
if (pendingModelOutput.length > 0) {
steps.push({
type: "model_output",
content: pendingModelOutput
});
pendingModelOutput = [];
}
};
for (const part of message.content) if (part.type === "text") pendingModelOutput.push({
type: "text",
text: part.text
});
else if (part.type === "reasoning") {
flushModelOutput();
const signature = (_b = (_a2 = part.providerOptions) == null ? void 0 : _a2.google) == null ? void 0 : _b.signature;
steps.push({
type: "thought",
...signature != null ? { signature } : {},
summary: part.text.length > 0 ? [{
type: "text",
text: part.text
}] : void 0
});
} else if (part.type === "file") {
const fileBlock = convertFilePartToContent({
part,
warnings,
mediaResolution
});
if (fileBlock != null) pendingModelOutput.push(fileBlock);
} else if (part.type === "tool-call") {
flushModelOutput();
const signature = (_d = (_c = part.providerOptions) == null ? void 0 : _c.google) == null ? void 0 : _d.signature;
const args = typeof part.input === "string" ? safeParseToolArgs(part.input) : (_e = part.input) != null ? _e : {};
steps.push({
type: "function_call",
id: part.toolCallId,
name: part.toolName,
arguments: args,
...signature != null ? { signature } : {}
});
} else warnings.push({
type: "other",
message: `google.interactions: unsupported assistant content part type "${part.type}"; part dropped.`
});
flushModelOutput();
break;
}
case "tool": {
const content = [];
for (const part of message.content) {
if (part.type !== "tool-result") {
warnings.push({
type: "other",
message: `google.interactions: unsupported tool message part type "${part.type}"; part dropped.`
});
continue;
}
const block = convertToolResultPart({
toolCallId: part.toolCallId,
toolName: part.toolName,
output: part.output,
signature: (_g = (_f = part.providerOptions) == null ? void 0 : _f.google) == null ? void 0 : _g.signature,
warnings
});
content.push(block);
}
if (content.length > 0) steps.push({
type: "user_input",
content
});
break;
}
}
return {
input: steps,
systemInstruction: systemTexts.length > 0 ? systemTexts.join("\n\n") : void 0,
warnings
};
}
function convertFilePartToContent({ part, warnings, mediaResolution }) {
const topLevel = getTopLevelMediaType$1(part.mediaType);
let kind;
switch (topLevel) {
case "image":
kind = "image";
break;
case "audio":
kind = "audio";
break;
case "video":
kind = "video";
break;
case "application":
kind = "document";
break;
default: kind = void 0;
}
if (kind == null) {
warnings.push({
type: "other",
message: `google.interactions: unsupported file media type "${part.mediaType}"; part dropped.`
});
return;
}
const resolutionField = mediaResolution != null && (kind === "image" || kind === "video") ? { resolution: mediaResolution } : {};
if (part.data instanceof URL) return {
type: kind,
uri: part.data.toString(),
...isFullMediaType(part.mediaType) ? { mime_type: part.mediaType } : {},
...resolutionField
};
if (!isFullMediaType(part.mediaType)) {
warnings.push({
type: "other",
message: `google.interactions: inline file data requires a full IANA media type (e.g. "image/png"), got "${part.mediaType}"; part dropped.`
});
return;
}
return {
type: kind,
data: convertToBase64$1(part.data),
mime_type: part.mediaType,
...resolutionField
};
}
function compactPromptForPreviousInteraction({ prompt, previousInteractionId }) {
const out = [];
const droppedToolCallIds = /* @__PURE__ */ new Set();
for (const message of prompt) {
if (message.role === "assistant") {
if (message.content.some((part) => {
var _a2, _b;
return ((_b = (_a2 = part.providerOptions) == null ? void 0 : _a2.google) == null ? void 0 : _b.interactionId) === previousInteractionId;
})) {
for (const part of message.content) if (part.type === "tool-call") droppedToolCallIds.add(part.toolCallId);
continue;
}
out.push(message);
continue;
}
if (message.role === "tool") {
const remaining = message.content.filter((part) => {
if (part.type !== "tool-result") return true;
return !droppedToolCallIds.has(part.toolCallId);
});
if (remaining.length === 0) continue;
out.push({
...message,
content: remaining
});
continue;
}
out.push(message);
}
return out;
}
function safeParseToolArgs(input) {
try {
const parsed = secureJsonParse$2(input);
if (parsed != null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
return { value: parsed };
} catch (e) {
return { value: input };
}
}
function convertToolResultPart({ toolCallId, toolName, output, signature, warnings }) {
var _a2;
const base = {
type: "function_result",
call_id: toolCallId,
name: toolName,
...signature != null ? { signature } : {}
};
switch (output.type) {
case "text": return {
...base,
result: output.value
};
case "json": return {
...base,
result: JSON.stringify(output.value)
};
case "error-text": return {
...base,
is_error: true,
result: output.value
};
case "error-json": return {
...base,
is_error: true,
result: JSON.stringify(output.value)
};
case "execution-denied": return {
...base,
is_error: true,
result: (_a2 = output.reason) != null ? _a2 : "Tool execution denied by user."
};
case "content": {
const blocks = [];
for (const item of output.value) if (item.type === "text") blocks.push({
type: "text",
text: item.text
});
else if (item.type === "image-data") {
const imageBlock = filePartToImageBlock({
part: {
type: "file",
mediaType: item.mediaType,
data: item.data
},
warnings
});
if (imageBlock != null) blocks.push(imageBlock);
} else if (item.type === "image-url") {
const imageBlock = filePartToImageBlock({
part: {
type: "file",
mediaType: "image/*",
data: new URL(item.url)
},
warnings
});
if (imageBlock != null) blocks.push(imageBlock);
} else if (item.type === "file-data" || item.type === "file-url") {
const mediaType = item.type === "file-data" ? item.mediaType : "application/*";
if (getTopLevelMediaType$1(mediaType) !== "image") {
warnings.push({
type: "other",
message: `google.interactions: tool-result file with mediaType "${mediaType}" is not supported (Interactions \`function_result.result\` accepts only text and image content); part dropped.`
});
continue;
}
const imageBlock = filePartToImageBlock({
part: item.type === "file-data" ? {
type: "file",
mediaType: item.mediaType,
data: item.data
} : {
type: "file",
mediaType,
data: new URL(item.url)
},
warnings
});
if (imageBlock != null) blocks.push(imageBlock);
} else warnings.push({
type: "other",
message: `google.interactions: tool-result content part type "${item.type}" is not supported; part dropped.`
});
return {
...base,
result: blocks
};
}
}
}
function filePartToImageBlock({ part, warnings }) {
if (part.data instanceof URL) return {
type: "image",
uri: part.data.toString(),
...isFullMediaType(part.mediaType) ? { mime_type: part.mediaType } : {}
};
if (!isFullMediaType(part.mediaType)) {
warnings.push({
type: "other",
message: `google.interactions: tool-result image part requires a full IANA media type (e.g. "image/png"), got "${part.mediaType}"; part dropped.`
});
return;
}
return {
type: "image",
data: convertToBase64$1(part.data),
mime_type: part.mediaType
};
}
function mergeAdjacentTextContent(content) {
if (content.length < 2) return content;
const result = [];
for (const block of content) {
const last = result[result.length - 1];
if (block.type === "text" && last != null && last.type === "text" && last.annotations == null && block.annotations == null) {
const merged = {
type: "text",
text: `${last.text}
${block.text}`
};
result[result.length - 1] = merged;
continue;
}
result.push(block);
}
return result;
}
var tokenByModalitySchema = () => z.object({
modality: z.string().nullish(),
tokens: z.number().nullish()
}).loose();
var usageSchema2 = () => z.object({
total_input_tokens: z.number().nullish(),
total_output_tokens: z.number().nullish(),
total_thought_tokens: z.number().nullish(),
total_cached_tokens: z.number().nullish(),
total_tool_use_tokens: z.number().nullish(),
total_tokens: z.number().nullish(),
input_tokens_by_modality: z.array(tokenByModalitySchema()).nullish(),
output_tokens_by_modality: z.array(tokenByModalitySchema()).nullish(),
cached_tokens_by_modality: z.array(tokenByModalitySchema()).nullish(),
tool_use_tokens_by_modality: z.array(tokenByModalitySchema()).nullish(),
grounding_tool_count: z.array(z.object({
type: z.string().nullish(),
count: z.number().nullish()
}).loose()).nullish()
}).loose();
var interactionStatusSchema = () => z.enum([
"in_progress",
"requires_action",
"completed",
"failed",
"cancelled",
"incomplete"
]);
var annotationSchema$1 = () => {
const urlCitation = z.object({
type: z.literal("url_citation"),
url: z.string().nullish(),
title: z.string().nullish(),
start_index: z.number().nullish(),
end_index: z.number().nullish()
}).loose();
const fileCitation = z.object({
type: z.literal("file_citation"),
file_name: z.string().nullish(),
document_uri: z.string().nullish(),
url: z.string().nullish(),
page_number: z.number().nullish(),
media_id: z.string().nullish(),
start_index: z.number().nullish(),
end_index: z.number().nullish(),
custom_metadata: z.record(z.string(), z.unknown()).nullish()
}).loose();
const placeCitation = z.object({
type: z.literal("place_citation"),
name: z.string().nullish(),
url: z.string().nullish(),
place_id: z.string().nullish(),
start_index: z.number().nullish(),
end_index: z.number().nullish()
}).loose();
return z.union([
urlCitation,
fileCitation,
placeCitation,
z.object({ type: z.string() }).loose()
]);
};
var thoughtSummaryItemSchema = () => z.object({
type: z.string(),
text: z.string().nullish(),
data: z.string().nullish(),
mime_type: z.string().nullish()
}).loose();
var contentBlockSchema = () => {
const textContent = z.object({
type: z.literal("text"),
text: z.string(),
annotations: z.array(annotationSchema$1()).nullish()
}).loose();
const imageContent = z.object({
type: z.literal("image"),
data: z.string().nullish(),
mime_type: z.string().nullish(),
resolution: z.enum([
"low",
"medium",
"high",
"ultra_high"
]).nullish(),
uri: z.string().nullish()
}).loose();
const videoContent = z.object({
type: z.literal("video"),
data: z.string().nullish(),
mime_type: z.string().nullish(),
uri: z.string().nullish()
}).loose();
return z.union([
textContent,
imageContent,
videoContent,
z.object({ type: z.string() }).loose()
]);
};
var BUILTIN_TOOL_CALL_STEP_TYPES = [
"google_search_call",
"code_execution_call",
"url_context_call",
"file_search_call",
"google_maps_call",
"mcp_server_tool_call"
];
var BUILTIN_TOOL_RESULT_STEP_TYPES = [
"google_search_result",
"code_execution_result",
"url_context_result",
"file_search_result",
"google_maps_result",
"mcp_server_tool_result"
];
var stepSchema = () => {
const userInputStep = z.object({
type: z.literal("user_input"),
content: z.array(contentBlockSchema()).nullish()
}).loose();
const modelOutputStep = z.object({
type: z.literal("model_output"),
content: z.array(contentBlockSchema()).nullish()
}).loose();
const functionCallStep = z.object({
type: z.literal("function_call"),
id: z.string(),
name: z.string(),
arguments: z.record(z.string(), z.unknown()).nullish(),
signature: z.string().nullish()
}).loose();
const thoughtStep = z.object({
type: z.literal("thought"),
signature: z.string().nullish(),
summary: z.array(thoughtSummaryItemSchema()).nullish()
}).loose();
const builtinToolCallStep = z.object({
type: z.enum(BUILTIN_TOOL_CALL_STEP_TYPES),
id: z.string(),
arguments: z.record(z.string(), z.unknown()).nullish(),
name: z.string().nullish(),
server_name: z.string().nullish(),
search_type: z.string().nullish(),
signature: z.string().nullish()
}).loose();
const builtinToolResultStep = z.object({
type: z.enum(BUILTIN_TOOL_RESULT_STEP_TYPES),
call_id: z.string(),
result: z.unknown().nullish(),
is_error: z.boolean().nullish(),
name: z.string().nullish(),
server_name: z.string().nullish(),
signature: z.string().nullish()
}).loose();
return z.union([
userInputStep,
modelOutputStep,
functionCallStep,
thoughtStep,
builtinToolCallStep,
builtinToolResultStep,
z.object({ type: z.string() }).loose()
]);
};
var googleInteractionsResponseSchema = lazySchema$1(() => zodSchema$2(z.object({
id: z.string().nullish(),
created: z.string().nullish(),
updated: z.string().nullish(),
status: interactionStatusSchema(),
model: z.string().nullish(),
agent: z.string().nullish(),
steps: z.array(stepSchema()).nullish(),
usage: usageSchema2().nullish(),
service_tier: z.string().nullish(),
previous_interaction_id: z.string().nullish(),
response_modalities: z.array(z.string()).nullish()
}).loose()));
var googleInteractionsEventSchema = lazySchema$1(() => zodSchema$2((() => {
const status = interactionStatusSchema();
const annotation = annotationSchema$1();
const thoughtSummaryItem = thoughtSummaryItemSchema();
const interactionCreatedEvent = z.object({
event_type: z.literal("interaction.created"),
event_id: z.string().nullish(),
interaction: z.object({
id: z.string().nullish(),
created: z.string().nullish(),
model: z.string().nullish(),
agent: z.string().nullish(),
status: status.nullish()
}).loose()
}).loose();
const stepStartEvent = z.object({
event_type: z.literal("step.start"),
event_id: z.string().nullish(),
index: z.number(),
step: stepSchema()
}).loose();
const stepDeltaText = z.object({
type: z.literal("text"),
text: z.string()
}).loose();
const stepDeltaThoughtSummary = z.object({
type: z.literal("thought_summary"),
content: thoughtSummaryItem.nullish()
}).loose();
const stepDeltaThoughtSignature = z.object({
type: z.literal("thought_signature"),
signature: z.string().nullish()
}).loose();
const stepDeltaArgumentsDelta = z.object({
type: z.literal("arguments_delta"),
arguments: z.string().nullish(),
id: z.string().nullish(),
signature: z.string().nullish()
}).loose();
const stepDeltaTextAnnotation = z.object({
type: z.enum(["text_annotation_delta", "text_annotation"]),
annotations: z.array(annotation).nullish()
}).loose();
const stepDeltaImage = z.object({
type: z.literal("image"),
data: z.string().nullish(),
mime_type: z.string().nullish(),
resolution: z.enum([
"low",
"medium",
"high",
"ultra_high"
]).nullish(),
uri: z.string().nullish()
}).loose();
const stepDeltaVideo = z.object({
type: z.literal("video"),
data: z.string().nullish(),
mime_type: z.string().nullish(),
uri: z.string().nullish()
}).loose();
const stepDeltaBuiltinToolCall = z.object({
type: z.enum(BUILTIN_TOOL_CALL_STEP_TYPES),
id: z.string().nullish(),
arguments: z.record(z.string(), z.unknown()).nullish(),
name: z.string().nullish(),
server_name: z.string().nullish(),
search_type: z.string().nullish(),
signature: z.string().nullish()
}).loose();
const stepDeltaBuiltinToolResult = z.object({
type: z.enum(BUILTIN_TOOL_RESULT_STEP_TYPES),
call_id: z.string().nullish(),
result: z.unknown().nullish(),
is_error: z.boolean().nullish(),
name: z.string().nullish(),
server_name: z.string().nullish(),
signature: z.string().nullish()
}).loose();
const stepDeltaUnknown = z.object({ type: z.string() }).loose();
const stepDeltaUnion = z.union([
stepDeltaText,
stepDeltaImage,
stepDeltaVideo,
stepDeltaThoughtSummary,
stepDeltaThoughtSignature,
stepDeltaArgumentsDelta,
stepDeltaTextAnnotation,
stepDeltaBuiltinToolCall,
stepDeltaBuiltinToolResult,
stepDeltaUnknown
]);
const stepDeltaEvent = z.object({
event_type: z.literal("step.delta"),
event_id: z.string().nullish(),
index: z.number(),
delta: stepDeltaUnion
}).loose();
const stepStopEvent = z.object({
event_type: z.literal("step.stop"),
event_id: z.string().nullish(),
index: z.number()
}).loose();
const interactionStatusUpdateEvent = z.object({
event_type: z.literal("interaction.status_update"),
event_id: z.string().nullish(),
interaction_id: z.string().nullish(),
status: status.nullish()
}).loose();
const interactionInProgressEvent = z.object({
event_type: z.literal("interaction.in_progress"),
event_id: z.string().nullish(),
interaction_id: z.string().nullish(),
status: status.nullish()
}).loose();
const interactionRequiresActionEvent = z.object({
event_type: z.literal("interaction.requires_action"),
event_id: z.string().nullish(),
interaction_id: z.string().nullish(),
status: status.nullish()
}).loose();
const interactionCompletedEvent = z.object({
event_type: z.literal("interaction.completed"),
event_id: z.string().nullish(),
interaction: z.object({
id: z.string().nullish(),
status: status.nullish(),
usage: usageSchema2().nullish(),
service_tier: z.string().nullish()
}).loose()
}).loose();
const errorEvent = z.object({
event_type: z.literal("error"),
event_id: z.string().nullish(),
error: z.object({
code: z.string().nullish(),
message: z.string().nullish()
}).loose().nullish()
}).loose();
const unknownEvent = z.object({ event_type: z.string() }).loose();
return z.union([
interactionCreatedEvent,
stepStartEvent,
stepDeltaEvent,
stepStopEvent,
interactionStatusUpdateEvent,
interactionInProgressEvent,
interactionRequiresActionEvent,
interactionCompletedEvent,
errorEvent,
unknownEvent
]);
})()));
var googleInteractionsLanguageModelOptions = lazySchema$1(() => zodSchema$2(z.object({
previousInteractionId: z.string().nullish(),
store: z.boolean().nullish(),
agent: z.string().nullish(),
agentConfig: z.union([z.object({ type: z.literal("dynamic") }).loose(), z.object({
type: z.literal("deep-research"),
thinkingSummaries: z.enum(["auto", "none"]).nullish(),
visualization: z.enum(["off", "auto"]).nullish(),
collaborativePlanning: z.boolean().nullish()
})]).nullish(),
thinkingLevel: z.enum([
"minimal",
"low",
"medium",
"high"
]).nullish(),
thinkingSummaries: z.enum(["auto", "none"]).nullish(),
/**
* Output-format entries that map directly to the API's `response_format`
* array. Use this to request image, audio, video, or non-JSON text
* outputs with modality-specific controls.
*
* Entries are sent in order. The AI SDK call-level `responseFormat: {
* type: 'json', schema }` still drives JSON-mode and adds a matching
* text entry automatically; entries listed here are appended.
*/
responseFormat: z.array(z.union([
z.object({
type: z.literal("text"),
mimeType: z.string().nullish(),
schema: z.unknown().nullish()
}).loose(),
z.object({
type: z.literal("image"),
mimeType: z.string().nullish(),
aspectRatio: z.enum([
"1:1",
"2:3",
"3:2",
"3:4",
"4:3",
"4:5",
"5:4",
"9:16",
"16:9",
"21:9",
"1:8",
"8:1",
"1:4",
"4:1"
]).nullish(),
imageSize: z.enum([
"1K",
"2K",
"4K",
"512"
]).nullish()
}).loose(),
z.object({
type: z.literal("audio"),
mimeType: z.string().nullish()
}).loose(),
z.object({
type: z.literal("video"),
aspectRatio: z.enum(["16:9", "9:16"]).nullish(),
resolution: z.enum([
"360p",
"720p",
"1080p",
"4k"
]).nullish(),
duration: z.string().nullish(),
delivery: z.enum(["inline", "uri"]).nullish(),
gcsUri: z.string().nullish()
}).loose()
])).nullish(),
/**
* @deprecated Use `responseFormat` with a `{ type: 'image', ... }`
* entry instead. Retained for backwards compatibility; the SDK
* translates it into a matching `response_format` image entry and
* emits a warning when set.
*/
imageConfig: z.object({
aspectRatio: z.enum([
"1:1",
"2:3",
"3:2",
"3:4",
"4:3",
"4:5",
"5:4",
"9:16",
"16:9",
"21:9",
"1:8",
"8:1",
"1:4",
"4:1"
]).nullish(),
imageSize: z.enum([
"1K",
"2K",
"4K",
"512"
]).nullish()
}).nullish(),
mediaResolution: z.enum([
"low",
"medium",
"high",
"ultra_high"
]).nullish(),
responseModalities: z.array(z.enum([
"text",
"image",
"audio",
"video",
"document"
])).nullish(),
serviceTier: z.enum([
"flex",
"standard",
"priority"
]).nullish(),
/**
* Alternative to AI SDK `system` message. If both are set, the AI SDK
* `system` message wins and a warning is emitted.
*/
systemInstruction: z.string().nullish(),
/**
* Per-block signature for round-tripping `thought.signature` and
* `function_call.signature` blocks. Set by the SDK on output reasoning /
* tool-call parts; passed back unchanged on input parts so the API
* accepts the prior turn.
*/
signature: z.string().nullish(),
/**
* Set by the SDK on output assistant messages. The converter uses it to
* decide which messages to drop when compacting under
* `previousInteractionId`.
*/
interactionId: z.string().nullish(),
/**
* Maximum time, in milliseconds, to poll a background interaction (agent
* call) before giving up. Defaults to 30 minutes. Long-running agents
* such as deep research can take tens of minutes — increase if needed.
*/
pollingTimeoutMs: z.number().int().positive().nullish(),
/**
* Run the interaction in the background. Required for agents whose
* server-side workflow cannot complete within a single request/response.
* When `true`, the POST returns with a non-terminal status and the SDK
* polls `GET /interactions/{id}` until the work completes. Some agents
* reject `true`; see the agent's documentation for which mode it
* requires.
*/
background: z.boolean().nullish(),
/**
* Environment configuration for the agent sandbox. Only applies to agent
* calls (`google.interactions({ agent })`); ignored on model-id calls.
*
* - `"remote"`: provision a fresh sandbox for this call.
* - any other string: an existing `environment_id` to reuse.
* - object: provision a fresh sandbox and optionally preload `sources`
* and/or constrain outbound traffic via `network`.
*/
environment: z.union([z.string(), z.object({
type: z.literal("remote"),
sources: z.array(z.union([
z.object({
type: z.literal("gcs"),
source: z.string(),
target: z.string().nullish()
}),
z.object({
type: z.literal("repository"),
source: z.string(),
target: z.string().nullish()
}),
z.object({
type: z.literal("inline"),
content: z.string(),
target: z.string()
})
])).nullish(),
network: z.union([z.literal("disabled"), z.object({ allowlist: z.array(z.object({
domain: z.string(),
transform: z.array(z.record(z.string(), z.string())).nullish()
})) })]).nullish()
})]).nullish()
})));
function googleProviderMetadata({ signature, interactionId }) {
const google2 = {};
if (signature != null) google2.signature = signature;
if (interactionId != null) google2.interactionId = interactionId;
return Object.keys(google2).length > 0 ? { providerMetadata: { google: google2 } } : {};
}
var BUILTIN_TOOL_CALL_TYPES2 = /* @__PURE__ */ new Set([
"google_search_call",
"code_execution_call",
"url_context_call",
"file_search_call",
"google_maps_call",
"mcp_server_tool_call"
]);
var BUILTIN_TOOL_RESULT_TYPES2 = /* @__PURE__ */ new Set([
"google_search_result",
"code_execution_result",
"url_context_result",
"file_search_result",
"google_maps_result",
"mcp_server_tool_result"
]);
function builtinToolNameFromCallType2(type) {
return type.replace(/_call$/, "");
}
function builtinToolNameFromResultType2(type) {
return type.replace(/_result$/, "");
}
function parseGoogleInteractionsOutputs({ steps, generateId: generateId3, interactionId }) {
var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
const content = [];
let hasFunctionCall = false;
if (steps == null) return {
content,
hasFunctionCall
};
for (const step of steps) {
if (step == null || typeof step !== "object") continue;
const type = step.type;
if (typeof type !== "string") continue;
switch (type) {
case "user_input": break;
case "model_output": {
const blocks = (_a2 = step.content) != null ? _a2 : [];
for (const block of blocks) {
if (block == null || typeof block !== "object") continue;
const blockType = block.type;
if (blockType === "text") {
const text = (_b = block.text) != null ? _b : "";
const annotations = block.annotations;
content.push({
type: "text",
text,
...googleProviderMetadata({ interactionId })
});
const sources = annotationsToSources({
annotations,
generateId: generateId3
});
for (const source of sources) content.push(source);
} else if (blockType === "image") {
const image = block;
if (image.data != null && image.data.length > 0) content.push({
type: "file",
mediaType: (_c = image.mime_type) != null ? _c : "image/png",
data: image.data,
...googleProviderMetadata({ interactionId })
});
else if (image.uri != null && image.uri.length > 0) content.push({
type: "file",
mediaType: (_d = image.mime_type) != null ? _d : "image/png",
data: "",
providerMetadata: { google: {
...interactionId != null ? { interactionId } : {},
imageUri: image.uri
} }
});
} else if (blockType === "video") {
const video = block;
if (video.data != null && video.data.length > 0) content.push({
type: "file",
mediaType: (_e = video.mime_type) != null ? _e : "video/mp4",
data: video.data,
...googleProviderMetadata({ interactionId })
});
else if (video.uri != null && video.uri.length > 0) content.push({
type: "file",
mediaType: (_f = video.mime_type) != null ? _f : "video/mp4",
data: "",
providerMetadata: { google: {
...interactionId != null ? { interactionId } : {},
videoUri: video.uri
} }
});
}
}
break;
}
case "thought": {
const thought = step;
const text = (Array.isArray(thought.summary) ? thought.summary : []).filter((item) => (item == null ? void 0 : item.type) === "text" && typeof item.text === "string").map((item) => item.text).join("\n");
content.push({
type: "reasoning",
text,
...googleProviderMetadata({
signature: thought.signature,
interactionId
})
});
break;
}
case "function_call": {
hasFunctionCall = true;
const call = step;
content.push({
type: "tool-call",
toolCallId: call.id,
toolName: call.name,
input: JSON.stringify((_g = call.arguments) != null ? _g : {}),
...googleProviderMetadata({
signature: call.signature,
interactionId
})
});
break;
}
default: if (BUILTIN_TOOL_CALL_TYPES2.has(type)) {
const call = step;
const toolName = type === "mcp_server_tool_call" ? (_h = call.name) != null ? _h : "mcp_server_tool" : builtinToolNameFromCallType2(type);
const input = JSON.stringify((_i = call.arguments) != null ? _i : {});
content.push({
type: "tool-call",
toolCallId: (_j = call.id) != null ? _j : generateId3(),
toolName,
input,
providerExecuted: true
});
} else if (BUILTIN_TOOL_RESULT_TYPES2.has(type)) {
const result = step;
const toolName = type === "mcp_server_tool_result" ? (_k = result.name) != null ? _k : "mcp_server_tool" : builtinToolNameFromResultType2(type);
content.push({
type: "tool-result",
toolCallId: (_l = result.call_id) != null ? _l : generateId3(),
toolName,
result: (_m = result.result) != null ? _m : null
});
const sources = builtinToolResultToSources({
block: step,
generateId: generateId3
});
for (const source of sources) content.push(source);
}
}
}
return {
content,
hasFunctionCall
};
}
var getOriginalFetch = () => globalThis.fetch;
async function cancelGoogleInteraction({ baseURL, interactionId, headers, fetch = getOriginalFetch() }) {
if (interactionId == null || interactionId.length === 0) return;
const url = `${baseURL}/interactions/${encodeURIComponent(interactionId)}/cancel`;
try {
const response = await fetch(url, {
method: "POST",
headers: withUserAgentSuffix$2(combineHeaders$2({ "Content-Type": "application/json" }, headers), getRuntimeEnvironmentUserAgent$2()),
body: "{}"
});
try {
await response.text();
} catch (e) {}
} catch (e) {}
}
var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
"completed",
"failed",
"cancelled",
"incomplete"
]);
function isTerminalStatus(status) {
return status != null && TERMINAL_STATUSES.has(status);
}
var DEFAULT_INITIAL_DELAY_MS = 1e3;
var DEFAULT_MAX_DELAY_MS = 1e4;
var DEFAULT_TIMEOUT_MS = 18e5;
async function pollGoogleInteractionUntilTerminal({ baseURL, interactionId, headers, fetch, abortSignal, initialDelayMs = DEFAULT_INITIAL_DELAY_MS, maxDelayMs = DEFAULT_MAX_DELAY_MS, timeoutMs = DEFAULT_TIMEOUT_MS }) {
if (interactionId == null || interactionId.length === 0) throw new Error("google.interactions: cannot poll a background interaction without an id. The POST response did not include an interaction id.");
const startedAt = Date.now();
let nextDelayMs = initialDelayMs;
const url = `${baseURL}/interactions/${encodeURIComponent(interactionId)}`;
const cancelOnServer = () => cancelGoogleInteraction({
baseURL,
interactionId,
headers,
fetch
});
try {
while (true) {
if (abortSignal == null ? void 0 : abortSignal.aborted) {
await cancelOnServer();
throw new DOMException("Polling was aborted", "AbortError");
}
if (Date.now() - startedAt > timeoutMs) throw new Error(`google.interactions: timed out polling interaction ${interactionId} after ${timeoutMs}ms.`);
await delay$2(nextDelayMs, { abortSignal });
const { value: response, rawValue: rawResponse, responseHeaders } = await getFromApi$2({
url,
headers,
failedResponseHandler: googleFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$2(googleInteractionsResponseSchema),
abortSignal,
fetch
});
if (isTerminalStatus(response.status)) return {
response,
rawResponse,
responseHeaders
};
nextDelayMs = Math.min(nextDelayMs * 2, maxDelayMs);
}
} catch (error) {
if (isAbortError$2(error)) await cancelOnServer();
throw error;
}
}
function prepareGoogleInteractionsTools({ tools, toolChoice }) {
var _a2, _b, _c, _d;
const toolWarnings = [];
const normalized = (tools == null ? void 0 : tools.length) ? tools : void 0;
if (normalized == null) return {
tools: void 0,
toolChoice: void 0,
toolWarnings
};
const interactionsTools = [];
for (const tool of normalized) {
if (tool.type === "function") {
interactionsTools.push({
type: "function",
name: tool.name,
description: (_a2 = tool.description) != null ? _a2 : "",
parameters: tool.inputSchema
});
continue;
}
if (tool.type === "provider") {
const args = (_b = tool.args) != null ? _b : {};
switch (tool.id) {
case "google.google_search": {
const searchTypesArg = args.searchTypes;
let search_types;
if (searchTypesArg != null && typeof searchTypesArg === "object") {
const list = [];
if (searchTypesArg.webSearch != null) list.push("web_search");
if (searchTypesArg.imageSearch != null) list.push("image_search");
if (list.length > 0) search_types = list;
}
interactionsTools.push({
type: "google_search",
...search_types != null ? { search_types } : {}
});
break;
}
case "google.code_execution":
interactionsTools.push({ type: "code_execution" });
break;
case "google.url_context":
interactionsTools.push({ type: "url_context" });
break;
case "google.file_search":
interactionsTools.push({
type: "file_search",
...args.fileSearchStoreNames != null ? { file_search_store_names: args.fileSearchStoreNames } : {},
...args.topK != null ? { top_k: args.topK } : {},
...args.metadataFilter != null ? { metadata_filter: args.metadataFilter } : {}
});
break;
case "google.google_maps":
interactionsTools.push({
type: "google_maps",
...args.latitude != null ? { latitude: args.latitude } : {},
...args.longitude != null ? { longitude: args.longitude } : {},
...args.enableWidget != null ? { enable_widget: args.enableWidget } : {}
});
break;
case "google.computer_use":
interactionsTools.push({
type: "computer_use",
environment: (_c = args.environment) != null ? _c : "browser",
...args.excludedPredefinedFunctions != null ? { excludedPredefinedFunctions: args.excludedPredefinedFunctions } : {}
});
break;
case "google.mcp_server":
interactionsTools.push({
type: "mcp_server",
...args.name != null ? { name: args.name } : {},
...args.url != null ? { url: args.url } : {},
...args.headers != null ? { headers: args.headers } : {},
...args.allowedTools != null ? { allowed_tools: args.allowedTools } : {}
});
break;
case "google.retrieval": {
const vertexAiSearchConfig = (_d = args.vertexAiSearchConfig) != null ? _d : void 0;
interactionsTools.push({
type: "retrieval",
...args.retrievalTypes != null ? { retrieval_types: args.retrievalTypes } : { retrieval_types: ["vertex_ai_search"] },
...vertexAiSearchConfig != null ? { vertex_ai_search_config: vertexAiSearchConfig } : {}
});
break;
}
default: toolWarnings.push({
type: "unsupported",
feature: `provider-defined tool ${tool.id}`,
details: `provider-defined tool ${tool.id} is not supported by google.interactions; tool dropped.`
});
}
continue;
}
toolWarnings.push({
type: "unsupported",
feature: `tool of type ${tool.type}`,
details: "Only function tools and google.* provider-defined tools are supported by google.interactions; tool dropped."
});
}
const hasFunctionTool = interactionsTools.some((t) => t.type === "function");
let mappedToolChoice;
if (toolChoice != null && hasFunctionTool) switch (toolChoice.type) {
case "auto":
mappedToolChoice = "auto";
break;
case "required":
mappedToolChoice = "any";
break;
case "none":
mappedToolChoice = "none";
break;
case "tool": mappedToolChoice = { allowed_tools: {
mode: "validated",
tools: [toolChoice.toolName]
} };
}
return {
tools: interactionsTools.length > 0 ? interactionsTools : void 0,
toolChoice: mappedToolChoice,
toolWarnings
};
}
var DEFAULT_MAX_RETRIES = 3;
var DEFAULT_RETRY_DELAY_MS = 500;
function streamGoogleInteractionEvents({ baseURL, interactionId, headers, fetch, abortSignal, maxRetries = DEFAULT_MAX_RETRIES, retryDelayMs = DEFAULT_RETRY_DELAY_MS }) {
if (interactionId.length === 0) throw new Error("google.interactions: cannot stream a background interaction without an id.");
const eventSourceHeaders = {
...headers,
accept: "text/event-stream"
};
let lastEventId;
let complete = false;
let attempt = 0;
let receivedAnyEventThisAttempt = false;
let currentReader;
const internalAbort = new AbortController();
const upstreamAbortHandler = () => internalAbort.abort();
if (abortSignal != null) {
if (abortSignal.aborted) internalAbort.abort();
else abortSignal.addEventListener("abort", upstreamAbortHandler, { once: true });
}
const effectiveSignal = internalAbort.signal;
function buildUrl() {
const base = `${baseURL}/interactions/${encodeURIComponent(interactionId)}`;
const params = new URLSearchParams({ stream: "true" });
if (lastEventId != null) params.set("last_event_id", lastEventId);
return `${base}?${params.toString()}`;
}
async function openReader() {
const { value: stream } = await getFromApi$2({
url: buildUrl(),
headers: eventSourceHeaders,
failedResponseHandler: googleFailedResponseHandler,
successfulResponseHandler: createEventSourceResponseHandler$2(googleInteractionsEventSchema),
abortSignal: effectiveSignal,
fetch
});
return stream.getReader();
}
return new ReadableStream({
async start(controller) {
try {
while (!complete && !effectiveSignal.aborted) {
if (currentReader == null) try {
currentReader = await openReader();
receivedAnyEventThisAttempt = false;
} catch (error) {
if (isAbortError$2(error) || effectiveSignal.aborted) {
controller.error(error);
return;
}
attempt++;
if (attempt >= maxRetries) {
controller.error(error);
return;
}
await delay$2(retryDelayMs * attempt, { abortSignal: effectiveSignal });
continue;
}
try {
const { done, value } = await currentReader.read();
if (done) {
currentReader = void 0;
if (complete) break;
if (!receivedAnyEventThisAttempt) {
attempt++;
if (attempt >= maxRetries) {
controller.error(/* @__PURE__ */ new Error("google.interactions: SSE stream closed without producing any events."));
return;
}
await delay$2(retryDelayMs * attempt, { abortSignal: effectiveSignal });
} else attempt = 0;
continue;
}
receivedAnyEventThisAttempt = true;
if (value.success) {
const ev = value.value;
if (typeof ev.event_id === "string" && ev.event_id.length > 0) lastEventId = ev.event_id;
if (ev.event_type === "interaction.completed" || ev.event_type === "error") complete = true;
}
controller.enqueue(value);
} catch (error) {
if (isAbortError$2(error) || effectiveSignal.aborted) {
controller.error(error);
return;
}
currentReader = void 0;
attempt++;
if (attempt >= maxRetries) {
controller.error(error);
return;
}
await delay$2(retryDelayMs * attempt, { abortSignal: effectiveSignal });
}
}
controller.close();
} catch (error) {
controller.error(error);
} finally {
if (abortSignal != null) abortSignal.removeEventListener("abort", upstreamAbortHandler);
currentReader?.cancel().catch(() => {});
currentReader = void 0;
if (effectiveSignal.aborted && !complete) await cancelGoogleInteraction({
baseURL,
interactionId,
headers,
fetch
});
}
},
cancel() {
internalAbort.abort();
currentReader?.cancel().catch(() => {});
currentReader = void 0;
}
});
}
function synthesizeGoogleInteractionsAgentStream({ response, warnings, generateId: generateId3, includeRawChunks, headerServiceTier }) {
return new ReadableStream({ start(controller) {
var _a2, _b, _c;
controller.enqueue({
type: "stream-start",
warnings
});
const interactionId = typeof response.id === "string" && response.id.length > 0 ? response.id : void 0;
let timestamp;
const created = response.created;
if (typeof created === "string") {
const parsed = new Date(created);
if (!Number.isNaN(parsed.getTime())) timestamp = parsed;
}
controller.enqueue({
type: "response-metadata",
...interactionId != null ? { id: interactionId } : {},
modelId: (_a2 = response.model) != null ? _a2 : void 0,
...timestamp ? { timestamp } : {}
});
if (includeRawChunks) controller.enqueue({
type: "raw",
rawValue: response
});
const { content, hasFunctionCall } = parseGoogleInteractionsOutputs({
steps: (_b = response.steps) != null ? _b : null,
generateId: generateId3,
interactionId
});
let blockCounter = 0;
const nextBlockId = () => `${interactionId != null ? interactionId : "agent"}:${blockCounter++}`;
for (const part of content) switch (part.type) {
case "text": {
const id = nextBlockId();
const providerMetadata2 = part.providerMetadata;
controller.enqueue({
type: "text-start",
id
});
if (part.text.length > 0) controller.enqueue({
type: "text-delta",
id,
delta: part.text
});
controller.enqueue({
type: "text-end",
id,
...providerMetadata2 ? { providerMetadata: providerMetadata2 } : {}
});
break;
}
case "reasoning": {
const id = nextBlockId();
const providerMetadata2 = part.providerMetadata;
controller.enqueue({
type: "reasoning-start",
id
});
if (part.text.length > 0) controller.enqueue({
type: "reasoning-delta",
id,
delta: part.text
});
controller.enqueue({
type: "reasoning-end",
id,
...providerMetadata2 ? { providerMetadata: providerMetadata2 } : {}
});
break;
}
case "tool-call": {
const providerMetadata2 = part.providerMetadata;
controller.enqueue({
type: "tool-input-start",
id: part.toolCallId,
toolName: part.toolName,
...part.providerExecuted ? { providerExecuted: part.providerExecuted } : {}
});
controller.enqueue({
type: "tool-input-delta",
id: part.toolCallId,
delta: part.input
});
controller.enqueue({
type: "tool-input-end",
id: part.toolCallId
});
controller.enqueue({
type: "tool-call",
toolCallId: part.toolCallId,
toolName: part.toolName,
input: part.input,
...part.providerExecuted ? { providerExecuted: part.providerExecuted } : {},
...providerMetadata2 ? { providerMetadata: providerMetadata2 } : {}
});
break;
}
case "tool-result":
controller.enqueue({
type: "tool-result",
toolCallId: part.toolCallId,
toolName: part.toolName,
result: part.result
});
break;
case "source":
case "file": controller.enqueue(part);
}
const serviceTier = (_c = response.service_tier) != null ? _c : headerServiceTier;
const finishReason = {
unified: mapGoogleInteractionsFinishReason({
status: response.status,
hasFunctionCall
}),
raw: response.status
};
const providerMetadata = { google: {
...interactionId != null ? { interactionId } : {},
...serviceTier != null ? { serviceTier } : {}
} };
controller.enqueue({
type: "finish",
finishReason,
usage: convertGoogleInteractionsUsage(response.usage),
providerMetadata
});
controller.close();
} });
}
var GoogleInteractionsLanguageModel = class {
constructor(modelOrAgent, config) {
this.specificationVersion = "v3";
if (typeof modelOrAgent === "string") {
this.modelId = modelOrAgent;
this.agent = void 0;
} else if ("managedAgent" in modelOrAgent) {
this.modelId = modelOrAgent.managedAgent;
this.agent = modelOrAgent.managedAgent;
} else {
this.modelId = modelOrAgent.agent;
this.agent = modelOrAgent.agent;
}
this.config = config;
}
get provider() {
return this.config.provider;
}
get supportedUrls() {
if (this.config.supportedUrls) return this.config.supportedUrls();
return {
"image/*": [/^https?:\/\/.+/],
"application/pdf": [/^https?:\/\/.+/],
"audio/*": [/^https?:\/\/.+/],
"video/*": [
/^https?:\/\/(www\.)?youtube\.com\/watch\?v=.+/,
/^https?:\/\/youtu\.be\/.+/,
/^gs:\/\/.+/
]
};
}
async getArgs(options) {
var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F;
const warnings = [];
const opts = await parseProviderOptions$1({
provider: "google",
providerOptions: options.providerOptions,
schema: googleInteractionsLanguageModelOptions
});
const isAgent = this.agent != null;
if (!isAgent) {
if (options.frequencyPenalty != null) warnings.push({
type: "unsupported",
feature: "frequencyPenalty"
});
if (options.presencePenalty != null) warnings.push({
type: "unsupported",
feature: "presencePenalty"
});
}
const hasTools = options.tools != null && options.tools.length > 0;
let toolsForBody;
let toolChoiceForBody;
if (hasTools) {
const prepared = prepareGoogleInteractionsTools({
tools: options.tools,
toolChoice: options.toolChoice
});
toolsForBody = prepared.tools;
toolChoiceForBody = prepared.toolChoice;
warnings.push(...prepared.toolWarnings);
}
const responseFormatEntries = [];
if (((_a2 = options.responseFormat) == null ? void 0 : _a2.type) === "json") {
if (isAgent) warnings.push({
type: "other",
message: "google.interactions: structured output (responseFormat) is not supported when an agent is set; responseFormat will be ignored."
});
else {
const entry = {
type: "text",
mime_type: "application/json",
...options.responseFormat.schema != null ? { schema: options.responseFormat.schema } : {}
};
responseFormatEntries.push(entry);
}
}
if ((opts == null ? void 0 : opts.responseFormat) != null) {
for (const entry of opts.responseFormat) if (entry.type === "text") responseFormatEntries.push(pruneUndefined({
type: "text",
mime_type: (_b = entry.mimeType) != null ? _b : void 0,
schema: (_c = entry.schema) != null ? _c : void 0
}));
else if (entry.type === "image") responseFormatEntries.push(pruneUndefined({
type: "image",
mime_type: (_d = entry.mimeType) != null ? _d : void 0,
aspect_ratio: (_e = entry.aspectRatio) != null ? _e : void 0,
image_size: (_f = entry.imageSize) != null ? _f : void 0
}));
else if (entry.type === "audio") responseFormatEntries.push(pruneUndefined({
type: "audio",
mime_type: (_g = entry.mimeType) != null ? _g : void 0
}));
else if (entry.type === "video") responseFormatEntries.push(pruneUndefined({
type: "video",
aspect_ratio: (_h = entry.aspectRatio) != null ? _h : void 0,
resolution: (_i = entry.resolution) != null ? _i : void 0,
duration: (_j = entry.duration) != null ? _j : void 0,
delivery: (_k = entry.delivery) != null ? _k : void 0,
gcs_uri: (_l = entry.gcsUri) != null ? _l : void 0
}));
}
const { input, systemInstruction: convertedSystemInstruction, warnings: convWarnings } = convertToGoogleInteractionsInput({
prompt: options.prompt,
previousInteractionId: (_m = opts == null ? void 0 : opts.previousInteractionId) != null ? _m : void 0,
store: (_n = opts == null ? void 0 : opts.store) != null ? _n : void 0,
mediaResolution: (_o = opts == null ? void 0 : opts.mediaResolution) != null ? _o : void 0
});
warnings.push(...convWarnings);
let systemInstruction = convertedSystemInstruction;
const optionSystemInstruction = (_p = opts == null ? void 0 : opts.systemInstruction) != null ? _p : void 0;
if (systemInstruction != null && optionSystemInstruction != null) warnings.push({
type: "other",
message: "google.interactions: both AI SDK system message and providerOptions.google.systemInstruction were set; using the AI SDK system message."
});
else if (systemInstruction == null && optionSystemInstruction != null) systemInstruction = optionSystemInstruction;
let generationConfig;
if (isAgent) {
const droppedFields = [];
if (options.temperature != null) droppedFields.push("temperature");
if (options.topP != null) droppedFields.push("topP");
if (options.topK != null) droppedFields.push("topK");
if (options.frequencyPenalty != null) droppedFields.push("frequencyPenalty");
if (options.presencePenalty != null) droppedFields.push("presencePenalty");
if (options.seed != null) droppedFields.push("seed");
if (options.stopSequences != null && options.stopSequences.length > 0) droppedFields.push("stopSequences");
if (options.maxOutputTokens != null) droppedFields.push("maxOutputTokens");
if ((opts == null ? void 0 : opts.thinkingLevel) != null) droppedFields.push("thinkingLevel");
if ((opts == null ? void 0 : opts.thinkingSummaries) != null) droppedFields.push("thinkingSummaries");
if ((opts == null ? void 0 : opts.imageConfig) != null) droppedFields.push("imageConfig");
if (droppedFields.length > 0) warnings.push({
type: "other",
message: `google.interactions: ${droppedFields.join(", ")} ${droppedFields.length === 1 ? "is" : "are"} not supported when an agent is set; use providerOptions.google.agentConfig instead. Dropped from the request body.`
});
generationConfig = void 0;
} else {
generationConfig = pruneUndefined({
temperature: (_q = options.temperature) != null ? _q : void 0,
top_p: (_r = options.topP) != null ? _r : void 0,
top_k: (_s = options.topK) != null ? _s : void 0,
seed: (_t = options.seed) != null ? _t : void 0,
stop_sequences: options.stopSequences != null && options.stopSequences.length > 0 ? options.stopSequences : void 0,
max_output_tokens: (_u = options.maxOutputTokens) != null ? _u : void 0,
thinking_level: (_v = opts == null ? void 0 : opts.thinkingLevel) != null ? _v : void 0,
thinking_summaries: (_w = opts == null ? void 0 : opts.thinkingSummaries) != null ? _w : void 0,
tool_choice: toolChoiceForBody
});
if ((opts == null ? void 0 : opts.imageConfig) != null) {
const alreadyHasImageEntry = responseFormatEntries.some((entry) => entry.type === "image");
warnings.push({
type: "other",
message: alreadyHasImageEntry ? "google.interactions: providerOptions.google.imageConfig is deprecated and was ignored because providerOptions.google.responseFormat already supplies an image entry. Use responseFormat exclusively." : "google.interactions: providerOptions.google.imageConfig is deprecated. Use providerOptions.google.responseFormat with a { type: \"image\", ... } entry instead."
});
if (!alreadyHasImageEntry) responseFormatEntries.push({
type: "image",
mime_type: "image/png",
...opts.imageConfig.aspectRatio != null ? { aspect_ratio: opts.imageConfig.aspectRatio } : {},
...opts.imageConfig.imageSize != null ? { image_size: opts.imageConfig.imageSize } : {}
});
}
}
let agentConfig;
if (isAgent && (opts == null ? void 0 : opts.agentConfig) != null) {
const ac = opts.agentConfig;
if (ac.type === "deep-research") agentConfig = pruneUndefined({
type: "deep-research",
thinking_summaries: (_x = ac.thinkingSummaries) != null ? _x : void 0,
visualization: (_y = ac.visualization) != null ? _y : void 0,
collaborative_planning: (_z = ac.collaborativePlanning) != null ? _z : void 0
});
else if (ac.type === "dynamic") agentConfig = { type: "dynamic" };
}
let environment;
if ((opts == null ? void 0 : opts.environment) != null) {
if (!isAgent) warnings.push({
type: "other",
message: "google.interactions: environment is only supported when an agent is set; environment will be omitted from the request body."
});
else if (typeof opts.environment === "string") environment = opts.environment;
else {
const env = opts.environment;
const sources = (_A = env.sources) == null ? void 0 : _A.map((s) => {
var _a3;
if (s.type === "inline") return {
type: "inline",
content: s.content,
target: s.target
};
return pruneUndefined({
type: s.type,
source: s.source,
target: (_a3 = s.target) != null ? _a3 : void 0
});
});
let network;
if (env.network === "disabled") network = "disabled";
else if (env.network != null) network = { allowlist: env.network.allowlist.map((entry) => {
var _a3;
return pruneUndefined({
domain: entry.domain,
transform: (_a3 = entry.transform) != null ? _a3 : void 0
});
}) };
environment = pruneUndefined({
type: "remote",
sources: sources != null && sources.length > 0 ? sources : void 0,
network
});
}
}
return {
args: pruneUndefined({
...isAgent ? { agent: this.agent } : { model: this.modelId },
input,
system_instruction: systemInstruction,
tools: toolsForBody,
response_format: responseFormatEntries.length > 0 ? responseFormatEntries : void 0,
response_modalities: (opts == null ? void 0 : opts.responseModalities) != null ? opts.responseModalities : void 0,
previous_interaction_id: (_B = opts == null ? void 0 : opts.previousInteractionId) != null ? _B : void 0,
service_tier: (_C = opts == null ? void 0 : opts.serviceTier) != null ? _C : void 0,
store: (_D = opts == null ? void 0 : opts.store) != null ? _D : void 0,
generation_config: generationConfig != null && Object.keys(generationConfig).length > 0 ? generationConfig : void 0,
agent_config: agentConfig,
environment,
background: (_E = opts == null ? void 0 : opts.background) != null ? _E : void 0
}),
warnings,
isAgent,
isBackground: (opts == null ? void 0 : opts.background) === true,
pollingTimeoutMs: (_F = opts == null ? void 0 : opts.pollingTimeoutMs) != null ? _F : void 0
};
}
async doGenerate(options) {
var _a2, _b, _c, _d, _e, _f;
const { args, warnings, isAgent, isBackground, pollingTimeoutMs } = await this.getArgs(options);
const url = `${this.config.baseURL}/interactions`;
const mergedHeaders = combineHeaders$2(INTERACTIONS_API_REVISION_HEADER, this.config.headers ? await resolve$1(this.config.headers) : void 0, options.headers);
let { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi$2({
url,
headers: mergedHeaders,
body: args,
failedResponseHandler: googleFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$2(googleInteractionsResponseSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
if ((isAgent || isBackground) && !isTerminalStatus(response.status)) {
const polled = await pollGoogleInteractionUntilTerminal({
baseURL: this.config.baseURL,
interactionId: response.id,
headers: mergedHeaders,
fetch: this.config.fetch,
abortSignal: options.abortSignal,
timeoutMs: pollingTimeoutMs
});
response = polled.response;
rawResponse = polled.rawResponse;
responseHeaders = (_a2 = polled.responseHeaders) != null ? _a2 : responseHeaders;
}
const interactionId = typeof response.id === "string" && response.id.length > 0 ? response.id : void 0;
const { content, hasFunctionCall } = parseGoogleInteractionsOutputs({
steps: (_b = response.steps) != null ? _b : null,
generateId: (_c = this.config.generateId) != null ? _c : generateId$2,
interactionId
});
const finishReason = {
unified: mapGoogleInteractionsFinishReason({
status: response.status,
hasFunctionCall
}),
raw: response.status
};
const serviceTier = (_e = (_d = response.service_tier) != null ? _d : responseHeaders == null ? void 0 : responseHeaders["x-gemini-service-tier"]) != null ? _e : void 0;
const outputTokensByModality = getGoogleInteractionsOutputTokensByModality(response.usage);
const providerMetadata = { google: {
...interactionId != null ? { interactionId } : {},
...serviceTier != null ? { serviceTier } : {},
...outputTokensByModality != null ? { outputTokensByModality } : {}
} };
let timestamp;
if (typeof response.created === "string") {
const parsed = new Date(response.created);
if (!Number.isNaN(parsed.getTime())) timestamp = parsed;
}
return {
content,
finishReason,
usage: convertGoogleInteractionsUsage(response.usage),
warnings,
providerMetadata,
request: { body: args },
response: {
headers: responseHeaders,
body: rawResponse,
...interactionId != null ? { id: interactionId } : {},
...timestamp ? { timestamp } : {},
modelId: (_f = response.model) != null ? _f : void 0
}
};
}
async doStream(options) {
var _a2;
const { args, warnings, isBackground, pollingTimeoutMs } = await this.getArgs(options);
const url = `${this.config.baseURL}/interactions`;
const mergedHeaders = combineHeaders$2(INTERACTIONS_API_REVISION_HEADER, this.config.headers ? await resolve$1(this.config.headers) : void 0, options.headers);
if (isBackground) return this.doStreamBackground({
args,
warnings,
url,
mergedHeaders,
options,
pollingTimeoutMs
});
const body = {
...args,
stream: true
};
const { responseHeaders, value: response } = await postJsonToApi$2({
url,
headers: mergedHeaders,
body,
failedResponseHandler: googleFailedResponseHandler,
successfulResponseHandler: createEventSourceResponseHandler$2(googleInteractionsEventSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const headerServiceTier = responseHeaders == null ? void 0 : responseHeaders["x-gemini-service-tier"];
const transform = buildGoogleInteractionsStreamTransform({
warnings,
generateId: (_a2 = this.config.generateId) != null ? _a2 : generateId$2,
includeRawChunks: options.includeRawChunks,
serviceTier: headerServiceTier
});
return {
stream: response.pipeThrough(transform),
request: { body },
response: { headers: responseHeaders }
};
}
async doStreamBackground({ args, warnings, url, mergedHeaders, options, pollingTimeoutMs }) {
var _a2, _b;
const { responseHeaders: postHeaders, value: postResponse } = await postJsonToApi$2({
url,
headers: mergedHeaders,
body: args,
failedResponseHandler: googleFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$2(googleInteractionsResponseSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const interactionId = postResponse.id;
if (interactionId == null || interactionId.length === 0) throw new Error("google.interactions: background POST response did not include an interaction id; cannot stream the result.");
const headerServiceTier = postHeaders == null ? void 0 : postHeaders["x-gemini-service-tier"];
if (isTerminalStatus(postResponse.status)) return {
stream: synthesizeGoogleInteractionsAgentStream({
response: postResponse,
warnings,
generateId: (_a2 = this.config.generateId) != null ? _a2 : generateId$2,
includeRawChunks: options.includeRawChunks,
headerServiceTier
}),
request: { body: args },
response: { headers: postHeaders }
};
const events = streamGoogleInteractionEvents({
baseURL: this.config.baseURL,
interactionId,
headers: mergedHeaders,
fetch: this.config.fetch,
abortSignal: options.abortSignal
});
const transform = buildGoogleInteractionsStreamTransform({
warnings,
generateId: (_b = this.config.generateId) != null ? _b : generateId$2,
includeRawChunks: options.includeRawChunks,
serviceTier: headerServiceTier
});
return {
stream: events.pipeThrough(transform),
request: { body: args },
response: { headers: postHeaders }
};
}
};
var INTERACTIONS_API_REVISION_HEADER = { "Api-Revision": "2026-05-20" };
function pruneUndefined(obj) {
const result = {};
for (const [key, value] of Object.entries(obj)) {
if (value === void 0) continue;
result[key] = value;
}
return result;
}
var supportedExternalUrlMediaTypes = [
"text/html",
"text/css",
"text/plain",
"text/xml",
"text/csv",
"text/rtf",
"text/javascript",
"application/json",
"application/pdf",
"image/bmp",
"image/jpeg",
"image/png",
"image/webp",
"video/mp4",
"video/mpeg",
"video/quicktime",
"video/avi",
"video/x-flv",
"video/mpg",
"video/webm",
"video/wmv",
"video/3gpp"
];
var externalHttpsUrlPattern = /^https:\/\/.*$/;
function supportsExternalFileUrls(modelId) {
return /(^|\/)gemini-/.test(modelId) && !/(^|\/)gemini-2\.0/.test(modelId);
}
function createGoogleGenerativeAI(options = {}) {
var _a2, _b;
const baseURL = (_a2 = withoutTrailingSlash$2(options.baseURL)) != null ? _a2 : "https://generativelanguage.googleapis.com/v1beta";
const providerName = (_b = options.name) != null ? _b : "google.generative-ai";
const getHeaders = () => withUserAgentSuffix$2({
"x-goog-api-key": loadApiKey$2({
apiKey: options.apiKey,
environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY",
description: "Google Generative AI"
}),
...options.headers
}, `ai-sdk/google/${VERSION$5}`);
const createChatModel = (modelId) => {
var _a3;
return new GoogleGenerativeAILanguageModel(modelId, {
provider: providerName,
baseURL,
headers: getHeaders,
generateId: (_a3 = options.generateId) != null ? _a3 : generateId$2,
supportedUrls: () => ({
"*": [
new RegExp(`^${baseURL}/files/.*$`),
new RegExp(`^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`),
new RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)
],
...supportsExternalFileUrls(modelId) ? Object.fromEntries(supportedExternalUrlMediaTypes.map((mediaType) => [mediaType, [externalHttpsUrlPattern]])) : {}
}),
fetch: options.fetch
});
};
const createEmbeddingModel = (modelId) => new GoogleGenerativeAIEmbeddingModel(modelId, {
provider: providerName,
baseURL,
headers: getHeaders,
fetch: options.fetch
});
const createImageModel = (modelId, settings = {}) => new GoogleGenerativeAIImageModel(modelId, settings, {
provider: providerName,
baseURL,
headers: getHeaders,
fetch: options.fetch
});
const createTranscriptionModel = (modelId) => new GoogleTranscriptionModel(modelId, {
provider: `${providerName}.transcription`,
baseURL,
headers: getHeaders,
fetch: options.fetch
});
const createVideoModel = (modelId) => {
var _a3;
return new GoogleGenerativeAIVideoModel(modelId, {
provider: providerName,
baseURL,
headers: getHeaders,
fetch: options.fetch,
generateId: (_a3 = options.generateId) != null ? _a3 : generateId$2
});
};
const createInteractionsModel = (modelIdOrAgent) => {
var _a3;
return new GoogleInteractionsLanguageModel(modelIdOrAgent, {
provider: `${providerName}.interactions`,
baseURL,
headers: getHeaders,
generateId: (_a3 = options.generateId) != null ? _a3 : generateId$2,
fetch: options.fetch
});
};
const provider = function(modelId) {
if (new.target) throw new Error("The Google Generative AI model function cannot be called with the new keyword.");
return createChatModel(modelId);
};
provider.specificationVersion = "v3";
provider.languageModel = createChatModel;
provider.chat = createChatModel;
provider.generativeAI = createChatModel;
provider.embedding = createEmbeddingModel;
provider.embeddingModel = createEmbeddingModel;
provider.textEmbedding = createEmbeddingModel;
provider.textEmbeddingModel = createEmbeddingModel;
provider.image = createImageModel;
provider.imageModel = createImageModel;
provider.transcription = createTranscriptionModel;
provider.transcriptionModel = createTranscriptionModel;
provider.video = createVideoModel;
provider.videoModel = createVideoModel;
provider.interactions = createInteractionsModel;
provider.tools = googleTools;
return provider;
}
createGoogleGenerativeAI();
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/groq/4.0.74/8ac5aad97fde20a7dfb371f3f59dc0bb413b926780ad139c8070529e218e3cd3/node_modules/@ai-sdk/groq/dist/index.js
function convertGroqUsage(usage) {
if (usage == null) return createNullLanguageModelUsage();
const promptTokens = usage.prompt_tokens ?? 0;
const cacheReadTokens = usage.prompt_tokens_details?.cached_tokens ?? void 0;
const completionTokens = usage.completion_tokens ?? 0;
const reasoningTokens = usage.completion_tokens_details?.reasoning_tokens ?? void 0;
const textTokens = reasoningTokens != null ? Math.max(0, completionTokens - reasoningTokens) : completionTokens;
return {
inputTokens: {
total: promptTokens,
noCache: cacheReadTokens != null ? promptTokens - cacheReadTokens : promptTokens,
cacheRead: cacheReadTokens,
cacheWrite: void 0
},
outputTokens: {
total: completionTokens,
text: textTokens,
reasoning: reasoningTokens
},
raw: usage
};
}
function convertToGroqChatMessages(prompt) {
const messages = [];
for (const { role, content } of prompt) switch (role) {
case "system":
messages.push({
role: "system",
content
});
break;
case "user":
if (content.length === 1 && content[0].type === "text") {
messages.push({
role: "user",
content: content[0].text
});
break;
}
messages.push({
role: "user",
content: content.map((part) => {
switch (part.type) {
case "text": return {
type: "text",
text: part.text
};
case "file": switch (part.data.type) {
case "reference": throw new UnsupportedFunctionalityError({ functionality: "file parts with provider references" });
case "text": throw new UnsupportedFunctionalityError({ functionality: "text file parts" });
case "url":
case "data":
if (getTopLevelMediaType$2(part.mediaType) !== "image") throw new UnsupportedFunctionalityError({ functionality: "Non-image file content parts" });
return {
type: "image_url",
image_url: { url: part.data.type === "url" ? part.data.url.toString() : `data:${resolveFullMediaType({ part })};base64,${convertToBase64(part.data.data)}` }
};
}
}
})
});
break;
case "assistant": {
let text = "";
let reasoning = "";
const toolCalls = [];
for (const part of content) switch (part.type) {
case "reasoning":
reasoning += part.text;
break;
case "text":
text += part.text;
break;
case "tool-call": toolCalls.push({
id: part.toolCallId,
type: "function",
function: {
name: part.toolName,
arguments: JSON.stringify(part.input)
}
});
}
messages.push({
role: "assistant",
content: text,
...reasoning.length > 0 ? { reasoning } : null,
...toolCalls.length > 0 ? { tool_calls: toolCalls } : null
});
break;
}
case "tool":
for (const toolResponse of content) {
if (toolResponse.type === "tool-approval-response") continue;
const output = toolResponse.output;
let contentValue;
switch (output.type) {
case "text":
case "error-text":
contentValue = output.value;
break;
case "execution-denied":
contentValue = output.reason ?? "Tool call execution denied.";
break;
case "content":
case "json":
case "error-json": contentValue = JSON.stringify(output.value);
}
messages.push({
role: "tool",
tool_call_id: toolResponse.toolCallId,
content: contentValue
});
}
break;
default: throw new Error(`Unsupported role: ${role}`);
}
return messages;
}
const groqLanguageModelChatOptions = z.object({
reasoningFormat: z.enum([
"parsed",
"raw",
"hidden"
]).optional(),
/**
* Specifies the reasoning effort level for model inference.
* @see https://console.groq.com/docs/reasoning#reasoning-effort
*/
reasoningEffort: z.enum([
"none",
"default",
"low",
"medium",
"high"
]).optional(),
/**
* Whether to enable parallel function calling during tool use. Default to true.
*/
parallelToolCalls: z.boolean().optional(),
/**
* A unique identifier representing your end-user, which can help OpenAI to
* monitor and detect abuse. Learn more.
*/
user: z.string().optional(),
/**
* Whether to use structured outputs.
*
* @default true
*/
structuredOutputs: z.boolean().optional(),
/**
* Whether to use strict JSON schema validation.
* When true, the model uses constrained decoding to guarantee schema compliance.
* Only used when structured outputs are enabled and a schema is provided.
*
* @default true
*/
strictJsonSchema: z.boolean().optional(),
/**
* Service tier for the request.
* - 'on_demand': Default tier with consistent performance and fairness
* - 'performance': Prioritized tier for latency-sensitive workloads
* - 'flex': Higher throughput tier optimized for workloads that can handle occasional request failures
* - 'auto': Uses on_demand rate limits, then falls back to flex tier if exceeded
*
* @default 'on_demand'
*/
serviceTier: z.enum([
"on_demand",
"performance",
"flex",
"auto"
]).optional()
});
const groqErrorDataSchema = z.object({ error: z.object({
message: z.string(),
type: z.string()
}) });
const groqFailedResponseHandler = createJsonErrorResponseHandler({
errorSchema: groqErrorDataSchema,
errorToMessage: (data) => data.error.message
});
const modelsWithoutBrowserSearch = /* @__PURE__ */ new Set([
"gemma2-9b-it",
"llama-3.1-8b-instant",
"llama-3.3-70b-versatile",
"meta-llama/llama-guard-4-12b",
"deepseek-r1-distill-llama-70b",
"meta-llama/llama-4-maverick-17b-128e-instruct",
"meta-llama/llama-4-scout-17b-16e-instruct",
"meta-llama/llama-prompt-guard-2-22m",
"meta-llama/llama-prompt-guard-2-86m",
"moonshotai/kimi-k2-instruct-0905",
"qwen/qwen3.6-27b",
"llama-guard-3-8b",
"llama3-70b-8192",
"llama3-8b-8192",
"mixtral-8x7b-32768",
"qwen-qwq-32b",
"qwen-2.5-32b",
"deepseek-r1-distill-qwen-32b"
]);
function isBrowserSearchSupportedModel(modelId) {
return !modelsWithoutBrowserSearch.has(modelId);
}
function prepareTools$1({ tools, toolChoice, modelId }) {
tools = tools?.length ? tools : void 0;
const toolWarnings = [];
if (tools == null) return {
tools: void 0,
toolChoice: void 0,
toolWarnings
};
const groqTools = [];
for (const tool of tools) if (tool.type === "provider") {
if (tool.id === "groq.browser_search") {
if (!isBrowserSearchSupportedModel(modelId)) toolWarnings.push({
type: "unsupported",
feature: `provider-defined tool ${tool.id}`,
details: `Browser search is not supported on model ${modelId}.`
});
else groqTools.push({ type: "browser_search" });
} else toolWarnings.push({
type: "unsupported",
feature: `provider-defined tool ${tool.id}`
});
} else groqTools.push({
type: "function",
function: {
name: tool.name,
description: tool.description,
parameters: tool.inputSchema,
...tool.strict != null ? { strict: tool.strict } : {}
}
});
if (toolChoice == null) return {
tools: groqTools,
toolChoice: void 0,
toolWarnings
};
const type = toolChoice.type;
switch (type) {
case "auto":
case "none":
case "required": return {
tools: groqTools,
toolChoice: type,
toolWarnings
};
case "tool": return {
tools: groqTools,
toolChoice: {
type: "function",
function: { name: toolChoice.toolName }
},
toolWarnings
};
default: throw new UnsupportedFunctionalityError({ functionality: `tool choice type: ${type}` });
}
}
function mapGroqFinishReason(finishReason) {
switch (finishReason) {
case "stop": return "stop";
case "length": return "length";
case "content_filter": return "content-filter";
case "function_call":
case "tool_calls": return "tool-calls";
default: return "other";
}
}
function createGroqStreamError(error, data) {
return createProviderStreamError({
message: error.message,
type: error.type,
...getGroqStreamErrorMetadata(error.type),
data
});
}
function getGroqStreamErrorMetadata(type) {
switch (type) {
case "rate_limit_error": return {
statusCode: 429,
isRetryable: true
};
case "api_error":
case "internal_server_error":
case "server_error": return {
statusCode: 500,
isRetryable: true
};
case "overloaded_error":
case "service_unavailable": return {
statusCode: 503,
isRetryable: true
};
case "timeout":
case "timeout_error": return {
statusCode: 504,
isRetryable: true
};
case "authentication_error":
case "invalid_api_key": return {
statusCode: 401,
isRetryable: false
};
case "permission_error": return {
statusCode: 403,
isRetryable: false
};
case "not_found_error":
case "model_not_found": return {
statusCode: 404,
isRetryable: false
};
case "bad_request":
case "context_length_exceeded":
case "invalid_request_error": return {
statusCode: 400,
isRetryable: false
};
default: return {};
}
}
var GroqChatLanguageModel = class GroqChatLanguageModel {
static [WORKFLOW_SERIALIZE](model) {
return serializeModelOptions({
modelId: model.modelId,
config: model.config
});
}
static [WORKFLOW_DESERIALIZE](options) {
return new GroqChatLanguageModel(options.modelId, options.config);
}
constructor(modelId, config) {
this.specificationVersion = "v4";
this.supportedUrls = { "image/*": [/^https?:\/\/.*$/] };
this.modelId = modelId;
this.config = config;
}
get provider() {
return this.config.provider;
}
async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, responseFormat, seed, reasoning, tools, toolChoice, providerOptions }) {
const warnings = [];
const groqOptions = await parseProviderOptions({
provider: "groq",
providerOptions,
schema: groqLanguageModelChatOptions
});
let jsonResponseTool;
if (responseFormat?.type === "json" && responseFormat.schema != null && tools?.some((tool) => tool.type === "function")) {
let name = "json";
for (let suffix = 1; tools.some((tool) => tool.name === name); suffix++) name = `json_${suffix}`;
jsonResponseTool = {
type: "function",
name,
description: responseFormat.description ?? "Respond with a JSON object.",
inputSchema: responseFormat.schema
};
}
const structuredOutputs = groqOptions?.structuredOutputs ?? true;
const strictJsonSchema = groqOptions?.strictJsonSchema ?? true;
if (topK != null) warnings.push({
type: "unsupported",
feature: "topK"
});
if (responseFormat?.type === "json" && responseFormat.schema != null && !structuredOutputs && jsonResponseTool == null) warnings.push({
type: "unsupported",
feature: "responseFormat",
details: "JSON response format schema is only supported with structuredOutputs"
});
const { tools: groqTools, toolChoice: groqToolChoice, toolWarnings } = prepareTools$1({
tools: jsonResponseTool != null ? [...tools ?? [], jsonResponseTool] : tools,
toolChoice: jsonResponseTool == null ? toolChoice : toolChoice?.type === "tool" ? toolChoice : toolChoice?.type === "none" ? {
type: "tool",
toolName: jsonResponseTool.name
} : { type: "required" },
modelId: this.modelId
});
let reasoningEffort = groqOptions?.reasoningEffort;
if (reasoningEffort == null && isCustomReasoning(reasoning)) {
const supportsNoneReasoning = this.modelId === "qwen/qwen3.6-27b";
const alwaysReasons = this.modelId.startsWith("openai/gpt-oss");
if (reasoning === "none" && !supportsNoneReasoning && !alwaysReasons) warnings.push({
type: "unsupported",
feature: "reasoning",
details: `reasoning "${reasoning}" is not supported by this model.`
});
else reasoningEffort = mapReasoningToProviderEffort({
reasoning,
effortMap: {
...supportsNoneReasoning && { none: "none" },
low: "low",
medium: "medium",
high: "high"
},
warnings
});
}
return {
args: {
model: this.modelId,
user: groqOptions?.user,
parallel_tool_calls: jsonResponseTool != null ? false : groqOptions?.parallelToolCalls,
max_tokens: maxOutputTokens,
temperature,
top_p: topP,
frequency_penalty: frequencyPenalty,
presence_penalty: presencePenalty,
stop: stopSequences,
seed,
response_format: jsonResponseTool == null && responseFormat?.type === "json" ? structuredOutputs && responseFormat.schema != null ? {
type: "json_schema",
json_schema: {
schema: responseFormat.schema,
strict: strictJsonSchema,
name: responseFormat.name ?? "response",
description: responseFormat.description
}
} : { type: "json_object" } : void 0,
reasoning_format: groqOptions?.reasoningFormat,
reasoning_effort: reasoningEffort,
service_tier: groqOptions?.serviceTier,
messages: convertToGroqChatMessages(prompt),
tools: groqTools,
tool_choice: groqToolChoice
},
warnings: [...warnings, ...toolWarnings],
jsonResponseToolName: jsonResponseTool?.name
};
}
async doGenerate(options) {
const { args, warnings, jsonResponseToolName } = await this.getArgs(options);
const body = JSON.stringify(args);
const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({
url: this.config.url({
path: "/chat/completions",
modelId: this.modelId
}),
headers: combineHeaders(await resolve(this.config.headers), options.headers),
body: args,
failedResponseHandler: groqFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler(groqChatResponseSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const choice = response.choices[0];
if (choice == null) throw new InvalidResponseDataError({
data: rawResponse,
message: "Response did not contain any choices."
});
const content = [];
const reasoning = choice.message.reasoning;
if (reasoning != null && reasoning.length > 0) content.push({
type: "reasoning",
text: reasoning
});
const text = choice.message.content;
if (jsonResponseToolName == null && text != null && text.length > 0) content.push({
type: "text",
text
});
if (choice.message.tool_calls != null) for (const toolCall of choice.message.tool_calls) if (toolCall.function.name === jsonResponseToolName) content.push({
type: "text",
text: toolCall.function.arguments
});
else content.push({
type: "tool-call",
toolCallId: toolCall.id || generateId(),
toolName: toolCall.function.name,
input: toolCall.function.arguments
});
return {
content,
finishReason: {
unified: jsonResponseToolName != null && content.some((part) => part.type === "text") && !content.some((part) => part.type === "tool-call") && choice.finish_reason === "tool_calls" ? "stop" : mapGroqFinishReason(choice.finish_reason),
raw: choice.finish_reason ?? void 0
},
usage: convertGroqUsage(response.usage),
response: {
...createLanguageModelResponseMetadata(response),
headers: responseHeaders,
body: rawResponse
},
warnings,
request: { body }
};
}
async doStream(options) {
const { args, warnings, jsonResponseToolName } = await this.getArgs(options);
const body = {
...args,
stream: true
};
const { responseHeaders, value: response } = await postJsonToApi({
url: this.config.url({
path: "/chat/completions",
modelId: this.modelId
}),
headers: combineHeaders(await resolve(this.config.headers), options.headers),
body,
failedResponseHandler: groqFailedResponseHandler,
successfulResponseHandler: createEventSourceResponseHandler(groqChatChunkSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
let toolCallTracker;
let finishReason = {
unified: "interrupted",
raw: void 0
};
let usage = void 0;
let isFirstChunk = true;
let isActiveText = false;
let isActiveReasoning = false;
const result = {
stream: response.pipeThrough(new TransformStream({
start(controller) {
toolCallTracker = new StreamingToolCallTracker(controller, {
generateId,
typeValidation: "required"
});
controller.enqueue({
type: "stream-start",
warnings
});
},
transform(chunk, controller) {
if (options.includeRawChunks) controller.enqueue({
type: "raw",
rawValue: chunk.rawValue
});
if (!chunk.success) {
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error: chunk.error
});
return;
}
const value = chunk.value;
if ("error" in value) {
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error: createGroqStreamError(value.error, value)
});
return;
}
if (isFirstChunk) {
isFirstChunk = false;
controller.enqueue({
type: "response-metadata",
...createLanguageModelResponseMetadata(value)
});
}
if (value.x_groq?.usage != null) usage = value.x_groq.usage;
const choice = value.choices[0];
if (choice?.finish_reason != null) finishReason = {
unified: mapGroqFinishReason(choice.finish_reason),
raw: choice.finish_reason
};
if (choice?.delta == null) return;
const delta = choice.delta;
if (delta.reasoning != null && delta.reasoning.length > 0) {
if (!isActiveReasoning) {
controller.enqueue({
type: "reasoning-start",
id: "reasoning-0"
});
isActiveReasoning = true;
}
controller.enqueue({
type: "reasoning-delta",
id: "reasoning-0",
delta: delta.reasoning
});
}
if (delta.content != null && delta.content.length > 0) {
if (isActiveReasoning) {
controller.enqueue({
type: "reasoning-end",
id: "reasoning-0"
});
isActiveReasoning = false;
}
if (!isActiveText) {
controller.enqueue({
type: "text-start",
id: "txt-0"
});
isActiveText = true;
}
controller.enqueue({
type: "text-delta",
id: "txt-0",
delta: delta.content
});
}
if (delta.tool_calls != null && delta.tool_calls.length > 0) {
if (isActiveReasoning) {
controller.enqueue({
type: "reasoning-end",
id: "reasoning-0"
});
isActiveReasoning = false;
}
for (const toolCallDelta of delta.tool_calls) toolCallTracker.processDelta(toolCallDelta);
}
},
flush(controller) {
if (isActiveReasoning) controller.enqueue({
type: "reasoning-end",
id: "reasoning-0"
});
if (isActiveText) controller.enqueue({
type: "text-end",
id: "txt-0"
});
toolCallTracker.flush();
controller.enqueue({
type: "finish",
finishReason,
usage: convertGroqUsage(usage)
});
}
})),
request: { body: JSON.stringify(body) },
response: { headers: responseHeaders }
};
return {
...result,
stream: jsonResponseToolName == null ? result.stream : result.stream.pipeThrough(convertJsonResponseToolStream(jsonResponseToolName))
};
}
};
const groqChatResponseSchema = lazySchema(() => zodSchema(z.object({
id: z.string().nullish(),
created: z.number().nullish(),
model: z.string().nullish(),
choices: z.array(z.object({
message: z.object({
content: z.string().nullish(),
reasoning: z.string().nullish(),
tool_calls: z.array(z.object({
id: z.string().nullish(),
type: z.literal("function"),
function: z.object({
name: z.string(),
arguments: z.string()
})
})).nullish()
}),
index: z.number(),
finish_reason: z.string().nullish()
})),
usage: z.object({
prompt_tokens: z.number().nullish(),
completion_tokens: z.number().nullish(),
total_tokens: z.number().nullish(),
prompt_tokens_details: z.object({ cached_tokens: z.number().nullish() }).nullish(),
completion_tokens_details: z.object({ reasoning_tokens: z.number().nullish() }).nullish()
}).nullish()
})));
const groqChatChunkSchema = lazySchema(() => zodSchema(z.union([z.object({
id: z.string().nullish(),
created: z.number().nullish(),
model: z.string().nullish(),
choices: z.array(z.object({
delta: z.object({
content: z.string().nullish(),
reasoning: z.string().nullish(),
tool_calls: z.array(z.object({
index: z.number(),
id: z.string().nullish(),
type: z.literal("function").optional(),
function: z.object({
name: z.string().nullish(),
arguments: z.string().nullish()
})
})).nullish()
}).nullish(),
finish_reason: z.string().nullable().optional(),
index: z.number()
})),
x_groq: z.object({ usage: z.object({
prompt_tokens: z.number().nullish(),
completion_tokens: z.number().nullish(),
total_tokens: z.number().nullish(),
prompt_tokens_details: z.object({ cached_tokens: z.number().nullish() }).nullish(),
completion_tokens_details: z.object({ reasoning_tokens: z.number().nullish() }).nullish()
}).nullish() }).nullish()
}), groqErrorDataSchema])));
const groqTranscriptionModelOptions = lazySchema(() => zodSchema(z.object({
language: z.string().nullish(),
prompt: z.string().nullish(),
responseFormat: z.string().nullish(),
temperature: z.number().min(0).max(1).nullish(),
timestampGranularities: z.array(z.string()).nullish()
})));
var GroqTranscriptionModel = class GroqTranscriptionModel {
get provider() {
return this.config.provider;
}
static [WORKFLOW_SERIALIZE](model) {
return serializeModelOptions({
modelId: model.modelId,
config: model.config
});
}
static [WORKFLOW_DESERIALIZE](options) {
return new GroqTranscriptionModel(options.modelId, options.config);
}
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
}
async getArgs({ audio, mediaType, providerOptions }) {
const warnings = [];
const groqOptions = await parseProviderOptions({
provider: "groq",
providerOptions,
schema: groqTranscriptionModelOptions
});
const formData = new FormData();
const blob = audio instanceof Uint8Array ? new Blob([audio]) : new Blob([convertBase64ToUint8Array(audio)]);
formData.append("model", this.modelId);
const fileExtension = mediaTypeToExtension(mediaType);
formData.append("file", new File([blob], "audio", { type: mediaType }), `audio.${fileExtension}`);
if (groqOptions) {
const transcriptionModelOptions = {
language: groqOptions.language ?? void 0,
prompt: groqOptions.prompt ?? void 0,
response_format: groqOptions.responseFormat ?? void 0,
temperature: groqOptions.temperature ?? void 0,
timestamp_granularities: groqOptions.timestampGranularities ?? void 0
};
for (const key in transcriptionModelOptions) {
const value = transcriptionModelOptions[key];
if (value !== void 0) {
if (Array.isArray(value)) for (const item of value) formData.append(`${key}[]`, String(item));
else formData.append(key, String(value));
}
}
}
return {
formData,
responseFormat: groqOptions?.responseFormat,
warnings
};
}
async doGenerate(options) {
const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
const { formData, responseFormat, warnings } = await this.getArgs(options);
const successfulResponseHandler = responseFormat === "text" ? groqTextTranscriptionResponseHandler : createJsonResponseHandler(groqTranscriptionResponseSchema);
const { value: response, responseHeaders, rawValue: rawResponse } = await postFormDataToApi({
url: this.config.url({
path: "/audio/transcriptions",
modelId: this.modelId
}),
headers: combineHeaders(await resolve(this.config.headers), options.headers),
formData,
failedResponseHandler: groqFailedResponseHandler,
successfulResponseHandler,
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
return {
text: response.text,
segments: response.segments?.map((segment) => ({
text: segment.text,
startSecond: segment.start,
endSecond: segment.end
})) ?? response.words?.map((word) => ({
text: word.word,
startSecond: word.start,
endSecond: word.end
})) ?? [],
language: response.language ?? void 0,
durationInSeconds: response.duration ?? void 0,
warnings,
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders,
body: rawResponse
}
};
}
};
const groqTranscriptionResponseSchema = z.object({
text: z.string(),
x_groq: z.object({ id: z.string() }),
task: z.string().nullish(),
language: z.string().nullish(),
duration: z.number().nullish(),
segments: z.array(z.object({
id: z.number(),
seek: z.number(),
start: z.number(),
end: z.number(),
text: z.string(),
tokens: z.array(z.number()),
temperature: z.number(),
avg_logprob: z.number(),
compression_ratio: z.number(),
no_speech_prob: z.number()
})).nullish(),
words: z.array(z.object({
word: z.string(),
start: z.number(),
end: z.number()
})).nullish()
});
const binaryResponseHandler = createBinaryResponseHandler();
const textDecoder$1 = new TextDecoder();
const groqTextTranscriptionResponseHandler = async (options) => {
const { value, responseHeaders } = await binaryResponseHandler(options);
const text = textDecoder$1.decode(value);
return {
value: { text },
rawValue: text,
responseHeaders
};
};
const groqTools = { browserSearch: createProviderExecutedToolFactory({
id: "groq.browser_search",
inputSchema: lazySchema(() => zodSchema(z.object({}))),
outputSchema: lazySchema(() => zodSchema(z.object({})))
}) };
const VERSION$4 = "4.0.74";
/**
* Create an Groq provider instance.
*/
function createGroq(options = {}) {
const baseURL = withoutTrailingSlash(options.baseURL) ?? "https://api.groq.com/openai/v1";
const getHeaders = () => resolveWith(options.apiKey, (apiKey) => withUserAgentSuffix({
Authorization: `Bearer ${loadApiKey({
apiKey,
environmentVariableName: "GROQ_API_KEY",
description: "Groq"
})}`,
...options.headers
}, `ai-sdk-groq/${VERSION$4}`));
const createChatModel = (modelId) => new GroqChatLanguageModel(modelId, {
provider: "groq.chat",
url: ({ path }) => `${baseURL}${path}`,
headers: getHeaders,
fetch: options.fetch
});
const createLanguageModel = (modelId) => {
if (new.target) throw new Error("The Groq model function cannot be called with the new keyword.");
return createChatModel(modelId);
};
const createTranscriptionModel = (modelId) => {
return new GroqTranscriptionModel(modelId, {
provider: "groq.transcription",
url: ({ path }) => `${baseURL}${path}`,
headers: getHeaders,
fetch: options.fetch
});
};
const provider = function(modelId) {
return createLanguageModel(modelId);
};
provider.specificationVersion = "v4";
provider.languageModel = createLanguageModel;
provider.chat = createChatModel;
provider.embeddingModel = (modelId) => {
throw new NoSuchModelError({
modelId,
modelType: "embeddingModel"
});
};
provider.textEmbeddingModel = provider.embeddingModel;
provider.imageModel = (modelId) => {
throw new NoSuchModelError({
modelId,
modelType: "imageModel"
});
};
provider.transcription = createTranscriptionModel;
provider.transcriptionModel = createTranscriptionModel;
provider.tools = groqTools;
return provider;
}
createGroq();
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/mistral/3.0.78/d7ae3108bf54dfdc6aa480e7d6a07d571e2ea796dc8797019fd4995564db3920/node_modules/@ai-sdk/mistral/dist/index.mjs
var mistralPromptTokensDetailsSchema = z.object({
messages: z.array(z.json()).nullish(),
cached_tokens: z.number().nullish(),
audio_tokens: z.number().nullish()
}).catchall(z.json());
var mistralCompletionTokensDetailsSchema = z.object({ reasoning_tokens: z.number().nullish() }).catchall(z.json());
var mistralUsageSchema = z.object({
prompt_tokens: z.number(),
completion_tokens: z.number(),
total_tokens: z.number(),
prompt_audio_seconds: z.number().nullish(),
request_count: z.number().nullish(),
service_tier: z.string().nullish(),
num_cached_tokens: z.number().nullish(),
prompt_tokens_details: mistralPromptTokensDetailsSchema.nullish(),
prompt_token_details: mistralPromptTokensDetailsSchema.nullish(),
completion_tokens_details: mistralCompletionTokensDetailsSchema.nullish()
}).catchall(z.json());
function convertMistralUsage(usage) {
var _a, _b, _c, _d, _e;
if (usage == null) return {
inputTokens: {
total: void 0,
noCache: void 0,
cacheRead: void 0,
cacheWrite: void 0
},
outputTokens: {
total: void 0,
text: void 0,
reasoning: void 0
},
raw: void 0
};
const promptTokens = usage.prompt_tokens;
const completionTokens = usage.completion_tokens;
const cacheReadTokens = (_e = (_d = (_b = usage.num_cached_tokens) != null ? _b : (_a = usage.prompt_tokens_details) == null ? void 0 : _a.cached_tokens) != null ? _d : (_c = usage.prompt_token_details) == null ? void 0 : _c.cached_tokens) != null ? _e : 0;
return {
inputTokens: {
total: promptTokens,
noCache: promptTokens - cacheReadTokens,
cacheRead: cacheReadTokens || void 0,
cacheWrite: void 0
},
outputTokens: {
total: completionTokens,
text: completionTokens,
reasoning: void 0
},
raw: usage
};
}
function formatFileUrl({ data, mediaType }) {
return data instanceof URL ? data.toString() : `data:${mediaType};base64,${convertToBase64$1(data)}`;
}
function convertToMistralChatMessages(prompt) {
var _a;
const messages = [];
for (let i = 0; i < prompt.length; i++) {
const { role, content } = prompt[i];
const isLastMessage = i === prompt.length - 1;
switch (role) {
case "system":
messages.push({
role: "system",
content
});
break;
case "user":
messages.push({
role: "user",
content: content.map((part) => {
switch (part.type) {
case "text": return {
type: "text",
text: part.text
};
case "file": if (part.mediaType.startsWith("image/")) {
const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
return {
type: "image_url",
image_url: formatFileUrl({
data: part.data,
mediaType
})
};
} else if (part.mediaType === "application/pdf") return {
type: "document_url",
document_url: formatFileUrl({
data: part.data,
mediaType: "application/pdf"
})
};
else throw new UnsupportedFunctionalityError$2({ functionality: "Only images and PDF file parts are supported" });
}
})
});
break;
case "assistant": {
let text = "";
let hasReasoning = false;
const contentParts = [];
const toolCalls = [];
for (const part of content) switch (part.type) {
case "text":
text += part.text;
contentParts.push({
type: "text",
text: part.text
});
break;
case "tool-call":
toolCalls.push({
id: part.toolCallId,
type: "function",
function: {
name: part.toolName,
arguments: JSON.stringify(part.input)
}
});
break;
case "reasoning":
hasReasoning = true;
contentParts.push({
type: "thinking",
thinking: [{
type: "text",
text: part.text
}],
closed: true
});
break;
default: throw new Error(`Unsupported content type in assistant message: ${part.type}`);
}
messages.push({
role: "assistant",
content: hasReasoning ? contentParts : text,
prefix: isLastMessage ? true : void 0,
tool_calls: toolCalls.length > 0 ? toolCalls : void 0
});
break;
}
case "tool":
for (const toolResponse of content) {
if (toolResponse.type === "tool-approval-response") continue;
const output = toolResponse.output;
let contentValue;
switch (output.type) {
case "text":
case "error-text":
contentValue = output.value;
break;
case "execution-denied":
contentValue = (_a = output.reason) != null ? _a : "Tool call execution denied.";
break;
case "content":
case "json":
case "error-json": contentValue = JSON.stringify(output.value);
}
messages.push({
role: "tool",
name: toolResponse.toolName,
tool_call_id: toolResponse.toolCallId,
content: contentValue
});
}
break;
default: throw new Error(`Unsupported role: ${role}`);
}
}
return messages;
}
function getResponseMetadata$2({ id, model, created }) {
return {
id: id != null ? id : void 0,
modelId: model != null ? model : void 0,
timestamp: created != null ? /* @__PURE__ */ new Date(created * 1e3) : void 0
};
}
function mapMistralFinishReason(finishReason) {
switch (finishReason) {
case "stop": return "stop";
case "length":
case "model_length": return "length";
case "tool_calls": return "tool-calls";
default: return "other";
}
}
var mistralLanguageModelOptions = lazySchema$1(() => zodSchema$2(z.object({
/**
* Whether to inject a safety prompt before all conversations.
*
* Defaults to `false`.
*/
safePrompt: z.boolean().optional(),
documentImageLimit: z.number().optional(),
documentPageLimit: z.number().optional(),
/**
* Whether to use structured outputs.
*
* @default true
*/
structuredOutputs: z.boolean().optional(),
/**
* Whether to use strict JSON schema validation.
*
* @default false
*/
strictJsonSchema: z.boolean().optional(),
/**
* Whether to enable parallel function calling during tool use.
* When set to false, the model will use at most one tool per response.
*
* @default true
*/
parallelToolCalls: z.boolean().optional(),
/**
* Controls the reasoning effort for models that support adjustable reasoning.
*
* - `'high'`: Enable reasoning
* - `'none'`: Disable reasoning
* - `'low'`, `'max'`: Lowest and highest reasoning effort for models that
* support them, e.g. `zai-glm-5-3`, which accepts `'low'`, `'high'`, and
* `'max'` but not `'none'`
*/
reasoningEffort: z.enum([
"high",
"none",
"low",
"max"
]).optional()
})));
var mistralFailedResponseHandler = createJsonErrorResponseHandler$2({
errorSchema: lazySchema$1(() => zodSchema$2(z.object({
object: z.literal("error"),
message: z.string(),
type: z.string(),
param: z.string().nullable(),
code: z.string().nullable()
}))),
errorToMessage: (data) => data.message
});
function prepareTools({ tools, toolChoice }) {
tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
const toolWarnings = [];
if (tools == null) return {
tools: void 0,
toolChoice: void 0,
toolWarnings
};
const mistralTools = [];
for (const tool of tools) if (tool.type === "provider") toolWarnings.push({
type: "unsupported",
feature: `provider-defined tool ${tool.id}`
});
else mistralTools.push({
type: "function",
function: {
name: tool.name,
description: tool.description,
parameters: tool.inputSchema,
...tool.strict != null ? { strict: tool.strict } : {}
}
});
if (toolChoice == null) return {
tools: mistralTools,
toolChoice: void 0,
toolWarnings
};
const type = toolChoice.type;
switch (type) {
case "auto":
case "none": return {
tools: mistralTools,
toolChoice: type,
toolWarnings
};
case "required": return {
tools: mistralTools,
toolChoice: "any",
toolWarnings
};
case "tool": return {
tools: mistralTools.filter((tool) => tool.function.name === toolChoice.toolName),
toolChoice: "any",
toolWarnings
};
default: throw new UnsupportedFunctionalityError$2({ functionality: `tool choice type: ${type}` });
}
}
var MistralChatLanguageModel = class {
constructor(modelId, config) {
this.specificationVersion = "v3";
this.supportedUrls = { "application/pdf": [/^https:\/\/.*$/] };
var _a;
this.modelId = modelId;
this.config = config;
this.generateId = (_a = config.generateId) != null ? _a : generateId$2;
}
get provider() {
return this.config.provider;
}
async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, responseFormat, seed, providerOptions, tools, toolChoice }) {
var _a, _b, _c, _d;
const warnings = [];
const options = (_a = await parseProviderOptions$1({
provider: "mistral",
providerOptions,
schema: mistralLanguageModelOptions
})) != null ? _a : {};
if (topK != null) warnings.push({
type: "unsupported",
feature: "topK"
});
const structuredOutputs = (_b = options.structuredOutputs) != null ? _b : true;
const strictJsonSchema = (_c = options.strictJsonSchema) != null ? _c : false;
if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && !(responseFormat == null ? void 0 : responseFormat.schema)) prompt = injectJsonInstructionIntoMessages$1({
messages: prompt,
schema: responseFormat.schema
});
const baseArgs = {
model: this.modelId,
safe_prompt: options.safePrompt,
max_tokens: maxOutputTokens,
temperature,
top_p: topP,
...frequencyPenalty != null ? { frequency_penalty: frequencyPenalty } : {},
...presencePenalty != null ? { presence_penalty: presencePenalty } : {},
stop: stopSequences,
random_seed: seed,
reasoning_effort: options.reasoningEffort,
response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? structuredOutputs && (responseFormat == null ? void 0 : responseFormat.schema) != null ? {
type: "json_schema",
json_schema: {
schema: responseFormat.schema,
strict: strictJsonSchema,
name: (_d = responseFormat.name) != null ? _d : "response",
description: responseFormat.description
}
} : { type: "json_object" } : void 0,
document_image_limit: options.documentImageLimit,
document_page_limit: options.documentPageLimit,
messages: convertToMistralChatMessages(prompt)
};
const { tools: mistralTools, toolChoice: mistralToolChoice, toolWarnings } = prepareTools({
tools,
toolChoice
});
return {
args: {
...baseArgs,
tools: mistralTools,
tool_choice: mistralToolChoice,
...mistralTools != null && options.parallelToolCalls !== void 0 ? { parallel_tool_calls: options.parallelToolCalls } : {}
},
warnings: [...warnings, ...toolWarnings]
};
}
async doGenerate(options) {
var _a;
const { args: body, warnings } = await this.getArgs(options);
const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi$2({
url: `${this.config.baseURL}/chat/completions`,
headers: combineHeaders$2(this.config.headers(), options.headers),
body,
failedResponseHandler: mistralFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$2(mistralChatResponseSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const choice = response.choices[0];
const content = [];
if (choice.message.content != null && Array.isArray(choice.message.content)) {
for (const part of choice.message.content) if (part.type === "thinking") {
const reasoningText = extractReasoningContent(part.thinking);
if (reasoningText.length > 0) content.push({
type: "reasoning",
text: reasoningText
});
} else if (part.type === "text") {
if (part.text.length > 0) content.push({
type: "text",
text: part.text
});
}
} else {
const text = extractTextContent(choice.message.content);
if (text != null && text.length > 0) content.push({
type: "text",
text
});
}
if (choice.message.tool_calls != null) for (const toolCall of choice.message.tool_calls) content.push({
type: "tool-call",
toolCallId: toolCall.id,
toolName: toolCall.function.name,
input: toolCall.function.arguments
});
return {
content,
finishReason: {
unified: mapMistralFinishReason(choice.finish_reason),
raw: (_a = choice.finish_reason) != null ? _a : void 0
},
usage: convertMistralUsage(response.usage),
request: { body },
response: {
...getResponseMetadata$2(response),
headers: responseHeaders,
body: rawResponse
},
warnings
};
}
async doStream(options) {
const { args, warnings } = await this.getArgs(options);
const body = {
...args,
stream: true
};
const { responseHeaders, value: response } = await postJsonToApi$2({
url: `${this.config.baseURL}/chat/completions`,
headers: combineHeaders$2(this.config.headers(), options.headers),
body,
failedResponseHandler: mistralFailedResponseHandler,
successfulResponseHandler: createEventSourceResponseHandler$2(mistralChatChunkSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
let finishReason = {
unified: "other",
raw: void 0
};
let usage = void 0;
let isFirstChunk = true;
let activeText = false;
let activeReasoningId = null;
const toolCalls = /* @__PURE__ */ new Set();
const toolCallsById = /* @__PURE__ */ new Map();
const toolCallsByIndex = /* @__PURE__ */ new Map();
let latestToolCall;
const generateId2 = this.generateId;
return {
stream: response.pipeThrough(new TransformStream({
start(controller) {
controller.enqueue({
type: "stream-start",
warnings
});
},
transform(chunk, controller) {
var _a;
if (options.includeRawChunks) controller.enqueue({
type: "raw",
rawValue: chunk.rawValue
});
if (!chunk.success) {
controller.enqueue({
type: "error",
error: chunk.error
});
return;
}
const value = chunk.value;
if (isFirstChunk) {
isFirstChunk = false;
controller.enqueue({
type: "response-metadata",
...getResponseMetadata$2(value)
});
}
if (value.usage != null) usage = value.usage;
const choice = value.choices[0];
const delta = choice.delta;
const textContent = extractTextContent(delta.content);
if (delta.content != null && Array.isArray(delta.content)) {
for (const part of delta.content) if (part.type === "thinking") {
const reasoningDelta = extractReasoningContent(part.thinking);
if (reasoningDelta.length > 0) {
if (activeReasoningId == null) {
if (activeText) {
controller.enqueue({
type: "text-end",
id: "0"
});
activeText = false;
}
activeReasoningId = generateId2();
controller.enqueue({
type: "reasoning-start",
id: activeReasoningId
});
}
controller.enqueue({
type: "reasoning-delta",
id: activeReasoningId,
delta: reasoningDelta
});
}
}
}
if (textContent != null && textContent.length > 0) {
if (!activeText) {
if (activeReasoningId != null) {
controller.enqueue({
type: "reasoning-end",
id: activeReasoningId
});
activeReasoningId = null;
}
controller.enqueue({
type: "text-start",
id: "0"
});
activeText = true;
}
controller.enqueue({
type: "text-delta",
id: "0",
delta: textContent
});
}
if ((delta == null ? void 0 : delta.tool_calls) != null) for (const toolCallDelta of delta.tool_calls) {
const { id, index } = toolCallDelta;
let toolCall = id != null && id.length > 0 ? toolCallsById.get(id) : index != null ? toolCallsByIndex.get(index) : latestToolCall;
if (toolCall == null) {
if (id == null) throw new InvalidResponseDataError$2({
data: toolCallDelta,
message: `Expected 'id' to be a string.`
});
if (toolCallDelta.function.name == null) throw new InvalidResponseDataError$2({
data: toolCallDelta,
message: `Expected 'function.name' to be a string.`
});
toolCall = {
id,
name: toolCallDelta.function.name,
input: (_a = toolCallDelta.function.arguments) != null ? _a : ""
};
toolCalls.add(toolCall);
if (id.length > 0) toolCallsById.set(id, toolCall);
controller.enqueue({
type: "tool-input-start",
id,
toolName: toolCall.name
});
if (toolCall.input.length > 0) controller.enqueue({
type: "tool-input-delta",
id,
delta: toolCall.input
});
} else if (toolCallDelta.function.arguments != null) {
toolCall.input += toolCallDelta.function.arguments;
controller.enqueue({
type: "tool-input-delta",
id: toolCall.id,
delta: toolCallDelta.function.arguments
});
}
if (index != null) toolCallsByIndex.set(index, toolCall);
latestToolCall = toolCall;
}
if (choice.finish_reason != null) finishReason = {
unified: mapMistralFinishReason(choice.finish_reason),
raw: choice.finish_reason
};
},
flush(controller) {
if (activeReasoningId != null) controller.enqueue({
type: "reasoning-end",
id: activeReasoningId
});
if (activeText) controller.enqueue({
type: "text-end",
id: "0"
});
for (const toolCall of toolCalls) {
controller.enqueue({
type: "tool-input-end",
id: toolCall.id
});
controller.enqueue({
type: "tool-call",
toolCallId: toolCall.id,
toolName: toolCall.name,
input: toolCall.input
});
}
controller.enqueue({
type: "finish",
finishReason,
usage: convertMistralUsage(usage)
});
}
})),
request: { body },
response: { headers: responseHeaders }
};
}
};
function extractReasoningContent(thinking) {
return thinking.filter((chunk) => chunk.type === "text").map((chunk) => chunk.text).join("");
}
function extractTextContent(content) {
if (typeof content === "string") return content;
if (content == null) return;
const textContent = [];
for (const chunk of content) {
const { type } = chunk;
switch (type) {
case "text":
textContent.push(chunk.text);
break;
case "thinking":
case "image_url":
case "reference": break;
default: throw new Error(`Unsupported type: ${type}`);
}
}
return textContent.length ? textContent.join("") : void 0;
}
var mistralContentSchema = () => z.union([z.string(), z.array(z.discriminatedUnion("type", [
z.object({
type: z.literal("text"),
text: z.string()
}),
z.object({
type: z.literal("image_url"),
image_url: z.union([z.string(), z.object({
url: z.string(),
detail: z.string().nullable()
})])
}),
z.object({
type: z.literal("reference"),
reference_ids: z.array(z.union([z.string(), z.number()]))
}),
z.object({
type: z.literal("thinking"),
thinking: z.array(z.object({
type: z.literal("text"),
text: z.string()
}))
})
]))]).nullish();
var mistralChatResponseSchema = lazySchema$1(() => zodSchema$2(z.object({
id: z.string().nullish(),
created: z.number().nullish(),
model: z.string().nullish(),
choices: z.array(z.object({
message: z.object({
role: z.literal("assistant"),
content: mistralContentSchema(),
tool_calls: z.array(z.object({
id: z.string(),
function: z.object({
name: z.string(),
arguments: z.string()
})
})).nullish()
}),
index: z.number(),
finish_reason: z.string().nullish()
})),
object: z.literal("chat.completion"),
usage: mistralUsageSchema
})));
var mistralChatChunkSchema = lazySchema$1(() => zodSchema$2(z.object({
id: z.string().nullish(),
created: z.number().nullish(),
model: z.string().nullish(),
choices: z.array(z.object({
delta: z.object({
role: z.enum(["assistant"]).optional(),
content: mistralContentSchema(),
tool_calls: z.array(z.object({
index: z.number().nullish(),
id: z.string().nullish(),
function: z.object({
name: z.string().nullish(),
arguments: z.string().nullish()
})
})).nullish()
}),
finish_reason: z.string().nullish(),
index: z.number()
})),
usage: mistralUsageSchema.nullish()
})));
var MistralEmbeddingModel = class {
constructor(modelId, config) {
this.specificationVersion = "v3";
this.maxEmbeddingsPerCall = 32;
this.supportsParallelCalls = false;
this.modelId = modelId;
this.config = config;
}
get provider() {
return this.config.provider;
}
async doEmbed({ values, abortSignal, headers }) {
if (values.length > this.maxEmbeddingsPerCall) throw new TooManyEmbeddingValuesForCallError$1({
provider: this.provider,
modelId: this.modelId,
maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
values
});
const { responseHeaders, value: response, rawValue } = await postJsonToApi$2({
url: `${this.config.baseURL}/embeddings`,
headers: combineHeaders$2(this.config.headers(), headers),
body: {
model: this.modelId,
input: values,
encoding_format: "float"
},
failedResponseHandler: mistralFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$2(MistralTextEmbeddingResponseSchema),
abortSignal,
fetch: this.config.fetch
});
return {
warnings: [],
embeddings: response.data.map((item) => item.embedding),
usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0,
response: {
headers: responseHeaders,
body: rawValue
}
};
}
};
var MistralTextEmbeddingResponseSchema = lazySchema$1(() => zodSchema$2(z.object({
data: z.array(z.object({ embedding: z.array(z.number()) })),
usage: z.object({ prompt_tokens: z.number() }).nullish()
})));
var mistralSpeechModelOptions = lazySchema$1(() => zodSchema$2(z.object({
/**
* Base64-encoded reference audio for one-off voice cloning.
*
* When provided, this takes precedence over the standard `voice` option.
*/
refAudio: z.string().min(1).optional(),
/**
* How expressive the speech is, from 1 to 5. Higher values trade voice
* similarity and stability for stronger delivery. Supported by Voxtral 3.
*/
expressiveness: z.number().min(1).max(5).optional(),
/**
* Pronunciation hints mapping words to lists of IPA phonemes.
* Supported by Voxtral 3.
*/
phonemeHints: z.record(z.string().min(1), z.array(z.string().min(1)).min(1)).optional()
})));
var MistralSpeechModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v3";
}
get provider() {
return this.config.provider;
}
async getArgs({ text, voice, outputFormat = "mp3", instructions, speed, language, providerOptions }) {
const warnings = [];
const mistralOptions = await parseProviderOptions$1({
provider: "mistral",
providerOptions,
schema: mistralSpeechModelOptions
});
let responseFormat = "mp3";
if ([
"pcm",
"wav",
"mp3",
"flac",
"opus"
].includes(outputFormat)) responseFormat = outputFormat;
else warnings.push({
type: "unsupported",
feature: "outputFormat",
details: `Unsupported output format: ${outputFormat}. Using mp3 instead.`
});
if (instructions != null) warnings.push({
type: "unsupported",
feature: "instructions",
details: "Mistral speech models do not support the `instructions` option. Use a reference audio clip to guide delivery."
});
if (speed != null) warnings.push({
type: "unsupported",
feature: "speed",
details: "Mistral speech models do not support the `speed` option. It was ignored."
});
if (language != null) warnings.push({
type: "unsupported",
feature: "language",
details: "Mistral speech models do not support the `language` option. Language is inferred from the input text and voice."
});
const refAudio = mistralOptions == null ? void 0 : mistralOptions.refAudio;
const requestBody = {
model: this.modelId,
input: text,
voice_id: refAudio == null ? voice : void 0,
ref_audio: refAudio,
expressiveness: mistralOptions == null ? void 0 : mistralOptions.expressiveness,
phoneme_hints: mistralOptions == null ? void 0 : mistralOptions.phonemeHints,
response_format: responseFormat,
stream: false
};
return {
requestBody,
requestBodyValues: {
...requestBody,
ref_audio: refAudio == null ? void 0 : "[redacted]"
},
warnings
};
}
async doGenerate(options) {
var _a, _b, _c, _d, _e;
const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
const { requestBody, requestBodyValues, warnings } = await this.getArgs(options);
const { value: response, responseHeaders, rawValue: rawResponse } = await postToApi$2({
url: `${this.config.baseURL}/audio/speech`,
headers: combineHeaders$2({ "Content-Type": "application/json" }, (_e = (_d = this.config).headers) == null ? void 0 : _e.call(_d), options.headers),
body: {
content: JSON.stringify(requestBody),
values: requestBodyValues
},
failedResponseHandler: mistralFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler$2(mistralSpeechResponseSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
return {
audio: response.audio_data,
warnings,
request: { body: JSON.stringify(requestBodyValues) },
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders,
body: rawResponse
}
};
}
};
var mistralSpeechResponseSchema = lazySchema$1(() => zodSchema$2(z.object({ audio_data: z.string() })));
var VERSION$3 = "3.0.78";
function createMistral(options = {}) {
var _a;
const baseURL = (_a = withoutTrailingSlash$2(options.baseURL)) != null ? _a : "https://api.mistral.ai/v1";
const getHeaders = () => withUserAgentSuffix$2({
Authorization: `Bearer ${loadApiKey$2({
apiKey: options.apiKey,
environmentVariableName: "MISTRAL_API_KEY",
description: "Mistral"
})}`,
...options.headers
}, `ai-sdk/mistral/${VERSION$3}`);
const createChatModel = (modelId) => new MistralChatLanguageModel(modelId, {
provider: "mistral.chat",
baseURL,
headers: getHeaders,
fetch: options.fetch,
generateId: options.generateId
});
const createEmbeddingModel = (modelId) => new MistralEmbeddingModel(modelId, {
provider: "mistral.embedding",
baseURL,
headers: getHeaders,
fetch: options.fetch
});
const createSpeechModel = (modelId) => new MistralSpeechModel(modelId, {
provider: "mistral.speech",
baseURL,
headers: getHeaders,
fetch: options.fetch
});
const provider = function(modelId) {
if (new.target) throw new Error("The Mistral model function cannot be called with the new keyword.");
return createChatModel(modelId);
};
provider.specificationVersion = "v3";
provider.languageModel = createChatModel;
provider.chat = createChatModel;
provider.embedding = createEmbeddingModel;
provider.embeddingModel = createEmbeddingModel;
provider.textEmbedding = createEmbeddingModel;
provider.textEmbeddingModel = createEmbeddingModel;
provider.speech = createSpeechModel;
provider.speechModel = createSpeechModel;
provider.imageModel = (modelId) => {
throw new NoSuchModelError$1({
modelId,
modelType: "imageModel"
});
};
return provider;
}
createMistral();
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/perplexity/3.1.9/ca01ae6d57e9912715db1c033b9048f68417201bcc9fd79accbdb49c8695c7fb/node_modules/@ai-sdk/perplexity/dist/index.mjs
var perplexityEmbeddingModelOptions = lazySchema$1(() => zodSchema$2(z.object({
/**
* The number of dimensions the resulting output embeddings should have
* (Matryoshka truncation). Ranges from 128 up to the model's full size
* (1024 for 0.6b models, 2560 for 4b models).
*/
dimensions: z.number().int().positive().optional(),
/**
* The quantized encoding format returned by the API. Perplexity does not
* return floating point embeddings; values are decoded to numbers:
* - `base64_int8` (default): signed int8 values, compare via cosine similarity.
* - `base64_binary`: packed bits per byte (0-255), compare via Hamming distance.
*/
encodingFormat: z.enum(["base64_int8", "base64_binary"]).optional()
})));
function convertPerplexityUsage(usage) {
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
if (usage == null) return {
inputTokens: {
total: void 0,
noCache: void 0,
cacheRead: void 0,
cacheWrite: void 0
},
outputTokens: {
total: void 0,
text: void 0,
reasoning: void 0
},
raw: void 0
};
const inputTokens = (_a = usage.input_tokens) != null ? _a : 0;
const outputTokens = (_b = usage.output_tokens) != null ? _b : 0;
const cacheReadTokens = (_f = (_e = (_c = usage.input_tokens_details) == null ? void 0 : _c.cache_read_input_tokens) != null ? _e : (_d = usage.input_tokens_details) == null ? void 0 : _d.cached_tokens) != null ? _f : 0;
const cacheWriteTokens = (_h = (_g = usage.input_tokens_details) == null ? void 0 : _g.cache_creation_input_tokens) != null ? _h : 0;
const reasoningTokens = (_j = (_i = usage.output_tokens_details) == null ? void 0 : _i.reasoning_tokens) != null ? _j : 0;
return {
inputTokens: {
total: inputTokens,
noCache: Math.max(0, inputTokens - cacheReadTokens - cacheWriteTokens),
cacheRead: cacheReadTokens,
cacheWrite: cacheWriteTokens
},
outputTokens: {
total: outputTokens,
text: Math.max(0, outputTokens - reasoningTokens),
reasoning: reasoningTokens
},
raw: usage
};
}
function serializeToolOutput(output) {
var _a;
switch (output.type) {
case "text":
case "error-text": return output.value;
case "json":
case "error-json": return JSON.stringify(output.value);
case "execution-denied": return (_a = output.reason) != null ? _a : "Tool call execution denied.";
case "content":
if (output.value.some((part) => part.type !== "text")) throw new UnsupportedFunctionalityError$2({ functionality: "file and custom tool result content" });
return output.value.map((part) => part.type === "text" ? part.text : "").join("");
default: throw new Error(`Unsupported tool output: ${output}`);
}
}
function getTopLevelMediaType(mediaType) {
const slashIndex = mediaType.indexOf("/");
return slashIndex === -1 ? mediaType : mediaType.substring(0, slashIndex);
}
function getThoughtSignature(providerOptions) {
var _a;
const thoughtSignature = (_a = providerOptions == null ? void 0 : providerOptions.perplexity) == null ? void 0 : _a.thoughtSignature;
return typeof thoughtSignature === "string" ? thoughtSignature : void 0;
}
function convertToPerplexityInput(prompt) {
var _a;
const input = [];
const warnings = [];
for (const { role, content } of prompt) switch (role) {
case "system":
input.push({
type: "message",
role: "system",
content
});
break;
case "user": {
const convertedContent = content.map((part) => {
switch (part.type) {
case "text": return {
type: "input_text",
text: part.text
};
case "file":
if (getTopLevelMediaType(part.mediaType) !== "image") throw new UnsupportedFunctionalityError$2({ functionality: `file part media type ${part.mediaType}` });
if (part.data instanceof URL) return {
type: "input_image",
image_url: part.data.toString()
};
return {
type: "input_image",
image_url: `data:${part.mediaType === "image/*" ? "image/jpeg" : part.mediaType};base64,${typeof part.data === "string" ? part.data : convertUint8ArrayToBase64$2(part.data)}`
};
}
});
const isTextOnly = convertedContent.every((part) => part.type === "input_text");
input.push({
type: "message",
role: "user",
content: isTextOnly ? convertedContent.map((part) => part.type === "input_text" ? part.text : "").join("") : convertedContent
});
break;
}
case "assistant": {
const text = content.filter((part) => part.type === "text").map((part) => part.text).join("");
if (text.length > 0) input.push({
type: "message",
role: "assistant",
content: text
});
for (const part of content) switch (part.type) {
case "text": break;
case "tool-call":
input.push({
type: "function_call",
call_id: part.toolCallId,
name: part.toolName,
arguments: JSON.stringify((_a = part.input) != null ? _a : {}),
thought_signature: getThoughtSignature(part.providerOptions)
});
break;
case "tool-result":
input.push({
type: "function_call_output",
call_id: part.toolCallId,
name: part.toolName,
output: serializeToolOutput(part.output),
thought_signature: getThoughtSignature(part.providerOptions)
});
break;
case "reasoning":
warnings.push({
type: "unsupported",
feature: "reasoning content in prompt"
});
break;
case "file": throw new UnsupportedFunctionalityError$2({ functionality: `assistant ${part.type} parts` });
default: throw new Error(`Unsupported assistant part: ${part}`);
}
break;
}
case "tool":
for (const part of content) {
if (part.type === "tool-approval-response") throw new UnsupportedFunctionalityError$2({ functionality: "tool approval responses" });
input.push({
type: "function_call_output",
call_id: part.toolCallId,
name: part.toolName,
output: serializeToolOutput(part.output),
thought_signature: getThoughtSignature(part.providerOptions)
});
}
break;
default: throw new Error(`Unsupported role: ${role}`);
}
return {
input,
warnings
};
}
function mapPerplexityFinishReason({ status, incompleteReason, hasFunctionCall }) {
switch (incompleteReason) {
case "max_output_tokens": return "length";
case "content_filter": return "content-filter";
}
switch (status) {
case "completed": return hasFunctionCall ? "tool-calls" : "stop";
case "requires_action": return "tool-calls";
case "failed": return "error";
default: return hasFunctionCall ? "tool-calls" : "other";
}
}
var perplexitySearchResultSchema = () => z.looseObject({
id: z.number().optional(),
title: z.string(),
url: z.string(),
snippet: z.string().optional(),
date: z.string().nullish(),
last_updated: z.string().nullish(),
source: z.string().optional()
});
var perplexityFetchedContentSchema = () => z.looseObject({
title: z.string(),
url: z.string(),
snippet: z.string().optional()
});
var perplexityContentPartSchema = () => z.looseObject({
type: z.string(),
text: z.string().optional(),
annotations: z.array(z.looseObject({
type: z.string().optional(),
url: z.string().optional(),
title: z.string().optional()
})).nullish()
});
var handledOutputTypes = [
"message",
"search_results",
"fetch_url_results",
"function_call"
];
var perplexityOutputItemSchema = () => z.union([
z.looseObject({
type: z.literal("message"),
id: z.string().nullish(),
content: z.array(perplexityContentPartSchema()).nullish()
}),
z.looseObject({
type: z.literal("search_results"),
results: z.array(perplexitySearchResultSchema()).nullish()
}),
z.looseObject({
type: z.literal("fetch_url_results"),
contents: z.array(perplexityFetchedContentSchema()).nullish()
}),
z.looseObject({
type: z.literal("function_call"),
id: z.string().nullish(),
call_id: z.string().nullish(),
name: z.string().nullish(),
arguments: z.string().nullish(),
thought_signature: z.string().nullish()
}),
z.object({ type: z.string().refine((type) => !handledOutputTypes.includes(type)) }).transform(() => ({ type: "unhandled" }))
]);
var perplexityCostSchema = () => z.looseObject({
currency: z.string().optional(),
input_cost: z.number().optional(),
output_cost: z.number().optional(),
total_cost: z.number().optional(),
cache_creation_cost: z.number().nullish(),
cache_read_cost: z.number().nullish(),
tool_calls_cost: z.number().nullish()
});
var perplexityUsageSchema = () => z.looseObject({
input_tokens: z.number(),
output_tokens: z.number(),
total_tokens: z.number(),
input_tokens_details: z.looseObject({
cached_tokens: z.number().optional(),
cache_creation_input_tokens: z.number().optional(),
cache_read_input_tokens: z.number().optional()
}).nullish(),
output_tokens_details: z.looseObject({ reasoning_tokens: z.number().optional() }).nullish(),
tool_calls_details: z.record(z.string(), z.looseObject({ invocation: z.number().optional() })).nullish(),
cost: perplexityCostSchema().nullish()
});
var perplexityAgentResponseSchema = () => z.looseObject({
id: z.string(),
created_at: z.number(),
model: z.string(),
object: z.literal("response"),
output: z.array(perplexityOutputItemSchema()),
status: z.string(),
incomplete_details: z.looseObject({ reason: z.string() }).nullish(),
error: z.looseObject({
code: z.string().optional(),
message: z.string(),
type: z.string().optional()
}).nullish(),
usage: perplexityUsageSchema().nullish()
});
var perplexityAgentResponseSchemaValidator = lazySchema$1(() => zodSchema$2(perplexityAgentResponseSchema()));
var perplexityAgentChunkSchema = lazySchema$1(() => zodSchema$2(z.looseObject({
type: z.string(),
sequence_number: z.number().nullish(),
response: perplexityAgentResponseSchema().nullish(),
item: perplexityOutputItemSchema().nullish(),
output_index: z.number().nullish(),
item_id: z.string().nullish(),
content_index: z.number().nullish(),
delta: z.string().nullish(),
text: z.string().nullish(),
thought: z.string().nullish(),
queries: z.array(z.string()).nullish(),
urls: z.array(z.string()).nullish(),
results: z.array(perplexitySearchResultSchema()).nullish(),
contents: z.array(perplexityFetchedContentSchema()).nullish(),
error: z.looseObject({
code: z.string().nullish(),
message: z.string(),
type: z.string().nullish()
}).nullish()
})));
var perplexityErrorSchema = lazySchema$1(() => zodSchema$2(z.looseObject({
error: z.union([z.string(), z.looseObject({
code: z.union([z.string(), z.number()]).optional(),
message: z.string().nullish(),
type: z.string().nullish()
})]).optional(),
detail: z.union([z.string(), z.array(z.looseObject({ msg: z.string() }))]).optional(),
message: z.string().optional()
})));
function perplexityErrorToMessage(data) {
var _a, _b, _c;
if (typeof data.error === "string") return data.error;
if (data.error != null) return (_b = (_a = data.error.message) != null ? _a : data.error.type) != null ? _b : "unknown error";
if (typeof data.detail === "string") return data.detail;
if (Array.isArray(data.detail)) return data.detail.map((detail) => detail.msg).join(", ");
return (_c = data.message) != null ? _c : "unknown error";
}
var userLocationSchema = () => z.looseObject({
latitude: z.number().optional(),
longitude: z.number().optional(),
country: z.string().optional(),
city: z.string().optional(),
region: z.string().optional()
});
var webSearchFiltersSchema = () => z.looseObject({
search_domain_filter: z.array(z.string()).optional(),
search_recency_filter: z.enum([
"hour",
"day",
"week",
"month",
"year"
]).optional(),
search_after_date_filter: z.string().optional(),
search_before_date_filter: z.string().optional(),
last_updated_after_filter: z.string().optional(),
last_updated_before_filter: z.string().optional()
});
var webSearchToolSchema = () => z.looseObject({
type: z.literal("web_search"),
filters: webSearchFiltersSchema().optional(),
max_results: z.number().int().positive().optional(),
max_tokens: z.number().optional(),
max_tokens_per_page: z.number().optional(),
search_context_size: z.enum([
"low",
"medium",
"high"
]).optional(),
user_location: userLocationSchema().optional()
});
var nativeToolSchema = () => z.union([
webSearchToolSchema(),
z.looseObject({
type: z.literal("fetch_url"),
max_urls: z.number().optional()
}),
z.looseObject({ type: z.literal("people_search") }),
z.looseObject({ type: z.literal("finance_search") }),
z.looseObject({ type: z.literal("sandbox") }),
z.looseObject({
type: z.literal("mcp"),
server_label: z.string(),
server_url: z.string(),
allowed_tools: z.array(z.string()).optional(),
authorization: z.string().optional(),
defer_loading: z.boolean().optional(),
headers: z.record(z.string(), z.string()).optional()
}),
z.looseObject({
type: z.literal("connector"),
id: z.string(),
server_label: z.string(),
server_description: z.string().optional(),
allowed_tools: z.array(z.string()).optional()
})
]);
var perplexityLanguageModelOptions = lazySchema$1(() => zodSchema$2(z.looseObject({
/** Top-level Agent API instructions. */
instructions: z.string().optional(),
/**
* Native Agent API tools. AI SDK function tools can also be supplied through
* the top-level `tools` option on `generateText` and `streamText`.
*/
tools: z.array(nativeToolSchema()).optional(),
/** A fallback model list for Agent API routing. */
models: z.array(z.string()).optional(),
/** Maximum number of agentic steps. */
max_steps: z.number().int().positive().optional(),
/** Maximum number of native tool calls. */
max_tool_calls: z.number().int().nonnegative().optional(),
/** Continue a conversation from an earlier Agent API response. */
previous_response_id: z.string().optional(),
/**
* Whether the response can be retrieved later. Setting this to false does
* not disable persistence or prevent previous_response_id continuations.
*/
store: z.boolean().optional(),
/** Preferred response language as an ISO 639-1 language code. */
language_preference: z.string().optional(),
/** Agent API reasoning configuration. */
reasoning: z.looseObject({ effort: z.enum([
"minimal",
"low",
"medium",
"high",
"xhigh"
]).optional() }).optional(),
/** Agent API skill configuration. */
skills: z.array(z.union([z.looseObject({
type: z.literal("builtin"),
name: z.enum([
"office",
"office/docx",
"office/pdf",
"office/pptx",
"office/xlsx"
])
}), z.looseObject({
type: z.literal("inline"),
name: z.string(),
description: z.string(),
instructions: z.string()
})])).optional()
})));
function preparePerplexityTools({ tools, toolChoice }) {
const preparedTools = [];
const warnings = [];
for (const tool of tools != null ? tools : []) {
if (tool.type === "provider") {
warnings.push({
type: "unsupported",
feature: `provider-defined tool ${tool.name}`
});
continue;
}
preparedTools.push({
type: "function",
name: tool.name,
description: tool.description,
parameters: tool.inputSchema,
strict: tool.strict
});
}
if (toolChoice != null && toolChoice.type !== "auto") warnings.push({
type: "unsupported",
feature: "toolChoice",
details: "The Perplexity Agent API currently selects tools automatically."
});
return {
tools: preparedTools,
warnings
};
}
var presetIds = /* @__PURE__ */ new Set([
"fast",
"low",
"medium",
"high",
"xhigh"
]);
function getModelSelection(modelId) {
if (presetIds.has(modelId)) return { preset: modelId };
return { model: modelId };
}
function getResponseMetadata$1(response) {
var _a, _b;
return {
id: (_a = response.id) != null ? _a : void 0,
modelId: (_b = response.model) != null ? _b : void 0,
timestamp: response.created_at != null ? /* @__PURE__ */ new Date(response.created_at * 1e3) : void 0
};
}
function getProviderMetadata(usage) {
var _a, _b, _c, _d, _e, _f, _g;
const cost = usage == null ? void 0 : usage.cost;
return { perplexity: {
usage: {
citationTokens: null,
numSearchQueries: (usage == null ? void 0 : usage.tool_calls_details) ? Object.entries(usage.tool_calls_details).filter(([name]) => name.includes("search")).reduce((total, [, details]) => {
var _a2;
return total + ((_a2 = details.invocation) != null ? _a2 : 0);
}, 0) : null
},
images: null,
cost: cost == null ? null : {
inputTokensCost: (_a = cost.input_cost) != null ? _a : null,
outputTokensCost: (_b = cost.output_cost) != null ? _b : null,
requestCost: null,
totalCost: (_c = cost.total_cost) != null ? _c : null,
currency: (_d = cost.currency) != null ? _d : null,
cacheCreationCost: (_e = cost.cache_creation_cost) != null ? _e : null,
cacheReadCost: (_f = cost.cache_read_cost) != null ? _f : null,
toolCallsCost: (_g = cost.tool_calls_cost) != null ? _g : null
},
toolCalls: (usage == null ? void 0 : usage.tool_calls_details) == null ? null : Object.fromEntries(Object.entries(usage.tool_calls_details).map(([name, details]) => {
var _a2;
return [name, { invocation: (_a2 = details.invocation) != null ? _a2 : null }];
}))
} };
}
function createSource(result, generateId2) {
var _a, _b, _c, _d, _e;
return {
type: "source",
sourceType: "url",
id: result.id == null ? generateId2() : String(result.id),
url: result.url,
title: result.title,
providerMetadata: { perplexity: {
resultId: (_a = result.id) != null ? _a : null,
snippet: (_b = result.snippet) != null ? _b : null,
date: (_c = result.date) != null ? _c : null,
lastUpdated: (_d = result.last_updated) != null ? _d : null,
source: (_e = result.source) != null ? _e : null
} }
};
}
function hasSearchResultId(source) {
var _a, _b;
return typeof ((_b = (_a = source.providerMetadata) == null ? void 0 : _a.perplexity) == null ? void 0 : _b.resultId) === "number";
}
function getSearchResults(item) {
var _a;
return item.type === "search_results" ? (_a = item.results) != null ? _a : [] : [];
}
function getFetchedSources(item) {
var _a;
return item.type === "fetch_url_results" ? (_a = item.contents) != null ? _a : [] : [];
}
var PerplexityLanguageModel = class {
constructor(modelId, config) {
this.specificationVersion = "v3";
this.provider = "perplexity";
this.supportedUrls = { "image/*": [/^https?:\/\/.*$/] };
this.modelId = modelId;
this.config = config;
}
async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, responseFormat, seed, providerOptions, tools, toolChoice }) {
var _a, _b;
const warnings = [];
const perplexityOptions = (_a = await parseProviderOptions$1({
provider: "perplexity",
providerOptions,
schema: perplexityLanguageModelOptions
})) != null ? _a : {};
if (topK != null) warnings.push({
type: "unsupported",
feature: "topK"
});
if (frequencyPenalty != null) warnings.push({
type: "unsupported",
feature: "frequencyPenalty"
});
if (presencePenalty != null) warnings.push({
type: "unsupported",
feature: "presencePenalty"
});
if (stopSequences != null) warnings.push({
type: "unsupported",
feature: "stopSequences"
});
if (seed != null) warnings.push({
type: "unsupported",
feature: "seed"
});
const { tools: nativeTools, ...agentOptions } = perplexityOptions;
const modelSelection = getModelSelection(this.modelId);
const { input, warnings: inputWarnings } = convertToPerplexityInput(prompt);
warnings.push(...inputWarnings);
const { tools: functionTools, warnings: toolWarnings } = preparePerplexityTools({
tools,
toolChoice
});
warnings.push(...toolWarnings);
const agentTools = [...nativeTools != null ? nativeTools : [], ...functionTools];
const body = {
...agentOptions,
...modelSelection,
input,
max_output_tokens: maxOutputTokens,
temperature,
top_p: topP,
response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null ? {
type: "json_schema",
json_schema: {
name: (_b = responseFormat.name) != null ? _b : "response",
description: responseFormat.description,
schema: responseFormat.schema,
strict: true
}
} : void 0,
tools: agentTools.length > 0 ? agentTools : void 0
};
if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema == null) warnings.push({
type: "unsupported",
feature: "JSON response format without a schema"
});
return {
args: body,
warnings
};
}
async doGenerate(options) {
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
const { args: body, warnings } = await this.getArgs(options);
const url = `${this.config.baseURL}/v1/agent`;
const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi$2({
url,
headers: combineHeaders$2((_b = (_a = this.config).headers) == null ? void 0 : _b.call(_a), options.headers),
body,
failedResponseHandler: createJsonErrorResponseHandler$2({
errorSchema: perplexityErrorSchema,
errorToMessage: perplexityErrorToMessage
}),
successfulResponseHandler: createJsonResponseHandler$2(perplexityAgentResponseSchemaValidator),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
if (response.error != null || response.status === "failed") throw new APICallError$2({
message: (_d = (_c = response.error) == null ? void 0 : _c.message) != null ? _d : "Perplexity response failed",
url,
requestBodyValues: body,
statusCode: 400,
responseHeaders,
responseBody: rawResponse,
isRetryable: false
});
const content = [];
const sourceIndexesByUrl = /* @__PURE__ */ new Map();
let hasFunctionCall = false;
const addSource = (source) => {
const existingIndex = sourceIndexesByUrl.get(source.url);
if (existingIndex == null) {
sourceIndexesByUrl.set(source.url, content.length);
content.push(source);
} else if (hasSearchResultId(source) && !hasSearchResultId(content[existingIndex])) content[existingIndex] = source;
};
for (const item of response.output) if (item.type === "message") for (const part of (_e = item.content) != null ? _e : []) {
if (part.type === "output_text" && part.text != null) content.push({
type: "text",
text: part.text
});
for (const annotation of (_f = part.annotations) != null ? _f : []) if (annotation.url != null) addSource({
type: "source",
sourceType: "url",
id: this.config.generateId(),
url: annotation.url,
title: annotation.title
});
}
else if (item.type === "search_results") for (const result of getSearchResults(item)) addSource(createSource(result, this.config.generateId));
else if (item.type === "fetch_url_results") for (const result of getFetchedSources(item)) addSource({
type: "source",
sourceType: "url",
id: this.config.generateId(),
url: result.url,
title: result.title,
providerMetadata: { perplexity: { snippet: (_g = result.snippet) != null ? _g : null } }
});
else if (item.type === "function_call" && item.call_id != null && item.name != null && item.arguments != null) {
hasFunctionCall = true;
content.push({
type: "tool-call",
toolCallId: item.call_id,
toolName: item.name,
input: item.arguments,
providerMetadata: { perplexity: {
itemId: (_h = item.id) != null ? _h : null,
...item.thought_signature != null && { thoughtSignature: item.thought_signature }
} }
});
}
const finishReason = (_j = (_i = response.incomplete_details) == null ? void 0 : _i.reason) != null ? _j : response.status;
return {
content,
finishReason: {
unified: mapPerplexityFinishReason({
status: response.status,
incompleteReason: (_k = response.incomplete_details) == null ? void 0 : _k.reason,
hasFunctionCall
}),
raw: finishReason
},
usage: convertPerplexityUsage(response.usage),
request: { body },
response: {
...getResponseMetadata$1(response),
headers: responseHeaders,
body: rawResponse
},
warnings,
providerMetadata: getProviderMetadata(response.usage)
};
}
async doStream(options) {
var _a, _b;
const { args, warnings } = await this.getArgs(options);
const body = {
...args,
stream: true
};
const { responseHeaders, value: response } = await postJsonToApi$2({
url: `${this.config.baseURL}/v1/agent`,
headers: combineHeaders$2((_b = (_a = this.config).headers) == null ? void 0 : _b.call(_a), options.headers),
body,
failedResponseHandler: createJsonErrorResponseHandler$2({
errorSchema: perplexityErrorSchema,
errorToMessage: perplexityErrorToMessage
}),
successfulResponseHandler: createEventSourceResponseHandler$2(perplexityAgentChunkSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
let finishReason = {
unified: "other",
raw: void 0
};
let usage;
let hasFunctionCall = false;
let hasResponseMetadata = false;
let activeReasoningId;
const textStates = /* @__PURE__ */ new Map();
const emittedSourceUrls = /* @__PURE__ */ new Set();
const pendingSourcesByUrl = /* @__PURE__ */ new Map();
const seenFunctionCalls = /* @__PURE__ */ new Set();
const generateId2 = this.config.generateId;
return {
stream: response.pipeThrough(new TransformStream({
start(controller) {
controller.enqueue({
type: "stream-start",
warnings
});
},
transform(chunk, controller) {
var _a2, _b2, _c, _d, _e, _f, _g, _h, _i;
if (options.includeRawChunks) controller.enqueue({
type: "raw",
rawValue: chunk.rawValue
});
if (!chunk.success) {
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error: chunk.error
});
return;
}
const value = chunk.value;
const getTextId = (itemId, outputIndex, contentIndex = 0) => {
const id = itemId != null ? itemId : String(outputIndex != null ? outputIndex : "text");
return contentIndex == null || contentIndex === 0 ? id : `${id}:${contentIndex}`;
};
const emitTextDelta = (id, delta) => {
let state = textStates.get(id);
if (state == null ? void 0 : state.ended) return;
if (state == null) {
state = {
text: "",
ended: false
};
textStates.set(id, state);
controller.enqueue({
type: "text-start",
id
});
}
state.text += delta;
controller.enqueue({
type: "text-delta",
id,
delta
});
};
const finishText = (id, text) => {
var _a3;
const state = textStates.get(id);
if (state == null ? void 0 : state.ended) return;
const emittedText = (_a3 = state == null ? void 0 : state.text) != null ? _a3 : "";
if (text != null && text.startsWith(emittedText) && text.length > emittedText.length) emitTextDelta(id, text.slice(emittedText.length));
const finalState = textStates.get(id);
if (finalState != null) {
finalState.ended = true;
controller.enqueue({
type: "text-end",
id
});
}
};
const finishOutputText = (item, outputIndex) => {
var _a3;
if (item.type === "message") {
for (const [contentIndex, part] of ((_a3 = item.content) != null ? _a3 : []).entries()) if (part.type === "output_text") finishText(getTextId(item.id, outputIndex, contentIndex), part.text);
}
};
const emitSource = (source) => {
if (emittedSourceUrls.has(source.url)) return;
if (hasSearchResultId(source)) {
pendingSourcesByUrl.delete(source.url);
emittedSourceUrls.add(source.url);
controller.enqueue(source);
} else if (!pendingSourcesByUrl.has(source.url)) pendingSourcesByUrl.set(source.url, source);
};
const emitReasoningThought = (thought) => {
if (activeReasoningId != null && thought != null) controller.enqueue({
type: "reasoning-delta",
id: activeReasoningId,
delta: thought
});
};
const emitFunctionCall = (item) => {
var _a3;
if (item.type !== "function_call" || item.call_id == null || item.name == null || item.arguments == null || seenFunctionCalls.has(item.call_id)) return;
seenFunctionCalls.add(item.call_id);
hasFunctionCall = true;
controller.enqueue({
type: "tool-input-start",
id: item.call_id,
toolName: item.name
});
controller.enqueue({
type: "tool-input-delta",
id: item.call_id,
delta: item.arguments
});
controller.enqueue({
type: "tool-input-end",
id: item.call_id
});
controller.enqueue({
type: "tool-call",
toolCallId: item.call_id,
toolName: item.name,
input: item.arguments,
providerMetadata: { perplexity: {
itemId: (_a3 = item.id) != null ? _a3 : null,
...item.thought_signature != null && { thoughtSignature: item.thought_signature }
} }
});
};
const emitOutputSources = (item) => {
var _a3, _b3, _c2;
if (item.type === "message") {
for (const part of (_a3 = item.content) != null ? _a3 : []) for (const annotation of (_b3 = part.annotations) != null ? _b3 : []) if (annotation.url != null) emitSource({
type: "source",
sourceType: "url",
id: generateId2(),
url: annotation.url,
title: annotation.title
});
}
for (const result of getSearchResults(item)) emitSource(createSource(result, generateId2));
for (const result of getFetchedSources(item)) emitSource({
type: "source",
sourceType: "url",
id: generateId2(),
url: result.url,
title: result.title,
providerMetadata: { perplexity: { snippet: (_c2 = result.snippet) != null ? _c2 : null } }
});
};
switch (value.type) {
case "response.created":
case "response.in_progress":
if (!hasResponseMetadata && value.response != null) {
controller.enqueue({
type: "response-metadata",
...getResponseMetadata$1(value.response)
});
hasResponseMetadata = true;
}
break;
case "response.output_text.delta":
if (value.delta != null) emitTextDelta(getTextId(value.item_id, value.output_index, value.content_index), value.delta);
break;
case "response.output_text.done":
finishText(getTextId(value.item_id, value.output_index, value.content_index), value.text);
break;
case "response.reasoning.started":
if (activeReasoningId != null) controller.enqueue({
type: "reasoning-end",
id: activeReasoningId
});
activeReasoningId = `reasoning-${(_a2 = value.sequence_number) != null ? _a2 : generateId2()}`;
controller.enqueue({
type: "reasoning-start",
id: activeReasoningId
});
emitReasoningThought(value.thought);
break;
case "response.reasoning.search_queries":
case "response.reasoning.fetch_url_queries":
emitReasoningThought(value.thought);
break;
case "response.reasoning.search_results":
emitReasoningThought(value.thought);
for (const result of (_b2 = value.results) != null ? _b2 : []) emitSource(createSource(result, generateId2));
break;
case "response.reasoning.fetch_url_results":
emitReasoningThought(value.thought);
for (const result of (_c = value.contents) != null ? _c : []) emitSource({
type: "source",
sourceType: "url",
id: generateId2(),
url: result.url,
title: result.title,
providerMetadata: { perplexity: { snippet: (_d = result.snippet) != null ? _d : null } }
});
break;
case "response.reasoning.stopped":
emitReasoningThought(value.thought);
if (activeReasoningId != null) {
controller.enqueue({
type: "reasoning-end",
id: activeReasoningId
});
activeReasoningId = void 0;
}
break;
case "response.output_item.done":
if (value.item != null) {
finishOutputText(value.item, value.output_index);
emitOutputSources(value.item);
emitFunctionCall(value.item);
}
break;
case "response.completed":
case "response.incomplete":
if (value.response != null) {
if (!hasResponseMetadata) {
controller.enqueue({
type: "response-metadata",
...getResponseMetadata$1(value.response)
});
hasResponseMetadata = true;
}
for (const [outputIndex, item] of value.response.output.entries()) {
finishOutputText(item, outputIndex);
emitOutputSources(item);
emitFunctionCall(item);
}
usage = (_e = value.response.usage) != null ? _e : void 0;
const rawFinishReason = (_g = (_f = value.response.incomplete_details) == null ? void 0 : _f.reason) != null ? _g : value.response.status;
finishReason = {
unified: mapPerplexityFinishReason({
status: value.response.status,
incompleteReason: (_h = value.response.incomplete_details) == null ? void 0 : _h.reason,
hasFunctionCall
}),
raw: rawFinishReason
};
}
break;
case "response.failed":
finishReason = {
unified: "error",
raw: "failed"
};
controller.enqueue({
type: "error",
error: (_i = value.error) != null ? _i : /* @__PURE__ */ new Error("Perplexity response failed")
});
}
},
flush(controller) {
for (const source of pendingSourcesByUrl.values()) controller.enqueue(source);
if (activeReasoningId != null) controller.enqueue({
type: "reasoning-end",
id: activeReasoningId
});
for (const [id, state] of textStates) if (!state.ended) controller.enqueue({
type: "text-end",
id
});
controller.enqueue({
type: "finish",
finishReason,
usage: convertPerplexityUsage(usage),
providerMetadata: getProviderMetadata(usage)
});
}
})),
request: { body },
response: { headers: responseHeaders }
};
}
};
var PerplexityEmbeddingModel = class {
constructor(modelId, config) {
this.specificationVersion = "v3";
this.maxEmbeddingsPerCall = 512;
this.supportsParallelCalls = true;
this.modelId = modelId;
this.config = config;
}
get provider() {
return this.config.provider;
}
async doEmbed({ values, abortSignal, headers, providerOptions }) {
var _a, _b, _c, _d, _e, _f;
if (values.length > this.maxEmbeddingsPerCall) throw new TooManyEmbeddingValuesForCallError$1({
provider: this.provider,
modelId: this.modelId,
maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
values
});
const perplexityOptions = (_a = await parseProviderOptions$1({
provider: "perplexity",
providerOptions,
schema: perplexityEmbeddingModelOptions
})) != null ? _a : {};
const encodingFormat = (_b = perplexityOptions.encodingFormat) != null ? _b : "base64_int8";
const { responseHeaders, value: response, rawValue } = await postJsonToApi$2({
url: `${this.config.baseURL}/v1/embeddings`,
headers: combineHeaders$2(this.config.headers(), headers),
body: {
model: this.modelId,
input: values,
dimensions: perplexityOptions.dimensions,
encoding_format: encodingFormat
},
failedResponseHandler: createJsonErrorResponseHandler$2({
errorSchema: perplexityErrorSchema,
errorToMessage: perplexityErrorToMessage
}),
successfulResponseHandler: createJsonResponseHandler$2(perplexityEmbeddingResponseSchema),
abortSignal,
fetch: this.config.fetch
});
const cost = (_c = response.usage) == null ? void 0 : _c.cost;
return {
embeddings: response.data.map((item) => decodeEmbedding(item.embedding, encodingFormat)),
usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0,
providerMetadata: cost ? { perplexity: { cost: {
inputCost: (_d = cost.input_cost) != null ? _d : null,
totalCost: (_e = cost.total_cost) != null ? _e : null,
currency: (_f = cost.currency) != null ? _f : null
} } } : void 0,
response: {
headers: responseHeaders,
body: rawValue
},
warnings: []
};
}
};
function decodeEmbedding(base64, encodingFormat) {
const bytes = convertBase64ToUint8Array$1(base64);
if (encodingFormat === "base64_int8") {
const int8 = new Int8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
return Array.from(int8);
}
return Array.from(bytes);
}
var perplexityEmbeddingResponseSchema = lazySchema$1(() => zodSchema$2(z.object({
data: z.array(z.object({ embedding: z.string() })),
usage: z.object({
prompt_tokens: z.number(),
cost: z.object({
input_cost: z.number().nullish(),
total_cost: z.number().nullish(),
currency: z.string().nullish()
}).nullish()
}).nullish()
})));
var VERSION$2 = "3.1.9";
function createPerplexity(options = {}) {
var _a;
const getHeaders = () => withUserAgentSuffix$2({
Authorization: `Bearer ${loadApiKey$2({
apiKey: options.apiKey,
environmentVariableName: "PERPLEXITY_API_KEY",
description: "Perplexity"
})}`,
"X-Pplx-Integration": "vercel-ai-sdk",
...options.headers
}, `ai-sdk/perplexity/${VERSION$2}`);
const baseURL = withoutTrailingSlash$2((_a = options.baseURL) != null ? _a : "https://api.perplexity.ai");
const createLanguageModel = (modelId) => {
return new PerplexityLanguageModel(modelId, {
baseURL,
headers: getHeaders,
generateId: generateId$2,
fetch: options.fetch
});
};
const createEmbeddingModel = (modelId) => new PerplexityEmbeddingModel(modelId, {
provider: "perplexity.embedding",
baseURL,
headers: getHeaders,
fetch: options.fetch
});
const provider = (modelId) => createLanguageModel(modelId);
provider.specificationVersion = "v3";
provider.languageModel = createLanguageModel;
provider.embedding = createEmbeddingModel;
provider.embeddingModel = createEmbeddingModel;
provider.textEmbeddingModel = createEmbeddingModel;
provider.imageModel = (modelId) => {
throw new NoSuchModelError$1({
modelId,
modelType: "imageModel"
});
};
return provider;
}
createPerplexity();
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/togetherai/3.0.83/20f70545dd8da1582f656285682dc37ed9494613695ca09b41ed52e853e809c0/node_modules/@ai-sdk/togetherai/dist/index.js
const togetheraiErrorSchema$1 = lazySchema(() => zodSchema(z.object({ error: z.object({ message: z.string() }) })));
const togetheraiRerankingResponseSchema = lazySchema(() => zodSchema(z.object({
id: z.string().nullish(),
model: z.string().nullish(),
results: z.array(z.object({
index: z.number(),
relevance_score: z.number()
})),
usage: z.object({
prompt_tokens: z.number(),
completion_tokens: z.number(),
total_tokens: z.number()
})
})));
const togetheraiRerankingModelOptionsSchema = lazySchema(() => zodSchema(z.object({ rankFields: z.array(z.string()).optional() })));
var TogetherAIRerankingModel = class {
constructor(modelId, config) {
this.specificationVersion = "v4";
this.modelId = modelId;
this.config = config;
}
get provider() {
return this.config.provider;
}
async doRerank({ documents, headers, query, topN, abortSignal, providerOptions }) {
const rerankingOptions = await parseProviderOptions({
provider: "togetherai",
providerOptions,
schema: togetheraiRerankingModelOptionsSchema
});
const { responseHeaders, value: response, rawValue } = await postJsonToApi({
url: `${this.config.baseURL}/rerank`,
headers: combineHeaders(await resolve(this.config.headers), headers),
body: {
model: this.modelId,
documents: documents.values,
query,
top_n: topN,
rank_fields: rerankingOptions?.rankFields,
return_documents: false
},
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: togetheraiErrorSchema$1,
errorToMessage: (data) => data.error.message
}),
successfulResponseHandler: createJsonResponseHandler(togetheraiRerankingResponseSchema),
abortSignal,
fetch: this.config.fetch
});
return {
ranking: response.results.map((result) => ({
index: result.index,
relevanceScore: result.relevance_score
})),
response: {
id: response.id ?? void 0,
modelId: response.model ?? void 0,
headers: responseHeaders,
body: rawValue
}
};
}
};
/**
* Provider options schema for Together AI image generation.
*/
const togetheraiImageModelOptionsSchema = lazySchema(() => zodSchema(z.looseObject({
/**
* Number of generation steps. Higher values can improve quality.
*/
steps: z.number().nullish(),
/**
* Guidance scale for image generation.
*/
guidance: z.number().nullish(),
/**
* Negative prompt to guide what to avoid.
*/
negative_prompt: z.string().nullish(),
/**
* Disable the safety checker for image generation.
* When true, the API will not reject images flagged as potentially NSFW.
* Not available for Flux Schnell Free and Flux Pro models.
*/
disable_safety_checker: z.boolean().nullish()
})));
const nonDiffusionImageModels = /* @__PURE__ */ new Set(["google/gemini-3-pro-image"]);
var TogetherAIImageModel = class TogetherAIImageModel {
get supportsFileInputs() {
if ([
"black-forest-labs/FLUX.1-kontext-pro",
"black-forest-labs/FLUX.1-kontext-max",
"black-forest-labs/FLUX.1-kontext-dev",
"black-forest-labs/FLUX.1-canny",
"black-forest-labs/FLUX.1-depth",
"black-forest-labs/FLUX.1-redux",
"black-forest-labs/FLUX.2-pro",
"black-forest-labs/FLUX.2-flex"
].includes(this.modelId)) return true;
return [
"stabilityai/stable-diffusion-xl-base-1.0",
"black-forest-labs/FLUX.1-dev",
"black-forest-labs/FLUX.1-dev-lora",
"black-forest-labs/FLUX.1-schnell",
"black-forest-labs/FLUX.1.1-pro",
"black-forest-labs/FLUX.1-pro",
"black-forest-labs/FLUX.1-schnell-Free",
"black-forest-labs/FLUX.2-dev",
"google/gemini-3-pro-image"
].includes(this.modelId) ? false : void 0;
}
get supportsMaskInputs() {
return this.supportsFileInputs == null ? void 0 : false;
}
get provider() {
return this.config.provider;
}
static [WORKFLOW_SERIALIZE](model) {
return serializeModelOptions({
modelId: model.modelId,
config: model.config
});
}
static [WORKFLOW_DESERIALIZE](options) {
return new TogetherAIImageModel(options.modelId, options.config);
}
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
this.maxImagesPerCall = 1;
}
async doGenerate({ prompt, n, size, seed, providerOptions, headers, abortSignal, files, mask }) {
const warnings = [];
if (mask != null) throw new Error("Together AI does not support mask-based image editing. Use FLUX Kontext models (e.g., black-forest-labs/FLUX.1-kontext-pro) with a reference image and descriptive prompt instead.");
if (size != null) warnings.push({
type: "unsupported",
feature: "aspectRatio",
details: "This model does not support the `aspectRatio` option. Use `size` instead."
});
const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
const togetheraiOptions = await parseProviderOptions({
provider: "togetherai",
providerOptions,
schema: togetheraiImageModelOptionsSchema
});
const isNonDiffusionModel = nonDiffusionImageModels.has(this.modelId);
const modelOptions = { ...togetheraiOptions };
if (isNonDiffusionModel) {
delete modelOptions.steps;
delete modelOptions.guidance;
delete modelOptions.negative_prompt;
delete modelOptions.disable_safety_checker;
if (seed != null) warnings.push({
type: "unsupported",
feature: "seed",
details: `The ${this.modelId} model does not support the \`seed\` option.`
});
}
let imageUrl;
if (files != null && files.length > 0) {
imageUrl = convertImageModelFileToDataUri(files[0]);
if (files.length > 1) warnings.push({
type: "other",
message: "Together AI only supports a single input image. Additional images are ignored."
});
}
const splitSize = size?.split("x");
const { value: response, responseHeaders } = await postJsonToApi({
url: `${this.config.baseURL}/images/generations`,
headers: combineHeaders(await resolve(this.config.headers), headers),
body: {
model: this.modelId,
prompt,
...seed != null && !isNonDiffusionModel ? { seed } : {},
...n > 1 ? { n } : {},
...splitSize && {
width: parseInt(splitSize[0]),
height: parseInt(splitSize[1])
},
...imageUrl != null ? { image_url: imageUrl } : {},
response_format: "base64",
...modelOptions
},
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: togetheraiErrorSchema,
errorToMessage: (data) => data.error.message
}),
successfulResponseHandler: createJsonResponseHandler(togetheraiImageResponseSchema),
abortSignal,
fetch: this.config.fetch
});
return {
images: response.data.map((item) => item.b64_json),
warnings,
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders
}
};
}
};
const togetheraiImageResponseSchema = z.object({ data: z.array(z.object({ b64_json: z.string() })) });
const togetheraiErrorSchema = z.object({ error: z.object({ message: z.string() }) });
const VERSION$1 = "3.0.83";
function loadDeprecatedApiKey() {
if (typeof process === "undefined") return;
if (typeof process.env.TOGETHER_API_KEY === "string") return;
const key = process.env.TOGETHER_AI_API_KEY;
if (typeof key === "string") console.warn("TOGETHER_AI_API_KEY is deprecated and will be removed in a future release. Please use TOGETHER_API_KEY instead.");
return key;
}
function getModelStructuredOutputSupport(modelId) {
return modelId === "deepseek-ai/DeepSeek-V4-Flash-0731";
}
function createTogetherAI(options = {}) {
const baseURL = withoutTrailingSlash(options.baseURL ?? "https://api.together.xyz/v1/");
const getHeaders = () => resolveWith(options.apiKey, (apiKey) => withUserAgentSuffix({
Authorization: `Bearer ${loadApiKey({
apiKey: apiKey ?? loadDeprecatedApiKey(),
environmentVariableName: "TOGETHER_API_KEY",
description: "TogetherAI"
})}`,
...options.headers
}, `ai-sdk-togetherai/${VERSION$1}`));
const getCommonModelConfig = (modelType) => ({
provider: `togetherai.${modelType}`,
url: ({ path }) => `${baseURL}${path}`,
headers: getHeaders,
fetch: options.fetch
});
const createChatModel = (modelId) => {
return new OpenAICompatibleChatLanguageModel(modelId, {
...getCommonModelConfig("chat"),
includeUsage: true,
supportsStructuredOutputs: getModelStructuredOutputSupport(modelId)
});
};
const createCompletionModel = (modelId) => new OpenAICompatibleCompletionLanguageModel(modelId, {
...getCommonModelConfig("completion"),
includeUsage: true
});
const createEmbeddingModel = (modelId) => new OpenAICompatibleEmbeddingModel(modelId, getCommonModelConfig("embedding"));
const createImageModel = (modelId) => new TogetherAIImageModel(modelId, {
...getCommonModelConfig("image"),
baseURL: baseURL ?? "https://api.together.xyz/v1/"
});
const createRerankingModel = (modelId) => new TogetherAIRerankingModel(modelId, {
...getCommonModelConfig("reranking"),
baseURL: baseURL ?? "https://api.together.xyz/v1/"
});
const provider = (modelId) => createChatModel(modelId);
provider.specificationVersion = "v4";
provider.completionModel = createCompletionModel;
provider.languageModel = createChatModel;
provider.chatModel = createChatModel;
provider.embeddingModel = createEmbeddingModel;
provider.textEmbeddingModel = createEmbeddingModel;
provider.image = createImageModel;
provider.imageModel = createImageModel;
provider.reranking = createRerankingModel;
provider.rerankingModel = createRerankingModel;
return provider;
}
createTogetherAI();
// ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/xai/5.0.35/e0618ebb4f63f13a767a1acb1d8d9b54666ee6ab27a9b4006e6b9cc1f854ade3/node_modules/@ai-sdk/xai/dist/index.js
const apiErrorSchema = () => z.object({ error: z.object({
message: z.string(),
type: z.string().nullish(),
param: z.any().nullish(),
code: z.union([z.string(), z.number()]).nullish()
}) });
const responsesErrorSchema = () => z.object({
code: z.string(),
error: z.string()
});
const speechErrorSchema = () => z.object({ error: z.string() });
const xaiFailedResponseHandler = createJsonErrorResponseHandler({
errorSchema: lazySchema(() => zodSchema(z.union([
apiErrorSchema(),
responsesErrorSchema(),
speechErrorSchema()
]))),
errorToMessage: (data) => {
if (typeof data.error === "string") return "code" in data ? `${data.code}: ${data.error}` : data.error;
return data.error.message;
}
});
const xaiImageModelOptions = lazySchema(() => zodSchema(z.object({
aspect_ratio: z.string().optional(),
output_format: z.string().optional(),
sync_mode: z.boolean().optional(),
resolution: z.enum([
"1k",
"1.5k",
"2k"
]).optional(),
quality: z.enum([
"low",
"medium",
"high",
"auto"
]).optional(),
user: z.string().optional()
})));
const xaiProviderOptions = {
language: {
reasoningEffort: { description: "Reasoning effort for configurable models." },
reasoningSummary: { description: "Deprecated summary level; xAI ignores this setting." },
logprobs: { description: "Return token log probabilities." },
topLogprobs: { description: "Number of token log probabilities to return." },
minP: { description: "Minimum probability sampling threshold." },
maxTurns: { description: "Maximum number of agentic tool-calling turns." },
parallelToolCalls: { description: "Allow parallel tool calls." },
promptCacheKey: { description: "Cache affinity key for shared prompt prefixes." },
safetyIdentifier: { description: "End-user identifier for policy violations." },
serviceTier: { description: "Default or priority processing tier." },
store: { description: "Store the input and response for later retrieval." },
previousResponseId: { description: "Previous response ID to continue." },
user: { description: "End-user identifier for abuse monitoring." },
include: { description: "Additional output data to return." }
},
image: {
aspect_ratio: { description: "Output aspect ratio, unless aspectRatio is provided." },
output_format: { description: "Output image encoding." },
sync_mode: { description: "Wait for image generation to complete." },
resolution: { description: "Output image resolution." },
quality: { description: "Output image quality." },
user: { description: "End-user identifier." }
},
speech: {
sampleRate: { description: "Output audio sample rate." },
bitRate: { description: "MP3 output bit rate." },
optimizeStreamingLatency: { description: "Trade quality for lower latency." },
textNormalization: { description: "Normalize written text before synthesis." },
withTimestamps: { description: "Return character timings and audio duration." },
replace: { description: "Spoken substitutions and pronunciation hints." }
},
transcription: {
audioFormat: { description: "Encoding of raw input audio." },
sampleRate: { description: "Input audio sample rate." },
language: { description: "Language for inverse text normalization." },
format: { description: "Enable inverse text normalization." },
multichannel: { description: "Transcribe each audio channel separately." },
channels: { description: "Number of interleaved input audio channels." },
diarize: { description: "Enable speaker diarization." },
keyterm: { description: "Terms to bias transcription toward." },
fillerWords: { description: "Include filler words in the transcript." },
vadThreshold: { description: "Voice activity detection threshold." },
streaming: { description: "WebSocket streaming transcription settings." }
}
};
const languageDefinitions = {
"grok-4.7": {
image: true,
reasoning: true,
efforts: [
"low",
"medium",
"high",
"xhigh"
]
},
"grok-4.6": {
image: true,
reasoning: true,
efforts: [
"low",
"medium",
"high",
"xhigh"
]
},
"grok-4.5": {
image: true,
reasoning: true,
efforts: [
"low",
"medium",
"high"
]
},
"grok-4.20-reasoning": {
image: true,
reasoning: true
},
"grok-4.20-non-reasoning": {
image: true,
reasoning: false
},
"grok-4-1-fast-reasoning": {
image: true,
reasoning: true
},
"grok-4-1-fast-non-reasoning": {
image: true,
reasoning: false
},
"grok-4-1": {
image: false,
reasoning: false
},
"grok-4-fast-reasoning": {
image: true,
reasoning: true
},
"grok-4-fast-non-reasoning": {
image: true,
reasoning: false
},
"grok-code-fast-1": {
image: false,
reasoning: true
},
"grok-4": {
image: false,
reasoning: true
},
"grok-3": {
image: false,
reasoning: false
},
"grok-3-mini": {
image: false,
reasoning: true
}
};
const modelsWithoutReasoningEffort = /^grok-4\.20(-\d{4})?-(non-)?reasoning$/;
const modelsWithoutNoneReasoningEffort = /^grok-(?:4\.[5-9](?!\d)|(?:[5-9]|[1-9]\d+)(?:[.-]|$))/;
function createLanguageModelEntry(modelId, definition) {
const configurable = !modelsWithoutReasoningEffort.test(modelId);
return {
capabilities: { language: {
inputs: {
image: definition?.image ?? "unknown",
audio: "unknown"
},
objectGeneration: definition != null ? true : "unknown",
tools: {
usage: definition != null ? true : "unknown",
streaming: definition != null ? true : "unknown"
},
reasoning: {
support: definition?.reasoning ?? "unknown",
efforts: definition?.efforts,
portable: {
configurable,
none: !modelsWithoutNoneReasoningEffort.test(modelId),
xhigh: modelId === "grok-4.6"
}
},
sampling: {
temperature: "unknown",
topP: "unknown",
logprobs: "unknown"
}
} },
providerOptions: { language: declareProviderOptions(xaiProviderOptions.language, definition != null ? true : "unknown", {
reasoningEffort: !configurable ? false : definition != null ? true : "unknown",
reasoningSummary: false
}) }
};
}
const commonAspectRatios = [
"1:1",
"16:9",
"9:16",
"4:3",
"3:4",
"3:2",
"2:3",
"2:1",
"1:2",
"19.5:9",
"9:19.5",
"20:9",
"9:20"
];
function createImageModelEntry(definition) {
return {
capabilities: { image: {
sizes: { description: "Use aspectRatio and providerOptions.xai.resolution instead of size." },
fileInput: definition != null ? true : "unknown",
maskInput: definition != null ? false : "unknown",
maxImagesPerCall: 3,
resolutions: definition?.resolutions,
aspectRatios: definition?.aspectRatios
} },
providerOptions: { image: declareProviderOptions(xaiProviderOptions.image, definition != null ? true : "unknown", { quality: definition?.quality ?? "unknown" }) }
};
}
const defaultSpeechModelEntry = {
capabilities: { speech: {
instructions: false,
language: true,
speed: true,
outputFormats: [
"mp3",
"wav",
"pcm",
"mulaw",
"alaw"
]
} },
providerOptions: { speech: declareProviderOptions(xaiProviderOptions.speech, true, { bitRate: { condition: "Only supported for MP3 output." } }) },
requestConfig: { speech: {
voice: "eve",
language: "auto",
outputFormat: "mp3"
} }
};
function createTranscriptionModelEntry(modelId, declared) {
const support = declared ? true : "unknown";
return {
capabilities: { transcription: {
transcription: support,
streaming: support,
duration: support,
segments: support,
language: support,
wordTimestamps: support,
diarization: support,
multichannel: support
} },
providerOptions: { transcription: declareProviderOptions(xaiProviderOptions.transcription, support, {
audioFormat: { condition: "Opus encoding is supported for streaming requests only." },
format: { condition: "Requires language and a request/response transcription request." },
streaming: { condition: "Only supported for streaming transcription." }
}) },
requestConfig: { transcription: { model: modelId || void 0 } }
};
}
const defaultTranscriptionModelEntry = createTranscriptionModelEntry("", true);
const xaiModelCatalog = {
...Object.fromEntries(Object.entries(languageDefinitions).map(([modelId, definition]) => [modelId, createLanguageModelEntry(modelId, definition)])),
"grok-imagine-image-2.0": createImageModelEntry({
resolutions: [
"1k",
"1.5k",
"2k"
],
aspectRatios: [
...commonAspectRatios,
"21:9",
"5:2",
"auto"
],
quality: true
}),
"grok-imagine-image-pro": createImageModelEntry({
resolutions: [
"1k",
"1.5k",
"2k"
],
aspectRatios: [...commonAspectRatios, "auto"],
quality: "unknown"
}),
"grok-imagine-image": createImageModelEntry({
resolutions: ["1k"],
aspectRatios: [...commonAspectRatios, "auto"],
quality: "unknown"
}),
"": {
capabilities: {
...defaultSpeechModelEntry.capabilities,
...defaultTranscriptionModelEntry.capabilities
},
providerOptions: {
...defaultSpeechModelEntry.providerOptions,
...defaultTranscriptionModelEntry.providerOptions
},
requestConfig: {
...defaultSpeechModelEntry.requestConfig,
...defaultTranscriptionModelEntry.requestConfig
}
},
"grok-voice-transcribe-2.0": createTranscriptionModelEntry("grok-voice-transcribe-2.0", true),
"grok-voice-latest": { capabilities: { realtime: {
conversation: "turn-based",
transports: ["websocket"],
connections: ["client-secret-websocket"]
} } }
};
function findModelEntry(modelId) {
return Object.prototype.hasOwnProperty.call(xaiModelCatalog, modelId) ? xaiModelCatalog[modelId] : void 0;
}
function getXaiLanguageModelEntry(modelId) {
const entry = findModelEntry(modelId);
return entry?.capabilities.language != null && entry.providerOptions?.language != null ? {
capabilities: { language: entry.capabilities.language },
providerOptions: { language: entry.providerOptions.language }
} : createLanguageModelEntry(modelId);
}
function getXaiImageModelEntry(modelId) {
const entry = findModelEntry(modelId);
return entry?.capabilities.image != null && entry.providerOptions?.image != null ? {
capabilities: { image: entry.capabilities.image },
providerOptions: { image: entry.providerOptions.image }
} : createImageModelEntry();
}
function getXaiSpeechModelEntry() {
return defaultSpeechModelEntry;
}
function getXaiTranscriptionModelEntry(modelId) {
const entry = findModelEntry(modelId);
return entry?.capabilities.transcription != null && entry.providerOptions?.transcription != null && entry.requestConfig?.transcription != null ? {
capabilities: { transcription: entry.capabilities.transcription },
providerOptions: { transcription: entry.providerOptions.transcription },
requestConfig: { transcription: entry.requestConfig.transcription }
} : createTranscriptionModelEntry(modelId, false);
}
function declareProviderOptions(definitions, support, exceptions) {
return Object.fromEntries(Object.keys(definitions).map((option) => [option, exceptions[option] ?? support]));
}
var XaiImageModel = class XaiImageModel {
get supportsFileInputs() {
const support = getXaiImageModelEntry(this.modelId).capabilities.image.fileInput;
return typeof support === "boolean" ? support : void 0;
}
get supportsMaskInputs() {
const support = getXaiImageModelEntry(this.modelId).capabilities.image.maskInput;
return typeof support === "boolean" ? support : void 0;
}
get provider() {
return this.config.provider;
}
static [WORKFLOW_SERIALIZE](model) {
return serializeModelOptions({
modelId: model.modelId,
config: model.config
});
}
static [WORKFLOW_DESERIALIZE](options) {
return new XaiImageModel(options.modelId, options.config);
}
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
this.maxImagesPerCall = getXaiImageModelEntry(modelId).capabilities.image.maxImagesPerCall;
}
async doGenerate({ prompt, n, size, aspectRatio, seed, providerOptions, headers, abortSignal, files, mask }) {
const warnings = [];
if (size != null) warnings.push({
type: "unsupported",
feature: "size",
details: "This model does not support the `size` option. Use `aspectRatio` instead."
});
if (seed != null) warnings.push({
type: "unsupported",
feature: "seed"
});
if (mask != null) warnings.push({
type: "unsupported",
feature: "mask"
});
const xaiOptions = await parseProviderOptions({
provider: "xai",
providerOptions,
schema: xaiImageModelOptions
});
const hasFiles = files != null && files.length > 0;
const imageUrls = hasFiles ? files.map((file) => convertImageModelFileToDataUri(file)) : [];
const endpoint = hasFiles ? "/images/edits" : "/images/generations";
const body = {
model: this.modelId,
prompt,
n,
response_format: "b64_json"
};
if (aspectRatio != null) body.aspect_ratio = aspectRatio;
if (xaiOptions?.output_format != null) body.output_format = xaiOptions.output_format;
if (xaiOptions?.sync_mode != null) body.sync_mode = xaiOptions.sync_mode;
if (xaiOptions?.aspect_ratio != null && aspectRatio == null) body.aspect_ratio = xaiOptions.aspect_ratio;
if (xaiOptions?.resolution != null) body.resolution = xaiOptions.resolution;
if (xaiOptions?.quality != null) body.quality = xaiOptions.quality;
if (xaiOptions?.user != null) body.user = xaiOptions.user;
if (imageUrls.length === 1) body.image = {
url: imageUrls[0],
type: "image_url"
};
else if (imageUrls.length > 1) body.images = imageUrls.map((url) => ({
url,
type: "image_url"
}));
const baseURL = this.config.baseURL ?? "https://api.x.ai/v1";
const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
const { value: response, responseHeaders } = await postJsonToApi({
url: `${baseURL}${endpoint}`,
headers: combineHeaders(await resolve(this.config.headers), headers),
body,
failedResponseHandler: xaiFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler(xaiImageResponseSchema),
abortSignal,
fetch: this.config.fetch
});
if (response.data.some((image) => image.respect_moderation === false)) throw new Error("Image generation was blocked due to a content policy violation.");
return {
images: response.data.every((image) => image.b64_json != null) ? response.data.map((image) => image.b64_json) : await Promise.all(response.data.map((image) => this.downloadImage(image.url, abortSignal))),
warnings,
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders
},
providerMetadata: { xai: {
images: response.data.map((item) => ({ ...item.revised_prompt ? { revisedPrompt: item.revised_prompt } : {} })),
...response.usage?.cost_in_usd_ticks != null ? { costInUsdTicks: response.usage.cost_in_usd_ticks } : {}
} }
};
}
async downloadImage(url, abortSignal) {
const { value } = await getFromApi({
url,
validateUrl: true,
trustedOrigin: this.config.baseURL,
abortSignal,
failedResponseHandler: createStatusCodeErrorResponseHandler(),
successfulResponseHandler: createBinaryResponseHandler(),
fetch: this.config.fetch
});
return value;
}
};
const xaiImageResponseSchema = lazySchema(() => zodSchema(z.object({
data: z.array(z.object({
url: z.string().nullish(),
b64_json: z.string().nullish(),
revised_prompt: z.string().nullish(),
respect_moderation: z.boolean().nullish()
})),
usage: z.object({ cost_in_usd_ticks: z.number().nullish() }).nullish()
})));
function getResponseMetadata({ id, model, created, created_at }) {
return createLanguageModelResponseMetadata({
id,
model,
created: created ?? created_at
});
}
function mapXaiFinishReason(finishReason) {
switch (finishReason) {
case "stop": return "stop";
case "length": return "length";
case "tool_calls":
case "function_call": return "tool-calls";
case "content_filter": return "content-filter";
default: return "other";
}
}
const xaiFilesResponseSchema = lazySchema(() => zodSchema(z.object({
id: z.string(),
object: z.string().nullish(),
bytes: z.number().nullish(),
created_at: z.number().nullish(),
expires_at: z.number().nullish(),
filename: z.string().nullish(),
purpose: z.string().nullish(),
status: z.string().nullish()
})));
const xaiFileDeleteResponseSchema = lazySchema(() => zodSchema(z.object({
id: z.string(),
object: z.string().nullish(),
deleted: z.boolean()
})));
const xaiFilePartProviderOptions = lazySchema(() => zodSchema(z.object({
/**
* Controls the resolution at which the model processes the image.
* `low` processes the image at reduced resolution and consumes fewer
* input tokens, `high` processes the image at full resolution, and
* `auto` lets the API decide. Defaults to full resolution when not set.
*
* Note: the xAI API silently ignores invalid values, so the value is
* validated client-side.
*
* @see https://docs.x.ai/developers/model-capabilities/images/understanding
*/
imageDetail: z.enum([
"low",
"high",
"auto"
]).optional() })));
async function convertToXaiResponsesInput({ prompt }) {
const input = [];
const inputWarnings = [];
for (const message of prompt) switch (message.role) {
case "system":
input.push({
role: "system",
content: message.content
});
break;
case "user": {
const contentParts = [];
for (const block of message.content) switch (block.type) {
case "text":
contentParts.push({
type: "input_text",
text: block.text
});
break;
case "file":
switch (block.data.type) {
case "reference":
contentParts.push({
type: "input_file",
file_id: resolveProviderReference({
reference: block.data.reference,
provider: "xai"
})
});
break;
case "text": throw new UnsupportedFunctionalityError({ functionality: "text file parts" });
case "url":
case "data": if (getTopLevelMediaType$2(block.mediaType) === "image") {
const imageUrl = block.data.type === "url" ? block.data.url.toString() : `data:${resolveFullMediaType({ part: block })};base64,${convertToBase64(block.data.data)}`;
const filePartOptions = await parseProviderOptions({
provider: "xai",
providerOptions: block.providerOptions,
schema: xaiFilePartProviderOptions
});
contentParts.push({
type: "input_image",
image_url: imageUrl,
...filePartOptions?.imageDetail != null && { detail: filePartOptions.imageDetail }
});
} else if (block.data.type === "url") contentParts.push({
type: "input_file",
file_url: block.data.url.toString()
});
else throw new UnsupportedFunctionalityError({ functionality: `file part media type ${block.mediaType} as inline data (xAI Responses requires a URL or a Files API reference for non-image files)` });
}
break;
default: inputWarnings.push({
type: "other",
message: "xAI Responses API does not support this content type in user messages"
});
}
input.push({
role: "user",
content: contentParts
});
break;
}
case "assistant":
for (const part of message.content) switch (part.type) {
case "text": {
const id = typeof part.providerOptions?.xai?.itemId === "string" ? part.providerOptions.xai.itemId : void 0;
input.push({
role: "assistant",
content: part.text,
id
});
break;
}
case "tool-call": {
if (part.providerExecuted) break;
const id = typeof part.providerOptions?.xai?.itemId === "string" ? part.providerOptions.xai.itemId : void 0;
input.push({
type: "function_call",
id: id ?? part.toolCallId,
call_id: part.toolCallId,
name: part.toolName,
arguments: JSON.stringify(part.input),
status: "completed"
});
break;
}
case "tool-result": break;
case "reasoning": {
const itemId = typeof part.providerOptions?.xai?.itemId === "string" ? part.providerOptions.xai.itemId : void 0;
const encryptedContent = typeof part.providerOptions?.xai?.reasoningEncryptedContent === "string" ? part.providerOptions.xai.reasoningEncryptedContent : void 0;
if (itemId != null || encryptedContent != null) {
const summaryParts = [];
if (part.text.length > 0) summaryParts.push({
type: "summary_text",
text: part.text
});
input.push({
type: "reasoning",
id: itemId ?? "",
summary: summaryParts,
status: "completed",
...encryptedContent != null && { encrypted_content: encryptedContent }
});
} else inputWarnings.push({
type: "other",
message: "Reasoning parts without itemId or encrypted content cannot be sent back to xAI. Skipping."
});
break;
}
case "reasoning-file":
case "custom":
case "file":
inputWarnings.push({
type: "other",
message: `xAI Responses API does not support ${part.type} in assistant messages`
});
break;
default: inputWarnings.push({
type: "other",
message: "xAI Responses API does not support this content type in assistant messages"
});
}
break;
case "tool":
for (const part of message.content) {
if (part.type === "tool-approval-response") continue;
const output = part.output;
let outputValue;
switch (output.type) {
case "text":
case "error-text":
outputValue = output.value;
break;
case "execution-denied":
outputValue = output.reason ?? "tool execution denied";
break;
case "json":
case "error-json":
outputValue = JSON.stringify(output.value);
break;
case "content":
outputValue = [];
for (const item of output.value) switch (item.type) {
case "text":
outputValue.push({
type: "input_text",
text: item.text
});
break;
case "file": if (getTopLevelMediaType$2(item.mediaType) === "image" && (item.data.type === "data" || item.data.type === "url")) outputValue.push({
type: "input_image",
image_url: item.data.type === "url" ? item.data.url.toString() : `data:${resolveFullMediaType({ part: item })};base64,${convertToBase64(item.data.data)}`
});
}
break;
default: outputValue = "";
}
input.push({
type: "function_call_output",
call_id: part.toolCallId,
output: outputValue
});
}
break;
default: inputWarnings.push({
type: "other",
message: "unsupported message role"
});
}
return {
input,
inputWarnings
};
}
function convertXaiResponsesUsage(usage) {
const cacheReadTokens = usage.input_tokens_details?.cached_tokens ?? 0;
const reasoningTokens = usage.output_tokens_details?.reasoning_tokens ?? 0;
const inputTokensIncludesCached = cacheReadTokens <= usage.input_tokens;
return {
inputTokens: {
total: inputTokensIncludesCached ? usage.input_tokens : usage.input_tokens + cacheReadTokens,
noCache: inputTokensIncludesCached ? usage.input_tokens - cacheReadTokens : usage.input_tokens,
cacheRead: cacheReadTokens,
cacheWrite: void 0
},
outputTokens: {
total: usage.output_tokens,
text: usage.output_tokens - reasoningTokens,
reasoning: reasoningTokens
},
raw: usage
};
}
function mapXaiResponsesFinishReason(finishReason) {
switch (finishReason) {
case "stop":
case "completed": return "stop";
case "length":
case "max_output_tokens": return "length";
case "tool_calls":
case "function_call": return "tool-calls";
case "content_filter": return "content-filter";
default: return "other";
}
}
const annotationSchema = () => z.union([z.object({
type: z.literal("url_citation"),
url: z.string(),
title: z.string().optional()
}), z.object({ type: z.string() })]);
const messageContentPartSchema = () => z.object({
type: z.string(),
text: z.string().optional(),
logprobs: z.array(z.any()).optional(),
annotations: z.array(annotationSchema()).optional()
});
const reasoningSummaryPartSchema = () => z.object({
type: z.string(),
text: z.string()
});
const toolCallSchema = () => z.object({
name: z.string().optional(),
arguments: z.string().optional(),
input: z.string().optional(),
call_id: z.string().optional(),
id: z.string(),
status: z.string(),
action: z.any().optional()
});
const webSearchWireSourceSchema = z.object({
type: z.literal("url"),
url: z.string()
});
const webSearchWireActionSchema = z.discriminatedUnion("type", [
z.object({
type: z.literal("search"),
query: z.string().nullish(),
queries: z.array(z.string()).nullish(),
sources: z.array(z.unknown()).nullish()
}),
z.object({
type: z.literal("open_page"),
url: z.string().nullish(),
sources: z.array(z.unknown()).nullish()
}),
z.object({
type: z.literal("find_in_page"),
url: z.string().nullish(),
pattern: z.string().nullish(),
sources: z.array(z.unknown()).nullish()
})
]);
const mcpCallSchema = () => z.object({
name: z.string().optional(),
arguments: z.string().optional(),
output: z.string().optional(),
error: z.string().optional(),
id: z.string(),
status: z.string(),
server_label: z.string().optional()
});
const outputItemSchema = () => z.discriminatedUnion("type", [
z.object({
type: z.literal("web_search_call"),
...toolCallSchema().shape
}),
z.object({
type: z.literal("x_search_call"),
...toolCallSchema().shape
}),
z.object({
type: z.literal("code_interpreter_call"),
...toolCallSchema().shape
}),
z.object({
type: z.literal("code_execution_call"),
...toolCallSchema().shape
}),
z.object({
type: z.literal("view_image_call"),
...toolCallSchema().shape
}),
z.object({
type: z.literal("view_x_video_call"),
...toolCallSchema().shape
}),
z.object({
type: z.literal("file_search_call"),
id: z.string(),
status: z.string(),
queries: z.array(z.string()).optional(),
results: z.array(z.object({
file_id: z.string(),
filename: z.string(),
score: z.number(),
text: z.string()
})).nullish()
}),
z.object({
type: z.literal("image_generation_call"),
id: z.string(),
status: z.string(),
prompt: z.string().nullish(),
result: z.string().nullish()
}),
z.object({
type: z.literal("custom_tool_call"),
...toolCallSchema().shape
}),
z.object({
type: z.literal("mcp_call"),
...mcpCallSchema().shape
}),
z.object({
type: z.literal("message"),
role: z.string(),
content: z.array(messageContentPartSchema()),
id: z.string(),
status: z.string()
}),
z.object({
type: z.literal("function_call"),
name: z.string(),
arguments: z.string(),
call_id: z.string(),
id: z.string()
}),
z.object({
type: z.literal("reasoning"),
id: z.string(),
summary: z.array(reasoningSummaryPartSchema()),
content: z.array(z.object({
type: z.string(),
text: z.string()
})).nullish(),
status: z.string(),
encrypted_content: z.string().nullish()
})
]);
const xaiResponsesUsageSchema = () => z.object({
input_tokens: z.number(),
output_tokens: z.number(),
total_tokens: z.number().optional(),
input_tokens_details: z.object({ cached_tokens: z.number().optional() }).catchall(z.json()).optional(),
output_tokens_details: z.object({ reasoning_tokens: z.number().optional() }).catchall(z.json()).optional(),
num_sources_used: z.number().optional(),
num_server_side_tools_used: z.number().optional(),
cost_in_usd_ticks: z.number().nullish()
}).catchall(z.json());
const xaiResponsesResponseSchema = () => z.object({
id: z.string().nullish(),
created_at: z.number().nullish(),
model: z.string().nullish(),
object: z.literal("response"),
output: z.array(outputItemSchema()),
usage: xaiResponsesUsageSchema().nullish(),
status: z.string(),
service_tier: z.string().nullish(),
prompt_cache_key: z.string().nullish(),
safety_identifier: z.string().nullish()
});
const xaiResponsesResponseSchemaValidator = lazySchema(() => zodSchema(xaiResponsesResponseSchema()));
const xaiResponsesChunkSchema = lazySchema(() => zodSchema(z.union([
z.object({
type: z.literal("response.created"),
response: xaiResponsesResponseSchema().partial({
usage: true,
status: true
})
}),
z.object({
type: z.literal("response.in_progress"),
response: xaiResponsesResponseSchema().partial({
usage: true,
status: true
})
}),
z.object({
type: z.literal("response.output_item.added"),
item: outputItemSchema(),
output_index: z.number()
}),
z.object({
type: z.literal("response.output_item.done"),
item: outputItemSchema(),
output_index: z.number()
}),
z.object({
type: z.literal("response.content_part.added"),
item_id: z.string(),
output_index: z.number(),
content_index: z.number(),
part: messageContentPartSchema()
}),
z.object({
type: z.literal("response.content_part.done"),
item_id: z.string(),
output_index: z.number(),
content_index: z.number(),
part: messageContentPartSchema()
}),
z.object({
type: z.literal("response.output_text.delta"),
item_id: z.string(),
output_index: z.number(),
content_index: z.number(),
delta: z.string(),
logprobs: z.array(z.any()).optional()
}),
z.object({
type: z.literal("response.output_text.done"),
item_id: z.string(),
output_index: z.number(),
content_index: z.number(),
text: z.string(),
logprobs: z.array(z.any()).optional(),
annotations: z.array(annotationSchema()).optional()
}),
z.object({
type: z.literal("response.output_text.annotation.added"),
item_id: z.string(),
output_index: z.number(),
content_index: z.number(),
annotation_index: z.number(),
annotation: annotationSchema()
}),
z.object({
type: z.literal("response.reasoning_summary_part.added"),
item_id: z.string(),
output_index: z.number(),
summary_index: z.number(),
part: reasoningSummaryPartSchema()
}),
z.object({
type: z.literal("response.reasoning_summary_part.done"),
item_id: z.string(),
output_index: z.number(),
summary_index: z.number(),
part: reasoningSummaryPartSchema()
}),
z.object({
type: z.literal("response.reasoning_summary_text.delta"),
item_id: z.string(),
output_index: z.number(),
summary_index: z.number(),
delta: z.string()
}),
z.object({
type: z.literal("response.reasoning_summary_text.done"),
item_id: z.string(),
output_index: z.number(),
summary_index: z.number(),
text: z.string()
}),
z.object({
type: z.literal("response.reasoning_text.delta"),
item_id: z.string(),
output_index: z.number(),
content_index: z.number(),
delta: z.string()
}),
z.object({
type: z.literal("response.reasoning_text.done"),
item_id: z.string(),
output_index: z.number(),
content_index: z.number(),
text: z.string()
}),
z.object({
type: z.literal("response.web_search_call.in_progress"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.web_search_call.searching"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.web_search_call.completed"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.x_search_call.in_progress"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.x_search_call.searching"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.x_search_call.completed"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.file_search_call.in_progress"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.file_search_call.searching"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.file_search_call.completed"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.image_generation_call.in_progress"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.image_generation_call.generating"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.image_generation_call.completed"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.code_execution_call.in_progress"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.code_execution_call.executing"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.code_execution_call.completed"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.code_interpreter_call.in_progress"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.code_interpreter_call.executing"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.code_interpreter_call.interpreting"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.code_interpreter_call.completed"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.code_interpreter_call_code.delta"),
item_id: z.string(),
output_index: z.number(),
delta: z.string()
}),
z.object({
type: z.literal("response.code_interpreter_call_code.done"),
item_id: z.string(),
output_index: z.number(),
code: z.string()
}),
z.object({
type: z.literal("response.custom_tool_call_input.delta"),
item_id: z.string(),
output_index: z.number(),
delta: z.string()
}),
z.object({
type: z.literal("response.custom_tool_call_input.done"),
item_id: z.string(),
output_index: z.number(),
input: z.string()
}),
z.object({
type: z.literal("response.function_call_arguments.delta"),
item_id: z.string(),
output_index: z.number(),
delta: z.string()
}),
z.object({
type: z.literal("response.function_call_arguments.done"),
item_id: z.string(),
output_index: z.number(),
arguments: z.string()
}),
z.object({
type: z.literal("response.mcp_call.in_progress"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.mcp_call.executing"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.mcp_call.completed"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.mcp_call.failed"),
item_id: z.string(),
output_index: z.number()
}),
z.object({
type: z.literal("response.mcp_call_arguments.delta"),
item_id: z.string(),
output_index: z.number(),
delta: z.string()
}),
z.object({
type: z.literal("response.mcp_call_arguments.done"),
item_id: z.string(),
output_index: z.number(),
arguments: z.string().optional()
}),
z.object({
type: z.literal("response.mcp_call_output.delta"),
item_id: z.string(),
output_index: z.number(),
delta: z.string()
}),
z.object({
type: z.literal("response.mcp_call_output.done"),
item_id: z.string(),
output_index: z.number(),
output: z.string().optional()
}),
z.object({
type: z.literal("response.incomplete"),
response: z.object({
incomplete_details: z.object({ reason: z.string() }).nullish(),
usage: xaiResponsesUsageSchema().nullish(),
service_tier: z.string().nullish(),
prompt_cache_key: z.string().nullish(),
safety_identifier: z.string().nullish()
})
}),
z.object({
type: z.literal("response.failed"),
response: z.object({
error: z.object({
code: z.string().nullish(),
message: z.string()
}).nullish(),
incomplete_details: z.object({ reason: z.string() }).nullish(),
usage: xaiResponsesUsageSchema().nullish()
})
}),
z.object({
type: z.literal("error"),
code: z.string().nullish(),
message: z.string(),
param: z.string().nullish()
}),
z.object({
type: z.literal("response.done"),
response: xaiResponsesResponseSchema()
}),
z.object({
type: z.literal("response.completed"),
response: xaiResponsesResponseSchema()
})
])));
/**
* @see https://docs.x.ai/docs/api-reference#create-new-response
*/
const xaiLanguageModelResponsesOptions = lazySchema(() => zodSchema(z.object({
/**
* Constrains how hard a reasoning model thinks before responding.
* Possible values are `none` (disables reasoning entirely; supported by
* `grok-4.3`), `low` (uses fewer reasoning tokens), `medium`, `high`
* (uses more reasoning tokens), and `xhigh`
* (supported by `grok-4.6` and `grok-4.7`).
*
* @see https://docs.x.ai/docs/guides/reasoning
*/
reasoningEffort: z.enum([
"none",
"low",
"medium",
"high",
"xhigh"
]).optional(),
/**
* @deprecated xAI ignores the requested summary level and always returns a
* detailed reasoning summary.
*/
reasoningSummary: z.enum([
"auto",
"concise",
"detailed"
]).optional(),
logprobs: z.boolean().optional(),
topLogprobs: z.number().int().min(0).max(8).optional(),
/** Min-p sampling threshold between 0 and 1. */
minP: z.number().min(0).max(1).optional(),
/** Maximum number of agentic tool-calling turns. */
maxTurns: z.number().int().optional(),
/** Whether the model may call tools in parallel. @default true */
parallelToolCalls: z.boolean().optional(),
/** Cache key used to route requests with shared prompt prefixes. */
promptCacheKey: z.string().optional(),
/** Stable identifier used to attribute policy violations to an end user. */
safetyIdentifier: z.string().optional(),
serviceTier: z.enum(["default", "priority"]).optional(),
/**
* Whether to store the input message(s) and model response for later retrieval.
* Must be set to `false` for teams with Zero Data Retention (ZDR) enabled,
* otherwise the API will return an error.
* @default true
*/
store: z.boolean().optional(),
/**
* The ID of the previous response from the model.
*/
previousResponseId: z.string().optional(),
/** A unique identifier for the end user, used for abuse monitoring. */
user: z.string().optional(),
/**
* Specify additional output data to include in the model response.
* Example values: 'file_search_call.results'.
*/
include: z.array(z.enum([
"file_search_call.results",
"web_search_call.action.sources",
"code_interpreter_call.outputs",
"reasoning.encrypted_content",
"no_inline_citations"
])).nullish()
})));
/**
* Schema for file search tool arguments.
* @see https://docs.x.ai/docs/guides/using-collections/api
*/
const fileSearchArgsSchema = lazySchema(() => zodSchema(z.object({
vectorStoreIds: z.array(z.string()),
maxNumResults: z.number().optional()
})));
const fileSearchOutputSchema = lazySchema(() => zodSchema(z.object({
queries: z.array(z.string()),
results: z.array(z.object({
fileId: z.string(),
filename: z.string(),
score: z.number().min(0).max(1),
text: z.string()
})).nullable()
})));
const fileSearchToolFactory = createProviderExecutedToolFactory({
id: "xai.file_search",
inputSchema: lazySchema(() => zodSchema(z.object({}))),
outputSchema: fileSearchOutputSchema
});
const fileSearch = (args) => fileSearchToolFactory(args);
/**
* Schema for image generation tool arguments.
* @see https://docs.x.ai/developers/tools/overview
*/
const imageGenerationArgsSchema = lazySchema(() => zodSchema(z.object({ action: z.enum([
"auto",
"generate",
"edit"
]).optional() })));
const imageGenerationToolFactory = createProviderExecutedToolFactory({
id: "xai.image_generation",
inputSchema: lazySchema(() => zodSchema(z.object({}))),
outputSchema: lazySchema(() => zodSchema(z.object({
result: z.string(),
prompt: z.string().optional()
})))
});
const imageGeneration = (args = {}) => imageGenerationToolFactory(args);
const mcpServerArgsSchema = lazySchema(() => zodSchema(z.object({
serverUrl: z.string().describe("The URL of the MCP server"),
serverLabel: z.string().optional().describe("A label for the MCP server"),
serverDescription: z.string().optional().describe("Description of the MCP server"),
allowedTools: z.array(z.string()).optional().describe("List of allowed tool names"),
headers: z.record(z.string(), z.string()).optional().describe("Custom headers to send"),
authorization: z.string().optional().describe("Authorization header value")
})));
const mcpServerOutputSchema = lazySchema(() => zodSchema(z.object({
name: z.string(),
arguments: z.string(),
result: z.unknown()
})));
const mcpServerToolFactory = createProviderExecutedToolFactory({
id: "xai.mcp",
inputSchema: lazySchema(() => zodSchema(z.object({}))),
outputSchema: mcpServerOutputSchema
});
const mcpServer = (args) => mcpServerToolFactory(args);
const webSearchArgsSchema = lazySchema(() => zodSchema(z.object({
allowedDomains: z.array(z.string()).max(5).optional(),
excludedDomains: z.array(z.string()).max(5).optional(),
enableImageSearch: z.boolean().optional(),
enableImageUnderstanding: z.boolean().optional()
})));
const webSearchOutputSchema = lazySchema(() => zodSchema(z.object({
action: z.discriminatedUnion("type", [
z.object({
type: z.literal("search"),
query: z.string().optional(),
queries: z.array(z.string()).optional()
}),
z.object({
type: z.literal("openPage"),
url: z.string().nullish()
}),
z.object({
type: z.literal("findInPage"),
url: z.string().nullish(),
pattern: z.string().nullish()
})
]).optional(),
sources: z.array(z.object({
type: z.literal("url"),
url: z.string()
})).optional()
})));
const webSearchToolFactory = createProviderExecutedToolFactory({
id: "xai.web_search",
inputSchema: lazySchema(() => zodSchema(z.object({}))),
outputSchema: webSearchOutputSchema
});
const webSearch = (args = {}) => webSearchToolFactory(args);
const xSearchArgsSchema = lazySchema(() => zodSchema(z.object({
allowedXHandles: z.array(z.string()).max(20).optional(),
excludedXHandles: z.array(z.string()).max(20).optional(),
fromDate: z.string().optional(),
toDate: z.string().optional(),
enableImageUnderstanding: z.boolean().optional(),
enableVideoUnderstanding: z.boolean().optional()
})));
const xSearchOutputSchema = lazySchema(() => zodSchema(z.object({
query: z.string(),
posts: z.array(z.object({
author: z.string(),
text: z.string(),
url: z.string(),
likes: z.number()
}))
})));
const xSearchToolFactory = createProviderExecutedToolFactory({
id: "xai.x_search",
inputSchema: lazySchema(() => zodSchema(z.object({}))),
outputSchema: xSearchOutputSchema
});
const xSearch = (args = {}) => xSearchToolFactory(args);
async function prepareResponsesTools({ tools, toolChoice }) {
const normalizedTools = tools?.length ? tools : void 0;
const toolWarnings = [];
if (normalizedTools == null) return {
tools: void 0,
toolChoice: void 0,
toolWarnings
};
const xaiTools = [];
const toolByName = /* @__PURE__ */ new Map();
for (const tool of normalizedTools) {
toolByName.set(tool.name, tool);
if (tool.type === "provider") switch (tool.id) {
case "xai.web_search": {
const args = await validateTypes({
value: tool.args,
schema: webSearchArgsSchema
});
xaiTools.push({
type: "web_search",
allowed_domains: args.allowedDomains,
excluded_domains: args.excludedDomains,
enable_image_search: args.enableImageSearch,
enable_image_understanding: args.enableImageUnderstanding
});
break;
}
case "xai.x_search": {
const args = await validateTypes({
value: tool.args,
schema: xSearchArgsSchema
});
xaiTools.push({
type: "x_search",
allowed_x_handles: args.allowedXHandles,
excluded_x_handles: args.excludedXHandles,
from_date: args.fromDate,
to_date: args.toDate,
enable_image_understanding: args.enableImageUnderstanding,
enable_video_understanding: args.enableVideoUnderstanding
});
break;
}
case "xai.code_execution":
xaiTools.push({ type: "code_interpreter" });
break;
case "xai.view_image":
xaiTools.push({ type: "view_image" });
break;
case "xai.view_x_video":
xaiTools.push({ type: "view_x_video" });
break;
case "xai.image_generation": {
const args = await validateTypes({
value: tool.args,
schema: imageGenerationArgsSchema
});
xaiTools.push({
type: "image_generation",
action: args.action
});
break;
}
case "xai.file_search": {
const args = await validateTypes({
value: tool.args,
schema: fileSearchArgsSchema
});
xaiTools.push({
type: "file_search",
vector_store_ids: args.vectorStoreIds,
max_num_results: args.maxNumResults
});
break;
}
case "xai.mcp": {
const args = await validateTypes({
value: tool.args,
schema: mcpServerArgsSchema
});
xaiTools.push({
type: "mcp",
server_url: args.serverUrl,
server_label: args.serverLabel,
server_description: args.serverDescription,
allowed_tools: args.allowedTools,
headers: args.headers,
authorization: args.authorization
});
break;
}
default: toolWarnings.push({
type: "unsupported",
feature: `provider-defined tool ${tool.name}`
});
}
else xaiTools.push({
type: "function",
name: tool.name,
description: tool.description,
parameters: tool.inputSchema,
...tool.strict != null ? { strict: tool.strict } : {}
});
}
if (toolChoice == null) return {
tools: xaiTools,
toolChoice: void 0,
toolWarnings
};
const type = toolChoice.type;
switch (type) {
case "auto":
case "none": return {
tools: xaiTools,
toolChoice: type,
toolWarnings
};
case "required": return {
tools: xaiTools,
toolChoice: "required",
toolWarnings
};
case "tool": {
const selectedTool = toolByName.get(toolChoice.toolName);
if (selectedTool == null) return {
tools: xaiTools,
toolChoice: void 0,
toolWarnings
};
if (selectedTool.type === "provider") {
toolWarnings.push({
type: "unsupported",
feature: `toolChoice for server-side tool "${selectedTool.name}"`
});
return {
tools: xaiTools,
toolChoice: void 0,
toolWarnings
};
}
return {
tools: xaiTools,
toolChoice: {
type: "function",
name: selectedTool.name
},
toolWarnings
};
}
default: throw new UnsupportedFunctionalityError({ functionality: `tool choice type: ${type}` });
}
}
function createXaiResponsesStreamError({ message, code, eventType, data }) {
const statusCode = getHttpStatusCode(code);
return createProviderStreamError({
message,
type: eventType,
code: code ?? void 0,
...statusCode != null ? {
statusCode,
isRetryable: isRetryableStatusCode(statusCode)
} : getXaiResponsesStreamErrorMetadata(code),
data
});
}
function getXaiResponsesStreamErrorMetadata(code) {
switch (code) {
case "rate_limit_exceeded":
case "rate_limit_error": return {
statusCode: 429,
isRetryable: true
};
case "insufficient_quota": return {
statusCode: 429,
isRetryable: false
};
case "api_error":
case "internal_server_error":
case "server_error": return {
statusCode: 500,
isRetryable: true
};
case "overloaded_error":
case "service_unavailable": return {
statusCode: 503,
isRetryable: true
};
case "timeout":
case "timeout_error": return {
statusCode: 504,
isRetryable: true
};
case "authentication_error":
case "invalid_api_key": return {
statusCode: 401,
isRetryable: false
};
case "permission_error": return {
statusCode: 403,
isRetryable: false
};
case "not_found_error":
case "model_not_found": return {
statusCode: 404,
isRetryable: false
};
case "bad_request":
case "context_length_exceeded":
case "invalid_request_error": return {
statusCode: 400,
isRetryable: false
};
default: return {};
}
}
function getHttpStatusCode(value) {
const statusCode = typeof value === "string" && /^\d{3}$/.test(value) ? Number(value) : value;
return typeof statusCode === "number" && Number.isInteger(statusCode) && statusCode >= 400 && statusCode <= 599 ? statusCode : void 0;
}
function isRetryableStatusCode(statusCode) {
return statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500;
}
const xaiResponsesSupportedUrls = {
"image/*": [/^https?:\/\/.*$/],
"application/pdf": [/^https?:\/\/.*$/],
"text/*": [/^https?:\/\/.*$/]
};
var XaiResponsesLanguageModel = class XaiResponsesLanguageModel {
static [WORKFLOW_SERIALIZE](model) {
return serializeModelOptions({
modelId: model.modelId,
config: model.config
});
}
static [WORKFLOW_DESERIALIZE](options) {
return new XaiResponsesLanguageModel(options.modelId, options.config);
}
constructor(modelId, config) {
this.specificationVersion = "v4";
this.supportedUrls = xaiResponsesSupportedUrls;
this.modelId = modelId;
this.config = config;
}
get provider() {
return this.config.provider;
}
static async prepareRequest({ modelId, options: { prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, seed, responseFormat, providerOptions, tools, toolChoice, reasoning } }) {
const warnings = [];
const options = await parseProviderOptions({
provider: "xai",
providerOptions,
schema: xaiLanguageModelResponsesOptions
}) ?? {};
if (frequencyPenalty != null) warnings.push({
type: "unsupported",
feature: "frequencyPenalty"
});
if (presencePenalty != null) warnings.push({
type: "unsupported",
feature: "presencePenalty"
});
if (stopSequences != null) warnings.push({
type: "unsupported",
feature: "stopSequences"
});
const webSearchToolName = tools?.find((tool) => tool.type === "provider" && tool.id === "xai.web_search")?.name;
const xSearchToolName = tools?.find((tool) => tool.type === "provider" && tool.id === "xai.x_search")?.name;
const codeExecutionToolName = tools?.find((tool) => tool.type === "provider" && tool.id === "xai.code_execution")?.name;
const mcpToolName = tools?.find((tool) => tool.type === "provider" && tool.id === "xai.mcp")?.name;
const fileSearchToolName = tools?.find((tool) => tool.type === "provider" && tool.id === "xai.file_search")?.name;
const imageGenerationToolName = tools?.find((tool) => tool.type === "provider" && tool.id === "xai.image_generation")?.name;
const { input, inputWarnings } = await convertToXaiResponsesInput({
prompt,
store: options.store ?? true
});
warnings.push(...inputWarnings);
const { tools: xaiTools, toolChoice: xaiToolChoice, toolWarnings } = await prepareResponsesTools({
tools,
toolChoice
});
warnings.push(...toolWarnings);
let include = options.include ? [...options.include] : void 0;
if (options.store === false) {
if (include == null) include = ["reasoning.encrypted_content"];
else include = [...include, "reasoning.encrypted_content"];
}
const { portable: reasoningCapabilities } = getXaiLanguageModelEntry(modelId).capabilities.language.reasoning;
let resolvedReasoningEffort = options.reasoningEffort;
if (resolvedReasoningEffort == null && isCustomReasoning(reasoning)) {
if (!reasoningCapabilities.configurable) warnings.push({
type: "unsupported",
feature: "reasoning",
details: `reasoning "${reasoning}" is not supported by this model.`
});
else resolvedReasoningEffort = mapReasoningToProviderEffort({
reasoning,
effortMap: {
...reasoningCapabilities.none && { none: "none" },
low: "low",
medium: "medium",
high: "high",
...reasoningCapabilities.xhigh && { xhigh: "xhigh" }
},
warnings
});
}
const baseArgs = {
model: modelId,
input,
logprobs: options.logprobs === true || options.topLogprobs != null ? true : void 0,
top_logprobs: options.topLogprobs,
max_output_tokens: maxOutputTokens,
temperature,
top_p: topP,
top_k: topK,
min_p: options.minP,
seed,
...responseFormat?.type === "json" && { text: { format: responseFormat.schema != null ? {
type: "json_schema",
strict: true,
name: responseFormat.name ?? "response",
description: responseFormat.description,
schema: responseFormat.schema
} : { type: "json_object" } } },
...resolvedReasoningEffort != null && { reasoning: { effort: resolvedReasoningEffort } },
...options.store === false && { store: options.store },
...include != null && { include },
...options.previousResponseId != null && { previous_response_id: options.previousResponseId },
...options.maxTurns != null && { max_turns: options.maxTurns },
...options.parallelToolCalls != null && { parallel_tool_calls: options.parallelToolCalls },
...options.promptCacheKey != null && { prompt_cache_key: options.promptCacheKey },
...options.safetyIdentifier != null && { safety_identifier: options.safetyIdentifier },
...options.serviceTier != null && { service_tier: options.serviceTier },
...options.user != null && { user: options.user }
};
if (xaiTools && xaiTools.length > 0) baseArgs.tools = xaiTools;
if (xaiToolChoice != null) baseArgs.tool_choice = xaiToolChoice;
return {
args: baseArgs,
warnings,
webSearchToolName,
xSearchToolName,
codeExecutionToolName,
mcpToolName,
fileSearchToolName,
imageGenerationToolName
};
}
getArgs(options) {
return XaiResponsesLanguageModel.prepareRequest({
modelId: this.modelId,
options
});
}
async doGenerate(options) {
const { args: body, warnings, webSearchToolName, xSearchToolName, codeExecutionToolName, mcpToolName, fileSearchToolName, imageGenerationToolName } = await this.getArgs(options);
const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({
url: `${this.config.baseURL ?? "https://api.x.ai/v1"}/responses`,
headers: combineHeaders(await resolve(this.config.headers), options.headers),
body,
failedResponseHandler: xaiFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler(xaiResponsesResponseSchemaValidator),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const content = [];
let hasFunctionCall = false;
const webSearchSubTools = [
"web_search",
"web_search_with_snippets",
"browse_page"
];
const xSearchSubTools = [
"x_user_search",
"x_keyword_search",
"x_semantic_search",
"x_thread_fetch"
];
for (const part of response.output) {
if (part.type === "file_search_call") {
const toolName = fileSearchToolName ?? "file_search";
content.push({
type: "tool-call",
toolCallId: part.id,
toolName,
input: "",
providerExecuted: true
});
content.push({
type: "tool-result",
toolCallId: part.id,
toolName,
result: {
queries: part.queries ?? [],
results: part.results?.map((result) => ({
fileId: result.file_id,
filename: result.filename,
score: result.score,
text: result.text
})) ?? null
}
});
continue;
}
if (part.type === "image_generation_call") {
const toolName = imageGenerationToolName ?? "image_generation";
content.push({
type: "tool-call",
toolCallId: part.id,
toolName,
input: "{}",
providerExecuted: true
});
if (part.result != null) content.push({
type: "tool-result",
toolCallId: part.id,
toolName,
result: {
result: part.result,
...part.prompt != null && { prompt: part.prompt }
}
});
else content.push({
type: "tool-result",
toolCallId: part.id,
toolName,
isError: true,
result: `Image generation failed (status: ${part.status}).`
});
continue;
}
if (part.type === "web_search_call" || part.type === "x_search_call" || part.type === "code_interpreter_call" || part.type === "code_execution_call" || part.type === "view_image_call" || part.type === "view_x_video_call" || part.type === "custom_tool_call" || part.type === "mcp_call") {
let toolName = part.name ?? "";
if (webSearchSubTools.includes(part.name ?? "") || part.type === "web_search_call") toolName = webSearchToolName ?? "web_search";
else if (xSearchSubTools.includes(part.name ?? "") || part.type === "x_search_call") toolName = xSearchToolName ?? "x_search";
else if (part.name === "code_execution" || part.type === "code_interpreter_call" || part.type === "code_execution_call") toolName = codeExecutionToolName ?? "code_execution";
else if (part.type === "mcp_call") toolName = mcpToolName ?? part.name ?? "mcp";
const toolInput = part.type === "custom_tool_call" ? part.input ?? "" : part.type === "mcp_call" ? part.arguments ?? "" : part.arguments ?? "";
content.push({
type: "tool-call",
toolCallId: part.id,
toolName,
input: toolInput,
providerExecuted: true
});
if (part.type === "web_search_call") content.push({
type: "tool-result",
toolCallId: part.id,
toolName,
result: mapWebSearchAction(part.action)
});
continue;
}
switch (part.type) {
case "message":
for (const contentPart of part.content) {
if (contentPart.text) content.push({
type: "text",
text: contentPart.text
});
if (contentPart.annotations) {
for (const annotation of contentPart.annotations) if (annotation.type === "url_citation" && "url" in annotation) content.push({
type: "source",
sourceType: "url",
id: this.config.generateId(),
url: annotation.url,
title: annotation.title ?? annotation.url
});
}
}
break;
case "function_call":
hasFunctionCall = true;
content.push({
type: "tool-call",
toolCallId: part.call_id,
toolName: part.name,
input: part.arguments
});
break;
case "reasoning": {
const reasoningText = (part.summary.length > 0 ? part.summary.map((s) => s.text) : (part.content ?? []).map((c) => c.text)).filter((text) => text && text.length > 0).join("");
if (reasoningText || part.encrypted_content) {
const hasMetadata = part.encrypted_content || part.id;
content.push({
type: "reasoning",
text: reasoningText,
...hasMetadata && { providerMetadata: { xai: {
...part.encrypted_content && { reasoningEncryptedContent: part.encrypted_content },
...part.id && { itemId: part.id }
} } }
});
}
break;
}
}
}
return {
content,
finishReason: {
unified: hasFunctionCall ? "tool-calls" : mapXaiResponsesFinishReason(response.status),
raw: response.status ?? void 0
},
usage: response.usage ? convertXaiResponsesUsage(response.usage) : {
inputTokens: {
total: 0,
noCache: 0,
cacheRead: 0,
cacheWrite: 0
},
outputTokens: {
total: 0,
text: 0,
reasoning: 0
}
},
...(response.usage?.cost_in_usd_ticks != null || response.service_tier != null || response.prompt_cache_key != null || response.safety_identifier != null) && { providerMetadata: { xai: {
...response.usage?.cost_in_usd_ticks != null && { costInUsdTicks: response.usage.cost_in_usd_ticks },
...response.service_tier != null && { serviceTier: response.service_tier },
...response.prompt_cache_key != null && { promptCacheKey: response.prompt_cache_key },
...response.safety_identifier != null && { safetyIdentifier: response.safety_identifier }
} } },
request: { body },
response: {
...getResponseMetadata(response),
headers: responseHeaders,
body: rawResponse
},
warnings
};
}
async doStream(options) {
const { args, warnings, webSearchToolName, xSearchToolName, codeExecutionToolName, mcpToolName, fileSearchToolName, imageGenerationToolName } = await this.getArgs(options);
const body = {
...args,
stream: true
};
const { responseHeaders, value: response } = await postJsonToApi({
url: `${this.config.baseURL ?? "https://api.x.ai/v1"}/responses`,
headers: combineHeaders(await resolve(this.config.headers), options.headers),
body,
failedResponseHandler: xaiFailedResponseHandler,
successfulResponseHandler: createEventSourceResponseHandler(xaiResponsesChunkSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
let finishReason = {
unified: "interrupted",
raw: void 0
};
let hasFunctionCall = false;
let usage = void 0;
let costInUsdTicks = void 0;
let serviceTier = void 0;
let promptCacheKey = void 0;
let safetyIdentifier = void 0;
let isFirstChunk = true;
const contentBlocks = {};
const seenToolCalls = /* @__PURE__ */ new Set();
const ongoingToolCalls = {};
const activeReasoning = {};
const self = this;
return {
stream: response.pipeThrough(new TransformStream({
start(controller) {
controller.enqueue({
type: "stream-start",
warnings
});
},
transform(chunk, controller) {
if (options.includeRawChunks) controller.enqueue({
type: "raw",
rawValue: chunk.rawValue
});
if (!chunk.success) {
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error: chunk.error
});
return;
}
const event = chunk.value;
if (event.type === "response.created" || event.type === "response.in_progress") {
if (isFirstChunk) {
controller.enqueue({
type: "response-metadata",
...getResponseMetadata(event.response)
});
isFirstChunk = false;
}
return;
}
if (event.type === "response.reasoning_summary_part.added") {
const blockId = `reasoning-${event.item_id}`;
if (activeReasoning[event.item_id] == null) {
activeReasoning[event.item_id] = {};
controller.enqueue({
type: "reasoning-start",
id: blockId,
providerMetadata: { xai: { itemId: event.item_id } }
});
}
}
if (event.type === "response.reasoning_summary_text.delta") {
const blockId = `reasoning-${event.item_id}`;
controller.enqueue({
type: "reasoning-delta",
id: blockId,
delta: event.delta,
providerMetadata: { xai: { itemId: event.item_id } }
});
return;
}
if (event.type === "response.reasoning_summary_text.done") return;
if (event.type === "response.reasoning_text.delta") {
const blockId = `reasoning-${event.item_id}`;
if (activeReasoning[event.item_id] == null) {
activeReasoning[event.item_id] = {};
controller.enqueue({
type: "reasoning-start",
id: blockId,
providerMetadata: { xai: { itemId: event.item_id } }
});
}
controller.enqueue({
type: "reasoning-delta",
id: blockId,
delta: event.delta,
providerMetadata: { xai: { itemId: event.item_id } }
});
return;
}
if (event.type === "response.reasoning_text.done") return;
if (event.type === "response.output_text.delta") {
const blockId = `text-${event.item_id}`;
if (contentBlocks[blockId] == null) {
contentBlocks[blockId] = { type: "text" };
controller.enqueue({
type: "text-start",
id: blockId
});
}
controller.enqueue({
type: "text-delta",
id: blockId,
delta: event.delta
});
return;
}
if (event.type === "response.output_text.done") {
if (event.annotations) {
for (const annotation of event.annotations) if (annotation.type === "url_citation" && "url" in annotation) controller.enqueue({
type: "source",
sourceType: "url",
id: self.config.generateId(),
url: annotation.url,
title: annotation.title ?? annotation.url
});
}
return;
}
if (event.type === "response.output_text.annotation.added") {
const annotation = event.annotation;
if (annotation.type === "url_citation" && "url" in annotation) controller.enqueue({
type: "source",
sourceType: "url",
id: self.config.generateId(),
url: annotation.url,
title: annotation.title ?? annotation.url
});
return;
}
if (event.type === "response.done" || event.type === "response.completed" || event.type === "response.incomplete") {
const response = event.response;
if (response.usage) {
usage = convertXaiResponsesUsage(response.usage);
costInUsdTicks = response.usage.cost_in_usd_ticks ?? void 0;
}
serviceTier = response.service_tier ?? void 0;
promptCacheKey = response.prompt_cache_key ?? void 0;
safetyIdentifier = response.safety_identifier ?? void 0;
if (event.type === "response.incomplete") {
const reason = "incomplete_details" in response ? response.incomplete_details?.reason : void 0;
finishReason = {
unified: reason ? mapXaiResponsesFinishReason(reason) : "other",
raw: reason ?? "incomplete"
};
} else if ("status" in response && response.status) finishReason = {
unified: hasFunctionCall ? "tool-calls" : mapXaiResponsesFinishReason(response.status),
raw: response.status
};
else if (finishReason.unified === "interrupted") finishReason = {
unified: "other",
raw: void 0
};
return;
}
if (event.type === "response.failed") {
const reason = event.response.incomplete_details?.reason;
finishReason = {
unified: reason ? mapXaiResponsesFinishReason(reason) : "error",
raw: reason ?? "error"
};
if (event.response.usage) usage = convertXaiResponsesUsage(event.response.usage);
if (event.response.error != null) controller.enqueue({
type: "error",
error: createXaiResponsesStreamError({
message: event.response.error.message,
code: event.response.error.code,
eventType: event.type,
data: event
})
});
return;
}
if (event.type === "error") {
finishReason = {
unified: "error",
raw: void 0
};
controller.enqueue({
type: "error",
error: createXaiResponsesStreamError({
message: event.message,
code: event.code,
eventType: event.type,
data: event
})
});
return;
}
if (event.type === "response.custom_tool_call_input.delta" || event.type === "response.custom_tool_call_input.done") return;
if (event.type === "response.function_call_arguments.delta") {
const toolCall = ongoingToolCalls[event.output_index];
if (toolCall != null) controller.enqueue({
type: "tool-input-delta",
id: toolCall.toolCallId,
delta: event.delta
});
return;
}
if (event.type === "response.function_call_arguments.done") return;
if (event.type === "response.image_generation_call.in_progress" || event.type === "response.image_generation_call.generating" || event.type === "response.image_generation_call.completed") {
if (!seenToolCalls.has(event.item_id)) {
seenToolCalls.add(event.item_id);
const toolName = imageGenerationToolName ?? "image_generation";
controller.enqueue({
type: "tool-input-start",
id: event.item_id,
toolName
});
controller.enqueue({
type: "tool-input-delta",
id: event.item_id,
delta: "{}"
});
controller.enqueue({
type: "tool-input-end",
id: event.item_id
});
controller.enqueue({
type: "tool-call",
toolCallId: event.item_id,
toolName,
input: "{}",
providerExecuted: true
});
}
return;
}
if (event.type === "response.output_item.added" || event.type === "response.output_item.done") {
const part = event.item;
if (part.type === "reasoning") {
if (event.type === "response.output_item.done") {
const blockId = `reasoning-${part.id}`;
if (!(part.id in activeReasoning)) {
activeReasoning[part.id] = {};
controller.enqueue({
type: "reasoning-start",
id: blockId,
providerMetadata: { xai: { ...part.id && { itemId: part.id } } }
});
}
controller.enqueue({
type: "reasoning-end",
id: blockId,
providerMetadata: { xai: {
...part.encrypted_content && { reasoningEncryptedContent: part.encrypted_content },
...part.id && { itemId: part.id }
} }
});
delete activeReasoning[part.id];
}
return;
}
if (part.type === "file_search_call") {
const toolName = fileSearchToolName ?? "file_search";
if (!seenToolCalls.has(part.id)) {
seenToolCalls.add(part.id);
controller.enqueue({
type: "tool-input-start",
id: part.id,
toolName
});
controller.enqueue({
type: "tool-input-delta",
id: part.id,
delta: ""
});
controller.enqueue({
type: "tool-input-end",
id: part.id
});
controller.enqueue({
type: "tool-call",
toolCallId: part.id,
toolName,
input: "",
providerExecuted: true
});
}
if (event.type === "response.output_item.done") controller.enqueue({
type: "tool-result",
toolCallId: part.id,
toolName,
result: {
queries: part.queries ?? [],
results: part.results?.map((result) => ({
fileId: result.file_id,
filename: result.filename,
score: result.score,
text: result.text
})) ?? null
}
});
return;
}
if (part.type === "image_generation_call") {
const toolName = imageGenerationToolName ?? "image_generation";
if (!seenToolCalls.has(part.id)) {
seenToolCalls.add(part.id);
controller.enqueue({
type: "tool-input-start",
id: part.id,
toolName
});
controller.enqueue({
type: "tool-input-delta",
id: part.id,
delta: "{}"
});
controller.enqueue({
type: "tool-input-end",
id: part.id
});
controller.enqueue({
type: "tool-call",
toolCallId: part.id,
toolName,
input: "{}",
providerExecuted: true
});
}
if (event.type === "response.output_item.done") {
if (part.result != null) controller.enqueue({
type: "tool-result",
toolCallId: part.id,
toolName,
result: {
result: part.result,
...part.prompt != null && { prompt: part.prompt }
}
});
else controller.enqueue({
type: "tool-result",
toolCallId: part.id,
toolName,
isError: true,
result: `Image generation failed (status: ${part.status}).`
});
}
return;
}
if (part.type === "web_search_call" || part.type === "x_search_call" || part.type === "code_interpreter_call" || part.type === "code_execution_call" || part.type === "view_image_call" || part.type === "view_x_video_call" || part.type === "custom_tool_call" || part.type === "mcp_call") {
const webSearchSubTools = [
"web_search",
"web_search_with_snippets",
"browse_page"
];
const xSearchSubTools = [
"x_user_search",
"x_keyword_search",
"x_semantic_search",
"x_thread_fetch"
];
let toolName = part.name ?? "";
if (webSearchSubTools.includes(part.name ?? "") || part.type === "web_search_call") toolName = webSearchToolName ?? "web_search";
else if (xSearchSubTools.includes(part.name ?? "") || part.type === "x_search_call") toolName = xSearchToolName ?? "x_search";
else if (part.name === "code_execution" || part.type === "code_interpreter_call" || part.type === "code_execution_call") toolName = codeExecutionToolName ?? "code_execution";
else if (part.type === "mcp_call") toolName = mcpToolName ?? part.name ?? "mcp";
const toolInput = part.type === "custom_tool_call" ? part.input ?? "" : part.type === "mcp_call" ? part.arguments ?? "" : part.arguments ?? "";
if ((part.type === "custom_tool_call" ? event.type === "response.output_item.done" : !seenToolCalls.has(part.id)) && !seenToolCalls.has(part.id)) {
seenToolCalls.add(part.id);
controller.enqueue({
type: "tool-input-start",
id: part.id,
toolName
});
controller.enqueue({
type: "tool-input-delta",
id: part.id,
delta: toolInput
});
controller.enqueue({
type: "tool-input-end",
id: part.id
});
controller.enqueue({
type: "tool-call",
toolCallId: part.id,
toolName,
input: toolInput,
providerExecuted: true
});
}
if (event.type === "response.output_item.done") controller.enqueue({
type: "tool-result",
toolCallId: part.id,
toolName,
result: part.type === "web_search_call" ? mapWebSearchAction(part.action) : {}
});
return;
}
if (part.type === "message") {
const blockId = `text-${part.id}`;
const streamed = contentBlocks[blockId] != null;
for (const contentPart of part.content) {
if (contentPart.text && contentPart.text.length > 0) {
if (contentBlocks[blockId] == null) {
contentBlocks[blockId] = { type: "text" };
controller.enqueue({
type: "text-start",
id: blockId
});
controller.enqueue({
type: "text-delta",
id: blockId,
delta: contentPart.text
});
}
}
if (!streamed && contentPart.annotations) {
for (const annotation of contentPart.annotations) if (annotation.type === "url_citation" && "url" in annotation) controller.enqueue({
type: "source",
sourceType: "url",
id: self.config.generateId(),
url: annotation.url,
title: annotation.title ?? annotation.url
});
}
}
} else if (part.type === "function_call") {
if (event.type === "response.output_item.added") {
ongoingToolCalls[event.output_index] = {
toolName: part.name,
toolCallId: part.call_id
};
controller.enqueue({
type: "tool-input-start",
id: part.call_id,
toolName: part.name
});
} else if (event.type === "response.output_item.done") {
hasFunctionCall = true;
ongoingToolCalls[event.output_index] = void 0;
controller.enqueue({
type: "tool-input-end",
id: part.call_id
});
controller.enqueue({
type: "tool-call",
toolCallId: part.call_id,
toolName: part.name,
input: part.arguments
});
}
}
}
},
flush(controller) {
for (const [blockId, block] of Object.entries(contentBlocks)) if (block.type === "text") controller.enqueue({
type: "text-end",
id: blockId
});
controller.enqueue({
type: "finish",
finishReason,
usage: usage ?? {
inputTokens: {
total: 0,
noCache: 0,
cacheRead: 0,
cacheWrite: 0
},
outputTokens: {
total: 0,
text: 0,
reasoning: 0
}
},
...(costInUsdTicks != null || serviceTier != null || promptCacheKey != null || safetyIdentifier != null) && { providerMetadata: { xai: {
...costInUsdTicks != null && { costInUsdTicks },
...serviceTier != null && { serviceTier },
...promptCacheKey != null && { promptCacheKey },
...safetyIdentifier != null && { safetyIdentifier }
} } }
});
}
})),
request: { body },
response: { headers: responseHeaders }
};
}
};
function mapWebSearchAction(action) {
const parsed = webSearchWireActionSchema.safeParse(action);
if (!parsed.success) return {};
const a = parsed.data;
const sources = a.sources?.flatMap((s) => {
const source = webSearchWireSourceSchema.safeParse(s);
return source.success ? [source.data] : [];
});
const sourcesExtra = sources != null && sources.length > 0 ? { sources } : {};
switch (a.type) {
case "search": return {
action: {
type: "search",
...a.query != null && { query: a.query },
...a.queries != null && { queries: a.queries }
},
...sourcesExtra
};
case "open_page": return {
action: {
type: "openPage",
url: a.url
},
...sourcesExtra
};
case "find_in_page": return {
action: {
type: "findInPage",
url: a.url,
pattern: a.pattern
},
...sourcesExtra
};
}
}
const xaiBatchEndpoint = "/v1/responses";
const xaiBatchName = "ai-sdk-text-batch";
const xaiBatchResultsPageSize = 1e3;
const xaiBatchProviderOptionsSchema = lazySchema(() => zodSchema(z.object({
/**
* TTL in seconds for the uploaded batch input file, measured from
* upload time. xAI accepts integers between 3600 (1 hour) and
* 2592000 (30 days) inclusive. Without it the file has no expiry.
*/
inputFileExpiresAfter: z.number().int().min(3600).max(2592e3).optional() })));
function assertSupportedBatchRequests(requests) {
for (const request of requests) {
const requestType = request.type;
if (requestType !== "text" && requestType !== "image") throw new UnsupportedFunctionalityError({
functionality: `batch request type: ${requestType}`,
message: `The xAI Batch API does not support batch requests with type "${requestType}".`
});
}
}
const xaiBatchImageResponseSchema = () => z.object({
data: z.array(z.object({
url: z.string().nullish(),
b64_json: z.string().nullish(),
revised_prompt: z.string().nullish(),
respect_moderation: z.boolean().nullish()
})),
usage: z.object({ cost_in_usd_ticks: z.number().nullish() }).nullish()
});
const xaiBatchResponseZodSchema = () => z.object({
batch_id: z.string(),
name: z.string().nullish(),
create_time: z.string().nullish(),
expire_time: z.string().nullish(),
cancel_time: z.string().nullish(),
cancel_by_xai_message: z.string().nullish(),
state: z.object({
num_requests: z.number().nullish(),
num_pending: z.number().nullish(),
num_success: z.number().nullish(),
num_error: z.number().nullish(),
num_cancelled: z.number().nullish()
}).nullish()
});
const xaiBatchResponseSchema = lazySchema(() => zodSchema(xaiBatchResponseZodSchema()));
const xaiBatchErrorSchema = () => z.object({
code: z.union([z.string(), z.number()]).nullish(),
message: z.string().nullish()
});
const xaiBatchResultSchema = () => z.object({
batch_request_id: z.string(),
batch_result: z.object({
response: z.object({
chat_get_completion: z.unknown().nullish(),
image_generation: z.unknown().nullish()
}).nullish(),
error: xaiBatchErrorSchema().nullish()
}).nullish(),
error_message: z.string().nullish()
});
const xaiBatchTextResponseSchema = () => z.object({
id: z.string().nullish(),
created: z.number().nullish(),
model: z.string().nullish(),
choices: z.array(z.object({
message: z.object({
role: z.enum(["assistant", "tool"]),
content: z.string().nullish(),
reasoning_content: z.string().nullish(),
tool_calls: z.array(z.object({
id: z.string(),
type: z.literal("function"),
function: z.object({
name: z.string(),
arguments: z.string()
})
})).nullish()
}),
index: z.number(),
finish_reason: z.string().nullish()
})).nullish(),
usage: z.object({
prompt_tokens: z.number(),
completion_tokens: z.number(),
total_tokens: z.number(),
cost_in_usd_ticks: z.number().nullish(),
prompt_tokens_details: z.object({ cached_tokens: z.number().nullish() }).nullish(),
completion_tokens_details: z.object({ reasoning_tokens: z.number().nullish() }).nullish()
}).nullish(),
citations: z.array(z.string().url()).nullish(),
service_tier: z.string().nullish(),
code: z.string().nullish(),
error: z.string().nullish()
});
const xaiBatchResultsPageSchema = lazySchema(() => zodSchema(z.object({
results: z.array(xaiBatchResultSchema()),
pagination_token: z.string().nullish()
})));
const xaiBatchListResponseSchema = lazySchema(() => zodSchema(z.object({
batches: z.array(xaiBatchResponseZodSchema()),
pagination_token: z.string().nullish()
})));
var XaiBatch = class {
constructor(options) {
this.options = options;
this.specificationVersion = "v4";
this.supportedUrls = xaiResponsesSupportedUrls;
this.provider = options.provider;
}
async doStartBatch(options) {
assertSupportedBatchRequests(options.requests);
const fileParts = [];
const warnings = options.webhookUrl == null ? [] : [{ warning: {
type: "unsupported",
feature: "webhookUrl",
details: "The xAI Batch API does not support per-batch webhook URLs."
} }];
const batchOptions = await parseProviderOptions({
provider: "xai",
providerOptions: options.providerOptions,
schema: xaiBatchProviderOptionsSchema
});
for (const request of options.requests) {
const preparedRequest = await this.prepareRequest(request);
fileParts.push(JSON.stringify({
custom_id: request.id,
method: "POST",
url: preparedRequest.endpoint,
body: preparedRequest.body
}), "\n");
for (const warning of preparedRequest.warnings) warnings.push({
requestId: request.id,
warning
});
}
const filename = "batch.jsonl";
const file = new Blob(fileParts, { type: "application/jsonl" });
fileParts.length = 0;
const formData = new FormData();
if (batchOptions?.inputFileExpiresAfter != null) formData.append("expires_after", String(batchOptions.inputFileExpiresAfter));
formData.append("file", file, filename);
const { value: uploadedFile } = await postFormDataToApi({
url: this.getUrl("/files"),
headers: combineHeaders(await resolve(this.options.config.headers), options.headers),
formData,
failedResponseHandler: xaiFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler(xaiFilesResponseSchema),
abortSignal: options.abortSignal,
fetch: this.options.config.fetch
});
const { value: batch } = await postJsonToApi({
url: this.getUrl("/batches"),
headers: combineHeaders(await resolve(this.options.config.headers), options.headers),
body: {
name: xaiBatchName,
input_file_id: uploadedFile.id
},
failedResponseHandler: xaiFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler(xaiBatchResponseSchema),
abortSignal: options.abortSignal,
fetch: this.options.config.fetch
});
return {
batchId: batch.batch_id,
...convertXaiBatchStatus(batch),
providerMetadata: { xai: {
inputFileId: uploadedFile.id,
...uploadedFile.expires_at != null ? { inputFileExpiresAt: (/* @__PURE__ */ new Date(uploadedFile.expires_at * 1e3)).toISOString() } : {}
} },
warnings
};
}
async doGetBatchStatus(options) {
return convertXaiBatchStatus(await this.retrieveBatch(options));
}
async doCancelBatch(options) {
await postJsonToApi({
url: this.getUrl(`/batches/${encodeURIComponent(options.batchId)}:cancel`),
headers: combineHeaders(await resolve(this.options.config.headers), options.headers),
body: {},
failedResponseHandler: xaiFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler(xaiBatchResponseSchema),
abortSignal: options.abortSignal,
fetch: this.options.config.fetch
});
return {};
}
async doListBatches(options) {
const url = new URL(this.getUrl("/batches"));
if (options.limit != null) url.searchParams.set("limit", String(options.limit));
if (options.cursor != null) url.searchParams.set("pagination_token", options.cursor);
const { value: page } = await getFromApi({
url: url.toString(),
headers: combineHeaders(await resolve(this.options.config.headers), options.headers),
failedResponseHandler: xaiFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler(xaiBatchListResponseSchema),
abortSignal: options.abortSignal,
fetch: this.options.config.fetch,
validateUrl: false
});
return {
batches: page.batches.map((batch) => ({
batchId: batch.batch_id,
...convertXaiBatchStatus(batch)
})),
...page.pagination_token != null ? { nextCursor: page.pagination_token } : {}
};
}
async doGetBatchResults(options) {
if (convertXaiBatchStatus(await this.retrieveBatch(options)).status === "pending") throw new InvalidArgumentError({
argument: "batchId",
message: `xAI batch "${options.batchId}" is not complete.`
});
return convertAsyncIteratorToReadableStream(this.iterateBatchResults(options));
}
async retrieveBatch(options) {
const { value: batch } = await getFromApi({
url: this.getUrl(`/batches/${encodeURIComponent(options.batchId)}`),
headers: combineHeaders(await resolve(this.options.config.headers), options.headers),
failedResponseHandler: xaiFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler(xaiBatchResponseSchema),
abortSignal: options.abortSignal,
fetch: this.options.config.fetch,
validateUrl: false
});
return batch;
}
async *iterateBatchResults(options) {
let paginationToken;
do {
const query = new URLSearchParams({ limit: String(xaiBatchResultsPageSize) });
if (paginationToken != null) query.set("pagination_token", paginationToken);
const { value: page } = await getFromApi({
url: this.getUrl(`/batches/${encodeURIComponent(options.batchId)}/results?${query}`),
headers: combineHeaders(await resolve(this.options.config.headers), options.headers),
failedResponseHandler: xaiFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler(xaiBatchResultsPageSchema),
abortSignal: options.abortSignal,
fetch: this.options.config.fetch,
validateUrl: false
});
for (const result of page.results) yield await this.convertBatchResult(result, options.abortSignal);
paginationToken = page.pagination_token ?? void 0;
} while (paginationToken != null);
}
async convertBatchResult(result, abortSignal) {
const error = result.batch_result?.error;
if ((result.error_message?.length ?? 0) > 0 || error?.code != null && error.code !== 0 && error.code !== "0" || error?.code == null && (error?.message?.length ?? 0) > 0) {
const convertedError = convertXaiBatchError(result);
return {
type: "text",
id: result.batch_request_id,
status: isXaiCancellationError(error?.code) ? "cancelled" : "failed",
error: convertedError
};
}
const response = result.batch_result?.response;
if (response?.chat_get_completion != null) {
const validation = await safeValidateTypes({
value: response.chat_get_completion,
schema: zodSchema(xaiBatchTextResponseSchema())
});
if (!validation.success) return invalidXaiBatchResult(result.batch_request_id);
const conversion = convertXaiBatchTextResponse(validation.value);
return conversion.success ? {
type: "text",
id: result.batch_request_id,
status: "succeeded",
result: conversion.result
} : {
type: "text",
id: result.batch_request_id,
status: "failed",
error: conversion.error
};
}
if (response?.image_generation != null) {
const validation = await safeValidateTypes({
value: response.image_generation,
schema: zodSchema(xaiBatchImageResponseSchema())
});
if (!validation.success) return invalidXaiImageBatchResult(result.batch_request_id);
if (validation.value.data.some((image) => image.respect_moderation === false)) return {
type: "image",
id: result.batch_request_id,
status: "failed",
error: { message: "Image generation was blocked due to a content policy violation." }
};
const imageResult = await this.convertImageBatchResponse(validation.value, abortSignal);
return {
type: "image",
id: result.batch_request_id,
status: "succeeded",
result: imageResult
};
}
return invalidXaiBatchResult(result.batch_request_id);
}
async prepareRequest(request) {
if (request.type === "text") {
const { args: body, warnings } = await XaiResponsesLanguageModel.prepareRequest({
modelId: request.modelId,
options: request.options
});
return {
endpoint: xaiBatchEndpoint,
body,
warnings
};
}
const { prompt, n, size, aspectRatio, seed, files, mask, providerOptions } = request.options;
const warnings = [];
if (size != null) warnings.push({
type: "unsupported",
feature: "size",
details: "This model does not support the `size` option. Use `aspectRatio` instead."
});
if (seed != null) warnings.push({
type: "unsupported",
feature: "seed"
});
if (mask != null) warnings.push({
type: "unsupported",
feature: "mask"
});
const xaiOptions = await parseProviderOptions({
provider: "xai",
providerOptions,
schema: xaiImageModelOptions
});
const imageUrls = (files ?? []).map(convertImageModelFileToDataUri);
const body = {
model: request.modelId,
prompt,
n,
response_format: "b64_json"
};
if (aspectRatio != null) body.aspect_ratio = aspectRatio;
if (xaiOptions?.output_format != null) body.output_format = xaiOptions.output_format;
if (xaiOptions?.sync_mode != null) body.sync_mode = xaiOptions.sync_mode;
if (xaiOptions?.aspect_ratio != null && aspectRatio == null) body.aspect_ratio = xaiOptions.aspect_ratio;
if (xaiOptions?.resolution != null) body.resolution = xaiOptions.resolution;
if (xaiOptions?.quality != null) body.quality = xaiOptions.quality;
if (xaiOptions?.user != null) body.user = xaiOptions.user;
if (imageUrls.length === 1) body.image = {
url: imageUrls[0],
type: "image_url"
};
else if (imageUrls.length > 1) body.images = imageUrls.map((url) => ({
url,
type: "image_url"
}));
return {
endpoint: files?.length ? "/v1/images/edits" : "/v1/images/generations",
body,
warnings
};
}
async convertImageBatchResponse(response, abortSignal) {
return {
images: response.data.every((image) => image.b64_json != null) ? response.data.map((image) => image.b64_json) : await Promise.all(response.data.map(async (image) => {
if (image.b64_json != null) return convertBase64ToUint8Array(image.b64_json);
if (image.url == null) throw new InvalidArgumentError({
argument: "batchResult",
message: "xAI returned an image without data or a URL."
});
const { value } = await getFromApi({
url: image.url,
validateUrl: true,
trustedOrigin: this.options.config.baseURL,
abortSignal,
failedResponseHandler: xaiFailedResponseHandler,
successfulResponseHandler: createBinaryResponseHandler(),
fetch: this.options.config.fetch
});
return value;
})),
warnings: [],
response: {
timestamp: /* @__PURE__ */ new Date(),
modelId: "",
headers: void 0
},
providerMetadata: { xai: {
images: response.data.map((item) => item.revised_prompt != null ? { revisedPrompt: item.revised_prompt } : {}),
...response.usage?.cost_in_usd_ticks != null ? { costInUsdTicks: response.usage.cost_in_usd_ticks } : {}
} }
};
}
getUrl(path) {
return `${this.options.config.baseURL ?? "https://api.x.ai/v1"}${path}`;
}
};
function convertXaiBatchStatus(batch) {
const requestCounts = normalizeBatchRequestCounts({
total: batch.state?.num_requests,
pending: batch.state?.num_pending,
completed: batch.state?.num_success,
failed: batch.state?.num_error != null && batch.state?.num_cancelled != null ? batch.state.num_error + batch.state.num_cancelled : void 0
});
const isCancelled = batch.cancel_time != null || batch.cancel_by_xai_message != null;
const isExpired = isPastDate(batch.expire_time);
return {
status: isCancelled || isExpired ? "failed" : requestCounts != null && requestCounts.total > 0 && requestCounts.pending === 0 ? "completed" : "pending",
...requestCounts != null ? { requestCounts } : {},
...isCancelled ? { error: {
message: batch.cancel_by_xai_message ?? `xAI batch "${batch.batch_id}" was cancelled.`,
code: "batch_cancelled"
} } : isExpired ? { error: {
message: `xAI batch "${batch.batch_id}" expired.`,
code: "batch_expired"
} } : {},
...batch.create_time != null ? { createdAt: batch.create_time } : {},
...batch.expire_time != null ? { expiresAt: batch.expire_time } : {}
};
}
function isPastDate(value) {
if (value == null) return false;
const timestamp = Date.parse(value);
return !Number.isNaN(timestamp) && timestamp <= Date.now();
}
function convertXaiBatchError(result) {
const error = result.batch_result?.error;
return {
message: result.error_message || error?.message || "xAI batch request failed.",
...error?.code != null && error.code !== 0 && error.code !== "0" ? { code: String(error.code) } : {}
};
}
function isXaiCancellationError(code) {
const normalizedCode = String(code).toLowerCase();
return code === 1 || normalizedCode === "1" || normalizedCode === "cancelled" || normalizedCode === "batch_cancelled";
}
function invalidXaiBatchResult(id) {
return {
type: "text",
id,
status: "failed",
error: {
message: "xAI returned an invalid Responses batch result.",
code: "invalid_response"
}
};
}
function invalidXaiImageBatchResult(id) {
return {
type: "image",
id,
status: "failed",
error: {
message: "xAI returned an invalid image batch result.",
code: "invalid_response"
}
};
}
function convertXaiBatchTextResponse(response) {
if (response.error != null) return {
success: false,
error: {
message: response.error,
...response.code != null ? { code: response.code } : {}
}
};
const choices = response.choices;
if (choices == null || choices.length === 0) return {
success: false,
error: {
message: "xAI returned a batch response without any choices.",
code: "invalid_response"
}
};
const content = [];
const providerExecutedToolCallIds = new Set(choices.filter((choice) => choice.message.role === "tool").flatMap((choice) => (choice.message.tool_calls ?? []).map((toolCall) => toolCall.id)));
let lastAssistantChoice;
for (const choice of choices) {
if (choice.message.role === "tool") {
if (choice.message.content != null) for (const toolCall of choice.message.tool_calls ?? []) content.push({
type: "tool-result",
toolCallId: toolCall.id,
toolName: toolCall.function.name,
result: choice.message.content,
dynamic: true
});
continue;
}
lastAssistantChoice = choice;
if (choice.message.content) content.push({
type: "text",
text: choice.message.content
});
if (choice.message.reasoning_content) content.push({
type: "reasoning",
text: choice.message.reasoning_content
});
for (const toolCall of choice.message.tool_calls ?? []) content.push({
type: "tool-call",
toolCallId: toolCall.id,
toolName: toolCall.function.name,
input: toolCall.function.arguments,
...providerExecutedToolCallIds.has(toolCall.id) ? {
providerExecuted: true,
dynamic: true
} : {}
});
}
for (const url of response.citations ?? []) content.push({
type: "source",
sourceType: "url",
id: url,
url
});
return {
success: true,
result: {
content,
finishReason: {
unified: mapXaiFinishReason(lastAssistantChoice?.finish_reason),
raw: lastAssistantChoice?.finish_reason ?? void 0
},
usage: response.usage ? convertXaiBatchTextUsage(response.usage) : createNullLanguageModelUsage(),
response: getResponseMetadata(response),
warnings: [],
...(response.usage?.cost_in_usd_ticks != null || response.service_tier != null) && { providerMetadata: { xai: {
...response.usage?.cost_in_usd_ticks != null ? { costInUsdTicks: response.usage.cost_in_usd_ticks } : {},
...response.service_tier != null ? { serviceTier: response.service_tier } : {}
} } }
}
};
}
function convertXaiBatchTextUsage(usage) {
const cacheReadTokens = usage.prompt_tokens_details?.cached_tokens ?? 0;
const reasoningTokens = usage.completion_tokens_details?.reasoning_tokens ?? 0;
const promptTokensIncludesCached = cacheReadTokens <= usage.prompt_tokens;
return {
inputTokens: {
total: promptTokensIncludesCached ? usage.prompt_tokens : usage.prompt_tokens + cacheReadTokens,
noCache: promptTokensIncludesCached ? usage.prompt_tokens - cacheReadTokens : usage.prompt_tokens,
cacheRead: cacheReadTokens,
cacheWrite: void 0
},
outputTokens: {
total: usage.completion_tokens + reasoningTokens,
text: usage.completion_tokens,
reasoning: reasoningTokens
},
raw: usage
};
}
function parseXaiRealtimeServerEvent(raw) {
const event = raw;
const type = event.type;
switch (type) {
case "session.created": return {
type: "session-created",
sessionId: event.session?.id,
raw
};
case "session.updated": return {
type: "session-updated",
raw
};
case "conversation.created": return {
type: "custom",
rawType: type,
raw
};
case "input_audio_buffer.speech_started": return {
type: "speech-started",
itemId: event.item_id,
raw
};
case "input_audio_buffer.speech_stopped": return {
type: "speech-stopped",
itemId: event.item_id,
raw
};
case "input_audio_buffer.committed": return {
type: "audio-committed",
itemId: event.item_id,
previousItemId: event.previous_item_id,
raw
};
case "conversation.item.added": return {
type: "conversation-item-added",
itemId: event.item?.id ?? event.item_id,
item: event.item,
raw
};
case "conversation.item.input_audio_transcription.completed": return {
type: "input-transcription-completed",
itemId: event.item_id,
transcript: event.transcript ?? "",
raw
};
case "response.created": return {
type: "response-created",
responseId: event.response?.id ?? event.response_id,
raw
};
case "response.done": return {
type: "response-done",
responseId: event.response?.id ?? event.response_id,
status: event.response?.status ?? "completed",
raw
};
case "response.output_item.added": return {
type: "output-item-added",
responseId: event.response_id,
itemId: event.item?.id ?? event.item_id,
raw
};
case "response.output_item.done": return {
type: "output-item-done",
responseId: event.response_id,
itemId: event.item?.id ?? event.item_id,
raw
};
case "response.content_part.added": return {
type: "content-part-added",
responseId: event.response_id,
itemId: event.item_id,
raw
};
case "response.content_part.done": return {
type: "content-part-done",
responseId: event.response_id,
itemId: event.item_id,
raw
};
case "response.output_audio.delta": return {
type: "audio-delta",
responseId: event.response_id,
itemId: event.item_id,
delta: event.delta,
raw
};
case "response.output_audio.done": return {
type: "audio-done",
responseId: event.response_id,
itemId: event.item_id,
raw
};
case "response.output_audio_transcript.delta": return {
type: "audio-transcript-delta",
responseId: event.response_id,
itemId: event.item_id,
delta: event.delta,
raw
};
case "response.output_audio_transcript.done": return {
type: "audio-transcript-done",
responseId: event.response_id,
itemId: event.item_id,
transcript: event.transcript,
raw
};
case "response.text.delta": return {
type: "text-delta",
responseId: event.response_id,
itemId: event.item_id,
delta: event.delta,
raw
};
case "response.text.done": return {
type: "text-done",
responseId: event.response_id,
itemId: event.item_id,
text: event.text,
raw
};
case "response.function_call_arguments.delta": return {
type: "function-call-arguments-delta",
responseId: event.response_id,
itemId: event.item_id,
callId: event.call_id,
delta: event.delta,
raw
};
case "response.function_call_arguments.done": return {
type: "function-call-arguments-done",
responseId: event.response_id,
itemId: event.item_id,
callId: event.call_id,
name: event.name,
arguments: event.arguments,
raw
};
case "mcp_list_tools.in_progress":
case "mcp_list_tools.completed":
case "mcp_list_tools.failed":
case "response.mcp_call_arguments.delta":
case "response.mcp_call_arguments.done":
case "response.mcp_call.in_progress":
case "response.mcp_call.completed":
case "response.mcp_call.failed": return {
type: "custom",
rawType: type,
raw
};
case "error": return {
type: "error",
message: event.error?.message ?? event.message ?? "Unknown error",
code: event.error?.code ?? event.code,
raw
};
default: return {
type: "custom",
rawType: type,
raw
};
}
}
function serializeXaiRealtimeClientEvent(event) {
switch (event.type) {
case "session-update": return {
type: "session.update",
session: buildXaiSessionConfig(event.config)
};
case "input-audio-append": return {
type: "input_audio_buffer.append",
audio: event.audio
};
case "input-audio-commit": return { type: "input_audio_buffer.commit" };
case "input-audio-clear": return { type: "input_audio_buffer.clear" };
case "conversation-item-create": {
const item = event.item;
switch (item.type) {
case "text-message": return {
type: "conversation.item.create",
item: {
type: "message",
role: item.role,
content: [{
type: "input_text",
text: item.text
}]
}
};
case "audio-message": return {
type: "conversation.item.create",
item: {
type: "message",
role: item.role,
content: [{
type: "input_audio",
audio: item.audio
}]
}
};
case "function-call-output": return {
type: "conversation.item.create",
item: {
type: "function_call_output",
call_id: item.callId,
output: item.output
}
};
}
break;
}
case "conversation-item-truncate": return;
case "response-create": return {
type: "response.create",
...event.options != null ? { response: {
...event.options.modalities != null ? { modalities: event.options.modalities } : {},
...event.options.instructions != null ? { instructions: event.options.instructions } : {}
} } : {}
};
case "response-cancel": return { type: "response.cancel" };
}
}
function buildXaiSessionConfig(config) {
const session = {};
if (config.instructions != null) session.instructions = config.instructions;
if (config.voice != null) session.voice = config.voice;
const audio = {};
if (config.inputAudioFormat != null) audio.input = { format: {
type: config.inputAudioFormat.type,
...config.inputAudioFormat.rate != null ? { rate: config.inputAudioFormat.rate } : {}
} };
if (config.outputAudioFormat != null) audio.output = { format: {
type: config.outputAudioFormat.type,
...config.outputAudioFormat.rate != null ? { rate: config.outputAudioFormat.rate } : {}
} };
if (Object.keys(audio).length > 0) session.audio = audio;
if (config.turnDetection != null) {
if (config.turnDetection.type === "disabled") session.turn_detection = null;
else {
const td = { type: "server_vad" };
if (config.turnDetection.threshold != null) td.threshold = config.turnDetection.threshold;
if (config.turnDetection.silenceDurationMs != null) td.silence_duration_ms = config.turnDetection.silenceDurationMs;
if (config.turnDetection.prefixPaddingMs != null) td.prefix_padding_ms = config.turnDetection.prefixPaddingMs;
session.turn_detection = td;
}
}
if (config.tools != null && config.tools.length > 0) session.tools = config.tools.map((tool) => ({
type: tool.type,
name: tool.name,
description: tool.description,
parameters: tool.parameters
}));
if (config.providerOptions != null) {
const xaiOptions = config.providerOptions;
if (Array.isArray(xaiOptions.tools)) session.tools = [...session.tools ?? [], ...xaiOptions.tools];
for (const [key, value] of Object.entries(xaiOptions)) if (key !== "tools") session[key] = value;
}
return session;
}
var XaiRealtimeModel = class {
constructor(modelId, config) {
this.specificationVersion = "v4";
this.modelId = modelId;
this.provider = config.provider;
this.config = config;
}
async doCreateClientSecret(options) {
const fetchFn = this.config.fetch ?? fetch;
const url = `${this.config.baseURL}/realtime/client_secrets`;
const body = {};
if (options.expiresAfterSeconds != null) body.expires_after = { seconds: options.expiresAfterSeconds };
const response = await fetchFn(url, {
method: "POST",
headers: {
...await resolve(this.config.headers),
"Content-Type": "application/json"
},
body: JSON.stringify(body)
});
if (!response.ok) {
const text = await response.text();
throw new Error(`xAI realtime client secret request failed: ${response.status} ${text}`);
}
const data = await response.json();
return {
token: data.value,
url: `wss://${new URL(this.config.baseURL).host}/v1/realtime?model=${encodeURIComponent(this.modelId)}`,
expiresAt: data.expires_at
};
}
getWebSocketConfig(options) {
return {
url: options.url,
protocols: [`xai-client-secret.${options.token}`]
};
}
parseServerEvent(raw) {
return parseXaiRealtimeServerEvent(raw);
}
serializeClientEvent(event) {
return serializeXaiRealtimeClientEvent(event);
}
buildSessionConfig(config) {
return buildXaiSessionConfig(config);
}
};
const codeExecutionOutputSchema = lazySchema(() => zodSchema(z.object({
output: z.string().describe("the output of the code execution"),
error: z.string().optional().describe("any error that occurred")
})));
const codeExecutionToolFactory = createProviderExecutedToolFactory({
id: "xai.code_execution",
inputSchema: z.object({}).describe("no input parameters"),
outputSchema: codeExecutionOutputSchema
});
const codeExecution = (args = {}) => codeExecutionToolFactory(args);
const viewImageOutputSchema = lazySchema(() => zodSchema(z.object({
description: z.string().describe("description of the image"),
objects: z.array(z.string()).optional().describe("objects detected in the image")
})));
const viewImageToolFactory = createProviderExecutedToolFactory({
id: "xai.view_image",
inputSchema: z.object({}).describe("no input parameters"),
outputSchema: viewImageOutputSchema
});
const viewImage = (args = {}) => viewImageToolFactory(args);
const viewXVideoOutputSchema = lazySchema(() => zodSchema(z.object({
transcript: z.string().optional().describe("transcript of the video"),
description: z.string().describe("description of the video content"),
duration: z.number().optional().describe("duration in seconds")
})));
const viewXVideoToolFactory = createProviderExecutedToolFactory({
id: "xai.view_x_video",
inputSchema: z.object({}).describe("no input parameters"),
outputSchema: viewXVideoOutputSchema
});
const viewXVideo = (args = {}) => viewXVideoToolFactory(args);
const xaiTools = {
codeExecution,
fileSearch,
imageGeneration,
mcpServer,
viewImage,
viewXVideo,
webSearch,
xSearch
};
const VERSION = "5.0.35";
const xaiFilesOptionsSchema = lazySchema(() => zodSchema(z.looseObject({
teamId: z.string().optional(),
filePath: z.string().optional(),
/**
* TTL in seconds measured from upload time; xAI accepts integers
* between 3600 (1 hour) and 2592000 (30 days) inclusive.
* Omit to keep the file until it is deleted.
*/
expiresAfter: z.number().int().min(3600).max(2592e3).optional()
})));
var XaiFiles = class {
get provider() {
return this.config.provider;
}
constructor(config) {
this.config = config;
this.specificationVersion = "v4";
}
getFileId(file) {
const fileId = file.xai;
if (fileId == null || fileId.trim() === "") throw new InvalidArgumentError({
argument: "file",
message: "file reference is missing an 'xai' file id."
});
return fileId;
}
async getHeaders(headers) {
return combineHeaders(await resolve(this.config.headers), headers);
}
async uploadFile({ data, mediaType, filename, abortSignal, headers, providerOptions }) {
let xaiOptions;
try {
xaiOptions = await parseProviderOptions({
provider: "xai",
providerOptions,
schema: xaiFilesOptionsSchema
});
} catch (error) {
if (data.type === "stream") await data.stream.cancel(error).catch(() => {});
throw error;
}
const requestHeaders = await this.getHeaders(headers);
const url = `${this.config.baseURL}/files`;
let response;
if (data.type === "stream") {
const parts = [];
if (xaiOptions?.expiresAfter != null) parts.push({
type: "field",
name: "expires_after",
value: String(xaiOptions.expiresAfter)
});
if (xaiOptions?.teamId != null) parts.push({
type: "field",
name: "team_id",
value: xaiOptions.teamId
});
parts.push({
type: "file",
name: "file",
filename,
mediaType,
content: data.stream
});
({value: response} = await postMultipartStreamToApi({
url,
headers: requestHeaders,
parts,
failedResponseHandler: xaiFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler(xaiFilesResponseSchema),
abortSignal,
fetch: this.config.fetch
}));
} else {
const fileBytes = convertInlineFileDataToUint8Array(data);
const blob = new Blob([fileBytes], { type: mediaType });
const formData = new FormData();
if (xaiOptions?.expiresAfter != null) formData.append("expires_after", String(xaiOptions.expiresAfter));
if (xaiOptions?.teamId != null) formData.append("team_id", xaiOptions.teamId);
if (filename != null) formData.append("file", blob, filename);
else formData.append("file", blob);
({value: response} = await postFormDataToApi({
url,
headers: requestHeaders,
formData,
failedResponseHandler: xaiFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler(xaiFilesResponseSchema),
abortSignal,
fetch: this.config.fetch
}));
}
return {
warnings: [],
providerReference: { xai: response.id },
...response.filename ?? filename ? { filename: response.filename ?? filename } : {},
...mediaType != null ? { mediaType } : {},
...response.bytes != null ? { byteSize: response.bytes } : {},
...response.created_at != null ? { createdAt: /* @__PURE__ */ new Date(response.created_at * 1e3) } : {},
...response.expires_at != null ? { expiresAt: /* @__PURE__ */ new Date(response.expires_at * 1e3) } : {},
providerMetadata: { xai: this.toFileMetadata(response) }
};
}
async getFileMetadata({ file, abortSignal, headers }) {
const fileId = this.getFileId(file);
const { value: response } = await getFromApi({
url: `${this.config.baseURL}/files/${encodePathSegment(fileId)}`,
headers: await this.getHeaders(headers),
failedResponseHandler: xaiFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler(xaiFilesResponseSchema),
abortSignal,
fetch: this.config.fetch,
validateUrl: false
});
return {
warnings: [],
providerReference: { xai: response.id },
...response.filename != null ? { filename: response.filename } : {},
...response.bytes != null ? { byteSize: response.bytes } : {},
...response.created_at != null ? { createdAt: /* @__PURE__ */ new Date(response.created_at * 1e3) } : {},
...response.expires_at != null ? { expiresAt: /* @__PURE__ */ new Date(response.expires_at * 1e3) } : {},
providerMetadata: { xai: this.toFileMetadata(response) }
};
}
async downloadFile({ file, abortSignal, headers }) {
const fileId = this.getFileId(file);
const { value: content, responseHeaders } = await getFromApi({
url: `${this.config.baseURL}/files/${encodePathSegment(fileId)}/content`,
headers: await this.getHeaders(headers),
failedResponseHandler: xaiFailedResponseHandler,
successfulResponseHandler: createBinaryStreamResponseHandler(),
abortSignal,
fetch: this.config.fetch,
validateUrl: false
});
const mediaType = responseHeaders?.["content-type"]?.split(";")[0].trim();
return {
warnings: [],
content,
...mediaType ? { mediaType } : {}
};
}
async deleteFile({ file, abortSignal, headers }) {
const fileId = this.getFileId(file);
const { value: response } = await deleteFromApi({
url: `${this.config.baseURL}/files/${encodePathSegment(fileId)}`,
headers: await this.getHeaders(headers),
failedResponseHandler: xaiFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler(xaiFileDeleteResponseSchema),
abortSignal,
fetch: this.config.fetch
});
return {
warnings: [],
providerReference: { xai: response.id },
deleted: response.deleted
};
}
toFileMetadata(response) {
return {
...response.filename != null ? { filename: response.filename } : {},
...response.purpose != null ? { purpose: response.purpose } : {},
...response.bytes != null ? { bytes: response.bytes } : {},
...response.created_at != null ? { createdAt: response.created_at } : {},
...response.status != null ? { status: response.status } : {},
...response.expires_at != null ? { expiresAt: response.expires_at } : {}
};
}
};
const nonEmptyStringSchema = () => z.string().min(1);
const resolutionSchema = () => z.enum([
"480p",
"720p",
"1080p"
]);
const modeSchema = () => z.enum([
"edit-video",
"extend-video",
"reference-to-video"
]);
const keyframeSchema = () => z.object({
imageUrl: nonEmptyStringSchema(),
timestampSeconds: z.number().positive()
});
const storageOptionsSchema = () => z.object({
filename: nonEmptyStringSchema(),
expiresAfter: z.number().int().positive().max(2592e3).optional(),
publicUrl: z.union([z.boolean(), z.object({ expiresAfter: z.number().int().min(3600).max(2592e3).optional() })]).optional()
});
const baseFields = () => ({
pollIntervalMs: z.number().positive().nullish(),
pollTimeoutMs: z.number().positive().nullish(),
resolution: resolutionSchema().nullish()
});
const runtimeSchema = () => z.looseObject({
mode: modeSchema().optional(),
videoUrl: nonEmptyStringSchema().optional(),
referenceImageUrls: z.array(nonEmptyStringSchema()).min(1).max(7).optional(),
referenceVoiceIds: z.array(nonEmptyStringSchema()).max(3).optional(),
keyframes: z.array(keyframeSchema()).max(4).optional(),
storageOptions: storageOptionsSchema().optional(),
user: z.string().optional(),
...baseFields()
});
const xaiVideoModelOptionsSchema = lazySchema(() => zodSchema(runtimeSchema()));
const RESOLUTION_MAP = {
"1920x1080": "1080p",
"1280x720": "720p",
"854x480": "480p",
"640x480": "480p"
};
function getFirstFrameImage(options) {
return options.frameImages?.find((frame) => frame.frameType === "first_frame")?.image;
}
function getLastFrameImage(options) {
return options.frameImages?.find((frame) => frame.frameType === "last_frame")?.image;
}
function resolveStartImage(options) {
return getFirstFrameImage(options) ?? options.image;
}
const isVideoFile = (file) => file.mediaType != null && getTopLevelMediaType$2(file.mediaType) === "video";
const isImageReference = (file) => file.mediaType == null || getTopLevelMediaType$2(file.mediaType) === "image";
const isAudioReference = (file) => file.mediaType != null && getTopLevelMediaType$2(file.mediaType) === "audio";
function fileToXaiUrl(file) {
if (file.type === "url") return file.url;
const base64Data = typeof file.data === "string" ? file.data : convertUint8ArrayToBase64(file.data);
return `data:${file.mediaType};base64,${base64Data}`;
}
function resolveReferences(options, xaiOptions, warnings) {
if (options.inputReferences != null && options.inputReferences.length > 0) {
const imageFiles = [];
for (const reference of options.inputReferences) {
if (isAudioReference(reference)) continue;
if (!isImageReference(reference)) {
warnings.push({
type: "unsupported",
feature: "inputReferences",
details: "xAI reference-to-video does not accept video references. The video reference was ignored. Use providerOptions.xai.mode \"extend-video\" to continue from a video."
});
continue;
}
imageFiles.push(reference);
}
return imageFiles.length > 0 ? imageFiles.map((reference) => ({ url: fileToXaiUrl(reference) })) : void 0;
}
if (xaiOptions?.referenceImageUrls != null && xaiOptions.referenceImageUrls.length > 0) return xaiOptions.referenceImageUrls.map((url) => ({ url }));
}
function resolveReferenceAudios(options) {
const audioReferences = options.inputReferences?.filter(isAudioReference);
return audioReferences != null && audioReferences.length > 0 ? audioReferences.map((reference) => ({ url: fileToXaiUrl(reference) })) : void 0;
}
function hasImageInputReference(options) {
return options.inputReferences?.some(isImageReference) ?? false;
}
function hasAudioInputReference(options) {
return options.inputReferences?.some(isAudioReference) ?? false;
}
function resolveVideoMode(options, xaiOptions) {
if (xaiOptions?.mode != null) return xaiOptions.mode;
if (xaiOptions?.videoUrl != null) return "edit-video";
const hasLegacyReferenceUrls = xaiOptions?.referenceImageUrls != null && xaiOptions.referenceImageUrls.length > 0;
if (hasImageInputReference(options) || hasAudioInputReference(options) || hasLegacyReferenceUrls) return "reference-to-video";
}
var XaiVideoModel = class {
get provider() {
return this.config.provider;
}
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
this.maxVideosPerCall = 1;
}
async buildRequestBody(options) {
const warnings = [];
const xaiOptions = await parseProviderOptions({
provider: "xai",
providerOptions: options.providerOptions,
schema: xaiVideoModelOptionsSchema
});
const effectiveMode = resolveVideoMode(options, xaiOptions);
const isEdit = effectiveMode === "edit-video";
const isExtension = effectiveMode === "extend-video";
const hasReferenceImages = effectiveMode === "reference-to-video";
if (options.fps != null) warnings.push({
type: "unsupported",
feature: "fps",
details: "xAI video models do not support custom FPS."
});
if (options.seed != null) warnings.push({
type: "unsupported",
feature: "seed",
details: "xAI video models do not support seed."
});
if (options.n != null && options.n > 1) warnings.push({
type: "unsupported",
feature: "n",
details: "xAI video models do not support generating multiple videos per call. Only 1 video will be generated."
});
if (isEdit && options.duration != null) warnings.push({
type: "unsupported",
feature: "duration",
details: "xAI video editing does not support custom duration."
});
if (isEdit && options.aspectRatio != null) warnings.push({
type: "unsupported",
feature: "aspectRatio",
details: "xAI video editing does not support custom aspect ratio."
});
if (isEdit && (xaiOptions?.resolution != null || options.resolution != null)) warnings.push({
type: "unsupported",
feature: "resolution",
details: "xAI video editing does not support custom resolution."
});
if (isExtension && options.aspectRatio != null) warnings.push({
type: "unsupported",
feature: "aspectRatio",
details: "xAI video extension does not support custom aspect ratio."
});
if (isExtension && (xaiOptions?.resolution != null || options.resolution != null)) warnings.push({
type: "unsupported",
feature: "resolution",
details: "xAI video extension does not support custom resolution."
});
const body = {
model: this.modelId,
prompt: options.prompt
};
const allowDuration = !isEdit;
const allowAspectRatio = !isEdit && !isExtension;
const allowResolution = !isEdit && !isExtension;
if (allowDuration && options.duration != null) body.duration = options.duration;
if (allowAspectRatio && options.aspectRatio != null) body.aspect_ratio = options.aspectRatio;
if (allowResolution && xaiOptions?.resolution != null) body.resolution = xaiOptions.resolution;
else if (allowResolution && options.resolution != null) {
const mapped = RESOLUTION_MAP[options.resolution];
if (mapped != null) body.resolution = mapped;
else warnings.push({
type: "unsupported",
feature: "resolution",
details: `Unrecognized resolution "${options.resolution}". Use providerOptions.xai.resolution with "480p", "720p", or "1080p" instead.`
});
}
if (options.generateAudio != null && !isEdit && !isExtension) body.generate_audio = options.generateAudio;
else if (options.generateAudio != null) warnings.push({
type: "unsupported",
feature: "generateAudio",
details: `xAI ${isEdit ? "video editing" : "video extension"} does not support generateAudio.`
});
if (xaiOptions?.storageOptions != null) {
const { filename, expiresAfter, publicUrl } = xaiOptions.storageOptions;
body.storage_options = {
filename,
...expiresAfter != null ? { expires_after: expiresAfter } : {},
...publicUrl != null ? { public_url: typeof publicUrl === "boolean" ? publicUrl : { ...publicUrl.expiresAfter != null ? { expires_after: publicUrl.expiresAfter } : {} } } : {}
};
}
if (xaiOptions?.keyframes != null && xaiOptions.keyframes.length > 0) {
if (this.modelId !== "grok-imagine-video-1.5" || isEdit || isExtension) warnings.push({
type: "unsupported",
feature: "keyframes",
details: this.modelId !== "grok-imagine-video-1.5" ? "xAI only supports keyframes with \"grok-imagine-video-1.5\"." : `xAI ${isEdit ? "video editing" : "video extension"} does not support keyframes.`
});
else body.keyframes = xaiOptions.keyframes.map((keyframe) => ({
image: { url: keyframe.imageUrl },
timestamp_s: keyframe.timestampSeconds
}));
}
if (isEdit) body.video = { url: xaiOptions.videoUrl };
if (isExtension) body.video = { url: xaiOptions.videoUrl };
const startImage = resolveStartImage(options);
if (startImage != null) {
if (isVideoFile(startImage)) {
const fromFrameImages = getFirstFrameImage(options) != null;
warnings.push({
type: "unsupported",
feature: fromFrameImages ? "frameImages" : "image",
details: "xAI does not accept a video as a start/frame image. The video was ignored. Use providerOptions.xai.mode \"extend-video\" to continue from a video instead."
});
} else body.image = { url: fileToXaiUrl(startImage) };
}
const lastFrameImage = getLastFrameImage(options);
if (lastFrameImage != null) {
if (this.modelId !== "grok-imagine-video-1.5" || isEdit || isExtension || isVideoFile(lastFrameImage)) warnings.push({
type: "unsupported",
feature: "frameImages",
details: this.modelId !== "grok-imagine-video-1.5" ? "xAI only supports last_frame with \"grok-imagine-video-1.5\". The last frame was ignored." : "xAI only accepts an image last_frame for video generation. The last frame was ignored."
});
else body.last_frame = { url: fileToXaiUrl(lastFrameImage) };
}
if (hasReferenceImages) {
const referenceImages = resolveReferences(options, xaiOptions, warnings);
const referenceAudios = resolveReferenceAudios(options);
if (referenceImages != null) body.reference_images = referenceImages;
else if (referenceAudios == null) warnings.push({
type: "unsupported",
feature: "referenceImages",
details: "xAI reference-to-video requires at least one image reference. The video will be generated without reference images."
});
const referenceVoices = (xaiOptions?.referenceVoiceIds)?.map((voiceId) => ({ voice_id: voiceId }));
const referenceAudioInputs = [...referenceAudios ?? [], ...referenceVoices ?? []];
if (referenceAudioInputs.length > 0) {
if (referenceAudioInputs.length > 3) warnings.push({
type: "unsupported",
feature: "inputReferences",
details: "xAI reference-to-video supports at most 3 audio references. Only the first 3 were used."
});
body.reference_audios = referenceAudioInputs.slice(0, 3);
}
if (body.resolution === "1080p") {
warnings.push({
type: "unsupported",
feature: "resolution",
details: "xAI reference-to-video is limited to 720p. The request was downgraded from 1080p to 720p."
});
body.resolution = "720p";
}
}
if (body.resolution === "1080p" && this.modelId === "grok-imagine-video") warnings.push({
type: "unsupported",
feature: "resolution",
details: "xAI model \"grok-imagine-video\" does not support 1080p. Use \"grok-imagine-video-1.5\" for 1080p, or a lower resolution. The request was sent with 1080p."
});
if (options.inputReferences != null && options.inputReferences.length > 0 && !hasReferenceImages) warnings.push({
type: "unsupported",
feature: "inputReferences",
details: hasImageInputReference(options) || hasAudioInputReference(options) ? "xAI only supports inputReferences for reference-to-video generation. The references were ignored." : "xAI reference-to-video requires at least one image or audio reference. The references were ignored."
});
if (xaiOptions?.referenceVoiceIds != null && xaiOptions.referenceVoiceIds.length > 0 && !hasReferenceImages) warnings.push({
type: "unsupported",
feature: "referenceVoiceIds",
details: "xAI only supports reference voices for reference-to-video generation. The reference voices were ignored."
});
if (!isExtension && xaiOptions?.user !== void 0) body.user = xaiOptions.user;
if (xaiOptions != null) {
for (const [key, value] of Object.entries(xaiOptions)) if (![
"mode",
"pollIntervalMs",
"pollTimeoutMs",
"resolution",
"videoUrl",
"referenceImageUrls",
"referenceVoiceIds",
"keyframes",
"storageOptions",
"user"
].includes(key)) body[key] = value;
}
return {
body,
warnings,
xaiOptions,
isEdit,
isExtension,
hasReferenceImages,
effectiveMode
};
}
async doStart(options) {
const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
const { body, warnings, isEdit, isExtension } = await this.buildRequestBody(options);
const baseURL = this.config.baseURL ?? "https://api.x.ai/v1";
let endpoint;
if (isEdit) endpoint = `${baseURL}/videos/edits`;
else if (isExtension) endpoint = `${baseURL}/videos/extensions`;
else endpoint = `${baseURL}/videos/generations`;
const { value: createResponse, responseHeaders } = await postJsonToApi({
url: endpoint,
headers: combineHeaders(await resolve(this.config.headers), options.headers),
body,
failedResponseHandler: xaiFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler(xaiCreateVideoResponseSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
const requestId = createResponse.request_id;
if (!requestId) throw new AISDKError({
name: "XAI_VIDEO_GENERATION_ERROR",
message: `No request_id returned from xAI API.`
});
return {
operation: { requestId },
warnings,
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders
}
};
}
async doStatus(options) {
const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
const { requestId } = options.operation;
const baseURL = this.config.baseURL ?? "https://api.x.ai/v1";
const { value: statusResponse, responseHeaders } = await getFromApi({
url: `${baseURL}/videos/${encodePathSegment(requestId)}`,
validateUrl: false,
headers: combineHeaders(await resolve(this.config.headers), options.headers),
successfulResponseHandler: xaiVideoStatusResponseHandler,
failedResponseHandler: xaiFailedResponseHandler,
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
if (statusResponse.status === "expired") return {
status: "error",
error: "Video generation request expired.",
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders
}
};
if (statusResponse.status === "failed") {
const errorDetails = statusResponse.error?.message ?? statusResponse.error?.code;
return {
status: "error",
error: errorDetails != null ? `Video generation failed: ${errorDetails}` : "Video generation failed.",
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders
}
};
}
if (statusResponse.status === "done" || statusResponse.status == null && statusResponse.video?.url) {
const video = statusResponse.video;
if (video?.respect_moderation === false) return {
status: "error",
error: "Video generation was blocked due to a content policy violation.",
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders
}
};
const videoUrl = video?.url ?? video?.file_output?.public_url ?? void 0;
if (!videoUrl) return {
status: "error",
error: "Video generation completed but no video URL was returned.",
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders
}
};
return {
status: "completed",
videos: [{
type: "url",
url: videoUrl,
mediaType: "video/mp4"
}],
warnings: [],
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders
},
providerMetadata: { xai: {
requestId,
videoUrl,
...video?.duration != null ? { duration: video.duration } : {},
...statusResponse.usage?.cost_in_usd_ticks != null ? { costInUsdTicks: statusResponse.usage.cost_in_usd_ticks } : {},
...statusResponse.progress != null ? { progress: statusResponse.progress } : {},
...video?.file_output != null ? { fileOutput: {
fileId: video.file_output.file_id,
filename: video.file_output.filename,
...video.file_output.expires_at != null ? { expiresAt: video.file_output.expires_at } : {},
...video.file_output.public_url != null ? { publicUrl: video.file_output.public_url } : {},
...video.file_output.public_url_error != null ? { publicUrlError: video.file_output.public_url_error } : {},
...video.file_output.public_url_expires_at != null ? { publicUrlExpiresAt: video.file_output.public_url_expires_at } : {}
} } : {},
...video?.storage_error != null ? { storageError: video.storage_error } : {}
} }
};
}
return {
status: "pending",
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders
}
};
}
};
const xaiCreateVideoResponseSchema = lazySchema(() => zodSchema(z.object({ request_id: z.string().nullish() })));
const xaiVideoStatusResponseSchema = lazySchema(() => zodSchema(z.object({
status: z.string().nullish(),
video: z.object({
url: z.string().nullish(),
duration: z.number().nullish(),
respect_moderation: z.boolean().nullish(),
file_output: z.object({
file_id: z.string(),
filename: z.string(),
expires_at: z.number().nullish(),
public_url: z.string().nullish(),
public_url_error: z.string().nullish(),
public_url_expires_at: z.number().nullish()
}).nullish(),
storage_error: z.string().nullish()
}).nullish(),
model: z.string().nullish(),
usage: z.object({ cost_in_usd_ticks: z.number().nullish() }).nullish(),
progress: z.number().nullish(),
error: z.object({
code: z.string().nullish(),
message: z.string().nullish()
}).nullish()
})));
const xaiVideoStatusJsonResponseHandler = createJsonResponseHandler(xaiVideoStatusResponseSchema);
const MAX_PENDING_BODY_BYTES = 1048576;
const textDecoder = new TextDecoder();
async function readPendingBody({ response, url, requestBodyValues }) {
if (response.body == null) return "";
const reader = response.body.getReader();
const chunks = [];
let totalBytes = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
totalBytes += value.length;
if (totalBytes > MAX_PENDING_BODY_BYTES) throw new APICallError({
message: `xAI video status response exceeded ${MAX_PENDING_BODY_BYTES} bytes`,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders: extractResponseHeaders(response)
});
chunks.push(value);
}
} finally {
reader.releaseLock();
}
const merged = new Uint8Array(totalBytes);
let offset = 0;
for (const chunk of chunks) {
merged.set(chunk, offset);
offset += chunk.length;
}
return textDecoder.decode(merged);
}
const xaiVideoStatusResponseHandler = async (options) => {
if (options.response.status === 202) {
const responseHeaders = extractResponseHeaders(options.response);
const text = await readPendingBody(options);
if (text.trim().length === 0) return {
responseHeaders,
value: { status: "pending" }
};
const parsed = await safeParseJSON({
text,
schema: xaiVideoStatusResponseSchema
});
return {
responseHeaders,
value: parsed.success ? parsed.value : { status: "pending" }
};
}
return xaiVideoStatusJsonResponseHandler(options);
};
const xaiSpeechModelOptionsSchema = lazySchema(() => zodSchema(z.object({
/**
* Sample rate of the generated audio in Hz.
*/
sampleRate: z.union([
z.literal(8e3),
z.literal(16e3),
z.literal(22050),
z.literal(24e3),
z.literal(44100),
z.literal(48e3)
]).nullish(),
/**
* MP3 bit rate in bits per second. Only applies when outputFormat is mp3.
*/
bitRate: z.union([
z.literal(32e3),
z.literal(64e3),
z.literal(96e3),
z.literal(128e3),
z.literal(192e3)
]).nullish(),
/**
* Reduce time to first audio chunk, trading some quality for latency.
*/
optimizeStreamingLatency: z.union([
z.literal(0),
z.literal(1),
z.literal(2)
]).nullish(),
/**
* Normalize written-form text into spoken-form text before synthesis.
*/
textNormalization: z.boolean().nullish(),
/**
* Return character-level timing metadata alongside the audio. When
* enabled, the response carries per-character start/end times and the
* total duration, exposed via `providerMetadata.xai`.
*/
withTimestamps: z.boolean().nullish(),
/**
* Map of phrases to spoken substitutions applied before synthesis.
* Values may be respellings (`{ 'Acme Mobile': 'Acme Mobull' }`) or IPA
* phonetics (`{ nginx: '/ˈɛndʒɪn ˈɛks/' }`).
*/
replace: z.record(z.string(), z.string()).nullish()
})));
const speechDefaults = getXaiSpeechModelEntry().requestConfig.speech;
var XaiSpeechModel = class XaiSpeechModel {
static [WORKFLOW_SERIALIZE](model) {
return serializeModelOptions({
modelId: model.modelId,
config: model.config
});
}
static [WORKFLOW_DESERIALIZE](options) {
return new XaiSpeechModel(options.modelId, options.config);
}
get provider() {
return this.config.provider;
}
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
}
async getArgs({ text, voice = speechDefaults.voice, outputFormat = speechDefaults.outputFormat, instructions, speed, language = speechDefaults.language, providerOptions }) {
const warnings = [];
const xaiOptions = await parseProviderOptions({
provider: "xai",
providerOptions,
schema: xaiSpeechModelOptionsSchema
});
const { speech } = getXaiSpeechModelEntry().capabilities;
let codec = speechDefaults.outputFormat;
if (speech.outputFormats.includes(outputFormat)) codec = outputFormat;
else warnings.push({
type: "unsupported",
feature: "outputFormat",
details: `Unsupported output format: ${outputFormat}. Using mp3 instead.`
});
if (speech.instructions === false && instructions != null) warnings.push({
type: "unsupported",
feature: "instructions",
details: "xAI speech models do not support the `instructions` option. Use xAI speech tags in `text` to control delivery."
});
const output_format = { codec };
if (xaiOptions?.sampleRate != null) output_format.sample_rate = xaiOptions.sampleRate;
if (xaiOptions?.bitRate != null) {
if (codec === "mp3") output_format.bit_rate = xaiOptions.bitRate;
else warnings.push({
type: "unsupported",
feature: "providerOptions",
details: "xAI `bitRate` is supported only for mp3 output. It was ignored."
});
}
return {
requestBody: {
text,
voice_id: voice,
language,
output_format,
speed,
optimize_streaming_latency: xaiOptions?.optimizeStreamingLatency,
text_normalization: xaiOptions?.textNormalization,
with_timestamps: xaiOptions?.withTimestamps,
replace: xaiOptions?.replace
},
warnings,
withTimestamps: xaiOptions?.withTimestamps === true
};
}
async doGenerate(options) {
const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
const { requestBody, warnings, withTimestamps } = await this.getArgs(options);
const { value, responseHeaders, rawValue } = await postJsonToApi({
url: `${this.config.baseURL}/tts`,
headers: combineHeaders(this.config.headers ? await resolve(this.config.headers) : void 0, options.headers),
body: requestBody,
failedResponseHandler: xaiFailedResponseHandler,
successfulResponseHandler: withTimestamps ? createJsonResponseHandler(xaiSpeechTimestampsResponseSchema) : createBinaryResponseHandler(),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
let audio;
let envelope;
if (value instanceof Uint8Array) audio = value;
else {
envelope = value;
audio = envelope.audio != null ? convertBase64ToUint8Array(envelope.audio) : /* @__PURE__ */ new Uint8Array(0);
}
const traceId = responseHeaders?.["x-trace-id"];
return {
audio,
warnings,
request: { body: JSON.stringify(requestBody) },
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders,
body: rawValue
},
providerMetadata: { xai: {
...traceId != null ? { traceId } : {},
...envelope?.duration != null ? { duration: envelope.duration } : {},
...envelope?.content_type != null ? { contentType: envelope.content_type } : {},
...envelope?.audio_timestamps != null ? { audioTimestamps: {
graphChars: envelope.audio_timestamps.graph_chars,
graphTimes: envelope.audio_timestamps.graph_times
} } : {}
} }
};
}
};
const xaiSpeechTimestampsResponseSchema = lazySchema(() => zodSchema(z.object({
audio: z.string().nullish(),
content_type: z.string().nullish(),
duration: z.number().nullish(),
audio_timestamps: z.object({
graph_chars: z.array(z.string()),
graph_times: z.array(z.tuple([z.number(), z.number()]))
}).nullish()
})));
const xaiTranscriptionModelOptionsSchema = lazySchema(() => zodSchema(z.object({
/**
* Input audio encoding for raw, headerless audio: `pcm`, `mulaw`, or
* `alaw`. Container formats such as Ogg/Opus are auto-detected, so do
* not set this for them. `opus` is for streaming only, with one raw Opus
* packet per chunk.
*/
audioFormat: z.enum([
"pcm",
"mulaw",
"alaw",
"opus"
]).nullish(),
/**
* Sample rate of the input audio in Hz.
*/
sampleRate: z.union([
z.literal(8e3),
z.literal(16e3),
z.literal(22050),
z.literal(24e3),
z.literal(44100),
z.literal(48e3)
]).nullish(),
/**
* Language code used for inverse text normalization.
*/
language: z.string().nullish(),
/**
* Enable inverse text normalization. Requires `language`.
*/
format: z.boolean().nullish(),
/**
* Enable per-channel transcription for multichannel audio.
*/
multichannel: z.boolean().nullish(),
/**
* Number of interleaved audio channels.
*/
channels: z.number().int().min(2).max(8).nullish(),
/**
* Enable speaker diarization.
*/
diarize: z.boolean().nullish(),
/**
* Terms to bias transcription toward.
*/
keyterm: z.union([z.string(), z.array(z.string())]).nullish(),
/**
* Include filler words such as "uh" and "um" in the transcript.
*/
fillerWords: z.boolean().nullish(),
/**
* Voice activity detection threshold between 0 and 1. Defaults to 0.5
* for `transcribe` and 0.08 for streaming. 0 disables the filter.
*/
vadThreshold: z.number().min(0).max(1).optional(),
/**
* Options for streaming speech-to-text over WebSocket.
*/
streaming: z.object({
/**
* Emit interim transcript results while speech is being processed.
*/
interimResults: z.boolean().optional(),
/**
* Silence duration in milliseconds before an utterance-final event.
*/
endpointing: z.number().int().min(0).max(5e3).optional(),
/**
* End-of-turn detection threshold. When set, enables Smart Turn.
*/
smartTurn: z.number().min(0).max(1).optional(),
/**
* Maximum silence duration in milliseconds before forcing speech_final.
*/
smartTurnTimeout: z.number().int().min(1).max(5e3).optional()
}).optional()
})));
var XaiTranscriptionModel = class XaiTranscriptionModel {
static [WORKFLOW_SERIALIZE](model) {
return serializeModelOptions({
modelId: model.modelId,
config: model.config
});
}
static [WORKFLOW_DESERIALIZE](options) {
return new XaiTranscriptionModel(options.modelId, options.config);
}
get provider() {
return this.config.provider;
}
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
}
async getArgs({ audio, mediaType, providerOptions }) {
const warnings = [];
const xaiOptions = await parseProviderOptions({
provider: "xai",
providerOptions,
schema: xaiTranscriptionModelOptionsSchema
});
const formData = new FormData();
appendXaiSttParams(formData, {
...getXaiSttParams(this.modelId, xaiOptions),
audio_format: xaiOptions?.audioFormat,
format: xaiOptions?.format
});
const blob = audio instanceof Uint8Array ? new Blob([audio]) : new Blob([convertBase64ToUint8Array(audio)]);
const fileExtension = mediaTypeToExtension(mediaType);
formData.append("file", new File([blob], "audio", { type: mediaType }), `audio.${fileExtension}`);
return {
formData,
warnings
};
}
async doGenerate(options) {
const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
const { formData, warnings } = await this.getArgs(options);
const { value: response, responseHeaders, rawValue: rawResponse } = await postFormDataToApi({
url: `${this.config.baseURL ?? "https://api.x.ai/v1"}/stt`,
headers: combineHeaders(await resolve(this.config.headers), options.headers),
formData,
failedResponseHandler: xaiFailedResponseHandler,
successfulResponseHandler: createJsonResponseHandler(xaiTranscriptionResponseSchema),
abortSignal: options.abortSignal,
fetch: this.config.fetch
});
return {
text: response.text,
segments: response.words?.map((word) => ({
text: word.text,
startSecond: word.start,
endSecond: word.end
})) ?? [],
language: response.language || void 0,
durationInSeconds: response.duration ?? void 0,
warnings,
response: {
timestamp: currentDate,
modelId: this.modelId,
headers: responseHeaders,
body: rawResponse
},
...response.words?.some((word) => word.speaker != null) && { providerMetadata: { xai: { words: response.words } } }
};
}
async doStream(options) {
const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
const warnings = [];
const xaiOptions = await parseProviderOptions({
provider: "xai",
providerOptions: options.providerOptions,
schema: xaiTranscriptionModelOptionsSchema
});
if (xaiOptions?.multichannel === true && xaiOptions.channels == null) throw new InvalidArgumentError({
argument: "providerOptions",
message: "providerOptions.xai.channels is required when providerOptions.xai.multichannel is true"
});
if (xaiOptions?.format != null) warnings.push({
type: "unsupported",
feature: "providerOptions.xai.format",
details: "xAI streaming transcription does not support format."
});
if (xaiOptions?.audioFormat == null && !inputAudioFormatEncodings.has(options.inputAudioFormat.type)) warnings.push({
type: "other",
message: `Unrecognized inputAudioFormat.type "${options.inputAudioFormat.type}"; falling back to raw PCM encoding. Use ${[...inputAudioFormatEncodings.keys()].join(", ")}, or set providerOptions.xai.audioFormat explicitly.`
});
const url = buildXaiStreamingTranscriptionUrl({
baseURL: this.config.baseURL ?? "https://api.x.ai/v1",
modelId: this.modelId,
inputAudioFormat: options.inputAudioFormat,
providerOptions: xaiOptions
});
const headers = combineHeaders(await resolve(this.config.headers), options.headers);
return {
request: { body: url.toString() },
response: {
timestamp: currentDate,
modelId: this.modelId
},
stream: createXaiStreamingTranscriptionStream({
webSocket: this.config.webSocket,
url,
headers,
warnings,
language: xaiOptions?.language ?? void 0,
expectedDoneCount: xaiOptions?.multichannel === true ? xaiOptions.channels : 1,
audio: options.audio,
abortSignal: options.abortSignal,
includeRawChunks: options.includeRawChunks
})
};
}
};
function createXaiStreamingTranscriptionStream({ webSocket, url, headers, warnings, language, expectedDoneCount, audio, abortSignal, includeRawChunks }) {
let finished = false;
let cleanup = () => {};
return new ReadableStream({
start: (controller) => {
const doneTexts = /* @__PURE__ */ new Map();
const finalizedTexts = /* @__PURE__ */ new Map();
const pendingTexts = /* @__PURE__ */ new Map();
let doneDuration;
let audioReader;
let connection;
cleanup = (closeCode) => {
if (audioReader != null) audioReader.cancel().catch(() => {});
else audio.cancel().catch(() => {});
connection?.close(closeCode);
};
const finishWithError = (error) => {
if (finished) return;
finished = true;
cleanup();
controller.error(error);
};
const maybeFinish = () => {
if (finished || doneTexts.size < expectedDoneCount) return;
finished = true;
const text = [...doneTexts.entries()].sort(([a], [b]) => a - b).map(([, value]) => value).join("\n");
controller.enqueue({
type: "finish",
text,
segments: [],
language,
durationInSeconds: doneDuration
});
controller.close();
cleanup(1e3);
};
const sendAudio = async (socket) => {
audioReader = audio.getReader();
try {
while (true) {
const { done, value } = await audioReader.read();
if (done || finished) break;
socket.send(value instanceof Uint8Array ? value : convertBase64ToUint8Array(value));
await waitForWebSocketBufferDrain(socket);
}
} finally {
audioReader.releaseLock();
audioReader = void 0;
}
if (!finished) socket.send(JSON.stringify({ type: "audio.done" }));
};
connection = connectToWebSocket({
url,
headers,
webSocket,
abortSignal,
onAbort: finishWithError,
onProcessingError: finishWithError,
onMessageText: async (text) => {
const parsed = await safeParseJSON({ text });
if (!parsed.success) return;
const raw = parsed.value;
if (includeRawChunks) controller.enqueue({
type: "raw",
rawValue: raw
});
switch (raw.type) {
case "transcript.created": {
controller.enqueue({
type: "stream-start",
warnings
});
const socket = connection?.socket;
if (socket == null) {
finishWithError(/* @__PURE__ */ new Error("WebSocket is not connected."));
break;
}
sendAudio(socket).catch(finishWithError);
break;
}
case "transcript.partial": {
const id = channelId(raw.channel_index);
const channelIndex = raw.channel_index ?? 0;
if (raw.is_final && raw.speech_final) {
const timing = timingFromXaiEvent(raw);
if (raw.text) finalizedTexts.set(channelIndex, [...finalizedTexts.get(channelIndex) ?? [], raw.text]);
pendingTexts.delete(channelIndex);
controller.enqueue({
type: "transcript-final",
id,
text: raw.text ?? "",
...timing,
channelIndex: raw.channel_index
});
} else {
pendingTexts.set(channelIndex, raw.text ?? "");
controller.enqueue({
type: "transcript-partial",
id,
text: raw.text ?? "",
startSecond: raw.start,
durationInSeconds: raw.duration,
channelIndex: raw.channel_index
});
}
break;
}
case "transcript.done": {
const channelIndex = raw.channel_index ?? 0;
const accumulated = [...finalizedTexts.get(channelIndex) ?? [], ...pendingTexts.get(channelIndex) ? [pendingTexts.get(channelIndex)] : []].join(" ");
doneTexts.set(channelIndex, raw.text || accumulated);
doneDuration = raw.duration ?? doneDuration;
maybeFinish();
break;
}
case "error": finishWithError(new Error(raw.message ?? "xAI STT error"));
}
},
onSocketError: () => {
finishWithError(/* @__PURE__ */ new Error("xAI streaming transcription error." + (webSocket == null ? " Note: the native WebSocket implementation in browsers, Node.js, Deno, and Bun cannot send the Authorization header required by xAI. Pass a header-capable WebSocket implementation (e.g. the 'ws' package) via createXai({ webSocket })." : "")));
},
onClose: () => {
if (finished) return;
finished = true;
cleanup();
controller.close();
}
});
},
cancel: () => {
if (finished) return;
finished = true;
cleanup();
}
});
}
function buildXaiStreamingTranscriptionUrl({ baseURL, modelId, inputAudioFormat, providerOptions }) {
const url = toWebSocketUrl(`${baseURL}/stt`);
const params = getXaiSttParams(modelId, providerOptions);
appendXaiSttParams(url.searchParams, {
...params,
sample_rate: params.sample_rate ?? inputAudioFormat.rate,
encoding: providerOptions?.audioFormat ?? inputAudioFormatEncodings.get(inputAudioFormat.type) ?? "pcm",
interim_results: providerOptions?.streaming?.interimResults,
endpointing: providerOptions?.streaming?.endpointing,
smart_turn: providerOptions?.streaming?.smartTurn,
smart_turn_timeout: providerOptions?.streaming?.smartTurnTimeout
});
return url;
}
function getXaiSttParams(modelId, options) {
return {
model: getXaiTranscriptionModelEntry(modelId).requestConfig.transcription.model,
sample_rate: options?.sampleRate,
language: options?.language,
multichannel: options?.multichannel,
channels: options?.channels,
diarize: options?.diarize,
filler_words: options?.fillerWords,
vad_threshold: options?.vadThreshold,
keyterm: options?.keyterm
};
}
function appendXaiSttParams(target, params) {
for (const [key, value] of Object.entries(params)) for (const item of Array.isArray(value) ? value : [value]) if (item != null) target.append(key, String(item));
}
const inputAudioFormatEncodings = /* @__PURE__ */ new Map([
["audio/pcm", "pcm"],
["audio/pcmu", "mulaw"],
["audio/pcma", "alaw"],
["audio/opus", "opus"]
]);
function channelId(channelIndex) {
return channelIndex == null ? void 0 : `channel-${channelIndex}`;
}
function timingFromXaiEvent(event) {
return {
...event.start != null ? { startSecond: event.start } : {},
...event.start != null && event.duration != null ? { endSecond: event.start + event.duration } : {}
};
}
const xaiTranscriptionResponseSchema = lazySchema(() => zodSchema(z.object({
text: z.string(),
language: z.string().nullish(),
duration: z.number().nullish(),
words: z.array(z.object({
text: z.string(),
start: z.number(),
end: z.number(),
speaker: z.number().nullish()
})).nullish()
})));
function createXai(options = {}) {
const baseURL = withoutTrailingSlash(options.baseURL ?? "https://api.x.ai/v1");
const getHeaders = () => resolveWith(options.apiKey, (apiKey) => withUserAgentSuffix({
Authorization: `Bearer ${loadApiKey({
apiKey,
environmentVariableName: "XAI_API_KEY",
description: "xAI API key"
})}`,
...options.headers
}, `ai-sdk-xai/${VERSION}`));
const createResponsesLanguageModel = (modelId) => {
return new XaiResponsesLanguageModel(modelId, {
provider: "xai.responses",
baseURL,
headers: getHeaders,
generateId,
fetch: options.fetch
});
};
const createImageModel = (modelId) => {
return new XaiImageModel(modelId, {
provider: "xai.image",
baseURL,
headers: getHeaders,
fetch: options.fetch
});
};
const createVideoModel = (modelId) => {
return new XaiVideoModel(modelId, {
provider: "xai.video",
baseURL,
headers: getHeaders,
fetch: options.fetch
});
};
const createRealtimeModel = (modelId) => {
return new XaiRealtimeModel(modelId, {
provider: "xai.realtime",
baseURL: baseURL ?? "https://api.x.ai/v1",
headers: getHeaders,
fetch: options.fetch
});
};
const createSpeechModel = () => {
return new XaiSpeechModel("", {
provider: "xai.speech",
baseURL,
headers: getHeaders,
fetch: options.fetch
});
};
const createTranscriptionModel = (modelId = "") => {
return new XaiTranscriptionModel(modelId, {
provider: "xai.transcription",
baseURL,
headers: getHeaders,
fetch: options.fetch,
webSocket: options.webSocket
});
};
const experimentalRealtimeFactory = Object.assign((modelId) => createRealtimeModel(modelId), { getToken: async (tokenOptions) => {
const secret = await createRealtimeModel(tokenOptions.model).doCreateClientSecret({
sessionConfig: tokenOptions.sessionConfig,
expiresAfterSeconds: tokenOptions.expiresAfterSeconds
});
return {
token: secret.token,
url: secret.url,
expiresAt: secret.expiresAt
};
} });
const createFiles = () => new XaiFiles({
provider: "xai.files",
baseURL,
headers: getHeaders,
fetch: options.fetch
});
const createBatch = () => new XaiBatch({
provider: "xai.batch",
config: {
provider: "xai.responses",
baseURL,
headers: getHeaders,
generateId,
fetch: options.fetch
}
});
const provider = (modelId) => createResponsesLanguageModel(modelId);
provider.specificationVersion = "v4";
provider.languageModel = createResponsesLanguageModel;
provider.responses = createResponsesLanguageModel;
provider.embeddingModel = (modelId) => {
throw new NoSuchModelError({
modelId,
modelType: "embeddingModel"
});
};
provider.textEmbeddingModel = provider.embeddingModel;
provider.imageModel = createImageModel;
provider.image = createImageModel;
provider.videoModel = createVideoModel;
provider.video = createVideoModel;
provider.experimental_realtime = experimentalRealtimeFactory;
provider.speechModel = createSpeechModel;
provider.speech = createSpeechModel;
provider.transcriptionModel = createTranscriptionModel;
provider.transcription = createTranscriptionModel;
provider.files = createFiles;
provider.experimental_batch = createBatch;
provider.tools = xaiTools;
return provider;
}
createXai();
// src/llm/model/gateway-resolver.ts
function parseModelRouterId(routerId, gatewayPrefix) {
if (gatewayPrefix && !routerId.startsWith(`${gatewayPrefix}/`)) throw new Error(`Expected ${gatewayPrefix}/ in model router ID ${routerId}`);
const idParts = routerId.split("/");
if (gatewayPrefix === "azure-openai") {
const modelId = idParts.slice(1).join("/");
if (!modelId) throw new Error(`Expected format azure-openai/deployment-name, but got ${routerId}`);
return {
providerId: "azure-openai",
modelId
};
}
if (gatewayPrefix && idParts.length === 2 && idParts[0] === gatewayPrefix) {
const modelId = idParts[1];
if (!modelId) throw new Error(`Expected format ${gatewayPrefix}/model, but got ${routerId}`);
return {
providerId: gatewayPrefix,
modelId
};
}
if (gatewayPrefix && idParts.length < 3) throw new Error(`Expected atleast 3 id parts ${gatewayPrefix}/provider/model, but only saw ${idParts.length} in ${routerId}`);
const providerId = idParts.at(gatewayPrefix ? 1 : 0);
const modelId = idParts.slice(gatewayPrefix ? 2 : 1).join(`/`);
if (!routerId.includes(`/`) || !providerId || !modelId) throw new Error(`Attempted to parse provider/model from ${routerId} but this ID doesn't appear to contain a provider`);
return {
providerId,
modelId
};
}
// src/llm/model/gateways/url-template.ts
function interpolateUrlTemplate(url, envVars) {
return url.replace(/\$\{([^}]+)\}/g, (_match, envVarName) => {
const key = envVarName.trim();
const value = envVars?.[key] ?? process.env[key];
if (value === void 0 || value === null) throw new Error(`Missing environment variable ${envVarName} required to build provider URL`);
return value;
});
}
// src/llm/model/gateways/models-dev.ts
var models_dev_exports = /* @__PURE__ */ __exportAll({ ModelsDevGateway: () => ModelsDevGateway });
function stringItems(value) {
return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
}
function isOptionalNumber(value) {
return value === void 0 || typeof value === "number";
}
function toReasoningOption(raw) {
if (!raw || typeof raw !== "object" || !("type" in raw)) return void 0;
if (raw.type === "toggle") return { type: "toggle" };
if (raw.type === "effort") {
const values = "values" in raw ? stringItems(raw.values) : [];
return values.length > 0 ? {
type: "effort",
values
} : void 0;
}
if (raw.type === "budget_tokens") {
const min = "min" in raw ? raw.min : void 0;
const max = "max" in raw ? raw.max : void 0;
if (!isOptionalNumber(min) || !isOptionalNumber(max)) return void 0;
return {
type: "budget_tokens",
...min !== void 0 ? { min } : {},
...max !== void 0 ? { max } : {}
};
}
}
function parseReasoningOptions(raw) {
if (!Array.isArray(raw)) return [];
return raw.map(toReasoningOption).filter((option) => option !== void 0);
}
function selectApiKeyEnvVar({ envVars, providerId }) {
const fallbackEnvVar = `${providerId.toUpperCase().replace(/-/g, "_")}_API_KEY`;
if (!envVars?.length) return fallbackEnvVar;
for (const suffix of [
"_API_TOKEN",
"_API_KEY",
"_TOKEN",
"_KEY",
"_PAT"
]) {
const preferredEnvVar = envVars.find((envVar) => envVar.endsWith(suffix));
if (preferredEnvVar) return preferredEnvVar;
}
return envVars[0] || fallbackEnvVar;
}
function resolveApiKeyFromEnv(apiKeyEnvVar) {
const envVars = Array.isArray(apiKeyEnvVar) ? apiKeyEnvVar : [apiKeyEnvVar];
for (const envVar of envVars) {
const apiKey = process.env[envVar];
if (apiKey) return apiKey;
}
}
const PROVIDER_OVERRIDES = {
google: { apiKeyEnvVar: ["GOOGLE_API_KEY", "GOOGLE_GENERATIVE_AI_API_KEY"] },
mistral: { url: "https://api.mistral.ai/v1" },
groq: { url: "https://api.groq.com/openai/v1" },
moonshotai: {
url: "https://api.moonshot.ai/anthropic/v1",
npm: "@ai-sdk/anthropic"
},
"moonshotai-cn": {
url: "https://api.moonshot.cn/anthropic/v1",
npm: "@ai-sdk/anthropic"
}
};
var ModelsDevGateway = class extends MastraModelGateway {
id = "models.dev";
name = "models.dev";
providerConfigs = {};
attachmentCapabilities = {};
temperatureCapabilities = {};
structuredOutputCapabilities = {};
reasoningCapabilities = {};
constructor(providerConfigs) {
super();
if (providerConfigs) this.providerConfigs = providerConfigs;
}
async fetchProviders() {
const response = await fetch("https://models.dev/api.json");
if (!response.ok) throw new Error(`Failed to fetch from models.dev: ${response.statusText}`);
const data = await response.json();
this.attachmentCapabilities = {};
this.temperatureCapabilities = {};
this.structuredOutputCapabilities = {};
this.reasoningCapabilities = {};
const providerConfigs = {};
for (const [providerId, providerInfo] of Object.entries(data)) {
if (EXCLUDED_PROVIDERS.includes(providerId)) continue;
if (!providerInfo || typeof providerInfo !== "object" || !providerInfo.models) continue;
const normalizedId = providerId;
const isOpenAICompatible = providerInfo.npm === "@ai-sdk/openai-compatible" || providerInfo.npm === "@ai-sdk/gateway" || normalizedId in PROVIDER_OVERRIDES;
const hasInstalledPackage = PROVIDERS_WITH_INSTALLED_PACKAGES.includes(providerId);
const hasApiAndEnv = providerInfo.api && providerInfo.env && providerInfo.env.length > 0;
if (isOpenAICompatible || hasInstalledPackage || hasApiAndEnv) {
const allModels = Object.entries(providerInfo.models);
const modelIds = allModels.map(([modelId]) => modelId).sort();
const modelReleaseDates = Object.fromEntries(allModels.flatMap(([modelId, info]) => typeof info?.release_date === "string" && info.release_date ? [[modelId, info.release_date]] : []));
const deprecatedModelIds = allModels.filter(([, modelInfo]) => modelInfo?.status === "deprecated").map(([modelId]) => modelId).sort();
const attachmentModels = allModels.filter(([, modelInfo]) => modelInfo?.attachment === true).map(([modelId]) => modelId).sort();
const temperatureModels = allModels.filter(([, modelInfo]) => modelInfo?.temperature === true).map(([modelId]) => modelId).sort();
const structuredOutputModels = allModels.filter(([, modelInfo]) => modelInfo?.structured_output === true).map(([modelId]) => modelId).sort();
const reasoningByModel = {};
for (const [modelId, modelInfo] of allModels) {
const reasoningOptions = parseReasoningOptions(modelInfo?.reasoning_options);
if (reasoningOptions.length > 0) reasoningByModel[modelId] = reasoningOptions;
}
const modelOverrides = {};
for (const [modelId, modelInfo] of allModels) {
const ov = modelInfo?.provider;
if (ov && (ov.api || ov.shape || ov.npm)) modelOverrides[modelId] = {
api: ov.api,
shape: ov.shape,
npm: ov.npm
};
}
const url = PROVIDER_OVERRIDES[normalizedId]?.url || providerInfo.api;
if (!hasInstalledPackage && !url) continue;
providerConfigs[normalizedId] = {
url,
apiKeyEnvVar: PROVIDER_OVERRIDES[normalizedId]?.apiKeyEnvVar || selectApiKeyEnvVar({
envVars: providerInfo.env,
providerId: normalizedId
}),
apiKeyHeader: !hasInstalledPackage ? PROVIDER_OVERRIDES[normalizedId]?.apiKeyHeader || "Authorization" : void 0,
name: providerInfo.name || providerId.charAt(0).toUpperCase() + providerId.slice(1),
models: modelIds,
...Object.keys(modelReleaseDates).length > 0 ? { modelReleaseDates } : {},
docUrl: providerInfo.doc,
gateway: `models.dev`,
npm: PROVIDER_OVERRIDES[normalizedId]?.npm || (providerInfo.npm && providerInfo.npm !== "@ai-sdk/openai-compatible" && providerInfo.npm !== "@ai-sdk/gateway" ? providerInfo.npm : void 0),
modelOverrides: Object.keys(modelOverrides).length > 0 ? modelOverrides : void 0,
deprecatedModels: deprecatedModelIds.length > 0 ? deprecatedModelIds : void 0
};
if (attachmentModels.length > 0) this.attachmentCapabilities[normalizedId] = attachmentModels;
if (temperatureModels.length > 0) this.temperatureCapabilities[normalizedId] = temperatureModels;
if (structuredOutputModels.length > 0) this.structuredOutputCapabilities[normalizedId] = structuredOutputModels;
if (Object.keys(reasoningByModel).length > 0) this.reasoningCapabilities[normalizedId] = reasoningByModel;
}
}
this.providerConfigs = providerConfigs;
return providerConfigs;
}
/**
* Return attachment capabilities collected during the last `fetchProviders()` call.
* Maps provider ID → list of model IDs that support attachments.
*/
getAttachmentCapabilities() {
return this.attachmentCapabilities;
}
getTemperatureCapabilities() {
return this.temperatureCapabilities;
}
getStructuredOutputCapabilities() {
return this.structuredOutputCapabilities;
}
getReasoningCapabilities() {
return this.reasoningCapabilities;
}
buildUrl(routerId, envVars) {
const { providerId, modelId } = parseModelRouterId(routerId);
const config = this.providerConfigs[providerId];
const template = config?.modelOverrides?.[modelId]?.api ?? config?.url;
const baseUrlEnvVar = `${providerId.toUpperCase().replace(/-/g, "_")}_BASE_URL`;
const customBaseUrl = envVars?.[baseUrlEnvVar] || process.env[baseUrlEnvVar];
if (customBaseUrl) return customBaseUrl;
if (!template) return;
return interpolateUrlTemplate(template, envVars);
}
getApiKey(modelId) {
const [provider, model] = modelId.split("/");
if (!provider || !model) throw new Error(`Could not identify provider from model id ${modelId}`);
const config = this.providerConfigs[provider];
if (!config) throw new Error(`Could not find config for provider ${provider} with model id ${modelId}`);
const apiKey = resolveApiKeyFromEnv(config.apiKeyEnvVar);
if (!apiKey) {
const envVarDisplay = Array.isArray(config.apiKeyEnvVar) ? config.apiKeyEnvVar.join(" or ") : config.apiKeyEnvVar;
throw new Error(`Could not find API key process.env.${envVarDisplay} for model id ${modelId}`);
}
return Promise.resolve(apiKey);
}
async resolveLanguageModel({ modelId, providerId, apiKey, headers }) {
const baseURL = this.buildUrl(`${providerId}/${modelId}`);
const mastraHeaders = {
"User-Agent": MASTRA_USER_AGENT,
...headers
};
const override = this.providerConfigs[providerId]?.modelOverrides?.[modelId];
if (override?.shape === "responses") return createOpenAI({
apiKey,
baseURL,
headers: mastraHeaders
}).responses(modelId);
switch (providerId) {
case "openai": return createOpenAI({
apiKey,
baseURL,
headers: mastraHeaders
}).responses(modelId);
case "gemini":
case "google": return createGoogleGenerativeAI({
apiKey,
baseURL,
headers: mastraHeaders
}).chat(modelId);
case "anthropic": return createAnthropic({
apiKey,
baseURL,
headers: mastraHeaders
})(modelId);
case "mistral": return createMistral({
apiKey,
baseURL,
headers: mastraHeaders
})(modelId);
case "groq": return createGroq({
apiKey,
baseURL,
headers: mastraHeaders
})(modelId);
case "openrouter": return createOpenRouter({
apiKey,
baseURL,
headers: mastraHeaders
})(modelId);
case "xai": return createXai({
apiKey,
baseURL,
headers: mastraHeaders
}).responses(modelId);
case "deepseek": return createDeepSeek({
apiKey,
baseURL,
headers: mastraHeaders
})(modelId);
case "perplexity": return createPerplexity({
apiKey,
baseURL,
headers: Object.keys(mastraHeaders).some((key) => key.toLowerCase() === "x-pplx-integration") ? mastraHeaders : {
"X-Pplx-Integration": MASTRA_USER_AGENT,
...mastraHeaders
}
})(modelId);
case "cerebras": return createCerebras({
apiKey,
baseURL,
headers: mastraHeaders
})(modelId);
case "togetherai": return createTogetherAI({
apiKey,
baseURL,
headers: mastraHeaders
})(modelId);
case "deepinfra": return createDeepInfra({
apiKey,
baseURL,
headers: mastraHeaders
})(modelId);
case "vercel": return createGatewayProvider({
apiKey,
baseURL,
headers: mastraHeaders
})(modelId);
case "moonshotai":
case "moonshotai-cn":
if (!baseURL) throw new Error(`No API URL found for ${providerId}/${modelId}`);
return createAnthropic({
apiKey,
baseURL,
headers: mastraHeaders
})(modelId);
default: {
const config = this.providerConfigs[providerId];
const npm = override?.npm ?? config?.npm;
if (providerId.includes("alibaba")) {
if (!baseURL) throw new Error(`No API URL found for ${providerId}/${modelId}`);
return createAlibaba({
apiKey,
baseURL,
headers: mastraHeaders
})(modelId);
}
if (npm === "@ai-sdk/anthropic") {
if (!baseURL) throw new Error(`No API URL found for ${providerId}/${modelId}`);
return createAnthropic({
apiKey,
baseURL,
headers: mastraHeaders
})(modelId);
}
if (npm === "@ai-sdk/openai") {
if (!baseURL) throw new Error(`No API URL found for ${providerId}/${modelId}`);
return createOpenAI({
apiKey,
baseURL,
headers: mastraHeaders
}).chat(modelId);
}
if (npm === "@ai-sdk/google") {
if (!baseURL) throw new Error(`No API URL found for ${providerId}/${modelId}`);
return createGoogleGenerativeAI({
apiKey,
baseURL,
headers: mastraHeaders
}).chat(modelId);
}
if (npm === "@ai-sdk/mistral") {
if (!baseURL) throw new Error(`No API URL found for ${providerId}/${modelId}`);
return createMistral({
apiKey,
baseURL,
headers: mastraHeaders
})(modelId);
}
if (!baseURL) throw new Error(`No API URL found for ${providerId}/${modelId}`);
return createOpenAICompatible({
name: providerId,
apiKey,
baseURL,
headers: mastraHeaders,
supportsStructuredOutputs: true,
...providerId.startsWith("kimi-code-plan") ? { includeUsage: true } : {}
}).chatModel(modelId);
}
}
}
};
// src/llm/model/gateways/netlify.ts
var netlify_exports = /* @__PURE__ */ __exportAll({ NetlifyGateway: () => NetlifyGateway });
var NetlifyGateway = class extends MastraModelGateway {
id = "netlify";
name = "Netlify AI Gateway";
tokenCache = new InMemoryServerCache();
async fetchProviders() {
const response = await fetch("https://api.netlify.com/api/v1/ai-gateway/providers");
if (!response.ok) throw new Error(`Failed to fetch from Netlify: ${response.statusText}`);
const data = await response.json();
const config = {
apiKeyEnvVar: ["NETLIFY_TOKEN", "NETLIFY_SITE_ID"],
apiKeyHeader: "Authorization",
name: `Netlify`,
gateway: `netlify`,
models: [],
docUrl: "https://docs.netlify.com/build/ai-gateway/overview/"
};
for (const [providerId, provider] of Object.entries(data.providers)) for (const model of provider.models) config.models.push(`${providerId}/${model}`);
return { netlify: config };
}
async buildUrl(routerId, envVars) {
const siteId = envVars?.["NETLIFY_SITE_ID"] || process.env["NETLIFY_SITE_ID"];
const netlifyToken = envVars?.["NETLIFY_TOKEN"] || process.env["NETLIFY_TOKEN"];
if (!netlifyToken) throw new MastraError({
id: "NETLIFY_GATEWAY_NO_TOKEN",
domain: "LLM",
category: "UNKNOWN",
text: `Missing NETLIFY_TOKEN environment variable required for model: ${routerId}`
});
if (!siteId) throw new MastraError({
id: "NETLIFY_GATEWAY_NO_SITE_ID",
domain: "LLM",
category: "UNKNOWN",
text: `Missing NETLIFY_SITE_ID environment variable required for model: ${routerId}`
});
try {
const tokenData = await this.getOrFetchToken(siteId, netlifyToken);
return tokenData.url.endsWith(`/`) ? tokenData.url.substring(0, tokenData.url.length - 1) : tokenData.url;
} catch (error) {
throw new MastraError({
id: "NETLIFY_GATEWAY_TOKEN_ERROR",
domain: "LLM",
category: "UNKNOWN",
text: `Failed to get Netlify AI Gateway token for model ${routerId}: ${error instanceof Error ? error.message : String(error)}`
});
}
}
/**
* Get cached token or fetch a new site-specific AI Gateway token from Netlify
*/
async getOrFetchToken(siteId, netlifyToken) {
const cacheKey = `netlify-token:${siteId}:${netlifyToken}`;
const cached = await this.tokenCache.get(cacheKey);
if (cached && cached.expiresAt > Date.now() / 1e3 + 60) return {
token: cached.token,
url: cached.url
};
const response = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}/ai-gateway/token`, {
method: "GET",
headers: { Authorization: `Bearer ${netlifyToken}` }
});
if (!response.ok) {
const error = await response.text();
throw new Error(`Failed to get Netlify AI Gateway token: ${response.status} ${error}`);
}
const tokenResponse = await response.json();
await this.tokenCache.set(cacheKey, {
token: tokenResponse.token,
url: tokenResponse.url,
expiresAt: tokenResponse.expires_at
});
return {
token: tokenResponse.token,
url: tokenResponse.url
};
}
/**
* Get cached token or fetch a new site-specific AI Gateway token from Netlify
*/
async getApiKey(modelId) {
const siteId = process.env["NETLIFY_SITE_ID"];
const netlifyToken = process.env["NETLIFY_TOKEN"];
if (!netlifyToken) throw new MastraError({
id: "NETLIFY_GATEWAY_NO_TOKEN",
domain: "LLM",
category: "UNKNOWN",
text: `Missing NETLIFY_TOKEN environment variable required for model: ${modelId}`
});
if (!siteId) throw new MastraError({
id: "NETLIFY_GATEWAY_NO_SITE_ID",
domain: "LLM",
category: "UNKNOWN",
text: `Missing NETLIFY_SITE_ID environment variable required for model: ${modelId}`
});
try {
return (await this.getOrFetchToken(siteId, netlifyToken)).token;
} catch (error) {
throw new MastraError({
id: "NETLIFY_GATEWAY_TOKEN_ERROR",
domain: "LLM",
category: "UNKNOWN",
text: `Failed to get Netlify AI Gateway token for model ${modelId}: ${error instanceof Error ? error.message : String(error)}`
});
}
}
async resolveLanguageModel({ modelId, providerId, apiKey, headers }) {
const baseURL = await this.buildUrl(`${providerId}/${modelId}`);
const mastraHeaders = {
"User-Agent": MASTRA_USER_AGENT,
...headers
};
switch (providerId) {
case "openai": return createOpenAI({
apiKey,
baseURL,
headers: mastraHeaders
}).responses(modelId);
case "gemini": return createGoogleGenerativeAI({
baseURL: `${baseURL}/v1beta/`,
apiKey,
headers: {
"user-agent": "google-genai-sdk/",
...mastraHeaders
}
}).chat(modelId);
case "anthropic": return createAnthropic({
apiKey,
baseURL: `${baseURL}/v1/`,
headers: {
"anthropic-version": "2023-06-01",
...mastraHeaders
}
})(modelId);
default: return createOpenAICompatible({
name: providerId,
apiKey,
baseURL,
headers: mastraHeaders,
supportsStructuredOutputs: true
}).chatModel(modelId);
}
}
};
export { MASTRA_GATEWAY_STREAM_TRANSPORT as _, interpolateUrlTemplate as a, createOpenAICompatible as b, GATEWAY_AUTH_HEADER as c, createAnthropic as d, findGatewayForModel as f, getCapabilityFileName as g, shouldEnableGateway as h, models_dev_exports as i, MASTRA_USER_AGENT as l, hasAuthCredentials as m, netlify_exports as n, parseModelRouterId as o, getGatewayId as p, ModelsDevGateway as r, createGoogleGenerativeAI as s, NetlifyGateway as t, createOpenRouter as u, MastraModelGateway as v, EventSourceParserStream$1 as x, createOpenAI as y };
//# sourceMappingURL=netlify-WYnWTeMp.js.map