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

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