@xpert-ai/chatkit-types 0.0.3 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,798 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+ var _a;
5
+ var __defProp2 = Object.defineProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all) __defProp2(target, name, {
8
+ get: all[name],
9
+ enumerable: true
10
+ });
11
+ };
12
+ function getDefaultExportFromCjs(x) {
13
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
14
+ }
15
+ var decamelize = function(str, sep) {
16
+ if (typeof str !== "string") {
17
+ throw new TypeError("Expected a string");
18
+ }
19
+ sep = typeof sep === "undefined" ? "_" : sep;
20
+ return str.replace(/([a-z\d])([A-Z])/g, "$1" + sep + "$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g, "$1" + sep + "$2").toLowerCase();
21
+ };
22
+ const snakeCase = /* @__PURE__ */ getDefaultExportFromCjs(decamelize);
23
+ var camelcase = { exports: {} };
24
+ const UPPERCASE = /[\p{Lu}]/u;
25
+ const LOWERCASE = /[\p{Ll}]/u;
26
+ const LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu;
27
+ const IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u;
28
+ const SEPARATORS = /[_.\- ]+/;
29
+ const LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source);
30
+ const SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu");
31
+ const NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu");
32
+ const preserveCamelCase = (string, toLowerCase, toUpperCase) => {
33
+ let isLastCharLower = false;
34
+ let isLastCharUpper = false;
35
+ let isLastLastCharUpper = false;
36
+ for (let i = 0; i < string.length; i++) {
37
+ const character = string[i];
38
+ if (isLastCharLower && UPPERCASE.test(character)) {
39
+ string = string.slice(0, i) + "-" + string.slice(i);
40
+ isLastCharLower = false;
41
+ isLastLastCharUpper = isLastCharUpper;
42
+ isLastCharUpper = true;
43
+ i++;
44
+ } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) {
45
+ string = string.slice(0, i - 1) + "-" + string.slice(i - 1);
46
+ isLastLastCharUpper = isLastCharUpper;
47
+ isLastCharUpper = false;
48
+ isLastCharLower = true;
49
+ } else {
50
+ isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character;
51
+ isLastLastCharUpper = isLastCharUpper;
52
+ isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character;
53
+ }
54
+ }
55
+ return string;
56
+ };
57
+ const preserveConsecutiveUppercase = (input, toLowerCase) => {
58
+ LEADING_CAPITAL.lastIndex = 0;
59
+ return input.replace(LEADING_CAPITAL, (m1) => toLowerCase(m1));
60
+ };
61
+ const postProcess = (input, toUpperCase) => {
62
+ SEPARATORS_AND_IDENTIFIER.lastIndex = 0;
63
+ NUMBERS_AND_IDENTIFIER.lastIndex = 0;
64
+ return input.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) => toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER, (m) => toUpperCase(m));
65
+ };
66
+ const camelCase = (input, options) => {
67
+ if (!(typeof input === "string" || Array.isArray(input))) {
68
+ throw new TypeError("Expected the input to be `string | string[]`");
69
+ }
70
+ options = {
71
+ pascalCase: false,
72
+ preserveConsecutiveUppercase: false,
73
+ ...options
74
+ };
75
+ if (Array.isArray(input)) {
76
+ input = input.map((x) => x.trim()).filter((x) => x.length).join("-");
77
+ } else {
78
+ input = input.trim();
79
+ }
80
+ if (input.length === 0) {
81
+ return "";
82
+ }
83
+ const toLowerCase = options.locale === false ? (string) => string.toLowerCase() : (string) => string.toLocaleLowerCase(options.locale);
84
+ const toUpperCase = options.locale === false ? (string) => string.toUpperCase() : (string) => string.toLocaleUpperCase(options.locale);
85
+ if (input.length === 1) {
86
+ return options.pascalCase ? toUpperCase(input) : toLowerCase(input);
87
+ }
88
+ const hasUpperCase = input !== toLowerCase(input);
89
+ if (hasUpperCase) {
90
+ input = preserveCamelCase(input, toLowerCase, toUpperCase);
91
+ }
92
+ input = input.replace(LEADING_SEPARATORS, "");
93
+ if (options.preserveConsecutiveUppercase) {
94
+ input = preserveConsecutiveUppercase(input, toLowerCase);
95
+ } else {
96
+ input = toLowerCase(input);
97
+ }
98
+ if (options.pascalCase) {
99
+ input = toUpperCase(input.charAt(0)) + input.slice(1);
100
+ }
101
+ return postProcess(input, toUpperCase);
102
+ };
103
+ camelcase.exports = camelCase;
104
+ camelcase.exports.default = camelCase;
105
+ function keyToJson(key, map) {
106
+ return (map == null ? void 0 : map[key]) || snakeCase(key);
107
+ }
108
+ function mapKeys(fields, mapper, map) {
109
+ const mapped = {};
110
+ for (const key in fields) if (Object.hasOwn(fields, key)) mapped[mapper(key, map)] = fields[key];
111
+ return mapped;
112
+ }
113
+ var serializable_exports = {};
114
+ __export(serializable_exports, {
115
+ Serializable: () => Serializable,
116
+ get_lc_unique_name: () => get_lc_unique_name
117
+ });
118
+ function shallowCopy(obj) {
119
+ return Array.isArray(obj) ? [...obj] : { ...obj };
120
+ }
121
+ function replaceSecrets(root, secretsMap) {
122
+ const result = shallowCopy(root);
123
+ for (const [path, secretId] of Object.entries(secretsMap)) {
124
+ const [last, ...partsReverse] = path.split(".").reverse();
125
+ let current = result;
126
+ for (const part of partsReverse.reverse()) {
127
+ if (current[part] === void 0) break;
128
+ current[part] = shallowCopy(current[part]);
129
+ current = current[part];
130
+ }
131
+ if (current[last] !== void 0) current[last] = {
132
+ lc: 1,
133
+ type: "secret",
134
+ id: [secretId]
135
+ };
136
+ }
137
+ return result;
138
+ }
139
+ function get_lc_unique_name(serializableClass) {
140
+ const parentClass = Object.getPrototypeOf(serializableClass);
141
+ const lcNameIsSubclassed = typeof serializableClass.lc_name === "function" && (typeof parentClass.lc_name !== "function" || serializableClass.lc_name() !== parentClass.lc_name());
142
+ if (lcNameIsSubclassed) return serializableClass.lc_name();
143
+ else return serializableClass.name;
144
+ }
145
+ var Serializable = class Serializable2 {
146
+ constructor(kwargs, ..._args) {
147
+ __publicField(this, "lc_serializable", false);
148
+ __publicField(this, "lc_kwargs");
149
+ if (this.lc_serializable_keys !== void 0) this.lc_kwargs = Object.fromEntries(Object.entries(kwargs || {}).filter(([key]) => {
150
+ var _a2;
151
+ return (_a2 = this.lc_serializable_keys) == null ? void 0 : _a2.includes(key);
152
+ }));
153
+ else this.lc_kwargs = kwargs ?? {};
154
+ }
155
+ /**
156
+ * The name of the serializable. Override to provide an alias or
157
+ * to preserve the serialized module name in minified environments.
158
+ *
159
+ * Implemented as a static method to support loading logic.
160
+ */
161
+ static lc_name() {
162
+ return this.name;
163
+ }
164
+ /**
165
+ * The final serialized identifier for the module.
166
+ */
167
+ get lc_id() {
168
+ return [...this.lc_namespace, get_lc_unique_name(this.constructor)];
169
+ }
170
+ /**
171
+ * A map of secrets, which will be omitted from serialization.
172
+ * Keys are paths to the secret in constructor args, e.g. "foo.bar.baz".
173
+ * Values are the secret ids, which will be used when deserializing.
174
+ */
175
+ get lc_secrets() {
176
+ return void 0;
177
+ }
178
+ /**
179
+ * A map of additional attributes to merge with constructor args.
180
+ * Keys are the attribute names, e.g. "foo".
181
+ * Values are the attribute values, which will be serialized.
182
+ * These attributes need to be accepted by the constructor as arguments.
183
+ */
184
+ get lc_attributes() {
185
+ return void 0;
186
+ }
187
+ /**
188
+ * A map of aliases for constructor args.
189
+ * Keys are the attribute names, e.g. "foo".
190
+ * Values are the alias that will replace the key in serialization.
191
+ * This is used to eg. make argument names match Python.
192
+ */
193
+ get lc_aliases() {
194
+ return void 0;
195
+ }
196
+ /**
197
+ * A manual list of keys that should be serialized.
198
+ * If not overridden, all fields passed into the constructor will be serialized.
199
+ */
200
+ get lc_serializable_keys() {
201
+ return void 0;
202
+ }
203
+ toJSON() {
204
+ if (!this.lc_serializable) return this.toJSONNotImplemented();
205
+ if (this.lc_kwargs instanceof Serializable2 || typeof this.lc_kwargs !== "object" || Array.isArray(this.lc_kwargs)) return this.toJSONNotImplemented();
206
+ const aliases = {};
207
+ const secrets = {};
208
+ const kwargs = Object.keys(this.lc_kwargs).reduce((acc, key) => {
209
+ acc[key] = key in this ? this[key] : this.lc_kwargs[key];
210
+ return acc;
211
+ }, {});
212
+ for (let current = Object.getPrototypeOf(this); current; current = Object.getPrototypeOf(current)) {
213
+ Object.assign(aliases, Reflect.get(current, "lc_aliases", this));
214
+ Object.assign(secrets, Reflect.get(current, "lc_secrets", this));
215
+ Object.assign(kwargs, Reflect.get(current, "lc_attributes", this));
216
+ }
217
+ Object.keys(secrets).forEach((keyPath) => {
218
+ let read = this;
219
+ let write = kwargs;
220
+ const [last, ...partsReverse] = keyPath.split(".").reverse();
221
+ for (const key of partsReverse.reverse()) {
222
+ if (!(key in read) || read[key] === void 0) return;
223
+ if (!(key in write) || write[key] === void 0) {
224
+ if (typeof read[key] === "object" && read[key] != null) write[key] = {};
225
+ else if (Array.isArray(read[key])) write[key] = [];
226
+ }
227
+ read = read[key];
228
+ write = write[key];
229
+ }
230
+ if (last in read && read[last] !== void 0) write[last] = write[last] || read[last];
231
+ });
232
+ return {
233
+ lc: 1,
234
+ type: "constructor",
235
+ id: this.lc_id,
236
+ kwargs: mapKeys(Object.keys(secrets).length ? replaceSecrets(kwargs, secrets) : kwargs, keyToJson, aliases)
237
+ };
238
+ }
239
+ toJSONNotImplemented() {
240
+ return {
241
+ lc: 1,
242
+ type: "not_implemented",
243
+ id: this.lc_id
244
+ };
245
+ }
246
+ };
247
+ function isDataContentBlock(content_block) {
248
+ return typeof content_block === "object" && content_block !== null && "type" in content_block && typeof content_block.type === "string" && "source_type" in content_block && (content_block.source_type === "url" || content_block.source_type === "base64" || content_block.source_type === "text" || content_block.source_type === "id");
249
+ }
250
+ function isURLContentBlock(content_block) {
251
+ return isDataContentBlock(content_block) && content_block.source_type === "url" && "url" in content_block && typeof content_block.url === "string";
252
+ }
253
+ function isBase64ContentBlock(content_block) {
254
+ return isDataContentBlock(content_block) && content_block.source_type === "base64" && "data" in content_block && typeof content_block.data === "string";
255
+ }
256
+ function isIDContentBlock(content_block) {
257
+ return isDataContentBlock(content_block) && content_block.source_type === "id" && "id" in content_block && typeof content_block.id === "string";
258
+ }
259
+ function parseBase64DataUrl({ dataUrl: data_url, asTypedArray = false }) {
260
+ const formatMatch = data_url.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);
261
+ let mime_type;
262
+ if (formatMatch) {
263
+ mime_type = formatMatch[1].toLowerCase();
264
+ const data = asTypedArray ? Uint8Array.from(atob(formatMatch[2]), (c) => c.charCodeAt(0)) : formatMatch[2];
265
+ return {
266
+ mime_type,
267
+ data
268
+ };
269
+ }
270
+ return void 0;
271
+ }
272
+ function _isContentBlock(block, type) {
273
+ return _isObject(block) && block.type === type;
274
+ }
275
+ function _isObject(value) {
276
+ return typeof value === "object" && value !== null;
277
+ }
278
+ function _isString(value) {
279
+ return typeof value === "string";
280
+ }
281
+ function convertToV1FromAnthropicContentBlock(block) {
282
+ if (_isContentBlock(block, "document") && _isObject(block.source) && "type" in block.source) {
283
+ if (block.source.type === "base64" && _isString(block.source.media_type) && _isString(block.source.data)) return {
284
+ type: "file",
285
+ mimeType: block.source.media_type,
286
+ data: block.source.data
287
+ };
288
+ else if (block.source.type === "url" && _isString(block.source.url)) return {
289
+ type: "file",
290
+ url: block.source.url
291
+ };
292
+ else if (block.source.type === "file" && _isString(block.source.file_id)) return {
293
+ type: "file",
294
+ fileId: block.source.file_id
295
+ };
296
+ else if (block.source.type === "text" && _isString(block.source.data)) return {
297
+ type: "file",
298
+ mimeType: String(block.source.media_type ?? "text/plain"),
299
+ data: block.source.data
300
+ };
301
+ } else if (_isContentBlock(block, "image") && _isObject(block.source) && "type" in block.source) {
302
+ if (block.source.type === "base64" && _isString(block.source.media_type) && _isString(block.source.data)) return {
303
+ type: "image",
304
+ mimeType: block.source.media_type,
305
+ data: block.source.data
306
+ };
307
+ else if (block.source.type === "url" && _isString(block.source.url)) return {
308
+ type: "image",
309
+ url: block.source.url
310
+ };
311
+ else if (block.source.type === "file" && _isString(block.source.file_id)) return {
312
+ type: "image",
313
+ fileId: block.source.file_id
314
+ };
315
+ }
316
+ return void 0;
317
+ }
318
+ function convertToV1FromAnthropicInput(content) {
319
+ function* iterateContent() {
320
+ for (const block of content) {
321
+ const stdBlock = convertToV1FromAnthropicContentBlock(block);
322
+ if (stdBlock) yield stdBlock;
323
+ else yield block;
324
+ }
325
+ }
326
+ return Array.from(iterateContent());
327
+ }
328
+ function convertToV1FromDataContentBlock(block) {
329
+ if (isURLContentBlock(block)) return {
330
+ type: block.type,
331
+ mimeType: block.mime_type,
332
+ url: block.url,
333
+ metadata: block.metadata
334
+ };
335
+ if (isBase64ContentBlock(block)) return {
336
+ type: block.type,
337
+ mimeType: block.mime_type ?? "application/octet-stream",
338
+ data: block.data,
339
+ metadata: block.metadata
340
+ };
341
+ if (isIDContentBlock(block)) return {
342
+ type: block.type,
343
+ mimeType: block.mime_type,
344
+ fileId: block.id,
345
+ metadata: block.metadata
346
+ };
347
+ return block;
348
+ }
349
+ function convertToV1FromDataContent(content) {
350
+ return content.map(convertToV1FromDataContentBlock);
351
+ }
352
+ function isOpenAIDataBlock(block) {
353
+ if (_isContentBlock(block, "image_url") && _isObject(block.image_url)) return true;
354
+ if (_isContentBlock(block, "input_audio") && _isObject(block.input_audio)) return true;
355
+ if (_isContentBlock(block, "file") && _isObject(block.file)) return true;
356
+ return false;
357
+ }
358
+ function convertToV1FromOpenAIDataBlock(block) {
359
+ if (_isContentBlock(block, "image_url") && _isObject(block.image_url) && _isString(block.image_url.url)) {
360
+ const parsed = parseBase64DataUrl({ dataUrl: block.image_url.url });
361
+ if (parsed) return {
362
+ type: "image",
363
+ mimeType: parsed.mime_type,
364
+ data: parsed.data
365
+ };
366
+ else return {
367
+ type: "image",
368
+ url: block.image_url.url
369
+ };
370
+ } else if (_isContentBlock(block, "input_audio") && _isObject(block.input_audio) && _isString(block.input_audio.data) && _isString(block.input_audio.format)) return {
371
+ type: "audio",
372
+ data: block.input_audio.data,
373
+ mimeType: `audio/${block.input_audio.format}`
374
+ };
375
+ else if (_isContentBlock(block, "file") && _isObject(block.file) && _isString(block.file.data)) {
376
+ const parsed = parseBase64DataUrl({ dataUrl: block.file.data });
377
+ if (parsed) return {
378
+ type: "file",
379
+ data: parsed.data,
380
+ mimeType: parsed.mime_type
381
+ };
382
+ else if (_isString(block.file.file_id)) return {
383
+ type: "file",
384
+ fileId: block.file.file_id
385
+ };
386
+ }
387
+ return block;
388
+ }
389
+ function convertToV1FromChatCompletionsInput(blocks) {
390
+ const convertedBlocks = [];
391
+ for (const block of blocks) if (isOpenAIDataBlock(block)) convertedBlocks.push(convertToV1FromOpenAIDataBlock(block));
392
+ else convertedBlocks.push(block);
393
+ return convertedBlocks;
394
+ }
395
+ function isMessage(message) {
396
+ return typeof message === "object" && message !== null && "type" in message && "content" in message && (typeof message.content === "string" || Array.isArray(message.content));
397
+ }
398
+ function convertToFormattedString(message, format = "pretty") {
399
+ if (format === "pretty") return convertToPrettyString(message);
400
+ return JSON.stringify(message);
401
+ }
402
+ function convertToPrettyString(message) {
403
+ const lines = [];
404
+ const title = ` ${message.type.charAt(0).toUpperCase() + message.type.slice(1)} Message `;
405
+ const sepLen = Math.floor((80 - title.length) / 2);
406
+ const sep = "=".repeat(sepLen);
407
+ const secondSep = title.length % 2 === 0 ? sep : `${sep}=`;
408
+ lines.push(`${sep}${title}${secondSep}`);
409
+ if (message.type === "ai") {
410
+ const aiMessage = message;
411
+ if (aiMessage.tool_calls && aiMessage.tool_calls.length > 0) {
412
+ lines.push("Tool Calls:");
413
+ for (const tc of aiMessage.tool_calls) {
414
+ lines.push(` ${tc.name} (${tc.id})`);
415
+ lines.push(` Call ID: ${tc.id}`);
416
+ lines.push(" Args:");
417
+ for (const [key, value] of Object.entries(tc.args)) lines.push(` ${key}: ${typeof value === "object" ? JSON.stringify(value) : value}`);
418
+ }
419
+ }
420
+ }
421
+ if (message.type === "tool") {
422
+ const toolMessage = message;
423
+ if (toolMessage.name) lines.push(`Name: ${toolMessage.name}`);
424
+ }
425
+ if (typeof message.content === "string" && message.content.trim()) {
426
+ if (lines.length > 1) lines.push("");
427
+ lines.push(message.content);
428
+ }
429
+ return lines.join("\n");
430
+ }
431
+ const MESSAGE_SYMBOL = Symbol.for("langchain.message");
432
+ function mergeContent(firstContent, secondContent) {
433
+ if (typeof firstContent === "string") {
434
+ if (firstContent === "") return secondContent;
435
+ if (typeof secondContent === "string") return firstContent + secondContent;
436
+ else if (Array.isArray(secondContent) && secondContent.length === 0) return firstContent;
437
+ else if (Array.isArray(secondContent) && secondContent.some((c) => isDataContentBlock(c))) return [{
438
+ type: "text",
439
+ source_type: "text",
440
+ text: firstContent
441
+ }, ...secondContent];
442
+ else return [{
443
+ type: "text",
444
+ text: firstContent
445
+ }, ...secondContent];
446
+ } else if (Array.isArray(secondContent)) return _mergeLists(firstContent, secondContent) ?? [...firstContent, ...secondContent];
447
+ else if (secondContent === "") return firstContent;
448
+ else if (Array.isArray(firstContent) && firstContent.some((c) => isDataContentBlock(c))) return [...firstContent, {
449
+ type: "file",
450
+ source_type: "text",
451
+ text: secondContent
452
+ }];
453
+ else return [...firstContent, {
454
+ type: "text",
455
+ text: secondContent
456
+ }];
457
+ }
458
+ function _mergeStatus(left, right) {
459
+ if (left === "error" || right === "error") return "error";
460
+ return "success";
461
+ }
462
+ function stringifyWithDepthLimit(obj, depthLimit) {
463
+ function helper(obj$1, currentDepth) {
464
+ if (typeof obj$1 !== "object" || obj$1 === null || obj$1 === void 0) return obj$1;
465
+ if (currentDepth >= depthLimit) {
466
+ if (Array.isArray(obj$1)) return "[Array]";
467
+ return "[Object]";
468
+ }
469
+ if (Array.isArray(obj$1)) return obj$1.map((item) => helper(item, currentDepth + 1));
470
+ const result = {};
471
+ for (const key of Object.keys(obj$1)) result[key] = helper(obj$1[key], currentDepth + 1);
472
+ return result;
473
+ }
474
+ return JSON.stringify(helper(obj, 0), null, 2);
475
+ }
476
+ var BaseMessage = class extends Serializable {
477
+ constructor(arg) {
478
+ const fields = typeof arg === "string" || Array.isArray(arg) ? { content: arg } : arg;
479
+ if (!fields.additional_kwargs) fields.additional_kwargs = {};
480
+ if (!fields.response_metadata) fields.response_metadata = {};
481
+ super(fields);
482
+ __publicField(this, "lc_namespace", ["langchain_core", "messages"]);
483
+ __publicField(this, "lc_serializable", true);
484
+ __publicField(this, _a, true);
485
+ __publicField(this, "id");
486
+ __publicField(this, "name");
487
+ __publicField(this, "content");
488
+ __publicField(this, "additional_kwargs");
489
+ __publicField(this, "response_metadata");
490
+ this.name = fields.name;
491
+ if (fields.content === void 0 && fields.contentBlocks !== void 0) {
492
+ this.content = fields.contentBlocks;
493
+ this.response_metadata = {
494
+ output_version: "v1",
495
+ ...fields.response_metadata
496
+ };
497
+ } else if (fields.content !== void 0) {
498
+ this.content = fields.content ?? [];
499
+ this.response_metadata = fields.response_metadata;
500
+ } else {
501
+ this.content = [];
502
+ this.response_metadata = fields.response_metadata;
503
+ }
504
+ this.additional_kwargs = fields.additional_kwargs;
505
+ this.id = fields.id;
506
+ }
507
+ get lc_aliases() {
508
+ return {
509
+ additional_kwargs: "additional_kwargs",
510
+ response_metadata: "response_metadata"
511
+ };
512
+ }
513
+ /**
514
+ * @deprecated Use .getType() instead or import the proper typeguard.
515
+ * For example:
516
+ *
517
+ * ```ts
518
+ * import { isAIMessage } from "@langchain/core/messages";
519
+ *
520
+ * const message = new AIMessage("Hello!");
521
+ * isAIMessage(message); // true
522
+ * ```
523
+ */
524
+ _getType() {
525
+ return this.type;
526
+ }
527
+ /**
528
+ * @deprecated Use .type instead
529
+ * The type of the message.
530
+ */
531
+ getType() {
532
+ return this._getType();
533
+ }
534
+ /** Get text content of the message. */
535
+ get text() {
536
+ if (typeof this.content === "string") return this.content;
537
+ if (!Array.isArray(this.content)) return "";
538
+ return this.content.map((c) => {
539
+ if (typeof c === "string") return c;
540
+ if (c.type === "text") return c.text;
541
+ return "";
542
+ }).join("");
543
+ }
544
+ get contentBlocks() {
545
+ const blocks = typeof this.content === "string" ? [{
546
+ type: "text",
547
+ text: this.content
548
+ }] : this.content;
549
+ const parsingSteps = [
550
+ convertToV1FromDataContent,
551
+ convertToV1FromChatCompletionsInput,
552
+ convertToV1FromAnthropicInput
553
+ ];
554
+ const parsedBlocks = parsingSteps.reduce((blocks$1, step) => step(blocks$1), blocks);
555
+ return parsedBlocks;
556
+ }
557
+ toDict() {
558
+ return {
559
+ type: this.getType(),
560
+ data: this.toJSON().kwargs
561
+ };
562
+ }
563
+ static lc_name() {
564
+ return "BaseMessage";
565
+ }
566
+ get _printableFields() {
567
+ return {
568
+ id: this.id,
569
+ content: this.content,
570
+ name: this.name,
571
+ additional_kwargs: this.additional_kwargs,
572
+ response_metadata: this.response_metadata
573
+ };
574
+ }
575
+ static isInstance(obj) {
576
+ return typeof obj === "object" && obj !== null && MESSAGE_SYMBOL in obj && obj[MESSAGE_SYMBOL] === true && isMessage(obj);
577
+ }
578
+ _updateId(value) {
579
+ this.id = value;
580
+ this.lc_kwargs.id = value;
581
+ }
582
+ get [(_a = MESSAGE_SYMBOL, Symbol.toStringTag)]() {
583
+ return this.constructor.lc_name();
584
+ }
585
+ [Symbol.for("nodejs.util.inspect.custom")](depth) {
586
+ if (depth === null) return this;
587
+ const printable = stringifyWithDepthLimit(this._printableFields, Math.max(4, depth));
588
+ return `${this.constructor.lc_name()} ${printable}`;
589
+ }
590
+ toFormattedString(format = "pretty") {
591
+ return convertToFormattedString(this, format);
592
+ }
593
+ };
594
+ function _mergeDicts(left = {}, right = {}) {
595
+ const merged = { ...left };
596
+ for (const [key, value] of Object.entries(right)) if (merged[key] == null) merged[key] = value;
597
+ else if (value == null) continue;
598
+ else if (typeof merged[key] !== typeof value || Array.isArray(merged[key]) !== Array.isArray(value)) throw new Error(`field[${key}] already exists in the message chunk, but with a different type.`);
599
+ else if (typeof merged[key] === "string") if (key === "type") continue;
600
+ else if ([
601
+ "id",
602
+ "name",
603
+ "output_version",
604
+ "model_provider"
605
+ ].includes(key)) {
606
+ if (value) merged[key] = value;
607
+ } else merged[key] += value;
608
+ else if (typeof merged[key] === "object" && !Array.isArray(merged[key])) merged[key] = _mergeDicts(merged[key], value);
609
+ else if (Array.isArray(merged[key])) merged[key] = _mergeLists(merged[key], value);
610
+ else if (merged[key] === value) continue;
611
+ else console.warn(`field[${key}] already exists in this message chunk and value has unsupported type.`);
612
+ return merged;
613
+ }
614
+ function _mergeLists(left, right) {
615
+ if (left === void 0 && right === void 0) return void 0;
616
+ else if (left === void 0 || right === void 0) return left || right;
617
+ else {
618
+ const merged = [...left];
619
+ for (const item of right) if (typeof item === "object" && item !== null && "index" in item && typeof item.index === "number") {
620
+ const toMerge = merged.findIndex((leftItem) => {
621
+ const isObject = typeof leftItem === "object";
622
+ const indiciesMatch = "index" in leftItem && leftItem.index === item.index;
623
+ const idsMatch = "id" in leftItem && "id" in item && (leftItem == null ? void 0 : leftItem.id) === (item == null ? void 0 : item.id);
624
+ const eitherItemMissingID = !("id" in leftItem) || !(leftItem == null ? void 0 : leftItem.id) || !("id" in item) || !(item == null ? void 0 : item.id);
625
+ return isObject && indiciesMatch && (idsMatch || eitherItemMissingID);
626
+ });
627
+ if (toMerge !== -1 && typeof merged[toMerge] === "object" && merged[toMerge] !== null) merged[toMerge] = _mergeDicts(merged[toMerge], item);
628
+ else merged.push(item);
629
+ } else if (typeof item === "object" && item !== null && "text" in item && item.text === "") continue;
630
+ else merged.push(item);
631
+ return merged;
632
+ }
633
+ }
634
+ function _mergeObj(left, right) {
635
+ if (left === void 0 && right === void 0) return void 0;
636
+ if (left === void 0 || right === void 0) return left ?? right;
637
+ else if (typeof left !== typeof right) throw new Error(`Cannot merge objects of different types.
638
+ Left ${typeof left}
639
+ Right ${typeof right}`);
640
+ else if (typeof left === "string" && typeof right === "string") return left + right;
641
+ else if (Array.isArray(left) && Array.isArray(right)) return _mergeLists(left, right);
642
+ else if (typeof left === "object" && typeof right === "object") return _mergeDicts(left, right);
643
+ else if (left === right) return left;
644
+ else throw new Error(`Can not merge objects of different types.
645
+ Left ${left}
646
+ Right ${right}`);
647
+ }
648
+ var BaseMessageChunk = class BaseMessageChunk2 extends BaseMessage {
649
+ static isInstance(obj) {
650
+ if (!super.isInstance(obj)) return false;
651
+ let proto = Object.getPrototypeOf(obj);
652
+ while (proto !== null) {
653
+ if (proto === BaseMessageChunk2.prototype) return true;
654
+ proto = Object.getPrototypeOf(proto);
655
+ }
656
+ return false;
657
+ }
658
+ };
659
+ var tool_exports = {};
660
+ __export(tool_exports, {
661
+ ToolMessage: () => ToolMessage,
662
+ ToolMessageChunk: () => ToolMessageChunk,
663
+ defaultToolCallParser: () => defaultToolCallParser,
664
+ isDirectToolOutput: () => isDirectToolOutput,
665
+ isToolMessage: () => isToolMessage,
666
+ isToolMessageChunk: () => isToolMessageChunk
667
+ });
668
+ function isDirectToolOutput(x) {
669
+ return x != null && typeof x === "object" && "lc_direct_tool_output" in x && x.lc_direct_tool_output === true;
670
+ }
671
+ var ToolMessage = class extends BaseMessage {
672
+ constructor(fields, tool_call_id, name) {
673
+ const toolMessageFields = typeof fields === "string" || Array.isArray(fields) ? {
674
+ content: fields,
675
+ name,
676
+ tool_call_id
677
+ } : fields;
678
+ super(toolMessageFields);
679
+ __publicField(this, "lc_direct_tool_output", true);
680
+ __publicField(this, "type", "tool");
681
+ /**
682
+ * Status of the tool invocation.
683
+ * @version 0.2.19
684
+ */
685
+ __publicField(this, "status");
686
+ __publicField(this, "tool_call_id");
687
+ __publicField(this, "metadata");
688
+ /**
689
+ * Artifact of the Tool execution which is not meant to be sent to the model.
690
+ *
691
+ * Should only be specified if it is different from the message content, e.g. if only
692
+ * a subset of the full tool output is being passed as message content but the full
693
+ * output is needed in other parts of the code.
694
+ */
695
+ __publicField(this, "artifact");
696
+ this.tool_call_id = toolMessageFields.tool_call_id;
697
+ this.artifact = toolMessageFields.artifact;
698
+ this.status = toolMessageFields.status;
699
+ this.metadata = toolMessageFields.metadata;
700
+ }
701
+ static lc_name() {
702
+ return "ToolMessage";
703
+ }
704
+ get lc_aliases() {
705
+ return { tool_call_id: "tool_call_id" };
706
+ }
707
+ static isInstance(message) {
708
+ return super.isInstance(message) && message.type === "tool";
709
+ }
710
+ get _printableFields() {
711
+ return {
712
+ ...super._printableFields,
713
+ tool_call_id: this.tool_call_id,
714
+ artifact: this.artifact
715
+ };
716
+ }
717
+ };
718
+ var ToolMessageChunk = class extends BaseMessageChunk {
719
+ constructor(fields) {
720
+ super(fields);
721
+ __publicField(this, "type", "tool");
722
+ __publicField(this, "tool_call_id");
723
+ /**
724
+ * Status of the tool invocation.
725
+ * @version 0.2.19
726
+ */
727
+ __publicField(this, "status");
728
+ /**
729
+ * Artifact of the Tool execution which is not meant to be sent to the model.
730
+ *
731
+ * Should only be specified if it is different from the message content, e.g. if only
732
+ * a subset of the full tool output is being passed as message content but the full
733
+ * output is needed in other parts of the code.
734
+ */
735
+ __publicField(this, "artifact");
736
+ this.tool_call_id = fields.tool_call_id;
737
+ this.artifact = fields.artifact;
738
+ this.status = fields.status;
739
+ }
740
+ static lc_name() {
741
+ return "ToolMessageChunk";
742
+ }
743
+ concat(chunk) {
744
+ const Cls = this.constructor;
745
+ return new Cls({
746
+ content: mergeContent(this.content, chunk.content),
747
+ additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),
748
+ response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata),
749
+ artifact: _mergeObj(this.artifact, chunk.artifact),
750
+ tool_call_id: this.tool_call_id,
751
+ id: this.id ?? chunk.id,
752
+ status: _mergeStatus(this.status, chunk.status)
753
+ });
754
+ }
755
+ get _printableFields() {
756
+ return {
757
+ ...super._printableFields,
758
+ tool_call_id: this.tool_call_id,
759
+ artifact: this.artifact
760
+ };
761
+ }
762
+ };
763
+ function defaultToolCallParser(rawToolCalls) {
764
+ const toolCalls = [];
765
+ const invalidToolCalls = [];
766
+ for (const toolCall of rawToolCalls) if (!toolCall.function) continue;
767
+ else {
768
+ const functionName = toolCall.function.name;
769
+ try {
770
+ const functionArgs = JSON.parse(toolCall.function.arguments);
771
+ toolCalls.push({
772
+ name: functionName || "",
773
+ args: functionArgs || {},
774
+ id: toolCall.id
775
+ });
776
+ } catch {
777
+ invalidToolCalls.push({
778
+ name: functionName,
779
+ args: toolCall.function.arguments,
780
+ id: toolCall.id,
781
+ error: "Malformed args."
782
+ });
783
+ }
784
+ }
785
+ return [toolCalls, invalidToolCalls];
786
+ }
787
+ function isToolMessage(x) {
788
+ return typeof x === "object" && x !== null && "getType" in x && typeof x.getType === "function" && x.getType() === "tool";
789
+ }
790
+ function isToolMessageChunk(x) {
791
+ return x._getType() === "tool";
792
+ }
793
+ function isClientToolRequest(value) {
794
+ return value && Array.isArray(value.clientToolCalls);
795
+ }
1
796
  var ChatMessageTypeEnum = /* @__PURE__ */ ((ChatMessageTypeEnum2) => {
2
797
  ChatMessageTypeEnum2["MESSAGE"] = "message";
3
798
  ChatMessageTypeEnum2["EVENT"] = "event";
@@ -37,6 +832,7 @@ var ChatMessageStepCategory = /* @__PURE__ */ ((ChatMessageStepCategory2) => {
37
832
  export {
38
833
  ChatMessageEventTypeEnum,
39
834
  ChatMessageStepCategory,
40
- ChatMessageTypeEnum
835
+ ChatMessageTypeEnum,
836
+ isClientToolRequest
41
837
  };
42
838
  //# sourceMappingURL=index.js.map