llm-exe 2.1.8 → 2.2.0

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
@@ -9,7 +9,6 @@ var __typeError = (msg) => {
9
9
  throw TypeError(msg);
10
10
  };
11
11
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
13
12
  var __export = (target, all) => {
14
13
  for (var name in all)
15
14
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -37,8 +36,8 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
37
36
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
38
37
 
39
38
  // src/index.ts
40
- var src_exports = {};
41
- __export(src_exports, {
39
+ var index_exports = {};
40
+ __export(index_exports, {
42
41
  BaseExecutor: () => BaseExecutor,
43
42
  BaseParser: () => BaseParser,
44
43
  BasePrompt: () => BasePrompt,
@@ -61,11 +60,14 @@ __export(src_exports, {
61
60
  createPrompt: () => createPrompt,
62
61
  createState: () => createState,
63
62
  createStateItem: () => createStateItem,
63
+ defineSchema: () => defineSchema,
64
+ registerHelpers: () => registerHelpers,
65
+ registerPartials: () => registerPartials,
64
66
  useExecutors: () => useExecutors,
65
67
  useLlm: () => useLlm,
66
68
  utils: () => utils_exports
67
69
  });
68
- module.exports = __toCommonJS(src_exports);
70
+ module.exports = __toCommonJS(index_exports);
69
71
 
70
72
  // src/utils/modules/pick.ts
71
73
  function pick(object, keys) {
@@ -76,38 +78,30 @@ function pick(object, keys) {
76
78
  return obj;
77
79
  }, {});
78
80
  }
79
- __name(pick, "pick");
80
81
 
81
82
  // src/utils/modules/ensureInputIsObject.ts
82
83
  function ensureInputIsObject(input) {
83
84
  if (input === null || typeof input === "undefined") {
84
- return {
85
- input
86
- };
85
+ return { input };
87
86
  }
88
87
  switch (typeof input) {
89
88
  case "object": {
90
89
  if (Array.isArray(input)) {
91
- return {
92
- input
93
- };
90
+ return { input };
94
91
  }
95
92
  return input;
96
93
  }
97
94
  default:
98
- return {
99
- input
100
- };
95
+ return { input };
101
96
  }
102
97
  }
103
- __name(ensureInputIsObject, "ensureInputIsObject");
104
98
 
105
99
  // src/utils/modules/uuid.ts
106
100
  var import_uuid = require("uuid");
107
101
 
108
102
  // src/executor/_metadata.ts
109
103
  var _state;
110
- var _ExecutorExecutionMetadataState = class _ExecutorExecutionMetadataState {
104
+ var ExecutorExecutionMetadataState = class {
111
105
  constructor(items) {
112
106
  __privateAdd(this, _state, {
113
107
  start: null,
@@ -150,12 +144,9 @@ var _ExecutorExecutionMetadataState = class _ExecutorExecutionMetadataState {
150
144
  }
151
145
  };
152
146
  _state = new WeakMap();
153
- __name(_ExecutorExecutionMetadataState, "ExecutorExecutionMetadataState");
154
- var ExecutorExecutionMetadataState = _ExecutorExecutionMetadataState;
155
147
  function createMetadataState(items) {
156
148
  return new ExecutorExecutionMetadataState(items);
157
149
  }
158
- __name(createMetadataState, "createMetadataState");
159
150
 
160
151
  // src/utils/const.ts
161
152
  var hookOnComplete = `onComplete`;
@@ -163,38 +154,34 @@ var hookOnError = `onError`;
163
154
  var hookOnSuccess = `onSuccess`;
164
155
 
165
156
  // src/executor/_base.ts
166
- var _BaseExecutor = class _BaseExecutor {
157
+ var BaseExecutor = class {
167
158
  constructor(name, type, options) {
168
159
  /**
169
- * @property id - internal id of the executor
170
- */
160
+ * @property id - internal id of the executor
161
+ */
171
162
  __publicField(this, "id");
172
163
  /**
173
- * @property type - type of executor
174
- */
164
+ * @property type - type of executor
165
+ */
175
166
  __publicField(this, "type");
176
167
  /**
177
- * @property created - timestamp date created
178
- */
168
+ * @property created - timestamp date created
169
+ */
179
170
  __publicField(this, "created");
180
171
  /**
181
- * @property name - name of executor
182
- */
172
+ * @property name - name of executor
173
+ */
183
174
  __publicField(this, "name");
184
175
  /**
185
- * @property executions -
186
- */
176
+ * @property executions -
177
+ */
187
178
  __publicField(this, "executions");
188
179
  __publicField(this, "traceId", null);
189
180
  /**
190
- * @property hooks - hooks to be ran during execution
191
- */
181
+ * @property hooks - hooks to be ran during execution
182
+ */
192
183
  __publicField(this, "hooks");
193
- __publicField(this, "allowedHooks", [
194
- hookOnComplete,
195
- hookOnError,
196
- hookOnSuccess
197
- ]);
184
+ __publicField(this, "allowedHooks", [hookOnComplete, hookOnError, hookOnSuccess]);
198
185
  this.id = (0, import_uuid.v4)();
199
186
  this.type = type;
200
187
  this.name = name;
@@ -210,29 +197,29 @@ var _BaseExecutor = class _BaseExecutor {
210
197
  }
211
198
  }
212
199
  /**
213
- *
214
- * Used to filter the input of the handler
215
- * @param _input
216
- * @returns original input formatted for handler
217
- */
200
+ *
201
+ * Used to filter the input of the handler
202
+ * @param _input
203
+ * @returns original input formatted for handler
204
+ */
218
205
  async getHandlerInput(_input, _metadata, _options) {
219
206
  return ensureInputIsObject(_input);
220
207
  }
221
208
  /**
222
- *
223
- * Used to filter the output of the handler
224
- * @param _input
225
- * @returns output O
226
- */
209
+ *
210
+ * Used to filter the output of the handler
211
+ * @param _input
212
+ * @returns output O
213
+ */
227
214
  getHandlerOutput(out, _metadata, _options) {
228
215
  return out;
229
216
  }
230
217
  /**
231
- *
232
- * execute - Runs the executor
233
- * @param _input
234
- * @returns handler output
235
- */
218
+ *
219
+ * execute - Runs the executor
220
+ * @param _input
221
+ * @returns handler output
222
+ */
236
223
  async execute(_input, _options) {
237
224
  this.executions++;
238
225
  const _metadata = createMetadataState({
@@ -240,31 +227,28 @@ var _BaseExecutor = class _BaseExecutor {
240
227
  input: _input
241
228
  });
242
229
  try {
243
- const input = await this.getHandlerInput(_input, _metadata.asPlainObject(), _options);
244
- _metadata.setItem({
245
- handlerInput: input
246
- });
230
+ const input = await this.getHandlerInput(
231
+ _input,
232
+ _metadata.asPlainObject(),
233
+ _options
234
+ );
235
+ _metadata.setItem({ handlerInput: input });
247
236
  let result = await this.handler(input, _options);
248
- _metadata.setItem({
249
- handlerOutput: result
250
- });
251
- const output = this.getHandlerOutput(result, _metadata.asPlainObject(), _options);
252
- _metadata.setItem({
253
- output
254
- });
237
+ _metadata.setItem({ handlerOutput: result });
238
+ const output = this.getHandlerOutput(
239
+ result,
240
+ _metadata.asPlainObject(),
241
+ _options
242
+ );
243
+ _metadata.setItem({ output });
255
244
  this.runHook("onSuccess", _metadata.asPlainObject());
256
245
  return output;
257
246
  } catch (error) {
258
- _metadata.setItem({
259
- error,
260
- errorMessage: error.message
261
- });
247
+ _metadata.setItem({ error, errorMessage: error.message });
262
248
  this.runHook("onError", _metadata.asPlainObject());
263
249
  throw error;
264
250
  } finally {
265
- _metadata.setItem({
266
- end: (/* @__PURE__ */ new Date()).getTime()
267
- });
251
+ _metadata.setItem({ end: (/* @__PURE__ */ new Date()).getTime() });
268
252
  this.runHook("onComplete", _metadata.asPlainObject());
269
253
  }
270
254
  }
@@ -284,9 +268,7 @@ var _BaseExecutor = class _BaseExecutor {
284
268
  }
285
269
  runHook(hook, _metadata) {
286
270
  const { [hook]: hooks = [] } = pick(this.hooks, this.allowedHooks);
287
- for (const hookFn of [
288
- ...hooks
289
- ]) {
271
+ for (const hookFn of [...hooks]) {
290
272
  if (typeof hookFn === "function") {
291
273
  try {
292
274
  hookFn(_metadata, this.getMetadata());
@@ -297,12 +279,12 @@ var _BaseExecutor = class _BaseExecutor {
297
279
  }
298
280
  setHooks(hooks = {}) {
299
281
  const hookKeys = Object.keys(hooks);
300
- for (const hookKey of hookKeys.filter((k) => this.allowedHooks.includes(k))) {
282
+ for (const hookKey of hookKeys.filter(
283
+ (k) => this.allowedHooks.includes(k)
284
+ )) {
301
285
  const hookInput = hooks[hookKey];
302
286
  if (hookInput) {
303
- const _hooks = Array.isArray(hookInput) ? hookInput : [
304
- hookInput
305
- ];
287
+ const _hooks = Array.isArray(hookInput) ? hookInput : [hookInput];
306
288
  for (const hook of _hooks) {
307
289
  if (hook && typeof hook === "function" && !this.hooks[hookKey].find((h) => h === hook)) {
308
290
  this.hooks[hookKey].push(hook);
@@ -325,19 +307,17 @@ var _BaseExecutor = class _BaseExecutor {
325
307
  return this;
326
308
  }
327
309
  on(eventName, fn) {
328
- return this.setHooks({
329
- [eventName]: fn
330
- });
310
+ return this.setHooks({ [eventName]: fn });
331
311
  }
332
312
  off(eventName, fn) {
333
313
  return this.removeHook(eventName, fn);
334
314
  }
335
315
  once(eventName, fn) {
336
316
  if (typeof fn !== "function") return this;
337
- const onceWrapper = /* @__PURE__ */ __name((...args) => {
317
+ const onceWrapper = (...args) => {
338
318
  fn(...args);
339
319
  this.off(eventName, onceWrapper);
340
- }, "onceWrapper");
320
+ };
341
321
  this.hooks[eventName].push(onceWrapper);
342
322
  return this;
343
323
  }
@@ -349,26 +329,20 @@ var _BaseExecutor = class _BaseExecutor {
349
329
  return this.traceId;
350
330
  }
351
331
  };
352
- __name(_BaseExecutor, "BaseExecutor");
353
- var BaseExecutor = _BaseExecutor;
354
332
 
355
333
  // src/utils/modules/inferFunctionName.ts
356
334
  function inferFunctionName(func, defaultName) {
357
- const name = func?.name;
358
- if (name && typeof name === "string") {
359
- if (name.substring(0, 6) === "bound ") {
360
- return name.replace("bound ", "");
361
- } else {
362
- return name;
363
- }
335
+ if (typeof func !== "function") return defaultName;
336
+ const name = func.name;
337
+ if (typeof name === "string" && name.length > 0) {
338
+ return name.startsWith("bound ") ? name.slice(6) : name;
364
339
  }
365
- var result = /^function\s+([\w\$]+)\s*\(/.exec(func.toString());
366
- return result ? result[1] : defaultName;
340
+ const match = /^function\s+([\w$]+)\s*\(/.exec(func.toString());
341
+ return match?.[1] ?? defaultName;
367
342
  }
368
- __name(inferFunctionName, "inferFunctionName");
369
343
 
370
344
  // src/executor/core.ts
371
- var _CoreExecutor = class _CoreExecutor extends BaseExecutor {
345
+ var CoreExecutor = class extends BaseExecutor {
372
346
  constructor(fn, options) {
373
347
  const name = fn?.name ? fn.name : inferFunctionName(fn.handler, "anonymous-core-executor");
374
348
  super(name, "function-executor", options);
@@ -379,16 +353,14 @@ var _CoreExecutor = class _CoreExecutor extends BaseExecutor {
379
353
  return this._handler.call(null, _input);
380
354
  }
381
355
  };
382
- __name(_CoreExecutor, "CoreExecutor");
383
- var CoreExecutor = _CoreExecutor;
384
356
 
385
357
  // src/parser/_base.ts
386
- var _BaseParser = class _BaseParser {
358
+ var BaseParser = class {
387
359
  /**
388
- * Create a new BaseParser.
389
- * @param name - The name of the parser.
390
- * @param options - options
391
- */
360
+ * Create a new BaseParser.
361
+ * @param name - The name of the parser.
362
+ * @param options - options
363
+ */
392
364
  constructor(name, options = {}, target = "text") {
393
365
  __publicField(this, "name");
394
366
  __publicField(this, "options");
@@ -400,14 +372,12 @@ var _BaseParser = class _BaseParser {
400
372
  }
401
373
  }
402
374
  };
403
- __name(_BaseParser, "BaseParser");
404
- var BaseParser = _BaseParser;
405
- var _BaseParserWithJson = class _BaseParserWithJson extends BaseParser {
375
+ var BaseParserWithJson = class extends BaseParser {
406
376
  /**
407
- * Create a new BaseParser.
408
- * @param name - The name of the parser.
409
- * @param options - options
410
- */
377
+ * Create a new BaseParser.
378
+ * @param name - The name of the parser.
379
+ * @param options - options
380
+ */
411
381
  constructor(name, options) {
412
382
  super(name);
413
383
  __publicField(this, "schema");
@@ -419,8 +389,6 @@ var _BaseParserWithJson = class _BaseParserWithJson extends BaseParser {
419
389
  }
420
390
  }
421
391
  };
422
- __name(_BaseParserWithJson, "BaseParserWithJson");
423
- var BaseParserWithJson = _BaseParserWithJson;
424
392
 
425
393
  // src/utils/index.ts
426
394
  var utils_exports = {};
@@ -453,7 +421,6 @@ function assert(condition, message) {
453
421
  }
454
422
  }
455
423
  }
456
- __name(assert, "assert");
457
424
 
458
425
  // src/utils/modules/defineSchema.ts
459
426
  var import_json_schema_to_ts = require("json-schema-to-ts");
@@ -461,13 +428,14 @@ function defineSchema(obj) {
461
428
  obj.additionalProperties = false;
462
429
  return (0, import_json_schema_to_ts.asConst)(obj);
463
430
  }
464
- __name(defineSchema, "defineSchema");
465
431
 
466
432
  // src/utils/modules/handlebars/utils/importPartials.ts
467
433
  function importPartials(_partials) {
468
434
  let partials2 = [];
469
435
  if (_partials) {
470
- const externalPartialKeys = Object.keys(_partials);
436
+ const externalPartialKeys = Object.keys(
437
+ _partials
438
+ );
471
439
  for (const externalPartialKey of externalPartialKeys) {
472
440
  if (typeof externalPartialKey === "string") {
473
441
  partials2.push({
@@ -479,13 +447,14 @@ function importPartials(_partials) {
479
447
  }
480
448
  return partials2;
481
449
  }
482
- __name(importPartials, "importPartials");
483
450
 
484
451
  // src/utils/modules/handlebars/utils/importHelpers.ts
485
452
  function importHelpers(_helpers) {
486
453
  let helpers = [];
487
454
  if (_helpers) {
488
- const externalHelperKeys = Object.keys(_helpers);
455
+ const externalHelperKeys = Object.keys(
456
+ _helpers
457
+ );
489
458
  for (const externalHelperKey of externalHelperKeys) {
490
459
  if (typeof externalHelperKey === "string") {
491
460
  helpers.push({
@@ -497,7 +466,6 @@ function importHelpers(_helpers) {
497
466
  }
498
467
  return helpers;
499
468
  }
500
- __name(importHelpers, "importHelpers");
501
469
 
502
470
  // src/utils/modules/toNumber.ts
503
471
  function toNumber(value) {
@@ -509,7 +477,6 @@ function toNumber(value) {
509
477
  }
510
478
  return NaN;
511
479
  }
512
- __name(toNumber, "toNumber");
513
480
 
514
481
  // src/utils/modules/get.ts
515
482
  function get(obj, path, defaultValue) {
@@ -517,17 +484,18 @@ function get(obj, path, defaultValue) {
517
484
  return defaultValue;
518
485
  }
519
486
  const pathString = Array.isArray(path) ? path.join(".") : path;
520
- const travel = /* @__PURE__ */ __name((regexp) => pathString.split(regexp).filter(Boolean).reduce((res, key) => res !== null && res !== void 0 ? res[key] : res, obj), "travel");
487
+ const travel = (regexp) => pathString.split(regexp).filter(Boolean).reduce(
488
+ (res, key) => res !== null && res !== void 0 ? res[key] : res,
489
+ obj
490
+ );
521
491
  const result = travel(/[,[\]]+?/) || travel(/[,[\].]+?/);
522
492
  return result === void 0 || result === obj ? defaultValue : result === null ? defaultValue : result;
523
493
  }
524
- __name(get, "get");
525
494
 
526
495
  // src/utils/modules/filterObjectOnSchema.ts
527
496
  function isObject(obj) {
528
497
  return obj === Object(obj);
529
498
  }
530
- __name(isObject, "isObject");
531
499
  function getType(schemaType) {
532
500
  if (!Array.isArray(schemaType)) {
533
501
  return schemaType;
@@ -540,7 +508,6 @@ function getType(schemaType) {
540
508
  }
541
509
  }
542
510
  }
543
- __name(getType, "getType");
544
511
  function filterObjectOnSchema(schema, doc, detach, property) {
545
512
  let result;
546
513
  if (doc === null || doc === void 0) {
@@ -585,25 +552,10 @@ function filterObjectOnSchema(schema, doc, detach, property) {
585
552
  }
586
553
  return result;
587
554
  }
588
- __name(filterObjectOnSchema, "filterObjectOnSchema");
589
555
 
590
556
  // src/utils/modules/handlebars/hbs.ts
591
557
  var import_handlebars = __toESM(require("handlebars"));
592
558
 
593
- // src/utils/modules/handlebars/utils/registerPartials.ts
594
- function _registerPartials(partials2, instance) {
595
- if (partials2 && Array.isArray(partials2)) {
596
- for (const partial of partials2) {
597
- if (partial.name && typeof partial.name === "string" && typeof partial.template === "string") {
598
- if (instance) {
599
- instance.registerPartial(partial.name, partial.template);
600
- }
601
- }
602
- }
603
- }
604
- }
605
- __name(_registerPartials, "_registerPartials");
606
-
607
559
  // src/utils/modules/handlebars/utils/registerHelpers.ts
608
560
  function _registerHelpers(helpers, instance) {
609
561
  if (helpers && Array.isArray(helpers)) {
@@ -616,17 +568,6 @@ function _registerHelpers(helpers, instance) {
616
568
  }
617
569
  }
618
570
  }
619
- __name(_registerHelpers, "_registerHelpers");
620
-
621
- // src/utils/modules/getEnvironmentVariable.ts
622
- function getEnvironmentVariable(name) {
623
- if (typeof process === "object" && process?.env) {
624
- return process.env[name];
625
- } else {
626
- return void 0;
627
- }
628
- }
629
- __name(getEnvironmentVariable, "getEnvironmentVariable");
630
571
 
631
572
  // src/utils/modules/handlebars/templates/index.ts
632
573
  var MarkdownCode = `{{#if code}}\`\`\`{{#if language}}{{language}}{{/if}}
@@ -700,7 +641,7 @@ __export(helpers_exports, {
700
641
  });
701
642
 
702
643
  // src/utils/modules/json.ts
703
- var maybeStringifyJSON = /* @__PURE__ */ __name((objOrMaybeString) => {
644
+ var maybeStringifyJSON = (objOrMaybeString) => {
704
645
  if (!objOrMaybeString || typeof objOrMaybeString !== "object") {
705
646
  return objOrMaybeString;
706
647
  }
@@ -710,8 +651,8 @@ var maybeStringifyJSON = /* @__PURE__ */ __name((objOrMaybeString) => {
710
651
  } catch (error) {
711
652
  }
712
653
  return "";
713
- }, "maybeStringifyJSON");
714
- var maybeParseJSON = /* @__PURE__ */ __name((objOrMaybeJSON) => {
654
+ };
655
+ var maybeParseJSON = (objOrMaybeJSON) => {
715
656
  if (!objOrMaybeJSON) return {};
716
657
  if (typeof objOrMaybeJSON === "string") {
717
658
  try {
@@ -727,24 +668,19 @@ var maybeParseJSON = /* @__PURE__ */ __name((objOrMaybeJSON) => {
727
668
  return objOrMaybeJSON;
728
669
  }
729
670
  return {};
730
- }, "maybeParseJSON");
671
+ };
731
672
  function isObjectStringified(maybeObject) {
732
673
  if (typeof maybeObject !== "string") return false;
733
- const isMaybeObject = maybeObject.substring(0, 1) === "{" && maybeObject.substring(maybeObject.length - 1, maybeObject.length) === "}";
734
- const isMaybeArray = maybeObject.substring(0, 1) === "[" && maybeObject.substring(maybeObject.length - 1, maybeObject.length) === "]";
735
- if (!isMaybeObject && !isMaybeArray) {
736
- return false;
737
- }
738
- let canDecode = false;
674
+ const trimmed = maybeObject.trim();
675
+ const isWrapped = trimmed.startsWith("{") && trimmed.endsWith("}") || trimmed.startsWith("[") && trimmed.endsWith("]");
676
+ if (!isWrapped) return false;
739
677
  try {
740
- JSON.parse(maybeObject);
741
- canDecode = true;
742
- } catch (error) {
743
- canDecode = false;
678
+ const parsed = JSON.parse(trimmed);
679
+ return typeof parsed === "object" && parsed !== null;
680
+ } catch {
681
+ return false;
744
682
  }
745
- return canDecode;
746
683
  }
747
- __name(isObjectStringified, "isObjectStringified");
748
684
  function helpJsonMarkup(str) {
749
685
  if (typeof str !== "string") {
750
686
  return str;
@@ -752,12 +688,17 @@ function helpJsonMarkup(str) {
752
688
  const input = str.trim();
753
689
  const markdownJsonStartsWith = "```json";
754
690
  const markdownJsonEndsWith = "```";
755
- if (input.substring(0, markdownJsonStartsWith.length) === markdownJsonStartsWith && input.substring(input.length - markdownJsonEndsWith.length, input.length) === markdownJsonEndsWith) {
756
- return str.substring(markdownJsonStartsWith.length, input.length - markdownJsonEndsWith.length)?.trim();
691
+ if (input.substring(0, markdownJsonStartsWith.length) === markdownJsonStartsWith && input.substring(
692
+ input.length - markdownJsonEndsWith.length,
693
+ input.length
694
+ ) === markdownJsonEndsWith) {
695
+ return str.substring(
696
+ markdownJsonStartsWith.length,
697
+ input.length - markdownJsonEndsWith.length
698
+ )?.trim();
757
699
  }
758
700
  return str;
759
701
  }
760
- __name(helpJsonMarkup, "helpJsonMarkup");
761
702
 
762
703
  // src/utils/modules/replaceTemplateStringSimple.ts
763
704
  function replaceTemplateStringSimple(template, context) {
@@ -774,31 +715,28 @@ function replaceTemplateStringSimple(template, context) {
774
715
  return typeof value === "string" ? value : String(value);
775
716
  });
776
717
  }
777
- __name(replaceTemplateStringSimple, "replaceTemplateStringSimple");
778
718
 
779
719
  // src/utils/modules/handlebars/helpers/indentJson.ts
780
720
  function indentJson(arg1, collapse = "false") {
781
721
  if (typeof arg1 !== "object") {
782
722
  return replaceTemplateStringSimple(arg1 || "", this);
783
723
  }
784
- const replaced = maybeParseJSON(replaceTemplateStringSimple(maybeStringifyJSON(arg1), this));
724
+ const replaced = maybeParseJSON(
725
+ replaceTemplateStringSimple(maybeStringifyJSON(arg1), this)
726
+ );
785
727
  if (collapse == "true") {
786
728
  return JSON.stringify(replaced);
787
729
  }
788
730
  return JSON.stringify(replaced, null, 2);
789
731
  }
790
- __name(indentJson, "indentJson");
791
732
 
792
733
  // src/utils/modules/schemaExampleWith.ts
793
734
  function schemaExampleWith(schema, property) {
794
735
  if (schema.type === "array") {
795
- return filterObjectOnSchema(schema, [
796
- {}
797
- ], void 0, property);
736
+ return filterObjectOnSchema(schema, [{}], void 0, property);
798
737
  }
799
738
  return filterObjectOnSchema(schema, {}, void 0, property);
800
739
  }
801
- __name(schemaExampleWith, "schemaExampleWith");
802
740
 
803
741
  // src/utils/modules/handlebars/helpers/jsonSchemaExample.ts
804
742
  function jsonSchemaExample(key, prop, collapse) {
@@ -808,7 +746,9 @@ function jsonSchemaExample(key, prop, collapse) {
808
746
  if (typeof result !== "object") {
809
747
  return "";
810
748
  }
811
- const replaced = maybeParseJSON(replaceTemplateStringSimple(maybeStringifyJSON(result), this));
749
+ const replaced = maybeParseJSON(
750
+ replaceTemplateStringSimple(maybeStringifyJSON(result), this)
751
+ );
812
752
  if (collapse == "true") {
813
753
  return JSON.stringify(replaced);
814
754
  }
@@ -816,41 +756,35 @@ function jsonSchemaExample(key, prop, collapse) {
816
756
  }
817
757
  return "";
818
758
  }
819
- __name(jsonSchemaExample, "jsonSchemaExample");
820
759
 
821
760
  // src/utils/modules/handlebars/helpers/getKeyOr.ts
822
761
  function getKeyOr(key, arg2) {
823
762
  const res = get(this, key);
824
763
  return typeof res !== "undefined" && res !== "" ? res : arg2;
825
764
  }
826
- __name(getKeyOr, "getKeyOr");
827
765
 
828
766
  // src/utils/modules/handlebars/helpers/getOr.ts
829
767
  function getOr(arg1, arg2) {
830
768
  return typeof arg1 !== "undefined" && arg1 !== "" ? arg1 : arg2;
831
769
  }
832
- __name(getOr, "getOr");
833
770
 
834
771
  // src/utils/modules/handlebars/helpers/pluralize.ts
835
772
  function pluralize(arg1, arg2) {
836
773
  const [singular, plural] = arg1.split("|");
837
774
  return arg2 > 1 ? plural : singular;
838
775
  }
839
- __name(pluralize, "pluralize");
840
776
 
841
777
  // src/utils/modules/handlebars/helpers/eq.ts
842
778
  function eq(arg1 = "", arg2 = "", options) {
843
779
  const isArr = arg2.toString().split(",").map((a) => a.trim());
844
780
  return isArr.includes(arg1) ? options.fn(this) : options.inverse(this);
845
781
  }
846
- __name(eq, "eq");
847
782
 
848
783
  // src/utils/modules/handlebars/helpers/neq.ts
849
784
  function neq(arg1 = "", arg2 = "", options) {
850
785
  const isArr = arg2.toString().split(",").map((a) => a.trim());
851
786
  return !isArr.includes(arg1) ? options.fn(this) : options.inverse(this);
852
787
  }
853
- __name(neq, "neq");
854
788
 
855
789
  // src/utils/modules/handlebars/helpers/ifCond.ts
856
790
  function ifCond(v1, operator, v2, options) {
@@ -879,13 +813,11 @@ function ifCond(v1, operator, v2, options) {
879
813
  return options.inverse(this);
880
814
  }
881
815
  }
882
- __name(ifCond, "ifCond");
883
816
 
884
817
  // src/utils/modules/handlebars/helpers/objectToList.ts
885
818
  function objectToList(arg = {}) {
886
819
  return Object.keys(arg).map((key) => `- ${key}: ${arg[key]}`).join("\n");
887
820
  }
888
- __name(objectToList, "objectToList");
889
821
 
890
822
  // src/utils/modules/handlebars/helpers/join.ts
891
823
  function join(array) {
@@ -893,13 +825,11 @@ function join(array) {
893
825
  if (!Array.isArray(array)) return "";
894
826
  return array.join(", ");
895
827
  }
896
- __name(join, "join");
897
828
 
898
829
  // src/utils/modules/handlebars/helpers/cut.ts
899
830
  function cutFn(str, arg) {
900
831
  return str.toString().replace(new RegExp(arg, "g"), "");
901
832
  }
902
- __name(cutFn, "cutFn");
903
833
 
904
834
  // src/utils/modules/handlebars/helpers/substring.ts
905
835
  function substringFn(str, start, end) {
@@ -912,47 +842,42 @@ function substringFn(str, start, end) {
912
842
  return str;
913
843
  }
914
844
  }
915
- __name(substringFn, "substringFn");
916
845
 
917
846
  // src/utils/modules/handlebars/helpers/with.ts
918
847
  function withFn(options, context) {
919
848
  return options.fn(context);
920
849
  }
921
- __name(withFn, "withFn");
922
850
 
923
851
  // src/utils/modules/handlebars/utils/makeHandlebarsInstance.ts
924
852
  function makeHandlebarsInstance(hbs2) {
925
853
  const handlebars = hbs2.create();
926
854
  const helperKeys = Object.keys(helpers_exports);
927
- _registerHelpers(helperKeys.map((a) => ({
928
- handler: helpers_exports[a],
929
- name: a
930
- })), handlebars);
931
- handlebars.registerHelper("hbsInTemplate", function(str, substitutions) {
932
- const template = handlebars.compile(str);
933
- return template(substitutions, {
934
- allowedProtoMethods: {
935
- substring: true
936
- }
937
- });
938
- });
939
- const helperPath = getEnvironmentVariable("CUSTOM_PROMPT_TEMPLATE_HELPERS_PATH");
940
- if (helperPath) {
941
- const externalHelpers = require(helperPath);
942
- _registerHelpers(importHelpers(externalHelpers), handlebars);
943
- }
944
- const contextPartialKeys = Object.keys(partials);
855
+ _registerHelpers(
856
+ helperKeys.map((a) => ({ handler: helpers_exports[a], name: a })),
857
+ handlebars
858
+ );
859
+ handlebars.registerHelper(
860
+ "hbsInTemplate",
861
+ function(str, substitutions) {
862
+ const template = handlebars.compile(str);
863
+ return template(substitutions, {
864
+ allowedProtoMethods: {
865
+ substring: true
866
+ }
867
+ });
868
+ }
869
+ );
870
+ const contextPartialKeys = Object.keys(
871
+ partials
872
+ );
945
873
  for (const contextPartialKey of contextPartialKeys) {
946
- handlebars.registerPartial(contextPartialKey, partials[contextPartialKey]);
947
- }
948
- const partialsPath = getEnvironmentVariable("CUSTOM_PROMPT_TEMPLATE_PARTIALS_PATH");
949
- if (typeof process === "object" && partialsPath) {
950
- const externalPartials = require(partialsPath);
951
- _registerPartials(importPartials(externalPartials), handlebars);
874
+ handlebars.registerPartial(
875
+ contextPartialKey,
876
+ partials[contextPartialKey]
877
+ );
952
878
  }
953
879
  return handlebars;
954
880
  }
955
- __name(makeHandlebarsInstance, "makeHandlebarsInstance");
956
881
 
957
882
  // src/utils/modules/isPromise.ts
958
883
  function isPromise(value) {
@@ -961,24 +886,16 @@ function isPromise(value) {
961
886
  }
962
887
  return Object.prototype.toString.call(value) === "[object AsyncFunction]";
963
888
  }
964
- __name(isPromise, "isPromise");
965
889
 
966
890
  // src/utils/modules/handlebars/utils/appendContextPath.ts
967
891
  function appendContextPath(contextPath, id) {
968
892
  return (contextPath ? `${contextPath}.` : "") + id;
969
893
  }
970
- __name(appendContextPath, "appendContextPath");
971
894
 
972
895
  // src/utils/modules/handlebars/utils/blockParams.ts
973
896
  function blockParams(params, ids) {
974
- return {
975
- ...params,
976
- ...{
977
- path: ids
978
- }
979
- };
897
+ return { ...params, ...{ path: ids } };
980
898
  }
981
- __name(blockParams, "blockParams");
982
899
 
983
900
  // src/utils/modules/extend.ts
984
901
  function extend(obj, _source) {
@@ -991,7 +908,6 @@ function extend(obj, _source) {
991
908
  }
992
909
  return obj;
993
910
  }
994
- __name(extend, "extend");
995
911
 
996
912
  // src/utils/modules/handlebars/utils/createFrame.ts
997
913
  function createFrame(object) {
@@ -999,7 +915,6 @@ function createFrame(object) {
999
915
  frame._parent = object;
1000
916
  return frame;
1001
917
  }
1002
- __name(createFrame, "createFrame");
1003
918
 
1004
919
  // src/utils/modules/isEmpty.ts
1005
920
  function isEmpty(value) {
@@ -1011,7 +926,6 @@ function isEmpty(value) {
1011
926
  }
1012
927
  return false;
1013
928
  }
1014
- __name(isEmpty, "isEmpty");
1015
929
 
1016
930
  // src/utils/modules/handlebars/helpers/async/with.ts
1017
931
  async function withFnAsync(context, options) {
@@ -1028,20 +942,18 @@ async function withFnAsync(context, options) {
1028
942
  let { data } = options;
1029
943
  if (options.data && options.ids) {
1030
944
  data = createFrame(options.data);
1031
- data.contextPath = appendContextPath(options.data.contextPath, options.ids[0]);
945
+ data.contextPath = appendContextPath(
946
+ options.data.contextPath,
947
+ options.ids[0]
948
+ );
1032
949
  }
1033
950
  return fn(context, {
1034
951
  data,
1035
- blockParams: blockParams([
1036
- context
1037
- ], [
1038
- data && data.contextPath
1039
- ])
952
+ blockParams: blockParams([context], [data && data.contextPath])
1040
953
  });
1041
954
  }
1042
955
  return options.inverse(this);
1043
956
  }
1044
- __name(withFnAsync, "withFnAsync");
1045
957
 
1046
958
  // src/utils/modules/handlebars/helpers/async/if.ts
1047
959
  async function ifFnAsync(conditional, options) {
@@ -1059,13 +971,11 @@ async function ifFnAsync(conditional, options) {
1059
971
  return options.fn(this);
1060
972
  }
1061
973
  }
1062
- __name(ifFnAsync, "ifFnAsync");
1063
974
 
1064
975
  // src/utils/modules/isReadableStream.ts
1065
976
  function isReadableStream(obj) {
1066
977
  return obj && typeof obj === "object" && typeof obj.pipe === "function" && typeof obj._read === "function";
1067
978
  }
1068
- __name(isReadableStream, "isReadableStream");
1069
979
 
1070
980
  // src/utils/modules/handlebars/helpers/async/each.ts
1071
981
  async function eachFnAsync(arg1, options) {
@@ -1079,7 +989,10 @@ async function eachFnAsync(arg1, options) {
1079
989
  let ret = [];
1080
990
  let contextPath = "";
1081
991
  if (options.data && options.ids) {
1082
- contextPath = `${appendContextPath(options.data.contextPath, options.ids[0])}.`;
992
+ contextPath = `${appendContextPath(
993
+ options.data.contextPath,
994
+ options.ids[0]
995
+ )}.`;
1083
996
  }
1084
997
  if (typeof arg1 === "function") {
1085
998
  arg1 = arg1.call(this);
@@ -1097,18 +1010,16 @@ async function eachFnAsync(arg1, options) {
1097
1010
  data.contextPath = contextPath + field;
1098
1011
  }
1099
1012
  }
1100
- ret.push(await fn(arg1[field], {
1101
- data,
1102
- blockParams: blockParams([
1103
- arg1[field],
1104
- field
1105
- ], [
1106
- contextPath + field,
1107
- null
1108
- ])
1109
- }));
1013
+ ret.push(
1014
+ await fn(arg1[field], {
1015
+ data,
1016
+ blockParams: blockParams(
1017
+ [arg1[field], field],
1018
+ [contextPath + field, null]
1019
+ )
1020
+ })
1021
+ );
1110
1022
  }
1111
- __name(execIteration, "execIteration");
1112
1023
  if (isPromise(arg1)) {
1113
1024
  arg1 = await arg1;
1114
1025
  }
@@ -1157,13 +1068,10 @@ async function eachFnAsync(arg1, options) {
1157
1068
  }
1158
1069
  if (i === 0) {
1159
1070
  ret = inverse(this);
1160
- ret = [
1161
- inverse(this)
1162
- ];
1071
+ ret = [inverse(this)];
1163
1072
  }
1164
1073
  return ret.join("");
1165
1074
  }
1166
- __name(eachFnAsync, "eachFnAsync");
1167
1075
 
1168
1076
  // src/utils/modules/handlebars/helpers/async/unless.ts
1169
1077
  async function unlessFnAsync(conditional, options) {
@@ -1176,7 +1084,6 @@ async function unlessFnAsync(conditional, options) {
1176
1084
  hash: options.hash
1177
1085
  });
1178
1086
  }
1179
- __name(unlessFnAsync, "unlessFnAsync");
1180
1087
 
1181
1088
  // src/utils/modules/handlebars/helpers/async/async-helpers.ts
1182
1089
  var asyncCoreOverrideHelpers = {
@@ -1188,9 +1095,8 @@ var asyncCoreOverrideHelpers = {
1188
1095
 
1189
1096
  // src/utils/modules/handlebars/utils/makeHandlebarsInstanceAsync.ts
1190
1097
  function makeHandlebarsInstanceAsync(hbs2) {
1191
- var _a;
1192
1098
  const handlebars = hbs2.create();
1193
- const asyncCompiler = (_a = class extends hbs2.JavaScriptCompiler {
1099
+ const asyncCompiler = class extends hbs2.JavaScriptCompiler {
1194
1100
  constructor() {
1195
1101
  super();
1196
1102
  this.compiler = asyncCompiler;
@@ -1203,30 +1109,20 @@ function makeHandlebarsInstanceAsync(hbs2) {
1203
1109
  }
1204
1110
  appendToBuffer(source, location, explicit) {
1205
1111
  if (!Array.isArray(source)) {
1206
- source = [
1207
- source
1208
- ];
1112
+ source = [source];
1209
1113
  }
1210
1114
  source = this.source.wrap(source, location);
1211
1115
  if (this.environment.isSimple) {
1212
- return [
1213
- "return await ",
1214
- source,
1215
- ";"
1216
- ];
1116
+ return ["return await ", source, ";"];
1217
1117
  }
1218
1118
  if (explicit) {
1219
- return [
1220
- "buffer += await ",
1221
- source,
1222
- ";"
1223
- ];
1119
+ return ["buffer += await ", source, ";"];
1224
1120
  }
1225
1121
  source.appendToBuffer = true;
1226
1122
  source.prepend("await ");
1227
1123
  return source;
1228
1124
  }
1229
- }, __name(_a, "asyncCompiler"), _a);
1125
+ };
1230
1126
  handlebars.JavaScriptCompiler = asyncCompiler;
1231
1127
  const _compile = handlebars.compile;
1232
1128
  const _template = handlebars.VM.template;
@@ -1237,90 +1133,110 @@ function makeHandlebarsInstanceAsync(hbs2) {
1237
1133
  }
1238
1134
  return _escapeExpression(value);
1239
1135
  }
1240
- __name(escapeExpression, "escapeExpression");
1241
1136
  function lookupProperty(containerLookupProperty) {
1242
1137
  return function(parent, propertyName) {
1243
1138
  if (isPromise(parent)) {
1244
1139
  if (typeof parent?.then === "function") {
1245
- return parent.then((p) => containerLookupProperty(p, propertyName));
1140
+ return parent.then(
1141
+ (p) => containerLookupProperty(p, propertyName)
1142
+ );
1246
1143
  }
1247
- return parent().then((p) => containerLookupProperty(p, propertyName));
1144
+ return parent().then(
1145
+ (p) => containerLookupProperty(p, propertyName)
1146
+ );
1248
1147
  }
1249
1148
  return containerLookupProperty(parent, propertyName);
1250
1149
  };
1251
1150
  }
1252
- __name(lookupProperty, "lookupProperty");
1253
1151
  handlebars.template = function(spec) {
1254
1152
  spec.main_d = (_prog, _props, container, _depth, data, blockParams2, depths) => async (context) => {
1255
1153
  container.escapeExpression = escapeExpression;
1256
1154
  container.lookupProperty = lookupProperty(container.lookupProperty);
1257
1155
  if (depths.length == 0) {
1258
- depths = [
1259
- data.root
1260
- ];
1156
+ depths = [data.root];
1261
1157
  }
1262
- const v = spec.main(container, context, container.helpers, container.partials, data, blockParams2, depths);
1158
+ const v = spec.main(
1159
+ container,
1160
+ context,
1161
+ container.helpers,
1162
+ container.partials,
1163
+ data,
1164
+ blockParams2,
1165
+ depths
1166
+ );
1263
1167
  return v;
1264
1168
  };
1265
1169
  return _template(spec, handlebars);
1266
1170
  };
1267
1171
  handlebars.compile = function(template, options) {
1268
- const compiled = _compile.apply(handlebars, [
1269
- template,
1270
- {
1271
- ...options
1272
- }
1273
- ]);
1172
+ const compiled = _compile.apply(handlebars, [template, { ...options }]);
1274
1173
  return function(context, execOptions) {
1275
1174
  context = context || {};
1276
1175
  return compiled.call(handlebars, context, execOptions);
1277
1176
  };
1278
1177
  };
1279
1178
  const helperKeys = Object.keys(helpers_exports);
1280
- _registerHelpers(helperKeys.map((a) => ({
1281
- handler: helpers_exports[a],
1282
- name: a
1283
- })), handlebars);
1284
- const asyncHelperKeys = Object.keys(asyncCoreOverrideHelpers);
1285
- _registerHelpers(asyncHelperKeys.map((a) => ({
1286
- handler: asyncCoreOverrideHelpers[a],
1287
- name: a
1288
- })), handlebars);
1289
- const contextPartialKeys = Object.keys(partials);
1179
+ _registerHelpers(
1180
+ helperKeys.map((a) => ({ handler: helpers_exports[a], name: a })),
1181
+ handlebars
1182
+ );
1183
+ const asyncHelperKeys = Object.keys(
1184
+ asyncCoreOverrideHelpers
1185
+ );
1186
+ _registerHelpers(
1187
+ asyncHelperKeys.map((a) => ({
1188
+ handler: asyncCoreOverrideHelpers[a],
1189
+ name: a
1190
+ })),
1191
+ handlebars
1192
+ );
1193
+ const contextPartialKeys = Object.keys(
1194
+ partials
1195
+ );
1290
1196
  for (const contextPartialKey of contextPartialKeys) {
1291
- handlebars.registerPartial(contextPartialKey, partials[contextPartialKey]);
1292
- }
1293
- const partialsPath = getEnvironmentVariable("CUSTOM_PROMPT_TEMPLATE_PARTIALS_PATH");
1294
- if (typeof process === "object" && partialsPath) {
1295
- const externalPartials = require(partialsPath);
1296
- _registerPartials(importPartials(externalPartials), handlebars);
1197
+ handlebars.registerPartial(
1198
+ contextPartialKey,
1199
+ partials[contextPartialKey]
1200
+ );
1297
1201
  }
1298
1202
  return handlebars;
1299
1203
  }
1300
- __name(makeHandlebarsInstanceAsync, "makeHandlebarsInstanceAsync");
1301
1204
 
1302
1205
  // src/utils/modules/handlebars/hbs.ts
1303
1206
  var _hbsAsync = makeHandlebarsInstanceAsync(import_handlebars.default);
1304
1207
  var _hbs = makeHandlebarsInstance(import_handlebars.default);
1305
1208
 
1209
+ // src/utils/modules/handlebars/utils/registerPartials.ts
1210
+ function _registerPartials(partials2, instance) {
1211
+ if (partials2 && Array.isArray(partials2)) {
1212
+ for (const partial of partials2) {
1213
+ if (partial.name && typeof partial.name === "string" && typeof partial.template === "string") {
1214
+ if (instance) {
1215
+ instance.registerPartial(partial.name, partial.template);
1216
+ }
1217
+ }
1218
+ }
1219
+ }
1220
+ }
1221
+
1306
1222
  // src/utils/modules/handlebars/index.ts
1307
1223
  var hbs = {
1308
1224
  handlebars: _hbs,
1309
- registerHelpers: /* @__PURE__ */ __name((helpers) => {
1225
+ registerHelpers: (helpers) => {
1310
1226
  _registerHelpers(helpers, _hbs);
1311
- }, "registerHelpers"),
1312
- registerPartials: /* @__PURE__ */ __name((partials2) => {
1227
+ },
1228
+ registerPartials: (partials2) => {
1313
1229
  _registerPartials(partials2, _hbs);
1314
- }, "registerPartials")
1230
+ }
1315
1231
  };
1316
1232
  var hbsAsync = {
1317
1233
  handlebars: _hbsAsync,
1318
- registerHelpers: /* @__PURE__ */ __name((helpers) => {
1234
+ registerHelpers: (helpers) => {
1319
1235
  _registerHelpers(helpers, _hbsAsync);
1320
- }, "registerHelpers"),
1321
- registerPartials: /* @__PURE__ */ __name((partials2) => {
1236
+ },
1237
+ registerPartials: (partials2) => {
1322
1238
  _registerPartials(partials2, _hbsAsync);
1323
- }, "registerPartials")
1239
+ }
1324
1240
  };
1325
1241
 
1326
1242
  // src/utils/modules/replaceTemplateString.ts
@@ -1353,7 +1269,6 @@ function replaceTemplateString(templateString, substitutions = {}, configuration
1353
1269
  });
1354
1270
  return res;
1355
1271
  }
1356
- __name(replaceTemplateString, "replaceTemplateString");
1357
1272
 
1358
1273
  // src/utils/modules/replaceTemplateStringAsync.ts
1359
1274
  async function replaceTemplateStringAsync(templateString, substitutions = {}, configuration = {
@@ -1385,24 +1300,22 @@ async function replaceTemplateStringAsync(templateString, substitutions = {}, co
1385
1300
  });
1386
1301
  return res;
1387
1302
  }
1388
- __name(replaceTemplateStringAsync, "replaceTemplateStringAsync");
1389
1303
 
1390
1304
  // src/utils/modules/asyncCallWithTimeout.ts
1391
- var asyncCallWithTimeout = /* @__PURE__ */ __name(async (asyncPromise, timeLimit = 1e4) => {
1305
+ var asyncCallWithTimeout = async (asyncPromise, timeLimit = 1e4) => {
1392
1306
  let timeoutHandle;
1393
1307
  const timeoutPromise = new Promise((_resolve, reject) => {
1394
1308
  timeoutHandle = setTimeout(() => {
1395
- return reject(new Error("Unable to perform action. Try again, or use another action."));
1309
+ return reject(
1310
+ new Error("Unable to perform action. Try again, or use another action.")
1311
+ );
1396
1312
  }, timeLimit);
1397
1313
  });
1398
- return Promise.race([
1399
- asyncPromise,
1400
- timeoutPromise
1401
- ]).then((result) => {
1314
+ return Promise.race([asyncPromise, timeoutPromise]).then((result) => {
1402
1315
  clearTimeout(timeoutHandle);
1403
1316
  return result;
1404
1317
  });
1405
- }, "asyncCallWithTimeout");
1318
+ };
1406
1319
 
1407
1320
  // src/utils/modules/guessProviderFromModel.ts
1408
1321
  function isModelKnownOpenAi(payload) {
@@ -1418,7 +1331,6 @@ function isModelKnownOpenAi(payload) {
1418
1331
  }
1419
1332
  return false;
1420
1333
  }
1421
- __name(isModelKnownOpenAi, "isModelKnownOpenAi");
1422
1334
  function isModelKnownAnthropic(payload) {
1423
1335
  const model = payload.model.toLowerCase();
1424
1336
  if (model.startsWith("claude-")) {
@@ -1426,7 +1338,6 @@ function isModelKnownAnthropic(payload) {
1426
1338
  }
1427
1339
  return false;
1428
1340
  }
1429
- __name(isModelKnownAnthropic, "isModelKnownAnthropic");
1430
1341
  function isModelKnownXai(payload) {
1431
1342
  const model = payload.model.toLowerCase();
1432
1343
  if (model.startsWith("grok-")) {
@@ -1434,7 +1345,6 @@ function isModelKnownXai(payload) {
1434
1345
  }
1435
1346
  return false;
1436
1347
  }
1437
- __name(isModelKnownXai, "isModelKnownXai");
1438
1348
  function isModelKnownBedrockAnthropic(payload) {
1439
1349
  const model = payload.model.toLowerCase();
1440
1350
  if (model.startsWith("anthropic.claude-")) {
@@ -1442,7 +1352,6 @@ function isModelKnownBedrockAnthropic(payload) {
1442
1352
  }
1443
1353
  return false;
1444
1354
  }
1445
- __name(isModelKnownBedrockAnthropic, "isModelKnownBedrockAnthropic");
1446
1355
  function guessProviderFromModel(payload) {
1447
1356
  switch (true) {
1448
1357
  case isModelKnownOpenAi(payload):
@@ -1457,19 +1366,16 @@ function guessProviderFromModel(payload) {
1457
1366
  throw new Error("Unsupported model");
1458
1367
  }
1459
1368
  }
1460
- __name(guessProviderFromModel, "guessProviderFromModel");
1461
1369
 
1462
1370
  // src/utils/modules/index.ts
1463
1371
  function registerHelpers(helpers) {
1464
1372
  hbs.registerHelpers(helpers);
1465
1373
  hbsAsync.registerHelpers(helpers);
1466
1374
  }
1467
- __name(registerHelpers, "registerHelpers");
1468
1375
  function registerPartials(partials2) {
1469
1376
  hbs.registerPartials(partials2);
1470
1377
  hbsAsync.registerPartials(partials2);
1471
1378
  }
1472
- __name(registerPartials, "registerPartials");
1473
1379
 
1474
1380
  // src/llm/output/_utils/getResultText.ts
1475
1381
  function getResultText(content) {
@@ -1478,10 +1384,9 @@ function getResultText(content) {
1478
1384
  }
1479
1385
  return "";
1480
1386
  }
1481
- __name(getResultText, "getResultText");
1482
1387
 
1483
1388
  // src/parser/parsers/OpenAiFunctionParser.ts
1484
- var _OpenAiFunctionParser = class _OpenAiFunctionParser extends BaseParser {
1389
+ var OpenAiFunctionParser = class extends BaseParser {
1485
1390
  constructor(options) {
1486
1391
  super("openAiFunction", options, "function_call");
1487
1392
  __publicField(this, "parser");
@@ -1498,30 +1403,32 @@ var _OpenAiFunctionParser = class _OpenAiFunctionParser extends BaseParser {
1498
1403
  return this.parser.parse(getResultText(text));
1499
1404
  }
1500
1405
  };
1501
- __name(_OpenAiFunctionParser, "OpenAiFunctionParser");
1502
- var OpenAiFunctionParser = _OpenAiFunctionParser;
1503
1406
 
1504
1407
  // src/parser/parsers/StringParser.ts
1505
- var _StringParser = class _StringParser extends BaseParser {
1408
+ var StringParser = class extends BaseParser {
1506
1409
  constructor(options) {
1507
1410
  super("string", options);
1508
1411
  }
1509
1412
  parse(text, _options) {
1510
- assert(typeof text === "string", `Invalid input. Expected string. Received ${typeof text}.`);
1413
+ assert(
1414
+ typeof text === "string",
1415
+ `Invalid input. Expected string. Received ${typeof text}.`
1416
+ );
1511
1417
  const parsed = text.toString();
1512
1418
  return parsed;
1513
1419
  }
1514
1420
  };
1515
- __name(_StringParser, "StringParser");
1516
- var StringParser = _StringParser;
1517
1421
 
1518
1422
  // src/parser/parsers/BooleanParser.ts
1519
- var _BooleanParser = class _BooleanParser extends BaseParser {
1423
+ var BooleanParser = class extends BaseParser {
1520
1424
  constructor(options) {
1521
1425
  super("boolean", options);
1522
1426
  }
1523
1427
  parse(text) {
1524
- assert(typeof text === "string", `Invalid input. Expected string. Received ${typeof text}.`);
1428
+ assert(
1429
+ typeof text === "string",
1430
+ `Invalid input. Expected string. Received ${typeof text}.`
1431
+ );
1525
1432
  const clean = text.toLowerCase().trim();
1526
1433
  if (clean === "true") {
1527
1434
  return true;
@@ -1529,17 +1436,14 @@ var _BooleanParser = class _BooleanParser extends BaseParser {
1529
1436
  return false;
1530
1437
  }
1531
1438
  };
1532
- __name(_BooleanParser, "BooleanParser");
1533
- var BooleanParser = _BooleanParser;
1534
1439
 
1535
1440
  // src/utils/modules/isFinite.ts
1536
1441
  function isFinite(value) {
1537
1442
  return typeof value === "number" && Number.isFinite(value);
1538
1443
  }
1539
- __name(isFinite, "isFinite");
1540
1444
 
1541
1445
  // src/parser/parsers/NumberParser.ts
1542
- var _NumberParser = class _NumberParser extends BaseParser {
1446
+ var NumberParser = class extends BaseParser {
1543
1447
  constructor(options) {
1544
1448
  super("number", options);
1545
1449
  }
@@ -1548,8 +1452,6 @@ var _NumberParser = class _NumberParser extends BaseParser {
1548
1452
  return match && isFinite(toNumber(match[0])) ? toNumber(match[0]) : -1;
1549
1453
  }
1550
1454
  };
1551
- __name(_NumberParser, "NumberParser");
1552
- var NumberParser = _NumberParser;
1553
1455
 
1554
1456
  // src/parser/_utils.ts
1555
1457
  var import_jsonschema = require("jsonschema");
@@ -1559,7 +1461,6 @@ function enforceParserSchema(schema, parsed) {
1559
1461
  }
1560
1462
  return filterObjectOnSchema(schema, parsed);
1561
1463
  }
1562
- __name(enforceParserSchema, "enforceParserSchema");
1563
1464
  function validateParserSchema(schema, parsed) {
1564
1465
  if (!schema || !parsed || typeof parsed !== "object") {
1565
1466
  return null;
@@ -1570,10 +1471,9 @@ function validateParserSchema(schema, parsed) {
1570
1471
  }
1571
1472
  return null;
1572
1473
  }
1573
- __name(validateParserSchema, "validateParserSchema");
1574
1474
 
1575
1475
  // src/utils/modules/errors.ts
1576
- var _LlmExeError = class _LlmExeError extends Error {
1476
+ var LlmExeError = class extends Error {
1577
1477
  constructor(message, code, context) {
1578
1478
  super(message ?? "");
1579
1479
  __publicField(this, "code");
@@ -1586,11 +1486,9 @@ var _LlmExeError = class _LlmExeError extends Error {
1586
1486
  }
1587
1487
  }
1588
1488
  };
1589
- __name(_LlmExeError, "LlmExeError");
1590
- var LlmExeError = _LlmExeError;
1591
1489
 
1592
1490
  // src/parser/parsers/JsonParser.ts
1593
- var _JsonParser = class _JsonParser extends BaseParserWithJson {
1491
+ var JsonParser = class extends BaseParserWithJson {
1594
1492
  constructor(options = {}) {
1595
1493
  super("json", options);
1596
1494
  }
@@ -1613,8 +1511,6 @@ var _JsonParser = class _JsonParser extends BaseParserWithJson {
1613
1511
  return parsed;
1614
1512
  }
1615
1513
  };
1616
- __name(_JsonParser, "JsonParser");
1617
- var JsonParser = _JsonParser;
1618
1514
 
1619
1515
  // src/utils/modules/camelCase.ts
1620
1516
  function camelCase(input) {
@@ -1629,10 +1525,9 @@ function camelCase(input) {
1629
1525
  }
1630
1526
  }).join("");
1631
1527
  }
1632
- __name(camelCase, "camelCase");
1633
1528
 
1634
1529
  // src/parser/parsers/ListToJsonParser.ts
1635
- var _ListToJsonParser = class _ListToJsonParser extends BaseParserWithJson {
1530
+ var ListToJsonParser = class extends BaseParserWithJson {
1636
1531
  constructor(options = {}) {
1637
1532
  super("listToJson", options);
1638
1533
  }
@@ -1662,76 +1557,65 @@ var _ListToJsonParser = class _ListToJsonParser extends BaseParserWithJson {
1662
1557
  return output;
1663
1558
  }
1664
1559
  };
1665
- __name(_ListToJsonParser, "ListToJsonParser");
1666
- var ListToJsonParser = _ListToJsonParser;
1667
1560
 
1668
1561
  // src/parser/parsers/ListToKeyValueParser.ts
1669
- var _ListToKeyValueParser = class _ListToKeyValueParser extends BaseParser {
1562
+ var ListToKeyValueParser = class extends BaseParser {
1670
1563
  constructor(options) {
1671
1564
  super("listToKeyValue", options);
1672
1565
  }
1673
1566
  parse(text) {
1674
- const lines = text.split("\n").map((s) => s.replace("- ", "").replace(/\'/g, "'"));
1567
+ const lines = text.split("\n").map((s) => s.replace("- ", "").replace(/'/g, "'"));
1675
1568
  let res = [];
1676
1569
  for (const line of lines) {
1677
1570
  const [key, value] = line.split(":");
1678
1571
  if (key && value) {
1679
- res.push({
1680
- key: key?.trim(),
1681
- value: value?.trim()
1682
- });
1572
+ res.push({ key: key?.trim(), value: value?.trim() });
1683
1573
  }
1684
1574
  }
1685
1575
  return res;
1686
1576
  }
1687
1577
  };
1688
- __name(_ListToKeyValueParser, "ListToKeyValueParser");
1689
- var ListToKeyValueParser = _ListToKeyValueParser;
1690
1578
 
1691
1579
  // src/parser/parsers/CustomParser.ts
1692
- var _CustomParser = class _CustomParser extends BaseParser {
1580
+ var CustomParser = class extends BaseParser {
1693
1581
  /**
1694
- * Creates a new CustomParser instance.
1695
- * @param {string} name The name of the parser.
1696
- * @param {any} parserFn The custom parsing function.
1697
- */
1582
+ * Creates a new CustomParser instance.
1583
+ * @param {string} name The name of the parser.
1584
+ * @param {any} parserFn The custom parsing function.
1585
+ */
1698
1586
  constructor(name, parserFn) {
1699
1587
  super(name);
1700
1588
  /**
1701
- * Custom parsing function.
1702
- * @type {any}
1703
- */
1589
+ * Custom parsing function.
1590
+ * @type {any}
1591
+ */
1704
1592
  __publicField(this, "parserFn");
1705
1593
  this.parserFn = parserFn;
1706
1594
  }
1707
1595
  /**
1708
- * Parses the text using the custom parsing function.
1709
- * @param {string} text The text to be parsed.
1710
- * @param {any} inputValues Additional input values for the parser function.
1711
- * @returns {O} The parsed value.
1712
- */
1596
+ * Parses the text using the custom parsing function.
1597
+ * @param {string} text The text to be parsed.
1598
+ * @param {any} inputValues Additional input values for the parser function.
1599
+ * @returns {O} The parsed value.
1600
+ */
1713
1601
  parse(text, inputValues) {
1714
1602
  return this.parserFn.call(this, text, inputValues);
1715
1603
  }
1716
1604
  };
1717
- __name(_CustomParser, "CustomParser");
1718
- var CustomParser = _CustomParser;
1719
1605
 
1720
1606
  // src/parser/parsers/ListToArrayParser.ts
1721
- var _ListToArrayParser = class _ListToArrayParser extends BaseParser {
1607
+ var ListToArrayParser = class extends BaseParser {
1722
1608
  constructor() {
1723
1609
  super("listToArray");
1724
1610
  }
1725
1611
  parse(text) {
1726
- const lines = text.split("\n").map((s) => s.replace(/^- /, "").replace(/\'/g, "'").trim());
1612
+ const lines = text.split("\n").map((s) => s.replace(/^- /, "").replace(/'/g, "'").trim());
1727
1613
  return lines;
1728
1614
  }
1729
1615
  };
1730
- __name(_ListToArrayParser, "ListToArrayParser");
1731
- var ListToArrayParser = _ListToArrayParser;
1732
1616
 
1733
1617
  // src/parser/parsers/ReplaceStringTemplateParser.ts
1734
- var _ReplaceStringTemplateParser = class _ReplaceStringTemplateParser extends BaseParser {
1618
+ var ReplaceStringTemplateParser = class extends BaseParser {
1735
1619
  constructor(options) {
1736
1620
  super("replaceStringTemplate", options);
1737
1621
  }
@@ -1739,17 +1623,38 @@ var _ReplaceStringTemplateParser = class _ReplaceStringTemplateParser extends Ba
1739
1623
  return replaceTemplateString(text, attributes);
1740
1624
  }
1741
1625
  };
1742
- __name(_ReplaceStringTemplateParser, "ReplaceStringTemplateParser");
1743
- var ReplaceStringTemplateParser = _ReplaceStringTemplateParser;
1626
+
1627
+ // src/parser/singleKeyObjectToString.ts
1628
+ function singleKeyObjectToString(input) {
1629
+ try {
1630
+ const parsed = JSON.parse(input);
1631
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
1632
+ const keys = Object.keys(parsed);
1633
+ if (keys.length === 1) {
1634
+ const value = parsed[keys[0]];
1635
+ if (typeof value === "string") {
1636
+ return value;
1637
+ } else {
1638
+ return input;
1639
+ }
1640
+ }
1641
+ }
1642
+ } catch {
1643
+ }
1644
+ return input;
1645
+ }
1744
1646
 
1745
1647
  // src/parser/parsers/MarkdownCodeBlocks.ts
1746
- var _MarkdownCodeBlocksParser = class _MarkdownCodeBlocksParser extends BaseParser {
1648
+ var MarkdownCodeBlocksParser = class extends BaseParser {
1747
1649
  constructor(options) {
1748
1650
  super("markdownCodeBlocks", options);
1749
1651
  }
1750
1652
  parse(input) {
1751
1653
  const out = [];
1752
- const regex = input.matchAll(new RegExp(/`{3}([\w]*)\n([\S\s]+?)\n`{3}/, "g"));
1654
+ if (isObjectStringified(input)) {
1655
+ input = singleKeyObjectToString(input);
1656
+ }
1657
+ const regex = input.matchAll(new RegExp(/```(\w*)\n([\s\S]*?)```/, "g"));
1753
1658
  for (const iterator of regex) {
1754
1659
  if (iterator) {
1755
1660
  const [_input, language, code] = iterator;
@@ -1762,24 +1667,26 @@ var _MarkdownCodeBlocksParser = class _MarkdownCodeBlocksParser extends BasePars
1762
1667
  return out;
1763
1668
  }
1764
1669
  };
1765
- __name(_MarkdownCodeBlocksParser, "MarkdownCodeBlocksParser");
1766
- var MarkdownCodeBlocksParser = _MarkdownCodeBlocksParser;
1767
1670
 
1768
1671
  // src/parser/parsers/MarkdownCodeBlock.ts
1769
- var _MarkdownCodeBlockParser = class _MarkdownCodeBlockParser extends BaseParser {
1672
+ var MarkdownCodeBlockParser = class extends BaseParser {
1770
1673
  constructor(options) {
1771
1674
  super("markdownCodeBlock", options);
1772
1675
  }
1773
1676
  parse(input) {
1774
1677
  const [block] = new MarkdownCodeBlocksParser().parse(input);
1678
+ if (!block) {
1679
+ return {
1680
+ code: "",
1681
+ language: ""
1682
+ };
1683
+ }
1775
1684
  return block;
1776
1685
  }
1777
1686
  };
1778
- __name(_MarkdownCodeBlockParser, "MarkdownCodeBlockParser");
1779
- var MarkdownCodeBlockParser = _MarkdownCodeBlockParser;
1780
1687
 
1781
1688
  // src/parser/parsers/StringExtractParser.ts
1782
- var _StringExtractParser = class _StringExtractParser extends BaseParser {
1689
+ var StringExtractParser = class extends BaseParser {
1783
1690
  constructor(options) {
1784
1691
  super("stringExtract", options);
1785
1692
  __publicField(this, "enum", []);
@@ -1792,7 +1699,10 @@ var _StringExtractParser = class _StringExtractParser extends BaseParser {
1792
1699
  }
1793
1700
  }
1794
1701
  parse(text) {
1795
- assert(typeof text === "string", `Invalid input. Expected string. Received ${typeof text}.`);
1702
+ assert(
1703
+ typeof text === "string",
1704
+ `Invalid input. Expected string. Received ${typeof text}.`
1705
+ );
1796
1706
  for (const option of this.enum) {
1797
1707
  const regex = this.ignoreCase ? new RegExp(option.toLowerCase(), "i") : new RegExp(option);
1798
1708
  if (regex.test(text)) {
@@ -1802,8 +1712,6 @@ var _StringExtractParser = class _StringExtractParser extends BaseParser {
1802
1712
  return "";
1803
1713
  }
1804
1714
  };
1805
- __name(_StringExtractParser, "StringExtractParser");
1806
- var StringExtractParser = _StringExtractParser;
1807
1715
 
1808
1716
  // src/parser/_functions.ts
1809
1717
  function createParser(type, options = {}) {
@@ -1833,16 +1741,18 @@ function createParser(type, options = {}) {
1833
1741
  return new StringParser();
1834
1742
  }
1835
1743
  }
1836
- __name(createParser, "createParser");
1837
1744
  function createCustomParser(name, parserFn) {
1838
1745
  return new CustomParser(name, parserFn);
1839
1746
  }
1840
- __name(createCustomParser, "createCustomParser");
1841
1747
 
1842
1748
  // src/executor/llm.ts
1843
- var _LlmExecutor = class _LlmExecutor extends BaseExecutor {
1749
+ var LlmExecutor = class extends BaseExecutor {
1844
1750
  constructor(llmConfiguration, options) {
1845
- super(llmConfiguration.name || "anonymous-llm-executor", "llm-executor", options);
1751
+ super(
1752
+ llmConfiguration.name || "anonymous-llm-executor",
1753
+ "llm-executor",
1754
+ options
1755
+ );
1846
1756
  __publicField(this, "llm");
1847
1757
  __publicField(this, "prompt");
1848
1758
  __publicField(this, "promptFn");
@@ -1858,12 +1768,13 @@ var _LlmExecutor = class _LlmExecutor extends BaseExecutor {
1858
1768
  }
1859
1769
  }
1860
1770
  async execute(_input, _options) {
1771
+ const input = _input ?? {};
1861
1772
  if (this?.parser instanceof JsonParser && this.parser.schema) {
1862
1773
  _options = Object.assign(_options || {}, {
1863
1774
  jsonSchema: this.parser.schema
1864
1775
  });
1865
1776
  }
1866
- return super.execute(_input, _options);
1777
+ return super.execute(input, _options);
1867
1778
  }
1868
1779
  async handler(_input, ..._args) {
1869
1780
  const call = await this.llm.call(_input, ..._args);
@@ -1908,57 +1819,45 @@ var _LlmExecutor = class _LlmExecutor extends BaseExecutor {
1908
1819
  return this.llm.getTraceId();
1909
1820
  }
1910
1821
  };
1911
- __name(_LlmExecutor, "LlmExecutor");
1912
- var LlmExecutor = _LlmExecutor;
1913
1822
 
1914
1823
  // src/executor/_functions.ts
1915
1824
  function createCoreExecutor(handler, options) {
1916
- return new CoreExecutor({
1917
- handler
1918
- }, options);
1825
+ return new CoreExecutor({ handler }, options);
1919
1826
  }
1920
- __name(createCoreExecutor, "createCoreExecutor");
1921
1827
  function createLlmExecutor(llmConfiguration, options) {
1922
1828
  return new LlmExecutor(llmConfiguration, options);
1923
1829
  }
1924
- __name(createLlmExecutor, "createLlmExecutor");
1925
1830
 
1926
1831
  // src/executor/llm-openai-function.ts
1927
- var _LlmExecutorOpenAiFunctions = class _LlmExecutorOpenAiFunctions extends LlmExecutor {
1832
+ var LlmExecutorOpenAiFunctions = class extends LlmExecutor {
1928
1833
  constructor(llmConfiguration, options) {
1929
- super(Object.assign({}, llmConfiguration, {
1930
- parser: new OpenAiFunctionParser({
1931
- parser: llmConfiguration.parser || new StringParser()
1932
- })
1933
- }), options);
1834
+ super(
1835
+ Object.assign({}, llmConfiguration, {
1836
+ parser: new OpenAiFunctionParser({
1837
+ parser: llmConfiguration.parser || new StringParser()
1838
+ })
1839
+ }),
1840
+ options
1841
+ );
1934
1842
  }
1935
1843
  async execute(_input, _options) {
1936
1844
  return super.execute(_input, _options);
1937
1845
  }
1938
1846
  };
1939
- __name(_LlmExecutorOpenAiFunctions, "LlmExecutorOpenAiFunctions");
1940
- var LlmExecutorOpenAiFunctions = _LlmExecutorOpenAiFunctions;
1941
1847
 
1942
1848
  // src/utils/modules/enforceResultAttributes.ts
1943
1849
  function enforceResultAttributes(input) {
1944
1850
  if (!input) {
1945
- return {
1946
- result: input,
1947
- attributes: {}
1948
- };
1851
+ return { result: input, attributes: {} };
1949
1852
  }
1950
1853
  if (typeof input === "object" && (Object.keys(input).length === 2 && "result" in input && "attributes" in input || Object.keys(input).length === 1 && ("result" in input || "attributes" in input))) {
1951
1854
  return input;
1952
1855
  }
1953
- return {
1954
- result: input,
1955
- attributes: {}
1956
- };
1856
+ return { result: input, attributes: {} };
1957
1857
  }
1958
- __name(enforceResultAttributes, "enforceResultAttributes");
1959
1858
 
1960
1859
  // src/plugins/callable/callable.ts
1961
- var _CallableExecutor = class _CallableExecutor {
1860
+ var CallableExecutor = class {
1962
1861
  constructor(options) {
1963
1862
  __publicField(this, "name");
1964
1863
  __publicField(this, "key");
@@ -1993,32 +1892,29 @@ var _CallableExecutor = class _CallableExecutor {
1993
1892
  async validateInput(input) {
1994
1893
  try {
1995
1894
  if (typeof this._validateInput === "function") {
1996
- const response = await this._validateInput(ensureInputIsObject(input), this._handler.getMetadata());
1895
+ const response = await this._validateInput(
1896
+ ensureInputIsObject(input),
1897
+ this._handler.getMetadata()
1898
+ );
1997
1899
  return enforceResultAttributes(response);
1998
1900
  }
1999
- return {
2000
- result: true,
2001
- attributes: {}
2002
- };
1901
+ return { result: true, attributes: {} };
2003
1902
  } catch (error) {
2004
- return {
2005
- result: false,
2006
- attributes: {
2007
- error: error.message
2008
- }
2009
- };
1903
+ return { result: false, attributes: { error: error.message } };
2010
1904
  }
2011
1905
  }
2012
1906
  visibilityHandler(input, attributes) {
2013
1907
  if (typeof this._visibilityHandler === "function") {
2014
- return this._visibilityHandler(input, this._handler.getMetadata(), attributes);
1908
+ return this._visibilityHandler(
1909
+ input,
1910
+ this._handler.getMetadata(),
1911
+ attributes
1912
+ );
2015
1913
  }
2016
1914
  return true;
2017
1915
  }
2018
1916
  };
2019
- __name(_CallableExecutor, "CallableExecutor");
2020
- var CallableExecutor = _CallableExecutor;
2021
- var _UseExecutorsBase = class _UseExecutorsBase {
1917
+ var UseExecutorsBase = class {
2022
1918
  constructor(handlers) {
2023
1919
  __publicField(this, "handlers", []);
2024
1920
  this.handlers = handlers;
@@ -2030,18 +1926,21 @@ var _UseExecutorsBase = class _UseExecutorsBase {
2030
1926
  return this.handlers.find((a) => a.name === name);
2031
1927
  }
2032
1928
  getFunctions() {
2033
- return [
2034
- ...this.handlers
2035
- ];
1929
+ return [...this.handlers];
2036
1930
  }
2037
1931
  getVisibleFunctions(_input, _attributes = {}) {
2038
1932
  const handlers = this.getFunctions();
2039
- return handlers.filter((a) => typeof a.visibilityHandler === "undefined" || typeof a.visibilityHandler === "function" && a.visibilityHandler(_input, _attributes));
1933
+ return handlers.filter(
1934
+ (a) => typeof a.visibilityHandler === "undefined" || typeof a.visibilityHandler === "function" && a.visibilityHandler(_input, _attributes)
1935
+ );
2040
1936
  }
2041
1937
  async callFunction(name, input) {
2042
1938
  try {
2043
1939
  const handler = this.getFunction(name);
2044
- assert(handler, `[invalid handler] The handler (${name}) does not exist.`);
1940
+ assert(
1941
+ handler,
1942
+ `[invalid handler] The handler (${name}) does not exist.`
1943
+ );
2045
1944
  const result = await handler.execute(ensureInputIsObject(input));
2046
1945
  return result;
2047
1946
  } catch (error) {
@@ -2051,41 +1950,37 @@ var _UseExecutorsBase = class _UseExecutorsBase {
2051
1950
  async validateFunctionInput(name, input) {
2052
1951
  try {
2053
1952
  const handler = this.getFunction(name);
2054
- assert(handler, `[invalid handler] The handler (${name}) does not exist.`);
2055
- const result = await handler.validateInput(ensureInputIsObject(input));
1953
+ assert(
1954
+ handler,
1955
+ `[invalid handler] The handler (${name}) does not exist.`
1956
+ );
1957
+ const result = await handler.validateInput(
1958
+ ensureInputIsObject(input)
1959
+ );
2056
1960
  return result;
2057
1961
  } catch (error) {
2058
- return {
2059
- result: false,
2060
- attributes: {
2061
- error: error.message
2062
- }
2063
- };
1962
+ return { result: false, attributes: { error: error.message } };
2064
1963
  }
2065
1964
  }
2066
1965
  };
2067
- __name(_UseExecutorsBase, "UseExecutorsBase");
2068
- var UseExecutorsBase = _UseExecutorsBase;
2069
1966
 
2070
1967
  // src/plugins/callable/index.ts
2071
1968
  function createCallableExecutor(options) {
2072
1969
  return new CallableExecutor(options);
2073
1970
  }
2074
- __name(createCallableExecutor, "createCallableExecutor");
2075
- var _UseExecutors = class _UseExecutors extends UseExecutorsBase {
1971
+ var UseExecutors = class extends UseExecutorsBase {
2076
1972
  constructor(handlers) {
2077
1973
  super(handlers);
2078
1974
  }
2079
1975
  };
2080
- __name(_UseExecutors, "UseExecutors");
2081
- var UseExecutors = _UseExecutors;
2082
1976
  function useExecutors(executors) {
2083
- return new UseExecutors(executors.map((e) => {
2084
- if (e instanceof CallableExecutor) return e;
2085
- return createCallableExecutor(e);
2086
- }));
1977
+ return new UseExecutors(
1978
+ executors.map((e) => {
1979
+ if (e instanceof CallableExecutor) return e;
1980
+ return createCallableExecutor(e);
1981
+ })
1982
+ );
2087
1983
  }
2088
- __name(useExecutors, "useExecutors");
2089
1984
 
2090
1985
  // src/utils/modules/deepClone.ts
2091
1986
  function deepClone(obj) {
@@ -2107,7 +2002,6 @@ function deepClone(obj) {
2107
2002
  }
2108
2003
  return obj;
2109
2004
  }
2110
- __name(deepClone, "deepClone");
2111
2005
 
2112
2006
  // src/llm/_utils.withDefaultModel.ts
2113
2007
  function withDefaultModel(obj1, model) {
@@ -2129,7 +2023,15 @@ function withDefaultModel(obj1, model) {
2129
2023
  }
2130
2024
  return copy;
2131
2025
  }
2132
- __name(withDefaultModel, "withDefaultModel");
2026
+
2027
+ // src/utils/modules/getEnvironmentVariable.ts
2028
+ function getEnvironmentVariable(name) {
2029
+ if (typeof process === "object" && process?.env) {
2030
+ return process.env[name];
2031
+ } else {
2032
+ return void 0;
2033
+ }
2034
+ }
2133
2035
 
2134
2036
  // src/llm/config/openai/index.ts
2135
2037
  var openAiChatV1 = {
@@ -2149,17 +2051,12 @@ var openAiChatV1 = {
2149
2051
  mapBody: {
2150
2052
  prompt: {
2151
2053
  key: "messages",
2152
- sanitize: /* @__PURE__ */ __name((v) => {
2054
+ sanitize: (v) => {
2153
2055
  if (typeof v === "string") {
2154
- return [
2155
- {
2156
- role: "user",
2157
- content: v
2158
- }
2159
- ];
2056
+ return [{ role: "user", content: v }];
2160
2057
  }
2161
2058
  return v;
2162
- }, "sanitize")
2059
+ }
2163
2060
  },
2164
2061
  model: {
2165
2062
  key: "model"
@@ -2169,7 +2066,7 @@ var openAiChatV1 = {
2169
2066
  },
2170
2067
  useJson: {
2171
2068
  key: "response_format.type",
2172
- sanitize: /* @__PURE__ */ __name((v) => v ? "json_object" : "text", "sanitize")
2069
+ sanitize: (v) => v ? "json_object" : "text"
2173
2070
  }
2174
2071
  }
2175
2072
  };
@@ -2199,7 +2096,7 @@ var openAiChatMockV1 = {
2199
2096
  },
2200
2097
  useJson: {
2201
2098
  key: "response_format.type",
2202
- sanitize: /* @__PURE__ */ __name((v) => v ? "json_object" : "text", "sanitize")
2099
+ sanitize: (v) => v ? "json_object" : "text"
2203
2100
  }
2204
2101
  }
2205
2102
  };
@@ -2213,35 +2110,17 @@ var openai = {
2213
2110
  // src/llm/config/anthropic/promptSanitize.ts
2214
2111
  function anthropicPromptSanitize(_messages, _inputBodyObj, _outputObj) {
2215
2112
  if (typeof _messages === "string") {
2216
- return [
2217
- {
2218
- role: "user",
2219
- content: _messages
2220
- }
2221
- ];
2113
+ return [{ role: "user", content: _messages }];
2222
2114
  }
2223
- const [first, ...messages] = [
2224
- ..._messages.map((a) => ({
2225
- ...a
2226
- }))
2227
- ];
2115
+ const [first, ...messages] = [..._messages.map((a) => ({ ...a }))];
2228
2116
  if (first.role === "system" && messages.length === 0) {
2229
- return [
2230
- {
2231
- role: "user",
2232
- content: first.content
2233
- },
2234
- ...messages
2235
- ];
2117
+ return [{ role: "user", content: first.content }, ...messages];
2236
2118
  }
2237
2119
  if (first.role === "system" && messages.length > 0) {
2238
2120
  _outputObj.system = first.content;
2239
2121
  return messages.map((m) => {
2240
2122
  if (m.role === "system") {
2241
- return {
2242
- ...m,
2243
- role: "user"
2244
- };
2123
+ return { ...m, role: "user" };
2245
2124
  }
2246
2125
  return m;
2247
2126
  });
@@ -2250,16 +2129,12 @@ function anthropicPromptSanitize(_messages, _inputBodyObj, _outputObj) {
2250
2129
  first,
2251
2130
  ...messages.map((m) => {
2252
2131
  if (m.role === "system") {
2253
- return {
2254
- ...m,
2255
- role: "user"
2256
- };
2132
+ return { ...m, role: "user" };
2257
2133
  }
2258
2134
  return m;
2259
2135
  })
2260
2136
  ];
2261
2137
  }
2262
- __name(anthropicPromptSanitize, "anthropicPromptSanitize");
2263
2138
 
2264
2139
  // src/llm/config/bedrock/index.ts
2265
2140
  var ANTORPIC_BEDROCK_VERSION = "bedrock-2023-05-31";
@@ -2275,10 +2150,7 @@ var amazonAnthropicChatV1 = {
2275
2150
  maxTokens: {},
2276
2151
  awsRegion: {
2277
2152
  default: getEnvironmentVariable("AWS_REGION"),
2278
- required: [
2279
- true,
2280
- "aws region is required"
2281
- ]
2153
+ required: [true, "aws region is required"]
2282
2154
  },
2283
2155
  awsSecretKey: {},
2284
2156
  awsAccessKey: {}
@@ -2321,7 +2193,7 @@ var amazonMetaChatV1 = {
2321
2193
  mapBody: {
2322
2194
  prompt: {
2323
2195
  key: "prompt",
2324
- sanitize: /* @__PURE__ */ __name((messages) => {
2196
+ sanitize: (messages) => {
2325
2197
  if (typeof messages === "string") {
2326
2198
  return messages;
2327
2199
  } else {
@@ -2329,7 +2201,7 @@ var amazonMetaChatV1 = {
2329
2201
  messages
2330
2202
  });
2331
2203
  }
2332
- }, "sanitize")
2204
+ }
2333
2205
  },
2334
2206
  topP: {
2335
2207
  key: "top_p"
@@ -2346,6 +2218,7 @@ var amazonMetaChatV1 = {
2346
2218
  var bedrock = {
2347
2219
  "amazon:anthropic.chat.v1": amazonAnthropicChatV1,
2348
2220
  "amazon:meta.chat.v1": amazonMetaChatV1
2221
+ // "amazon:nova.chat.v1": amazonAmazonNovaChatV1,
2349
2222
  };
2350
2223
 
2351
2224
  // src/llm/config/anthropic/index.ts
@@ -2360,10 +2233,7 @@ var anthropicChatV1 = {
2360
2233
  prompt: {},
2361
2234
  system: {},
2362
2235
  maxTokens: {
2363
- required: [
2364
- true,
2365
- "maxTokens required"
2366
- ],
2236
+ required: [true, "maxTokens required"],
2367
2237
  default: 4096
2368
2238
  },
2369
2239
  anthropicApiKey: {
@@ -2388,10 +2258,22 @@ var anthropicChatV1 = {
2388
2258
  };
2389
2259
  var anthropic = {
2390
2260
  "anthropic.chat.v1": anthropicChatV1,
2391
- "anthropic.claude-3-7-sonnet": withDefaultModel(anthropicChatV1, "claude-3-7-sonnet-latest"),
2392
- "anthropic.claude-3-5-sonnet": withDefaultModel(anthropicChatV1, "claude-3-5-sonnet-latest"),
2393
- "anthropic.claude-3-5-haiku": withDefaultModel(anthropicChatV1, "claude-3-5-haiku-latest"),
2394
- "anthropic.claude-3-opus": withDefaultModel(anthropicChatV1, "claude-3-opus-latest")
2261
+ "anthropic.claude-3-7-sonnet": withDefaultModel(
2262
+ anthropicChatV1,
2263
+ "claude-3-7-sonnet-latest"
2264
+ ),
2265
+ "anthropic.claude-3-5-sonnet": withDefaultModel(
2266
+ anthropicChatV1,
2267
+ "claude-3-5-sonnet-latest"
2268
+ ),
2269
+ "anthropic.claude-3-5-haiku": withDefaultModel(
2270
+ anthropicChatV1,
2271
+ "claude-3-5-haiku-latest"
2272
+ ),
2273
+ "anthropic.claude-3-opus": withDefaultModel(
2274
+ anthropicChatV1,
2275
+ "claude-3-opus-latest"
2276
+ )
2395
2277
  };
2396
2278
 
2397
2279
  // src/llm/config/x/index.ts
@@ -2412,17 +2294,12 @@ var xaiChatV1 = {
2412
2294
  mapBody: {
2413
2295
  prompt: {
2414
2296
  key: "messages",
2415
- sanitize: /* @__PURE__ */ __name((v) => {
2297
+ sanitize: (v) => {
2416
2298
  if (typeof v === "string") {
2417
- return [
2418
- {
2419
- role: "user",
2420
- content: v
2421
- }
2422
- ];
2299
+ return [{ role: "user", content: v }];
2423
2300
  }
2424
2301
  return v;
2425
- }, "sanitize")
2302
+ }
2426
2303
  },
2427
2304
  model: {
2428
2305
  key: "model"
@@ -2432,7 +2309,7 @@ var xaiChatV1 = {
2432
2309
  },
2433
2310
  useJson: {
2434
2311
  key: "response_format.type",
2435
- sanitize: /* @__PURE__ */ __name((v) => v ? "json_object" : "text", "sanitize")
2312
+ sanitize: (v) => v ? "json_object" : "text"
2436
2313
  }
2437
2314
  }
2438
2315
  };
@@ -2454,17 +2331,12 @@ var ollamaChatV1 = {
2454
2331
  mapBody: {
2455
2332
  prompt: {
2456
2333
  key: "messages",
2457
- sanitize: /* @__PURE__ */ __name((v) => {
2334
+ sanitize: (v) => {
2458
2335
  if (typeof v === "string") {
2459
- return [
2460
- {
2461
- role: "user",
2462
- content: v
2463
- }
2464
- ];
2336
+ return [{ role: "user", content: v }];
2465
2337
  }
2466
2338
  return v;
2467
- }, "sanitize")
2339
+ }
2468
2340
  },
2469
2341
  model: {
2470
2342
  key: "model"
@@ -2482,90 +2354,58 @@ var ollama = {
2482
2354
 
2483
2355
  // src/utils/modules/modifyPromptRoleChange.ts
2484
2356
  function modifyPromptRoleChange(messages, roleChanges) {
2485
- const roleChangeMap = new Map(roleChanges.map(({ from, to }) => [
2486
- from,
2487
- to
2488
- ]));
2357
+ const roleChangeMap = new Map(roleChanges.map(({ from, to }) => [from, to]));
2489
2358
  if (Array.isArray(messages)) {
2490
2359
  return messages.map((message) => {
2491
2360
  const newRole2 = roleChangeMap.get(message.role);
2492
- return newRole2 ? {
2493
- ...message,
2494
- role: newRole2
2495
- } : message;
2361
+ return newRole2 ? { ...message, role: newRole2 } : message;
2496
2362
  });
2497
2363
  }
2498
2364
  const newRole = roleChangeMap.get(messages.role);
2499
- return newRole ? {
2500
- ...messages,
2501
- role: newRole
2502
- } : messages;
2365
+ return newRole ? { ...messages, role: newRole } : messages;
2503
2366
  }
2504
- __name(modifyPromptRoleChange, "modifyPromptRoleChange");
2505
2367
 
2506
2368
  // src/llm/config/google/promptSanitizeMessageCallback.ts
2507
2369
  function googleGeminiPromptMessageCallback(_message) {
2508
- let message = {
2509
- ..._message
2510
- };
2370
+ let message = { ..._message };
2511
2371
  message = modifyPromptRoleChange(_message, [
2512
- {
2513
- from: "assistant",
2514
- to: "model"
2515
- }
2372
+ { from: "assistant", to: "model" }
2516
2373
  ]);
2517
2374
  const { role, ...payload } = message;
2518
2375
  const parts = [];
2519
2376
  if (typeof payload.content === "string") {
2520
- parts.push({
2521
- text: message.content
2522
- });
2377
+ parts.push({ text: message.content });
2523
2378
  }
2524
2379
  return {
2525
2380
  role,
2526
2381
  parts
2527
2382
  };
2528
2383
  }
2529
- __name(googleGeminiPromptMessageCallback, "googleGeminiPromptMessageCallback");
2530
2384
 
2531
2385
  // src/llm/config/google/promptSanitize.ts
2532
2386
  function googleGeminiPromptSanitize(_messages, _inputBodyObj, _outputObj) {
2533
2387
  if (typeof _messages === "string") {
2534
- return [
2535
- {
2536
- role: "user",
2537
- parts: [
2538
- {
2539
- text: _messages
2540
- }
2541
- ]
2542
- }
2543
- ];
2388
+ return [{ role: "user", parts: [{ text: _messages }] }];
2544
2389
  }
2545
2390
  if (Array.isArray(_messages)) {
2546
2391
  if (_messages.length === 0) {
2547
2392
  throw new Error("Empty messages array");
2548
2393
  }
2549
2394
  if (_messages.length === 1 && _messages[0].role === "system") {
2550
- return [
2551
- {
2552
- role: "user",
2553
- parts: [
2554
- {
2555
- text: _messages[0].content
2556
- }
2557
- ]
2558
- }
2559
- ];
2395
+ return [{ role: "user", parts: [{ text: _messages[0].content }] }];
2560
2396
  }
2561
- const hasSystemInstruction = _messages.some((message) => message.role === "system");
2397
+ const hasSystemInstruction = _messages.some(
2398
+ (message) => message.role === "system"
2399
+ );
2562
2400
  if (hasSystemInstruction) {
2563
- const theSystemInstructions = _messages.filter((message) => message.role === "system");
2564
- const withoutSystemInstructions = _messages.filter((message) => message.role !== "system");
2401
+ const theSystemInstructions = _messages.filter(
2402
+ (message) => message.role === "system"
2403
+ );
2404
+ const withoutSystemInstructions = _messages.filter(
2405
+ (message) => message.role !== "system"
2406
+ );
2565
2407
  _outputObj.system_instruction = {
2566
- parts: theSystemInstructions.map((message) => ({
2567
- text: message.content
2568
- }))
2408
+ parts: theSystemInstructions.map((message) => ({ text: message.content }))
2569
2409
  };
2570
2410
  return withoutSystemInstructions.map(googleGeminiPromptMessageCallback);
2571
2411
  }
@@ -2573,7 +2413,6 @@ function googleGeminiPromptSanitize(_messages, _inputBodyObj, _outputObj) {
2573
2413
  }
2574
2414
  throw new Error("Invalid messages format");
2575
2415
  }
2576
- __name(googleGeminiPromptSanitize, "googleGeminiPromptSanitize");
2577
2416
 
2578
2417
  // src/llm/config/google/index.ts
2579
2418
  var googleGeminiChatV1 = {
@@ -2594,13 +2433,25 @@ var googleGeminiChatV1 = {
2594
2433
  key: "contents",
2595
2434
  sanitize: googleGeminiPromptSanitize
2596
2435
  }
2436
+ // topP: {
2437
+ // key: "top_p",
2438
+ // }
2597
2439
  }
2598
2440
  };
2599
2441
  var google = {
2600
2442
  "google.chat.v1": googleGeminiChatV1,
2601
- "google.gemini-2.0-flash": withDefaultModel(googleGeminiChatV1, "gemini-2.0-flash"),
2602
- "google.gemini-2.0-flash-lite": withDefaultModel(googleGeminiChatV1, "gemini-2.0-flash-lite"),
2603
- "google.gemini-1.5-pro": withDefaultModel(googleGeminiChatV1, "gemini-1.5-pro")
2443
+ "google.gemini-2.0-flash": withDefaultModel(
2444
+ googleGeminiChatV1,
2445
+ "gemini-2.0-flash"
2446
+ ),
2447
+ "google.gemini-2.0-flash-lite": withDefaultModel(
2448
+ googleGeminiChatV1,
2449
+ "gemini-2.0-flash-lite"
2450
+ ),
2451
+ "google.gemini-1.5-pro": withDefaultModel(
2452
+ googleGeminiChatV1,
2453
+ "gemini-1.5-pro"
2454
+ )
2604
2455
  };
2605
2456
 
2606
2457
  // src/llm/config/deepseek/index.ts
@@ -2621,17 +2472,12 @@ var deepseekChatV1 = {
2621
2472
  mapBody: {
2622
2473
  prompt: {
2623
2474
  key: "messages",
2624
- sanitize: /* @__PURE__ */ __name((v) => {
2475
+ sanitize: (v) => {
2625
2476
  if (typeof v === "string") {
2626
- return [
2627
- {
2628
- role: "user",
2629
- content: v
2630
- }
2631
- ];
2477
+ return [{ role: "user", content: v }];
2632
2478
  }
2633
2479
  return v;
2634
- }, "sanitize")
2480
+ }
2635
2481
  },
2636
2482
  model: {
2637
2483
  key: "model"
@@ -2641,7 +2487,7 @@ var deepseekChatV1 = {
2641
2487
  },
2642
2488
  useJson: {
2643
2489
  key: "response_format.type",
2644
- sanitize: /* @__PURE__ */ __name((v) => v ? "json_object" : "text", "sanitize")
2490
+ sanitize: (v) => v ? "json_object" : "text"
2645
2491
  }
2646
2492
  }
2647
2493
  };
@@ -2677,7 +2523,6 @@ function getLlmConfig(provider) {
2677
2523
  resolution: "Provide a valid provider"
2678
2524
  });
2679
2525
  }
2680
- __name(getLlmConfig, "getLlmConfig");
2681
2526
 
2682
2527
  // src/llm/output/_utils/getResultContent.ts
2683
2528
  function getResultContent(result, index) {
@@ -2686,11 +2531,8 @@ function getResultContent(result, index) {
2686
2531
  const val = arr[index];
2687
2532
  return val ? val : [];
2688
2533
  }
2689
- return [
2690
- ...result.content
2691
- ];
2534
+ return [...result.content];
2692
2535
  }
2693
- __name(getResultContent, "getResultContent");
2694
2536
 
2695
2537
  // src/llm/output/base.ts
2696
2538
  function BaseLlmOutput2(result) {
@@ -2699,12 +2541,8 @@ function BaseLlmOutput2(result) {
2699
2541
  name: result.name,
2700
2542
  usage: result.usage,
2701
2543
  stopReason: result.stopReason,
2702
- options: [
2703
- ...result?.options || []
2704
- ],
2705
- content: [
2706
- ...result.content
2707
- ],
2544
+ options: [...result?.options || []],
2545
+ content: [...result.content],
2708
2546
  created: result?.created || (/* @__PURE__ */ new Date()).getTime()
2709
2547
  });
2710
2548
  function getResult() {
@@ -2718,14 +2556,12 @@ function BaseLlmOutput2(result) {
2718
2556
  stopReason: __result.stopReason
2719
2557
  };
2720
2558
  }
2721
- __name(getResult, "getResult");
2722
2559
  return {
2723
- getResultContent: /* @__PURE__ */ __name((index) => getResultContent(__result, index), "getResultContent"),
2724
- getResultText: /* @__PURE__ */ __name(() => getResultText(__result.content), "getResultText"),
2560
+ getResultContent: (index) => getResultContent(__result, index),
2561
+ getResultText: () => getResultText(__result.content),
2725
2562
  getResult
2726
2563
  };
2727
2564
  }
2728
- __name(BaseLlmOutput2, "BaseLlmOutput2");
2729
2565
 
2730
2566
  // src/llm/output/_util.ts
2731
2567
  function normalizeFunctionCall(input, provider) {
@@ -2736,20 +2572,16 @@ function normalizeFunctionCall(input, provider) {
2736
2572
  }
2737
2573
  return input;
2738
2574
  }
2739
- __name(normalizeFunctionCall, "normalizeFunctionCall");
2740
2575
  function formatOptions(response, handler) {
2741
2576
  const out = [];
2742
2577
  for (const item of response) {
2743
2578
  const result = handler(item);
2744
2579
  if (result) {
2745
- out.push([
2746
- result
2747
- ]);
2580
+ out.push([result]);
2748
2581
  }
2749
2582
  }
2750
2583
  return out;
2751
2584
  }
2752
- __name(formatOptions, "formatOptions");
2753
2585
  function formatContent(response, handler) {
2754
2586
  const out = [];
2755
2587
  const result = handler(response);
@@ -2758,7 +2590,6 @@ function formatContent(response, handler) {
2758
2590
  }
2759
2591
  return out;
2760
2592
  }
2761
- __name(formatContent, "formatContent");
2762
2593
 
2763
2594
  // src/llm/output/openai.ts
2764
2595
  function formatResult(result) {
@@ -2782,7 +2613,6 @@ function formatResult(result) {
2782
2613
  text: ""
2783
2614
  };
2784
2615
  }
2785
- __name(formatResult, "formatResult");
2786
2616
  function OutputOpenAIChat(result, _config) {
2787
2617
  const id = result.id;
2788
2618
  const name = result.model || _config?.model || "openai.unknown";
@@ -2806,7 +2636,6 @@ function OutputOpenAIChat(result, _config) {
2806
2636
  options
2807
2637
  });
2808
2638
  }
2809
- __name(OutputOpenAIChat, "OutputOpenAIChat");
2810
2639
 
2811
2640
  // src/llm/output/claude.ts
2812
2641
  function formatResult2(response) {
@@ -2829,7 +2658,6 @@ function formatResult2(response) {
2829
2658
  }
2830
2659
  return out;
2831
2660
  }
2832
- __name(formatResult2, "formatResult");
2833
2661
  function OutputAnthropicClaude3Chat(result, _config) {
2834
2662
  const id = result.id;
2835
2663
  const name = result.model || _config?.model || "anthropic.unknown";
@@ -2848,17 +2676,13 @@ function OutputAnthropicClaude3Chat(result, _config) {
2848
2676
  content
2849
2677
  });
2850
2678
  }
2851
- __name(OutputAnthropicClaude3Chat, "OutputAnthropicClaude3Chat");
2852
2679
 
2853
2680
  // src/llm/output/llama.ts
2854
2681
  function OutputMetaLlama3Chat(result, _config) {
2855
2682
  const name = _config?.model || "meta";
2856
2683
  const stopReason = result.stop_reason;
2857
2684
  const content = [
2858
- {
2859
- type: "text",
2860
- text: result.generation
2861
- }
2685
+ { type: "text", text: result.generation }
2862
2686
  ];
2863
2687
  const usage = {
2864
2688
  output_tokens: result?.generation_token_count,
@@ -2872,7 +2696,6 @@ function OutputMetaLlama3Chat(result, _config) {
2872
2696
  content
2873
2697
  });
2874
2698
  }
2875
- __name(OutputMetaLlama3Chat, "OutputMetaLlama3Chat");
2876
2699
 
2877
2700
  // src/llm/output/default.ts
2878
2701
  function OutputDefault(result, _config) {
@@ -2880,10 +2703,7 @@ function OutputDefault(result, _config) {
2880
2703
  const stopReason = result?.stopReason || "stop";
2881
2704
  const content = [];
2882
2705
  if (result?.text) {
2883
- content.push({
2884
- type: "text",
2885
- text: result.text
2886
- });
2706
+ content.push({ type: "text", text: result.text });
2887
2707
  }
2888
2708
  const usage = {
2889
2709
  output_tokens: result?.output_tokens || 0,
@@ -2897,7 +2717,6 @@ function OutputDefault(result, _config) {
2897
2717
  content
2898
2718
  });
2899
2719
  }
2900
- __name(OutputDefault, "OutputDefault");
2901
2720
 
2902
2721
  // src/llm/output/xai.ts
2903
2722
  function formatResult3(result) {
@@ -2921,7 +2740,6 @@ function formatResult3(result) {
2921
2740
  text: ""
2922
2741
  };
2923
2742
  }
2924
- __name(formatResult3, "formatResult");
2925
2743
  function OutputXAIChat(result, _config) {
2926
2744
  const id = result.id;
2927
2745
  const name = result?.model;
@@ -2945,7 +2763,6 @@ function OutputXAIChat(result, _config) {
2945
2763
  options
2946
2764
  });
2947
2765
  }
2948
- __name(OutputXAIChat, "OutputXAIChat");
2949
2766
 
2950
2767
  // src/llm/output/_utils/combineJsonl.ts
2951
2768
  function combineJsonl(jsonl) {
@@ -2959,7 +2776,9 @@ function combineJsonl(jsonl) {
2959
2776
  if (lines.length === 0) {
2960
2777
  throw new Error("No JSON lines provided.");
2961
2778
  }
2962
- lines.sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
2779
+ lines.sort(
2780
+ (a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
2781
+ );
2963
2782
  let combinedContent = lines.map((line) => line?.message?.content ?? "").join("");
2964
2783
  combinedContent = combinedContent.replace(/\\u003c/g, "<").replace(/\\u003e/g, ">");
2965
2784
  const finalLine = lines.find((line) => line.done === true);
@@ -2992,7 +2811,6 @@ function combineJsonl(jsonl) {
2992
2811
  content
2993
2812
  };
2994
2813
  }
2995
- __name(combineJsonl, "combineJsonl");
2996
2814
 
2997
2815
  // src/llm/output/ollama.ts
2998
2816
  function OutputOllamaChat(result, _config) {
@@ -3001,9 +2819,7 @@ function OutputOllamaChat(result, _config) {
3001
2819
  const name = combined.result.model || _config?.model || "ollama.unknown";
3002
2820
  const created = (/* @__PURE__ */ new Date(`${combined.result.created_at}`)).getTime();
3003
2821
  const stopReason = `${combined?.result?.done_reason || "stop"}`;
3004
- const content = [
3005
- combined.content
3006
- ];
2822
+ const content = [combined.content];
3007
2823
  const usage = {
3008
2824
  output_tokens: 0,
3009
2825
  input_tokens: 0,
@@ -3019,7 +2835,6 @@ function OutputOllamaChat(result, _config) {
3019
2835
  options: []
3020
2836
  });
3021
2837
  }
3022
- __name(OutputOllamaChat, "OutputOllamaChat");
3023
2838
 
3024
2839
  // src/llm/output/google.gemini/formatResult.ts
3025
2840
  function formatResult4(result) {
@@ -3044,7 +2859,6 @@ function formatResult4(result) {
3044
2859
  text: ""
3045
2860
  };
3046
2861
  }
3047
- __name(formatResult4, "formatResult");
3048
2862
 
3049
2863
  // src/llm/output/google.gemini/index.ts
3050
2864
  function OutputGoogleGeminiChat(result, _config) {
@@ -3070,7 +2884,6 @@ function OutputGoogleGeminiChat(result, _config) {
3070
2884
  options
3071
2885
  });
3072
2886
  }
3073
- __name(OutputGoogleGeminiChat, "OutputGoogleGeminiChat");
3074
2887
 
3075
2888
  // src/llm/output/index.ts
3076
2889
  function getOutputParser(config, response) {
@@ -3102,7 +2915,6 @@ function getOutputParser(config, response) {
3102
2915
  }
3103
2916
  }
3104
2917
  }
3105
- __name(getOutputParser, "getOutputParser");
3106
2918
 
3107
2919
  // src/utils/modules/debug.ts
3108
2920
  function debug(...args) {
@@ -3114,7 +2926,11 @@ function debug(...args) {
3114
2926
  } else if (arg instanceof Array) {
3115
2927
  logs.push(arg.map((item) => JSON.stringify(item, null, 2)));
3116
2928
  } else if (arg instanceof Map) {
3117
- logs.push(Array.from(arg.entries()).map(([key, value]) => `${key}: ${JSON.stringify(value, null, 2)}`));
2929
+ logs.push(
2930
+ Array.from(arg.entries()).map(
2931
+ ([key, value]) => `${key}: ${JSON.stringify(value, null, 2)}`
2932
+ )
2933
+ );
3118
2934
  } else if (arg instanceof Set) {
3119
2935
  logs.push(Array.from(arg).map((item) => JSON.stringify(item, null, 2)));
3120
2936
  } else if (arg instanceof Date) {
@@ -3138,7 +2954,6 @@ function debug(...args) {
3138
2954
  console.debug(...logs);
3139
2955
  }
3140
2956
  }
3141
- __name(debug, "debug");
3142
2957
 
3143
2958
  // src/utils/modules/isValidUrl.ts
3144
2959
  function isValidUrl(input) {
@@ -3149,7 +2964,6 @@ function isValidUrl(input) {
3149
2964
  return false;
3150
2965
  }
3151
2966
  }
3152
- __name(isValidUrl, "isValidUrl");
3153
2967
 
3154
2968
  // src/utils/modules/request.ts
3155
2969
  async function apiRequest(url, options) {
@@ -3185,7 +2999,6 @@ async function apiRequest(url, options) {
3185
2999
  throw new Error(`Request to ${url} failed: ${message}`);
3186
3000
  }
3187
3001
  }
3188
- __name(apiRequest, "apiRequest");
3189
3002
 
3190
3003
  // src/utils/modules/convertDotNotation.ts
3191
3004
  function convertDotNotation(obj) {
@@ -3210,7 +3023,6 @@ function convertDotNotation(obj) {
3210
3023
  }
3211
3024
  return result;
3212
3025
  }
3213
- __name(convertDotNotation, "convertDotNotation");
3214
3026
 
3215
3027
  // src/llm/_utils.mapBody.ts
3216
3028
  function mapBody(template, body) {
@@ -3223,9 +3035,11 @@ function mapBody(template, body) {
3223
3035
  if (providerSpecificKey) {
3224
3036
  let valueForThisKey = body[genericInputKey];
3225
3037
  if (providerSpecificSettings.sanitize && typeof providerSpecificSettings.sanitize === "function") {
3226
- valueForThisKey = providerSpecificSettings.sanitize(valueForThisKey, Object.freeze({
3227
- ...body
3228
- }), output);
3038
+ valueForThisKey = providerSpecificSettings.sanitize(
3039
+ valueForThisKey,
3040
+ Object.freeze({ ...body }),
3041
+ output
3042
+ );
3229
3043
  }
3230
3044
  if (typeof valueForThisKey !== "undefined") {
3231
3045
  output[providerSpecificKey] = valueForThisKey;
@@ -3236,127 +3050,16 @@ function mapBody(template, body) {
3236
3050
  }
3237
3051
  return convertDotNotation(output);
3238
3052
  }
3239
- __name(mapBody, "mapBody");
3240
3053
 
3241
3054
  // src/utils/modules/getAwsAuthorizationHeaders.ts
3242
3055
  var import_credential_providers = require("@aws-sdk/credential-providers");
3243
3056
  var import_signature_v4 = require("@smithy/signature-v4");
3244
-
3245
- // node_modules/@smithy/types/dist-es/auth/auth.js
3246
- var HttpAuthLocation;
3247
- (function(HttpAuthLocation2) {
3248
- HttpAuthLocation2["HEADER"] = "header";
3249
- HttpAuthLocation2["QUERY"] = "query";
3250
- })(HttpAuthLocation || (HttpAuthLocation = {}));
3251
-
3252
- // node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js
3253
- var HttpApiKeyAuthLocation;
3254
- (function(HttpApiKeyAuthLocation2) {
3255
- HttpApiKeyAuthLocation2["HEADER"] = "header";
3256
- HttpApiKeyAuthLocation2["QUERY"] = "query";
3257
- })(HttpApiKeyAuthLocation || (HttpApiKeyAuthLocation = {}));
3258
-
3259
- // node_modules/@smithy/types/dist-es/endpoint.js
3260
- var EndpointURLScheme;
3261
- (function(EndpointURLScheme2) {
3262
- EndpointURLScheme2["HTTP"] = "http";
3263
- EndpointURLScheme2["HTTPS"] = "https";
3264
- })(EndpointURLScheme || (EndpointURLScheme = {}));
3265
-
3266
- // node_modules/@smithy/types/dist-es/extensions/checksum.js
3267
- var AlgorithmId;
3268
- (function(AlgorithmId2) {
3269
- AlgorithmId2["MD5"] = "md5";
3270
- AlgorithmId2["CRC32"] = "crc32";
3271
- AlgorithmId2["CRC32C"] = "crc32c";
3272
- AlgorithmId2["SHA1"] = "sha1";
3273
- AlgorithmId2["SHA256"] = "sha256";
3274
- })(AlgorithmId || (AlgorithmId = {}));
3275
-
3276
- // node_modules/@smithy/types/dist-es/http.js
3277
- var FieldPosition;
3278
- (function(FieldPosition2) {
3279
- FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
3280
- FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
3281
- })(FieldPosition || (FieldPosition = {}));
3282
-
3283
- // node_modules/@smithy/types/dist-es/profile.js
3284
- var IniSectionType;
3285
- (function(IniSectionType2) {
3286
- IniSectionType2["PROFILE"] = "profile";
3287
- IniSectionType2["SSO_SESSION"] = "sso-session";
3288
- IniSectionType2["SERVICES"] = "services";
3289
- })(IniSectionType || (IniSectionType = {}));
3290
-
3291
- // node_modules/@smithy/types/dist-es/transfer.js
3292
- var RequestHandlerProtocol;
3293
- (function(RequestHandlerProtocol2) {
3294
- RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
3295
- RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
3296
- RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
3297
- })(RequestHandlerProtocol || (RequestHandlerProtocol = {}));
3298
-
3299
- // node_modules/@smithy/protocol-http/dist-es/httpRequest.js
3300
- var _HttpRequest = class _HttpRequest {
3301
- constructor(options) {
3302
- this.method = options.method || "GET";
3303
- this.hostname = options.hostname || "localhost";
3304
- this.port = options.port;
3305
- this.query = options.query || {};
3306
- this.headers = options.headers || {};
3307
- this.body = options.body;
3308
- this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:";
3309
- this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/";
3310
- this.username = options.username;
3311
- this.password = options.password;
3312
- this.fragment = options.fragment;
3313
- }
3314
- static clone(request) {
3315
- const cloned = new _HttpRequest({
3316
- ...request,
3317
- headers: {
3318
- ...request.headers
3319
- }
3320
- });
3321
- if (cloned.query) {
3322
- cloned.query = cloneQuery(cloned.query);
3323
- }
3324
- return cloned;
3325
- }
3326
- static isInstance(request) {
3327
- if (!request) {
3328
- return false;
3329
- }
3330
- const req = request;
3331
- return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
3332
- }
3333
- clone() {
3334
- return _HttpRequest.clone(this);
3335
- }
3336
- };
3337
- __name(_HttpRequest, "HttpRequest");
3338
- var HttpRequest = _HttpRequest;
3339
- function cloneQuery(query) {
3340
- return Object.keys(query).reduce((carry, paramName) => {
3341
- const param = query[paramName];
3342
- return {
3343
- ...carry,
3344
- [paramName]: Array.isArray(param) ? [
3345
- ...param
3346
- ] : param
3347
- };
3348
- }, {});
3349
- }
3350
- __name(cloneQuery, "cloneQuery");
3351
-
3352
- // src/utils/modules/getAwsAuthorizationHeaders.ts
3057
+ var import_protocol_http = require("@smithy/protocol-http");
3353
3058
  var import_sha256_js = require("@aws-crypto/sha256-js");
3354
3059
 
3355
3060
  // src/utils/modules/runWithTemporaryEnv.ts
3356
3061
  async function runWithTemporaryEnv(env, handler) {
3357
- const previousEnv = {
3358
- ...process.env
3359
- };
3062
+ const previousEnv = { ...process.env };
3360
3063
  try {
3361
3064
  env();
3362
3065
  const value = await handler();
@@ -3365,22 +3068,24 @@ async function runWithTemporaryEnv(env, handler) {
3365
3068
  process.env = previousEnv;
3366
3069
  }
3367
3070
  }
3368
- __name(runWithTemporaryEnv, "runWithTemporaryEnv");
3369
3071
 
3370
3072
  // src/utils/modules/getAwsAuthorizationHeaders.ts
3371
3073
  async function getAwsAuthorizationHeaders(req, props) {
3372
3074
  const providerChain = (0, import_credential_providers.fromNodeProviderChain)();
3373
- const credentials = await runWithTemporaryEnv(() => {
3374
- if (props.awsAccessKey) {
3375
- process.env["AWS_ACCESS_KEY_ID"] = props.awsAccessKey;
3376
- }
3377
- if (props.awsSecretKey) {
3378
- process.env["AWS_SECRET_ACCESS_KEY"] = props.awsSecretKey;
3379
- }
3380
- if (props.awsSessionToken) {
3381
- process.env["AWS_SESSION_TOKEN"] = props.awsSessionToken;
3382
- }
3383
- }, () => providerChain());
3075
+ const credentials = await runWithTemporaryEnv(
3076
+ () => {
3077
+ if (props.awsAccessKey) {
3078
+ process.env["AWS_ACCESS_KEY_ID"] = props.awsAccessKey;
3079
+ }
3080
+ if (props.awsSecretKey) {
3081
+ process.env["AWS_SECRET_ACCESS_KEY"] = props.awsSecretKey;
3082
+ }
3083
+ if (props.awsSessionToken) {
3084
+ process.env["AWS_SESSION_TOKEN"] = props.awsSessionToken;
3085
+ }
3086
+ },
3087
+ () => providerChain()
3088
+ );
3384
3089
  const signer = new import_signature_v4.SignatureV4({
3385
3090
  service: "bedrock",
3386
3091
  region: props.regionName,
@@ -3388,14 +3093,10 @@ async function getAwsAuthorizationHeaders(req, props) {
3388
3093
  sha256: import_sha256_js.Sha256
3389
3094
  });
3390
3095
  const url = new URL(props.url);
3391
- const headers = !req.headers ? {} : Symbol.iterator in req.headers ? Object.fromEntries(Array.from(req.headers).map((header) => [
3392
- ...header
3393
- ])) : {
3394
- ...req.headers
3395
- };
3096
+ const headers = !req.headers ? {} : Symbol.iterator in req.headers ? Object.fromEntries(Array.from(req.headers).map((header) => [...header])) : { ...req.headers };
3396
3097
  delete headers["connection"];
3397
3098
  headers["host"] = url.hostname;
3398
- const request = new HttpRequest({
3099
+ const request = new import_protocol_http.HttpRequest({
3399
3100
  method: req?.method?.toUpperCase(),
3400
3101
  protocol: url.protocol,
3401
3102
  path: url.pathname,
@@ -3405,7 +3106,6 @@ async function getAwsAuthorizationHeaders(req, props) {
3405
3106
  const signed = await signer.sign(request);
3406
3107
  return signed.headers;
3407
3108
  }
3408
- __name(getAwsAuthorizationHeaders, "getAwsAuthorizationHeaders");
3409
3109
 
3410
3110
  // src/llm/_utils.parseHeaders.ts
3411
3111
  async function parseHeaders(config, replacements, payload) {
@@ -3414,27 +3114,28 @@ async function parseHeaders(config, replacements, payload) {
3414
3114
  const headers = Object.assign({}, payload.headers, parse);
3415
3115
  if (config.provider.startsWith("amazon:") || config.provider.startsWith("amazon.")) {
3416
3116
  const url = payload.url;
3417
- return getAwsAuthorizationHeaders({
3418
- method: config.method,
3419
- headers,
3420
- body: payload.body
3421
- }, {
3422
- url,
3423
- regionName: replacements?.awsRegion || getEnvironmentVariable("AWS_REGION"),
3424
- awsSecretKey: replacements.awsSecretKey,
3425
- awsAccessKey: replacements.awsAccessKey
3426
- });
3117
+ return getAwsAuthorizationHeaders(
3118
+ {
3119
+ method: config.method,
3120
+ headers,
3121
+ body: payload.body
3122
+ },
3123
+ {
3124
+ url,
3125
+ regionName: replacements?.awsRegion || getEnvironmentVariable("AWS_REGION"),
3126
+ awsSecretKey: replacements.awsSecretKey,
3127
+ awsAccessKey: replacements.awsAccessKey
3128
+ }
3129
+ );
3427
3130
  } else {
3428
3131
  return headers;
3429
3132
  }
3430
3133
  }
3431
- __name(parseHeaders, "parseHeaders");
3432
3134
 
3433
3135
  // src/llm/output/_utils/cleanJsonSchemaFor.ts
3434
3136
  var providerFieldExclusions = {
3435
- "openai.chat": [
3436
- "default"
3437
- ]
3137
+ "openai.chat": ["default"]
3138
+ // fields to exclude for openai.chat
3438
3139
  };
3439
3140
  function cleanJsonSchemaFor(schema = {}, provider) {
3440
3141
  const clone = deepClone(schema);
@@ -3452,18 +3153,19 @@ function cleanJsonSchemaFor(schema = {}, provider) {
3452
3153
  }
3453
3154
  return obj;
3454
3155
  }
3455
- __name(removeDisallowedFields, "removeDisallowedFields");
3456
3156
  return removeDisallowedFields(clone);
3457
3157
  }
3458
- __name(cleanJsonSchemaFor, "cleanJsonSchemaFor");
3459
3158
 
3460
3159
  // src/llm/llm.call.ts
3461
3160
  async function useLlm_call(state, messages, _options) {
3462
3161
  const config = getLlmConfig(state.key);
3463
3162
  const { functionCallStrictInput = false } = _options || {};
3464
- const input = mapBody(config.mapBody, Object.assign({}, state, {
3465
- prompt: messages
3466
- }));
3163
+ const input = mapBody(
3164
+ config.mapBody,
3165
+ Object.assign({}, state, {
3166
+ prompt: messages
3167
+ })
3168
+ );
3467
3169
  if (_options && _options?.jsonSchema) {
3468
3170
  if (state.provider === "openai.chat") {
3469
3171
  const curr = input["response_format"] || {};
@@ -3482,14 +3184,15 @@ async function useLlm_call(state, messages, _options) {
3482
3184
  if (_options?.functionCall === "none") {
3483
3185
  _options.functions = [];
3484
3186
  } else if (_options?.functionCall === "auto" || _options?.functionCall === "any") {
3485
- input["tool_choice"] = {
3486
- type: _options?.functionCall
3487
- };
3187
+ input["tool_choice"] = { type: _options?.functionCall };
3488
3188
  } else {
3489
3189
  input["tool_choice"] = _options?.functionCall;
3490
3190
  }
3491
3191
  } else if (state.provider === "openai.chat") {
3492
- input["tool_choice"] = normalizeFunctionCall(_options?.functionCall, "openai");
3192
+ input["tool_choice"] = normalizeFunctionCall(
3193
+ _options?.functionCall,
3194
+ "openai"
3195
+ );
3493
3196
  }
3494
3197
  }
3495
3198
  if (_options && _options?.functions?.length) {
@@ -3508,11 +3211,13 @@ async function useLlm_call(state, messages, _options) {
3508
3211
  };
3509
3212
  return {
3510
3213
  type: "function",
3511
- function: Object.assign(props, {
3512
- parameters: cleanJsonSchemaFor(props.parameters, "openai.chat")
3513
- }, {
3514
- strict: functionCallStrictInput
3515
- })
3214
+ function: Object.assign(
3215
+ props,
3216
+ {
3217
+ parameters: cleanJsonSchemaFor(props.parameters, "openai.chat")
3218
+ },
3219
+ { strict: functionCallStrictInput }
3220
+ )
3516
3221
  };
3517
3222
  });
3518
3223
  }
@@ -3528,16 +3233,14 @@ async function useLlm_call(state, messages, _options) {
3528
3233
  id: "0123-45-6789",
3529
3234
  model: "model",
3530
3235
  created: (/* @__PURE__ */ new Date()).getTime(),
3531
- usage: {
3532
- completion_tokens: 0,
3533
- prompt_tokens: 0,
3534
- total_tokens: 0
3535
- },
3236
+ usage: { completion_tokens: 0, prompt_tokens: 0, total_tokens: 0 },
3536
3237
  choices: [
3537
3238
  {
3538
3239
  message: {
3539
3240
  role: "assistant",
3540
- content: `Hello world from LLM! The input was ${JSON.stringify(messages)}`
3241
+ content: `Hello world from LLM! The input was ${JSON.stringify(
3242
+ messages
3243
+ )}`
3541
3244
  }
3542
3245
  }
3543
3246
  ]
@@ -3548,7 +3251,6 @@ async function useLlm_call(state, messages, _options) {
3548
3251
  });
3549
3252
  return getOutputParser(state, response);
3550
3253
  }
3551
- __name(useLlm_call, "useLlm_call");
3552
3254
 
3553
3255
  // src/llm/_utils.stateFromOptions.ts
3554
3256
  function stateFromOptions(options, config) {
@@ -3567,16 +3269,16 @@ function stateFromOptions(options, config) {
3567
3269
  state[key] = thisConfig.default;
3568
3270
  }
3569
3271
  }
3570
- if (thisConfig?.required && typeof get(state, key) === "undefined") {
3571
- const [required, message = `Error: [${key}] is required`] = thisConfig?.required;
3572
- if (required) {
3272
+ const value = get(state, key);
3273
+ if (Array.isArray(thisConfig?.required)) {
3274
+ const [required, message = `Error: [${key}] is required`] = thisConfig.required;
3275
+ if (required && typeof value === "undefined") {
3573
3276
  throw new Error(message);
3574
3277
  }
3575
3278
  }
3576
3279
  }
3577
3280
  return state;
3578
3281
  }
3579
- __name(stateFromOptions, "stateFromOptions");
3580
3282
 
3581
3283
  // src/utils/modules/deepFreeze.ts
3582
3284
  function deepFreeze(obj) {
@@ -3593,13 +3295,14 @@ function deepFreeze(obj) {
3593
3295
  }
3594
3296
  if (typeof obj === "object" && obj !== null) {
3595
3297
  for (const key of Object.keys(obj)) {
3596
- obj[key] = deepFreeze(obj[key]);
3298
+ obj[key] = deepFreeze(
3299
+ obj[key]
3300
+ );
3597
3301
  }
3598
3302
  return Object.freeze(obj);
3599
3303
  }
3600
3304
  return obj;
3601
3305
  }
3602
- __name(deepFreeze, "deepFreeze");
3603
3306
 
3604
3307
  // src/utils/modules/requestWrapper.ts
3605
3308
  var import_exponential_backoff = require("exponential-backoff");
@@ -3620,19 +3323,29 @@ function apiRequestWrapper(config, options, handler, doNotRetryErrorMessages = [
3620
3323
  async function call(messages, options2) {
3621
3324
  try {
3622
3325
  metrics.total_calls++;
3623
- const result = await (0, import_exponential_backoff.backOff)(() => asyncCallWithTimeout(handler(deepFreeze(state), deepFreeze(messages), deepFreeze(options2)), timeout), {
3624
- startingDelay: 0,
3625
- maxDelay,
3626
- numOfAttempts,
3627
- jitter,
3628
- retry: /* @__PURE__ */ __name((_error, _stepNumber) => {
3629
- if (doNotRetryErrorMessages.includes(_error.message)) {
3630
- return false;
3326
+ const result = await (0, import_exponential_backoff.backOff)(
3327
+ () => asyncCallWithTimeout(
3328
+ handler(
3329
+ deepFreeze(state),
3330
+ deepFreeze(messages),
3331
+ deepFreeze(options2)
3332
+ ),
3333
+ timeout
3334
+ ),
3335
+ {
3336
+ startingDelay: 0,
3337
+ maxDelay,
3338
+ numOfAttempts,
3339
+ jitter,
3340
+ retry: (_error, _stepNumber) => {
3341
+ if (doNotRetryErrorMessages.includes(_error.message)) {
3342
+ return false;
3343
+ }
3344
+ metrics.total_call_retry++;
3345
+ return true;
3631
3346
  }
3632
- metrics.total_call_retry++;
3633
- return true;
3634
- }, "retry")
3635
- });
3347
+ }
3348
+ );
3636
3349
  metrics.total_call_success++;
3637
3350
  return result;
3638
3351
  } catch (error) {
@@ -3640,29 +3353,32 @@ function apiRequestWrapper(config, options, handler, doNotRetryErrorMessages = [
3640
3353
  throw error;
3641
3354
  }
3642
3355
  }
3643
- __name(call, "call");
3644
3356
  function getMetadata() {
3645
- const { awsSecretKey, awsAccessKey, openAiApiKey, anthropicApiKey, ...rest } = options;
3646
- return Object.assign({
3647
- traceId: getTraceId(),
3648
- timeout,
3649
- jitter,
3650
- maxDelay,
3651
- numOfAttempts,
3652
- metrics: {
3653
- ...metrics
3654
- }
3655
- }, rest);
3357
+ const {
3358
+ awsSecretKey,
3359
+ awsAccessKey,
3360
+ openAiApiKey,
3361
+ anthropicApiKey,
3362
+ ...rest
3363
+ } = options;
3364
+ return Object.assign(
3365
+ {
3366
+ traceId: getTraceId(),
3367
+ timeout,
3368
+ jitter,
3369
+ maxDelay,
3370
+ numOfAttempts,
3371
+ metrics: { ...metrics }
3372
+ },
3373
+ rest
3374
+ );
3656
3375
  }
3657
- __name(getMetadata, "getMetadata");
3658
3376
  function getTraceId() {
3659
3377
  return traceId;
3660
3378
  }
3661
- __name(getTraceId, "getTraceId");
3662
3379
  function withTraceId(id) {
3663
3380
  traceId = id;
3664
3381
  }
3665
- __name(withTraceId, "withTraceId");
3666
3382
  return {
3667
3383
  call,
3668
3384
  getTraceId,
@@ -3670,14 +3386,12 @@ function apiRequestWrapper(config, options, handler, doNotRetryErrorMessages = [
3670
3386
  getMetadata
3671
3387
  };
3672
3388
  }
3673
- __name(apiRequestWrapper, "apiRequestWrapper");
3674
3389
 
3675
3390
  // src/llm/llm.ts
3676
3391
  function useLlm(provider, options = {}) {
3677
3392
  const config = getLlmConfig(provider);
3678
3393
  return apiRequestWrapper(config, options, useLlm_call);
3679
3394
  }
3680
- __name(useLlm, "useLlm");
3681
3395
 
3682
3396
  // src/embedding/config.ts
3683
3397
  var embeddingConfigs = {
@@ -3725,10 +3439,7 @@ var embeddingConfigs = {
3725
3439
  },
3726
3440
  awsRegion: {
3727
3441
  default: getEnvironmentVariable("AWS_REGION"),
3728
- required: [
3729
- true,
3730
- "aws region is required"
3731
- ]
3442
+ required: [true, "aws region is required"]
3732
3443
  },
3733
3444
  awsSecretKey: {},
3734
3445
  awsAccessKey: {}
@@ -3753,7 +3464,6 @@ function getEmbeddingConfig(provider) {
3753
3464
  }
3754
3465
  throw new Error(`Invalid provider: ${provider}`);
3755
3466
  }
3756
- __name(getEmbeddingConfig, "getEmbeddingConfig");
3757
3467
 
3758
3468
  // src/embedding/output/BaseEmbeddingOutput.ts
3759
3469
  function BaseEmbeddingOutput(result) {
@@ -3761,9 +3471,7 @@ function BaseEmbeddingOutput(result) {
3761
3471
  id: result.id || (0, import_uuid.v4)(),
3762
3472
  model: result.model,
3763
3473
  usage: result.usage,
3764
- embedding: [
3765
- ...result?.embedding || []
3766
- ],
3474
+ embedding: [...result?.embedding || []],
3767
3475
  created: result?.created || (/* @__PURE__ */ new Date()).getTime()
3768
3476
  });
3769
3477
  function getResult() {
@@ -3775,7 +3483,6 @@ function BaseEmbeddingOutput(result) {
3775
3483
  embedding: __result.embedding
3776
3484
  };
3777
3485
  }
3778
- __name(getResult, "getResult");
3779
3486
  function getEmbedding(index) {
3780
3487
  if (index && index > 0) {
3781
3488
  const arr = __result?.embedding;
@@ -3784,22 +3491,18 @@ function BaseEmbeddingOutput(result) {
3784
3491
  }
3785
3492
  return __result.embedding[0];
3786
3493
  }
3787
- __name(getEmbedding, "getEmbedding");
3788
3494
  return {
3789
3495
  getEmbedding,
3790
3496
  getResult
3791
3497
  };
3792
3498
  }
3793
- __name(BaseEmbeddingOutput, "BaseEmbeddingOutput");
3794
3499
 
3795
3500
  // src/embedding/output/AmazonTitan.ts
3796
3501
  function AmazonTitanEmbedding(result, config) {
3797
3502
  const __result = deepClone(result);
3798
3503
  const model = config.model || "amazon.unknown";
3799
3504
  const created = (/* @__PURE__ */ new Date()).getTime();
3800
- const embedding = [
3801
- __result.embedding
3802
- ];
3505
+ const embedding = [__result.embedding];
3803
3506
  const usage = {
3804
3507
  output_tokens: 0,
3805
3508
  input_tokens: __result.inputTextTokenCount,
@@ -3812,7 +3515,6 @@ function AmazonTitanEmbedding(result, config) {
3812
3515
  embedding
3813
3516
  });
3814
3517
  }
3815
- __name(AmazonTitanEmbedding, "AmazonTitanEmbedding");
3816
3518
 
3817
3519
  // src/embedding/output/OpenAiEmbedding.ts
3818
3520
  function OpenAiEmbedding(result, config) {
@@ -3833,7 +3535,6 @@ function OpenAiEmbedding(result, config) {
3833
3535
  embedding
3834
3536
  });
3835
3537
  }
3836
- __name(OpenAiEmbedding, "OpenAiEmbedding");
3837
3538
 
3838
3539
  // src/embedding/output/getEmbeddingOutputParser.ts
3839
3540
  function getEmbeddingOutputParser(config, response) {
@@ -3846,14 +3547,16 @@ function getEmbeddingOutputParser(config, response) {
3846
3547
  throw new Error("Unsupported provider");
3847
3548
  }
3848
3549
  }
3849
- __name(getEmbeddingOutputParser, "getEmbeddingOutputParser");
3850
3550
 
3851
3551
  // src/embedding/embedding.call.ts
3852
3552
  async function createEmbedding_call(state, _input, _options) {
3853
3553
  const config = getEmbeddingConfig(state.key);
3854
- const input = mapBody(config.mapBody, Object.assign({}, state, {
3855
- input: _input
3856
- }));
3554
+ const input = mapBody(
3555
+ config.mapBody,
3556
+ Object.assign({}, state, {
3557
+ input: _input
3558
+ })
3559
+ );
3857
3560
  const body = JSON.stringify(input);
3858
3561
  const url = replaceTemplateStringSimple(config.endpoint, state);
3859
3562
  const headers = await parseHeaders(config, state, {
@@ -3868,21 +3571,19 @@ async function createEmbedding_call(state, _input, _options) {
3868
3571
  });
3869
3572
  return getEmbeddingOutputParser(state, request);
3870
3573
  }
3871
- __name(createEmbedding_call, "createEmbedding_call");
3872
3574
 
3873
3575
  // src/embedding/embedding.ts
3874
3576
  function createEmbedding(provider, options) {
3875
3577
  const config = getEmbeddingConfig(provider);
3876
3578
  return apiRequestWrapper(config, options, createEmbedding_call);
3877
3579
  }
3878
- __name(createEmbedding, "createEmbedding");
3879
3580
 
3880
3581
  // src/prompt/_base.ts
3881
- var _BasePrompt = class _BasePrompt {
3582
+ var BasePrompt = class {
3882
3583
  /**
3883
- * constructor description
3884
- * @param initialPromptMessage An initial message to add to the prompt.
3885
- */
3584
+ * constructor description
3585
+ * @param initialPromptMessage An initial message to add to the prompt.
3586
+ */
3886
3587
  constructor(initialPromptMessage, options) {
3887
3588
  __publicField(this, "type", "text");
3888
3589
  __publicField(this, "messages", []);
@@ -3916,11 +3617,11 @@ var _BasePrompt = class _BasePrompt {
3916
3617
  }
3917
3618
  }
3918
3619
  /**
3919
- * addToPrompt description
3920
- * @param content The message content
3921
- * @param role The role of the user. Defaults to system for base text prompt.
3922
- * @return instance of BasePrompt.
3923
- */
3620
+ * addToPrompt description
3621
+ * @param content The message content
3622
+ * @param role The role of the user. Defaults to system for base text prompt.
3623
+ * @return instance of BasePrompt.
3624
+ */
3924
3625
  addToPrompt(content, role = "system") {
3925
3626
  if (content) {
3926
3627
  switch (role) {
@@ -3933,10 +3634,10 @@ var _BasePrompt = class _BasePrompt {
3933
3634
  return this;
3934
3635
  }
3935
3636
  /**
3936
- * addSystemMessage description
3937
- * @param content The message content
3938
- * @return returns BasePrompt so it can be chained.
3939
- */
3637
+ * addSystemMessage description
3638
+ * @param content The message content
3639
+ * @return returns BasePrompt so it can be chained.
3640
+ */
3940
3641
  addSystemMessage(content) {
3941
3642
  this.messages.push({
3942
3643
  role: "system",
@@ -3945,58 +3646,62 @@ var _BasePrompt = class _BasePrompt {
3945
3646
  return this;
3946
3647
  }
3947
3648
  /**
3948
- * registerPartial description
3949
- * @param partialOrPartials Additional partials that can be made available to the template parser.
3950
- * @return BasePrompt so it can be chained.
3951
- */
3649
+ * registerPartial description
3650
+ * @param partialOrPartials Additional partials that can be made available to the template parser.
3651
+ * @return BasePrompt so it can be chained.
3652
+ */
3952
3653
  registerPartial(partialOrPartials) {
3953
- const partials2 = Array.isArray(partialOrPartials) ? partialOrPartials : [
3954
- partialOrPartials
3955
- ];
3654
+ const partials2 = Array.isArray(partialOrPartials) ? partialOrPartials : [partialOrPartials];
3956
3655
  this.partials.push(...partials2);
3957
3656
  return this;
3958
3657
  }
3959
3658
  /**
3960
- * registerHelpers description
3961
- * @param helperOrHelpers Additional helper functions that can be made available to the template parser.
3962
- * @return BasePrompt so it can be chained.
3963
- */
3659
+ * registerHelpers description
3660
+ * @param helperOrHelpers Additional helper functions that can be made available to the template parser.
3661
+ * @return BasePrompt so it can be chained.
3662
+ */
3964
3663
  registerHelpers(helperOrHelpers) {
3965
- const helpers = Array.isArray(helperOrHelpers) ? helperOrHelpers : [
3966
- helperOrHelpers
3967
- ];
3664
+ const helpers = Array.isArray(helperOrHelpers) ? helperOrHelpers : [helperOrHelpers];
3968
3665
  this.helpers.push(...helpers);
3969
3666
  return this;
3970
3667
  }
3971
3668
  /**
3972
- * format description
3973
- * @param values The message content
3974
- * @param separator The separator between messages. defaults to "\n\n"
3975
- * @return returns messages formatted with template replacement
3976
- */
3669
+ * format description
3670
+ * @param values The message content
3671
+ * @param separator The separator between messages. defaults to "\n\n"
3672
+ * @return returns messages formatted with template replacement
3673
+ */
3977
3674
  format(values, separator = "\n\n") {
3978
3675
  const replacements = this.getReplacements(values);
3979
3676
  const messages = this.messages.map((message) => {
3980
- return message.content && !Array.isArray(message.content) ? this.replaceTemplateString(this.runPromptFilter(message.content, this.filters.pre, values), replacements, {
3981
- partials: this.partials,
3982
- helpers: this.helpers
3983
- }) : "";
3677
+ return message.content && !Array.isArray(message.content) ? this.replaceTemplateString(
3678
+ this.runPromptFilter(message.content, this.filters.pre, values),
3679
+ replacements,
3680
+ {
3681
+ partials: this.partials,
3682
+ helpers: this.helpers
3683
+ }
3684
+ ) : "";
3984
3685
  }).join(separator);
3985
3686
  return this.runPromptFilter(messages, this.filters.post, values);
3986
3687
  }
3987
3688
  /**
3988
- * format description
3989
- * @param values The message content
3990
- * @param separator The separator between messages. defaults to "\n\n"
3991
- * @return returns messages formatted with template replacement
3992
- */
3689
+ * format description
3690
+ * @param values The message content
3691
+ * @param separator The separator between messages. defaults to "\n\n"
3692
+ * @return returns messages formatted with template replacement
3693
+ */
3993
3694
  async formatAsync(values, separator = "\n\n") {
3994
3695
  const replacements = this.getReplacements(values);
3995
3696
  const _messages = await Promise.all(this.messages.map((message) => {
3996
- return message.content && !Array.isArray(message.content) ? this.replaceTemplateStringAsync(this.runPromptFilter(message.content, this.filters.pre, values), replacements, {
3997
- partials: this.partials,
3998
- helpers: this.helpers
3999
- }) : "";
3697
+ return message.content && !Array.isArray(message.content) ? this.replaceTemplateStringAsync(
3698
+ this.runPromptFilter(message.content, this.filters.pre, values),
3699
+ replacements,
3700
+ {
3701
+ partials: this.partials,
3702
+ helpers: this.helpers
3703
+ }
3704
+ ) : "";
4000
3705
  }));
4001
3706
  const messages = _messages.join(separator);
4002
3707
  return this.runPromptFilter(messages, this.filters.post, values);
@@ -4010,33 +3715,31 @@ var _BasePrompt = class _BasePrompt {
4010
3715
  }
4011
3716
  getReplacements(values) {
4012
3717
  const { input = "", ...restOfValues } = values;
4013
- const replacements = Object.assign({}, {
4014
- ...restOfValues
4015
- }, {
4016
- input,
4017
- _input: input
4018
- });
3718
+ const replacements = Object.assign(
3719
+ {},
3720
+ { ...restOfValues },
3721
+ {
3722
+ input,
3723
+ _input: input
3724
+ }
3725
+ );
4019
3726
  return replacements;
4020
3727
  }
4021
3728
  /**
4022
- * validate description
4023
- * @return {boolean} Returns false if the template is not valid.
4024
- */
3729
+ * validate description
3730
+ * @return {boolean} Returns false if the template is not valid.
3731
+ */
4025
3732
  validate() {
4026
3733
  return true;
4027
3734
  }
4028
3735
  };
4029
- __name(_BasePrompt, "BasePrompt");
4030
- var BasePrompt = _BasePrompt;
4031
3736
 
4032
3737
  // src/prompt/text.ts
4033
- var _TextPrompt = class _TextPrompt extends BasePrompt {
3738
+ var TextPrompt = class extends BasePrompt {
4034
3739
  constructor(base, options) {
4035
3740
  super(base, options);
4036
3741
  }
4037
3742
  };
4038
- __name(_TextPrompt, "TextPrompt");
4039
- var TextPrompt = _TextPrompt;
4040
3743
 
4041
3744
  // src/utils/modules/unescape.ts
4042
3745
  function unescape(str) {
@@ -4050,13 +3753,10 @@ function unescape(str) {
4050
3753
  const entityRegex = /&amp;|&lt;|&gt;|&quot;|&#39;/g;
4051
3754
  return str.replace(entityRegex, (m) => map[m]);
4052
3755
  }
4053
- __name(unescape, "unescape");
4054
3756
 
4055
3757
  // src/utils/modules/extractPromptPlaceholderToken.ts
4056
3758
  function extractPromptPlaceholderToken(tok) {
4057
- if (!tok) return {
4058
- token: ""
4059
- };
3759
+ if (!tok) return { token: "" };
4060
3760
  const token = tok.replace(/ /g, "");
4061
3761
  if (token.substring(2, 18) === ">DialogueHistory") {
4062
3762
  const matchKey = tok.match(/key=(['"`])((?:(?!\1).)*)\1/);
@@ -4083,11 +3783,8 @@ function extractPromptPlaceholderToken(tok) {
4083
3783
  };
4084
3784
  }
4085
3785
  }
4086
- return {
4087
- token: ""
4088
- };
3786
+ return { token: "" };
4089
3787
  }
4090
- __name(extractPromptPlaceholderToken, "extractPromptPlaceholderToken");
4091
3788
 
4092
3789
  // src/utils/modules/escape.ts
4093
3790
  function escape(str) {
@@ -4100,29 +3797,28 @@ function escape(str) {
4100
3797
  };
4101
3798
  return str.replace(/[&<>"']/g, (m) => map[m]);
4102
3799
  }
4103
- __name(escape, "escape");
4104
3800
 
4105
3801
  // src/prompt/chat.ts
4106
- var _ChatPrompt = class _ChatPrompt extends BasePrompt {
3802
+ var ChatPrompt = class extends BasePrompt {
4107
3803
  /**
4108
- * new `ChatPrompt`
4109
- * @param initialSystemPromptMessage (optional) An initial system message to add to the new prompt.
4110
- * @param options (optional) Options to pass in when creating the prompt.
4111
- */
3804
+ * new `ChatPrompt`
3805
+ * @param initialSystemPromptMessage (optional) An initial system message to add to the new prompt.
3806
+ * @param options (optional) Options to pass in when creating the prompt.
3807
+ */
4112
3808
  constructor(initialSystemPromptMessage, options) {
4113
3809
  super(initialSystemPromptMessage, options);
4114
3810
  /**
4115
- * @property type - Prompt type (chat)
4116
- */
3811
+ * @property type - Prompt type (chat)
3812
+ */
4117
3813
  __publicField(this, "type", "chat");
4118
3814
  /**
4119
- * @property parseUserTemplates - Whether or not to allow parsing
4120
- * user messages with the template engine. This could be a risk,
4121
- * so we only parse user messages if explicitly set.
4122
- */
4123
- __publicField(this, "parseUserTemplates", false);
4124
- if (options?.allowUnsafeUserTemplate) {
4125
- this.parseUserTemplates = true;
3815
+ * @property parseUserTemplates - Whether or not to allow parsing
3816
+ * user messages with the template engine. This could be a risk,
3817
+ * so we only parse user messages if explicitly set.
3818
+ */
3819
+ __publicField(this, "parseUserTemplates", true);
3820
+ if (typeof options?.allowUnsafeUserTemplate === "boolean") {
3821
+ this.parseUserTemplates = options?.allowUnsafeUserTemplate;
4126
3822
  }
4127
3823
  }
4128
3824
  addToPrompt(content, role, name) {
@@ -4143,21 +3839,18 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4143
3839
  break;
4144
3840
  case "function_call":
4145
3841
  assert(name, "Function message requires name");
4146
- this.addFunctionCallMessage({
4147
- name,
4148
- arguments: content
4149
- });
3842
+ this.addFunctionCallMessage({ name, arguments: content });
4150
3843
  break;
4151
3844
  }
4152
3845
  }
4153
3846
  return this;
4154
3847
  }
4155
3848
  /**
4156
- * addUserMessage Helper to add a user message to the prompt.
4157
- * @param content The message content.
4158
- * @param name (optional) The name of the user.
4159
- * @return instance of ChatPrompt.
4160
- */
3849
+ * addUserMessage Helper to add a user message to the prompt.
3850
+ * @param content The message content.
3851
+ * @param name (optional) The name of the user.
3852
+ * @return instance of ChatPrompt.
3853
+ */
4161
3854
  addUserMessage(content, name) {
4162
3855
  const message = {
4163
3856
  role: "user",
@@ -4170,10 +3863,10 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4170
3863
  return this;
4171
3864
  }
4172
3865
  /**
4173
- * addAssistantMessage Helper to add an assistant message to the prompt.
4174
- * @param content The message content.
4175
- * @return ChatPrompt so it can be chained.
4176
- */
3866
+ * addAssistantMessage Helper to add an assistant message to the prompt.
3867
+ * @param content The message content.
3868
+ * @return ChatPrompt so it can be chained.
3869
+ */
4177
3870
  addAssistantMessage(content) {
4178
3871
  this.messages.push({
4179
3872
  role: "assistant",
@@ -4182,10 +3875,10 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4182
3875
  return this;
4183
3876
  }
4184
3877
  /**
4185
- * addFunctionMessage Helper to add an assistant message to the prompt.
4186
- * @param content The message content.
4187
- * @return ChatPrompt so it can be chained.
4188
- */
3878
+ * addFunctionMessage Helper to add an assistant message to the prompt.
3879
+ * @param content The message content.
3880
+ * @return ChatPrompt so it can be chained.
3881
+ */
4189
3882
  addFunctionMessage(content, name) {
4190
3883
  this.messages.push({
4191
3884
  role: "function",
@@ -4195,10 +3888,10 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4195
3888
  return this;
4196
3889
  }
4197
3890
  /**
4198
- * addFunctionCallMessage Helper to add an assistant message to the prompt.
4199
- * @param content The message content.
4200
- * @return ChatPrompt so it can be chained.
4201
- */
3891
+ * addFunctionCallMessage Helper to add an assistant message to the prompt.
3892
+ * @param content The message content.
3893
+ * @return ChatPrompt so it can be chained.
3894
+ */
4202
3895
  addFunctionCallMessage(function_call) {
4203
3896
  if (function_call) {
4204
3897
  this.messages.push({
@@ -4213,10 +3906,10 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4213
3906
  return this;
4214
3907
  }
4215
3908
  /**
4216
- * addFromHistory Adds multiple messages at one time.
4217
- * @param history History of chat messages.
4218
- * @return ChatPrompt so it can be chained.
4219
- */
3909
+ * addFromHistory Adds multiple messages at one time.
3910
+ * @param history History of chat messages.
3911
+ * @return ChatPrompt so it can be chained.
3912
+ */
4220
3913
  addFromHistory(history) {
4221
3914
  if (history && Array.isArray(history)) {
4222
3915
  for (const message of history) {
@@ -4243,15 +3936,13 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4243
3936
  return this;
4244
3937
  }
4245
3938
  /**
4246
- * addPlaceholder description
4247
- * @param content The message content
4248
- * @return returns ChatPrompt so it can be chained.
4249
- */
3939
+ * addPlaceholder description
3940
+ * @param content The message content
3941
+ * @return returns ChatPrompt so it can be chained.
3942
+ */
4250
3943
  addChatHistoryPlaceholder(key, options) {
4251
3944
  const start = `{{> DialogueHistory `;
4252
- const params = [
4253
- `key='${String(key)}'`
4254
- ];
3945
+ const params = [`key='${String(key)}'`];
4255
3946
  const end = `}}`;
4256
3947
  if (options?.assistant) {
4257
3948
  params.push(`assistant='${options.assistant}'`);
@@ -4266,17 +3957,14 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4266
3957
  return this;
4267
3958
  }
4268
3959
  /**
4269
- * addTokenPlaceholder description
4270
- * @param content The message content
4271
- * @return returns ChatPrompt so it can be chained.
4272
- */
3960
+ * addTokenPlaceholder description
3961
+ * @param content The message content
3962
+ * @return returns ChatPrompt so it can be chained.
3963
+ */
4273
3964
  addMessagePlaceholder(content, role = "user", name) {
4274
3965
  if (content) {
4275
3966
  const start = `{{> SingleChatMessage `;
4276
- const params = [
4277
- `role='${role}'`,
4278
- `content='${escape(content)}'`
4279
- ];
3967
+ const params = [`role='${role}'`, `content='${escape(content)}'`];
4280
3968
  const end = `}}`;
4281
3969
  if (name) {
4282
3970
  params.push(`name='${name}'`);
@@ -4296,11 +3984,7 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4296
3984
  for (const message of history) {
4297
3985
  switch (message.role) {
4298
3986
  case "user": {
4299
- const m = pick(message, [
4300
- "role",
4301
- "content",
4302
- "name"
4303
- ]);
3987
+ const m = pick(message, ["role", "content", "name"]);
4304
3988
  if (user) {
4305
3989
  m["name"] = user;
4306
3990
  }
@@ -4341,19 +4025,16 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4341
4025
  return messagesOut;
4342
4026
  }
4343
4027
  /**
4344
- * format formats the stored prompt based on input values.
4345
- * Uses template engine.
4346
- * Output is intended for LLM.
4347
- * @param values input values.
4348
- * @return formatted prompt.
4349
- */
4028
+ * format formats the stored prompt based on input values.
4029
+ * Uses template engine.
4030
+ * Output is intended for LLM.
4031
+ * @param values input values.
4032
+ * @return formatted prompt.
4033
+ */
4350
4034
  format(values) {
4351
4035
  const messagesOut = [];
4352
4036
  const replacements = this.getReplacements(values);
4353
- const safeToParseTemplate = [
4354
- "assistant",
4355
- "system"
4356
- ];
4037
+ const safeToParseTemplate = ["assistant", "system"];
4357
4038
  if (this.parseUserTemplates) {
4358
4039
  safeToParseTemplate.push("user");
4359
4040
  }
@@ -4362,7 +4043,12 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4362
4043
  const tokenData = extractPromptPlaceholderToken(message.content);
4363
4044
  switch (tokenData.token) {
4364
4045
  case ">DialogueHistory": {
4365
- messagesOut.push(...this._format_placeholderDialogueHistory(tokenData, replacements));
4046
+ messagesOut.push(
4047
+ ...this._format_placeholderDialogueHistory(
4048
+ tokenData,
4049
+ replacements
4050
+ )
4051
+ );
4366
4052
  break;
4367
4053
  }
4368
4054
  case ">SingleChatMessage": {
@@ -4385,70 +4071,103 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4385
4071
  }
4386
4072
  }
4387
4073
  } else if (message.role === "function") {
4388
- messagesOut.push(Object.assign({}, message, {
4389
- content: this.replaceTemplateString(message.content, replacements, {
4390
- partials: this.partials,
4391
- helpers: this.helpers
4074
+ messagesOut.push(
4075
+ Object.assign({}, message, {
4076
+ content: this.replaceTemplateString(message.content, replacements, {
4077
+ partials: this.partials,
4078
+ helpers: this.helpers
4079
+ })
4392
4080
  })
4393
- }));
4081
+ );
4394
4082
  } else {
4395
4083
  if (safeToParseTemplate.includes(message.role)) {
4396
4084
  if (Array.isArray(message.content)) {
4397
- const content = message.content.map((m) => m.text ? {
4398
- type: "text",
4399
- text: this.runPromptFilter(this.replaceTemplateString(this.runPromptFilter(m.text, this.filters.pre, values), replacements, {
4400
- partials: this.partials,
4401
- helpers: this.helpers
4402
- }), this.filters.post, values)
4403
- } : m);
4404
- messagesOut.push(Object.assign({}, message, {
4405
- content
4406
- }));
4085
+ const content = message.content.map(
4086
+ (m) => m.text ? {
4087
+ type: "text",
4088
+ text: this.runPromptFilter(
4089
+ this.replaceTemplateString(
4090
+ this.runPromptFilter(m.text, this.filters.pre, values),
4091
+ replacements,
4092
+ {
4093
+ partials: this.partials,
4094
+ helpers: this.helpers
4095
+ }
4096
+ ),
4097
+ this.filters.post,
4098
+ values
4099
+ )
4100
+ } : m
4101
+ );
4102
+ messagesOut.push(Object.assign({}, message, { content }));
4407
4103
  } else if (message.content) {
4408
- const content = this.runPromptFilter(this.replaceTemplateString(this.runPromptFilter(message.content, this.filters.pre, values), replacements, {
4409
- partials: this.partials,
4410
- helpers: this.helpers
4411
- }), this.filters.post, values);
4412
- messagesOut.push(Object.assign({}, message, {
4413
- content
4414
- }));
4104
+ const content = this.runPromptFilter(
4105
+ this.replaceTemplateString(
4106
+ this.runPromptFilter(message.content, this.filters.pre, values),
4107
+ replacements,
4108
+ {
4109
+ partials: this.partials,
4110
+ helpers: this.helpers
4111
+ }
4112
+ ),
4113
+ this.filters.post,
4114
+ values
4115
+ );
4116
+ messagesOut.push(Object.assign({}, message, { content }));
4415
4117
  } else {
4416
- messagesOut.push(Object.assign({}, message, {
4417
- content: null
4418
- }));
4118
+ messagesOut.push(Object.assign({}, message, { content: null }));
4419
4119
  }
4420
4120
  } else {
4421
- messagesOut.push(Object.assign({}, message, {
4422
- content: Array.isArray(message.content) ? message.content.map((m) => m.text ? {
4423
- type: "text",
4424
- text: this.runPromptFilter(this.runPromptFilter(m.text, this.filters.pre, values), this.filters.post, values)
4425
- } : m) : message.content && !Array.isArray(message.content) ? this.runPromptFilter(this.runPromptFilter(message.content, this.filters.pre, values), this.filters.post, values) : null
4426
- }));
4121
+ messagesOut.push(
4122
+ Object.assign({}, message, {
4123
+ content: Array.isArray(message.content) ? message.content.map(
4124
+ (m) => m.text ? {
4125
+ type: "text",
4126
+ text: this.runPromptFilter(
4127
+ this.runPromptFilter(
4128
+ m.text,
4129
+ this.filters.pre,
4130
+ values
4131
+ ),
4132
+ this.filters.post,
4133
+ values
4134
+ )
4135
+ } : m
4136
+ ) : message.content && !Array.isArray(message.content) ? this.runPromptFilter(
4137
+ this.runPromptFilter(
4138
+ message.content,
4139
+ this.filters.pre,
4140
+ values
4141
+ ),
4142
+ this.filters.post,
4143
+ values
4144
+ ) : null
4145
+ })
4146
+ );
4427
4147
  }
4428
4148
  }
4429
4149
  }
4430
4150
  return messagesOut;
4431
4151
  }
4432
4152
  /**
4433
- * format formats the stored prompt based on input values.
4434
- * Uses template engine.
4435
- * Output is intended for LLM.
4436
- * @param values input values.
4437
- * @return formatted prompt.
4438
- */
4153
+ * format formats the stored prompt based on input values.
4154
+ * Uses template engine.
4155
+ * Output is intended for LLM.
4156
+ * @param values input values.
4157
+ * @return formatted prompt.
4158
+ */
4439
4159
  async formatAsync(values) {
4440
4160
  const messagesOut = [];
4441
4161
  const replacements = this.getReplacements(values);
4442
- const safeToParseTemplate = [
4443
- "assistant",
4444
- "system"
4445
- ];
4162
+ const safeToParseTemplate = ["assistant", "system"];
4446
4163
  if (this.parseUserTemplates) {
4447
4164
  safeToParseTemplate.push("user");
4448
4165
  }
4449
4166
  for (const message of this.messages) {
4450
4167
  if (message.role === "placeholder") {
4451
- const { token, ...data } = extractPromptPlaceholderToken(message.content);
4168
+ const { token, ...data } = extractPromptPlaceholderToken(
4169
+ message.content
4170
+ );
4452
4171
  switch (token) {
4453
4172
  case ">DialogueHistory": {
4454
4173
  const { key = "", user } = data;
@@ -4457,11 +4176,7 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4457
4176
  for (const message2 of history) {
4458
4177
  switch (message2.role) {
4459
4178
  case "user": {
4460
- const m = pick(message2, [
4461
- "role",
4462
- "content",
4463
- "name"
4464
- ]);
4179
+ const m = pick(message2, ["role", "content", "name"]);
4465
4180
  if (user) {
4466
4181
  m["name"] = user;
4467
4182
  }
@@ -4507,10 +4222,14 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4507
4222
  const message2 = {
4508
4223
  role,
4509
4224
  name,
4510
- content: await this.replaceTemplateStringAsync(content, replacements, {
4511
- partials: this.partials,
4512
- helpers: this.helpers
4513
- })
4225
+ content: await this.replaceTemplateStringAsync(
4226
+ content,
4227
+ replacements,
4228
+ {
4229
+ partials: this.partials,
4230
+ helpers: this.helpers
4231
+ }
4232
+ )
4514
4233
  };
4515
4234
  if (!name || role !== "user") {
4516
4235
  delete message2.name;
@@ -4521,12 +4240,18 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4521
4240
  }
4522
4241
  }
4523
4242
  } else if (message.role === "function") {
4524
- messagesOut.push(Object.assign({}, message, {
4525
- content: await this.replaceTemplateStringAsync(message.content, replacements, {
4526
- partials: this.partials,
4527
- helpers: this.helpers
4243
+ messagesOut.push(
4244
+ Object.assign({}, message, {
4245
+ content: await this.replaceTemplateStringAsync(
4246
+ message.content,
4247
+ replacements,
4248
+ {
4249
+ partials: this.partials,
4250
+ helpers: this.helpers
4251
+ }
4252
+ )
4528
4253
  })
4529
- }));
4254
+ );
4530
4255
  } else {
4531
4256
  if (safeToParseTemplate.includes(message.role)) {
4532
4257
  if (Array.isArray(message.content)) {
@@ -4537,10 +4262,14 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4537
4262
  type: "text",
4538
4263
  text: this.runPromptFilter(
4539
4264
  // HERE
4540
- await this.replaceTemplateStringAsync(this.runPromptFilter(m.text, this.filters.pre, values), replacements, {
4541
- partials: this.partials,
4542
- helpers: this.helpers
4543
- }),
4265
+ await this.replaceTemplateStringAsync(
4266
+ this.runPromptFilter(m.text, this.filters.pre, values),
4267
+ replacements,
4268
+ {
4269
+ partials: this.partials,
4270
+ helpers: this.helpers
4271
+ }
4272
+ ),
4544
4273
  this.filters.post,
4545
4274
  values
4546
4275
  )
@@ -4549,45 +4278,65 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4549
4278
  content.push(m);
4550
4279
  }
4551
4280
  }
4552
- messagesOut.push(Object.assign({}, message, {
4553
- content
4554
- }));
4281
+ messagesOut.push(Object.assign({}, message, { content }));
4555
4282
  } else if (message.content) {
4556
- const content = this.runPromptFilter(await this.replaceTemplateStringAsync(this.runPromptFilter(message.content, this.filters.pre, values), replacements, {
4557
- partials: this.partials,
4558
- helpers: this.helpers
4559
- }), this.filters.post, values);
4560
- messagesOut.push(Object.assign({}, message, {
4561
- content
4562
- }));
4283
+ const content = this.runPromptFilter(
4284
+ await this.replaceTemplateStringAsync(
4285
+ this.runPromptFilter(message.content, this.filters.pre, values),
4286
+ replacements,
4287
+ {
4288
+ partials: this.partials,
4289
+ helpers: this.helpers
4290
+ }
4291
+ ),
4292
+ this.filters.post,
4293
+ values
4294
+ );
4295
+ messagesOut.push(Object.assign({}, message, { content }));
4563
4296
  } else {
4564
- messagesOut.push(Object.assign({}, message, {
4565
- content: null
4566
- }));
4297
+ messagesOut.push(Object.assign({}, message, { content: null }));
4567
4298
  }
4568
4299
  } else {
4569
- messagesOut.push(Object.assign({}, message, {
4570
- content: Array.isArray(message.content) ? message.content.map((m) => m.text ? {
4571
- type: "text",
4572
- text: this.runPromptFilter(this.runPromptFilter(m.text, this.filters.pre, values), this.filters.post, values)
4573
- } : m) : message.content && !Array.isArray(message.content) ? this.runPromptFilter(this.runPromptFilter(message.content, this.filters.pre, values), this.filters.post, values) : null
4574
- }));
4300
+ messagesOut.push(
4301
+ Object.assign({}, message, {
4302
+ content: Array.isArray(message.content) ? message.content.map(
4303
+ (m) => m.text ? {
4304
+ type: "text",
4305
+ text: this.runPromptFilter(
4306
+ this.runPromptFilter(
4307
+ m.text,
4308
+ this.filters.pre,
4309
+ values
4310
+ ),
4311
+ this.filters.post,
4312
+ values
4313
+ )
4314
+ } : m
4315
+ ) : message.content && !Array.isArray(message.content) ? this.runPromptFilter(
4316
+ this.runPromptFilter(
4317
+ message.content,
4318
+ this.filters.pre,
4319
+ values
4320
+ ),
4321
+ this.filters.post,
4322
+ values
4323
+ ) : null
4324
+ })
4325
+ );
4575
4326
  }
4576
4327
  }
4577
4328
  }
4578
4329
  return messagesOut;
4579
4330
  }
4580
4331
  /**
4581
- * validate Ensures there are not unresolved tokens in prompt.
4582
- * @TODO Make this work!
4583
- * @return Returns false if the template is not valid.
4584
- */
4332
+ * validate Ensures there are not unresolved tokens in prompt.
4333
+ * @TODO Make this work!
4334
+ * @return Returns false if the template is not valid.
4335
+ */
4585
4336
  validate() {
4586
4337
  return true;
4587
4338
  }
4588
4339
  };
4589
- __name(_ChatPrompt, "ChatPrompt");
4590
- var ChatPrompt = _ChatPrompt;
4591
4340
 
4592
4341
  // src/prompt/_functions.ts
4593
4342
  function createPrompt(type, initialPromptMessage, options) {
@@ -4598,14 +4347,12 @@ function createPrompt(type, initialPromptMessage, options) {
4598
4347
  return new TextPrompt(initialPromptMessage);
4599
4348
  }
4600
4349
  }
4601
- __name(createPrompt, "createPrompt");
4602
4350
  function createChatPrompt(initialSystemPromptMessage, options) {
4603
4351
  return new ChatPrompt(initialSystemPromptMessage, options);
4604
4352
  }
4605
- __name(createChatPrompt, "createChatPrompt");
4606
4353
 
4607
4354
  // src/state/item.ts
4608
- var _BaseStateItem = class _BaseStateItem {
4355
+ var BaseStateItem = class {
4609
4356
  constructor(key, initialValue) {
4610
4357
  __publicField(this, "key");
4611
4358
  __publicField(this, "value");
@@ -4615,7 +4362,10 @@ var _BaseStateItem = class _BaseStateItem {
4615
4362
  this.initialValue = initialValue;
4616
4363
  }
4617
4364
  setValue(value) {
4618
- assert(typeof value === typeof this.value, `Invalid value type. Expected ${typeof this.value}, received ${typeof value}`);
4365
+ assert(
4366
+ typeof value === typeof this.value,
4367
+ `Invalid value type. Expected ${typeof this.value}, received ${typeof value}`
4368
+ );
4619
4369
  this.value = value;
4620
4370
  }
4621
4371
  getKey() {
@@ -4639,19 +4389,18 @@ var _BaseStateItem = class _BaseStateItem {
4639
4389
  value: this.serializeValue()
4640
4390
  };
4641
4391
  }
4392
+ // deserialize() {}
4642
4393
  };
4643
- __name(_BaseStateItem, "BaseStateItem");
4644
- var BaseStateItem = _BaseStateItem;
4645
- var _DefaultStateItem = class _DefaultStateItem extends BaseStateItem {
4394
+ var DefaultStateItem = class extends BaseStateItem {
4646
4395
  constructor(name, defaultValue) {
4647
4396
  super(name, defaultValue);
4648
4397
  }
4398
+ // serialize() { return {}; }
4399
+ // deserialize() {}
4649
4400
  };
4650
- __name(_DefaultStateItem, "DefaultStateItem");
4651
- var DefaultStateItem = _DefaultStateItem;
4652
4401
 
4653
4402
  // src/state/dialogue.ts
4654
- var _Dialogue = class _Dialogue extends BaseStateItem {
4403
+ var Dialogue = class extends BaseStateItem {
4655
4404
  constructor(name) {
4656
4405
  super(name, []);
4657
4406
  __publicField(this, "name");
@@ -4747,17 +4496,14 @@ var _Dialogue = class _Dialogue extends BaseStateItem {
4747
4496
  return {
4748
4497
  class: "Dialogue",
4749
4498
  name: this.name,
4750
- value: [
4751
- ...this.value
4752
- ]
4499
+ value: [...this.value]
4753
4500
  };
4754
4501
  }
4502
+ // deserialize() {}
4755
4503
  };
4756
- __name(_Dialogue, "Dialogue");
4757
- var Dialogue = _Dialogue;
4758
4504
 
4759
4505
  // src/state/_base.ts
4760
- var _BaseState = class _BaseState {
4506
+ var BaseState = class {
4761
4507
  constructor() {
4762
4508
  __publicField(this, "dialogues", {});
4763
4509
  __publicField(this, "attributes", {});
@@ -4782,8 +4528,14 @@ var _BaseState = class _BaseState {
4782
4528
  return dialogue;
4783
4529
  }
4784
4530
  createContextItem(item) {
4785
- assert(item instanceof BaseStateItem, "Invalid context item. Must be instance of BaseStateItem");
4786
- assert(!this.context[item?.getKey()], `key (${item?.getKey()}) already exists`);
4531
+ assert(
4532
+ item instanceof BaseStateItem,
4533
+ "Invalid context item. Must be instance of BaseStateItem"
4534
+ );
4535
+ assert(
4536
+ !this.context[item?.getKey()],
4537
+ `key (${item?.getKey()}) already exists`
4538
+ );
4787
4539
  this.context[item.getKey()] = item;
4788
4540
  return this.context[item.getKey()];
4789
4541
  }
@@ -4805,14 +4557,16 @@ var _BaseState = class _BaseState {
4805
4557
  serialize() {
4806
4558
  const dialogues = {};
4807
4559
  const context = {};
4808
- const attributes = {
4809
- ...this.attributes
4810
- };
4811
- const dialogueKeys = Object.keys(this.dialogues);
4560
+ const attributes = { ...this.attributes };
4561
+ const dialogueKeys = Object.keys(
4562
+ this.dialogues
4563
+ );
4812
4564
  for (const dialogueKey of dialogueKeys) {
4813
4565
  dialogues[dialogueKey] = this.dialogues[dialogueKey].serialize();
4814
4566
  }
4815
- const contextKeys = Object.keys(this.context);
4567
+ const contextKeys = Object.keys(
4568
+ this.context
4569
+ );
4816
4570
  for (const contextKey of contextKeys) {
4817
4571
  context[contextKey] = this.context[contextKey].serialize();
4818
4572
  }
@@ -4823,9 +4577,7 @@ var _BaseState = class _BaseState {
4823
4577
  };
4824
4578
  }
4825
4579
  };
4826
- __name(_BaseState, "BaseState");
4827
- var BaseState = _BaseState;
4828
- var _DefaultState = class _DefaultState extends BaseState {
4580
+ var DefaultState = class extends BaseState {
4829
4581
  constructor() {
4830
4582
  super();
4831
4583
  }
@@ -4833,22 +4585,17 @@ var _DefaultState = class _DefaultState extends BaseState {
4833
4585
  console.log("Save not implemented in default state.");
4834
4586
  }
4835
4587
  };
4836
- __name(_DefaultState, "DefaultState");
4837
- var DefaultState = _DefaultState;
4838
4588
 
4839
4589
  // src/state/_functions.ts
4840
4590
  function createState() {
4841
4591
  return new DefaultState();
4842
4592
  }
4843
- __name(createState, "createState");
4844
4593
  function createDialogue(name) {
4845
4594
  return new Dialogue(name);
4846
4595
  }
4847
- __name(createDialogue, "createDialogue");
4848
4596
  function createStateItem(name, defaultValue) {
4849
4597
  return new DefaultStateItem(name, defaultValue);
4850
4598
  }
4851
- __name(createStateItem, "createStateItem");
4852
4599
  // Annotate the CommonJS export names for ESM import in node:
4853
4600
  0 && (module.exports = {
4854
4601
  BaseExecutor,
@@ -4873,6 +4620,9 @@ __name(createStateItem, "createStateItem");
4873
4620
  createPrompt,
4874
4621
  createState,
4875
4622
  createStateItem,
4623
+ defineSchema,
4624
+ registerHelpers,
4625
+ registerPartials,
4876
4626
  useExecutors,
4877
4627
  useLlm,
4878
4628
  utils