llm-exe 2.0.0-beta.6 → 2.0.0-beta.8

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