@forbespro/lead-agent
Version:
Lead Chat Agent React Component
1,093 lines (1,092 loc) • 29.2 kB
JavaScript
import { generateId as M, safeParseJSON as P } from "./index15.js";
import "./index35.js";
var S = {
code: "0",
name: "text",
parse: (t) => {
if (typeof t != "string")
throw new Error('"text" parts expect a string value.');
return { type: "text", value: t };
}
}, R = {
code: "3",
name: "error",
parse: (t) => {
if (typeof t != "string")
throw new Error('"error" parts expect a string value.');
return { type: "error", value: t };
}
}, N = {
code: "4",
name: "assistant_message",
parse: (t) => {
if (t == null || typeof t != "object" || !("id" in t) || !("role" in t) || !("content" in t) || typeof t.id != "string" || typeof t.role != "string" || t.role !== "assistant" || !Array.isArray(t.content) || !t.content.every(
(e) => e != null && typeof e == "object" && "type" in e && e.type === "text" && "text" in e && e.text != null && typeof e.text == "object" && "value" in e.text && typeof e.text.value == "string"
))
throw new Error(
'"assistant_message" parts expect an object with an "id", "role", and "content" property.'
);
return {
type: "assistant_message",
value: t
};
}
}, C = {
code: "5",
name: "assistant_control_data",
parse: (t) => {
if (t == null || typeof t != "object" || !("threadId" in t) || !("messageId" in t) || typeof t.threadId != "string" || typeof t.messageId != "string")
throw new Error(
'"assistant_control_data" parts expect an object with a "threadId" and "messageId" property.'
);
return {
type: "assistant_control_data",
value: {
threadId: t.threadId,
messageId: t.messageId
}
};
}
}, x = {
code: "6",
name: "data_message",
parse: (t) => {
if (t == null || typeof t != "object" || !("role" in t) || !("data" in t) || typeof t.role != "string" || t.role !== "data")
throw new Error(
'"data_message" parts expect an object with a "role" and "data" property.'
);
return {
type: "data_message",
value: t
};
}
}, J = [
S,
R,
N,
C,
x
];
S.code + "", R.code + "", N.code + "", C.code + "", x.code + "";
S.name + "", S.code, R.name + "", R.code, N.name + "", N.code, C.name + "", C.code, x.name + "", x.code;
J.map((t) => t.code);
function F({
promptTokens: t,
completionTokens: e
}) {
return {
promptTokens: t,
completionTokens: e,
totalTokens: t + e
};
}
function U(t) {
const e = ["ROOT"];
let r = -1, s = null;
function i(o, n, I) {
switch (o) {
case '"': {
r = n, e.pop(), e.push(I), e.push("INSIDE_STRING");
break;
}
case "f":
case "t":
case "n": {
r = n, s = n, e.pop(), e.push(I), e.push("INSIDE_LITERAL");
break;
}
case "-": {
e.pop(), e.push(I), e.push("INSIDE_NUMBER");
break;
}
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9": {
r = n, e.pop(), e.push(I), e.push("INSIDE_NUMBER");
break;
}
case "{": {
r = n, e.pop(), e.push(I), e.push("INSIDE_OBJECT_START");
break;
}
case "[": {
r = n, e.pop(), e.push(I), e.push("INSIDE_ARRAY_START");
break;
}
}
}
function c(o, n) {
switch (o) {
case ",": {
e.pop(), e.push("INSIDE_OBJECT_AFTER_COMMA");
break;
}
case "}": {
r = n, e.pop();
break;
}
}
}
function u(o, n) {
switch (o) {
case ",": {
e.pop(), e.push("INSIDE_ARRAY_AFTER_COMMA");
break;
}
case "]": {
r = n, e.pop();
break;
}
}
}
for (let o = 0; o < t.length; o++) {
const n = t[o];
switch (e[e.length - 1]) {
case "ROOT":
i(n, o, "FINISH");
break;
case "INSIDE_OBJECT_START": {
switch (n) {
case '"': {
e.pop(), e.push("INSIDE_OBJECT_KEY");
break;
}
case "}": {
r = o, e.pop();
break;
}
}
break;
}
case "INSIDE_OBJECT_AFTER_COMMA": {
switch (n) {
case '"': {
e.pop(), e.push("INSIDE_OBJECT_KEY");
break;
}
}
break;
}
case "INSIDE_OBJECT_KEY": {
switch (n) {
case '"': {
e.pop(), e.push("INSIDE_OBJECT_AFTER_KEY");
break;
}
}
break;
}
case "INSIDE_OBJECT_AFTER_KEY": {
switch (n) {
case ":": {
e.pop(), e.push("INSIDE_OBJECT_BEFORE_VALUE");
break;
}
}
break;
}
case "INSIDE_OBJECT_BEFORE_VALUE": {
i(n, o, "INSIDE_OBJECT_AFTER_VALUE");
break;
}
case "INSIDE_OBJECT_AFTER_VALUE": {
c(n, o);
break;
}
case "INSIDE_STRING": {
switch (n) {
case '"': {
e.pop(), r = o;
break;
}
case "\\": {
e.push("INSIDE_STRING_ESCAPE");
break;
}
default:
r = o;
}
break;
}
case "INSIDE_ARRAY_START": {
switch (n) {
case "]": {
r = o, e.pop();
break;
}
default: {
r = o, i(n, o, "INSIDE_ARRAY_AFTER_VALUE");
break;
}
}
break;
}
case "INSIDE_ARRAY_AFTER_VALUE": {
switch (n) {
case ",": {
e.pop(), e.push("INSIDE_ARRAY_AFTER_COMMA");
break;
}
case "]": {
r = o, e.pop();
break;
}
default: {
r = o;
break;
}
}
break;
}
case "INSIDE_ARRAY_AFTER_COMMA": {
i(n, o, "INSIDE_ARRAY_AFTER_VALUE");
break;
}
case "INSIDE_STRING_ESCAPE": {
e.pop(), r = o;
break;
}
case "INSIDE_NUMBER": {
switch (n) {
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9": {
r = o;
break;
}
case "e":
case "E":
case "-":
case ".":
break;
case ",": {
e.pop(), e[e.length - 1] === "INSIDE_ARRAY_AFTER_VALUE" && u(n, o), e[e.length - 1] === "INSIDE_OBJECT_AFTER_VALUE" && c(n, o);
break;
}
case "}": {
e.pop(), e[e.length - 1] === "INSIDE_OBJECT_AFTER_VALUE" && c(n, o);
break;
}
case "]": {
e.pop(), e[e.length - 1] === "INSIDE_ARRAY_AFTER_VALUE" && u(n, o);
break;
}
default: {
e.pop();
break;
}
}
break;
}
case "INSIDE_LITERAL": {
const l = t.substring(s, o + 1);
!"false".startsWith(l) && !"true".startsWith(l) && !"null".startsWith(l) ? (e.pop(), e[e.length - 1] === "INSIDE_OBJECT_AFTER_VALUE" ? c(n, o) : e[e.length - 1] === "INSIDE_ARRAY_AFTER_VALUE" && u(n, o)) : r = o;
break;
}
}
}
let p = t.slice(0, r + 1);
for (let o = e.length - 1; o >= 0; o--)
switch (e[o]) {
case "INSIDE_STRING": {
p += '"';
break;
}
case "INSIDE_OBJECT_KEY":
case "INSIDE_OBJECT_AFTER_KEY":
case "INSIDE_OBJECT_AFTER_COMMA":
case "INSIDE_OBJECT_START":
case "INSIDE_OBJECT_BEFORE_VALUE":
case "INSIDE_OBJECT_AFTER_VALUE": {
p += "}";
break;
}
case "INSIDE_ARRAY_START":
case "INSIDE_ARRAY_AFTER_COMMA":
case "INSIDE_ARRAY_AFTER_VALUE": {
p += "]";
break;
}
case "INSIDE_LITERAL": {
const I = t.substring(s, t.length);
"true".startsWith(I) ? p += "true".slice(I.length) : "false".startsWith(I) ? p += "false".slice(I.length) : "null".startsWith(I) && (p += "null".slice(I.length));
}
}
return p;
}
function V(t) {
if (t === void 0)
return { value: void 0, state: "undefined-input" };
let e = P({ text: t });
return e.success ? { value: e.value, state: "successful-parse" } : (e = P({ text: U(t) }), e.success ? { value: e.value, state: "repaired-parse" } : { value: void 0, state: "failed-parse" });
}
var Y = {
code: "0",
name: "text",
parse: (t) => {
if (typeof t != "string")
throw new Error('"text" parts expect a string value.');
return { type: "text", value: t };
}
}, v = {
code: "2",
name: "data",
parse: (t) => {
if (!Array.isArray(t))
throw new Error('"data" parts expect an array value.');
return { type: "data", value: t };
}
}, j = {
code: "3",
name: "error",
parse: (t) => {
if (typeof t != "string")
throw new Error('"error" parts expect a string value.');
return { type: "error", value: t };
}
}, W = {
code: "8",
name: "message_annotations",
parse: (t) => {
if (!Array.isArray(t))
throw new Error('"message_annotations" parts expect an array value.');
return { type: "message_annotations", value: t };
}
}, K = {
code: "9",
name: "tool_call",
parse: (t) => {
if (t == null || typeof t != "object" || !("toolCallId" in t) || typeof t.toolCallId != "string" || !("toolName" in t) || typeof t.toolName != "string" || !("args" in t) || typeof t.args != "object")
throw new Error(
'"tool_call" parts expect an object with a "toolCallId", "toolName", and "args" property.'
);
return {
type: "tool_call",
value: t
};
}
}, G = {
code: "a",
name: "tool_result",
parse: (t) => {
if (t == null || typeof t != "object" || !("toolCallId" in t) || typeof t.toolCallId != "string" || !("result" in t))
throw new Error(
'"tool_result" parts expect an object with a "toolCallId" and a "result" property.'
);
return {
type: "tool_result",
value: t
};
}
}, $ = {
code: "b",
name: "tool_call_streaming_start",
parse: (t) => {
if (t == null || typeof t != "object" || !("toolCallId" in t) || typeof t.toolCallId != "string" || !("toolName" in t) || typeof t.toolName != "string")
throw new Error(
'"tool_call_streaming_start" parts expect an object with a "toolCallId" and "toolName" property.'
);
return {
type: "tool_call_streaming_start",
value: t
};
}
}, q = {
code: "c",
name: "tool_call_delta",
parse: (t) => {
if (t == null || typeof t != "object" || !("toolCallId" in t) || typeof t.toolCallId != "string" || !("argsTextDelta" in t) || typeof t.argsTextDelta != "string")
throw new Error(
'"tool_call_delta" parts expect an object with a "toolCallId" and "argsTextDelta" property.'
);
return {
type: "tool_call_delta",
value: t
};
}
}, H = {
code: "d",
name: "finish_message",
parse: (t) => {
if (t == null || typeof t != "object" || !("finishReason" in t) || typeof t.finishReason != "string")
throw new Error(
'"finish_message" parts expect an object with a "finishReason" property.'
);
const e = {
finishReason: t.finishReason
};
return "usage" in t && t.usage != null && typeof t.usage == "object" && "promptTokens" in t.usage && "completionTokens" in t.usage && (e.usage = {
promptTokens: typeof t.usage.promptTokens == "number" ? t.usage.promptTokens : Number.NaN,
completionTokens: typeof t.usage.completionTokens == "number" ? t.usage.completionTokens : Number.NaN
}), {
type: "finish_message",
value: e
};
}
}, z = {
code: "e",
name: "finish_step",
parse: (t) => {
if (t == null || typeof t != "object" || !("finishReason" in t) || typeof t.finishReason != "string")
throw new Error(
'"finish_step" parts expect an object with a "finishReason" property.'
);
const e = {
finishReason: t.finishReason,
isContinued: !1
};
return "usage" in t && t.usage != null && typeof t.usage == "object" && "promptTokens" in t.usage && "completionTokens" in t.usage && (e.usage = {
promptTokens: typeof t.usage.promptTokens == "number" ? t.usage.promptTokens : Number.NaN,
completionTokens: typeof t.usage.completionTokens == "number" ? t.usage.completionTokens : Number.NaN
}), "isContinued" in t && typeof t.isContinued == "boolean" && (e.isContinued = t.isContinued), {
type: "finish_step",
value: e
};
}
}, Q = {
code: "f",
name: "start_step",
parse: (t) => {
if (t == null || typeof t != "object" || !("messageId" in t) || typeof t.messageId != "string")
throw new Error(
'"start_step" parts expect an object with an "id" property.'
);
return {
type: "start_step",
value: {
messageId: t.messageId
}
};
}
}, X = {
code: "g",
name: "reasoning",
parse: (t) => {
if (typeof t != "string")
throw new Error('"reasoning" parts expect a string value.');
return { type: "reasoning", value: t };
}
}, Z = {
code: "h",
name: "source",
parse: (t) => {
if (t == null || typeof t != "object")
throw new Error('"source" parts expect a Source object.');
return {
type: "source",
value: t
};
}
}, tt = {
code: "i",
name: "redacted_reasoning",
parse: (t) => {
if (t == null || typeof t != "object" || !("data" in t) || typeof t.data != "string")
throw new Error(
'"redacted_reasoning" parts expect an object with a "data" property.'
);
return { type: "redacted_reasoning", value: { data: t.data } };
}
}, et = {
code: "j",
name: "reasoning_signature",
parse: (t) => {
if (t == null || typeof t != "object" || !("signature" in t) || typeof t.signature != "string")
throw new Error(
'"reasoning_signature" parts expect an object with a "signature" property.'
);
return {
type: "reasoning_signature",
value: { signature: t.signature }
};
}
}, at = {
code: "k",
name: "file",
parse: (t) => {
if (t == null || typeof t != "object" || !("data" in t) || typeof t.data != "string" || !("mimeType" in t) || typeof t.mimeType != "string")
throw new Error(
'"file" parts expect an object with a "data" and "mimeType" property.'
);
return { type: "file", value: t };
}
}, O = [
Y,
v,
j,
W,
K,
G,
$,
q,
H,
z,
Q,
X,
Z,
tt,
et,
at
], rt = Object.fromEntries(
O.map((t) => [t.code, t])
);
Object.fromEntries(
O.map((t) => [t.name, t.code])
);
var ot = O.map((t) => t.code), nt = (t) => {
const e = t.indexOf(":");
if (e === -1)
throw new Error("Failed to parse stream string. No separator found.");
const r = t.slice(0, e);
if (!ot.includes(r))
throw new Error(`Failed to parse stream string. Invalid code ${r}.`);
const s = r, i = t.slice(e + 1), c = JSON.parse(i);
return rt[s].parse(c);
}, st = 10;
function it(t, e) {
const r = new Uint8Array(e);
let s = 0;
for (const i of t)
r.set(i, s), s += i.length;
return t.length = 0, r;
}
async function lt({
stream: t,
onTextPart: e,
onReasoningPart: r,
onReasoningSignaturePart: s,
onRedactedReasoningPart: i,
onSourcePart: c,
onFilePart: u,
onDataPart: p,
onErrorPart: o,
onToolCallStreamingStartPart: n,
onToolCallDeltaPart: I,
onToolCallPart: l,
onToolResultPart: w,
onMessageAnnotationsPart: E,
onFinishMessagePart: y,
onFinishStepPart: T,
onStartStepPart: m
}) {
const g = t.getReader(), A = new TextDecoder(), b = [];
let k = 0;
for (; ; ) {
const { value: _ } = await g.read();
if (_ && (b.push(_), k += _.length, _[_.length - 1] !== st))
continue;
if (b.length === 0)
break;
const a = it(b, k);
k = 0;
const d = A.decode(a, { stream: !0 }).split(`
`).filter((h) => h !== "").map(nt);
for (const { type: h, value: f } of d)
switch (h) {
case "text":
await (e == null ? void 0 : e(f));
break;
case "reasoning":
await (r == null ? void 0 : r(f));
break;
case "reasoning_signature":
await (s == null ? void 0 : s(f));
break;
case "redacted_reasoning":
await (i == null ? void 0 : i(f));
break;
case "file":
await (u == null ? void 0 : u(f));
break;
case "source":
await (c == null ? void 0 : c(f));
break;
case "data":
await (p == null ? void 0 : p(f));
break;
case "error":
await (o == null ? void 0 : o(f));
break;
case "message_annotations":
await (E == null ? void 0 : E(f));
break;
case "tool_call_streaming_start":
await (n == null ? void 0 : n(f));
break;
case "tool_call_delta":
await (I == null ? void 0 : I(f));
break;
case "tool_call":
await (l == null ? void 0 : l(f));
break;
case "tool_result":
await (w == null ? void 0 : w(f));
break;
case "finish_message":
await (y == null ? void 0 : y(f));
break;
case "finish_step":
await (T == null ? void 0 : T(f));
break;
case "start_step":
await (m == null ? void 0 : m(f));
break;
default: {
const D = h;
throw new Error(`Unknown stream part type: ${D}`);
}
}
}
}
async function ct({
stream: t,
update: e,
onToolCall: r,
onFinish: s,
generateId: i = M,
getCurrentDate: c = () => /* @__PURE__ */ new Date(),
lastMessage: u
}) {
var p, o;
const n = (u == null ? void 0 : u.role) === "assistant";
let I = n ? 1 + // find max step in existing tool invocations:
((o = (p = u.toolInvocations) == null ? void 0 : p.reduce((a, d) => {
var h;
return Math.max(a, (h = d.step) != null ? h : 0);
}, 0)) != null ? o : 0) : 0;
const l = n ? structuredClone(u) : {
id: i(),
createdAt: c(),
role: "assistant",
content: "",
parts: []
};
let w, E, y;
function T(a, d) {
const h = l.parts.find(
(f) => f.type === "tool-invocation" && f.toolInvocation.toolCallId === a
);
h != null ? h.toolInvocation = d : l.parts.push({
type: "tool-invocation",
toolInvocation: d
});
}
const m = [];
let g = n ? u == null ? void 0 : u.annotations : void 0;
const A = {};
let b = {
completionTokens: NaN,
promptTokens: NaN,
totalTokens: NaN
}, k = "unknown";
function _() {
const a = [...m];
g != null && g.length && (l.annotations = g);
const d = {
// deep copy the message to ensure that deep changes (msg attachments) are updated
// with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
...structuredClone(l),
// add a revision id to ensure that the message is updated with SWR. SWR uses a
// hashing approach by default to detect changes, but it only works for shallow
// changes. This is why we need to add a revision id to ensure that the message
// is updated with SWR (without it, the changes get stuck in SWR and are not
// forwarded to rendering):
revisionId: i()
};
e({
message: d,
data: a,
replaceLastMessage: n
});
}
await lt({
stream: t,
onTextPart(a) {
w == null ? (w = {
type: "text",
text: a
}, l.parts.push(w)) : w.text += a, l.content += a, _();
},
onReasoningPart(a) {
var d;
y == null ? (y = { type: "text", text: a }, E != null && E.details.push(y)) : y.text += a, E == null ? (E = {
type: "reasoning",
reasoning: a,
details: [y]
}, l.parts.push(E)) : E.reasoning += a, l.reasoning = ((d = l.reasoning) != null ? d : "") + a, _();
},
onReasoningSignaturePart(a) {
y != null && (y.signature = a.signature);
},
onRedactedReasoningPart(a) {
E == null && (E = {
type: "reasoning",
reasoning: "",
details: []
}, l.parts.push(E)), E.details.push({
type: "redacted",
data: a.data
}), y = void 0, _();
},
onFilePart(a) {
l.parts.push({
type: "file",
mimeType: a.mimeType,
data: a.data
}), _();
},
onSourcePart(a) {
l.parts.push({
type: "source",
source: a
}), _();
},
onToolCallStreamingStartPart(a) {
l.toolInvocations == null && (l.toolInvocations = []), A[a.toolCallId] = {
text: "",
step: I,
toolName: a.toolName,
index: l.toolInvocations.length
};
const d = {
state: "partial-call",
step: I,
toolCallId: a.toolCallId,
toolName: a.toolName,
args: void 0
};
l.toolInvocations.push(d), T(a.toolCallId, d), _();
},
onToolCallDeltaPart(a) {
const d = A[a.toolCallId];
d.text += a.argsTextDelta;
const { value: h } = V(d.text), f = {
state: "partial-call",
step: d.step,
toolCallId: a.toolCallId,
toolName: d.toolName,
args: h
};
l.toolInvocations[d.index] = f, T(a.toolCallId, f), _();
},
async onToolCallPart(a) {
const d = {
state: "call",
step: I,
...a
};
if (A[a.toolCallId] != null ? l.toolInvocations[A[a.toolCallId].index] = d : (l.toolInvocations == null && (l.toolInvocations = []), l.toolInvocations.push(d)), T(a.toolCallId, d), _(), r) {
const h = await r({ toolCall: a });
if (h != null) {
const f = {
state: "result",
step: I,
...a,
result: h
};
l.toolInvocations[l.toolInvocations.length - 1] = f, T(a.toolCallId, f), _();
}
}
},
onToolResultPart(a) {
const d = l.toolInvocations;
if (d == null)
throw new Error("tool_result must be preceded by a tool_call");
const h = d.findIndex(
(D) => D.toolCallId === a.toolCallId
);
if (h === -1)
throw new Error(
"tool_result must be preceded by a tool_call with the same toolCallId"
);
const f = {
...d[h],
state: "result",
...a
};
d[h] = f, T(a.toolCallId, f), _();
},
onDataPart(a) {
m.push(...a), _();
},
onMessageAnnotationsPart(a) {
g == null ? g = [...a] : g.push(...a), _();
},
onFinishStepPart(a) {
I += 1, w = a.isContinued ? w : void 0, E = void 0, y = void 0;
},
onStartStepPart(a) {
n || (l.id = a.messageId), l.parts.push({ type: "step-start" }), _();
},
onFinishMessagePart(a) {
k = a.finishReason, a.usage != null && (b = F(a.usage));
},
onErrorPart(a) {
throw new Error(a);
}
}), s == null || s({ message: l, finishReason: k, usage: b });
}
async function pt({
stream: t,
onTextPart: e
}) {
const r = t.pipeThrough(new TextDecoderStream()).getReader();
for (; ; ) {
const { done: s, value: i } = await r.read();
if (s)
break;
await e(i);
}
}
async function dt({
stream: t,
update: e,
onFinish: r,
getCurrentDate: s = () => /* @__PURE__ */ new Date(),
generateId: i = M
}) {
const c = { type: "text", text: "" }, u = {
id: i(),
createdAt: s(),
role: "assistant",
content: "",
parts: [c]
};
await pt({
stream: t,
onTextPart: (p) => {
u.content += p, c.text += p, e({
message: { ...u },
data: [],
replaceLastMessage: !1
});
}
}), r == null || r(u, {
usage: { completionTokens: NaN, promptTokens: NaN, totalTokens: NaN },
finishReason: "unknown"
});
}
var ft = () => fetch;
async function gt({
api: t,
body: e,
streamProtocol: r = "data",
credentials: s,
headers: i,
abortController: c,
restoreMessagesOnFailure: u,
onResponse: p,
onUpdate: o,
onFinish: n,
onToolCall: I,
generateId: l,
fetch: w = ft(),
lastMessage: E
}) {
var y, T;
const m = await w(t, {
method: "POST",
body: JSON.stringify(e),
headers: {
"Content-Type": "application/json",
...i
},
signal: (y = c == null ? void 0 : c()) == null ? void 0 : y.signal,
credentials: s
}).catch((g) => {
throw u(), g;
});
if (p)
try {
await p(m);
} catch (g) {
throw g;
}
if (!m.ok)
throw u(), new Error(
(T = await m.text()) != null ? T : "Failed to fetch the chat response."
);
if (!m.body)
throw new Error("The response body is empty.");
switch (r) {
case "text": {
await dt({
stream: m.body,
update: o,
onFinish: n,
generateId: l
});
return;
}
case "data": {
await ct({
stream: m.body,
update: o,
lastMessage: E,
onToolCall: I,
onFinish({ message: g, finishReason: A, usage: b }) {
n && g != null && n(g, { usage: b, finishReason: A });
},
generateId: l
});
return;
}
default: {
const g = r;
throw new Error(`Unknown stream protocol: ${g}`);
}
}
}
function L(t) {
return t == null ? void 0 : t.reduce((e, r) => {
var s;
return Math.max(e, (s = r.step) != null ? s : 0);
}, 0);
}
function ut(t) {
var e;
return (e = t.parts) != null ? e : [
...t.toolInvocations ? t.toolInvocations.map((r) => ({
type: "tool-invocation",
toolInvocation: r
})) : [],
...t.reasoning ? [
{
type: "reasoning",
reasoning: t.reasoning,
details: [{ type: "text", text: t.reasoning }]
}
] : [],
...t.content ? [{ type: "text", text: t.content }] : []
];
}
function Et(t) {
return t.map((e) => ({
...e,
parts: ut(e)
}));
}
function B(t, e) {
if (t === e)
return !0;
if (t == null || e == null)
return !1;
if (typeof t != "object" && typeof e != "object")
return t === e;
if (t.constructor !== e.constructor)
return !1;
if (t instanceof Date && e instanceof Date)
return t.getTime() === e.getTime();
if (Array.isArray(t)) {
if (t.length !== e.length)
return !1;
for (let i = 0; i < t.length; i++)
if (!B(t[i], e[i]))
return !1;
return !0;
}
const r = Object.keys(t), s = Object.keys(e);
if (r.length !== s.length)
return !1;
for (const i of r)
if (!s.includes(i) || !B(t[i], e[i]))
return !1;
return !0;
}
async function yt(t) {
if (!t)
return [];
if (t instanceof FileList)
return Promise.all(
Array.from(t).map(async (e) => {
const { name: r, type: s } = e, i = await new Promise((c, u) => {
const p = new FileReader();
p.onload = (o) => {
var n;
c((n = o.target) == null ? void 0 : n.result);
}, p.onerror = (o) => u(o), p.readAsDataURL(e);
});
return {
name: r,
contentType: s,
url: i
};
})
);
if (Array.isArray(t))
return t;
throw new Error("Invalid attachments type");
}
function mt({
originalMaxToolInvocationStep: t,
originalMessageCount: e,
maxSteps: r,
messages: s
}) {
var i;
const c = s[s.length - 1];
return (
// check if the feature is enabled:
r > 1 && // ensure there is a last message:
c != null && // ensure we actually have new steps (to prevent infinite loops in case of errors):
(s.length > e || L(c.toolInvocations) !== t) && // check that next step is possible:
It(c) && // limit the number of automatic steps:
((i = L(c.toolInvocations)) != null ? i : 0) < r
);
}
function It(t) {
if (t.role !== "assistant")
return !1;
const e = t.parts.reduce((s, i, c) => i.type === "step-start" ? c : s, -1), r = t.parts.slice(e + 1).filter((s) => s.type === "tool-invocation");
return r.length > 0 && r.every((s) => "result" in s.toolInvocation);
}
function wt({
messages: t,
toolCallId: e,
toolResult: r
}) {
var s;
const i = t[t.length - 1], c = i.parts.find(
(p) => p.type === "tool-invocation" && p.toolInvocation.toolCallId === e
);
if (c == null)
return;
const u = {
...c.toolInvocation,
state: "result",
result: r
};
c.toolInvocation = u, i.toolInvocations = (s = i.toolInvocations) == null ? void 0 : s.map(
(p) => p.toolCallId === e ? u : p
);
}
export {
gt as callChatApi,
L as extractMaxToolInvocationStep,
Et as fillMessageParts,
M as generateId,
ut as getMessageParts,
It as isAssistantMessageWithCompletedToolCalls,
B as isDeepEqualData,
nt as parseDataStreamPart,
V as parsePartialJson,
yt as prepareAttachmentsForRequest,
lt as processDataStream,
pt as processTextStream,
mt as shouldResubmitMessages,
wt as updateToolCallResult
};