llm-exe 2.1.7 → 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, "'"));
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,37 +2110,31 @@ 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
- return messages;
2121
+ return messages.map((m) => {
2122
+ if (m.role === "system") {
2123
+ return { ...m, role: "user" };
2124
+ }
2125
+ return m;
2126
+ });
2240
2127
  }
2241
2128
  return [
2242
2129
  first,
2243
- ...messages
2130
+ ...messages.map((m) => {
2131
+ if (m.role === "system") {
2132
+ return { ...m, role: "user" };
2133
+ }
2134
+ return m;
2135
+ })
2244
2136
  ];
2245
2137
  }
2246
- __name(anthropicPromptSanitize, "anthropicPromptSanitize");
2247
2138
 
2248
2139
  // src/llm/config/bedrock/index.ts
2249
2140
  var ANTORPIC_BEDROCK_VERSION = "bedrock-2023-05-31";
@@ -2259,10 +2150,7 @@ var amazonAnthropicChatV1 = {
2259
2150
  maxTokens: {},
2260
2151
  awsRegion: {
2261
2152
  default: getEnvironmentVariable("AWS_REGION"),
2262
- required: [
2263
- true,
2264
- "aws region is required"
2265
- ]
2153
+ required: [true, "aws region is required"]
2266
2154
  },
2267
2155
  awsSecretKey: {},
2268
2156
  awsAccessKey: {}
@@ -2305,7 +2193,7 @@ var amazonMetaChatV1 = {
2305
2193
  mapBody: {
2306
2194
  prompt: {
2307
2195
  key: "prompt",
2308
- sanitize: /* @__PURE__ */ __name((messages) => {
2196
+ sanitize: (messages) => {
2309
2197
  if (typeof messages === "string") {
2310
2198
  return messages;
2311
2199
  } else {
@@ -2313,7 +2201,7 @@ var amazonMetaChatV1 = {
2313
2201
  messages
2314
2202
  });
2315
2203
  }
2316
- }, "sanitize")
2204
+ }
2317
2205
  },
2318
2206
  topP: {
2319
2207
  key: "top_p"
@@ -2330,6 +2218,7 @@ var amazonMetaChatV1 = {
2330
2218
  var bedrock = {
2331
2219
  "amazon:anthropic.chat.v1": amazonAnthropicChatV1,
2332
2220
  "amazon:meta.chat.v1": amazonMetaChatV1
2221
+ // "amazon:nova.chat.v1": amazonAmazonNovaChatV1,
2333
2222
  };
2334
2223
 
2335
2224
  // src/llm/config/anthropic/index.ts
@@ -2344,10 +2233,7 @@ var anthropicChatV1 = {
2344
2233
  prompt: {},
2345
2234
  system: {},
2346
2235
  maxTokens: {
2347
- required: [
2348
- true,
2349
- "maxTokens required"
2350
- ],
2236
+ required: [true, "maxTokens required"],
2351
2237
  default: 4096
2352
2238
  },
2353
2239
  anthropicApiKey: {
@@ -2372,10 +2258,22 @@ var anthropicChatV1 = {
2372
2258
  };
2373
2259
  var anthropic = {
2374
2260
  "anthropic.chat.v1": anthropicChatV1,
2375
- "anthropic.claude-3-7-sonnet": withDefaultModel(anthropicChatV1, "claude-3-7-sonnet-latest"),
2376
- "anthropic.claude-3-5-sonnet": withDefaultModel(anthropicChatV1, "claude-3-5-sonnet-latest"),
2377
- "anthropic.claude-3-5-haiku": withDefaultModel(anthropicChatV1, "claude-3-5-haiku-latest"),
2378
- "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
+ )
2379
2277
  };
2380
2278
 
2381
2279
  // src/llm/config/x/index.ts
@@ -2396,17 +2294,12 @@ var xaiChatV1 = {
2396
2294
  mapBody: {
2397
2295
  prompt: {
2398
2296
  key: "messages",
2399
- sanitize: /* @__PURE__ */ __name((v) => {
2297
+ sanitize: (v) => {
2400
2298
  if (typeof v === "string") {
2401
- return [
2402
- {
2403
- role: "user",
2404
- content: v
2405
- }
2406
- ];
2299
+ return [{ role: "user", content: v }];
2407
2300
  }
2408
2301
  return v;
2409
- }, "sanitize")
2302
+ }
2410
2303
  },
2411
2304
  model: {
2412
2305
  key: "model"
@@ -2416,7 +2309,7 @@ var xaiChatV1 = {
2416
2309
  },
2417
2310
  useJson: {
2418
2311
  key: "response_format.type",
2419
- sanitize: /* @__PURE__ */ __name((v) => v ? "json_object" : "text", "sanitize")
2312
+ sanitize: (v) => v ? "json_object" : "text"
2420
2313
  }
2421
2314
  }
2422
2315
  };
@@ -2438,17 +2331,12 @@ var ollamaChatV1 = {
2438
2331
  mapBody: {
2439
2332
  prompt: {
2440
2333
  key: "messages",
2441
- sanitize: /* @__PURE__ */ __name((v) => {
2334
+ sanitize: (v) => {
2442
2335
  if (typeof v === "string") {
2443
- return [
2444
- {
2445
- role: "user",
2446
- content: v
2447
- }
2448
- ];
2336
+ return [{ role: "user", content: v }];
2449
2337
  }
2450
2338
  return v;
2451
- }, "sanitize")
2339
+ }
2452
2340
  },
2453
2341
  model: {
2454
2342
  key: "model"
@@ -2466,90 +2354,58 @@ var ollama = {
2466
2354
 
2467
2355
  // src/utils/modules/modifyPromptRoleChange.ts
2468
2356
  function modifyPromptRoleChange(messages, roleChanges) {
2469
- const roleChangeMap = new Map(roleChanges.map(({ from, to }) => [
2470
- from,
2471
- to
2472
- ]));
2357
+ const roleChangeMap = new Map(roleChanges.map(({ from, to }) => [from, to]));
2473
2358
  if (Array.isArray(messages)) {
2474
2359
  return messages.map((message) => {
2475
2360
  const newRole2 = roleChangeMap.get(message.role);
2476
- return newRole2 ? {
2477
- ...message,
2478
- role: newRole2
2479
- } : message;
2361
+ return newRole2 ? { ...message, role: newRole2 } : message;
2480
2362
  });
2481
2363
  }
2482
2364
  const newRole = roleChangeMap.get(messages.role);
2483
- return newRole ? {
2484
- ...messages,
2485
- role: newRole
2486
- } : messages;
2365
+ return newRole ? { ...messages, role: newRole } : messages;
2487
2366
  }
2488
- __name(modifyPromptRoleChange, "modifyPromptRoleChange");
2489
2367
 
2490
2368
  // src/llm/config/google/promptSanitizeMessageCallback.ts
2491
2369
  function googleGeminiPromptMessageCallback(_message) {
2492
- let message = {
2493
- ..._message
2494
- };
2370
+ let message = { ..._message };
2495
2371
  message = modifyPromptRoleChange(_message, [
2496
- {
2497
- from: "assistant",
2498
- to: "model"
2499
- }
2372
+ { from: "assistant", to: "model" }
2500
2373
  ]);
2501
2374
  const { role, ...payload } = message;
2502
2375
  const parts = [];
2503
2376
  if (typeof payload.content === "string") {
2504
- parts.push({
2505
- text: message.content
2506
- });
2377
+ parts.push({ text: message.content });
2507
2378
  }
2508
2379
  return {
2509
2380
  role,
2510
2381
  parts
2511
2382
  };
2512
2383
  }
2513
- __name(googleGeminiPromptMessageCallback, "googleGeminiPromptMessageCallback");
2514
2384
 
2515
2385
  // src/llm/config/google/promptSanitize.ts
2516
2386
  function googleGeminiPromptSanitize(_messages, _inputBodyObj, _outputObj) {
2517
2387
  if (typeof _messages === "string") {
2518
- return [
2519
- {
2520
- role: "user",
2521
- parts: [
2522
- {
2523
- text: _messages
2524
- }
2525
- ]
2526
- }
2527
- ];
2388
+ return [{ role: "user", parts: [{ text: _messages }] }];
2528
2389
  }
2529
2390
  if (Array.isArray(_messages)) {
2530
2391
  if (_messages.length === 0) {
2531
2392
  throw new Error("Empty messages array");
2532
2393
  }
2533
2394
  if (_messages.length === 1 && _messages[0].role === "system") {
2534
- return [
2535
- {
2536
- role: "user",
2537
- parts: [
2538
- {
2539
- text: _messages[0].content
2540
- }
2541
- ]
2542
- }
2543
- ];
2395
+ return [{ role: "user", parts: [{ text: _messages[0].content }] }];
2544
2396
  }
2545
- const hasSystemInstruction = _messages.some((message) => message.role === "system");
2397
+ const hasSystemInstruction = _messages.some(
2398
+ (message) => message.role === "system"
2399
+ );
2546
2400
  if (hasSystemInstruction) {
2547
- const theSystemInstructions = _messages.filter((message) => message.role === "system");
2548
- 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
+ );
2549
2407
  _outputObj.system_instruction = {
2550
- parts: theSystemInstructions.map((message) => ({
2551
- text: message.content
2552
- }))
2408
+ parts: theSystemInstructions.map((message) => ({ text: message.content }))
2553
2409
  };
2554
2410
  return withoutSystemInstructions.map(googleGeminiPromptMessageCallback);
2555
2411
  }
@@ -2557,7 +2413,6 @@ function googleGeminiPromptSanitize(_messages, _inputBodyObj, _outputObj) {
2557
2413
  }
2558
2414
  throw new Error("Invalid messages format");
2559
2415
  }
2560
- __name(googleGeminiPromptSanitize, "googleGeminiPromptSanitize");
2561
2416
 
2562
2417
  // src/llm/config/google/index.ts
2563
2418
  var googleGeminiChatV1 = {
@@ -2578,13 +2433,25 @@ var googleGeminiChatV1 = {
2578
2433
  key: "contents",
2579
2434
  sanitize: googleGeminiPromptSanitize
2580
2435
  }
2436
+ // topP: {
2437
+ // key: "top_p",
2438
+ // }
2581
2439
  }
2582
2440
  };
2583
2441
  var google = {
2584
2442
  "google.chat.v1": googleGeminiChatV1,
2585
- "google.gemini-2.0-flash": withDefaultModel(googleGeminiChatV1, "gemini-2.0-flash"),
2586
- "google.gemini-2.0-flash-lite": withDefaultModel(googleGeminiChatV1, "gemini-2.0-flash-lite"),
2587
- "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
+ )
2588
2455
  };
2589
2456
 
2590
2457
  // src/llm/config/deepseek/index.ts
@@ -2605,17 +2472,12 @@ var deepseekChatV1 = {
2605
2472
  mapBody: {
2606
2473
  prompt: {
2607
2474
  key: "messages",
2608
- sanitize: /* @__PURE__ */ __name((v) => {
2475
+ sanitize: (v) => {
2609
2476
  if (typeof v === "string") {
2610
- return [
2611
- {
2612
- role: "user",
2613
- content: v
2614
- }
2615
- ];
2477
+ return [{ role: "user", content: v }];
2616
2478
  }
2617
2479
  return v;
2618
- }, "sanitize")
2480
+ }
2619
2481
  },
2620
2482
  model: {
2621
2483
  key: "model"
@@ -2625,7 +2487,7 @@ var deepseekChatV1 = {
2625
2487
  },
2626
2488
  useJson: {
2627
2489
  key: "response_format.type",
2628
- sanitize: /* @__PURE__ */ __name((v) => v ? "json_object" : "text", "sanitize")
2490
+ sanitize: (v) => v ? "json_object" : "text"
2629
2491
  }
2630
2492
  }
2631
2493
  };
@@ -2661,7 +2523,6 @@ function getLlmConfig(provider) {
2661
2523
  resolution: "Provide a valid provider"
2662
2524
  });
2663
2525
  }
2664
- __name(getLlmConfig, "getLlmConfig");
2665
2526
 
2666
2527
  // src/llm/output/_utils/getResultContent.ts
2667
2528
  function getResultContent(result, index) {
@@ -2670,11 +2531,8 @@ function getResultContent(result, index) {
2670
2531
  const val = arr[index];
2671
2532
  return val ? val : [];
2672
2533
  }
2673
- return [
2674
- ...result.content
2675
- ];
2534
+ return [...result.content];
2676
2535
  }
2677
- __name(getResultContent, "getResultContent");
2678
2536
 
2679
2537
  // src/llm/output/base.ts
2680
2538
  function BaseLlmOutput2(result) {
@@ -2683,12 +2541,8 @@ function BaseLlmOutput2(result) {
2683
2541
  name: result.name,
2684
2542
  usage: result.usage,
2685
2543
  stopReason: result.stopReason,
2686
- options: [
2687
- ...result?.options || []
2688
- ],
2689
- content: [
2690
- ...result.content
2691
- ],
2544
+ options: [...result?.options || []],
2545
+ content: [...result.content],
2692
2546
  created: result?.created || (/* @__PURE__ */ new Date()).getTime()
2693
2547
  });
2694
2548
  function getResult() {
@@ -2702,14 +2556,12 @@ function BaseLlmOutput2(result) {
2702
2556
  stopReason: __result.stopReason
2703
2557
  };
2704
2558
  }
2705
- __name(getResult, "getResult");
2706
2559
  return {
2707
- getResultContent: /* @__PURE__ */ __name((index) => getResultContent(__result, index), "getResultContent"),
2708
- getResultText: /* @__PURE__ */ __name(() => getResultText(__result.content), "getResultText"),
2560
+ getResultContent: (index) => getResultContent(__result, index),
2561
+ getResultText: () => getResultText(__result.content),
2709
2562
  getResult
2710
2563
  };
2711
2564
  }
2712
- __name(BaseLlmOutput2, "BaseLlmOutput2");
2713
2565
 
2714
2566
  // src/llm/output/_util.ts
2715
2567
  function normalizeFunctionCall(input, provider) {
@@ -2720,20 +2572,16 @@ function normalizeFunctionCall(input, provider) {
2720
2572
  }
2721
2573
  return input;
2722
2574
  }
2723
- __name(normalizeFunctionCall, "normalizeFunctionCall");
2724
2575
  function formatOptions(response, handler) {
2725
2576
  const out = [];
2726
2577
  for (const item of response) {
2727
2578
  const result = handler(item);
2728
2579
  if (result) {
2729
- out.push([
2730
- result
2731
- ]);
2580
+ out.push([result]);
2732
2581
  }
2733
2582
  }
2734
2583
  return out;
2735
2584
  }
2736
- __name(formatOptions, "formatOptions");
2737
2585
  function formatContent(response, handler) {
2738
2586
  const out = [];
2739
2587
  const result = handler(response);
@@ -2742,7 +2590,6 @@ function formatContent(response, handler) {
2742
2590
  }
2743
2591
  return out;
2744
2592
  }
2745
- __name(formatContent, "formatContent");
2746
2593
 
2747
2594
  // src/llm/output/openai.ts
2748
2595
  function formatResult(result) {
@@ -2766,7 +2613,6 @@ function formatResult(result) {
2766
2613
  text: ""
2767
2614
  };
2768
2615
  }
2769
- __name(formatResult, "formatResult");
2770
2616
  function OutputOpenAIChat(result, _config) {
2771
2617
  const id = result.id;
2772
2618
  const name = result.model || _config?.model || "openai.unknown";
@@ -2790,7 +2636,6 @@ function OutputOpenAIChat(result, _config) {
2790
2636
  options
2791
2637
  });
2792
2638
  }
2793
- __name(OutputOpenAIChat, "OutputOpenAIChat");
2794
2639
 
2795
2640
  // src/llm/output/claude.ts
2796
2641
  function formatResult2(response) {
@@ -2813,7 +2658,6 @@ function formatResult2(response) {
2813
2658
  }
2814
2659
  return out;
2815
2660
  }
2816
- __name(formatResult2, "formatResult");
2817
2661
  function OutputAnthropicClaude3Chat(result, _config) {
2818
2662
  const id = result.id;
2819
2663
  const name = result.model || _config?.model || "anthropic.unknown";
@@ -2832,17 +2676,13 @@ function OutputAnthropicClaude3Chat(result, _config) {
2832
2676
  content
2833
2677
  });
2834
2678
  }
2835
- __name(OutputAnthropicClaude3Chat, "OutputAnthropicClaude3Chat");
2836
2679
 
2837
2680
  // src/llm/output/llama.ts
2838
2681
  function OutputMetaLlama3Chat(result, _config) {
2839
2682
  const name = _config?.model || "meta";
2840
2683
  const stopReason = result.stop_reason;
2841
2684
  const content = [
2842
- {
2843
- type: "text",
2844
- text: result.generation
2845
- }
2685
+ { type: "text", text: result.generation }
2846
2686
  ];
2847
2687
  const usage = {
2848
2688
  output_tokens: result?.generation_token_count,
@@ -2856,7 +2696,6 @@ function OutputMetaLlama3Chat(result, _config) {
2856
2696
  content
2857
2697
  });
2858
2698
  }
2859
- __name(OutputMetaLlama3Chat, "OutputMetaLlama3Chat");
2860
2699
 
2861
2700
  // src/llm/output/default.ts
2862
2701
  function OutputDefault(result, _config) {
@@ -2864,10 +2703,7 @@ function OutputDefault(result, _config) {
2864
2703
  const stopReason = result?.stopReason || "stop";
2865
2704
  const content = [];
2866
2705
  if (result?.text) {
2867
- content.push({
2868
- type: "text",
2869
- text: result.text
2870
- });
2706
+ content.push({ type: "text", text: result.text });
2871
2707
  }
2872
2708
  const usage = {
2873
2709
  output_tokens: result?.output_tokens || 0,
@@ -2881,7 +2717,6 @@ function OutputDefault(result, _config) {
2881
2717
  content
2882
2718
  });
2883
2719
  }
2884
- __name(OutputDefault, "OutputDefault");
2885
2720
 
2886
2721
  // src/llm/output/xai.ts
2887
2722
  function formatResult3(result) {
@@ -2905,7 +2740,6 @@ function formatResult3(result) {
2905
2740
  text: ""
2906
2741
  };
2907
2742
  }
2908
- __name(formatResult3, "formatResult");
2909
2743
  function OutputXAIChat(result, _config) {
2910
2744
  const id = result.id;
2911
2745
  const name = result?.model;
@@ -2929,7 +2763,6 @@ function OutputXAIChat(result, _config) {
2929
2763
  options
2930
2764
  });
2931
2765
  }
2932
- __name(OutputXAIChat, "OutputXAIChat");
2933
2766
 
2934
2767
  // src/llm/output/_utils/combineJsonl.ts
2935
2768
  function combineJsonl(jsonl) {
@@ -2943,7 +2776,9 @@ function combineJsonl(jsonl) {
2943
2776
  if (lines.length === 0) {
2944
2777
  throw new Error("No JSON lines provided.");
2945
2778
  }
2946
- 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
+ );
2947
2782
  let combinedContent = lines.map((line) => line?.message?.content ?? "").join("");
2948
2783
  combinedContent = combinedContent.replace(/\\u003c/g, "<").replace(/\\u003e/g, ">");
2949
2784
  const finalLine = lines.find((line) => line.done === true);
@@ -2976,7 +2811,6 @@ function combineJsonl(jsonl) {
2976
2811
  content
2977
2812
  };
2978
2813
  }
2979
- __name(combineJsonl, "combineJsonl");
2980
2814
 
2981
2815
  // src/llm/output/ollama.ts
2982
2816
  function OutputOllamaChat(result, _config) {
@@ -2985,9 +2819,7 @@ function OutputOllamaChat(result, _config) {
2985
2819
  const name = combined.result.model || _config?.model || "ollama.unknown";
2986
2820
  const created = (/* @__PURE__ */ new Date(`${combined.result.created_at}`)).getTime();
2987
2821
  const stopReason = `${combined?.result?.done_reason || "stop"}`;
2988
- const content = [
2989
- combined.content
2990
- ];
2822
+ const content = [combined.content];
2991
2823
  const usage = {
2992
2824
  output_tokens: 0,
2993
2825
  input_tokens: 0,
@@ -3003,7 +2835,6 @@ function OutputOllamaChat(result, _config) {
3003
2835
  options: []
3004
2836
  });
3005
2837
  }
3006
- __name(OutputOllamaChat, "OutputOllamaChat");
3007
2838
 
3008
2839
  // src/llm/output/google.gemini/formatResult.ts
3009
2840
  function formatResult4(result) {
@@ -3028,7 +2859,6 @@ function formatResult4(result) {
3028
2859
  text: ""
3029
2860
  };
3030
2861
  }
3031
- __name(formatResult4, "formatResult");
3032
2862
 
3033
2863
  // src/llm/output/google.gemini/index.ts
3034
2864
  function OutputGoogleGeminiChat(result, _config) {
@@ -3054,7 +2884,6 @@ function OutputGoogleGeminiChat(result, _config) {
3054
2884
  options
3055
2885
  });
3056
2886
  }
3057
- __name(OutputGoogleGeminiChat, "OutputGoogleGeminiChat");
3058
2887
 
3059
2888
  // src/llm/output/index.ts
3060
2889
  function getOutputParser(config, response) {
@@ -3086,7 +2915,45 @@ function getOutputParser(config, response) {
3086
2915
  }
3087
2916
  }
3088
2917
  }
3089
- __name(getOutputParser, "getOutputParser");
2918
+
2919
+ // src/utils/modules/debug.ts
2920
+ function debug(...args) {
2921
+ const debugValue = getEnvironmentVariable("LLM_EXE_DEBUG");
2922
+ const logs = [];
2923
+ for (const arg of args) {
2924
+ if (arg && typeof arg === "object") {
2925
+ if (arg instanceof Error) {
2926
+ } else if (arg instanceof Array) {
2927
+ logs.push(arg.map((item) => JSON.stringify(item, null, 2)));
2928
+ } else if (arg instanceof Map) {
2929
+ logs.push(
2930
+ Array.from(arg.entries()).map(
2931
+ ([key, value]) => `${key}: ${JSON.stringify(value, null, 2)}`
2932
+ )
2933
+ );
2934
+ } else if (arg instanceof Set) {
2935
+ logs.push(Array.from(arg).map((item) => JSON.stringify(item, null, 2)));
2936
+ } else if (arg instanceof Date) {
2937
+ logs.push(arg.toISOString());
2938
+ } else if (arg instanceof RegExp) {
2939
+ logs.push(arg.toString());
2940
+ } else {
2941
+ try {
2942
+ logs.push(JSON.stringify(arg, null, 2));
2943
+ } catch (error) {
2944
+ console.error("Error parsing object:", error);
2945
+ }
2946
+ }
2947
+ } else if (typeof arg === "string") {
2948
+ logs.push(arg);
2949
+ } else {
2950
+ logs.push(arg);
2951
+ }
2952
+ }
2953
+ if (typeof debugValue === "string" && debugValue !== "" && debugValue.toLowerCase() !== "undefined" && debugValue.toLowerCase() !== "null") {
2954
+ console.debug(...logs);
2955
+ }
2956
+ }
3090
2957
 
3091
2958
  // src/utils/modules/isValidUrl.ts
3092
2959
  function isValidUrl(input) {
@@ -3097,7 +2964,6 @@ function isValidUrl(input) {
3097
2964
  return false;
3098
2965
  }
3099
2966
  }
3100
- __name(isValidUrl, "isValidUrl");
3101
2967
 
3102
2968
  // src/utils/modules/request.ts
3103
2969
  async function apiRequest(url, options) {
@@ -3105,6 +2971,7 @@ async function apiRequest(url, options) {
3105
2971
  ...options
3106
2972
  };
3107
2973
  try {
2974
+ debug(url, finalOptions);
3108
2975
  if (!url || !isValidUrl(url)) {
3109
2976
  throw new Error("Invalid URL");
3110
2977
  }
@@ -3132,7 +2999,6 @@ async function apiRequest(url, options) {
3132
2999
  throw new Error(`Request to ${url} failed: ${message}`);
3133
3000
  }
3134
3001
  }
3135
- __name(apiRequest, "apiRequest");
3136
3002
 
3137
3003
  // src/utils/modules/convertDotNotation.ts
3138
3004
  function convertDotNotation(obj) {
@@ -3157,7 +3023,6 @@ function convertDotNotation(obj) {
3157
3023
  }
3158
3024
  return result;
3159
3025
  }
3160
- __name(convertDotNotation, "convertDotNotation");
3161
3026
 
3162
3027
  // src/llm/_utils.mapBody.ts
3163
3028
  function mapBody(template, body) {
@@ -3170,9 +3035,11 @@ function mapBody(template, body) {
3170
3035
  if (providerSpecificKey) {
3171
3036
  let valueForThisKey = body[genericInputKey];
3172
3037
  if (providerSpecificSettings.sanitize && typeof providerSpecificSettings.sanitize === "function") {
3173
- valueForThisKey = providerSpecificSettings.sanitize(valueForThisKey, Object.freeze({
3174
- ...body
3175
- }), output);
3038
+ valueForThisKey = providerSpecificSettings.sanitize(
3039
+ valueForThisKey,
3040
+ Object.freeze({ ...body }),
3041
+ output
3042
+ );
3176
3043
  }
3177
3044
  if (typeof valueForThisKey !== "undefined") {
3178
3045
  output[providerSpecificKey] = valueForThisKey;
@@ -3183,127 +3050,16 @@ function mapBody(template, body) {
3183
3050
  }
3184
3051
  return convertDotNotation(output);
3185
3052
  }
3186
- __name(mapBody, "mapBody");
3187
3053
 
3188
3054
  // src/utils/modules/getAwsAuthorizationHeaders.ts
3189
3055
  var import_credential_providers = require("@aws-sdk/credential-providers");
3190
3056
  var import_signature_v4 = require("@smithy/signature-v4");
3191
-
3192
- // node_modules/@smithy/types/dist-es/auth/auth.js
3193
- var HttpAuthLocation;
3194
- (function(HttpAuthLocation2) {
3195
- HttpAuthLocation2["HEADER"] = "header";
3196
- HttpAuthLocation2["QUERY"] = "query";
3197
- })(HttpAuthLocation || (HttpAuthLocation = {}));
3198
-
3199
- // node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js
3200
- var HttpApiKeyAuthLocation;
3201
- (function(HttpApiKeyAuthLocation2) {
3202
- HttpApiKeyAuthLocation2["HEADER"] = "header";
3203
- HttpApiKeyAuthLocation2["QUERY"] = "query";
3204
- })(HttpApiKeyAuthLocation || (HttpApiKeyAuthLocation = {}));
3205
-
3206
- // node_modules/@smithy/types/dist-es/endpoint.js
3207
- var EndpointURLScheme;
3208
- (function(EndpointURLScheme2) {
3209
- EndpointURLScheme2["HTTP"] = "http";
3210
- EndpointURLScheme2["HTTPS"] = "https";
3211
- })(EndpointURLScheme || (EndpointURLScheme = {}));
3212
-
3213
- // node_modules/@smithy/types/dist-es/extensions/checksum.js
3214
- var AlgorithmId;
3215
- (function(AlgorithmId2) {
3216
- AlgorithmId2["MD5"] = "md5";
3217
- AlgorithmId2["CRC32"] = "crc32";
3218
- AlgorithmId2["CRC32C"] = "crc32c";
3219
- AlgorithmId2["SHA1"] = "sha1";
3220
- AlgorithmId2["SHA256"] = "sha256";
3221
- })(AlgorithmId || (AlgorithmId = {}));
3222
-
3223
- // node_modules/@smithy/types/dist-es/http.js
3224
- var FieldPosition;
3225
- (function(FieldPosition2) {
3226
- FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
3227
- FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
3228
- })(FieldPosition || (FieldPosition = {}));
3229
-
3230
- // node_modules/@smithy/types/dist-es/profile.js
3231
- var IniSectionType;
3232
- (function(IniSectionType2) {
3233
- IniSectionType2["PROFILE"] = "profile";
3234
- IniSectionType2["SSO_SESSION"] = "sso-session";
3235
- IniSectionType2["SERVICES"] = "services";
3236
- })(IniSectionType || (IniSectionType = {}));
3237
-
3238
- // node_modules/@smithy/types/dist-es/transfer.js
3239
- var RequestHandlerProtocol;
3240
- (function(RequestHandlerProtocol2) {
3241
- RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
3242
- RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
3243
- RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
3244
- })(RequestHandlerProtocol || (RequestHandlerProtocol = {}));
3245
-
3246
- // node_modules/@smithy/protocol-http/dist-es/httpRequest.js
3247
- var _HttpRequest = class _HttpRequest {
3248
- constructor(options) {
3249
- this.method = options.method || "GET";
3250
- this.hostname = options.hostname || "localhost";
3251
- this.port = options.port;
3252
- this.query = options.query || {};
3253
- this.headers = options.headers || {};
3254
- this.body = options.body;
3255
- this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:";
3256
- this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/";
3257
- this.username = options.username;
3258
- this.password = options.password;
3259
- this.fragment = options.fragment;
3260
- }
3261
- static clone(request) {
3262
- const cloned = new _HttpRequest({
3263
- ...request,
3264
- headers: {
3265
- ...request.headers
3266
- }
3267
- });
3268
- if (cloned.query) {
3269
- cloned.query = cloneQuery(cloned.query);
3270
- }
3271
- return cloned;
3272
- }
3273
- static isInstance(request) {
3274
- if (!request) {
3275
- return false;
3276
- }
3277
- const req = request;
3278
- return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
3279
- }
3280
- clone() {
3281
- return _HttpRequest.clone(this);
3282
- }
3283
- };
3284
- __name(_HttpRequest, "HttpRequest");
3285
- var HttpRequest = _HttpRequest;
3286
- function cloneQuery(query) {
3287
- return Object.keys(query).reduce((carry, paramName) => {
3288
- const param = query[paramName];
3289
- return {
3290
- ...carry,
3291
- [paramName]: Array.isArray(param) ? [
3292
- ...param
3293
- ] : param
3294
- };
3295
- }, {});
3296
- }
3297
- __name(cloneQuery, "cloneQuery");
3298
-
3299
- // src/utils/modules/getAwsAuthorizationHeaders.ts
3057
+ var import_protocol_http = require("@smithy/protocol-http");
3300
3058
  var import_sha256_js = require("@aws-crypto/sha256-js");
3301
3059
 
3302
3060
  // src/utils/modules/runWithTemporaryEnv.ts
3303
3061
  async function runWithTemporaryEnv(env, handler) {
3304
- const previousEnv = {
3305
- ...process.env
3306
- };
3062
+ const previousEnv = { ...process.env };
3307
3063
  try {
3308
3064
  env();
3309
3065
  const value = await handler();
@@ -3312,22 +3068,24 @@ async function runWithTemporaryEnv(env, handler) {
3312
3068
  process.env = previousEnv;
3313
3069
  }
3314
3070
  }
3315
- __name(runWithTemporaryEnv, "runWithTemporaryEnv");
3316
3071
 
3317
3072
  // src/utils/modules/getAwsAuthorizationHeaders.ts
3318
3073
  async function getAwsAuthorizationHeaders(req, props) {
3319
3074
  const providerChain = (0, import_credential_providers.fromNodeProviderChain)();
3320
- const credentials = await runWithTemporaryEnv(() => {
3321
- if (props.awsAccessKey) {
3322
- process.env["AWS_ACCESS_KEY_ID"] = props.awsAccessKey;
3323
- }
3324
- if (props.awsSecretKey) {
3325
- process.env["AWS_SECRET_ACCESS_KEY"] = props.awsSecretKey;
3326
- }
3327
- if (props.awsSessionToken) {
3328
- process.env["AWS_SESSION_TOKEN"] = props.awsSessionToken;
3329
- }
3330
- }, () => 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
+ );
3331
3089
  const signer = new import_signature_v4.SignatureV4({
3332
3090
  service: "bedrock",
3333
3091
  region: props.regionName,
@@ -3335,14 +3093,10 @@ async function getAwsAuthorizationHeaders(req, props) {
3335
3093
  sha256: import_sha256_js.Sha256
3336
3094
  });
3337
3095
  const url = new URL(props.url);
3338
- const headers = !req.headers ? {} : Symbol.iterator in req.headers ? Object.fromEntries(Array.from(req.headers).map((header) => [
3339
- ...header
3340
- ])) : {
3341
- ...req.headers
3342
- };
3096
+ const headers = !req.headers ? {} : Symbol.iterator in req.headers ? Object.fromEntries(Array.from(req.headers).map((header) => [...header])) : { ...req.headers };
3343
3097
  delete headers["connection"];
3344
3098
  headers["host"] = url.hostname;
3345
- const request = new HttpRequest({
3099
+ const request = new import_protocol_http.HttpRequest({
3346
3100
  method: req?.method?.toUpperCase(),
3347
3101
  protocol: url.protocol,
3348
3102
  path: url.pathname,
@@ -3352,7 +3106,6 @@ async function getAwsAuthorizationHeaders(req, props) {
3352
3106
  const signed = await signer.sign(request);
3353
3107
  return signed.headers;
3354
3108
  }
3355
- __name(getAwsAuthorizationHeaders, "getAwsAuthorizationHeaders");
3356
3109
 
3357
3110
  // src/llm/_utils.parseHeaders.ts
3358
3111
  async function parseHeaders(config, replacements, payload) {
@@ -3361,27 +3114,28 @@ async function parseHeaders(config, replacements, payload) {
3361
3114
  const headers = Object.assign({}, payload.headers, parse);
3362
3115
  if (config.provider.startsWith("amazon:") || config.provider.startsWith("amazon.")) {
3363
3116
  const url = payload.url;
3364
- return getAwsAuthorizationHeaders({
3365
- method: config.method,
3366
- headers,
3367
- body: payload.body
3368
- }, {
3369
- url,
3370
- regionName: replacements?.awsRegion || getEnvironmentVariable("AWS_REGION"),
3371
- awsSecretKey: replacements.awsSecretKey,
3372
- awsAccessKey: replacements.awsAccessKey
3373
- });
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
+ );
3374
3130
  } else {
3375
3131
  return headers;
3376
3132
  }
3377
3133
  }
3378
- __name(parseHeaders, "parseHeaders");
3379
3134
 
3380
3135
  // src/llm/output/_utils/cleanJsonSchemaFor.ts
3381
3136
  var providerFieldExclusions = {
3382
- "openai.chat": [
3383
- "default"
3384
- ]
3137
+ "openai.chat": ["default"]
3138
+ // fields to exclude for openai.chat
3385
3139
  };
3386
3140
  function cleanJsonSchemaFor(schema = {}, provider) {
3387
3141
  const clone = deepClone(schema);
@@ -3399,18 +3153,19 @@ function cleanJsonSchemaFor(schema = {}, provider) {
3399
3153
  }
3400
3154
  return obj;
3401
3155
  }
3402
- __name(removeDisallowedFields, "removeDisallowedFields");
3403
3156
  return removeDisallowedFields(clone);
3404
3157
  }
3405
- __name(cleanJsonSchemaFor, "cleanJsonSchemaFor");
3406
3158
 
3407
3159
  // src/llm/llm.call.ts
3408
3160
  async function useLlm_call(state, messages, _options) {
3409
3161
  const config = getLlmConfig(state.key);
3410
3162
  const { functionCallStrictInput = false } = _options || {};
3411
- const input = mapBody(config.mapBody, Object.assign({}, state, {
3412
- prompt: messages
3413
- }));
3163
+ const input = mapBody(
3164
+ config.mapBody,
3165
+ Object.assign({}, state, {
3166
+ prompt: messages
3167
+ })
3168
+ );
3414
3169
  if (_options && _options?.jsonSchema) {
3415
3170
  if (state.provider === "openai.chat") {
3416
3171
  const curr = input["response_format"] || {};
@@ -3429,14 +3184,15 @@ async function useLlm_call(state, messages, _options) {
3429
3184
  if (_options?.functionCall === "none") {
3430
3185
  _options.functions = [];
3431
3186
  } else if (_options?.functionCall === "auto" || _options?.functionCall === "any") {
3432
- input["tool_choice"] = {
3433
- type: _options?.functionCall
3434
- };
3187
+ input["tool_choice"] = { type: _options?.functionCall };
3435
3188
  } else {
3436
3189
  input["tool_choice"] = _options?.functionCall;
3437
3190
  }
3438
3191
  } else if (state.provider === "openai.chat") {
3439
- input["tool_choice"] = normalizeFunctionCall(_options?.functionCall, "openai");
3192
+ input["tool_choice"] = normalizeFunctionCall(
3193
+ _options?.functionCall,
3194
+ "openai"
3195
+ );
3440
3196
  }
3441
3197
  }
3442
3198
  if (_options && _options?.functions?.length) {
@@ -3455,11 +3211,13 @@ async function useLlm_call(state, messages, _options) {
3455
3211
  };
3456
3212
  return {
3457
3213
  type: "function",
3458
- function: Object.assign(props, {
3459
- parameters: cleanJsonSchemaFor(props.parameters, "openai.chat")
3460
- }, {
3461
- strict: functionCallStrictInput
3462
- })
3214
+ function: Object.assign(
3215
+ props,
3216
+ {
3217
+ parameters: cleanJsonSchemaFor(props.parameters, "openai.chat")
3218
+ },
3219
+ { strict: functionCallStrictInput }
3220
+ )
3463
3221
  };
3464
3222
  });
3465
3223
  }
@@ -3475,16 +3233,14 @@ async function useLlm_call(state, messages, _options) {
3475
3233
  id: "0123-45-6789",
3476
3234
  model: "model",
3477
3235
  created: (/* @__PURE__ */ new Date()).getTime(),
3478
- usage: {
3479
- completion_tokens: 0,
3480
- prompt_tokens: 0,
3481
- total_tokens: 0
3482
- },
3236
+ usage: { completion_tokens: 0, prompt_tokens: 0, total_tokens: 0 },
3483
3237
  choices: [
3484
3238
  {
3485
3239
  message: {
3486
3240
  role: "assistant",
3487
- 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
+ )}`
3488
3244
  }
3489
3245
  }
3490
3246
  ]
@@ -3495,7 +3251,6 @@ async function useLlm_call(state, messages, _options) {
3495
3251
  });
3496
3252
  return getOutputParser(state, response);
3497
3253
  }
3498
- __name(useLlm_call, "useLlm_call");
3499
3254
 
3500
3255
  // src/llm/_utils.stateFromOptions.ts
3501
3256
  function stateFromOptions(options, config) {
@@ -3514,16 +3269,16 @@ function stateFromOptions(options, config) {
3514
3269
  state[key] = thisConfig.default;
3515
3270
  }
3516
3271
  }
3517
- if (thisConfig?.required && typeof get(state, key) === "undefined") {
3518
- const [required, message = `Error: [${key}] is required`] = thisConfig?.required;
3519
- 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") {
3520
3276
  throw new Error(message);
3521
3277
  }
3522
3278
  }
3523
3279
  }
3524
3280
  return state;
3525
3281
  }
3526
- __name(stateFromOptions, "stateFromOptions");
3527
3282
 
3528
3283
  // src/utils/modules/deepFreeze.ts
3529
3284
  function deepFreeze(obj) {
@@ -3540,13 +3295,14 @@ function deepFreeze(obj) {
3540
3295
  }
3541
3296
  if (typeof obj === "object" && obj !== null) {
3542
3297
  for (const key of Object.keys(obj)) {
3543
- obj[key] = deepFreeze(obj[key]);
3298
+ obj[key] = deepFreeze(
3299
+ obj[key]
3300
+ );
3544
3301
  }
3545
3302
  return Object.freeze(obj);
3546
3303
  }
3547
3304
  return obj;
3548
3305
  }
3549
- __name(deepFreeze, "deepFreeze");
3550
3306
 
3551
3307
  // src/utils/modules/requestWrapper.ts
3552
3308
  var import_exponential_backoff = require("exponential-backoff");
@@ -3567,19 +3323,29 @@ function apiRequestWrapper(config, options, handler, doNotRetryErrorMessages = [
3567
3323
  async function call(messages, options2) {
3568
3324
  try {
3569
3325
  metrics.total_calls++;
3570
- const result = await (0, import_exponential_backoff.backOff)(() => asyncCallWithTimeout(handler(deepFreeze(state), deepFreeze(messages), deepFreeze(options2)), timeout), {
3571
- startingDelay: 0,
3572
- maxDelay,
3573
- numOfAttempts,
3574
- jitter,
3575
- retry: /* @__PURE__ */ __name((_error, _stepNumber) => {
3576
- if (doNotRetryErrorMessages.includes(_error.message)) {
3577
- 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;
3578
3346
  }
3579
- metrics.total_call_retry++;
3580
- return true;
3581
- }, "retry")
3582
- });
3347
+ }
3348
+ );
3583
3349
  metrics.total_call_success++;
3584
3350
  return result;
3585
3351
  } catch (error) {
@@ -3587,29 +3353,32 @@ function apiRequestWrapper(config, options, handler, doNotRetryErrorMessages = [
3587
3353
  throw error;
3588
3354
  }
3589
3355
  }
3590
- __name(call, "call");
3591
3356
  function getMetadata() {
3592
- const { awsSecretKey, awsAccessKey, openAiApiKey, anthropicApiKey, ...rest } = options;
3593
- return Object.assign({
3594
- traceId: getTraceId(),
3595
- timeout,
3596
- jitter,
3597
- maxDelay,
3598
- numOfAttempts,
3599
- metrics: {
3600
- ...metrics
3601
- }
3602
- }, 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
+ );
3603
3375
  }
3604
- __name(getMetadata, "getMetadata");
3605
3376
  function getTraceId() {
3606
3377
  return traceId;
3607
3378
  }
3608
- __name(getTraceId, "getTraceId");
3609
3379
  function withTraceId(id) {
3610
3380
  traceId = id;
3611
3381
  }
3612
- __name(withTraceId, "withTraceId");
3613
3382
  return {
3614
3383
  call,
3615
3384
  getTraceId,
@@ -3617,14 +3386,12 @@ function apiRequestWrapper(config, options, handler, doNotRetryErrorMessages = [
3617
3386
  getMetadata
3618
3387
  };
3619
3388
  }
3620
- __name(apiRequestWrapper, "apiRequestWrapper");
3621
3389
 
3622
3390
  // src/llm/llm.ts
3623
3391
  function useLlm(provider, options = {}) {
3624
3392
  const config = getLlmConfig(provider);
3625
3393
  return apiRequestWrapper(config, options, useLlm_call);
3626
3394
  }
3627
- __name(useLlm, "useLlm");
3628
3395
 
3629
3396
  // src/embedding/config.ts
3630
3397
  var embeddingConfigs = {
@@ -3672,10 +3439,7 @@ var embeddingConfigs = {
3672
3439
  },
3673
3440
  awsRegion: {
3674
3441
  default: getEnvironmentVariable("AWS_REGION"),
3675
- required: [
3676
- true,
3677
- "aws region is required"
3678
- ]
3442
+ required: [true, "aws region is required"]
3679
3443
  },
3680
3444
  awsSecretKey: {},
3681
3445
  awsAccessKey: {}
@@ -3700,7 +3464,6 @@ function getEmbeddingConfig(provider) {
3700
3464
  }
3701
3465
  throw new Error(`Invalid provider: ${provider}`);
3702
3466
  }
3703
- __name(getEmbeddingConfig, "getEmbeddingConfig");
3704
3467
 
3705
3468
  // src/embedding/output/BaseEmbeddingOutput.ts
3706
3469
  function BaseEmbeddingOutput(result) {
@@ -3708,9 +3471,7 @@ function BaseEmbeddingOutput(result) {
3708
3471
  id: result.id || (0, import_uuid.v4)(),
3709
3472
  model: result.model,
3710
3473
  usage: result.usage,
3711
- embedding: [
3712
- ...result?.embedding || []
3713
- ],
3474
+ embedding: [...result?.embedding || []],
3714
3475
  created: result?.created || (/* @__PURE__ */ new Date()).getTime()
3715
3476
  });
3716
3477
  function getResult() {
@@ -3722,7 +3483,6 @@ function BaseEmbeddingOutput(result) {
3722
3483
  embedding: __result.embedding
3723
3484
  };
3724
3485
  }
3725
- __name(getResult, "getResult");
3726
3486
  function getEmbedding(index) {
3727
3487
  if (index && index > 0) {
3728
3488
  const arr = __result?.embedding;
@@ -3731,22 +3491,18 @@ function BaseEmbeddingOutput(result) {
3731
3491
  }
3732
3492
  return __result.embedding[0];
3733
3493
  }
3734
- __name(getEmbedding, "getEmbedding");
3735
3494
  return {
3736
3495
  getEmbedding,
3737
3496
  getResult
3738
3497
  };
3739
3498
  }
3740
- __name(BaseEmbeddingOutput, "BaseEmbeddingOutput");
3741
3499
 
3742
3500
  // src/embedding/output/AmazonTitan.ts
3743
3501
  function AmazonTitanEmbedding(result, config) {
3744
3502
  const __result = deepClone(result);
3745
3503
  const model = config.model || "amazon.unknown";
3746
3504
  const created = (/* @__PURE__ */ new Date()).getTime();
3747
- const embedding = [
3748
- __result.embedding
3749
- ];
3505
+ const embedding = [__result.embedding];
3750
3506
  const usage = {
3751
3507
  output_tokens: 0,
3752
3508
  input_tokens: __result.inputTextTokenCount,
@@ -3759,7 +3515,6 @@ function AmazonTitanEmbedding(result, config) {
3759
3515
  embedding
3760
3516
  });
3761
3517
  }
3762
- __name(AmazonTitanEmbedding, "AmazonTitanEmbedding");
3763
3518
 
3764
3519
  // src/embedding/output/OpenAiEmbedding.ts
3765
3520
  function OpenAiEmbedding(result, config) {
@@ -3780,7 +3535,6 @@ function OpenAiEmbedding(result, config) {
3780
3535
  embedding
3781
3536
  });
3782
3537
  }
3783
- __name(OpenAiEmbedding, "OpenAiEmbedding");
3784
3538
 
3785
3539
  // src/embedding/output/getEmbeddingOutputParser.ts
3786
3540
  function getEmbeddingOutputParser(config, response) {
@@ -3793,14 +3547,16 @@ function getEmbeddingOutputParser(config, response) {
3793
3547
  throw new Error("Unsupported provider");
3794
3548
  }
3795
3549
  }
3796
- __name(getEmbeddingOutputParser, "getEmbeddingOutputParser");
3797
3550
 
3798
3551
  // src/embedding/embedding.call.ts
3799
3552
  async function createEmbedding_call(state, _input, _options) {
3800
3553
  const config = getEmbeddingConfig(state.key);
3801
- const input = mapBody(config.mapBody, Object.assign({}, state, {
3802
- input: _input
3803
- }));
3554
+ const input = mapBody(
3555
+ config.mapBody,
3556
+ Object.assign({}, state, {
3557
+ input: _input
3558
+ })
3559
+ );
3804
3560
  const body = JSON.stringify(input);
3805
3561
  const url = replaceTemplateStringSimple(config.endpoint, state);
3806
3562
  const headers = await parseHeaders(config, state, {
@@ -3815,21 +3571,19 @@ async function createEmbedding_call(state, _input, _options) {
3815
3571
  });
3816
3572
  return getEmbeddingOutputParser(state, request);
3817
3573
  }
3818
- __name(createEmbedding_call, "createEmbedding_call");
3819
3574
 
3820
3575
  // src/embedding/embedding.ts
3821
3576
  function createEmbedding(provider, options) {
3822
3577
  const config = getEmbeddingConfig(provider);
3823
3578
  return apiRequestWrapper(config, options, createEmbedding_call);
3824
3579
  }
3825
- __name(createEmbedding, "createEmbedding");
3826
3580
 
3827
3581
  // src/prompt/_base.ts
3828
- var _BasePrompt = class _BasePrompt {
3582
+ var BasePrompt = class {
3829
3583
  /**
3830
- * constructor description
3831
- * @param initialPromptMessage An initial message to add to the prompt.
3832
- */
3584
+ * constructor description
3585
+ * @param initialPromptMessage An initial message to add to the prompt.
3586
+ */
3833
3587
  constructor(initialPromptMessage, options) {
3834
3588
  __publicField(this, "type", "text");
3835
3589
  __publicField(this, "messages", []);
@@ -3863,11 +3617,11 @@ var _BasePrompt = class _BasePrompt {
3863
3617
  }
3864
3618
  }
3865
3619
  /**
3866
- * addToPrompt description
3867
- * @param content The message content
3868
- * @param role The role of the user. Defaults to system for base text prompt.
3869
- * @return instance of BasePrompt.
3870
- */
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
+ */
3871
3625
  addToPrompt(content, role = "system") {
3872
3626
  if (content) {
3873
3627
  switch (role) {
@@ -3880,10 +3634,10 @@ var _BasePrompt = class _BasePrompt {
3880
3634
  return this;
3881
3635
  }
3882
3636
  /**
3883
- * addSystemMessage description
3884
- * @param content The message content
3885
- * @return returns BasePrompt so it can be chained.
3886
- */
3637
+ * addSystemMessage description
3638
+ * @param content The message content
3639
+ * @return returns BasePrompt so it can be chained.
3640
+ */
3887
3641
  addSystemMessage(content) {
3888
3642
  this.messages.push({
3889
3643
  role: "system",
@@ -3892,58 +3646,62 @@ var _BasePrompt = class _BasePrompt {
3892
3646
  return this;
3893
3647
  }
3894
3648
  /**
3895
- * registerPartial description
3896
- * @param partialOrPartials Additional partials that can be made available to the template parser.
3897
- * @return BasePrompt so it can be chained.
3898
- */
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
+ */
3899
3653
  registerPartial(partialOrPartials) {
3900
- const partials2 = Array.isArray(partialOrPartials) ? partialOrPartials : [
3901
- partialOrPartials
3902
- ];
3654
+ const partials2 = Array.isArray(partialOrPartials) ? partialOrPartials : [partialOrPartials];
3903
3655
  this.partials.push(...partials2);
3904
3656
  return this;
3905
3657
  }
3906
3658
  /**
3907
- * registerHelpers description
3908
- * @param helperOrHelpers Additional helper functions that can be made available to the template parser.
3909
- * @return BasePrompt so it can be chained.
3910
- */
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
+ */
3911
3663
  registerHelpers(helperOrHelpers) {
3912
- const helpers = Array.isArray(helperOrHelpers) ? helperOrHelpers : [
3913
- helperOrHelpers
3914
- ];
3664
+ const helpers = Array.isArray(helperOrHelpers) ? helperOrHelpers : [helperOrHelpers];
3915
3665
  this.helpers.push(...helpers);
3916
3666
  return this;
3917
3667
  }
3918
3668
  /**
3919
- * format description
3920
- * @param values The message content
3921
- * @param separator The separator between messages. defaults to "\n\n"
3922
- * @return returns messages formatted with template replacement
3923
- */
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
+ */
3924
3674
  format(values, separator = "\n\n") {
3925
3675
  const replacements = this.getReplacements(values);
3926
3676
  const messages = this.messages.map((message) => {
3927
- return message.content && !Array.isArray(message.content) ? this.replaceTemplateString(this.runPromptFilter(message.content, this.filters.pre, values), replacements, {
3928
- partials: this.partials,
3929
- helpers: this.helpers
3930
- }) : "";
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
+ ) : "";
3931
3685
  }).join(separator);
3932
3686
  return this.runPromptFilter(messages, this.filters.post, values);
3933
3687
  }
3934
3688
  /**
3935
- * format description
3936
- * @param values The message content
3937
- * @param separator The separator between messages. defaults to "\n\n"
3938
- * @return returns messages formatted with template replacement
3939
- */
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
+ */
3940
3694
  async formatAsync(values, separator = "\n\n") {
3941
3695
  const replacements = this.getReplacements(values);
3942
3696
  const _messages = await Promise.all(this.messages.map((message) => {
3943
- return message.content && !Array.isArray(message.content) ? this.replaceTemplateStringAsync(this.runPromptFilter(message.content, this.filters.pre, values), replacements, {
3944
- partials: this.partials,
3945
- helpers: this.helpers
3946
- }) : "";
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
+ ) : "";
3947
3705
  }));
3948
3706
  const messages = _messages.join(separator);
3949
3707
  return this.runPromptFilter(messages, this.filters.post, values);
@@ -3957,33 +3715,31 @@ var _BasePrompt = class _BasePrompt {
3957
3715
  }
3958
3716
  getReplacements(values) {
3959
3717
  const { input = "", ...restOfValues } = values;
3960
- const replacements = Object.assign({}, {
3961
- ...restOfValues
3962
- }, {
3963
- input,
3964
- _input: input
3965
- });
3718
+ const replacements = Object.assign(
3719
+ {},
3720
+ { ...restOfValues },
3721
+ {
3722
+ input,
3723
+ _input: input
3724
+ }
3725
+ );
3966
3726
  return replacements;
3967
3727
  }
3968
3728
  /**
3969
- * validate description
3970
- * @return {boolean} Returns false if the template is not valid.
3971
- */
3729
+ * validate description
3730
+ * @return {boolean} Returns false if the template is not valid.
3731
+ */
3972
3732
  validate() {
3973
3733
  return true;
3974
3734
  }
3975
3735
  };
3976
- __name(_BasePrompt, "BasePrompt");
3977
- var BasePrompt = _BasePrompt;
3978
3736
 
3979
3737
  // src/prompt/text.ts
3980
- var _TextPrompt = class _TextPrompt extends BasePrompt {
3738
+ var TextPrompt = class extends BasePrompt {
3981
3739
  constructor(base, options) {
3982
3740
  super(base, options);
3983
3741
  }
3984
3742
  };
3985
- __name(_TextPrompt, "TextPrompt");
3986
- var TextPrompt = _TextPrompt;
3987
3743
 
3988
3744
  // src/utils/modules/unescape.ts
3989
3745
  function unescape(str) {
@@ -3997,13 +3753,10 @@ function unescape(str) {
3997
3753
  const entityRegex = /&amp;|&lt;|&gt;|&quot;|&#39;/g;
3998
3754
  return str.replace(entityRegex, (m) => map[m]);
3999
3755
  }
4000
- __name(unescape, "unescape");
4001
3756
 
4002
3757
  // src/utils/modules/extractPromptPlaceholderToken.ts
4003
3758
  function extractPromptPlaceholderToken(tok) {
4004
- if (!tok) return {
4005
- token: ""
4006
- };
3759
+ if (!tok) return { token: "" };
4007
3760
  const token = tok.replace(/ /g, "");
4008
3761
  if (token.substring(2, 18) === ">DialogueHistory") {
4009
3762
  const matchKey = tok.match(/key=(['"`])((?:(?!\1).)*)\1/);
@@ -4030,11 +3783,8 @@ function extractPromptPlaceholderToken(tok) {
4030
3783
  };
4031
3784
  }
4032
3785
  }
4033
- return {
4034
- token: ""
4035
- };
3786
+ return { token: "" };
4036
3787
  }
4037
- __name(extractPromptPlaceholderToken, "extractPromptPlaceholderToken");
4038
3788
 
4039
3789
  // src/utils/modules/escape.ts
4040
3790
  function escape(str) {
@@ -4047,29 +3797,28 @@ function escape(str) {
4047
3797
  };
4048
3798
  return str.replace(/[&<>"']/g, (m) => map[m]);
4049
3799
  }
4050
- __name(escape, "escape");
4051
3800
 
4052
3801
  // src/prompt/chat.ts
4053
- var _ChatPrompt = class _ChatPrompt extends BasePrompt {
3802
+ var ChatPrompt = class extends BasePrompt {
4054
3803
  /**
4055
- * new `ChatPrompt`
4056
- * @param initialSystemPromptMessage (optional) An initial system message to add to the new prompt.
4057
- * @param options (optional) Options to pass in when creating the prompt.
4058
- */
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
+ */
4059
3808
  constructor(initialSystemPromptMessage, options) {
4060
3809
  super(initialSystemPromptMessage, options);
4061
3810
  /**
4062
- * @property type - Prompt type (chat)
4063
- */
3811
+ * @property type - Prompt type (chat)
3812
+ */
4064
3813
  __publicField(this, "type", "chat");
4065
3814
  /**
4066
- * @property parseUserTemplates - Whether or not to allow parsing
4067
- * user messages with the template engine. This could be a risk,
4068
- * so we only parse user messages if explicitly set.
4069
- */
4070
- __publicField(this, "parseUserTemplates", false);
4071
- if (options?.allowUnsafeUserTemplate) {
4072
- 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;
4073
3822
  }
4074
3823
  }
4075
3824
  addToPrompt(content, role, name) {
@@ -4090,21 +3839,18 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4090
3839
  break;
4091
3840
  case "function_call":
4092
3841
  assert(name, "Function message requires name");
4093
- this.addFunctionCallMessage({
4094
- name,
4095
- arguments: content
4096
- });
3842
+ this.addFunctionCallMessage({ name, arguments: content });
4097
3843
  break;
4098
3844
  }
4099
3845
  }
4100
3846
  return this;
4101
3847
  }
4102
3848
  /**
4103
- * addUserMessage Helper to add a user message to the prompt.
4104
- * @param content The message content.
4105
- * @param name (optional) The name of the user.
4106
- * @return instance of ChatPrompt.
4107
- */
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
+ */
4108
3854
  addUserMessage(content, name) {
4109
3855
  const message = {
4110
3856
  role: "user",
@@ -4117,10 +3863,10 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4117
3863
  return this;
4118
3864
  }
4119
3865
  /**
4120
- * addAssistantMessage Helper to add an assistant message to the prompt.
4121
- * @param content The message content.
4122
- * @return ChatPrompt so it can be chained.
4123
- */
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
+ */
4124
3870
  addAssistantMessage(content) {
4125
3871
  this.messages.push({
4126
3872
  role: "assistant",
@@ -4129,10 +3875,10 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4129
3875
  return this;
4130
3876
  }
4131
3877
  /**
4132
- * addFunctionMessage Helper to add an assistant message to the prompt.
4133
- * @param content The message content.
4134
- * @return ChatPrompt so it can be chained.
4135
- */
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
+ */
4136
3882
  addFunctionMessage(content, name) {
4137
3883
  this.messages.push({
4138
3884
  role: "function",
@@ -4142,10 +3888,10 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4142
3888
  return this;
4143
3889
  }
4144
3890
  /**
4145
- * addFunctionCallMessage Helper to add an assistant message to the prompt.
4146
- * @param content The message content.
4147
- * @return ChatPrompt so it can be chained.
4148
- */
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
+ */
4149
3895
  addFunctionCallMessage(function_call) {
4150
3896
  if (function_call) {
4151
3897
  this.messages.push({
@@ -4160,10 +3906,10 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4160
3906
  return this;
4161
3907
  }
4162
3908
  /**
4163
- * addFromHistory Adds multiple messages at one time.
4164
- * @param history History of chat messages.
4165
- * @return ChatPrompt so it can be chained.
4166
- */
3909
+ * addFromHistory Adds multiple messages at one time.
3910
+ * @param history History of chat messages.
3911
+ * @return ChatPrompt so it can be chained.
3912
+ */
4167
3913
  addFromHistory(history) {
4168
3914
  if (history && Array.isArray(history)) {
4169
3915
  for (const message of history) {
@@ -4190,15 +3936,13 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4190
3936
  return this;
4191
3937
  }
4192
3938
  /**
4193
- * addPlaceholder description
4194
- * @param content The message content
4195
- * @return returns ChatPrompt so it can be chained.
4196
- */
3939
+ * addPlaceholder description
3940
+ * @param content The message content
3941
+ * @return returns ChatPrompt so it can be chained.
3942
+ */
4197
3943
  addChatHistoryPlaceholder(key, options) {
4198
3944
  const start = `{{> DialogueHistory `;
4199
- const params = [
4200
- `key='${String(key)}'`
4201
- ];
3945
+ const params = [`key='${String(key)}'`];
4202
3946
  const end = `}}`;
4203
3947
  if (options?.assistant) {
4204
3948
  params.push(`assistant='${options.assistant}'`);
@@ -4213,17 +3957,14 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4213
3957
  return this;
4214
3958
  }
4215
3959
  /**
4216
- * addTokenPlaceholder description
4217
- * @param content The message content
4218
- * @return returns ChatPrompt so it can be chained.
4219
- */
3960
+ * addTokenPlaceholder description
3961
+ * @param content The message content
3962
+ * @return returns ChatPrompt so it can be chained.
3963
+ */
4220
3964
  addMessagePlaceholder(content, role = "user", name) {
4221
3965
  if (content) {
4222
3966
  const start = `{{> SingleChatMessage `;
4223
- const params = [
4224
- `role='${role}'`,
4225
- `content='${escape(content)}'`
4226
- ];
3967
+ const params = [`role='${role}'`, `content='${escape(content)}'`];
4227
3968
  const end = `}}`;
4228
3969
  if (name) {
4229
3970
  params.push(`name='${name}'`);
@@ -4243,11 +3984,7 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4243
3984
  for (const message of history) {
4244
3985
  switch (message.role) {
4245
3986
  case "user": {
4246
- const m = pick(message, [
4247
- "role",
4248
- "content",
4249
- "name"
4250
- ]);
3987
+ const m = pick(message, ["role", "content", "name"]);
4251
3988
  if (user) {
4252
3989
  m["name"] = user;
4253
3990
  }
@@ -4288,19 +4025,16 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4288
4025
  return messagesOut;
4289
4026
  }
4290
4027
  /**
4291
- * format formats the stored prompt based on input values.
4292
- * Uses template engine.
4293
- * Output is intended for LLM.
4294
- * @param values input values.
4295
- * @return formatted prompt.
4296
- */
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
+ */
4297
4034
  format(values) {
4298
4035
  const messagesOut = [];
4299
4036
  const replacements = this.getReplacements(values);
4300
- const safeToParseTemplate = [
4301
- "assistant",
4302
- "system"
4303
- ];
4037
+ const safeToParseTemplate = ["assistant", "system"];
4304
4038
  if (this.parseUserTemplates) {
4305
4039
  safeToParseTemplate.push("user");
4306
4040
  }
@@ -4309,7 +4043,12 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4309
4043
  const tokenData = extractPromptPlaceholderToken(message.content);
4310
4044
  switch (tokenData.token) {
4311
4045
  case ">DialogueHistory": {
4312
- messagesOut.push(...this._format_placeholderDialogueHistory(tokenData, replacements));
4046
+ messagesOut.push(
4047
+ ...this._format_placeholderDialogueHistory(
4048
+ tokenData,
4049
+ replacements
4050
+ )
4051
+ );
4313
4052
  break;
4314
4053
  }
4315
4054
  case ">SingleChatMessage": {
@@ -4332,70 +4071,103 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4332
4071
  }
4333
4072
  }
4334
4073
  } else if (message.role === "function") {
4335
- messagesOut.push(Object.assign({}, message, {
4336
- content: this.replaceTemplateString(message.content, replacements, {
4337
- partials: this.partials,
4338
- 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
+ })
4339
4080
  })
4340
- }));
4081
+ );
4341
4082
  } else {
4342
4083
  if (safeToParseTemplate.includes(message.role)) {
4343
4084
  if (Array.isArray(message.content)) {
4344
- const content = message.content.map((m) => m.text ? {
4345
- type: "text",
4346
- text: this.runPromptFilter(this.replaceTemplateString(this.runPromptFilter(m.text, this.filters.pre, values), replacements, {
4347
- partials: this.partials,
4348
- helpers: this.helpers
4349
- }), this.filters.post, values)
4350
- } : m);
4351
- messagesOut.push(Object.assign({}, message, {
4352
- content
4353
- }));
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 }));
4354
4103
  } else if (message.content) {
4355
- const content = this.runPromptFilter(this.replaceTemplateString(this.runPromptFilter(message.content, this.filters.pre, values), replacements, {
4356
- partials: this.partials,
4357
- helpers: this.helpers
4358
- }), this.filters.post, values);
4359
- messagesOut.push(Object.assign({}, message, {
4360
- content
4361
- }));
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 }));
4362
4117
  } else {
4363
- messagesOut.push(Object.assign({}, message, {
4364
- content: null
4365
- }));
4118
+ messagesOut.push(Object.assign({}, message, { content: null }));
4366
4119
  }
4367
4120
  } else {
4368
- messagesOut.push(Object.assign({}, message, {
4369
- content: Array.isArray(message.content) ? message.content.map((m) => m.text ? {
4370
- type: "text",
4371
- text: this.runPromptFilter(this.runPromptFilter(m.text, this.filters.pre, values), this.filters.post, values)
4372
- } : m) : message.content && !Array.isArray(message.content) ? this.runPromptFilter(this.runPromptFilter(message.content, this.filters.pre, values), this.filters.post, values) : null
4373
- }));
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
+ );
4374
4147
  }
4375
4148
  }
4376
4149
  }
4377
4150
  return messagesOut;
4378
4151
  }
4379
4152
  /**
4380
- * format formats the stored prompt based on input values.
4381
- * Uses template engine.
4382
- * Output is intended for LLM.
4383
- * @param values input values.
4384
- * @return formatted prompt.
4385
- */
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
+ */
4386
4159
  async formatAsync(values) {
4387
4160
  const messagesOut = [];
4388
4161
  const replacements = this.getReplacements(values);
4389
- const safeToParseTemplate = [
4390
- "assistant",
4391
- "system"
4392
- ];
4162
+ const safeToParseTemplate = ["assistant", "system"];
4393
4163
  if (this.parseUserTemplates) {
4394
4164
  safeToParseTemplate.push("user");
4395
4165
  }
4396
4166
  for (const message of this.messages) {
4397
4167
  if (message.role === "placeholder") {
4398
- const { token, ...data } = extractPromptPlaceholderToken(message.content);
4168
+ const { token, ...data } = extractPromptPlaceholderToken(
4169
+ message.content
4170
+ );
4399
4171
  switch (token) {
4400
4172
  case ">DialogueHistory": {
4401
4173
  const { key = "", user } = data;
@@ -4404,11 +4176,7 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4404
4176
  for (const message2 of history) {
4405
4177
  switch (message2.role) {
4406
4178
  case "user": {
4407
- const m = pick(message2, [
4408
- "role",
4409
- "content",
4410
- "name"
4411
- ]);
4179
+ const m = pick(message2, ["role", "content", "name"]);
4412
4180
  if (user) {
4413
4181
  m["name"] = user;
4414
4182
  }
@@ -4454,10 +4222,14 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4454
4222
  const message2 = {
4455
4223
  role,
4456
4224
  name,
4457
- content: await this.replaceTemplateStringAsync(content, replacements, {
4458
- partials: this.partials,
4459
- helpers: this.helpers
4460
- })
4225
+ content: await this.replaceTemplateStringAsync(
4226
+ content,
4227
+ replacements,
4228
+ {
4229
+ partials: this.partials,
4230
+ helpers: this.helpers
4231
+ }
4232
+ )
4461
4233
  };
4462
4234
  if (!name || role !== "user") {
4463
4235
  delete message2.name;
@@ -4468,12 +4240,18 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4468
4240
  }
4469
4241
  }
4470
4242
  } else if (message.role === "function") {
4471
- messagesOut.push(Object.assign({}, message, {
4472
- content: await this.replaceTemplateStringAsync(message.content, replacements, {
4473
- partials: this.partials,
4474
- 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
+ )
4475
4253
  })
4476
- }));
4254
+ );
4477
4255
  } else {
4478
4256
  if (safeToParseTemplate.includes(message.role)) {
4479
4257
  if (Array.isArray(message.content)) {
@@ -4484,10 +4262,14 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4484
4262
  type: "text",
4485
4263
  text: this.runPromptFilter(
4486
4264
  // HERE
4487
- await this.replaceTemplateStringAsync(this.runPromptFilter(m.text, this.filters.pre, values), replacements, {
4488
- partials: this.partials,
4489
- helpers: this.helpers
4490
- }),
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
+ ),
4491
4273
  this.filters.post,
4492
4274
  values
4493
4275
  )
@@ -4496,45 +4278,65 @@ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
4496
4278
  content.push(m);
4497
4279
  }
4498
4280
  }
4499
- messagesOut.push(Object.assign({}, message, {
4500
- content
4501
- }));
4281
+ messagesOut.push(Object.assign({}, message, { content }));
4502
4282
  } else if (message.content) {
4503
- const content = this.runPromptFilter(await this.replaceTemplateStringAsync(this.runPromptFilter(message.content, this.filters.pre, values), replacements, {
4504
- partials: this.partials,
4505
- helpers: this.helpers
4506
- }), this.filters.post, values);
4507
- messagesOut.push(Object.assign({}, message, {
4508
- content
4509
- }));
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 }));
4510
4296
  } else {
4511
- messagesOut.push(Object.assign({}, message, {
4512
- content: null
4513
- }));
4297
+ messagesOut.push(Object.assign({}, message, { content: null }));
4514
4298
  }
4515
4299
  } else {
4516
- messagesOut.push(Object.assign({}, message, {
4517
- content: Array.isArray(message.content) ? message.content.map((m) => m.text ? {
4518
- type: "text",
4519
- text: this.runPromptFilter(this.runPromptFilter(m.text, this.filters.pre, values), this.filters.post, values)
4520
- } : m) : message.content && !Array.isArray(message.content) ? this.runPromptFilter(this.runPromptFilter(message.content, this.filters.pre, values), this.filters.post, values) : null
4521
- }));
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
+ );
4522
4326
  }
4523
4327
  }
4524
4328
  }
4525
4329
  return messagesOut;
4526
4330
  }
4527
4331
  /**
4528
- * validate Ensures there are not unresolved tokens in prompt.
4529
- * @TODO Make this work!
4530
- * @return Returns false if the template is not valid.
4531
- */
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
+ */
4532
4336
  validate() {
4533
4337
  return true;
4534
4338
  }
4535
4339
  };
4536
- __name(_ChatPrompt, "ChatPrompt");
4537
- var ChatPrompt = _ChatPrompt;
4538
4340
 
4539
4341
  // src/prompt/_functions.ts
4540
4342
  function createPrompt(type, initialPromptMessage, options) {
@@ -4545,14 +4347,12 @@ function createPrompt(type, initialPromptMessage, options) {
4545
4347
  return new TextPrompt(initialPromptMessage);
4546
4348
  }
4547
4349
  }
4548
- __name(createPrompt, "createPrompt");
4549
4350
  function createChatPrompt(initialSystemPromptMessage, options) {
4550
4351
  return new ChatPrompt(initialSystemPromptMessage, options);
4551
4352
  }
4552
- __name(createChatPrompt, "createChatPrompt");
4553
4353
 
4554
4354
  // src/state/item.ts
4555
- var _BaseStateItem = class _BaseStateItem {
4355
+ var BaseStateItem = class {
4556
4356
  constructor(key, initialValue) {
4557
4357
  __publicField(this, "key");
4558
4358
  __publicField(this, "value");
@@ -4562,7 +4362,10 @@ var _BaseStateItem = class _BaseStateItem {
4562
4362
  this.initialValue = initialValue;
4563
4363
  }
4564
4364
  setValue(value) {
4565
- 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
+ );
4566
4369
  this.value = value;
4567
4370
  }
4568
4371
  getKey() {
@@ -4586,19 +4389,18 @@ var _BaseStateItem = class _BaseStateItem {
4586
4389
  value: this.serializeValue()
4587
4390
  };
4588
4391
  }
4392
+ // deserialize() {}
4589
4393
  };
4590
- __name(_BaseStateItem, "BaseStateItem");
4591
- var BaseStateItem = _BaseStateItem;
4592
- var _DefaultStateItem = class _DefaultStateItem extends BaseStateItem {
4394
+ var DefaultStateItem = class extends BaseStateItem {
4593
4395
  constructor(name, defaultValue) {
4594
4396
  super(name, defaultValue);
4595
4397
  }
4398
+ // serialize() { return {}; }
4399
+ // deserialize() {}
4596
4400
  };
4597
- __name(_DefaultStateItem, "DefaultStateItem");
4598
- var DefaultStateItem = _DefaultStateItem;
4599
4401
 
4600
4402
  // src/state/dialogue.ts
4601
- var _Dialogue = class _Dialogue extends BaseStateItem {
4403
+ var Dialogue = class extends BaseStateItem {
4602
4404
  constructor(name) {
4603
4405
  super(name, []);
4604
4406
  __publicField(this, "name");
@@ -4694,17 +4496,14 @@ var _Dialogue = class _Dialogue extends BaseStateItem {
4694
4496
  return {
4695
4497
  class: "Dialogue",
4696
4498
  name: this.name,
4697
- value: [
4698
- ...this.value
4699
- ]
4499
+ value: [...this.value]
4700
4500
  };
4701
4501
  }
4502
+ // deserialize() {}
4702
4503
  };
4703
- __name(_Dialogue, "Dialogue");
4704
- var Dialogue = _Dialogue;
4705
4504
 
4706
4505
  // src/state/_base.ts
4707
- var _BaseState = class _BaseState {
4506
+ var BaseState = class {
4708
4507
  constructor() {
4709
4508
  __publicField(this, "dialogues", {});
4710
4509
  __publicField(this, "attributes", {});
@@ -4729,8 +4528,14 @@ var _BaseState = class _BaseState {
4729
4528
  return dialogue;
4730
4529
  }
4731
4530
  createContextItem(item) {
4732
- assert(item instanceof BaseStateItem, "Invalid context item. Must be instance of BaseStateItem");
4733
- 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
+ );
4734
4539
  this.context[item.getKey()] = item;
4735
4540
  return this.context[item.getKey()];
4736
4541
  }
@@ -4752,14 +4557,16 @@ var _BaseState = class _BaseState {
4752
4557
  serialize() {
4753
4558
  const dialogues = {};
4754
4559
  const context = {};
4755
- const attributes = {
4756
- ...this.attributes
4757
- };
4758
- const dialogueKeys = Object.keys(this.dialogues);
4560
+ const attributes = { ...this.attributes };
4561
+ const dialogueKeys = Object.keys(
4562
+ this.dialogues
4563
+ );
4759
4564
  for (const dialogueKey of dialogueKeys) {
4760
4565
  dialogues[dialogueKey] = this.dialogues[dialogueKey].serialize();
4761
4566
  }
4762
- const contextKeys = Object.keys(this.context);
4567
+ const contextKeys = Object.keys(
4568
+ this.context
4569
+ );
4763
4570
  for (const contextKey of contextKeys) {
4764
4571
  context[contextKey] = this.context[contextKey].serialize();
4765
4572
  }
@@ -4770,9 +4577,7 @@ var _BaseState = class _BaseState {
4770
4577
  };
4771
4578
  }
4772
4579
  };
4773
- __name(_BaseState, "BaseState");
4774
- var BaseState = _BaseState;
4775
- var _DefaultState = class _DefaultState extends BaseState {
4580
+ var DefaultState = class extends BaseState {
4776
4581
  constructor() {
4777
4582
  super();
4778
4583
  }
@@ -4780,22 +4585,17 @@ var _DefaultState = class _DefaultState extends BaseState {
4780
4585
  console.log("Save not implemented in default state.");
4781
4586
  }
4782
4587
  };
4783
- __name(_DefaultState, "DefaultState");
4784
- var DefaultState = _DefaultState;
4785
4588
 
4786
4589
  // src/state/_functions.ts
4787
4590
  function createState() {
4788
4591
  return new DefaultState();
4789
4592
  }
4790
- __name(createState, "createState");
4791
4593
  function createDialogue(name) {
4792
4594
  return new Dialogue(name);
4793
4595
  }
4794
- __name(createDialogue, "createDialogue");
4795
4596
  function createStateItem(name, defaultValue) {
4796
4597
  return new DefaultStateItem(name, defaultValue);
4797
4598
  }
4798
- __name(createStateItem, "createStateItem");
4799
4599
  // Annotate the CommonJS export names for ESM import in node:
4800
4600
  0 && (module.exports = {
4801
4601
  BaseExecutor,
@@ -4820,6 +4620,9 @@ __name(createStateItem, "createStateItem");
4820
4620
  createPrompt,
4821
4621
  createState,
4822
4622
  createStateItem,
4623
+ defineSchema,
4624
+ registerHelpers,
4625
+ registerPartials,
4823
4626
  useExecutors,
4824
4627
  useLlm,
4825
4628
  utils