llm-exe 1.0.2 → 2.0.0-beta.10

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