ai-sdk-react-model-picker
Version:
A flexible, theme-aware React component library for selecting and managing AI models. Built for seamless integration with Vercel's AI SDK v5, with special support for VSCode extensions and JetBrains IDEs.
1,743 lines (1,740 loc) • 55.8 kB
JavaScript
import { fe as g, fy as f, f2 as j, fL as H, fM as Ie, em as C, el as ht, fd as b, eI as pe, fo as mt } from "./schemas-DvchZWm7.js";
var gt = Object.defineProperty, _t = Object.defineProperties, vt = Object.getOwnPropertyDescriptors, ve = Object.getOwnPropertySymbols, yt = Object.prototype.hasOwnProperty, bt = Object.prototype.propertyIsEnumerable, ye = (e, t, n) => t in e ? gt(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n, E = (e, t) => {
for (var n in t || (t = {}))
yt.call(t, n) && ye(e, n, t[n]);
if (ve)
for (var n of ve(t))
bt.call(t, n) && ye(e, n, t[n]);
return e;
}, V = (e, t) => _t(e, vt(t)), Ee = "vercel.ai.error", kt = Symbol.for(Ee), Se, wt = class Oe 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: t,
message: n,
cause: o
}) {
super(n), this[Se] = !0, this.name = t, this.cause = o;
}
/**
* 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(t) {
return Oe.hasMarker(t, Ee);
}
static hasMarker(t, n) {
const o = Symbol.for(n);
return t != null && typeof t == "object" && o in t && typeof t[o] == "boolean" && t[o] === !0;
}
};
Se = kt;
var O = wt, Re = "AI_APICallError", $e = `vercel.ai.error.${Re}`, Tt = Symbol.for($e), Ce, M = class extends O {
constructor({
message: e,
url: t,
requestBodyValues: n,
statusCode: o,
responseHeaders: s,
responseBody: i,
cause: l,
isRetryable: a = o != null && (o === 408 || // request timeout
o === 409 || // conflict
o === 429 || // too many requests
o >= 500),
// server error
data: r
}) {
super({ name: Re, message: e, cause: l }), this[Ce] = !0, this.url = t, this.requestBodyValues = n, this.statusCode = o, this.responseHeaders = s, this.responseBody = i, this.isRetryable = a, this.data = r;
}
static isInstance(e) {
return O.hasMarker(e, $e);
}
};
Ce = Tt;
var Ne = "AI_EmptyResponseBodyError", Ae = `vercel.ai.error.${Ne}`, xt = Symbol.for(Ae), Pe, It = class extends O {
// used in isInstance
constructor({ message: e = "Empty response body" } = {}) {
super({ name: Ne, message: e }), this[Pe] = !0;
}
static isInstance(e) {
return O.hasMarker(e, Ae);
}
};
Pe = xt;
function qe(e) {
return e == null ? "unknown error" : typeof e == "string" ? e : e instanceof Error ? e.message : JSON.stringify(e);
}
var je = "AI_InvalidArgumentError", De = `vercel.ai.error.${je}`, Et = Symbol.for(De), Me, St = class extends O {
constructor({
message: e,
cause: t,
argument: n
}) {
super({ name: je, message: e, cause: t }), this[Me] = !0, this.argument = n;
}
static isInstance(e) {
return O.hasMarker(e, De);
}
};
Me = Et;
var Ue = "AI_InvalidPromptError", Be = `vercel.ai.error.${Ue}`, Ot = Symbol.for(Be), Le, Rt = class extends O {
constructor({
prompt: e,
message: t,
cause: n
}) {
super({ name: Ue, message: `Invalid prompt: ${t}`, cause: n }), this[Le] = !0, this.prompt = e;
}
static isInstance(e) {
return O.hasMarker(e, Be);
}
};
Le = Ot;
var He = "AI_InvalidResponseDataError", Ve = `vercel.ai.error.${He}`, $t = Symbol.for(Ve), Je, le = class extends O {
constructor({
data: e,
message: t = `Invalid response data: ${JSON.stringify(e)}.`
}) {
super({ name: He, message: t }), this[Je] = !0, this.data = e;
}
static isInstance(e) {
return O.hasMarker(e, Ve);
}
};
Je = $t;
var Fe = "AI_JSONParseError", Ke = `vercel.ai.error.${Fe}`, Ct = Symbol.for(Ke), We, te = class extends O {
constructor({ text: e, cause: t }) {
super({
name: Fe,
message: `JSON parsing failed: Text: ${e}.
Error message: ${qe(t)}`,
cause: t
}), this[We] = !0, this.text = e;
}
static isInstance(e) {
return O.hasMarker(e, Ke);
}
};
We = Ct;
var Ge = "AI_LoadAPIKeyError", ze = `vercel.ai.error.${Ge}`, Nt = Symbol.for(ze), Ye, ee = class extends O {
// used in isInstance
constructor({ message: e }) {
super({ name: Ge, message: e }), this[Ye] = !0;
}
static isInstance(e) {
return O.hasMarker(e, ze);
}
};
Ye = Nt;
var Ze = "AI_TypeValidationError", Qe = `vercel.ai.error.${Ze}`, At = Symbol.for(Qe), Xe, Pt = class de extends O {
constructor({ value: t, cause: n }) {
super({
name: Ze,
message: `Type validation failed: Value: ${JSON.stringify(t)}.
Error message: ${qe(n)}`,
cause: n
}), this[Xe] = !0, this.value = t;
}
static isInstance(t) {
return O.hasMarker(t, Qe);
}
/**
* Wraps an error into a TypeValidationError.
* If the cause is already a TypeValidationError with the same value, 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.
* @returns {TypeValidationError} A TypeValidationError instance.
*/
static wrap({
value: t,
cause: n
}) {
return de.isInstance(n) && n.value === t ? n : new de({ value: t, cause: n });
}
};
Xe = At;
var z = Pt, et = "AI_UnsupportedFunctionalityError", tt = `vercel.ai.error.${et}`, qt = Symbol.for(tt), nt, B = class extends O {
constructor({
functionality: e,
message: t = `'${e}' functionality not supported.`
}) {
super({ name: et, message: t }), this[nt] = !0, this.functionality = e;
}
static isInstance(e) {
return O.hasMarker(e, tt);
}
};
nt = qt;
var be = class extends Error {
constructor(e, t) {
super(e), this.name = "ParseError", this.type = t.type, this.field = t.field, this.value = t.value, this.line = t.line;
}
};
function ue(e) {
}
function jt(e) {
if (typeof e == "function")
throw new TypeError(
"`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
);
const { onEvent: t = ue, onError: n = ue, onRetry: o = ue, onComment: s } = e;
let i = "", l = !0, a, r = "", p = "";
function u(c) {
const k = l ? c.replace(/^\xEF\xBB\xBF/, "") : c, [x, y] = Dt(`${i}${k}`);
for (const w of x)
h(w);
i = y, l = !1;
}
function h(c) {
if (c === "") {
m();
return;
}
if (c.startsWith(":")) {
s && s(c.slice(c.startsWith(": ") ? 2 : 1));
return;
}
const k = c.indexOf(":");
if (k !== -1) {
const x = c.slice(0, k), y = c[k + 1] === " " ? 2 : 1, w = c.slice(k + y);
d(x, w, c);
return;
}
d(c, "", c);
}
function d(c, k, x) {
switch (c) {
case "event":
p = k;
break;
case "data":
r = `${r}${k}
`;
break;
case "id":
a = k.includes("\0") ? void 0 : k;
break;
case "retry":
/^\d+$/.test(k) ? o(parseInt(k, 10)) : n(
new be(`Invalid \`retry\` value: "${k}"`, {
type: "invalid-retry",
value: k,
line: x
})
);
break;
default:
n(
new be(
`Unknown field "${c.length > 20 ? `${c.slice(0, 20)}…` : c}"`,
{ type: "unknown-field", field: c, value: k, line: x }
)
);
break;
}
}
function m() {
r.length > 0 && t({
id: a,
event: p || void 0,
// If the data buffer's last character is a U+000A LINE FEED (LF) character,
// then remove the last character from the data buffer.
data: r.endsWith(`
`) ? r.slice(0, -1) : r
}), a = void 0, r = "", p = "";
}
function T(c = {}) {
i && c.consume && h(i), l = !0, a = void 0, r = "", p = "", i = "";
}
return { feed: u, reset: T };
}
function Dt(e) {
const t = [];
let n = "", o = 0;
for (; o < e.length; ) {
const s = e.indexOf("\r", o), i = e.indexOf(`
`, o);
let l = -1;
if (s !== -1 && i !== -1 ? l = Math.min(s, i) : s !== -1 ? l = s : i !== -1 && (l = i), l === -1) {
n = e.slice(o);
break;
} else {
const a = e.slice(o, l);
t.push(a), o = l + 1, e[o - 1] === "\r" && e[o] === `
` && o++;
}
}
return [t, n];
}
var Mt = class extends TransformStream {
constructor({ onError: e, onRetry: t, onComment: n } = {}) {
let o;
super({
start(s) {
o = jt({
onEvent: (i) => {
s.enqueue(i);
},
onError(i) {
e === "terminate" ? s.error(i) : typeof e == "function" && e(i);
},
onRetry: t,
onComment: n
});
},
transform(s) {
o.feed(s);
}
});
}
};
new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
function ne(...e) {
return e.reduce(
(t, n) => E(E({}, t), n ?? {}),
{}
);
}
function ae(e) {
return Object.fromEntries([...e.headers]);
}
var Ut = ({
prefix: e,
size: t = 16,
alphabet: n = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
separator: o = "-"
} = {}) => {
const s = () => {
const i = n.length, l = new Array(t);
for (let a = 0; a < t; a++)
l[a] = n[Math.random() * i | 0];
return l.join("");
};
if (e == null)
return s;
if (n.includes(o))
throw new St({
argument: "separator",
message: `The separator "${o}" must not be part of the alphabet "${n}".`
});
return () => `${e}${o}${s()}`;
}, q = Ut();
function fe(e) {
return (e instanceof Error || e instanceof DOMException) && (e.name === "AbortError" || e.name === "ResponseAborted" || // Next.js
e.name === "TimeoutError");
}
var Bt = ["fetch failed", "failed to fetch"];
function Lt({
error: e,
url: t,
requestBodyValues: n
}) {
if (fe(e))
return e;
if (e instanceof TypeError && Bt.includes(e.message.toLowerCase())) {
const o = e.cause;
if (o != null)
return new M({
message: `Cannot connect to API: ${o.message}`,
cause: o,
url: t,
requestBodyValues: n,
isRetryable: !0
// retry when network error
});
}
return e;
}
function Ht(e) {
return Object.fromEntries(
Object.entries(e).filter(([t, n]) => n != null)
);
}
function ot({
apiKey: e,
environmentVariableName: t,
apiKeyParameterName: n = "apiKey",
description: o
}) {
if (typeof e == "string")
return e;
if (e != null)
throw new ee({
message: `${o} API key must be a string.`
});
if (typeof process > "u")
throw new ee({
message: `${o} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`
});
if (e = process.env[t], e == null)
throw new ee({
message: `${o} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`
});
if (typeof e != "string")
throw new ee({
message: `${o} API key must be a string. The value of the ${t} environment variable is not a string.`
});
return e;
}
var Vt = /"__proto__"\s*:/, Jt = /"constructor"\s*:/;
function Ft(e) {
const t = JSON.parse(e);
return t === null || typeof t != "object" || Vt.test(e) === !1 && Jt.test(e) === !1 ? t : Kt(t);
}
function Kt(e) {
let t = [e];
for (; t.length; ) {
const n = t;
t = [];
for (const o of n) {
if (Object.prototype.hasOwnProperty.call(o, "__proto__"))
throw new SyntaxError("Object contains forbidden prototype property");
if (Object.prototype.hasOwnProperty.call(o, "constructor") && Object.prototype.hasOwnProperty.call(o.constructor, "prototype"))
throw new SyntaxError("Object contains forbidden prototype property");
for (const s in o) {
const i = o[s];
i && typeof i == "object" && t.push(i);
}
}
}
return e;
}
function me(e) {
const { stackTraceLimit: t } = Error;
Error.stackTraceLimit = 0;
try {
return Ft(e);
} finally {
Error.stackTraceLimit = t;
}
}
var he = Symbol.for("vercel.ai.validator");
function Wt(e) {
return { [he]: !0, validate: e };
}
function Gt(e) {
return typeof e == "object" && e !== null && he in e && e[he] === !0 && "validate" in e;
}
function zt(e) {
return Gt(e) ? e : Yt(e);
}
function Yt(e) {
return Wt(async (t) => {
const n = await e["~standard"].validate(t);
return n.issues == null ? { success: !0, value: n.value } : {
success: !1,
error: new z({
value: t,
cause: n.issues
})
};
});
}
async function Zt({
value: e,
schema: t
}) {
const n = await st({ value: e, schema: t });
if (!n.success)
throw z.wrap({ value: e, cause: n.error });
return n.value;
}
async function st({
value: e,
schema: t
}) {
const n = zt(t);
try {
if (n.validate == null)
return { success: !0, value: e, rawValue: e };
const o = await n.validate(e);
return o.success ? { success: !0, value: o.value, rawValue: e } : {
success: !1,
error: z.wrap({ value: e, cause: o.error }),
rawValue: e
};
} catch (o) {
return {
success: !1,
error: z.wrap({ value: e, cause: o }),
rawValue: e
};
}
}
async function Qt({
text: e,
schema: t
}) {
try {
const n = me(e);
return t == null ? n : Zt({ value: n, schema: t });
} catch (n) {
throw te.isInstance(n) || z.isInstance(n) ? n : new te({ text: e, cause: n });
}
}
async function rt({
text: e,
schema: t
}) {
try {
const n = me(e);
return t == null ? { success: !0, value: n, rawValue: n } : await st({ value: n, schema: t });
} catch (n) {
return {
success: !1,
error: te.isInstance(n) ? n : new te({ text: e, cause: n }),
rawValue: void 0
};
}
}
function ce(e) {
try {
return me(e), !0;
} catch {
return !1;
}
}
function Xt({
stream: e,
schema: t
}) {
return e.pipeThrough(new TextDecoderStream()).pipeThrough(new Mt()).pipeThrough(
new TransformStream({
async transform({ data: n }, o) {
n !== "[DONE]" && o.enqueue(await rt({ text: n, schema: t }));
}
})
);
}
var en = () => globalThis.fetch, oe = async ({
url: e,
headers: t,
body: n,
failedResponseHandler: o,
successfulResponseHandler: s,
abortSignal: i,
fetch: l
}) => tn({
url: e,
headers: E({
"Content-Type": "application/json"
}, t),
body: {
content: JSON.stringify(n),
values: n
},
failedResponseHandler: o,
successfulResponseHandler: s,
abortSignal: i,
fetch: l
}), tn = async ({
url: e,
headers: t = {},
body: n,
successfulResponseHandler: o,
failedResponseHandler: s,
abortSignal: i,
fetch: l = en()
}) => {
try {
const a = await l(e, {
method: "POST",
headers: Ht(t),
body: n.content,
signal: i
}), r = ae(a);
if (!a.ok) {
let p;
try {
p = await s({
response: a,
url: e,
requestBodyValues: n.values
});
} catch (u) {
throw fe(u) || M.isInstance(u) ? u : new M({
message: "Failed to process error response",
cause: u,
statusCode: a.status,
url: e,
responseHeaders: r,
requestBodyValues: n.values
});
}
throw p.value;
}
try {
return await o({
response: a,
url: e,
requestBodyValues: n.values
});
} catch (p) {
throw p instanceof Error && (fe(p) || M.isInstance(p)) ? p : new M({
message: "Failed to process successful response",
cause: p,
statusCode: a.status,
url: e,
responseHeaders: r,
requestBodyValues: n.values
});
}
} catch (a) {
throw Lt({ error: a, url: e, requestBodyValues: n.values });
}
}, nn = ({
errorSchema: e,
errorToMessage: t,
isRetryable: n
}) => async ({ response: o, url: s, requestBodyValues: i }) => {
const l = await o.text(), a = ae(o);
if (l.trim() === "")
return {
responseHeaders: a,
value: new M({
message: o.statusText,
url: s,
requestBodyValues: i,
statusCode: o.status,
responseHeaders: a,
responseBody: l,
isRetryable: n?.(o)
})
};
try {
const r = await Qt({
text: l,
schema: e
});
return {
responseHeaders: a,
value: new M({
message: t(r),
url: s,
requestBodyValues: i,
statusCode: o.status,
responseHeaders: a,
responseBody: l,
data: r,
isRetryable: n?.(o, r)
})
};
} catch {
return {
responseHeaders: a,
value: new M({
message: o.statusText,
url: s,
requestBodyValues: i,
statusCode: o.status,
responseHeaders: a,
responseBody: l,
isRetryable: n?.(o)
})
};
}
}, at = (e) => async ({ response: t }) => {
const n = ae(t);
if (t.body == null)
throw new It({});
return {
responseHeaders: n,
value: Xt({
stream: t.body,
schema: e
})
};
}, it = (e) => async ({ response: t, url: n, requestBodyValues: o }) => {
const s = await t.text(), i = await rt({
text: s,
schema: e
}), l = ae(t);
if (!i.success)
throw new M({
message: "Invalid JSON response",
cause: i.error,
statusCode: t.status,
responseHeaders: l,
responseBody: s,
url: n,
requestBodyValues: o
});
return {
responseHeaders: l,
value: i.value,
rawValue: i.rawValue
};
}, { btoa: on } = globalThis;
function sn(e) {
let t = "";
for (let n = 0; n < e.length; n++)
t += String.fromCodePoint(e[n]);
return on(t);
}
function lt(e) {
return e?.replace(/\/$/, "");
}
var rn = g({
type: j(
"reasoning.summary"
/* Summary */
),
summary: f()
}), an = g({
type: j(
"reasoning.encrypted"
/* Encrypted */
),
data: f()
}), ln = g({
type: j(
"reasoning.text"
/* Text */
),
text: f().nullish(),
signature: f().nullish()
}), un = H([
rn,
an,
ln
]), cn = H([
un,
Ie().transform(() => null)
]), ge = C(cn).transform((e) => e.filter((t) => !!t)), _e = g({
error: g({
code: H([f(), b()]).nullable().optional().default(null),
message: f(),
type: f().nullable().optional().default(null),
param: ht().nullable().optional().default(null)
})
}), se = nn({
errorSchema: _e,
errorToMessage: (e) => e.error.message
});
function re(e) {
switch (e) {
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 "unknown";
}
}
function ut({
url: e,
protocols: t
}) {
try {
const n = new URL(e);
return t.has(n.protocol);
} catch {
return !1;
}
}
function ke({
part: e,
defaultMediaType: t
}) {
var n, o;
if (e.data instanceof Uint8Array) {
const i = sn(e.data);
return `data:${(n = e.mediaType) != null ? n : t};base64,${i}`;
}
const s = e.data.toString();
return ut({
url: s,
protocols: /* @__PURE__ */ new Set(["http:", "https:"])
}) || s.startsWith("data:") ? s : `data:${(o = e.mediaType) != null ? o : t};base64,${s}`;
}
function we(e, t) {
var n;
const o = e.match(/^data:([^;]+)/);
return o && (n = o[1]) != null ? n : t;
}
function Te(e) {
const t = e.match(/^data:[^;]*;base64,(.+)$/);
return t ? t[1] : e;
}
function U(e) {
var t, n, o;
const s = e?.anthropic, i = e?.openrouter;
return (o = (n = (t = i?.cacheControl) != null ? t : i?.cache_control) != null ? n : s?.cacheControl) != null ? o : s?.cache_control;
}
function pn(e) {
var t, n, o;
const s = [];
for (const { role: i, content: l, providerOptions: a } of e)
switch (i) {
case "system": {
s.push({
role: "system",
content: l,
cache_control: U(a)
});
break;
}
case "user": {
if (l.length === 1 && ((t = l[0]) == null ? void 0 : t.type) === "text") {
const u = (n = U(a)) != null ? n : U(l[0].providerOptions), h = u ? [
{
type: "text",
text: l[0].text,
cache_control: u
}
] : l[0].text;
s.push({
role: "user",
content: h
});
break;
}
const r = U(a), p = l.map(
(u) => {
var h, d, m, T, c, k;
const x = (h = U(u.providerOptions)) != null ? h : r;
switch (u.type) {
case "text":
return {
type: "text",
text: u.text,
// For text parts, only use part-specific cache control
cache_control: x
};
case "file": {
if ((d = u.mediaType) != null && d.startsWith("image/"))
return {
type: "image_url",
image_url: {
url: ke({
part: u,
defaultMediaType: "image/jpeg"
})
},
// For image parts, use part-specific or message-level cache control
cache_control: x
};
const y = String(
(k = (c = (T = (m = u.providerOptions) == null ? void 0 : m.openrouter) == null ? void 0 : T.filename) != null ? c : u.filename) != null ? k : ""
), w = ke({
part: u,
defaultMediaType: "application/pdf"
});
return ut({
url: w,
protocols: /* @__PURE__ */ new Set(["http:", "https:"])
}) ? {
type: "file",
file: {
filename: y,
file_data: w
}
} : {
type: "file",
file: {
filename: y,
file_data: w
},
cache_control: x
};
}
default:
return {
type: "text",
text: "",
cache_control: x
};
}
}
);
s.push({
role: "user",
content: p
});
break;
}
case "assistant": {
let r = "", p = "";
const u = [], h = [];
for (const d of l)
switch (d.type) {
case "text": {
r += d.text;
break;
}
case "tool-call": {
h.push({
id: d.toolCallId,
type: "function",
function: {
name: d.toolName,
arguments: JSON.stringify(d.input)
}
});
break;
}
case "reasoning": {
p += d.text, u.push({
type: "reasoning.text",
text: d.text
});
break;
}
}
s.push({
role: "assistant",
content: r,
tool_calls: h.length > 0 ? h : void 0,
reasoning: p || void 0,
reasoning_details: u.length > 0 ? u : void 0,
cache_control: U(a)
});
break;
}
case "tool": {
for (const r of l) {
const p = dn(r);
s.push({
role: "tool",
tool_call_id: r.toolCallId,
content: p,
cache_control: (o = U(a)) != null ? o : U(r.providerOptions)
});
}
break;
}
}
return s;
}
function dn(e) {
return e.output.type === "text" ? e.output.value : JSON.stringify(e.output.value);
}
H([
j("auto"),
j("none"),
j("required"),
g({
type: j("function"),
function: g({
name: f()
})
})
]);
function fn(e) {
switch (e.type) {
case "auto":
case "none":
case "required":
return e.type;
case "tool":
return {
type: "function",
function: { name: e.toolName }
};
default:
throw new Error(`Invalid tool choice type: ${e}`);
}
}
var hn = g({
type: j("image_url"),
image_url: g({
url: f()
})
}), mn = H([
hn,
Ie().transform(() => null)
]), ct = C(mn).transform((e) => e.filter((t) => !!t)), pt = g({
id: f().optional(),
model: f().optional(),
provider: f().optional(),
usage: g({
prompt_tokens: b(),
prompt_tokens_details: g({
cached_tokens: b()
}).nullish(),
completion_tokens: b(),
completion_tokens_details: g({
reasoning_tokens: b()
}).nullish(),
total_tokens: b(),
cost: b().optional(),
cost_details: g({
upstream_inference_cost: b().nullish()
}).nullish()
}).nullish()
}), gn = pt.extend({
choices: C(
g({
message: g({
role: j("assistant"),
content: f().nullable().optional(),
reasoning: f().nullable().optional(),
reasoning_details: ge.nullish(),
images: ct.nullish(),
tool_calls: C(
g({
id: f().optional().nullable(),
type: j("function"),
function: g({
name: f(),
arguments: f()
})
})
).optional(),
annotations: C(
g({
type: pe(["url_citation"]),
url_citation: g({
end_index: b(),
start_index: b(),
title: f(),
url: f(),
content: f().optional()
})
})
).nullish()
}),
index: b().nullish(),
logprobs: g({
content: C(
g({
token: f(),
logprob: b(),
top_logprobs: C(
g({
token: f(),
logprob: b()
})
)
})
).nullable()
}).nullable().optional(),
finish_reason: f().optional().nullable()
})
)
}), _n = H([
pt.extend({
choices: C(
g({
delta: g({
role: pe(["assistant"]).optional(),
content: f().nullish(),
reasoning: f().nullish().optional(),
reasoning_details: ge.nullish(),
images: ct.nullish(),
tool_calls: C(
g({
index: b().nullish(),
id: f().nullish(),
type: j("function").optional(),
function: g({
name: f().nullish(),
arguments: f().nullish()
})
})
).nullish(),
annotations: C(
g({
type: pe(["url_citation"]),
url_citation: g({
end_index: b(),
start_index: b(),
title: f(),
url: f(),
content: f().optional()
})
})
).nullish()
}).nullish(),
logprobs: g({
content: C(
g({
token: f(),
logprob: b(),
top_logprobs: C(
g({
token: f(),
logprob: b()
})
)
})
).nullable()
}).nullish(),
finish_reason: f().nullable().optional(),
index: b().nullish()
})
)
}),
_e
]), dt = class {
constructor(e, t, n) {
this.specificationVersion = "v2", this.provider = "openrouter", this.defaultObjectGenerationMode = "tool", 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.modelId = e, this.settings = t, this.config = n;
}
getArgs({
prompt: e,
maxOutputTokens: t,
temperature: n,
topP: o,
frequencyPenalty: s,
presencePenalty: i,
seed: l,
stopSequences: a,
responseFormat: r,
topK: p,
tools: u,
toolChoice: h
}) {
var d;
const m = E(E({
// model id:
model: this.modelId,
models: this.settings.models,
// model specific settings:
logit_bias: this.settings.logitBias,
logprobs: this.settings.logprobs === !0 || typeof this.settings.logprobs == "number" ? !0 : void 0,
top_logprobs: typeof this.settings.logprobs == "number" ? this.settings.logprobs : typeof this.settings.logprobs == "boolean" && this.settings.logprobs ? 0 : void 0,
user: this.settings.user,
parallel_tool_calls: this.settings.parallelToolCalls,
// standardized settings:
max_tokens: t,
temperature: n,
top_p: o,
frequency_penalty: s,
presence_penalty: i,
seed: l,
stop: a,
response_format: r,
top_k: p,
// messages:
messages: pn(e),
// OpenRouter specific settings:
include_reasoning: this.settings.includeReasoning,
reasoning: this.settings.reasoning,
usage: this.settings.usage,
// Web search settings:
plugins: this.settings.plugins,
web_search_options: this.settings.web_search_options,
// Provider routing settings:
provider: this.settings.provider
}, this.config.extraBody), this.settings.extraBody);
if (r?.type === "json" && r.schema != null)
return V(E({}, m), {
response_format: {
type: "json_schema",
json_schema: E({
schema: r.schema,
strict: !0,
name: (d = r.name) != null ? d : "response"
}, r.description && {
description: r.description
})
}
});
if (u && u.length > 0) {
const T = u.filter((c) => c.type === "function").map((c) => ({
type: "function",
function: {
name: c.name,
description: c.description,
parameters: c.inputSchema
}
}));
return V(E({}, m), {
tools: T,
tool_choice: h ? fn(h) : void 0
});
}
return m;
}
async doGenerate(e) {
var t, n, o, s, i, l, a, r, p, u, h, d, m, T, c, k, x, y, w, R, D, J, F, K;
const Y = (e.providerOptions || {}).openrouter || {}, W = E(E({}, this.getArgs(e)), Y), { value: S, responseHeaders: Z } = await oe({
url: this.config.url({
path: "/chat/completions",
modelId: this.modelId
}),
headers: ne(this.config.headers(), e.headers),
body: W,
failedResponseHandler: se,
successfulResponseHandler: it(
gn
),
abortSignal: e.abortSignal,
fetch: this.config.fetch
}), $ = S.choices[0];
if (!$)
throw new Error("No choice in response");
const L = S.usage ? {
inputTokens: (t = S.usage.prompt_tokens) != null ? t : 0,
outputTokens: (n = S.usage.completion_tokens) != null ? n : 0,
totalTokens: ((o = S.usage.prompt_tokens) != null ? o : 0) + ((s = S.usage.completion_tokens) != null ? s : 0),
reasoningTokens: (l = (i = S.usage.completion_tokens_details) == null ? void 0 : i.reasoning_tokens) != null ? l : 0,
cachedInputTokens: (r = (a = S.usage.prompt_tokens_details) == null ? void 0 : a.cached_tokens) != null ? r : 0
} : {
inputTokens: 0,
outputTokens: 0,
totalTokens: 0,
reasoningTokens: 0,
cachedInputTokens: 0
}, G = (p = $.message.reasoning_details) != null ? p : [], I = G.length > 0 ? G.map((v) => {
switch (v.type) {
case "reasoning.text": {
if (v.text)
return {
type: "reasoning",
text: v.text
};
break;
}
case "reasoning.summary": {
if (v.summary)
return {
type: "reasoning",
text: v.summary
};
break;
}
case "reasoning.encrypted": {
if (v.data)
return {
type: "reasoning",
text: "[REDACTED]"
};
break;
}
}
return null;
}).filter((v) => v !== null) : $.message.reasoning ? [
{
type: "reasoning",
text: $.message.reasoning
}
] : [], P = [];
if (P.push(...I), $.message.content && P.push({
type: "text",
text: $.message.content
}), $.message.tool_calls)
for (const v of $.message.tool_calls)
P.push({
type: "tool-call",
toolCallId: (u = v.id) != null ? u : q(),
toolName: v.function.name,
input: v.function.arguments
});
if ($.message.images)
for (const v of $.message.images)
P.push({
type: "file",
mediaType: we(v.image_url.url, "image/jpeg"),
data: Te(v.image_url.url)
});
if ($.message.annotations)
for (const v of $.message.annotations)
v.type === "url_citation" && P.push({
type: "source",
sourceType: "url",
id: v.url_citation.url,
url: v.url_citation.url,
title: v.url_citation.title,
providerMetadata: {
openrouter: {
content: v.url_citation.content || ""
}
}
});
return {
content: P,
finishReason: re($.finish_reason),
usage: L,
warnings: [],
providerMetadata: {
openrouter: {
provider: (h = S.provider) != null ? h : "",
usage: {
promptTokens: (d = L.inputTokens) != null ? d : 0,
completionTokens: (m = L.outputTokens) != null ? m : 0,
totalTokens: (T = L.totalTokens) != null ? T : 0,
cost: (c = S.usage) == null ? void 0 : c.cost,
promptTokensDetails: {
cachedTokens: (y = (x = (k = S.usage) == null ? void 0 : k.prompt_tokens_details) == null ? void 0 : x.cached_tokens) != null ? y : 0
},
completionTokensDetails: {
reasoningTokens: (D = (R = (w = S.usage) == null ? void 0 : w.completion_tokens_details) == null ? void 0 : R.reasoning_tokens) != null ? D : 0
},
costDetails: {
upstreamInferenceCost: (K = (F = (J = S.usage) == null ? void 0 : J.cost_details) == null ? void 0 : F.upstream_inference_cost) != null ? K : 0
}
}
}
},
request: { body: W },
response: {
id: S.id,
modelId: S.model,
headers: Z
}
};
}
async doStream(e) {
var t;
const o = (e.providerOptions || {}).openrouter || {}, s = E(E({}, this.getArgs(e)), o), { value: i, responseHeaders: l } = await oe({
url: this.config.url({
path: "/chat/completions",
modelId: this.modelId
}),
headers: ne(this.config.headers(), e.headers),
body: V(E({}, s), {
stream: !0,
// only include stream_options when in strict compatibility mode:
stream_options: this.config.compatibility === "strict" ? E({
include_usage: !0
}, (t = this.settings.usage) != null && t.include ? { include_usage: !0 } : {}) : void 0
}),
failedResponseHandler: se,
successfulResponseHandler: at(
_n
),
abortSignal: e.abortSignal,
fetch: this.config.fetch
}), a = [];
let r = "other";
const p = {
inputTokens: Number.NaN,
outputTokens: Number.NaN,
totalTokens: Number.NaN,
reasoningTokens: Number.NaN,
cachedInputTokens: Number.NaN
}, u = {};
let h = !1, d = !1, m, T, c, k;
return {
stream: i.pipeThrough(
new TransformStream({
transform(x, y) {
var w, R, D, J, F, K, ie, Y, W, S, Z, $, L, G;
if (!x.success) {
r = "error", y.enqueue({ type: "error", error: x.error });
return;
}
const I = x.value;
if ("error" in I) {
r = "error", y.enqueue({ type: "error", error: I.error });
return;
}
if (I.provider && (k = I.provider), I.id && (c = I.id, y.enqueue({
type: "response-metadata",
id: I.id
})), I.model && y.enqueue({
type: "response-metadata",
modelId: I.model
}), I.usage != null) {
if (p.inputTokens = I.usage.prompt_tokens, p.outputTokens = I.usage.completion_tokens, p.totalTokens = I.usage.prompt_tokens + I.usage.completion_tokens, u.promptTokens = I.usage.prompt_tokens, I.usage.prompt_tokens_details) {
const _ = (w = I.usage.prompt_tokens_details.cached_tokens) != null ? w : 0;
p.cachedInputTokens = _, u.promptTokensDetails = {
cachedTokens: _
};
}
if (u.completionTokens = I.usage.completion_tokens, I.usage.completion_tokens_details) {
const _ = (R = I.usage.completion_tokens_details.reasoning_tokens) != null ? R : 0;
p.reasoningTokens = _, u.completionTokensDetails = {
reasoningTokens: _
};
}
u.cost = I.usage.cost, u.totalTokens = I.usage.total_tokens;
}
const P = I.choices[0];
if (P?.finish_reason != null && (r = re(P.finish_reason)), P?.delta == null)
return;
const v = P.delta, Q = (_) => {
d || (T = c || q(), y.enqueue({
type: "reasoning-start",
id: T
}), d = !0), y.enqueue({
type: "reasoning-delta",
delta: _,
id: T || q()
});
};
if (v.reasoning_details && v.reasoning_details.length > 0)
for (const _ of v.reasoning_details)
switch (_.type) {
case "reasoning.text": {
_.text && Q(_.text);
break;
}
case "reasoning.encrypted": {
_.data && Q("[REDACTED]");
break;
}
case "reasoning.summary": {
_.summary && Q(_.summary);
break;
}
}
else v.reasoning && Q(v.reasoning);
if (v.content && (d && !h && (y.enqueue({
type: "reasoning-end",
id: T || q()
}), d = !1), h || (m = c || q(), y.enqueue({
type: "text-start",
id: m
}), h = !0), y.enqueue({
type: "text-delta",
delta: v.content,
id: m || q()
})), v.annotations)
for (const _ of v.annotations)
_.type === "url_citation" && y.enqueue({
type: "source",
sourceType: "url",
id: _.url_citation.url,
url: _.url_citation.url,
title: _.url_citation.title,
providerMetadata: {
openrouter: {
content: _.url_citation.content || ""
}
}
});
if (v.tool_calls != null)
for (const _ of v.tool_calls) {
const X = (D = _.index) != null ? D : a.length - 1;
if (a[X] == null) {
if (_.type !== "function")
throw new le({
data: _,
message: "Expected 'function' type."
});
if (_.id == null)
throw new le({
data: _,
message: "Expected 'id' to be a string."
});
if (((J = _.function) == null ? void 0 : J.name) == null)
throw new le({
data: _,
message: "Expected 'function.name' to be a string."
});
a[X] = {
id: _.id,
type: "function",
function: {
name: _.function.name,
arguments: (F = _.function.arguments) != null ? F : ""
},
inputStarted: !1,
sent: !1
};
const A = a[X];
if (A == null)
throw new Error("Tool call is missing");
((K = A.function) == null ? void 0 : K.name) != null && ((ie = A.function) == null ? void 0 : ie.arguments) != null && ce(A.function.arguments) && (A.inputStarted = !0, y.enqueue({
type: "tool-input-start",
id: A.id,
toolName: A.function.name
}), y.enqueue({
type: "tool-input-delta",
id: A.id,
delta: A.function.arguments
}), y.enqueue({
type: "tool-input-end",
id: A.id
}), y.enqueue({
type: "tool-call",
toolCallId: A.id,
toolName: A.function.name,
input: A.function.arguments
}), A.sent = !0);
continue;
}
const N = a[X];
if (N == null)
throw new Error("Tool call is missing");
N.inputStarted || (N.inputStarted = !0, y.enqueue({
type: "tool-input-start",
id: N.id,
toolName: N.function.name
})), ((Y = _.function) == null ? void 0 : Y.arguments) != null && (N.function.arguments += (S = (W = _.function) == null ? void 0 : W.arguments) != null ? S : ""), y.enqueue({
type: "tool-input-delta",
id: N.id,
delta: (Z = _.function.arguments) != null ? Z : ""
}), (($ = N.function) == null ? void 0 : $.name) != null && ((L = N.function) == null ? void 0 : L.arguments) != null && ce(N.function.arguments) && (y.enqueue({
type: "tool-call",
toolCallId: (G = N.id) != null ? G : q(),
toolName: N.function.name,
input: N.function.arguments
}), N.sent = !0);
}
if (v.images != null)
for (const _ of v.images)
y.enqueue({
type: "file",
mediaType: we(_.image_url.url, "image/jpeg"),
data: Te(_.image_url.url)
});
},
flush(x) {
var y;
if (r === "tool-calls")
for (const R of a)
R && !R.sent && (x.enqueue({
type: "tool-call",
toolCallId: (y = R.id) != null ? y : q(),
toolName: R.function.name,
// Coerce invalid arguments to an empty JSON object
input: ce(R.function.arguments) ? R.function.arguments : "{}"
}), R.sent = !0);
d && x.enqueue({
type: "reasoning-end",
id: T || q()
}), h && x.enqueue({
type: "text-end",
id: m || q()
});
const w = {
usage: u
};
k !== void 0 && (w.provider = k), x.enqueue({
type: "finish",
finishReason: r,
usage: p,
providerMetadata: {
openrouter: w
}
});
}
})
),
warnings: [],
request: { body: s },
response: { headers: l }
};
}
};
function vn({
prompt: e,
inputFormat: t,
user: n = "user",
assistant: o = "assistant"
}) {
if (e.length === 1 && e[0] && e[0].role === "user" && e[0].content.length === 1 && e[0].content[0] && e[0].content[0].type === "text")
return { prompt: e[0].content[0].text };
let s = "";
e[0] && e[0].role === "system" && (s += `${e[0].content}
`, e = e.slice(1));
for (const { role: i, content: l } of e)
switch (i) {
case "system":
throw new Rt({
message: `Unexpected system message in prompt: ${l}`,
prompt: e
});
case "user": {
const a = l.map((r) => {
switch (r.type) {
case "text":
return r.text;
case "file":
throw new B({
functionality: "file attachments"
});
default:
return "";
}
}).join("");
s += `${n}:
${a}
`;
break;
}
case "assistant": {
const a = l.map(
(r) => {
switch (r.type) {
case "text":
return r.text;
case "tool-call":
throw new B({
functionality: "tool-call messages"
});
case "tool-result":
throw new B({
functionality: "tool-result messages"
});
case "reasoning":
throw new B({
functionality: "reasoning messages"
});
case "file":
throw new B({
functionality: "file attachments"
});
default:
return "";
}
}
).join("");
s += `${o}:
${a}
`;
break;
}
case "tool":
throw new B({
functionality: "tool messages"
});
}
return s += `${o}:
`, {
prompt: s
};
}
var xe = H([
g({
id: f().optional(),
model: f().optional(),
choices: C(
g({
text: f(),
reasoning: f().nullish().optional(),
reasoning_details: ge.nullish(),
finish_reason: f().nullish(),
index: b().nullish(),
logprobs: g({
tokens: C(f()),
token_logprobs: C(b()),
top_logprobs: C(mt(f(), b())).nullable()
}).nullable().optional()
})
),
usage: g({
prompt_tokens: b(),
prompt_tokens_details: g({
cached_tokens: b()
}).nullish(),
completion_tokens: b(),
completion_tokens_details: g({
reasoning_tokens: b()
}).nullish(),
total_tokens: b(),
cost: b().optional()
}).nullish()
}),
_e
]), ft = class {
constructor(e, t, n) {
this.specificationVersion = "v2", this.provider = "openrouter", 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 = e, this.settings = t, this.config = n;
}
getArgs({
prompt: e,
maxOutputTokens: t,
temperature: n,
topP: o,
frequencyPenalty: s,
presencePenalty: i,
seed: l,
responseFormat: a,
topK: r,
stopSequences: p,
tools: u,
toolChoice: h
}) {
const { prompt: d } = vn({
prompt: e,
inputFormat: "prompt"
});
if (u?.length)
throw new B({
functionality: "tools"
});
if (h)
throw new B({
functionality: "toolChoice"
});
return E(E({
// model id:
model: this.modelId,
models: this.settings.models,
// model specific settings:
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,
suffix: this.settings.suffix,
user: this.settings.user,
// standardized settings:
max_tokens: t,
temperature: n,
top_p: o,
frequency_penalty: s,
presence_penalty: i,
seed: l,
stop: p,
response_format: a,
top_k: r,
// prompt:
prompt: d,
// OpenRouter specific settings:
include_reasoning: this.settings.includeReasoning,
reasoning: this.settings.reasoning
}, this.config.extraBody), this.settings.extraBody);
}
async doGenerate(e) {
var t, n, o, s, i, l, a, r, p, u, h, d, m, T, c;
const x = (e.providerOptions || {}).openrouter || {}, y = E(E({}, this.getArgs(e)), x), { value: w, responseHeaders: R } = await oe({
url: this.config.url({
path: "/completions",
modelId: this.modelId
}),
headers: ne(this.config.headers(), e.headers),
body: y,
failedResponseHandler: se,
successfulResponseHandler: it(
xe
),
abortSignal: e.abortSignal,
fetch: this.config.fetch
});
if ("error" in w)
throw new Error(`${w.error.message}`);
const D = w.choices[0];
if (!D)
throw new Error("No choice in OpenRouter completion response");
return {
content: [
{
type: "text",
text: (t = D.text) != null ? t : ""
}
],
finishReason: re(D.finish_reason),
usage: {
inputTokens: (o = (n = w.usage) == null ? void 0 : n.prompt_tokens) != null ? o : 0,
outputTokens: (