llm-exe 1.0.2 → 2.0.0-beta.10

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.
Files changed (209) hide show
  1. package/LICENSE +21 -0
  2. package/dist/index.d.mts +1224 -0
  3. package/dist/index.d.ts +1207 -46
  4. package/dist/index.js +4188 -80
  5. package/dist/index.mjs +4150 -0
  6. package/package.json +35 -29
  7. package/readme.md +79 -2
  8. package/dist/embedding/base.d.ts +0 -8
  9. package/dist/embedding/base.js +0 -43
  10. package/dist/embedding/base.js.map +0 -1
  11. package/dist/embedding/openai.d.ts +0 -11
  12. package/dist/embedding/openai.js +0 -73
  13. package/dist/embedding/openai.js.map +0 -1
  14. package/dist/executor/_base.d.ts +0 -68
  15. package/dist/executor/_base.js +0 -229
  16. package/dist/executor/_base.js.map +0 -1
  17. package/dist/executor/_functions.d.ts +0 -25
  18. package/dist/executor/_functions.js +0 -30
  19. package/dist/executor/_functions.js.map +0 -1
  20. package/dist/executor/_metadata.d.ts +0 -8
  21. package/dist/executor/_metadata.js +0 -59
  22. package/dist/executor/_metadata.js.map +0 -1
  23. package/dist/executor/core.d.ts +0 -10
  24. package/dist/executor/core.js +0 -28
  25. package/dist/executor/core.js.map +0 -1
  26. package/dist/executor/index.d.ts +0 -5
  27. package/dist/executor/index.js +0 -15
  28. package/dist/executor/index.js.map +0 -1
  29. package/dist/executor/llm-openai-function.d.ts +0 -13
  30. package/dist/executor/llm-openai-function.js +0 -23
  31. package/dist/executor/llm-openai-function.js.map +0 -1
  32. package/dist/executor/llm.d.ts +0 -32
  33. package/dist/executor/llm.js +0 -82
  34. package/dist/executor/llm.js.map +0 -1
  35. package/dist/index.js.map +0 -1
  36. package/dist/interfaces/chat.d.ts +0 -74
  37. package/dist/interfaces/chat.js +0 -3
  38. package/dist/interfaces/chat.js.map +0 -1
  39. package/dist/interfaces/functions.d.ts +0 -67
  40. package/dist/interfaces/functions.js +0 -4
  41. package/dist/interfaces/functions.js.map +0 -1
  42. package/dist/interfaces/index.d.ts +0 -7
  43. package/dist/interfaces/index.js +0 -23
  44. package/dist/interfaces/index.js.map +0 -1
  45. package/dist/interfaces/openai.d.ts +0 -46
  46. package/dist/interfaces/openai.js +0 -3
  47. package/dist/interfaces/openai.js.map +0 -1
  48. package/dist/interfaces/parser.d.ts +0 -8
  49. package/dist/interfaces/parser.js +0 -3
  50. package/dist/interfaces/parser.js.map +0 -1
  51. package/dist/interfaces/prompt.d.ts +0 -22
  52. package/dist/interfaces/prompt.js +0 -3
  53. package/dist/interfaces/prompt.js.map +0 -1
  54. package/dist/interfaces/utils.d.ts +0 -18
  55. package/dist/interfaces/utils.js +0 -3
  56. package/dist/interfaces/utils.js.map +0 -1
  57. package/dist/llm/_base.d.ts +0 -84
  58. package/dist/llm/_base.js +0 -184
  59. package/dist/llm/_base.js.map +0 -1
  60. package/dist/llm/index.d.ts +0 -2
  61. package/dist/llm/index.js +0 -9
  62. package/dist/llm/index.js.map +0 -1
  63. package/dist/llm/openai.d.ts +0 -96
  64. package/dist/llm/openai.js +0 -259
  65. package/dist/llm/openai.js.map +0 -1
  66. package/dist/llm/output/base.d.ts +0 -12
  67. package/dist/llm/output/base.js +0 -45
  68. package/dist/llm/output/base.js.map +0 -1
  69. package/dist/llm/output/index.d.ts +0 -9
  70. package/dist/llm/output/index.js +0 -30
  71. package/dist/llm/output/index.js.map +0 -1
  72. package/dist/llm/output/openai.d.ts +0 -17
  73. package/dist/llm/output/openai.js +0 -58
  74. package/dist/llm/output/openai.js.map +0 -1
  75. package/dist/parser/_base.d.ts +0 -33
  76. package/dist/parser/_base.js +0 -62
  77. package/dist/parser/_base.js.map +0 -1
  78. package/dist/parser/_functions.d.ts +0 -109
  79. package/dist/parser/_functions.js +0 -55
  80. package/dist/parser/_functions.js.map +0 -1
  81. package/dist/parser/_utils.d.ts +0 -3
  82. package/dist/parser/_utils.js +0 -24
  83. package/dist/parser/_utils.js.map +0 -1
  84. package/dist/parser/index.d.ts +0 -15
  85. package/dist/parser/index.js +0 -34
  86. package/dist/parser/index.js.map +0 -1
  87. package/dist/parser/parsers/BooleanParser.d.ts +0 -8
  88. package/dist/parser/parsers/BooleanParser.js +0 -20
  89. package/dist/parser/parsers/BooleanParser.js.map +0 -1
  90. package/dist/parser/parsers/CustomParser.d.ts +0 -28
  91. package/dist/parser/parsers/CustomParser.js +0 -42
  92. package/dist/parser/parsers/CustomParser.js.map +0 -1
  93. package/dist/parser/parsers/JsonParser.d.ts +0 -7
  94. package/dist/parser/parsers/JsonParser.js +0 -27
  95. package/dist/parser/parsers/JsonParser.js.map +0 -1
  96. package/dist/parser/parsers/ListToArrayParser.d.ts +0 -5
  97. package/dist/parser/parsers/ListToArrayParser.js +0 -17
  98. package/dist/parser/parsers/ListToArrayParser.js.map +0 -1
  99. package/dist/parser/parsers/ListToJsonParser.d.ts +0 -7
  100. package/dist/parser/parsers/ListToJsonParser.js +0 -34
  101. package/dist/parser/parsers/ListToJsonParser.js.map +0 -1
  102. package/dist/parser/parsers/ListToKeyValueParser.d.ts +0 -14
  103. package/dist/parser/parsers/ListToKeyValueParser.js +0 -24
  104. package/dist/parser/parsers/ListToKeyValueParser.js.map +0 -1
  105. package/dist/parser/parsers/MarkdownCodeBlock.d.ts +0 -14
  106. package/dist/parser/parsers/MarkdownCodeBlock.js +0 -16
  107. package/dist/parser/parsers/MarkdownCodeBlock.js.map +0 -1
  108. package/dist/parser/parsers/MarkdownCodeBlocks.d.ts +0 -14
  109. package/dist/parser/parsers/MarkdownCodeBlocks.js +0 -25
  110. package/dist/parser/parsers/MarkdownCodeBlocks.js.map +0 -1
  111. package/dist/parser/parsers/NumberParser.d.ts +0 -8
  112. package/dist/parser/parsers/NumberParser.js +0 -16
  113. package/dist/parser/parsers/NumberParser.js.map +0 -1
  114. package/dist/parser/parsers/OpenAiFunctionParser.d.ts +0 -16
  115. package/dist/parser/parsers/OpenAiFunctionParser.js +0 -32
  116. package/dist/parser/parsers/OpenAiFunctionParser.js.map +0 -1
  117. package/dist/parser/parsers/ReplaceStringTemplateParser.d.ts +0 -8
  118. package/dist/parser/parsers/ReplaceStringTemplateParser.js +0 -15
  119. package/dist/parser/parsers/ReplaceStringTemplateParser.js.map +0 -1
  120. package/dist/parser/parsers/StringExtractParser.d.ts +0 -12
  121. package/dist/parser/parsers/StringExtractParser.js +0 -42
  122. package/dist/parser/parsers/StringExtractParser.js.map +0 -1
  123. package/dist/parser/parsers/StringParser.d.ts +0 -8
  124. package/dist/parser/parsers/StringParser.js +0 -17
  125. package/dist/parser/parsers/StringParser.js.map +0 -1
  126. package/dist/plugins/callable/callable.d.ts +0 -87
  127. package/dist/plugins/callable/callable.js +0 -149
  128. package/dist/plugins/callable/callable.js.map +0 -1
  129. package/dist/plugins/callable/index.d.ts +0 -21
  130. package/dist/plugins/callable/index.js +0 -29
  131. package/dist/plugins/callable/index.js.map +0 -1
  132. package/dist/prompt/_base.d.ts +0 -61
  133. package/dist/prompt/_base.js +0 -164
  134. package/dist/prompt/_base.js.map +0 -1
  135. package/dist/prompt/_functions.d.ts +0 -19
  136. package/dist/prompt/_functions.js +0 -24
  137. package/dist/prompt/_functions.js.map +0 -1
  138. package/dist/prompt/chat.d.ts +0 -103
  139. package/dist/prompt/chat.js +0 -328
  140. package/dist/prompt/chat.js.map +0 -1
  141. package/dist/prompt/index.d.ts +0 -4
  142. package/dist/prompt/index.js +0 -13
  143. package/dist/prompt/index.js.map +0 -1
  144. package/dist/prompt/text.d.ts +0 -10
  145. package/dist/prompt/text.js +0 -16
  146. package/dist/prompt/text.js.map +0 -1
  147. package/dist/state/_base.d.ts +0 -29
  148. package/dist/state/_base.js +0 -96
  149. package/dist/state/_base.js.map +0 -1
  150. package/dist/state/_functions.d.ts +0 -7
  151. package/dist/state/_functions.js +0 -34
  152. package/dist/state/_functions.js.map +0 -1
  153. package/dist/state/dialogue.d.ts +0 -24
  154. package/dist/state/dialogue.js +0 -111
  155. package/dist/state/dialogue.js.map +0 -1
  156. package/dist/state/index.d.ts +0 -4
  157. package/dist/state/index.js +0 -16
  158. package/dist/state/index.js.map +0 -1
  159. package/dist/state/item.d.ts +0 -22
  160. package/dist/state/item.js +0 -63
  161. package/dist/state/item.js.map +0 -1
  162. package/dist/types/index.d.ts +0 -1
  163. package/dist/types/index.js +0 -18
  164. package/dist/types/index.js.map +0 -1
  165. package/dist/utils/const.d.ts +0 -16
  166. package/dist/utils/const.js +0 -20
  167. package/dist/utils/const.js.map +0 -1
  168. package/dist/utils/index.d.ts +0 -1
  169. package/dist/utils/index.js +0 -18
  170. package/dist/utils/index.js.map +0 -1
  171. package/dist/utils/modules/asyncCallWithTimeout.d.ts +0 -1
  172. package/dist/utils/modules/asyncCallWithTimeout.js +0 -17
  173. package/dist/utils/modules/asyncCallWithTimeout.js.map +0 -1
  174. package/dist/utils/modules/handlebars/hbs.d.ts +0 -11
  175. package/dist/utils/modules/handlebars/hbs.js +0 -65
  176. package/dist/utils/modules/handlebars/hbs.js.map +0 -1
  177. package/dist/utils/modules/handlebars/helpers/index.d.ts +0 -11
  178. package/dist/utils/modules/handlebars/helpers/index.js +0 -108
  179. package/dist/utils/modules/handlebars/helpers/index.js.map +0 -1
  180. package/dist/utils/modules/handlebars/index.d.ts +0 -2
  181. package/dist/utils/modules/handlebars/index.js +0 -79
  182. package/dist/utils/modules/handlebars/index.js.map +0 -1
  183. package/dist/utils/modules/handlebars/templates/index.d.ts +0 -12
  184. package/dist/utils/modules/handlebars/templates/index.js +0 -46
  185. package/dist/utils/modules/handlebars/templates/index.js.map +0 -1
  186. package/dist/utils/modules/index.d.ts +0 -73
  187. package/dist/utils/modules/index.js +0 -190
  188. package/dist/utils/modules/index.js.map +0 -1
  189. package/dist/utils/modules/json-schema-filter.d.ts +0 -2
  190. package/dist/utils/modules/json-schema-filter.js +0 -90
  191. package/dist/utils/modules/json-schema-filter.js.map +0 -1
  192. package/dist/utils/modules/json.d.ts +0 -3
  193. package/dist/utils/modules/json.js +0 -57
  194. package/dist/utils/modules/json.js.map +0 -1
  195. package/dist/utils/modules/openai.d.ts +0 -12
  196. package/dist/utils/modules/openai.js +0 -31
  197. package/dist/utils/modules/openai.js.map +0 -1
  198. package/dist/utils/modules/replaceTemplateString.d.ts +0 -2
  199. package/dist/utils/modules/replaceTemplateString.js +0 -21
  200. package/dist/utils/modules/replaceTemplateString.js.map +0 -1
  201. package/dist/vector/base.d.ts +0 -11
  202. package/dist/vector/base.js +0 -23
  203. package/dist/vector/base.js.map +0 -1
  204. package/dist/vector/index.d.ts +0 -2
  205. package/dist/vector/index.js +0 -8
  206. package/dist/vector/index.js.map +0 -1
  207. package/dist/vector/pinecone.d.ts +0 -6
  208. package/dist/vector/pinecone.js +0 -23
  209. package/dist/vector/pinecone.js.map +0 -1
package/dist/index.mjs ADDED
@@ -0,0 +1,4150 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __typeError = (msg) => {
3
+ throw TypeError(msg);
4
+ };
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
+ }) : x)(function(x) {
10
+ if (typeof require !== "undefined") return require.apply(this, arguments);
11
+ throw Error('Dynamic require of "' + x + '" is not supported');
12
+ });
13
+ var __export = (target, all) => {
14
+ for (var name in all)
15
+ __defProp(target, name, { get: all[name], enumerable: true });
16
+ };
17
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
18
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
19
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
20
+ 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);
21
+
22
+ // src/utils/modules/pick.ts
23
+ function pick(object, keys) {
24
+ return keys.reduce((obj, key) => {
25
+ if (object && object.hasOwnProperty(key)) {
26
+ obj[key] = object[key];
27
+ }
28
+ return obj;
29
+ }, {});
30
+ }
31
+ __name(pick, "pick");
32
+
33
+ // src/utils/modules/ensureInputIsObject.ts
34
+ function ensureInputIsObject(input) {
35
+ if (input === null || typeof input === "undefined") {
36
+ return {
37
+ input
38
+ };
39
+ }
40
+ switch (typeof input) {
41
+ case "object": {
42
+ if (Array.isArray(input)) {
43
+ return {
44
+ input
45
+ };
46
+ }
47
+ return input;
48
+ }
49
+ default:
50
+ return {
51
+ input
52
+ };
53
+ }
54
+ }
55
+ __name(ensureInputIsObject, "ensureInputIsObject");
56
+
57
+ // src/utils/modules/uuid.ts
58
+ import { v4 as uuidv4 } from "uuid";
59
+
60
+ // src/executor/_metadata.ts
61
+ var _state;
62
+ var _ExecutorExecutionMetadataState = class _ExecutorExecutionMetadataState {
63
+ constructor(items) {
64
+ __privateAdd(this, _state, {
65
+ start: null,
66
+ end: null,
67
+ input: void 0,
68
+ handlerInput: void 0,
69
+ handlerOutput: void 0,
70
+ output: void 0,
71
+ errorMessage: void 0,
72
+ error: void 0,
73
+ metadata: null
74
+ });
75
+ if (items) {
76
+ this.setItem(items);
77
+ }
78
+ }
79
+ setItem(items) {
80
+ if (!items || typeof items !== "object" || Array.isArray(items)) {
81
+ return this;
82
+ }
83
+ const keys = Object.keys(items);
84
+ for (const key of keys) {
85
+ const value = items[key];
86
+ __privateGet(this, _state)[key] = value;
87
+ }
88
+ return this;
89
+ }
90
+ asPlainObject() {
91
+ return Object.freeze({
92
+ start: __privateGet(this, _state).start,
93
+ end: __privateGet(this, _state).end,
94
+ input: __privateGet(this, _state).input,
95
+ handlerInput: __privateGet(this, _state).handlerInput,
96
+ handlerOutput: __privateGet(this, _state).handlerOutput,
97
+ output: __privateGet(this, _state).output,
98
+ errorMessage: __privateGet(this, _state).errorMessage,
99
+ error: __privateGet(this, _state).error,
100
+ metadata: __privateGet(this, _state).metadata
101
+ });
102
+ }
103
+ };
104
+ _state = new WeakMap();
105
+ __name(_ExecutorExecutionMetadataState, "ExecutorExecutionMetadataState");
106
+ var ExecutorExecutionMetadataState = _ExecutorExecutionMetadataState;
107
+ function createMetadataState(items) {
108
+ return new ExecutorExecutionMetadataState(items);
109
+ }
110
+ __name(createMetadataState, "createMetadataState");
111
+
112
+ // src/utils/const.ts
113
+ var hookOnComplete = `onComplete`;
114
+ var hookOnError = `onError`;
115
+ var hookOnSuccess = `onSuccess`;
116
+
117
+ // src/executor/_base.ts
118
+ var _BaseExecutor = class _BaseExecutor {
119
+ constructor(name, type, options) {
120
+ /**
121
+ * @property id - internal id of the executor
122
+ */
123
+ __publicField(this, "id");
124
+ /**
125
+ * @property type - type of executor
126
+ */
127
+ __publicField(this, "type");
128
+ /**
129
+ * @property created - timestamp date created
130
+ */
131
+ __publicField(this, "created");
132
+ /**
133
+ * @property name - name of executor
134
+ */
135
+ __publicField(this, "name");
136
+ /**
137
+ * @property executions -
138
+ */
139
+ __publicField(this, "executions");
140
+ __publicField(this, "traceId", null);
141
+ /**
142
+ * @property hooks - hooks to be ran during execution
143
+ */
144
+ __publicField(this, "hooks");
145
+ __publicField(this, "allowedHooks", [
146
+ hookOnComplete,
147
+ hookOnError,
148
+ hookOnSuccess
149
+ ]);
150
+ this.id = uuidv4();
151
+ this.type = type;
152
+ this.name = name;
153
+ this.created = (/* @__PURE__ */ new Date()).getTime();
154
+ this.executions = 0;
155
+ this.hooks = {
156
+ onSuccess: [],
157
+ onError: [],
158
+ onComplete: []
159
+ };
160
+ if (options?.hooks) {
161
+ this.setHooks(options.hooks);
162
+ }
163
+ }
164
+ /**
165
+ *
166
+ * Used to filter the input of the handler
167
+ * @param _input
168
+ * @returns original input formatted for handler
169
+ */
170
+ async getHandlerInput(_input, _metadata, _options) {
171
+ return ensureInputIsObject(_input);
172
+ }
173
+ /**
174
+ *
175
+ * Used to filter the output of the handler
176
+ * @param _input
177
+ * @returns output O
178
+ */
179
+ getHandlerOutput(out, _metadata, _options) {
180
+ return out;
181
+ }
182
+ /**
183
+ *
184
+ * execute - Runs the executor
185
+ * @param _input
186
+ * @returns handler output
187
+ */
188
+ async execute(_input, _options) {
189
+ this.executions++;
190
+ const _metadata = createMetadataState({
191
+ start: (/* @__PURE__ */ new Date()).getTime(),
192
+ input: _input
193
+ });
194
+ try {
195
+ const input = await this.getHandlerInput(_input, _metadata.asPlainObject(), _options);
196
+ _metadata.setItem({
197
+ handlerInput: input
198
+ });
199
+ let result = await this.handler(input, _options);
200
+ _metadata.setItem({
201
+ handlerOutput: result
202
+ });
203
+ const output = this.getHandlerOutput(result, _metadata.asPlainObject(), _options);
204
+ _metadata.setItem({
205
+ output
206
+ });
207
+ this.runHook("onSuccess", _metadata.asPlainObject());
208
+ return output;
209
+ } catch (error) {
210
+ _metadata.setItem({
211
+ error,
212
+ errorMessage: error.message
213
+ });
214
+ this.runHook("onError", _metadata.asPlainObject());
215
+ throw error;
216
+ } finally {
217
+ _metadata.setItem({
218
+ end: (/* @__PURE__ */ new Date()).getTime()
219
+ });
220
+ this.runHook("onComplete", _metadata.asPlainObject());
221
+ }
222
+ }
223
+ metadata() {
224
+ return {};
225
+ }
226
+ getMetadata(metadata) {
227
+ return Object.assign({}, this.metadata(), {
228
+ traceId: this.getTraceId(),
229
+ id: this.id,
230
+ type: this.type,
231
+ name: this.name,
232
+ created: this.created,
233
+ executions: this.executions,
234
+ metadata
235
+ });
236
+ }
237
+ runHook(hook, _metadata) {
238
+ const { [hook]: hooks = [] } = pick(this.hooks, this.allowedHooks);
239
+ for (const hookFn of [
240
+ ...hooks
241
+ ]) {
242
+ if (typeof hookFn === "function") {
243
+ try {
244
+ hookFn(_metadata, this.getMetadata());
245
+ } catch (error) {
246
+ }
247
+ }
248
+ }
249
+ }
250
+ setHooks(hooks = {}) {
251
+ const hookKeys = Object.keys(hooks);
252
+ for (const hookKey of hookKeys.filter((k) => this.allowedHooks.includes(k))) {
253
+ const hookInput = hooks[hookKey];
254
+ if (hookInput) {
255
+ const _hooks = Array.isArray(hookInput) ? hookInput : [
256
+ hookInput
257
+ ];
258
+ for (const hook of _hooks) {
259
+ if (hook && typeof hook === "function" && !this.hooks[hookKey].find((h) => h === hook)) {
260
+ this.hooks[hookKey].push(hook);
261
+ }
262
+ }
263
+ }
264
+ }
265
+ return this;
266
+ }
267
+ removeHook(eventName, fn) {
268
+ if (typeof fn !== "function") return this;
269
+ const lis = this.hooks[eventName];
270
+ if (!lis) return this;
271
+ for (let i = lis.length; i >= 0; i--) {
272
+ if (lis[i] === fn) {
273
+ lis.splice(i, 1);
274
+ break;
275
+ }
276
+ }
277
+ return this;
278
+ }
279
+ on(eventName, fn) {
280
+ return this.setHooks({
281
+ [eventName]: fn
282
+ });
283
+ }
284
+ off(eventName, fn) {
285
+ return this.removeHook(eventName, fn);
286
+ }
287
+ once(eventName, fn) {
288
+ if (typeof fn !== "function") return this;
289
+ const onceWrapper = /* @__PURE__ */ __name((...args) => {
290
+ fn(...args);
291
+ this.off(eventName, onceWrapper);
292
+ }, "onceWrapper");
293
+ this.hooks[eventName].push(onceWrapper);
294
+ return this;
295
+ }
296
+ withTraceId(traceId) {
297
+ this.traceId = traceId;
298
+ return this;
299
+ }
300
+ getTraceId() {
301
+ return this.traceId;
302
+ }
303
+ };
304
+ __name(_BaseExecutor, "BaseExecutor");
305
+ var BaseExecutor = _BaseExecutor;
306
+
307
+ // src/utils/modules/inferFunctionName.ts
308
+ function inferFunctionName(func, defaultName) {
309
+ const name = func?.name;
310
+ if (name && typeof name === "string") {
311
+ if (name.substring(0, 6) === "bound ") {
312
+ return name.replace("bound ", "");
313
+ } else {
314
+ return name;
315
+ }
316
+ }
317
+ var result = /^function\s+([\w\$]+)\s*\(/.exec(func.toString());
318
+ return result ? result[1] : defaultName;
319
+ }
320
+ __name(inferFunctionName, "inferFunctionName");
321
+
322
+ // src/executor/core.ts
323
+ var _CoreExecutor = class _CoreExecutor extends BaseExecutor {
324
+ constructor(fn, options) {
325
+ const name = fn?.name ? fn.name : inferFunctionName(fn.handler, "anonymous-core-executor");
326
+ super(name, "function-executor", options);
327
+ __publicField(this, "_handler");
328
+ this._handler = fn.handler.bind(null);
329
+ }
330
+ async handler(_input) {
331
+ return this._handler.call(null, _input);
332
+ }
333
+ };
334
+ __name(_CoreExecutor, "CoreExecutor");
335
+ var CoreExecutor = _CoreExecutor;
336
+
337
+ // src/parser/_base.ts
338
+ var _BaseParser = class _BaseParser {
339
+ /**
340
+ * Create a new BaseParser.
341
+ * @param name - The name of the parser.
342
+ * @param options - options
343
+ */
344
+ constructor(name, options = {}, target = "text") {
345
+ __publicField(this, "name");
346
+ __publicField(this, "options");
347
+ __publicField(this, "target", "text");
348
+ this.name = name;
349
+ this.target = target;
350
+ if (options) {
351
+ this.options = options;
352
+ }
353
+ }
354
+ };
355
+ __name(_BaseParser, "BaseParser");
356
+ var BaseParser = _BaseParser;
357
+ var _BaseParserWithJson = class _BaseParserWithJson extends BaseParser {
358
+ /**
359
+ * Create a new BaseParser.
360
+ * @param name - The name of the parser.
361
+ * @param options - options
362
+ */
363
+ constructor(name, options) {
364
+ super(name);
365
+ __publicField(this, "schema");
366
+ __publicField(this, "validateSchema");
367
+ const { schema, validateSchema: validateSchema2 } = options;
368
+ this.validateSchema = !!validateSchema2;
369
+ if (schema) {
370
+ this.schema = schema;
371
+ }
372
+ }
373
+ };
374
+ __name(_BaseParserWithJson, "BaseParserWithJson");
375
+ var BaseParserWithJson = _BaseParserWithJson;
376
+
377
+ // src/utils/index.ts
378
+ var utils_exports = {};
379
+ __export(utils_exports, {
380
+ assert: () => assert,
381
+ asyncCallWithTimeout: () => asyncCallWithTimeout,
382
+ defineSchema: () => defineSchema,
383
+ filterObjectOnSchema: () => filterObjectOnSchema,
384
+ importHelpers: () => importHelpers,
385
+ importPartials: () => importPartials,
386
+ isObjectStringified: () => isObjectStringified,
387
+ maybeParseJSON: () => maybeParseJSON,
388
+ maybeStringifyJSON: () => maybeStringifyJSON,
389
+ registerHelpers: () => registerHelpers,
390
+ registerPartials: () => registerPartials,
391
+ replaceTemplateString: () => replaceTemplateString,
392
+ replaceTemplateStringAsync: () => replaceTemplateStringAsync
393
+ });
394
+
395
+ // src/utils/modules/assert.ts
396
+ function assert(condition, message) {
397
+ if (condition === void 0 || condition === null || condition === false) {
398
+ if (typeof message === "string") {
399
+ throw new Error(message);
400
+ } else if (message instanceof Error) {
401
+ throw message;
402
+ } else {
403
+ throw new Error(`Assertion error`);
404
+ }
405
+ }
406
+ }
407
+ __name(assert, "assert");
408
+
409
+ // src/utils/modules/defineSchema.ts
410
+ import { asConst } from "json-schema-to-ts";
411
+ function defineSchema(obj) {
412
+ obj.additionalProperties = false;
413
+ return asConst(obj);
414
+ }
415
+ __name(defineSchema, "defineSchema");
416
+
417
+ // src/utils/modules/handlebars/utils/importPartials.ts
418
+ function importPartials(_partials) {
419
+ let partials2 = [];
420
+ if (_partials) {
421
+ const externalPartialKeys = Object.keys(_partials);
422
+ for (const externalPartialKey of externalPartialKeys) {
423
+ if (typeof externalPartialKey === "string") {
424
+ partials2.push({
425
+ name: externalPartialKey,
426
+ template: _partials[externalPartialKey]
427
+ });
428
+ }
429
+ }
430
+ }
431
+ return partials2;
432
+ }
433
+ __name(importPartials, "importPartials");
434
+
435
+ // src/utils/modules/handlebars/utils/importHelpers.ts
436
+ function importHelpers(_helpers) {
437
+ let helpers = [];
438
+ if (_helpers) {
439
+ const externalHelperKeys = Object.keys(_helpers);
440
+ for (const externalHelperKey of externalHelperKeys) {
441
+ if (typeof externalHelperKey === "string") {
442
+ helpers.push({
443
+ name: externalHelperKey,
444
+ handler: _helpers[externalHelperKey]
445
+ });
446
+ }
447
+ }
448
+ }
449
+ return helpers;
450
+ }
451
+ __name(importHelpers, "importHelpers");
452
+
453
+ // src/utils/modules/handlebars/hbs.ts
454
+ import Handlebars from "handlebars";
455
+
456
+ // src/utils/modules/handlebars/helpers/index.ts
457
+ var helpers_exports = {};
458
+ __export(helpers_exports, {
459
+ eq: () => eq,
460
+ getKeyOr: () => getKeyOr,
461
+ getOr: () => getOr,
462
+ hbsInTemplate: () => hbsInTemplate,
463
+ ifCond: () => ifCond,
464
+ indentJson: () => indentJson,
465
+ join: () => join,
466
+ jsonSchemaExample: () => jsonSchemaExample,
467
+ neq: () => neq,
468
+ objectToList: () => objectToList,
469
+ pluralize: () => pluralize
470
+ });
471
+
472
+ // src/utils/modules/replaceTemplateString.ts
473
+ function replaceTemplateString(templateString, substitutions = {}, configuration = {
474
+ helpers: [],
475
+ partials: []
476
+ }) {
477
+ if (!templateString) return templateString || "";
478
+ const tempHelpers = [];
479
+ const tempPartials = [];
480
+ if (Array.isArray(configuration.helpers)) {
481
+ registerHelpers(configuration.helpers, hbs);
482
+ tempHelpers.push(...configuration.helpers.map((a) => a.name));
483
+ }
484
+ if (Array.isArray(configuration.partials)) {
485
+ registerPartials(configuration.partials, hbs);
486
+ tempPartials.push(...configuration.partials.map((a) => a.name));
487
+ }
488
+ const template = hbs.compile(templateString);
489
+ const res = template(substitutions, {
490
+ allowedProtoMethods: {
491
+ substring: true
492
+ }
493
+ });
494
+ tempHelpers.forEach(function(n) {
495
+ hbs.unregisterHelper(n);
496
+ });
497
+ tempPartials.forEach(function(n) {
498
+ hbs.unregisterPartial(n);
499
+ });
500
+ return res;
501
+ }
502
+ __name(replaceTemplateString, "replaceTemplateString");
503
+
504
+ // src/utils/modules/handlebars/helpers/hbsInTemplate.ts
505
+ function hbsInTemplate(arg1) {
506
+ const data = this;
507
+ const replace = replaceTemplateString(arg1, data);
508
+ return replace;
509
+ }
510
+ __name(hbsInTemplate, "hbsInTemplate");
511
+
512
+ // src/utils/modules/get.ts
513
+ function get(obj, path, defaultValue) {
514
+ if (obj == null || path === "" || Array.isArray(path) && path.length === 0) {
515
+ return defaultValue;
516
+ }
517
+ const pathString = Array.isArray(path) ? path.join(".") : path;
518
+ const travel = /* @__PURE__ */ __name((regexp) => pathString.split(regexp).filter(Boolean).reduce((res, key) => res !== null && res !== void 0 ? res[key] : res, obj), "travel");
519
+ const result = travel(/[,[\]]+?/) || travel(/[,[\].]+?/);
520
+ return result === void 0 || result === obj ? defaultValue : result === null ? defaultValue : result;
521
+ }
522
+ __name(get, "get");
523
+
524
+ // src/utils/modules/handlebars/helpers/getKeyOr.ts
525
+ function getKeyOr(key, arg2) {
526
+ const res = get(this, key);
527
+ return typeof res !== "undefined" && res !== "" ? res : arg2;
528
+ }
529
+ __name(getKeyOr, "getKeyOr");
530
+
531
+ // src/utils/modules/handlebars/helpers/getOr.ts
532
+ function getOr(arg1, arg2) {
533
+ return typeof arg1 !== "undefined" && arg1 !== "" ? arg1 : arg2;
534
+ }
535
+ __name(getOr, "getOr");
536
+
537
+ // src/utils/modules/handlebars/helpers/indentJson.ts
538
+ function indentJson(arg1, collapse = "false") {
539
+ if (typeof arg1 !== "object") {
540
+ return replaceTemplateString(arg1 || "", this);
541
+ }
542
+ const replaced = maybeParseJSON(replaceTemplateString(maybeStringifyJSON(arg1), this));
543
+ if (collapse == "true") {
544
+ return JSON.stringify(replaced);
545
+ }
546
+ return JSON.stringify(replaced, null, 2);
547
+ }
548
+ __name(indentJson, "indentJson");
549
+
550
+ // src/utils/modules/toNumber.ts
551
+ function toNumber(value) {
552
+ if (typeof value === "number") {
553
+ return value;
554
+ }
555
+ if (typeof value === "string" && value.trim() !== "") {
556
+ return Number(value);
557
+ }
558
+ return NaN;
559
+ }
560
+ __name(toNumber, "toNumber");
561
+
562
+ // src/utils/modules/filterObjectOnSchema.ts
563
+ function isObject(obj) {
564
+ return obj === Object(obj);
565
+ }
566
+ __name(isObject, "isObject");
567
+ function getType(schemaType) {
568
+ if (!Array.isArray(schemaType)) {
569
+ return schemaType;
570
+ }
571
+ var typeArray = schemaType;
572
+ for (var i = 0; i < typeArray.length; i++) {
573
+ var type = typeArray[i];
574
+ if (type !== "null") {
575
+ return type;
576
+ }
577
+ }
578
+ }
579
+ __name(getType, "getType");
580
+ function filterObjectOnSchema(schema, doc, detach, property) {
581
+ let result;
582
+ if (doc === null || doc === void 0) {
583
+ return doc;
584
+ }
585
+ var type = getType(schema.type);
586
+ if (type === "object" && isObject(doc) && schema.properties) {
587
+ result = {};
588
+ Object.keys(schema.properties).forEach(function(key) {
589
+ var child = doc[key];
590
+ var sp = schema.properties[key];
591
+ var filteredChild = filterObjectOnSchema(sp, child, detach, property);
592
+ if (property) {
593
+ result[key] = get(sp, property, "");
594
+ } else {
595
+ if (filteredChild === void 0) {
596
+ if (typeof sp?.default !== "undefined") {
597
+ result[key] = get(sp, "default", "");
598
+ } else {
599
+ return;
600
+ }
601
+ } else {
602
+ if (sp.type === "integer" || sp.type === "number") {
603
+ result[key] = toNumber(filteredChild);
604
+ } else if (sp.type === "boolean") {
605
+ result[key] = !!filteredChild;
606
+ } else {
607
+ result[key] = filteredChild;
608
+ }
609
+ }
610
+ }
611
+ });
612
+ } else if (type === "object" && isObject(doc) && detach) {
613
+ return {};
614
+ } else if (type === "array" && Array.isArray(doc) && schema.items) {
615
+ result = [];
616
+ doc.forEach(function(item) {
617
+ result.push(filterObjectOnSchema(schema.items, item, detach, property));
618
+ });
619
+ } else {
620
+ result = doc;
621
+ }
622
+ return result;
623
+ }
624
+ __name(filterObjectOnSchema, "filterObjectOnSchema");
625
+
626
+ // src/utils/modules/schemaExampleWith.ts
627
+ function schemaExampleWith(schema, property) {
628
+ if (schema.type === "array") {
629
+ return filterObjectOnSchema(schema, [
630
+ {}
631
+ ], void 0, property);
632
+ }
633
+ return filterObjectOnSchema(schema, {}, void 0, property);
634
+ }
635
+ __name(schemaExampleWith, "schemaExampleWith");
636
+
637
+ // src/utils/modules/handlebars/helpers/jsonSchemaExample.ts
638
+ function jsonSchemaExample(key, prop, collapse) {
639
+ const schema = get(this, key);
640
+ if (schema && schema.type) {
641
+ const result = schemaExampleWith(schema, prop);
642
+ if (typeof result !== "object") {
643
+ return "";
644
+ }
645
+ const replaced = maybeParseJSON(replaceTemplateString(maybeStringifyJSON(result), this));
646
+ if (collapse == "true") {
647
+ return JSON.stringify(replaced);
648
+ }
649
+ return JSON.stringify(replaced, null, 2);
650
+ }
651
+ return "";
652
+ }
653
+ __name(jsonSchemaExample, "jsonSchemaExample");
654
+
655
+ // src/utils/modules/handlebars/helpers/pluralize.ts
656
+ function pluralize(arg1, arg2) {
657
+ const [singular, plural] = arg1.split("|");
658
+ return arg2 > 1 ? plural : singular;
659
+ }
660
+ __name(pluralize, "pluralize");
661
+
662
+ // src/utils/modules/handlebars/helpers/eq.ts
663
+ function eq(arg1 = "", arg2 = "", options) {
664
+ const isArr = arg2.toString().split(",").map((a) => a.trim());
665
+ return isArr.includes(arg1) ? options.fn(this) : options.inverse(this);
666
+ }
667
+ __name(eq, "eq");
668
+
669
+ // src/utils/modules/handlebars/helpers/neq.ts
670
+ function neq(arg1 = "", arg2 = "", options) {
671
+ const isArr = arg2.toString().split(",").map((a) => a.trim());
672
+ return !isArr.includes(arg1) ? options.fn(this) : options.inverse(this);
673
+ }
674
+ __name(neq, "neq");
675
+
676
+ // src/utils/modules/handlebars/helpers/ifCond.ts
677
+ function ifCond(v1, operator, v2, options) {
678
+ switch (operator) {
679
+ case "==":
680
+ return v1 == v2 ? options.fn(this) : options.inverse(this);
681
+ case "===":
682
+ return v1 === v2 ? options.fn(this) : options.inverse(this);
683
+ case "!=":
684
+ return v1 != v2 ? options.fn(this) : options.inverse(this);
685
+ case "!==":
686
+ return v1 !== v2 ? options.fn(this) : options.inverse(this);
687
+ case "<":
688
+ return v1 < v2 ? options.fn(this) : options.inverse(this);
689
+ case "<=":
690
+ return v1 <= v2 ? options.fn(this) : options.inverse(this);
691
+ case ">":
692
+ return v1 > v2 ? options.fn(this) : options.inverse(this);
693
+ case ">=":
694
+ return v1 >= v2 ? options.fn(this) : options.inverse(this);
695
+ case "&&":
696
+ return v1 && v2 ? options.fn(this) : options.inverse(this);
697
+ case "||":
698
+ return v1 || v2 ? options.fn(this) : options.inverse(this);
699
+ default:
700
+ return options.inverse(this);
701
+ }
702
+ }
703
+ __name(ifCond, "ifCond");
704
+
705
+ // src/utils/modules/handlebars/helpers/objectToList.ts
706
+ function objectToList(arg = {}) {
707
+ return Object.keys(arg).map((key) => `- ${key}: ${arg[key]}`).join("\n");
708
+ }
709
+ __name(objectToList, "objectToList");
710
+
711
+ // src/utils/modules/handlebars/helpers/join.ts
712
+ function join(array) {
713
+ if (typeof array === "string") return array;
714
+ if (!Array.isArray(array)) return "";
715
+ return array.join(", ");
716
+ }
717
+ __name(join, "join");
718
+
719
+ // src/utils/modules/handlebars/templates/index.ts
720
+ var MarkdownCode = `{{#if code}}\`\`\`{{#if language}}{{language}}{{/if}}
721
+ {{{code}}}
722
+ \`\`\`{{/if}}`;
723
+ var ThoughtActionResult = `
724
+ {{#if title}}{{#if attributes.stepsTaken.length}}{{title}}
725
+ {{/if}}{{/if}}
726
+ {{#each attributes.stepsTaken as | step |}}
727
+ {{#if step.thought}}Thought: {{step.result}}{{/if}}
728
+ {{#if step.result}}Action: {{step.action}}{{/if}}
729
+ {{#if step.result}}Result: {{step.result}}{{/if}}
730
+ {{/each}}`;
731
+ var ChatConversationHistory = `{{~#if title}}{{~#if chat_history.length}}{{title}}
732
+ {{~/if}}{{~/if}}
733
+ {{#each chat_history as | item |}}
734
+ {{~#eq item.role 'user'}}{{#if @last}}{{../mostRecentRolePrefix}}{{../userName}}{{../mostRecentRoleSuffix}}{{else}}{{../userName}}{{/if}}: {{#if @last}}{{../mostRecentMessagePrefix}}{{/if}}{{{item.content}}}{{#if @last}}{{../mostRecentMessageSuffix}}{{/if}}
735
+ {{/eq}}
736
+ {{~#eq item.role 'assistant'}}{{#if @last}}{{../mostRecentRolePrefix}}{{../assistantName}}{{../mostRecentRoleSuffix}}{{else}}{{../assistantName}}{{/if}}: {{#if @last}}{{../mostRecentMessagePrefix}}{{/if}}{{{item.content}}}{{#if @last}}{{../mostRecentMessageSuffix}}{{/if}}
737
+ {{/eq}}
738
+ {{~#eq item.role 'system'}}{{../systemName}}: {{{item.content}}}
739
+ {{/eq}}
740
+ {{~/each}}`;
741
+ var DialogueHistory = `{{>ChatConversationHistory title=title chat_history=(getKeyOr key []) assistantName=(getOr assistant 'Assistant') userName=(getOr user 'User') systemName=(getOr system 'System') mostRecentRolePrefix=mostRecentRolePrefix mostRecentRoleSuffix=mostRecentRoleSuffix mostRecentMessagePrefix=mostRecentMessagePrefix mostRecentMessageSuffix=mostRecentMessageSuffix}}`;
742
+ var SingleChatMessage = `{{~#eq role 'user'}}{{getOr name 'User'}}: {{{content}}}{{~/eq}}
743
+ {{~#eq role 'assistant'}}{{getOr assistant 'Assistant'}}: {{{content}}}{{~/eq}}
744
+ {{~#eq role 'system'}}{{getOr system 'System'}}: {{{content}}}{{~/eq}}`;
745
+ var ThoughtsAndObservations = `{{~#each thoughts as | step |}}
746
+ {{~#if step.thought}}Thought: {{{step.thought}}}
747
+ {{/if}}
748
+ {{~#if step.observation}}Observation: {{{step.observation}}}
749
+ {{/if}}
750
+ {{~/each}}`;
751
+ var JsonSchema = `{{#if (getKeyOr key false)}}
752
+ \`\`\`json
753
+ {{{indentJson (getKeyOr key) collapse}}}
754
+ \`\`\`
755
+ {{~/if}}`;
756
+ var JsonSchemaExampleJson = `{{#if (getOr key false)}}
757
+ \`\`\`json
758
+ {{{jsonSchemaExample key (getOr property '') collapse}}}
759
+ \`\`\`
760
+ {{~/if}}`;
761
+ var partials = {
762
+ JsonSchema,
763
+ JsonSchemaExampleJson,
764
+ MarkdownCode,
765
+ DialogueHistory,
766
+ SingleChatMessage,
767
+ ChatConversationHistory,
768
+ ThoughtsAndObservations,
769
+ ThoughtActionResult
770
+ };
771
+
772
+ // src/utils/modules/handlebars/utils/appendContextPath.ts
773
+ function appendContextPath(contextPath, id) {
774
+ return (contextPath ? `${contextPath}.` : "") + id;
775
+ }
776
+ __name(appendContextPath, "appendContextPath");
777
+
778
+ // src/utils/modules/handlebars/utils/blockParams.ts
779
+ function blockParams(params, ids) {
780
+ return {
781
+ ...params,
782
+ ...{
783
+ path: ids
784
+ }
785
+ };
786
+ }
787
+ __name(blockParams, "blockParams");
788
+
789
+ // src/utils/modules/extend.ts
790
+ function extend(obj, _source) {
791
+ for (let i = 1; i < arguments.length; i++) {
792
+ for (const key in arguments[i]) {
793
+ if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
794
+ obj[key] = arguments[i][key];
795
+ }
796
+ }
797
+ }
798
+ return obj;
799
+ }
800
+ __name(extend, "extend");
801
+
802
+ // src/utils/modules/handlebars/utils/createFrame.ts
803
+ function createFrame(object) {
804
+ const frame = extend({}, object);
805
+ frame._parent = object;
806
+ return frame;
807
+ }
808
+ __name(createFrame, "createFrame");
809
+
810
+ // src/utils/modules/isEmpty.ts
811
+ function isEmpty(value) {
812
+ if (!value && value !== 0) {
813
+ return true;
814
+ }
815
+ if (Array.isArray(value) && value.length === 0) {
816
+ return true;
817
+ }
818
+ return false;
819
+ }
820
+ __name(isEmpty, "isEmpty");
821
+
822
+ // src/utils/modules/isPromise.ts
823
+ function isPromise(value) {
824
+ if (typeof value === "object" && value !== null && typeof value.then === "function") {
825
+ return true;
826
+ }
827
+ return Object.prototype.toString.call(value) === "[object AsyncFunction]";
828
+ }
829
+ __name(isPromise, "isPromise");
830
+
831
+ // src/utils/modules/handlebars/helpers/async/with.ts
832
+ async function withFnAsync(context, options) {
833
+ if (arguments.length !== 2) {
834
+ throw new Error("#with requires exactly one argument");
835
+ }
836
+ if (isPromise(context)) {
837
+ context = await context;
838
+ } else if (typeof context === "function") {
839
+ context = context.call(this);
840
+ }
841
+ const { fn } = options;
842
+ if (!isEmpty(context)) {
843
+ let { data } = options;
844
+ if (options.data && options.ids) {
845
+ data = createFrame(options.data);
846
+ data.contextPath = appendContextPath(options.data.contextPath, options.ids[0]);
847
+ }
848
+ return fn(context, {
849
+ data,
850
+ blockParams: blockParams([
851
+ context
852
+ ], [
853
+ data && data.contextPath
854
+ ])
855
+ });
856
+ }
857
+ return options.inverse(this);
858
+ }
859
+ __name(withFnAsync, "withFnAsync");
860
+
861
+ // src/utils/modules/handlebars/helpers/async/if.ts
862
+ async function ifFnAsync(conditional, options) {
863
+ if (arguments.length !== 2) {
864
+ throw new Error("#if requires exactly one argument");
865
+ }
866
+ if (isPromise(conditional)) {
867
+ conditional = await conditional;
868
+ } else if (typeof conditional === "function") {
869
+ conditional = conditional.call(this);
870
+ }
871
+ if (!options.hash.includeZero && !conditional || isEmpty(conditional)) {
872
+ return options.inverse(this);
873
+ } else {
874
+ return options.fn(this);
875
+ }
876
+ }
877
+ __name(ifFnAsync, "ifFnAsync");
878
+
879
+ // src/utils/modules/isReadableStream.ts
880
+ function isReadableStream(obj) {
881
+ return obj && typeof obj === "object" && typeof obj.pipe === "function" && typeof obj._read === "function";
882
+ }
883
+ __name(isReadableStream, "isReadableStream");
884
+
885
+ // src/utils/modules/handlebars/helpers/async/each.ts
886
+ async function eachFnAsync(arg1, options) {
887
+ if (!options) {
888
+ throw new Error("Must pass iterator to #each");
889
+ }
890
+ const { fn } = options;
891
+ const { inverse } = options;
892
+ let i = 0;
893
+ let data = {};
894
+ let ret = [];
895
+ let contextPath = "";
896
+ if (options.data && options.ids) {
897
+ contextPath = `${appendContextPath(options.data.contextPath, options.ids[0])}.`;
898
+ }
899
+ if (typeof arg1 === "function") {
900
+ arg1 = arg1.call(this);
901
+ }
902
+ if (options.data) {
903
+ data = createFrame(options.data);
904
+ }
905
+ async function execIteration(field, index, last) {
906
+ if (data) {
907
+ data.key = field;
908
+ data.index = index;
909
+ data.first = index === 0;
910
+ data.last = !!last;
911
+ if (contextPath) {
912
+ data.contextPath = contextPath + field;
913
+ }
914
+ }
915
+ ret.push(await fn(arg1[field], {
916
+ data,
917
+ blockParams: blockParams([
918
+ arg1[field],
919
+ field
920
+ ], [
921
+ contextPath + field,
922
+ null
923
+ ])
924
+ }));
925
+ }
926
+ __name(execIteration, "execIteration");
927
+ if (isPromise(arg1)) {
928
+ arg1 = await arg1;
929
+ }
930
+ if (arg1 && typeof arg1 === "object") {
931
+ if (Array.isArray(arg1)) {
932
+ for (let j = arg1.length; i < j; i++) {
933
+ if (i in arg1) {
934
+ await execIteration(i, i, i === arg1.length - 1);
935
+ }
936
+ }
937
+ } else if (global.Symbol && arg1[global.Symbol.iterator]) {
938
+ const newContext = [], iterator = arg1[global.Symbol.iterator]();
939
+ for (let it = iterator.next(); !it.done; it = iterator.next()) {
940
+ newContext.push(it.value);
941
+ }
942
+ arg1 = newContext;
943
+ for (let j = arg1.length; i < j; i++) {
944
+ await execIteration(i, i, i === arg1.length - 1);
945
+ }
946
+ } else if (isReadableStream(arg1)) {
947
+ const newContext = [];
948
+ await new Promise((resolve, reject) => {
949
+ arg1.on("data", (item) => {
950
+ newContext.push(item);
951
+ }).on("end", async () => {
952
+ arg1 = newContext;
953
+ for (let j = arg1.length; i < j; i++) {
954
+ await execIteration(i, i, i === arg1.length - 1);
955
+ }
956
+ resolve(true);
957
+ }).once("error", (e) => reject(e));
958
+ });
959
+ } else {
960
+ let priorKey;
961
+ for (const key of Object.keys(arg1)) {
962
+ if (priorKey !== void 0) {
963
+ await execIteration(priorKey, i - 1);
964
+ }
965
+ priorKey = key;
966
+ i++;
967
+ }
968
+ if (priorKey !== void 0) {
969
+ await execIteration(priorKey, i - 1, true);
970
+ }
971
+ }
972
+ }
973
+ if (i === 0) {
974
+ ret = inverse(this);
975
+ ret = [
976
+ inverse(this)
977
+ ];
978
+ }
979
+ return ret.join("");
980
+ }
981
+ __name(eachFnAsync, "eachFnAsync");
982
+
983
+ // src/utils/modules/handlebars/helpers/async/unless.ts
984
+ async function unlessFnAsync(conditional, options) {
985
+ if (arguments.length !== 2) {
986
+ throw new Error("#unless requires exactly one argument");
987
+ }
988
+ return ifFnAsync.call(this, conditional, {
989
+ fn: options.inverse,
990
+ inverse: options.fn,
991
+ hash: options.hash
992
+ });
993
+ }
994
+ __name(unlessFnAsync, "unlessFnAsync");
995
+
996
+ // src/utils/modules/handlebars/helpers/async/async-helpers.ts
997
+ var asyncCoreOverrideHelpers = {
998
+ if: ifFnAsync,
999
+ with: withFnAsync,
1000
+ each: eachFnAsync,
1001
+ unless: unlessFnAsync
1002
+ };
1003
+
1004
+ // src/utils/modules/getEnvironmentVariable.ts
1005
+ function getEnvironmentVariable(name) {
1006
+ if (typeof process === "object" && process?.env) {
1007
+ return process.env[name];
1008
+ } else {
1009
+ return void 0;
1010
+ }
1011
+ }
1012
+ __name(getEnvironmentVariable, "getEnvironmentVariable");
1013
+
1014
+ // src/utils/modules/handlebars/useHandlebars.ts
1015
+ function useHandlebars(hbsInstance, preferAsync = false) {
1016
+ hbsInstance.registerHelper("with", function(context, options) {
1017
+ return options.fn(context);
1018
+ });
1019
+ hbsInstance.registerHelper("cut", function(str, arg2) {
1020
+ return str.toString().replace(new RegExp(arg2, "g"), "");
1021
+ });
1022
+ hbsInstance.registerHelper("substring", function(str, start, end) {
1023
+ if (str.length > end) {
1024
+ return str.substring(start, end);
1025
+ } else {
1026
+ return str;
1027
+ }
1028
+ });
1029
+ hbsInstance.registerHelper("unless", function(conditional, options) {
1030
+ if (arguments.length !== 2) {
1031
+ throw new Error("#unless requires exactly one argument");
1032
+ }
1033
+ const ifFn = hbsInstance.helpers["if"];
1034
+ return ifFn(conditional, {
1035
+ fn: options.inverse,
1036
+ inverse: options.fn,
1037
+ hash: options.hash
1038
+ });
1039
+ });
1040
+ const helperKeys = Object.keys(helpers_exports);
1041
+ registerHelpers(helperKeys.map((a) => ({
1042
+ handler: helpers_exports[a],
1043
+ name: a
1044
+ })), hbsInstance);
1045
+ if (preferAsync) {
1046
+ const asyncHelperKeys = Object.keys(asyncCoreOverrideHelpers);
1047
+ registerHelpers(asyncHelperKeys.map((a) => ({
1048
+ handler: asyncCoreOverrideHelpers[a],
1049
+ name: a
1050
+ })), hbsInstance);
1051
+ }
1052
+ const helperPath = getEnvironmentVariable("CUSTOM_PROMPT_TEMPLATE_HELPERS_PATH");
1053
+ if (helperPath) {
1054
+ const externalHelpers = __require(helperPath);
1055
+ registerHelpers(importHelpers(externalHelpers), hbsInstance);
1056
+ }
1057
+ const contextPartialKeys = Object.keys(partials);
1058
+ for (const contextPartialKey of contextPartialKeys) {
1059
+ hbsInstance.registerPartial(contextPartialKey, partials[contextPartialKey]);
1060
+ }
1061
+ const partialsPath = getEnvironmentVariable("CUSTOM_PROMPT_TEMPLATE_PARTIALS_PATH");
1062
+ if (typeof process === "object" && partialsPath) {
1063
+ const externalPartials = __require(partialsPath);
1064
+ registerPartials(importPartials(externalPartials), hbsInstance);
1065
+ }
1066
+ return hbsInstance;
1067
+ }
1068
+ __name(useHandlebars, "useHandlebars");
1069
+
1070
+ // src/utils/modules/handlebars/utils/makeHandlebarsInstanceAsync.ts
1071
+ function makeHandlebarsInstanceAsync(hbs2) {
1072
+ var _a;
1073
+ const handlebars = hbs2.create();
1074
+ const asyncCompiler = (_a = class extends hbs2.JavaScriptCompiler {
1075
+ constructor() {
1076
+ super();
1077
+ this.compiler = asyncCompiler;
1078
+ }
1079
+ mergeSource(varDeclarations) {
1080
+ const sources = super.mergeSource(varDeclarations);
1081
+ sources.prepend("return (async () => {");
1082
+ sources.add(" })()");
1083
+ return sources;
1084
+ }
1085
+ appendToBuffer(source, location, explicit) {
1086
+ if (!Array.isArray(source)) {
1087
+ source = [
1088
+ source
1089
+ ];
1090
+ }
1091
+ source = this.source.wrap(source, location);
1092
+ if (this.environment.isSimple) {
1093
+ return [
1094
+ "return await ",
1095
+ source,
1096
+ ";"
1097
+ ];
1098
+ }
1099
+ if (explicit) {
1100
+ return [
1101
+ "buffer += await ",
1102
+ source,
1103
+ ";"
1104
+ ];
1105
+ }
1106
+ source.appendToBuffer = true;
1107
+ source.prepend("await ");
1108
+ return source;
1109
+ }
1110
+ }, __name(_a, "asyncCompiler"), _a);
1111
+ handlebars.JavaScriptCompiler = asyncCompiler;
1112
+ const _compile = handlebars.compile;
1113
+ const _template = handlebars.VM.template;
1114
+ const _escapeExpression = handlebars.escapeExpression;
1115
+ function escapeExpression(value) {
1116
+ if (isPromise(value)) {
1117
+ return value.then((v) => _escapeExpression(v));
1118
+ }
1119
+ return _escapeExpression(value);
1120
+ }
1121
+ __name(escapeExpression, "escapeExpression");
1122
+ function lookupProperty(containerLookupProperty) {
1123
+ return function(parent, propertyName) {
1124
+ if (isPromise(parent)) {
1125
+ if (typeof parent?.then === "function") {
1126
+ return parent.then((p) => containerLookupProperty(p, propertyName));
1127
+ }
1128
+ return parent().then((p) => containerLookupProperty(p, propertyName));
1129
+ }
1130
+ return containerLookupProperty(parent, propertyName);
1131
+ };
1132
+ }
1133
+ __name(lookupProperty, "lookupProperty");
1134
+ handlebars.template = function(spec) {
1135
+ spec.main_d = (_prog, _props, container, _depth, data, blockParams2, depths) => async (context) => {
1136
+ container.escapeExpression = escapeExpression;
1137
+ container.lookupProperty = lookupProperty(container.lookupProperty);
1138
+ if (depths.length == 0) {
1139
+ depths = [
1140
+ data.root
1141
+ ];
1142
+ }
1143
+ const v = spec.main(container, context, container.helpers, container.partials, data, blockParams2, depths);
1144
+ return v;
1145
+ };
1146
+ return _template(spec, handlebars);
1147
+ };
1148
+ handlebars.compile = function(template, options) {
1149
+ const compiled = _compile.apply(handlebars, [
1150
+ template,
1151
+ {
1152
+ ...options
1153
+ }
1154
+ ]);
1155
+ return function(context, execOptions) {
1156
+ context = context || {};
1157
+ return compiled.call(handlebars, context, execOptions);
1158
+ };
1159
+ };
1160
+ return handlebars;
1161
+ }
1162
+ __name(makeHandlebarsInstanceAsync, "makeHandlebarsInstanceAsync");
1163
+
1164
+ // src/utils/modules/handlebars/hbs.ts
1165
+ var __hbsAsync = makeHandlebarsInstanceAsync(Handlebars);
1166
+ var __hbs = Handlebars.create();
1167
+ var hbs = useHandlebars(__hbs);
1168
+ var hbsAsync = useHandlebars(__hbsAsync, true);
1169
+ function registerPartials(partials2, instance) {
1170
+ if (partials2 && Array.isArray(partials2)) {
1171
+ for (const partial of partials2) {
1172
+ if (partial.name && typeof partial.name === "string" && typeof partial.template === "string") {
1173
+ if (instance) {
1174
+ instance.registerPartial(partial.name, partial.template);
1175
+ } else {
1176
+ hbs.registerPartial(partial.name, partial.template);
1177
+ hbsAsync.registerPartial(partial.name, partial.template);
1178
+ }
1179
+ }
1180
+ }
1181
+ }
1182
+ }
1183
+ __name(registerPartials, "registerPartials");
1184
+ function registerHelpers(helpers, instance) {
1185
+ if (helpers && Array.isArray(helpers)) {
1186
+ for (const helper of helpers) {
1187
+ if (helper.name && typeof helper.name === "string" && typeof helper.handler === "function") {
1188
+ if (instance) {
1189
+ instance.registerHelper(helper.name, helper.handler);
1190
+ } else {
1191
+ hbs.registerHelper(helper.name, helper.handler);
1192
+ hbsAsync.registerHelper(helper.name, helper.handler);
1193
+ }
1194
+ }
1195
+ }
1196
+ }
1197
+ }
1198
+ __name(registerHelpers, "registerHelpers");
1199
+
1200
+ // src/utils/modules/replaceTemplateStringAsync.ts
1201
+ async function replaceTemplateStringAsync(templateString, substitutions = {}, configuration = {
1202
+ helpers: [],
1203
+ partials: []
1204
+ }) {
1205
+ if (!templateString) return Promise.resolve(templateString || "");
1206
+ const tempHelpers = [];
1207
+ const tempPartials = [];
1208
+ if (Array.isArray(configuration.helpers)) {
1209
+ registerHelpers(configuration.helpers, hbsAsync);
1210
+ tempHelpers.push(...configuration.helpers.map((a) => a.name));
1211
+ }
1212
+ if (Array.isArray(configuration.partials)) {
1213
+ registerPartials(configuration.partials, hbsAsync);
1214
+ tempPartials.push(...configuration.partials.map((a) => a.name));
1215
+ }
1216
+ const template = hbsAsync.compile(templateString);
1217
+ const res = await template(substitutions, {
1218
+ allowedProtoMethods: {
1219
+ substring: true
1220
+ }
1221
+ });
1222
+ tempHelpers.forEach(function(n) {
1223
+ hbsAsync.unregisterHelper(n);
1224
+ });
1225
+ tempPartials.forEach(function(n) {
1226
+ hbsAsync.unregisterPartial(n);
1227
+ });
1228
+ return res;
1229
+ }
1230
+ __name(replaceTemplateStringAsync, "replaceTemplateStringAsync");
1231
+
1232
+ // src/utils/modules/asyncCallWithTimeout.ts
1233
+ var asyncCallWithTimeout = /* @__PURE__ */ __name(async (asyncPromise, timeLimit = 1e4) => {
1234
+ let timeoutHandle;
1235
+ const timeoutPromise = new Promise((_resolve, reject) => {
1236
+ timeoutHandle = setTimeout(() => {
1237
+ return reject(new Error("Unable to perform action. Try again, or use another action."));
1238
+ }, timeLimit);
1239
+ });
1240
+ return Promise.race([
1241
+ asyncPromise,
1242
+ timeoutPromise
1243
+ ]).then((result) => {
1244
+ clearTimeout(timeoutHandle);
1245
+ return result;
1246
+ });
1247
+ }, "asyncCallWithTimeout");
1248
+
1249
+ // src/utils/modules/json.ts
1250
+ var maybeStringifyJSON = /* @__PURE__ */ __name((objOrMaybeString) => {
1251
+ if (!objOrMaybeString || typeof objOrMaybeString !== "object") {
1252
+ return objOrMaybeString;
1253
+ }
1254
+ try {
1255
+ const result = JSON.stringify(objOrMaybeString);
1256
+ return result;
1257
+ } catch (error) {
1258
+ }
1259
+ return "";
1260
+ }, "maybeStringifyJSON");
1261
+ var maybeParseJSON = /* @__PURE__ */ __name((objOrMaybeJSON) => {
1262
+ if (!objOrMaybeJSON) return {};
1263
+ if (typeof objOrMaybeJSON === "string") {
1264
+ try {
1265
+ const cleanMarkdown = helpJsonMarkup(objOrMaybeJSON);
1266
+ const result = JSON.parse(cleanMarkdown);
1267
+ if (typeof result === "object" && result !== null) {
1268
+ return result;
1269
+ }
1270
+ } catch (error) {
1271
+ }
1272
+ }
1273
+ if (typeof objOrMaybeJSON === "object" && objOrMaybeJSON !== null) {
1274
+ return objOrMaybeJSON;
1275
+ }
1276
+ return {};
1277
+ }, "maybeParseJSON");
1278
+ function isObjectStringified(maybeObject) {
1279
+ if (typeof maybeObject !== "string") return false;
1280
+ const isMaybeObject = maybeObject.substring(0, 1) === "{" && maybeObject.substring(maybeObject.length - 1, maybeObject.length) === "}";
1281
+ const isMaybeArray = maybeObject.substring(0, 1) === "[" && maybeObject.substring(maybeObject.length - 1, maybeObject.length) === "]";
1282
+ if (!isMaybeObject && !isMaybeArray) {
1283
+ return false;
1284
+ }
1285
+ let canDecode = false;
1286
+ try {
1287
+ JSON.parse(maybeObject);
1288
+ canDecode = true;
1289
+ } catch (error) {
1290
+ canDecode = false;
1291
+ }
1292
+ return canDecode;
1293
+ }
1294
+ __name(isObjectStringified, "isObjectStringified");
1295
+ function helpJsonMarkup(str) {
1296
+ if (typeof str !== "string") {
1297
+ return str;
1298
+ }
1299
+ const input = str.trim();
1300
+ const markdownJsonStartsWith = "```json";
1301
+ const markdownJsonEndsWith = "```";
1302
+ if (input.substring(0, markdownJsonStartsWith.length) === markdownJsonStartsWith && input.substring(input.length - markdownJsonEndsWith.length, input.length) === markdownJsonEndsWith) {
1303
+ return str.substring(markdownJsonStartsWith.length, input.length - markdownJsonEndsWith.length)?.trim();
1304
+ }
1305
+ return str;
1306
+ }
1307
+ __name(helpJsonMarkup, "helpJsonMarkup");
1308
+
1309
+ // src/llm/output/_utils/getResultText.ts
1310
+ function getResultText(content) {
1311
+ if (content.length === 1 && content.every((a) => a.type === "text")) {
1312
+ return content[0]?.text || "";
1313
+ }
1314
+ return "";
1315
+ }
1316
+ __name(getResultText, "getResultText");
1317
+
1318
+ // src/parser/parsers/OpenAiFunctionParser.ts
1319
+ var _OpenAiFunctionParser = class _OpenAiFunctionParser extends BaseParser {
1320
+ constructor(options) {
1321
+ super("openAiFunction", options, "function_call");
1322
+ __publicField(this, "parser");
1323
+ this.parser = options.parser;
1324
+ }
1325
+ parse(text, _options) {
1326
+ const functionUse = text.find((a) => a.type === "function_use");
1327
+ if (functionUse && "name" in functionUse && "input" in functionUse) {
1328
+ return {
1329
+ name: functionUse.name,
1330
+ arguments: maybeParseJSON(functionUse.input)
1331
+ };
1332
+ }
1333
+ return this.parser.parse(getResultText(text));
1334
+ }
1335
+ };
1336
+ __name(_OpenAiFunctionParser, "OpenAiFunctionParser");
1337
+ var OpenAiFunctionParser = _OpenAiFunctionParser;
1338
+
1339
+ // src/parser/parsers/StringParser.ts
1340
+ var _StringParser = class _StringParser extends BaseParser {
1341
+ constructor(options) {
1342
+ super("string", options);
1343
+ }
1344
+ parse(text, _options) {
1345
+ assert(typeof text === "string", `Invalid input. Expected string. Received ${typeof text}.`);
1346
+ const parsed = text.toString();
1347
+ return parsed;
1348
+ }
1349
+ };
1350
+ __name(_StringParser, "StringParser");
1351
+ var StringParser = _StringParser;
1352
+
1353
+ // src/parser/parsers/BooleanParser.ts
1354
+ var _BooleanParser = class _BooleanParser extends BaseParser {
1355
+ constructor(options) {
1356
+ super("boolean", options);
1357
+ }
1358
+ parse(text) {
1359
+ assert(typeof text === "string", `Invalid input. Expected string. Received ${typeof text}.`);
1360
+ const clean = text.toLowerCase().trim();
1361
+ if (clean === "true") {
1362
+ return true;
1363
+ }
1364
+ return false;
1365
+ }
1366
+ };
1367
+ __name(_BooleanParser, "BooleanParser");
1368
+ var BooleanParser = _BooleanParser;
1369
+
1370
+ // src/utils/modules/isFinite.ts
1371
+ function isFinite(value) {
1372
+ return typeof value === "number" && Number.isFinite(value);
1373
+ }
1374
+ __name(isFinite, "isFinite");
1375
+
1376
+ // src/parser/parsers/NumberParser.ts
1377
+ var _NumberParser = class _NumberParser extends BaseParser {
1378
+ constructor(options) {
1379
+ super("number", options);
1380
+ }
1381
+ parse(text) {
1382
+ const match = text.match(/\d/g);
1383
+ return match && isFinite(toNumber(match[0])) ? toNumber(match[0]) : -1;
1384
+ }
1385
+ };
1386
+ __name(_NumberParser, "NumberParser");
1387
+ var NumberParser = _NumberParser;
1388
+
1389
+ // src/parser/_utils.ts
1390
+ import { validate as validateSchema } from "jsonschema";
1391
+ function enforceParserSchema(schema, parsed) {
1392
+ if (!schema || !parsed || typeof parsed !== "object") {
1393
+ return parsed;
1394
+ }
1395
+ return filterObjectOnSchema(schema, parsed);
1396
+ }
1397
+ __name(enforceParserSchema, "enforceParserSchema");
1398
+ function validateParserSchema(schema, parsed) {
1399
+ if (!schema || !parsed || typeof parsed !== "object") {
1400
+ return null;
1401
+ }
1402
+ const validate = validateSchema(parsed, schema);
1403
+ if (validate.errors.length) {
1404
+ return validate.errors;
1405
+ }
1406
+ return null;
1407
+ }
1408
+ __name(validateParserSchema, "validateParserSchema");
1409
+
1410
+ // src/parser/parsers/JsonParser.ts
1411
+ var _JsonParser = class _JsonParser extends BaseParserWithJson {
1412
+ constructor(options = {}) {
1413
+ super("json", options);
1414
+ }
1415
+ parse(text, _attributes) {
1416
+ const parsed = maybeParseJSON(helpJsonMarkup(text));
1417
+ if (this.schema) {
1418
+ const enforce = enforceParserSchema(this.schema, parsed);
1419
+ if (this.validateSchema) {
1420
+ const valid = validateParserSchema(this.schema, enforce);
1421
+ if (valid && valid.length) {
1422
+ throw new Error(valid[0].message);
1423
+ }
1424
+ }
1425
+ return enforce;
1426
+ }
1427
+ return parsed;
1428
+ }
1429
+ };
1430
+ __name(_JsonParser, "JsonParser");
1431
+ var JsonParser = _JsonParser;
1432
+
1433
+ // src/utils/modules/camelCase.ts
1434
+ function camelCase(input) {
1435
+ if (!input) return input;
1436
+ input = input.replace(/[^a-zA-Z0-9_]+/g, " ").trim();
1437
+ const words = input.split(/\s+|_/);
1438
+ return words.map((word, index) => {
1439
+ if (index === 0) {
1440
+ return word.toLowerCase();
1441
+ } else {
1442
+ return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
1443
+ }
1444
+ }).join("");
1445
+ }
1446
+ __name(camelCase, "camelCase");
1447
+
1448
+ // src/parser/parsers/ListToJsonParser.ts
1449
+ var _ListToJsonParser = class _ListToJsonParser extends BaseParserWithJson {
1450
+ constructor(options = {}) {
1451
+ super("listToJson", options);
1452
+ }
1453
+ parse(text) {
1454
+ const lines = text.split("\n");
1455
+ const output = {};
1456
+ lines.forEach((line) => {
1457
+ const [key, value] = line.split(":");
1458
+ if (value) {
1459
+ output[camelCase(key)] = value.trim();
1460
+ }
1461
+ });
1462
+ if (this.schema) {
1463
+ const parsed = enforceParserSchema(this.schema, output);
1464
+ if (this?.validateSchema) {
1465
+ const valid = validateParserSchema(this.schema, parsed);
1466
+ if (valid && valid.length) {
1467
+ throw new Error(valid[0].message);
1468
+ }
1469
+ }
1470
+ return parsed;
1471
+ }
1472
+ return output;
1473
+ }
1474
+ };
1475
+ __name(_ListToJsonParser, "ListToJsonParser");
1476
+ var ListToJsonParser = _ListToJsonParser;
1477
+
1478
+ // src/parser/parsers/ListToKeyValueParser.ts
1479
+ var _ListToKeyValueParser = class _ListToKeyValueParser extends BaseParser {
1480
+ constructor(options) {
1481
+ super("listToKeyValue", options);
1482
+ }
1483
+ parse(text) {
1484
+ const lines = text.split("\n").map((s) => s.replace("- ", "").replace(/\'/g, "'"));
1485
+ let res = [];
1486
+ for (const line of lines) {
1487
+ const [key, value] = line.split(":");
1488
+ if (key && value) {
1489
+ res.push({
1490
+ key: key?.trim(),
1491
+ value: value?.trim()
1492
+ });
1493
+ }
1494
+ }
1495
+ return res;
1496
+ }
1497
+ };
1498
+ __name(_ListToKeyValueParser, "ListToKeyValueParser");
1499
+ var ListToKeyValueParser = _ListToKeyValueParser;
1500
+
1501
+ // src/parser/parsers/CustomParser.ts
1502
+ var _CustomParser = class _CustomParser extends BaseParser {
1503
+ /**
1504
+ * Creates a new CustomParser instance.
1505
+ * @param {string} name The name of the parser.
1506
+ * @param {any} parserFn The custom parsing function.
1507
+ */
1508
+ constructor(name, parserFn) {
1509
+ super(name);
1510
+ /**
1511
+ * Custom parsing function.
1512
+ * @type {any}
1513
+ */
1514
+ __publicField(this, "parserFn");
1515
+ this.parserFn = parserFn;
1516
+ }
1517
+ /**
1518
+ * Parses the text using the custom parsing function.
1519
+ * @param {string} text The text to be parsed.
1520
+ * @param {any} inputValues Additional input values for the parser function.
1521
+ * @returns {O} The parsed value.
1522
+ */
1523
+ parse(text, inputValues) {
1524
+ return this.parserFn.call(this, text, inputValues);
1525
+ }
1526
+ };
1527
+ __name(_CustomParser, "CustomParser");
1528
+ var CustomParser = _CustomParser;
1529
+
1530
+ // src/parser/parsers/ListToArrayParser.ts
1531
+ var _ListToArrayParser = class _ListToArrayParser extends BaseParser {
1532
+ constructor() {
1533
+ super("listToArray");
1534
+ }
1535
+ parse(text) {
1536
+ const lines = text.split("\n").map((s) => s.replace("- ", "").replace(/\'/g, "'"));
1537
+ return lines;
1538
+ }
1539
+ };
1540
+ __name(_ListToArrayParser, "ListToArrayParser");
1541
+ var ListToArrayParser = _ListToArrayParser;
1542
+
1543
+ // src/parser/parsers/ReplaceStringTemplateParser.ts
1544
+ var _ReplaceStringTemplateParser = class _ReplaceStringTemplateParser extends BaseParser {
1545
+ constructor(options) {
1546
+ super("replaceStringTemplate", options);
1547
+ }
1548
+ parse(text, attributes) {
1549
+ return replaceTemplateString(text, attributes);
1550
+ }
1551
+ };
1552
+ __name(_ReplaceStringTemplateParser, "ReplaceStringTemplateParser");
1553
+ var ReplaceStringTemplateParser = _ReplaceStringTemplateParser;
1554
+
1555
+ // src/parser/parsers/MarkdownCodeBlocks.ts
1556
+ var _MarkdownCodeBlocksParser = class _MarkdownCodeBlocksParser extends BaseParser {
1557
+ constructor(options) {
1558
+ super("markdownCodeBlocks", options);
1559
+ }
1560
+ parse(input) {
1561
+ const out = [];
1562
+ const regex = input.matchAll(new RegExp(/`{3}([\w]*)\n([\S\s]+?)\n`{3}/, "g"));
1563
+ for (const iterator of regex) {
1564
+ if (iterator) {
1565
+ const [_input, language, code] = iterator;
1566
+ out.push({
1567
+ language,
1568
+ code
1569
+ });
1570
+ }
1571
+ }
1572
+ return out;
1573
+ }
1574
+ };
1575
+ __name(_MarkdownCodeBlocksParser, "MarkdownCodeBlocksParser");
1576
+ var MarkdownCodeBlocksParser = _MarkdownCodeBlocksParser;
1577
+
1578
+ // src/parser/parsers/MarkdownCodeBlock.ts
1579
+ var _MarkdownCodeBlockParser = class _MarkdownCodeBlockParser extends BaseParser {
1580
+ constructor(options) {
1581
+ super("markdownCodeBlock", options);
1582
+ }
1583
+ parse(input) {
1584
+ const [block] = new MarkdownCodeBlocksParser().parse(input);
1585
+ return block;
1586
+ }
1587
+ };
1588
+ __name(_MarkdownCodeBlockParser, "MarkdownCodeBlockParser");
1589
+ var MarkdownCodeBlockParser = _MarkdownCodeBlockParser;
1590
+
1591
+ // src/parser/parsers/StringExtractParser.ts
1592
+ var _StringExtractParser = class _StringExtractParser extends BaseParser {
1593
+ constructor(options) {
1594
+ super("stringExtract", options);
1595
+ __publicField(this, "enum", []);
1596
+ __publicField(this, "ignoreCase");
1597
+ if (options?.enum) {
1598
+ this.enum.push(...options.enum);
1599
+ }
1600
+ if (options?.ignoreCase) {
1601
+ this.ignoreCase = true;
1602
+ }
1603
+ }
1604
+ parse(text) {
1605
+ assert(typeof text === "string", `Invalid input. Expected string. Received ${typeof text}.`);
1606
+ for (const option of this.enum) {
1607
+ const regex = this.ignoreCase ? new RegExp(option.toLowerCase(), "i") : new RegExp(option);
1608
+ if (regex.test(text)) {
1609
+ return option;
1610
+ }
1611
+ }
1612
+ return "";
1613
+ }
1614
+ };
1615
+ __name(_StringExtractParser, "StringExtractParser");
1616
+ var StringExtractParser = _StringExtractParser;
1617
+
1618
+ // src/parser/_functions.ts
1619
+ function createParser(type, options = {}) {
1620
+ switch (type) {
1621
+ case "json":
1622
+ return new JsonParser(options);
1623
+ case "markdownCodeBlocks":
1624
+ return new MarkdownCodeBlocksParser();
1625
+ case "markdownCodeBlock":
1626
+ return new MarkdownCodeBlockParser();
1627
+ case "listToArray":
1628
+ return new ListToArrayParser();
1629
+ case "listToJson":
1630
+ return new ListToJsonParser(options);
1631
+ case "listToKeyValue":
1632
+ return new ListToKeyValueParser();
1633
+ case "replaceStringTemplate":
1634
+ return new ReplaceStringTemplateParser();
1635
+ case "boolean":
1636
+ return new BooleanParser();
1637
+ case "number":
1638
+ return new NumberParser();
1639
+ case "stringExtract":
1640
+ return new StringExtractParser(options);
1641
+ case "string":
1642
+ default:
1643
+ return new StringParser();
1644
+ }
1645
+ }
1646
+ __name(createParser, "createParser");
1647
+ function createCustomParser(name, parserFn) {
1648
+ return new CustomParser(name, parserFn);
1649
+ }
1650
+ __name(createCustomParser, "createCustomParser");
1651
+
1652
+ // src/executor/llm.ts
1653
+ var _LlmExecutor = class _LlmExecutor extends BaseExecutor {
1654
+ constructor(llmConfiguration, options) {
1655
+ super(llmConfiguration.name || "anonymous-llm-executor", "llm-executor", options);
1656
+ __publicField(this, "llm");
1657
+ __publicField(this, "prompt");
1658
+ __publicField(this, "promptFn");
1659
+ __publicField(this, "parser");
1660
+ this.llm = llmConfiguration.llm;
1661
+ this.parser = llmConfiguration?.parser || new StringParser();
1662
+ if (typeof llmConfiguration.prompt === "function") {
1663
+ this.prompt = void 0;
1664
+ this.promptFn = llmConfiguration.prompt;
1665
+ } else {
1666
+ this.prompt = llmConfiguration.prompt;
1667
+ this.promptFn = null;
1668
+ }
1669
+ }
1670
+ async execute(_input, _options) {
1671
+ if (this?.parser instanceof JsonParser && this.parser.schema) {
1672
+ _options = Object.assign(_options || {}, {
1673
+ jsonSchema: this.parser.schema
1674
+ });
1675
+ }
1676
+ return super.execute(_input, _options);
1677
+ }
1678
+ async handler(_input, ..._args) {
1679
+ const call = await this.llm.call(_input, ..._args);
1680
+ return call;
1681
+ }
1682
+ async getHandlerInput(_input) {
1683
+ if (this.prompt) {
1684
+ if (isPromise(this.prompt.formatAsync)) {
1685
+ return await this.prompt.formatAsync(_input);
1686
+ } else {
1687
+ return this.prompt.format(_input);
1688
+ }
1689
+ }
1690
+ if (this.promptFn) {
1691
+ const prompt = this.promptFn(_input);
1692
+ const promptFormatted = prompt.format(_input);
1693
+ return promptFormatted;
1694
+ }
1695
+ throw new Error("Missing prompt");
1696
+ }
1697
+ getHandlerOutput(out, _metadata) {
1698
+ if (this.parser.target === "function_call") {
1699
+ const outToStr = out.getResultContent();
1700
+ return this.parser.parse(outToStr, _metadata);
1701
+ } else {
1702
+ const outToStr = out.getResultText();
1703
+ return this.parser.parse(outToStr, _metadata);
1704
+ }
1705
+ }
1706
+ metadata() {
1707
+ return {
1708
+ llm: this.llm.getMetadata()
1709
+ };
1710
+ }
1711
+ getTraceId() {
1712
+ if (this.traceId) {
1713
+ return this.traceId;
1714
+ }
1715
+ return this.llm.getTraceId();
1716
+ }
1717
+ };
1718
+ __name(_LlmExecutor, "LlmExecutor");
1719
+ var LlmExecutor = _LlmExecutor;
1720
+
1721
+ // src/executor/_functions.ts
1722
+ function createCoreExecutor(handler, options) {
1723
+ return new CoreExecutor({
1724
+ handler
1725
+ }, options);
1726
+ }
1727
+ __name(createCoreExecutor, "createCoreExecutor");
1728
+ function createLlmExecutor(llmConfiguration, options) {
1729
+ return new LlmExecutor(llmConfiguration, options);
1730
+ }
1731
+ __name(createLlmExecutor, "createLlmExecutor");
1732
+
1733
+ // src/executor/llm-openai-function.ts
1734
+ var _LlmExecutorOpenAiFunctions = class _LlmExecutorOpenAiFunctions extends LlmExecutor {
1735
+ constructor(llmConfiguration, options) {
1736
+ super(Object.assign({}, llmConfiguration, {
1737
+ parser: new OpenAiFunctionParser({
1738
+ parser: llmConfiguration.parser || new StringParser()
1739
+ })
1740
+ }), options);
1741
+ }
1742
+ async execute(_input, _options) {
1743
+ return super.execute(_input, _options);
1744
+ }
1745
+ };
1746
+ __name(_LlmExecutorOpenAiFunctions, "LlmExecutorOpenAiFunctions");
1747
+ var LlmExecutorOpenAiFunctions = _LlmExecutorOpenAiFunctions;
1748
+
1749
+ // src/utils/modules/enforceResultAttributes.ts
1750
+ function enforceResultAttributes(input) {
1751
+ if (!input) {
1752
+ return {
1753
+ result: input,
1754
+ attributes: {}
1755
+ };
1756
+ }
1757
+ 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))) {
1758
+ return input;
1759
+ }
1760
+ return {
1761
+ result: input,
1762
+ attributes: {}
1763
+ };
1764
+ }
1765
+ __name(enforceResultAttributes, "enforceResultAttributes");
1766
+
1767
+ // src/plugins/callable/callable.ts
1768
+ var _CallableExecutor = class _CallableExecutor {
1769
+ constructor(options) {
1770
+ __publicField(this, "name");
1771
+ __publicField(this, "key");
1772
+ __publicField(this, "description");
1773
+ __publicField(this, "input");
1774
+ __publicField(this, "attributes");
1775
+ __publicField(this, "parameters");
1776
+ __publicField(this, "_handler");
1777
+ const defaults = {
1778
+ key: options.name
1779
+ };
1780
+ this.name = options.name;
1781
+ this.key = options?.key || defaults.key;
1782
+ this.description = options.description;
1783
+ this.input = options.input;
1784
+ this.parameters = options.parameters || {};
1785
+ this.attributes = options?.attributes || {};
1786
+ this._validateInput = options.validateInput;
1787
+ this._visibilityHandler = options?.visibilityHandler;
1788
+ if (options.handler instanceof BaseExecutor) {
1789
+ this._handler = options.handler;
1790
+ } else if (typeof options.handler === "function") {
1791
+ this._handler = createCoreExecutor(options.handler);
1792
+ } else {
1793
+ throw new Error("Invalid handler");
1794
+ }
1795
+ }
1796
+ async execute(input) {
1797
+ const response = await this._handler.execute(ensureInputIsObject(input));
1798
+ return enforceResultAttributes(response);
1799
+ }
1800
+ async validateInput(input) {
1801
+ try {
1802
+ if (typeof this._validateInput === "function") {
1803
+ const response = await this._validateInput(ensureInputIsObject(input), this._handler.getMetadata());
1804
+ return enforceResultAttributes(response);
1805
+ }
1806
+ return {
1807
+ result: true,
1808
+ attributes: {}
1809
+ };
1810
+ } catch (error) {
1811
+ return {
1812
+ result: false,
1813
+ attributes: {
1814
+ error: error.message
1815
+ }
1816
+ };
1817
+ }
1818
+ }
1819
+ visibilityHandler(input, attributes) {
1820
+ if (typeof this._visibilityHandler === "function") {
1821
+ return this._visibilityHandler(input, this._handler.getMetadata(), attributes);
1822
+ }
1823
+ return true;
1824
+ }
1825
+ };
1826
+ __name(_CallableExecutor, "CallableExecutor");
1827
+ var CallableExecutor = _CallableExecutor;
1828
+ var _UseExecutorsBase = class _UseExecutorsBase {
1829
+ constructor(handlers) {
1830
+ __publicField(this, "handlers", []);
1831
+ this.handlers = handlers;
1832
+ }
1833
+ hasFunction(name) {
1834
+ return !!this.getFunction(name);
1835
+ }
1836
+ getFunction(name) {
1837
+ return this.handlers.find((a) => a.name === name);
1838
+ }
1839
+ getFunctions() {
1840
+ return [
1841
+ ...this.handlers
1842
+ ];
1843
+ }
1844
+ getVisibleFunctions(_input, _attributes = {}) {
1845
+ const handlers = this.getFunctions();
1846
+ return handlers.filter((a) => typeof a.visibilityHandler === "undefined" || typeof a.visibilityHandler === "function" && a.visibilityHandler(_input, _attributes));
1847
+ }
1848
+ async callFunction(name, input) {
1849
+ try {
1850
+ const handler = this.getFunction(name);
1851
+ assert(handler, `[invalid handler] The handler (${name}) does not exist.`);
1852
+ const result = await handler.execute(ensureInputIsObject(input));
1853
+ return result;
1854
+ } catch (error) {
1855
+ return error.message;
1856
+ }
1857
+ }
1858
+ async validateFunctionInput(name, input) {
1859
+ try {
1860
+ const handler = this.getFunction(name);
1861
+ assert(handler, `[invalid handler] The handler (${name}) does not exist.`);
1862
+ const result = await handler.validateInput(ensureInputIsObject(input));
1863
+ return result;
1864
+ } catch (error) {
1865
+ return {
1866
+ result: false,
1867
+ attributes: {
1868
+ error: error.message
1869
+ }
1870
+ };
1871
+ }
1872
+ }
1873
+ };
1874
+ __name(_UseExecutorsBase, "UseExecutorsBase");
1875
+ var UseExecutorsBase = _UseExecutorsBase;
1876
+
1877
+ // src/plugins/callable/index.ts
1878
+ function createCallableExecutor(options) {
1879
+ return new CallableExecutor(options);
1880
+ }
1881
+ __name(createCallableExecutor, "createCallableExecutor");
1882
+ var _UseExecutors = class _UseExecutors extends UseExecutorsBase {
1883
+ constructor(handlers) {
1884
+ super(handlers);
1885
+ }
1886
+ };
1887
+ __name(_UseExecutors, "UseExecutors");
1888
+ var UseExecutors = _UseExecutors;
1889
+ function useExecutors(executors) {
1890
+ return new UseExecutors(executors.map((e) => {
1891
+ if (e instanceof CallableExecutor) return e;
1892
+ return createCallableExecutor(e);
1893
+ }));
1894
+ }
1895
+ __name(useExecutors, "useExecutors");
1896
+
1897
+ // src/utils/modules/deepClone.ts
1898
+ function deepClone(obj) {
1899
+ if (obj === null || obj === void 0) return obj;
1900
+ if (obj instanceof Date) {
1901
+ return new Date(obj.getTime());
1902
+ }
1903
+ if (Array.isArray(obj)) {
1904
+ return obj.map((item) => deepClone(item));
1905
+ }
1906
+ if (typeof obj === "object" && obj !== null) {
1907
+ const cloneObj = {};
1908
+ for (const key in obj) {
1909
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
1910
+ cloneObj[key] = deepClone(obj[key]);
1911
+ }
1912
+ }
1913
+ return cloneObj;
1914
+ }
1915
+ return obj;
1916
+ }
1917
+ __name(deepClone, "deepClone");
1918
+
1919
+ // src/llm/_utils.withDefaultModel.ts
1920
+ function withDefaultModel(obj1, model) {
1921
+ const copy = deepClone(obj1);
1922
+ if (copy.options.model) {
1923
+ copy.options.model.default = model;
1924
+ } else {
1925
+ copy.options.model = {
1926
+ default: model
1927
+ };
1928
+ }
1929
+ if (copy.mapBody.model) {
1930
+ copy.mapBody.model.default = model;
1931
+ } else {
1932
+ copy.mapBody.model = {
1933
+ key: "model",
1934
+ default: model
1935
+ };
1936
+ }
1937
+ return copy;
1938
+ }
1939
+ __name(withDefaultModel, "withDefaultModel");
1940
+
1941
+ // src/llm/config/openai/index.ts
1942
+ var openAiChatV1 = {
1943
+ key: "openai.chat.v1",
1944
+ provider: "openai.chat",
1945
+ endpoint: `https://api.openai.com/v1/chat/completions`,
1946
+ options: {
1947
+ prompt: {},
1948
+ topP: {},
1949
+ useJson: {},
1950
+ openAiApiKey: {
1951
+ default: getEnvironmentVariable("OPENAI_API_KEY")
1952
+ }
1953
+ },
1954
+ method: "POST",
1955
+ headers: `{"Authorization":"Bearer {{openAiApiKey}}", "Content-Type": "application/json" }`,
1956
+ mapBody: {
1957
+ prompt: {
1958
+ key: "messages",
1959
+ sanitize: /* @__PURE__ */ __name((v) => {
1960
+ if (typeof v === "string") {
1961
+ return [
1962
+ {
1963
+ role: "user",
1964
+ content: v
1965
+ }
1966
+ ];
1967
+ }
1968
+ return v;
1969
+ }, "sanitize")
1970
+ },
1971
+ model: {
1972
+ key: "model"
1973
+ },
1974
+ topP: {
1975
+ key: "top_p"
1976
+ },
1977
+ useJson: {
1978
+ key: "response_format.type",
1979
+ sanitize: /* @__PURE__ */ __name((v) => v ? "json_object" : "text", "sanitize")
1980
+ }
1981
+ }
1982
+ };
1983
+ var openAiChatMockV1 = {
1984
+ key: "openai.chat-mock.v1",
1985
+ provider: "openai.chat-mock",
1986
+ endpoint: `http://localhost`,
1987
+ options: {
1988
+ prompt: {},
1989
+ topP: {},
1990
+ useJson: {},
1991
+ openAiApiKey: {
1992
+ default: getEnvironmentVariable("OPENAI_API_KEY_MOCK")
1993
+ }
1994
+ },
1995
+ method: "POST",
1996
+ headers: `{"Authorization":"Bearer {{openAiApiKey}}", "Content-Type": "application/json" }`,
1997
+ mapBody: {
1998
+ prompt: {
1999
+ key: "messages"
2000
+ },
2001
+ model: {
2002
+ key: "model"
2003
+ },
2004
+ topP: {
2005
+ key: "top_p"
2006
+ },
2007
+ useJson: {
2008
+ key: "response_format.type",
2009
+ sanitize: /* @__PURE__ */ __name((v) => v ? "json_object" : "text", "sanitize")
2010
+ }
2011
+ }
2012
+ };
2013
+ var openai = {
2014
+ "openai.chat.v1": openAiChatV1,
2015
+ "openai.chat-mock.v1": openAiChatMockV1,
2016
+ "openai.gpt-4o": withDefaultModel(openAiChatV1, "gpt-4o"),
2017
+ "openai.gpt-4o-mini": withDefaultModel(openAiChatV1, "gpt-4o-mini")
2018
+ };
2019
+
2020
+ // src/llm/config/anthropic/index.ts
2021
+ var ANTORPIC_VERSION = "2023-06-01";
2022
+ function anthropicPromptSanitize(_messages, _inputBodyObj, _outputObj) {
2023
+ if (typeof _messages === "string") {
2024
+ return [
2025
+ {
2026
+ role: "user",
2027
+ content: _messages
2028
+ }
2029
+ ];
2030
+ }
2031
+ const [first, ...messages] = [
2032
+ ..._messages.map((a) => ({
2033
+ ...a
2034
+ }))
2035
+ ];
2036
+ if (first.role === "system") {
2037
+ _outputObj.system = first.content;
2038
+ return messages;
2039
+ }
2040
+ return [
2041
+ first,
2042
+ ...messages
2043
+ ];
2044
+ }
2045
+ __name(anthropicPromptSanitize, "anthropicPromptSanitize");
2046
+ var anthropicChatV1 = {
2047
+ key: "anthropic.chat.v1",
2048
+ provider: "anthropic.chat",
2049
+ endpoint: `https://api.anthropic.com/v1/messages`,
2050
+ headers: `{"x-api-key":"{{anthropicApiKey}}", "Content-Type": "application/json", "anthropic-version": "${ANTORPIC_VERSION}" }`,
2051
+ method: "POST",
2052
+ options: {
2053
+ prompt: {},
2054
+ system: {},
2055
+ maxTokens: {
2056
+ required: [
2057
+ true,
2058
+ "maxTokens required"
2059
+ ]
2060
+ },
2061
+ anthropicApiKey: {
2062
+ default: getEnvironmentVariable("ANTHROPIC_API_KEY")
2063
+ }
2064
+ },
2065
+ mapBody: {
2066
+ model: {
2067
+ key: "model"
2068
+ },
2069
+ maxTokens: {
2070
+ key: "max_tokens"
2071
+ },
2072
+ system: {
2073
+ key: "system"
2074
+ },
2075
+ prompt: {
2076
+ key: "messages",
2077
+ sanitize: anthropicPromptSanitize
2078
+ }
2079
+ }
2080
+ };
2081
+ var anthropic = {
2082
+ "anthropic.chat.v1": anthropicChatV1,
2083
+ "anthropic.claude-3-5-sonnet": withDefaultModel(anthropicChatV1, "claude-3-5-sonnet-20240620"),
2084
+ "anthropic.claude-3-opus": withDefaultModel(anthropicChatV1, "claude-3-opus-20240229"),
2085
+ "anthropic.claude-3-sonnet": withDefaultModel(anthropicChatV1, "claude-3-sonnet-20240229"),
2086
+ "anthropic.claude-3-haiku": withDefaultModel(anthropicChatV1, "claude-3-haiku-20240307")
2087
+ };
2088
+
2089
+ // src/llm/config/bedrock/index.ts
2090
+ var ANTORPIC_BEDROCK_VERSION = "bedrock-2023-05-31";
2091
+ var amazonAnthropicChatV1 = {
2092
+ key: "amazon:anthropic.chat.v1",
2093
+ provider: "amazon:anthropic.chat",
2094
+ method: "POST",
2095
+ headers: `{"Content-Type": "application/json" }`,
2096
+ endpoint: `https://bedrock-runtime.{{awsRegion}}.amazonaws.com/model/{{model}}/invoke`,
2097
+ options: {
2098
+ prompt: {},
2099
+ topP: {},
2100
+ maxTokens: {},
2101
+ awsRegion: {
2102
+ default: getEnvironmentVariable("AWS_REGION"),
2103
+ required: [
2104
+ true,
2105
+ "aws region is required"
2106
+ ]
2107
+ },
2108
+ awsSecretKey: {},
2109
+ awsAccessKey: {}
2110
+ },
2111
+ mapBody: {
2112
+ prompt: {
2113
+ key: "messages",
2114
+ sanitize: anthropicPromptSanitize
2115
+ },
2116
+ topP: {
2117
+ key: "top_p"
2118
+ },
2119
+ maxTokens: {
2120
+ key: "max_tokens",
2121
+ default: 1e4
2122
+ },
2123
+ anthropic_version: {
2124
+ key: "anthropic_version",
2125
+ default: ANTORPIC_BEDROCK_VERSION
2126
+ }
2127
+ }
2128
+ };
2129
+ var amazonMetaChatV1 = {
2130
+ key: "amazon:meta.chat.v1",
2131
+ provider: "amazon:meta.chat",
2132
+ method: "POST",
2133
+ headers: `{"Content-Type": "application/json" }`,
2134
+ options: {
2135
+ prompt: {},
2136
+ topP: {},
2137
+ maxTokens: {},
2138
+ temperature: {},
2139
+ awsRegion: {
2140
+ default: getEnvironmentVariable("AWS_REGION")
2141
+ },
2142
+ awsSecretKey: {},
2143
+ awsAccessKey: {}
2144
+ },
2145
+ endpoint: `https://bedrock-runtime.{{awsRegion}}.amazonaws.com/model/{{model}}/invoke`,
2146
+ mapBody: {
2147
+ prompt: {
2148
+ key: "prompt",
2149
+ sanitize: /* @__PURE__ */ __name((messages) => {
2150
+ if (typeof messages === "string") {
2151
+ return messages;
2152
+ } else {
2153
+ return replaceTemplateString(`{{>DialogueHistory key='messages'}}`, {
2154
+ messages
2155
+ });
2156
+ }
2157
+ }, "sanitize")
2158
+ },
2159
+ topP: {
2160
+ key: "top_p"
2161
+ },
2162
+ temperature: {
2163
+ key: "temperature"
2164
+ },
2165
+ maxTokens: {
2166
+ key: "max_gen_len",
2167
+ default: 2048
2168
+ }
2169
+ }
2170
+ };
2171
+ var bedrock = {
2172
+ "amazon:anthropic.chat.v1": amazonAnthropicChatV1,
2173
+ "amazon:meta.chat.v1": amazonMetaChatV1
2174
+ };
2175
+
2176
+ // src/llm/config.ts
2177
+ var configs = {
2178
+ ...openai,
2179
+ ...anthropic,
2180
+ ...bedrock
2181
+ };
2182
+ function getLlmConfig(provider) {
2183
+ const pick2 = configs[provider];
2184
+ if (pick2) {
2185
+ return pick2;
2186
+ }
2187
+ throw new Error("Invalid provider");
2188
+ }
2189
+ __name(getLlmConfig, "getLlmConfig");
2190
+
2191
+ // src/llm/output/_utils/getResultContent.ts
2192
+ function getResultContent(result, index) {
2193
+ if (index && index > 0) {
2194
+ const arr = result?.options || [];
2195
+ const val = arr[index];
2196
+ return val ? val : [];
2197
+ }
2198
+ return [
2199
+ ...result.content
2200
+ ];
2201
+ }
2202
+ __name(getResultContent, "getResultContent");
2203
+
2204
+ // src/llm/output/base.ts
2205
+ function BaseLlmOutput2(result) {
2206
+ const __result = Object.freeze({
2207
+ id: result.id || uuidv4(),
2208
+ name: result.name,
2209
+ usage: result.usage,
2210
+ stopReason: result.stopReason,
2211
+ options: [
2212
+ ...result?.options || []
2213
+ ],
2214
+ content: [
2215
+ ...result.content
2216
+ ],
2217
+ created: result?.created || (/* @__PURE__ */ new Date()).getTime()
2218
+ });
2219
+ function getResult() {
2220
+ return {
2221
+ id: __result.id,
2222
+ name: __result.name,
2223
+ created: __result.created,
2224
+ usage: __result.usage,
2225
+ options: __result.options,
2226
+ content: __result.content,
2227
+ stopReason: __result.stopReason
2228
+ };
2229
+ }
2230
+ __name(getResult, "getResult");
2231
+ return {
2232
+ getResultContent: /* @__PURE__ */ __name((index) => getResultContent(__result, index), "getResultContent"),
2233
+ getResultText: /* @__PURE__ */ __name(() => getResultText(__result.content), "getResultText"),
2234
+ getResult
2235
+ };
2236
+ }
2237
+ __name(BaseLlmOutput2, "BaseLlmOutput2");
2238
+
2239
+ // src/llm/output/_util.ts
2240
+ function normalizeFunctionCall(input, provider) {
2241
+ if (input === "any") {
2242
+ if (provider === "openai") {
2243
+ return "required";
2244
+ }
2245
+ }
2246
+ return input;
2247
+ }
2248
+ __name(normalizeFunctionCall, "normalizeFunctionCall");
2249
+ function formatOptions(response, handler) {
2250
+ const out = [];
2251
+ for (const item of response) {
2252
+ const result = handler(item);
2253
+ if (result) {
2254
+ out.push([
2255
+ result
2256
+ ]);
2257
+ }
2258
+ }
2259
+ return out;
2260
+ }
2261
+ __name(formatOptions, "formatOptions");
2262
+ function formatContent(response, handler) {
2263
+ const out = [];
2264
+ const result = handler(response);
2265
+ if (result) {
2266
+ out.push(result);
2267
+ }
2268
+ return out;
2269
+ }
2270
+ __name(formatContent, "formatContent");
2271
+
2272
+ // src/llm/output/openai.ts
2273
+ function formatResult(result) {
2274
+ if (typeof result?.message?.content === "string") {
2275
+ return {
2276
+ type: "text",
2277
+ text: result.message.content
2278
+ };
2279
+ } else if (result?.message && "tool_calls" in result.message) {
2280
+ const tool_calls = result.message.tool_calls;
2281
+ for (const call of tool_calls) {
2282
+ return {
2283
+ type: "function_use",
2284
+ name: call.function.name,
2285
+ input: JSON.parse(call.function.arguments)
2286
+ };
2287
+ }
2288
+ }
2289
+ return {
2290
+ type: "text",
2291
+ text: ""
2292
+ };
2293
+ }
2294
+ __name(formatResult, "formatResult");
2295
+ function OutputOpenAIChat(result, _config) {
2296
+ const id = result.id;
2297
+ const name = result.model || _config?.model || "openai.unknown";
2298
+ const created = result.created;
2299
+ const [_content, ..._options] = result?.choices || [];
2300
+ const stopReason = _content?.finish_reason;
2301
+ const content = formatContent(_content, formatResult);
2302
+ const options = formatOptions(_options, formatResult);
2303
+ const usage = {
2304
+ output_tokens: result?.usage?.completion_tokens,
2305
+ input_tokens: result?.usage?.prompt_tokens,
2306
+ total_tokens: result?.usage?.total_tokens
2307
+ };
2308
+ return BaseLlmOutput2({
2309
+ id,
2310
+ name,
2311
+ created,
2312
+ usage,
2313
+ stopReason,
2314
+ content,
2315
+ options
2316
+ });
2317
+ }
2318
+ __name(OutputOpenAIChat, "OutputOpenAIChat");
2319
+
2320
+ // src/llm/output/claude.ts
2321
+ function formatResult2(response) {
2322
+ const content = response?.content || [];
2323
+ const out = [];
2324
+ for (let i = 0; i < content.length; i++) {
2325
+ const result = content[i];
2326
+ if (result.type === "text") {
2327
+ out.push({
2328
+ type: "text",
2329
+ text: result.text
2330
+ });
2331
+ } else if (result.type === "tool_use") {
2332
+ out.push({
2333
+ type: "function_use",
2334
+ name: result.name,
2335
+ input: result.input
2336
+ });
2337
+ }
2338
+ }
2339
+ return out;
2340
+ }
2341
+ __name(formatResult2, "formatResult");
2342
+ function OutputAnthropicClaude3Chat(result, _config) {
2343
+ const id = result.id;
2344
+ const name = result.model || _config?.model || "anthropic.unknown";
2345
+ const stopReason = result.stop_reason;
2346
+ const content = formatResult2(result);
2347
+ const usage = {
2348
+ input_tokens: result?.usage?.input_tokens,
2349
+ output_tokens: result?.usage?.output_tokens,
2350
+ total_tokens: result?.usage?.input_tokens + result?.usage?.input_tokens
2351
+ };
2352
+ return BaseLlmOutput2({
2353
+ id,
2354
+ name,
2355
+ usage,
2356
+ stopReason,
2357
+ content
2358
+ });
2359
+ }
2360
+ __name(OutputAnthropicClaude3Chat, "OutputAnthropicClaude3Chat");
2361
+
2362
+ // src/llm/output/llama.ts
2363
+ function OutputMetaLlama3Chat(result, _config) {
2364
+ const name = _config?.model || "meta";
2365
+ const stopReason = result.stop_reason;
2366
+ const content = [
2367
+ {
2368
+ type: "text",
2369
+ text: result.generation
2370
+ }
2371
+ ];
2372
+ const usage = {
2373
+ output_tokens: result?.generation_token_count,
2374
+ input_tokens: result?.prompt_token_count,
2375
+ total_tokens: result?.generation_token_count + result?.prompt_token_count
2376
+ };
2377
+ return BaseLlmOutput2({
2378
+ name,
2379
+ usage,
2380
+ stopReason,
2381
+ content
2382
+ });
2383
+ }
2384
+ __name(OutputMetaLlama3Chat, "OutputMetaLlama3Chat");
2385
+
2386
+ // src/llm/output/default.ts
2387
+ function OutputDefault(result, _config) {
2388
+ const name = _config.model || "unknown";
2389
+ const stopReason = result?.stopReason || "stop";
2390
+ const content = [];
2391
+ if (result?.text) {
2392
+ content.push({
2393
+ type: "text",
2394
+ text: result.text
2395
+ });
2396
+ }
2397
+ const usage = {
2398
+ output_tokens: result?.output_tokens || 0,
2399
+ input_tokens: result?.input_tokens || 0,
2400
+ total_tokens: (result?.input_tokens || 0) + (result?.output_tokens || 0)
2401
+ };
2402
+ return BaseLlmOutput2({
2403
+ name,
2404
+ usage,
2405
+ stopReason,
2406
+ content
2407
+ });
2408
+ }
2409
+ __name(OutputDefault, "OutputDefault");
2410
+
2411
+ // src/llm/output/index.ts
2412
+ function getOutputParser(config, response) {
2413
+ switch (config?.key) {
2414
+ case "openai.chat.v1":
2415
+ case "openai.chat-mock.v1":
2416
+ return OutputOpenAIChat(response, config);
2417
+ case "anthropic.chat.v1":
2418
+ case "amazon:anthropic.chat.v1":
2419
+ return OutputAnthropicClaude3Chat(response, config);
2420
+ case "amazon:meta.chat.v1":
2421
+ return OutputMetaLlama3Chat(response, config);
2422
+ default: {
2423
+ if (config?.key?.startsWith("custom:")) {
2424
+ return OutputDefault(response, config);
2425
+ }
2426
+ throw new Error("Unsupported provider");
2427
+ }
2428
+ }
2429
+ }
2430
+ __name(getOutputParser, "getOutputParser");
2431
+
2432
+ // src/utils/modules/request.ts
2433
+ async function apiRequest(url, options) {
2434
+ const finalOptions = {
2435
+ ...options
2436
+ };
2437
+ try {
2438
+ const response = await fetch(url, finalOptions);
2439
+ if (!response.ok) {
2440
+ throw new Error(`HTTP error! Status: ${response.status}. Error`);
2441
+ }
2442
+ const responseData = await response.json();
2443
+ return responseData;
2444
+ } catch (error) {
2445
+ const message = error instanceof Error ? error.message : "Error";
2446
+ throw new Error(`Request to ${url} failed: ${message}`);
2447
+ }
2448
+ }
2449
+ __name(apiRequest, "apiRequest");
2450
+
2451
+ // src/utils/modules/replaceTemplateStringSimple.ts
2452
+ function replaceTemplateStringSimple(template, context) {
2453
+ return template.replace(/{{\s*([\w.]+)\s*}}/g, (_match, key) => {
2454
+ const keys = key.split(".");
2455
+ let value = context;
2456
+ for (const k of keys) {
2457
+ if (value && typeof value === "object" && k in value) {
2458
+ value = value[k];
2459
+ } else {
2460
+ return "";
2461
+ }
2462
+ }
2463
+ return typeof value === "string" ? value : String(value);
2464
+ });
2465
+ }
2466
+ __name(replaceTemplateStringSimple, "replaceTemplateStringSimple");
2467
+
2468
+ // src/utils/modules/convertDotNotation.ts
2469
+ function convertDotNotation(obj) {
2470
+ const result = {};
2471
+ for (const key in obj) {
2472
+ if (obj.hasOwnProperty(key)) {
2473
+ if (key.includes(".")) {
2474
+ const keys = key.split(".");
2475
+ let currentLevel = result;
2476
+ for (let i = 0; i < keys.length; i++) {
2477
+ if (i === keys.length - 1) {
2478
+ currentLevel[keys[i]] = obj[key];
2479
+ } else {
2480
+ currentLevel[keys[i]] = currentLevel[keys[i]] || {};
2481
+ currentLevel = currentLevel[keys[i]];
2482
+ }
2483
+ }
2484
+ } else {
2485
+ result[key] = obj[key];
2486
+ }
2487
+ }
2488
+ }
2489
+ return result;
2490
+ }
2491
+ __name(convertDotNotation, "convertDotNotation");
2492
+
2493
+ // src/llm/_utils.mapBody.ts
2494
+ function mapBody(template, body) {
2495
+ const output = {};
2496
+ const keys = Object.keys(template);
2497
+ for (let i = 0; i < keys.length; i++) {
2498
+ const genericInputKey = keys[i];
2499
+ const providerSpecificSettings = template[genericInputKey];
2500
+ const { key: providerSpecificKey, default: defaultValue } = providerSpecificSettings;
2501
+ if (providerSpecificKey) {
2502
+ let valueForThisKey = body[genericInputKey];
2503
+ if (providerSpecificSettings.sanitize && typeof providerSpecificSettings.sanitize === "function") {
2504
+ valueForThisKey = providerSpecificSettings.sanitize(valueForThisKey, Object.freeze({
2505
+ ...body
2506
+ }), output);
2507
+ }
2508
+ if (typeof valueForThisKey !== "undefined") {
2509
+ output[providerSpecificKey] = valueForThisKey;
2510
+ } else if (typeof valueForThisKey === "undefined" && typeof defaultValue !== "undefined") {
2511
+ output[providerSpecificKey] = defaultValue;
2512
+ }
2513
+ }
2514
+ }
2515
+ return convertDotNotation(output);
2516
+ }
2517
+ __name(mapBody, "mapBody");
2518
+
2519
+ // src/utils/modules/getAwsAuthorizationHeaders.ts
2520
+ import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
2521
+ import { SignatureV4 } from "@smithy/signature-v4";
2522
+
2523
+ // node_modules/@smithy/types/dist-es/auth/auth.js
2524
+ var HttpAuthLocation;
2525
+ (function(HttpAuthLocation2) {
2526
+ HttpAuthLocation2["HEADER"] = "header";
2527
+ HttpAuthLocation2["QUERY"] = "query";
2528
+ })(HttpAuthLocation || (HttpAuthLocation = {}));
2529
+
2530
+ // node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js
2531
+ var HttpApiKeyAuthLocation;
2532
+ (function(HttpApiKeyAuthLocation2) {
2533
+ HttpApiKeyAuthLocation2["HEADER"] = "header";
2534
+ HttpApiKeyAuthLocation2["QUERY"] = "query";
2535
+ })(HttpApiKeyAuthLocation || (HttpApiKeyAuthLocation = {}));
2536
+
2537
+ // node_modules/@smithy/types/dist-es/endpoint.js
2538
+ var EndpointURLScheme;
2539
+ (function(EndpointURLScheme2) {
2540
+ EndpointURLScheme2["HTTP"] = "http";
2541
+ EndpointURLScheme2["HTTPS"] = "https";
2542
+ })(EndpointURLScheme || (EndpointURLScheme = {}));
2543
+
2544
+ // node_modules/@smithy/types/dist-es/extensions/checksum.js
2545
+ var AlgorithmId;
2546
+ (function(AlgorithmId2) {
2547
+ AlgorithmId2["MD5"] = "md5";
2548
+ AlgorithmId2["CRC32"] = "crc32";
2549
+ AlgorithmId2["CRC32C"] = "crc32c";
2550
+ AlgorithmId2["SHA1"] = "sha1";
2551
+ AlgorithmId2["SHA256"] = "sha256";
2552
+ })(AlgorithmId || (AlgorithmId = {}));
2553
+
2554
+ // node_modules/@smithy/types/dist-es/http.js
2555
+ var FieldPosition;
2556
+ (function(FieldPosition2) {
2557
+ FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
2558
+ FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
2559
+ })(FieldPosition || (FieldPosition = {}));
2560
+
2561
+ // node_modules/@smithy/types/dist-es/profile.js
2562
+ var IniSectionType;
2563
+ (function(IniSectionType2) {
2564
+ IniSectionType2["PROFILE"] = "profile";
2565
+ IniSectionType2["SSO_SESSION"] = "sso-session";
2566
+ IniSectionType2["SERVICES"] = "services";
2567
+ })(IniSectionType || (IniSectionType = {}));
2568
+
2569
+ // node_modules/@smithy/types/dist-es/transfer.js
2570
+ var RequestHandlerProtocol;
2571
+ (function(RequestHandlerProtocol2) {
2572
+ RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
2573
+ RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
2574
+ RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
2575
+ })(RequestHandlerProtocol || (RequestHandlerProtocol = {}));
2576
+
2577
+ // node_modules/@smithy/protocol-http/dist-es/httpRequest.js
2578
+ var _HttpRequest = class _HttpRequest {
2579
+ constructor(options) {
2580
+ this.method = options.method || "GET";
2581
+ this.hostname = options.hostname || "localhost";
2582
+ this.port = options.port;
2583
+ this.query = options.query || {};
2584
+ this.headers = options.headers || {};
2585
+ this.body = options.body;
2586
+ this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:";
2587
+ this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/";
2588
+ this.username = options.username;
2589
+ this.password = options.password;
2590
+ this.fragment = options.fragment;
2591
+ }
2592
+ static clone(request) {
2593
+ const cloned = new _HttpRequest({
2594
+ ...request,
2595
+ headers: {
2596
+ ...request.headers
2597
+ }
2598
+ });
2599
+ if (cloned.query) {
2600
+ cloned.query = cloneQuery(cloned.query);
2601
+ }
2602
+ return cloned;
2603
+ }
2604
+ static isInstance(request) {
2605
+ if (!request) {
2606
+ return false;
2607
+ }
2608
+ const req = request;
2609
+ return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
2610
+ }
2611
+ clone() {
2612
+ return _HttpRequest.clone(this);
2613
+ }
2614
+ };
2615
+ __name(_HttpRequest, "HttpRequest");
2616
+ var HttpRequest = _HttpRequest;
2617
+ function cloneQuery(query) {
2618
+ return Object.keys(query).reduce((carry, paramName) => {
2619
+ const param = query[paramName];
2620
+ return {
2621
+ ...carry,
2622
+ [paramName]: Array.isArray(param) ? [
2623
+ ...param
2624
+ ] : param
2625
+ };
2626
+ }, {});
2627
+ }
2628
+ __name(cloneQuery, "cloneQuery");
2629
+
2630
+ // src/utils/modules/getAwsAuthorizationHeaders.ts
2631
+ import { Sha256 } from "@aws-crypto/sha256-js";
2632
+
2633
+ // src/utils/modules/runWithTemporaryEnv.ts
2634
+ async function runWithTemporaryEnv(env, handler) {
2635
+ const previousEnv = {
2636
+ ...process.env
2637
+ };
2638
+ try {
2639
+ env();
2640
+ const value = await handler();
2641
+ return value;
2642
+ } finally {
2643
+ process.env = previousEnv;
2644
+ }
2645
+ }
2646
+ __name(runWithTemporaryEnv, "runWithTemporaryEnv");
2647
+
2648
+ // src/utils/modules/getAwsAuthorizationHeaders.ts
2649
+ async function getAwsAuthorizationHeaders(req, props) {
2650
+ const providerChain = fromNodeProviderChain();
2651
+ const credentials = await runWithTemporaryEnv(() => {
2652
+ if (props.awsAccessKey) {
2653
+ process.env["AWS_ACCESS_KEY_ID"] = props.awsAccessKey;
2654
+ }
2655
+ if (props.awsSecretKey) {
2656
+ process.env["AWS_SECRET_ACCESS_KEY"] = props.awsSecretKey;
2657
+ }
2658
+ if (props.awsSessionToken) {
2659
+ process.env["AWS_SESSION_TOKEN"] = props.awsSessionToken;
2660
+ }
2661
+ }, () => providerChain());
2662
+ const signer = new SignatureV4({
2663
+ service: "bedrock",
2664
+ region: props.regionName,
2665
+ credentials,
2666
+ sha256: Sha256
2667
+ });
2668
+ const url = new URL(props.url);
2669
+ const headers = !req.headers ? {} : Symbol.iterator in req.headers ? Object.fromEntries(Array.from(req.headers).map((header) => [
2670
+ ...header
2671
+ ])) : {
2672
+ ...req.headers
2673
+ };
2674
+ delete headers["connection"];
2675
+ headers["host"] = url.hostname;
2676
+ const request = new HttpRequest({
2677
+ method: req?.method?.toUpperCase(),
2678
+ protocol: url.protocol,
2679
+ path: url.pathname,
2680
+ body: req.body,
2681
+ headers
2682
+ });
2683
+ const signed = await signer.sign(request);
2684
+ return signed.headers;
2685
+ }
2686
+ __name(getAwsAuthorizationHeaders, "getAwsAuthorizationHeaders");
2687
+
2688
+ // src/llm/_utils.parseHeaders.ts
2689
+ async function parseHeaders(config, replacements, payload) {
2690
+ const replace = replaceTemplateStringSimple(config.headers, replacements);
2691
+ const parse = replace ? JSON.parse(replace) : {};
2692
+ const headers = Object.assign({}, payload.headers, parse);
2693
+ if (config.provider.startsWith("amazon:") || config.provider.startsWith("amazon.")) {
2694
+ const url = payload.url;
2695
+ return getAwsAuthorizationHeaders({
2696
+ method: config.method,
2697
+ headers,
2698
+ body: payload.body
2699
+ }, {
2700
+ url,
2701
+ regionName: replacements?.awsRegion || getEnvironmentVariable("AWS_REGION"),
2702
+ awsSecretKey: replacements.awsSecretKey,
2703
+ awsAccessKey: replacements.awsAccessKey
2704
+ });
2705
+ } else {
2706
+ return headers;
2707
+ }
2708
+ }
2709
+ __name(parseHeaders, "parseHeaders");
2710
+
2711
+ // src/llm/output/_utils/cleanJsonSchemaFor.ts
2712
+ var providerFieldExclusions = {
2713
+ "openai.chat": [
2714
+ "default"
2715
+ ]
2716
+ };
2717
+ function cleanJsonSchemaFor(schema = {}, provider) {
2718
+ const clone = deepClone(schema);
2719
+ const exclusions = providerFieldExclusions[provider] || [];
2720
+ function removeDisallowedFields(obj) {
2721
+ if (Array.isArray(obj)) {
2722
+ return obj.map(removeDisallowedFields);
2723
+ } else if (typeof obj === "object" && obj !== null) {
2724
+ return Object.keys(obj).reduce((acc, key) => {
2725
+ if (!exclusions.includes(key)) {
2726
+ acc[key] = removeDisallowedFields(obj[key]);
2727
+ }
2728
+ return acc;
2729
+ }, {});
2730
+ }
2731
+ return obj;
2732
+ }
2733
+ __name(removeDisallowedFields, "removeDisallowedFields");
2734
+ return removeDisallowedFields(clone);
2735
+ }
2736
+ __name(cleanJsonSchemaFor, "cleanJsonSchemaFor");
2737
+
2738
+ // src/llm/llm.call.ts
2739
+ async function useLlm_call(state, messages, _options) {
2740
+ const config = getLlmConfig(state.key);
2741
+ const { functionCallStrictInput = false } = _options || {};
2742
+ const input = mapBody(config.mapBody, Object.assign({}, state, {
2743
+ prompt: messages
2744
+ }));
2745
+ if (_options && _options?.jsonSchema) {
2746
+ if (state.provider === "openai.chat") {
2747
+ const curr = input["response_format"] || {};
2748
+ const newObj = Object.assign(curr, {
2749
+ type: "json_schema",
2750
+ json_schema: {
2751
+ name: "output",
2752
+ schema: cleanJsonSchemaFor(_options?.jsonSchema, "openai.chat")
2753
+ }
2754
+ });
2755
+ if (!!functionCallStrictInput) {
2756
+ newObj["json_schema"]["strict"] = true;
2757
+ }
2758
+ input["response_format"] = newObj;
2759
+ }
2760
+ }
2761
+ if (_options && _options?.functionCall) {
2762
+ if (state.provider === "anthropic.chat") {
2763
+ if (_options?.functionCall === "none") {
2764
+ _options.functions = [];
2765
+ } else if (_options?.functionCall === "auto" || _options?.functionCall === "any") {
2766
+ input["tool_choice"] = {
2767
+ type: _options?.functionCall
2768
+ };
2769
+ } else {
2770
+ input["tool_choice"] = _options?.functionCall;
2771
+ }
2772
+ } else if (state.provider === "openai.chat") {
2773
+ input["tool_choice"] = normalizeFunctionCall(_options?.functionCall, "openai");
2774
+ }
2775
+ }
2776
+ if (_options && _options?.functions?.length) {
2777
+ if (state.provider === "anthropic.chat") {
2778
+ input["tools"] = _options.functions.map((f) => ({
2779
+ name: f.name,
2780
+ description: f.description,
2781
+ input_schema: f.parameters
2782
+ }));
2783
+ } else if (state.provider === "openai.chat") {
2784
+ input["tools"] = _options.functions.map((f) => {
2785
+ const props = {
2786
+ name: f?.name,
2787
+ description: f?.description,
2788
+ parameters: f?.parameters
2789
+ };
2790
+ return {
2791
+ type: "function",
2792
+ function: Object.assign(props, {
2793
+ parameters: cleanJsonSchemaFor(props.parameters, "openai.chat")
2794
+ }, {
2795
+ strict: true
2796
+ })
2797
+ };
2798
+ });
2799
+ }
2800
+ }
2801
+ const body = typeof input === "string" ? input : JSON.stringify(input);
2802
+ const url = replaceTemplateStringSimple(config.endpoint, state);
2803
+ const headers = await parseHeaders(config, state, {
2804
+ url,
2805
+ headers: {},
2806
+ body
2807
+ });
2808
+ const response = config.provider === "openai.chat-mock" ? {
2809
+ id: "0123-45-6789",
2810
+ model: "model",
2811
+ created: (/* @__PURE__ */ new Date()).getTime(),
2812
+ usage: {
2813
+ completion_tokens: 0,
2814
+ prompt_tokens: 0,
2815
+ total_tokens: 0
2816
+ },
2817
+ choices: [
2818
+ {
2819
+ message: {
2820
+ role: "assistant",
2821
+ content: `Hello world from LLM! The input was ${JSON.stringify(messages)}`
2822
+ }
2823
+ }
2824
+ ]
2825
+ } : await apiRequest(url, {
2826
+ method: config.method,
2827
+ body,
2828
+ headers
2829
+ });
2830
+ return getOutputParser(state, response);
2831
+ }
2832
+ __name(useLlm_call, "useLlm_call");
2833
+
2834
+ // src/llm/_utils.stateFromOptions.ts
2835
+ function stateFromOptions(options, config) {
2836
+ const optionsKeys = Object.keys(config.options);
2837
+ const state = Object.assign(pick(options, optionsKeys), {
2838
+ provider: config.provider,
2839
+ key: config.key,
2840
+ model: options.model
2841
+ });
2842
+ const keys = Object.keys(config.options);
2843
+ for (const key of keys) {
2844
+ const thisConfig = config.options[key];
2845
+ const thisValue = get(state, key);
2846
+ if (typeof thisValue === "undefined") {
2847
+ if (typeof thisConfig?.default !== "undefined") {
2848
+ state[key] = thisConfig.default;
2849
+ }
2850
+ }
2851
+ if (thisConfig?.required && typeof get(state, key) === "undefined") {
2852
+ const [required, message = `Error: [${key}] is required`] = thisConfig?.required;
2853
+ if (required) {
2854
+ throw new Error(message);
2855
+ }
2856
+ }
2857
+ }
2858
+ return state;
2859
+ }
2860
+ __name(stateFromOptions, "stateFromOptions");
2861
+
2862
+ // src/utils/modules/deepFreeze.ts
2863
+ function deepFreeze(obj) {
2864
+ if (obj === null || obj === void 0) return obj;
2865
+ if (Object.isFrozen(obj)) return obj;
2866
+ if (obj instanceof Date) {
2867
+ return new Date(obj.getTime());
2868
+ }
2869
+ if (Array.isArray(obj)) {
2870
+ obj.forEach((item, index) => {
2871
+ obj[index] = deepFreeze(item);
2872
+ });
2873
+ return Object.freeze(obj);
2874
+ }
2875
+ if (typeof obj === "object" && obj !== null) {
2876
+ for (const key of Object.keys(obj)) {
2877
+ obj[key] = deepFreeze(obj[key]);
2878
+ }
2879
+ return Object.freeze(obj);
2880
+ }
2881
+ return obj;
2882
+ }
2883
+ __name(deepFreeze, "deepFreeze");
2884
+
2885
+ // src/utils/modules/requestWrapper.ts
2886
+ import { backOff } from "exponential-backoff";
2887
+ function apiRequestWrapper(config, options, handler, doNotRetryErrorMessages = []) {
2888
+ const state = stateFromOptions(options, config);
2889
+ const metrics = {
2890
+ total_calls: 0,
2891
+ total_call_success: 0,
2892
+ total_call_retry: 0,
2893
+ total_call_error: 0,
2894
+ history: []
2895
+ };
2896
+ const timeout = options.timeout || 3e4;
2897
+ const maxDelay = options.maxDelay || 5e3;
2898
+ const numOfAttempts = options.numOfAttempts || 2;
2899
+ const jitter = options.jitter || "none";
2900
+ let traceId = options?.traceId || null;
2901
+ async function call(messages, options2) {
2902
+ try {
2903
+ metrics.total_calls++;
2904
+ const result = await backOff(() => asyncCallWithTimeout(handler(deepFreeze(state), deepFreeze(messages), deepFreeze(options2)), timeout), {
2905
+ startingDelay: 0,
2906
+ maxDelay,
2907
+ numOfAttempts,
2908
+ jitter,
2909
+ retry: /* @__PURE__ */ __name((_error, _stepNumber) => {
2910
+ if (doNotRetryErrorMessages.includes(_error.message)) {
2911
+ return false;
2912
+ }
2913
+ metrics.total_call_retry++;
2914
+ return true;
2915
+ }, "retry")
2916
+ });
2917
+ metrics.total_call_success++;
2918
+ return result;
2919
+ } catch (error) {
2920
+ metrics.total_call_error++;
2921
+ throw error;
2922
+ }
2923
+ }
2924
+ __name(call, "call");
2925
+ function getMetadata() {
2926
+ const { awsSecretKey, awsAccessKey, openAiApiKey, anthropicApiKey, ...rest } = options;
2927
+ return Object.assign({
2928
+ traceId: getTraceId(),
2929
+ timeout,
2930
+ jitter,
2931
+ maxDelay,
2932
+ numOfAttempts,
2933
+ metrics: {
2934
+ ...metrics
2935
+ }
2936
+ }, rest);
2937
+ }
2938
+ __name(getMetadata, "getMetadata");
2939
+ function getTraceId() {
2940
+ return traceId;
2941
+ }
2942
+ __name(getTraceId, "getTraceId");
2943
+ function withTraceId(id) {
2944
+ traceId = id;
2945
+ }
2946
+ __name(withTraceId, "withTraceId");
2947
+ return {
2948
+ call,
2949
+ getTraceId,
2950
+ withTraceId,
2951
+ getMetadata
2952
+ };
2953
+ }
2954
+ __name(apiRequestWrapper, "apiRequestWrapper");
2955
+
2956
+ // src/llm/llm.ts
2957
+ function useLlm(provider, options = {}) {
2958
+ const config = getLlmConfig(provider);
2959
+ return apiRequestWrapper(config, options, useLlm_call);
2960
+ }
2961
+ __name(useLlm, "useLlm");
2962
+
2963
+ // src/embedding/config.ts
2964
+ var embeddingConfigs = {
2965
+ "openai.embedding.v1": {
2966
+ key: "openai.embedding.v1",
2967
+ provider: "openai.embedding",
2968
+ endpoint: `https://api.openai.com/v1/embeddings`,
2969
+ method: "POST",
2970
+ headers: `{"Authorization":"Bearer {{openAiApiKey}}", "Content-Type": "application/json" }`,
2971
+ options: {
2972
+ input: {},
2973
+ dimensions: {},
2974
+ encodingFormat: {},
2975
+ openAiApiKey: {}
2976
+ },
2977
+ mapBody: {
2978
+ input: {
2979
+ key: "input"
2980
+ },
2981
+ model: {
2982
+ key: "model"
2983
+ },
2984
+ dimensions: {
2985
+ key: "dimensions"
2986
+ },
2987
+ encodingFormat: {
2988
+ key: "encoding_format"
2989
+ }
2990
+ }
2991
+ },
2992
+ "amazon.embedding.v1": {
2993
+ key: "amazon.embedding.v1",
2994
+ provider: "amazon.embedding",
2995
+ endpoint: `https://bedrock-runtime.{{awsRegion}}.amazonaws.com/model/{{model}}/invoke`,
2996
+ method: "POST",
2997
+ headers: `{"Content-Type": "application/json" }`,
2998
+ options: {
2999
+ input: {},
3000
+ dimensions: {},
3001
+ awsRegion: {
3002
+ default: getEnvironmentVariable("AWS_REGION"),
3003
+ required: [
3004
+ true,
3005
+ "aws region is required"
3006
+ ]
3007
+ },
3008
+ awsSecretKey: {},
3009
+ awsAccessKey: {}
3010
+ },
3011
+ mapBody: {
3012
+ input: {
3013
+ key: "inputText"
3014
+ },
3015
+ dimensions: {
3016
+ key: "dimensions"
3017
+ }
3018
+ }
3019
+ }
3020
+ };
3021
+ function getEmbeddingConfig(provider) {
3022
+ const pick2 = embeddingConfigs[provider];
3023
+ if (pick2) {
3024
+ return pick2;
3025
+ }
3026
+ throw new Error("Invalid provider");
3027
+ }
3028
+ __name(getEmbeddingConfig, "getEmbeddingConfig");
3029
+
3030
+ // src/embedding/output/BaseEmbeddingOutput.ts
3031
+ function BaseEmbeddingOutput(result) {
3032
+ const __result = Object.freeze({
3033
+ id: result.id || uuidv4(),
3034
+ model: result.model,
3035
+ usage: result.usage,
3036
+ embedding: [
3037
+ ...result?.embedding || []
3038
+ ],
3039
+ created: result?.created || (/* @__PURE__ */ new Date()).getTime()
3040
+ });
3041
+ function getResult() {
3042
+ return {
3043
+ id: __result.id,
3044
+ model: __result.model,
3045
+ created: __result.created,
3046
+ usage: __result.usage,
3047
+ embedding: __result.embedding
3048
+ };
3049
+ }
3050
+ __name(getResult, "getResult");
3051
+ function getEmbedding(index) {
3052
+ if (index && index > 0) {
3053
+ const arr = __result?.embedding;
3054
+ const val = arr[index];
3055
+ return val ? val : [];
3056
+ }
3057
+ return __result.embedding[0];
3058
+ }
3059
+ __name(getEmbedding, "getEmbedding");
3060
+ return {
3061
+ getEmbedding,
3062
+ getResult
3063
+ };
3064
+ }
3065
+ __name(BaseEmbeddingOutput, "BaseEmbeddingOutput");
3066
+
3067
+ // src/embedding/output/AmazonTitan.ts
3068
+ function AmazonTitanEmbedding(result, config) {
3069
+ const __result = deepClone(result);
3070
+ const model = config.model || "amazon.unknown";
3071
+ const created = (/* @__PURE__ */ new Date()).getTime();
3072
+ const embedding = [
3073
+ __result.embedding
3074
+ ];
3075
+ const usage = {
3076
+ output_tokens: 0,
3077
+ input_tokens: __result.inputTextTokenCount,
3078
+ total_tokens: __result.inputTextTokenCount
3079
+ };
3080
+ return BaseEmbeddingOutput({
3081
+ model,
3082
+ created,
3083
+ usage,
3084
+ embedding
3085
+ });
3086
+ }
3087
+ __name(AmazonTitanEmbedding, "AmazonTitanEmbedding");
3088
+
3089
+ // src/embedding/output/OpenAiEmbedding.ts
3090
+ function OpenAiEmbedding(result, config) {
3091
+ const __result = deepClone(result);
3092
+ const model = __result.model || config.model || "openai.unknown";
3093
+ const created = (/* @__PURE__ */ new Date()).getTime();
3094
+ const results = result?.data || [];
3095
+ const embedding = results.map((a) => a.embedding);
3096
+ const usage = {
3097
+ output_tokens: 0,
3098
+ input_tokens: result?.usage?.prompt_tokens,
3099
+ total_tokens: result?.usage?.total_tokens
3100
+ };
3101
+ return BaseEmbeddingOutput({
3102
+ model,
3103
+ created,
3104
+ usage,
3105
+ embedding
3106
+ });
3107
+ }
3108
+ __name(OpenAiEmbedding, "OpenAiEmbedding");
3109
+
3110
+ // src/embedding/output/getEmbeddingOutputParser.ts
3111
+ function getEmbeddingOutputParser(config, response) {
3112
+ switch (config.key) {
3113
+ case "openai.embedding.v1":
3114
+ return OpenAiEmbedding(response, config);
3115
+ case "amazon.embedding.v1":
3116
+ return AmazonTitanEmbedding(response, config);
3117
+ default:
3118
+ throw new Error("Unsupported provider");
3119
+ }
3120
+ }
3121
+ __name(getEmbeddingOutputParser, "getEmbeddingOutputParser");
3122
+
3123
+ // src/embedding/embedding.call.ts
3124
+ async function createEmbedding_call(state, _input, _options) {
3125
+ const config = getEmbeddingConfig(state.key);
3126
+ const input = mapBody(config.mapBody, Object.assign({}, state, {
3127
+ input: _input
3128
+ }));
3129
+ const body = typeof input === "string" ? input : JSON.stringify(input);
3130
+ const url = replaceTemplateStringSimple(config.endpoint, state);
3131
+ const headers = await parseHeaders(config, state, {
3132
+ url,
3133
+ headers: {},
3134
+ body
3135
+ });
3136
+ const request = await apiRequest(url, {
3137
+ method: config.method,
3138
+ body,
3139
+ headers
3140
+ });
3141
+ return getEmbeddingOutputParser(state, request);
3142
+ }
3143
+ __name(createEmbedding_call, "createEmbedding_call");
3144
+
3145
+ // src/embedding/embedding.ts
3146
+ function createEmbedding(provider, options) {
3147
+ const config = getEmbeddingConfig(provider);
3148
+ return apiRequestWrapper(config, options, createEmbedding_call);
3149
+ }
3150
+ __name(createEmbedding, "createEmbedding");
3151
+
3152
+ // src/prompt/_base.ts
3153
+ var _BasePrompt = class _BasePrompt {
3154
+ /**
3155
+ * constructor description
3156
+ * @param initialPromptMessage An initial message to add to the prompt.
3157
+ */
3158
+ constructor(initialPromptMessage, options) {
3159
+ __publicField(this, "type", "text");
3160
+ __publicField(this, "messages", []);
3161
+ __publicField(this, "partials", []);
3162
+ __publicField(this, "helpers", []);
3163
+ __publicField(this, "replaceTemplateString", replaceTemplateString);
3164
+ __publicField(this, "replaceTemplateStringAsync", replaceTemplateStringAsync);
3165
+ __publicField(this, "filters", {
3166
+ pre: [],
3167
+ post: []
3168
+ });
3169
+ if (initialPromptMessage) {
3170
+ this.addToPrompt(initialPromptMessage, "system");
3171
+ }
3172
+ if (options) {
3173
+ if (options.partials) {
3174
+ this.registerPartial(options.partials);
3175
+ }
3176
+ if (options.helpers) {
3177
+ this.registerHelpers(options.helpers);
3178
+ }
3179
+ if (options.preFilters && Array.isArray(options.preFilters)) {
3180
+ this.filters.pre.push(...options.preFilters);
3181
+ }
3182
+ if (options.postFilters && Array.isArray(options.postFilters)) {
3183
+ this.filters.post.push(...options.postFilters);
3184
+ }
3185
+ if (options.replaceTemplateString) {
3186
+ this.replaceTemplateString = options.replaceTemplateString;
3187
+ }
3188
+ }
3189
+ }
3190
+ /**
3191
+ * addToPrompt description
3192
+ * @param content The message content
3193
+ * @param role The role of the user. Defaults to system for base text prompt.
3194
+ * @return instance of BasePrompt.
3195
+ */
3196
+ addToPrompt(content, role = "system") {
3197
+ if (content) {
3198
+ switch (role) {
3199
+ case "system":
3200
+ default:
3201
+ this.addSystemMessage(content);
3202
+ break;
3203
+ }
3204
+ }
3205
+ return this;
3206
+ }
3207
+ /**
3208
+ * addSystemMessage description
3209
+ * @param content The message content
3210
+ * @return returns BasePrompt so it can be chained.
3211
+ */
3212
+ addSystemMessage(content) {
3213
+ this.messages.push({
3214
+ role: "system",
3215
+ content
3216
+ });
3217
+ return this;
3218
+ }
3219
+ /**
3220
+ * registerPartial description
3221
+ * @param partialOrPartials Additional partials that can be made available to the template parser.
3222
+ * @return BasePrompt so it can be chained.
3223
+ */
3224
+ registerPartial(partialOrPartials) {
3225
+ const partials2 = Array.isArray(partialOrPartials) ? partialOrPartials : [
3226
+ partialOrPartials
3227
+ ];
3228
+ this.partials.push(...partials2);
3229
+ return this;
3230
+ }
3231
+ /**
3232
+ * registerHelpers description
3233
+ * @param helperOrHelpers Additional helper functions that can be made available to the template parser.
3234
+ * @return BasePrompt so it can be chained.
3235
+ */
3236
+ registerHelpers(helperOrHelpers) {
3237
+ const helpers = Array.isArray(helperOrHelpers) ? helperOrHelpers : [
3238
+ helperOrHelpers
3239
+ ];
3240
+ this.helpers.push(...helpers);
3241
+ return this;
3242
+ }
3243
+ /**
3244
+ * format description
3245
+ * @param values The message content
3246
+ * @param separator The separator between messages. defaults to "\n\n"
3247
+ * @return returns messages formatted with template replacement
3248
+ */
3249
+ format(values, separator = "\n\n") {
3250
+ const replacements = this.getReplacements(values);
3251
+ const messages = this.messages.map((message) => {
3252
+ return message.content && !Array.isArray(message.content) ? this.replaceTemplateString(this.runPromptFilter(message.content, this.filters.pre, values), replacements, {
3253
+ partials: this.partials,
3254
+ helpers: this.helpers
3255
+ }) : "";
3256
+ }).join(separator);
3257
+ return this.runPromptFilter(messages, this.filters.post, values);
3258
+ }
3259
+ /**
3260
+ * format description
3261
+ * @param values The message content
3262
+ * @param separator The separator between messages. defaults to "\n\n"
3263
+ * @return returns messages formatted with template replacement
3264
+ */
3265
+ async formatAsync(values, separator = "\n\n") {
3266
+ const replacements = this.getReplacements(values);
3267
+ const _messages = await Promise.all(this.messages.map((message) => {
3268
+ return message.content && !Array.isArray(message.content) ? this.replaceTemplateStringAsync(this.runPromptFilter(message.content, this.filters.pre, values), replacements, {
3269
+ partials: this.partials,
3270
+ helpers: this.helpers
3271
+ }) : "";
3272
+ }));
3273
+ const messages = _messages.join(separator);
3274
+ return this.runPromptFilter(messages, this.filters.post, values);
3275
+ }
3276
+ runPromptFilter(prompt, filters, values) {
3277
+ let promptValue = prompt;
3278
+ for (const filter of filters) {
3279
+ promptValue = filter(promptValue, values);
3280
+ }
3281
+ return promptValue;
3282
+ }
3283
+ getReplacements(values) {
3284
+ const { input = "", ...restOfValues } = values;
3285
+ const replacements = Object.assign({}, {
3286
+ ...restOfValues
3287
+ }, {
3288
+ input,
3289
+ _input: input
3290
+ });
3291
+ return replacements;
3292
+ }
3293
+ /**
3294
+ * validate description
3295
+ * @return {boolean} Returns false if the template is not valid.
3296
+ */
3297
+ validate() {
3298
+ return true;
3299
+ }
3300
+ };
3301
+ __name(_BasePrompt, "BasePrompt");
3302
+ var BasePrompt = _BasePrompt;
3303
+
3304
+ // src/prompt/text.ts
3305
+ var _TextPrompt = class _TextPrompt extends BasePrompt {
3306
+ constructor(base, options) {
3307
+ super(base, options);
3308
+ }
3309
+ };
3310
+ __name(_TextPrompt, "TextPrompt");
3311
+ var TextPrompt = _TextPrompt;
3312
+
3313
+ // src/utils/modules/unescape.ts
3314
+ function unescape(str) {
3315
+ const map = {
3316
+ "&amp;": "&",
3317
+ "&lt;": "<",
3318
+ "&gt;": ">",
3319
+ "&quot;": '"',
3320
+ "&#39;": "'"
3321
+ };
3322
+ const entityRegex = /&amp;|&lt;|&gt;|&quot;|&#39;/g;
3323
+ return str.replace(entityRegex, (m) => map[m]);
3324
+ }
3325
+ __name(unescape, "unescape");
3326
+
3327
+ // src/utils/modules/extractPromptPlaceholderToken.ts
3328
+ function extractPromptPlaceholderToken(tok) {
3329
+ if (!tok) return {
3330
+ token: ""
3331
+ };
3332
+ const token = tok.replace(/ /g, "");
3333
+ if (token.substring(2, 18) === ">DialogueHistory") {
3334
+ const matchKey = tok.match(/key=(['"`])((?:(?!\1).)*)\1/);
3335
+ const matchAssistant = tok.match(/assistant=(['"`])((?:(?!\1).)*)\1/);
3336
+ const matchUser = tok.match(/user=(['"`])((?:(?!\1).)*)\1/);
3337
+ if (matchKey) {
3338
+ return {
3339
+ token: ">DialogueHistory",
3340
+ key: matchKey[2],
3341
+ assistant: matchAssistant ? get(matchAssistant, "[2]", "") : void 0,
3342
+ user: matchUser ? get(matchUser, "[2]", "") : matchUser
3343
+ };
3344
+ }
3345
+ } else if (token.substring(2, 20) === ">SingleChatMessage") {
3346
+ const matchRole = tok.match(/role=(['"`])((?:(?!\1).)*)\1/);
3347
+ const matchContent = tok.match(/content=(['"`])((?:(?!\1).)*)\1/);
3348
+ const matchName = tok.match(/name=(['"`])((?:(?!\1).)*)\1/);
3349
+ if (matchRole) {
3350
+ return {
3351
+ token: ">SingleChatMessage",
3352
+ name: matchName ? get(matchName, "[2]") : void 0,
3353
+ content: matchContent ? unescape(get(matchContent, "[2]", "")) : void 0,
3354
+ role: get(matchRole, "[2]", "")
3355
+ };
3356
+ }
3357
+ }
3358
+ return {
3359
+ token: ""
3360
+ };
3361
+ }
3362
+ __name(extractPromptPlaceholderToken, "extractPromptPlaceholderToken");
3363
+
3364
+ // src/utils/modules/escape.ts
3365
+ function escape(str) {
3366
+ const map = {
3367
+ "&": "&amp;",
3368
+ "<": "&lt;",
3369
+ ">": "&gt;",
3370
+ '"': "&quot;",
3371
+ "'": "&#39;"
3372
+ };
3373
+ return str.replace(/[&<>"']/g, (m) => map[m]);
3374
+ }
3375
+ __name(escape, "escape");
3376
+
3377
+ // src/prompt/chat.ts
3378
+ var _ChatPrompt = class _ChatPrompt extends BasePrompt {
3379
+ /**
3380
+ * new `ChatPrompt`
3381
+ * @param initialSystemPromptMessage (optional) An initial system message to add to the new prompt.
3382
+ * @param options (optional) Options to pass in when creating the prompt.
3383
+ */
3384
+ constructor(initialSystemPromptMessage, options) {
3385
+ super(initialSystemPromptMessage, options);
3386
+ /**
3387
+ * @property type - Prompt type (chat)
3388
+ */
3389
+ __publicField(this, "type", "chat");
3390
+ /**
3391
+ * @property parseUserTemplates - Whether or not to allow parsing
3392
+ * user messages with the template engine. This could be a risk,
3393
+ * so we only parse user messages if explicitly set.
3394
+ */
3395
+ __publicField(this, "parseUserTemplates", false);
3396
+ if (options?.allowUnsafeUserTemplate) {
3397
+ this.parseUserTemplates = true;
3398
+ }
3399
+ }
3400
+ addToPrompt(content, role, name) {
3401
+ if (content) {
3402
+ switch (role) {
3403
+ case "system":
3404
+ this.addSystemMessage(content);
3405
+ break;
3406
+ case "user":
3407
+ this.addUserMessage(content, name);
3408
+ break;
3409
+ case "assistant":
3410
+ this.addAssistantMessage(content);
3411
+ break;
3412
+ case "function":
3413
+ assert(name, "Function message requires name");
3414
+ this.addFunctionMessage(content, name);
3415
+ break;
3416
+ case "function_call":
3417
+ assert(name, "Function message requires name");
3418
+ this.addFunctionCallMessage({
3419
+ name,
3420
+ arguments: content
3421
+ });
3422
+ break;
3423
+ }
3424
+ }
3425
+ return this;
3426
+ }
3427
+ /**
3428
+ * addUserMessage Helper to add a user message to the prompt.
3429
+ * @param content The message content.
3430
+ * @param name (optional) The name of the user.
3431
+ * @return instance of ChatPrompt.
3432
+ */
3433
+ addUserMessage(content, name) {
3434
+ const message = {
3435
+ role: "user",
3436
+ content
3437
+ };
3438
+ if (name) {
3439
+ message.name = name;
3440
+ }
3441
+ this.messages.push(message);
3442
+ return this;
3443
+ }
3444
+ /**
3445
+ * addAssistantMessage Helper to add an assistant message to the prompt.
3446
+ * @param content The message content.
3447
+ * @return ChatPrompt so it can be chained.
3448
+ */
3449
+ addAssistantMessage(content) {
3450
+ this.messages.push({
3451
+ role: "assistant",
3452
+ content
3453
+ });
3454
+ return this;
3455
+ }
3456
+ /**
3457
+ * addFunctionMessage Helper to add an assistant message to the prompt.
3458
+ * @param content The message content.
3459
+ * @return ChatPrompt so it can be chained.
3460
+ */
3461
+ addFunctionMessage(content, name) {
3462
+ this.messages.push({
3463
+ role: "function",
3464
+ name,
3465
+ content
3466
+ });
3467
+ return this;
3468
+ }
3469
+ /**
3470
+ * addFunctionCallMessage Helper to add an assistant message to the prompt.
3471
+ * @param content The message content.
3472
+ * @return ChatPrompt so it can be chained.
3473
+ */
3474
+ addFunctionCallMessage(function_call) {
3475
+ if (function_call) {
3476
+ this.messages.push({
3477
+ role: "assistant",
3478
+ function_call: {
3479
+ name: function_call.name,
3480
+ arguments: maybeStringifyJSON(function_call.arguments)
3481
+ },
3482
+ content: null
3483
+ });
3484
+ }
3485
+ return this;
3486
+ }
3487
+ /**
3488
+ * addFromHistory Adds multiple messages at one time.
3489
+ * @param history History of chat messages.
3490
+ * @return ChatPrompt so it can be chained.
3491
+ */
3492
+ addFromHistory(history) {
3493
+ if (history && Array.isArray(history)) {
3494
+ for (const message of history) {
3495
+ switch (message.role) {
3496
+ case "user":
3497
+ this.addUserMessage(message.content, message?.name);
3498
+ break;
3499
+ case "assistant":
3500
+ if (message.function_call) {
3501
+ this.addFunctionCallMessage(message.function_call);
3502
+ } else if (message?.content) {
3503
+ this.addAssistantMessage(message?.content);
3504
+ }
3505
+ break;
3506
+ case "system":
3507
+ this.addSystemMessage(message.content);
3508
+ break;
3509
+ case "function":
3510
+ this.addFunctionMessage(message.content, message.name);
3511
+ break;
3512
+ }
3513
+ }
3514
+ }
3515
+ return this;
3516
+ }
3517
+ /**
3518
+ * addPlaceholder description
3519
+ * @param content The message content
3520
+ * @return returns ChatPrompt so it can be chained.
3521
+ */
3522
+ addChatHistoryPlaceholder(key, options) {
3523
+ const start = `{{> DialogueHistory `;
3524
+ const params = [
3525
+ `key='${String(key)}'`
3526
+ ];
3527
+ const end = `}}`;
3528
+ if (options?.assistant) {
3529
+ params.push(`assistant='${options.assistant}'`);
3530
+ }
3531
+ if (options?.user) {
3532
+ params.push(`user='${options.user}'`);
3533
+ }
3534
+ this.messages.push({
3535
+ role: "placeholder",
3536
+ content: `${start}${params.join(" ")}${end}`
3537
+ });
3538
+ return this;
3539
+ }
3540
+ /**
3541
+ * addTokenPlaceholder description
3542
+ * @param content The message content
3543
+ * @return returns ChatPrompt so it can be chained.
3544
+ */
3545
+ addMessagePlaceholder(content, role = "user", name) {
3546
+ if (content) {
3547
+ const start = `{{> SingleChatMessage `;
3548
+ const params = [
3549
+ `role='${role}'`,
3550
+ `content='${escape(content)}'`
3551
+ ];
3552
+ const end = `}}`;
3553
+ if (name) {
3554
+ params.push(`name='${name}'`);
3555
+ }
3556
+ this.messages.push({
3557
+ role: "placeholder",
3558
+ content: `${start}${params.join(" ")}${end}`
3559
+ });
3560
+ }
3561
+ return this;
3562
+ }
3563
+ _format_placeholderDialogueHistory(data, replacements) {
3564
+ const messagesOut = [];
3565
+ const { key = "", user } = data;
3566
+ const history = get(replacements, key, []);
3567
+ if (history && Array.isArray(history)) {
3568
+ for (const message of history) {
3569
+ switch (message.role) {
3570
+ case "user": {
3571
+ const m = pick(message, [
3572
+ "role",
3573
+ "content",
3574
+ "name"
3575
+ ]);
3576
+ if (user) {
3577
+ m["name"] = user;
3578
+ }
3579
+ messagesOut.push(m);
3580
+ break;
3581
+ }
3582
+ case "assistant": {
3583
+ if (message.function_call) {
3584
+ messagesOut.push({
3585
+ role: "assistant",
3586
+ content: null,
3587
+ function_call: message.function_call
3588
+ });
3589
+ } else if (message?.content) {
3590
+ messagesOut.push({
3591
+ role: "assistant",
3592
+ content: message.content
3593
+ });
3594
+ }
3595
+ break;
3596
+ }
3597
+ case "function":
3598
+ messagesOut.push({
3599
+ role: "function",
3600
+ name: message.name,
3601
+ content: message.content
3602
+ });
3603
+ break;
3604
+ case "system":
3605
+ messagesOut.push({
3606
+ role: "system",
3607
+ content: message.content
3608
+ });
3609
+ break;
3610
+ }
3611
+ }
3612
+ }
3613
+ return messagesOut;
3614
+ }
3615
+ /**
3616
+ * format formats the stored prompt based on input values.
3617
+ * Uses template engine.
3618
+ * Output is intended for LLM.
3619
+ * @param values input values.
3620
+ * @return formatted prompt.
3621
+ */
3622
+ format(values) {
3623
+ const messagesOut = [];
3624
+ const replacements = this.getReplacements(values);
3625
+ const safeToParseTemplate = [
3626
+ "assistant",
3627
+ "system"
3628
+ ];
3629
+ if (this.parseUserTemplates) {
3630
+ safeToParseTemplate.push("user");
3631
+ }
3632
+ for (const message of this.messages) {
3633
+ if (message.role === "placeholder") {
3634
+ const tokenData = extractPromptPlaceholderToken(message.content);
3635
+ switch (tokenData.token) {
3636
+ case ">DialogueHistory": {
3637
+ messagesOut.push(...this._format_placeholderDialogueHistory(tokenData, replacements));
3638
+ break;
3639
+ }
3640
+ case ">SingleChatMessage": {
3641
+ const { name, content, role } = tokenData;
3642
+ if (role && content) {
3643
+ const message2 = {
3644
+ role,
3645
+ name,
3646
+ content: this.replaceTemplateString(content, replacements, {
3647
+ partials: this.partials,
3648
+ helpers: this.helpers
3649
+ })
3650
+ };
3651
+ if (!name || role !== "user") {
3652
+ delete message2.name;
3653
+ }
3654
+ messagesOut.push(message2);
3655
+ }
3656
+ break;
3657
+ }
3658
+ }
3659
+ } else if (message.role === "function") {
3660
+ messagesOut.push(Object.assign({}, message, {
3661
+ content: this.replaceTemplateString(message.content, replacements, {
3662
+ partials: this.partials,
3663
+ helpers: this.helpers
3664
+ })
3665
+ }));
3666
+ } else {
3667
+ if (safeToParseTemplate.includes(message.role)) {
3668
+ if (Array.isArray(message.content)) {
3669
+ const content = message.content.map((m) => m.text ? {
3670
+ type: "text",
3671
+ text: this.runPromptFilter(this.replaceTemplateString(this.runPromptFilter(m.text, this.filters.pre, values), replacements, {
3672
+ partials: this.partials,
3673
+ helpers: this.helpers
3674
+ }), this.filters.post, values)
3675
+ } : m);
3676
+ messagesOut.push(Object.assign({}, message, {
3677
+ content
3678
+ }));
3679
+ } else if (message.content) {
3680
+ const content = this.runPromptFilter(this.replaceTemplateString(this.runPromptFilter(message.content, this.filters.pre, values), replacements, {
3681
+ partials: this.partials,
3682
+ helpers: this.helpers
3683
+ }), this.filters.post, values);
3684
+ messagesOut.push(Object.assign({}, message, {
3685
+ content
3686
+ }));
3687
+ } else {
3688
+ messagesOut.push(Object.assign({}, message, {
3689
+ content: null
3690
+ }));
3691
+ }
3692
+ } else {
3693
+ messagesOut.push(Object.assign({}, message, {
3694
+ content: Array.isArray(message.content) ? message.content.map((m) => m.text ? {
3695
+ type: "text",
3696
+ text: this.runPromptFilter(this.runPromptFilter(m.text, this.filters.pre, values), this.filters.post, values)
3697
+ } : m) : message.content && !Array.isArray(message.content) ? this.runPromptFilter(this.runPromptFilter(message.content, this.filters.pre, values), this.filters.post, values) : null
3698
+ }));
3699
+ }
3700
+ }
3701
+ }
3702
+ return messagesOut;
3703
+ }
3704
+ /**
3705
+ * format formats the stored prompt based on input values.
3706
+ * Uses template engine.
3707
+ * Output is intended for LLM.
3708
+ * @param values input values.
3709
+ * @return formatted prompt.
3710
+ */
3711
+ async formatAsync(values) {
3712
+ const messagesOut = [];
3713
+ const replacements = this.getReplacements(values);
3714
+ const safeToParseTemplate = [
3715
+ "assistant",
3716
+ "system"
3717
+ ];
3718
+ if (this.parseUserTemplates) {
3719
+ safeToParseTemplate.push("user");
3720
+ }
3721
+ for (const message of this.messages) {
3722
+ if (message.role === "placeholder") {
3723
+ const { token, ...data } = extractPromptPlaceholderToken(message.content);
3724
+ switch (token) {
3725
+ case ">DialogueHistory": {
3726
+ const { key = "", user } = data;
3727
+ const history = get(replacements, key, []);
3728
+ if (history && Array.isArray(history)) {
3729
+ for (const message2 of history) {
3730
+ switch (message2.role) {
3731
+ case "user": {
3732
+ const m = pick(message2, [
3733
+ "role",
3734
+ "content",
3735
+ "name"
3736
+ ]);
3737
+ if (user) {
3738
+ m["name"] = user;
3739
+ }
3740
+ messagesOut.push(m);
3741
+ break;
3742
+ }
3743
+ case "assistant": {
3744
+ if (message2.function_call) {
3745
+ messagesOut.push({
3746
+ role: "assistant",
3747
+ content: null,
3748
+ function_call: message2.function_call
3749
+ });
3750
+ } else if (message2?.content) {
3751
+ messagesOut.push({
3752
+ role: "assistant",
3753
+ content: message2.content
3754
+ });
3755
+ }
3756
+ break;
3757
+ }
3758
+ case "function":
3759
+ messagesOut.push({
3760
+ role: "function",
3761
+ name: message2.name,
3762
+ content: message2.content
3763
+ });
3764
+ break;
3765
+ case "system":
3766
+ messagesOut.push({
3767
+ role: "system",
3768
+ content: message2.content
3769
+ });
3770
+ break;
3771
+ }
3772
+ }
3773
+ }
3774
+ break;
3775
+ }
3776
+ case ">SingleChatMessage": {
3777
+ const { name, content, role } = data;
3778
+ if (role && content) {
3779
+ const message2 = {
3780
+ role,
3781
+ name,
3782
+ content: await this.replaceTemplateStringAsync(content, replacements, {
3783
+ partials: this.partials,
3784
+ helpers: this.helpers
3785
+ })
3786
+ };
3787
+ if (!name || role !== "user") {
3788
+ delete message2.name;
3789
+ }
3790
+ messagesOut.push(message2);
3791
+ }
3792
+ break;
3793
+ }
3794
+ }
3795
+ } else if (message.role === "function") {
3796
+ messagesOut.push(Object.assign({}, message, {
3797
+ content: await this.replaceTemplateStringAsync(message.content, replacements, {
3798
+ partials: this.partials,
3799
+ helpers: this.helpers
3800
+ })
3801
+ }));
3802
+ } else {
3803
+ if (safeToParseTemplate.includes(message.role)) {
3804
+ if (Array.isArray(message.content)) {
3805
+ const content = [];
3806
+ for (const m of message.content) {
3807
+ if (m.text) {
3808
+ content.push({
3809
+ type: "text",
3810
+ text: this.runPromptFilter(
3811
+ // HERE
3812
+ await this.replaceTemplateStringAsync(this.runPromptFilter(m.text, this.filters.pre, values), replacements, {
3813
+ partials: this.partials,
3814
+ helpers: this.helpers
3815
+ }),
3816
+ this.filters.post,
3817
+ values
3818
+ )
3819
+ });
3820
+ } else {
3821
+ content.push(m);
3822
+ }
3823
+ }
3824
+ messagesOut.push(Object.assign({}, message, {
3825
+ content
3826
+ }));
3827
+ } else if (message.content) {
3828
+ const content = this.runPromptFilter(await this.replaceTemplateStringAsync(this.runPromptFilter(message.content, this.filters.pre, values), replacements, {
3829
+ partials: this.partials,
3830
+ helpers: this.helpers
3831
+ }), this.filters.post, values);
3832
+ messagesOut.push(Object.assign({}, message, {
3833
+ content
3834
+ }));
3835
+ } else {
3836
+ messagesOut.push(Object.assign({}, message, {
3837
+ content: null
3838
+ }));
3839
+ }
3840
+ } else {
3841
+ messagesOut.push(Object.assign({}, message, {
3842
+ content: Array.isArray(message.content) ? message.content.map((m) => m.text ? {
3843
+ type: "text",
3844
+ text: this.runPromptFilter(this.runPromptFilter(m.text, this.filters.pre, values), this.filters.post, values)
3845
+ } : m) : message.content && !Array.isArray(message.content) ? this.runPromptFilter(this.runPromptFilter(message.content, this.filters.pre, values), this.filters.post, values) : null
3846
+ }));
3847
+ }
3848
+ }
3849
+ }
3850
+ return messagesOut;
3851
+ }
3852
+ /**
3853
+ * validate Ensures there are not unresolved tokens in prompt.
3854
+ * @TODO Make this work!
3855
+ * @return Returns false if the template is not valid.
3856
+ */
3857
+ validate() {
3858
+ return true;
3859
+ }
3860
+ };
3861
+ __name(_ChatPrompt, "ChatPrompt");
3862
+ var ChatPrompt = _ChatPrompt;
3863
+
3864
+ // src/prompt/_functions.ts
3865
+ function createPrompt(type, initialPromptMessage, options) {
3866
+ switch (type) {
3867
+ case "chat":
3868
+ return new ChatPrompt(initialPromptMessage, options);
3869
+ default:
3870
+ return new TextPrompt(initialPromptMessage);
3871
+ }
3872
+ }
3873
+ __name(createPrompt, "createPrompt");
3874
+ function createChatPrompt(initialSystemPromptMessage, options) {
3875
+ return new ChatPrompt(initialSystemPromptMessage, options);
3876
+ }
3877
+ __name(createChatPrompt, "createChatPrompt");
3878
+
3879
+ // src/state/item.ts
3880
+ var _BaseStateItem = class _BaseStateItem {
3881
+ constructor(key, initialValue) {
3882
+ __publicField(this, "key");
3883
+ __publicField(this, "value");
3884
+ __publicField(this, "initialValue");
3885
+ this.key = key;
3886
+ this.value = initialValue;
3887
+ this.initialValue = initialValue;
3888
+ }
3889
+ setValue(value) {
3890
+ assert(typeof value === typeof this.value, `Invalid value type. Expected ${typeof this.value}, received ${typeof value}`);
3891
+ this.value = value;
3892
+ }
3893
+ getKey() {
3894
+ return this.key;
3895
+ }
3896
+ getValue() {
3897
+ return this.value;
3898
+ }
3899
+ resetValue() {
3900
+ this.value = this.initialValue;
3901
+ }
3902
+ serializeValue() {
3903
+ return {
3904
+ [this.getKey()]: this.getValue()
3905
+ };
3906
+ }
3907
+ serialize() {
3908
+ return {
3909
+ class: "BaseStateItem",
3910
+ name: this.getKey(),
3911
+ value: this.serializeValue()
3912
+ };
3913
+ }
3914
+ };
3915
+ __name(_BaseStateItem, "BaseStateItem");
3916
+ var BaseStateItem = _BaseStateItem;
3917
+ var _DefaultStateItem = class _DefaultStateItem extends BaseStateItem {
3918
+ constructor(name, defaultValue) {
3919
+ super(name, defaultValue);
3920
+ }
3921
+ };
3922
+ __name(_DefaultStateItem, "DefaultStateItem");
3923
+ var DefaultStateItem = _DefaultStateItem;
3924
+
3925
+ // src/state/dialogue.ts
3926
+ var _Dialogue = class _Dialogue extends BaseStateItem {
3927
+ constructor(name) {
3928
+ super(name, []);
3929
+ __publicField(this, "name");
3930
+ this.name = name;
3931
+ }
3932
+ setUserMessage(content, name) {
3933
+ if (content) {
3934
+ const msg = {
3935
+ role: "user",
3936
+ content
3937
+ };
3938
+ if (name) {
3939
+ msg.name = name;
3940
+ }
3941
+ this.value.push(msg);
3942
+ }
3943
+ return this;
3944
+ }
3945
+ setAssistantMessage(content) {
3946
+ if (content) {
3947
+ this.value.push({
3948
+ role: "assistant",
3949
+ content
3950
+ });
3951
+ }
3952
+ return this;
3953
+ }
3954
+ setSystemMessage(content) {
3955
+ if (content) {
3956
+ this.value.push({
3957
+ role: "system",
3958
+ content
3959
+ });
3960
+ }
3961
+ return this;
3962
+ }
3963
+ setFunctionMessage(content, name) {
3964
+ if (content) {
3965
+ this.value.push({
3966
+ role: "function",
3967
+ name,
3968
+ content
3969
+ });
3970
+ }
3971
+ return this;
3972
+ }
3973
+ setFunctionCallMessage(input) {
3974
+ this.value.push({
3975
+ role: "assistant",
3976
+ function_call: {
3977
+ name: input?.function_call.name,
3978
+ arguments: maybeStringifyJSON(input?.function_call.arguments)
3979
+ },
3980
+ content: null
3981
+ });
3982
+ return this;
3983
+ }
3984
+ setMessageTurn(userMessage, assistantMessage, systemMessage = "") {
3985
+ this.setUserMessage(userMessage);
3986
+ this.setAssistantMessage(assistantMessage);
3987
+ this.setSystemMessage(systemMessage);
3988
+ return this;
3989
+ }
3990
+ setHistory(messages) {
3991
+ for (const message of messages) {
3992
+ switch (message?.role) {
3993
+ case "user":
3994
+ this.setUserMessage(message?.content, message?.name);
3995
+ break;
3996
+ case "assistant":
3997
+ if (message.function_call) {
3998
+ this.setFunctionCallMessage({
3999
+ function_call: message.function_call
4000
+ });
4001
+ } else if (message?.content) {
4002
+ this.setAssistantMessage(message?.content);
4003
+ }
4004
+ break;
4005
+ case "system":
4006
+ this.setSystemMessage(message?.content);
4007
+ break;
4008
+ case "function":
4009
+ this.setFunctionMessage(message?.content, message.name);
4010
+ break;
4011
+ }
4012
+ }
4013
+ return this;
4014
+ }
4015
+ getHistory() {
4016
+ return this.getValue();
4017
+ }
4018
+ serialize() {
4019
+ return {
4020
+ class: "Dialogue",
4021
+ name: this.name,
4022
+ value: [
4023
+ ...this.value
4024
+ ]
4025
+ };
4026
+ }
4027
+ };
4028
+ __name(_Dialogue, "Dialogue");
4029
+ var Dialogue = _Dialogue;
4030
+
4031
+ // src/state/_base.ts
4032
+ var _BaseState = class _BaseState {
4033
+ constructor() {
4034
+ __publicField(this, "dialogues", {});
4035
+ __publicField(this, "attributes", {});
4036
+ __publicField(this, "context", {});
4037
+ }
4038
+ createDialogue(name = "defaultDialogue") {
4039
+ assert(!this.dialogues[name], `Dialogue already exists`);
4040
+ this.dialogues[name] = new Dialogue(name);
4041
+ return this.dialogues[name];
4042
+ }
4043
+ useDialogue(name = "defaultDialogue") {
4044
+ const dialogue = this.dialogues[name];
4045
+ if (!dialogue) {
4046
+ this.dialogues[name] = new Dialogue(name);
4047
+ return this.dialogues[name];
4048
+ }
4049
+ return dialogue;
4050
+ }
4051
+ getDialogue(name = "defaultDialogue") {
4052
+ const dialogue = this.dialogues[name];
4053
+ assert(dialogue, `Invalid dialogue ${name}`);
4054
+ return dialogue;
4055
+ }
4056
+ createContextItem(item) {
4057
+ assert(item instanceof BaseStateItem, "Invalid context item. Must be instance of BaseStateItem");
4058
+ assert(!this.context[item?.getKey()], `key (${item?.getKey()}) already exists`);
4059
+ this.context[item.getKey()] = item;
4060
+ return this.context[item.getKey()];
4061
+ }
4062
+ getContext(key) {
4063
+ return this.context[key];
4064
+ }
4065
+ getContextValue(key) {
4066
+ return this.context[key]?.getValue();
4067
+ }
4068
+ setAttribute(key, value) {
4069
+ this.attributes[key] = value;
4070
+ }
4071
+ deleteAttribute(key) {
4072
+ delete this.attributes[key];
4073
+ }
4074
+ clearAttributes() {
4075
+ this.attributes = {};
4076
+ }
4077
+ serialize() {
4078
+ const dialogues = {};
4079
+ const context = {};
4080
+ const attributes = {
4081
+ ...this.attributes
4082
+ };
4083
+ const dialogueKeys = Object.keys(this.dialogues);
4084
+ for (const dialogueKey of dialogueKeys) {
4085
+ dialogues[dialogueKey] = this.dialogues[dialogueKey].serialize();
4086
+ }
4087
+ const contextKeys = Object.keys(this.context);
4088
+ for (const contextKey of contextKeys) {
4089
+ context[contextKey] = this.context[contextKey].serialize();
4090
+ }
4091
+ return {
4092
+ dialogues,
4093
+ context,
4094
+ attributes
4095
+ };
4096
+ }
4097
+ };
4098
+ __name(_BaseState, "BaseState");
4099
+ var BaseState = _BaseState;
4100
+ var _DefaultState = class _DefaultState extends BaseState {
4101
+ constructor() {
4102
+ super();
4103
+ }
4104
+ async saveState() {
4105
+ console.log("Save not implemented in default state.");
4106
+ }
4107
+ };
4108
+ __name(_DefaultState, "DefaultState");
4109
+ var DefaultState = _DefaultState;
4110
+
4111
+ // src/state/_functions.ts
4112
+ function createState() {
4113
+ return new DefaultState();
4114
+ }
4115
+ __name(createState, "createState");
4116
+ function createDialogue(name) {
4117
+ return new Dialogue(name);
4118
+ }
4119
+ __name(createDialogue, "createDialogue");
4120
+ function createStateItem(name, defaultValue) {
4121
+ return new DefaultStateItem(name, defaultValue);
4122
+ }
4123
+ __name(createStateItem, "createStateItem");
4124
+ export {
4125
+ BaseExecutor,
4126
+ BaseParser,
4127
+ BasePrompt,
4128
+ BaseStateItem,
4129
+ ChatPrompt,
4130
+ CustomParser,
4131
+ DefaultState,
4132
+ DefaultStateItem,
4133
+ LlmExecutorOpenAiFunctions,
4134
+ OpenAiFunctionParser,
4135
+ TextPrompt,
4136
+ createCallableExecutor,
4137
+ createChatPrompt,
4138
+ createCoreExecutor,
4139
+ createCustomParser,
4140
+ createDialogue,
4141
+ createEmbedding,
4142
+ createLlmExecutor,
4143
+ createParser,
4144
+ createPrompt,
4145
+ createState,
4146
+ createStateItem,
4147
+ useExecutors,
4148
+ useLlm,
4149
+ utils_exports as utils
4150
+ };