@promptbook/cli 0.69.0-2 → 0.69.0-5

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 (22) hide show
  1. package/esm/index.es.js +1033 -947
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/typings/src/_packages/core.index.d.ts +1 -1
  4. package/esm/typings/src/_packages/types.index.d.ts +4 -0
  5. package/esm/typings/src/conversion/utils/extractParameterNamesFromTemplate.d.ts +2 -1
  6. package/esm/typings/src/execution/PipelineExecutorResult.d.ts +5 -3
  7. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorOptions.d.ts +20 -0
  8. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorSettings.d.ts +30 -0
  9. package/esm/typings/src/execution/createPipelineExecutor/00-createPipelineExecutor.d.ts +10 -0
  10. package/esm/typings/src/execution/createPipelineExecutor/10-executePipeline.d.ts +55 -0
  11. package/esm/typings/src/execution/createPipelineExecutor/20-executeTemplate.d.ts +62 -0
  12. package/esm/typings/src/execution/createPipelineExecutor/30-executeFormatCell.d.ts +30 -0
  13. package/esm/typings/src/execution/createPipelineExecutor/40-executeAttempt.d.ts +30 -0
  14. package/esm/typings/src/execution/createPipelineExecutor/filterJustOutputParameters.d.ts +34 -0
  15. package/esm/typings/src/execution/createPipelineExecutor/getContextForTemplate.d.ts +10 -0
  16. package/esm/typings/src/execution/createPipelineExecutor/getKnowledgeForTemplate.d.ts +27 -0
  17. package/esm/typings/src/execution/createPipelineExecutor/getReservedParametersForTemplate.d.ts +30 -0
  18. package/esm/typings/src/execution/createPipelineExecutor/getSamplesForTemplate.d.ts +10 -0
  19. package/package.json +1 -1
  20. package/umd/index.umd.js +1033 -947
  21. package/umd/index.umd.js.map +1 -1
  22. package/esm/typings/src/execution/createPipelineExecutor.d.ts +0 -72
package/esm/index.es.js CHANGED
@@ -20,7 +20,7 @@ import OpenAI from 'openai';
20
20
  /**
21
21
  * The version of the Promptbook library
22
22
  */
23
- var PROMPTBOOK_VERSION = '0.69.0-1';
23
+ var PROMPTBOOK_VERSION = '0.69.0-4';
24
24
  // TODO: !!!! List here all the versions and annotate + put into script
25
25
 
26
26
  /*! *****************************************************************************
@@ -473,6 +473,7 @@ var RESERVED_PARAMETER_NAMES = $asDeeplyFrozenSerializableJson('RESERVED_PARAMET
473
473
  'samples',
474
474
  'modelName',
475
475
  'currentDate',
476
+ // <- TODO: !!!!! list here all command names
476
477
  // <- TODO: Add more like 'date', 'modelName',...
477
478
  // <- TODO: Add [emoji] + instructions ACRY when adding new reserved parameter
478
479
  ]);
@@ -1049,7 +1050,7 @@ function forEachAsync(array, options, callbackfunction) {
1049
1050
  });
1050
1051
  }
1051
1052
 
1052
- var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.69.0-1",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",resultingParameterName:"knowledgePieces",dependentParameterNames:["knowledgeContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",promptbookVersion:"0.69.0-1",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",resultingParameterName:"keywords",dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",promptbookVersion:"0.69.0-1",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",resultingParameterName:"title",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",promptbookVersion:"0.69.0-1",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
1053
+ var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.69.0-4",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",resultingParameterName:"knowledgePieces",dependentParameterNames:["knowledgeContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",promptbookVersion:"0.69.0-4",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",resultingParameterName:"keywords",dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",promptbookVersion:"0.69.0-4",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",resultingParameterName:"title",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",promptbookVersion:"0.69.0-4",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
1053
1054
 
1054
1055
  /**
1055
1056
  * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
@@ -1300,12 +1301,12 @@ function validatePipelineCore(pipeline) {
1300
1301
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1301
1302
  if (!Array.isArray(pipeline.parameters)) {
1302
1303
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1303
- throw new ParseError(spaceTrim(function (block) { return "\n Promptbook is valid JSON but with wrong structure\n\n `promptbook.parameters` expected to be an array, but got ".concat(typeof pipeline.parameters, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1304
+ throw new ParseError(spaceTrim(function (block) { return "\n Pipeline is valid JSON but with wrong structure\n\n `PipelineJson.parameters` expected to be an array, but got ".concat(typeof pipeline.parameters, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1304
1305
  }
1305
1306
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1306
1307
  if (!Array.isArray(pipeline.templates)) {
1307
1308
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1308
- throw new ParseError(spaceTrim(function (block) { return "\n Promptbook is valid JSON but with wrong structure\n\n `promptbook.templates` expected to be an array, but got ".concat(typeof pipeline.templates, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1309
+ throw new ParseError(spaceTrim(function (block) { return "\n Pipeline is valid JSON but with wrong structure\n\n `PipelineJson.templates` expected to be an array, but got ".concat(typeof pipeline.templates, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1309
1310
  }
1310
1311
  var _loop_1 = function (parameter) {
1311
1312
  if (parameter.isInput && parameter.isOutput) {
@@ -2197,160 +2198,36 @@ function assertsExecutionSuccessful(executionResult) {
2197
2198
  */
2198
2199
 
2199
2200
  /**
2200
- * Parses the given script and returns the list of all used variables that are not defined in the script
2201
- *
2202
- * @param script from which to extract the variables
2203
- * @returns the list of variable names
2204
- * @throws {ParseError} if the script is invalid
2205
- * @public exported from `@promptbook/utils`
2206
- */
2207
- function extractVariables(script) {
2208
- var variables = new Set();
2209
- script = "(()=>{".concat(script, "})()");
2210
- try {
2211
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2212
- try {
2213
- eval(script);
2214
- }
2215
- catch (error) {
2216
- if (!(error instanceof ReferenceError)) {
2217
- throw error;
2218
- }
2219
- var undefinedName = error.message.split(' ')[0];
2220
- /*
2221
- Note: Parsing the error
2222
- [PipelineUrlError: thing is not defined]
2223
- */
2224
- if (!undefinedName) {
2225
- throw error;
2226
- }
2227
- if (script.includes(undefinedName + '(')) {
2228
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2229
- }
2230
- else {
2231
- variables.add(undefinedName);
2232
- script = "const ".concat(undefinedName, " = '';") + script;
2233
- }
2234
- }
2235
- }
2236
- catch (error) {
2237
- if (!(error instanceof Error)) {
2238
- throw error;
2239
- }
2240
- throw new ParseError(spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2241
- }
2242
- return variables;
2243
- }
2244
- /**
2245
- * TODO: [🔣] Support for multiple languages - python, java,...
2246
- */
2247
-
2248
- /**
2249
- * Parses the template and returns the set of all used parameters
2201
+ * Determine if the pipeline is fully prepared
2250
2202
  *
2251
- * @param template the template with used parameters
2252
- * @returns the set of parameter names
2253
- * @throws {ParseError} if the script is invalid
2254
- * @public exported from `@promptbook/utils`
2203
+ * @public exported from `@promptbook/core`
2255
2204
  */
2256
- function extractParameterNamesFromTemplate(template) {
2257
- var e_1, _a, e_2, _b, e_3, _c;
2258
- var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2259
- var parameterNames = new Set();
2260
- try {
2261
- for (var _d = __values(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameterNames(title)), false), __read(extractParameterNames(description || '')), false), __read(extractParameterNames(content)), false), __read(extractParameterNames(preparedContent || '')), false)), _e = _d.next(); !_e.done; _e = _d.next()) {
2262
- var parameterName = _e.value;
2263
- parameterNames.add(parameterName);
2264
- }
2265
- }
2266
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2267
- finally {
2268
- try {
2269
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2270
- }
2271
- finally { if (e_1) throw e_1.error; }
2272
- }
2273
- if (templateType === 'SCRIPT_TEMPLATE') {
2274
- try {
2275
- for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2276
- var parameterName = _g.value;
2277
- parameterNames.add(parameterName);
2278
- }
2279
- }
2280
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2281
- finally {
2282
- try {
2283
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2284
- }
2285
- finally { if (e_2) throw e_2.error; }
2286
- }
2287
- }
2288
- try {
2289
- for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2290
- var jokerName = _j.value;
2291
- parameterNames.add(jokerName);
2292
- }
2293
- }
2294
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2295
- finally {
2296
- try {
2297
- if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2298
- }
2299
- finally { if (e_3) throw e_3.error; }
2300
- }
2301
- parameterNames.delete('content');
2302
- // <- Note {websiteContent} is used in `preparedContent`
2303
- // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2304
- if (foreach !== undefined) {
2305
- if (parameterNames.has(foreach.subparameterName)) {
2306
- parameterNames.delete(foreach.subparameterName);
2307
- parameterNames.add(foreach.parameterName);
2308
- // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2309
- }
2205
+ function isPipelinePrepared(pipeline) {
2206
+ // Note: Ignoring `pipeline.preparations` @@@
2207
+ // Note: Ignoring `pipeline.knowledgePieces` @@@
2208
+ if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2209
+ return false;
2310
2210
  }
2311
- return parameterNames;
2312
- }
2313
- /**
2314
- * TODO: [🔣] If script require contentLanguage
2315
- */
2316
-
2317
- /**
2318
- * Serializes an error into a [🚉] JSON-serializable object
2319
- *
2320
- * @public exported from `@promptbook/utils`
2321
- */
2322
- function serializeError(error) {
2323
- var name = error.name, message = error.message, stack = error.stack;
2324
- if (!__spreadArray(['Error'], __read(Object.keys(ERRORS)), false).includes(name)) {
2325
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n \n Cannot serialize error with name \"".concat(name, "\"\n\n ").concat(block(stack || message), "\n \n "); }));
2211
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2212
+ return false;
2326
2213
  }
2327
- return {
2328
- name: name,
2329
- message: message,
2330
- stack: stack,
2331
- };
2214
+ /*
2215
+ TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2216
+ > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2217
+ > return false;
2218
+ > }
2219
+ */
2220
+ return true;
2332
2221
  }
2333
-
2334
2222
  /**
2335
- * Function isValidJsonString will tell you if the string is valid JSON or not
2336
- *
2337
- * @public exported from `@promptbook/utils`
2223
+ * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2224
+ * TODO: [🐠] Maybe base this on `makeValidator`
2225
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2226
+ * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2227
+ * - [🏍] ? Is context in each template
2228
+ * - [♨] Are samples prepared
2229
+ * - [♨] Are templates prepared
2338
2230
  */
2339
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
2340
- try {
2341
- JSON.parse(value);
2342
- return true;
2343
- }
2344
- catch (error) {
2345
- if (!(error instanceof Error)) {
2346
- throw error;
2347
- }
2348
- if (error.message.includes('Unexpected token')) {
2349
- return false;
2350
- }
2351
- return false;
2352
- }
2353
- }
2354
2231
 
2355
2232
  /**
2356
2233
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
@@ -2646,87 +2523,262 @@ function joinLlmExecutionTools() {
2646
2523
  */
2647
2524
 
2648
2525
  /**
2649
- * Extracts all code blocks from markdown.
2650
- *
2651
- * Note: There are multiple simmilar function:
2652
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2653
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2654
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2655
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2526
+ * Serializes an error into a [🚉] JSON-serializable object
2656
2527
  *
2657
- * @param markdown any valid markdown
2658
- * @returns code blocks with language and content
2659
- * @throws {ParseError} if block is not closed properly
2660
- * @public exported from `@promptbook/markdown-utils`
2528
+ * @public exported from `@promptbook/utils`
2661
2529
  */
2662
- function extractAllBlocksFromMarkdown(markdown) {
2663
- var e_1, _a;
2664
- var codeBlocks = [];
2665
- var lines = markdown.split('\n');
2666
- // Note: [0] Ensure that the last block notated by gt > will be closed
2667
- lines.push('');
2668
- var currentCodeBlock = null;
2669
- try {
2670
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2671
- var line = lines_1_1.value;
2672
- if (line.startsWith('> ') || line === '>') {
2673
- if (currentCodeBlock === null) {
2674
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2675
- } /* not else */
2676
- if (currentCodeBlock.blockNotation === '>') {
2677
- if (currentCodeBlock.content !== '') {
2678
- currentCodeBlock.content += '\n';
2679
- }
2680
- currentCodeBlock.content += line.slice(2);
2681
- }
2682
- }
2683
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2684
- codeBlocks.push(currentCodeBlock);
2685
- currentCodeBlock = null;
2686
- }
2687
- /* not else */
2688
- if (line.startsWith('```')) {
2689
- var language = line.slice(3).trim() || null;
2690
- if (currentCodeBlock === null) {
2691
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2692
- }
2693
- else {
2694
- if (language !== null) {
2695
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2696
- }
2697
- codeBlocks.push(currentCodeBlock);
2698
- currentCodeBlock = null;
2699
- }
2700
- }
2701
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2702
- if (currentCodeBlock.content !== '') {
2703
- currentCodeBlock.content += '\n';
2704
- }
2705
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2706
- }
2707
- }
2708
- }
2709
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2710
- finally {
2711
- try {
2712
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2713
- }
2714
- finally { if (e_1) throw e_1.error; }
2715
- }
2716
- if (currentCodeBlock !== null) {
2717
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2530
+ function serializeError(error) {
2531
+ var name = error.name, message = error.message, stack = error.stack;
2532
+ if (!__spreadArray(['Error'], __read(Object.keys(ERRORS)), false).includes(name)) {
2533
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n \n Cannot serialize error with name \"".concat(name, "\"\n\n ").concat(block(stack || message), "\n \n "); }));
2718
2534
  }
2719
- return codeBlocks;
2535
+ return {
2536
+ name: name,
2537
+ message: message,
2538
+ stack: stack,
2539
+ };
2720
2540
  }
2721
- /**
2722
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2723
- */
2724
2541
 
2725
2542
  /**
2726
- * Extracts extracts exactly one valid JSON code block
2543
+ * Takes an item or an array of items and returns an array of items
2727
2544
  *
2728
- * - When given string is a valid JSON as it is, it just returns it
2729
- * - When there is no JSON code block the function throws a `ParseError`
2545
+ * 1) Any item except array and undefined returns array with that one item (also null)
2546
+ * 2) Undefined returns empty array
2547
+ * 3) Array returns itself
2548
+ *
2549
+ * @private internal utility
2550
+ */
2551
+ function arrayableToArray(input) {
2552
+ if (input === undefined) {
2553
+ return [];
2554
+ }
2555
+ if (input instanceof Array) {
2556
+ return input;
2557
+ }
2558
+ return [input];
2559
+ }
2560
+
2561
+ /**
2562
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2563
+ *
2564
+ * @param script from which to extract the variables
2565
+ * @returns the list of variable names
2566
+ * @throws {ParseError} if the script is invalid
2567
+ * @public exported from `@promptbook/utils`
2568
+ */
2569
+ function extractVariables(script) {
2570
+ var variables = new Set();
2571
+ script = "(()=>{".concat(script, "})()");
2572
+ try {
2573
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2574
+ try {
2575
+ eval(script);
2576
+ }
2577
+ catch (error) {
2578
+ if (!(error instanceof ReferenceError)) {
2579
+ throw error;
2580
+ }
2581
+ var undefinedName = error.message.split(' ')[0];
2582
+ /*
2583
+ Note: Parsing the error
2584
+ [PipelineUrlError: thing is not defined]
2585
+ */
2586
+ if (!undefinedName) {
2587
+ throw error;
2588
+ }
2589
+ if (script.includes(undefinedName + '(')) {
2590
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2591
+ }
2592
+ else {
2593
+ variables.add(undefinedName);
2594
+ script = "const ".concat(undefinedName, " = '';") + script;
2595
+ }
2596
+ }
2597
+ }
2598
+ catch (error) {
2599
+ if (!(error instanceof Error)) {
2600
+ throw error;
2601
+ }
2602
+ throw new ParseError(spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2603
+ }
2604
+ return variables;
2605
+ }
2606
+ /**
2607
+ * TODO: [🔣] Support for multiple languages - python, java,...
2608
+ */
2609
+
2610
+ /**
2611
+ * Parses the template and returns the set of all used parameters
2612
+ *
2613
+ * @param template the template with used parameters
2614
+ * @returns the set of parameter names
2615
+ * @throws {ParseError} if the script is invalid
2616
+ * @public exported from `@promptbook/utils`
2617
+ */
2618
+ function extractParameterNamesFromTemplate(template) {
2619
+ var e_1, _a, e_2, _b, e_3, _c;
2620
+ var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2621
+ var parameterNames = new Set();
2622
+ try {
2623
+ for (var _d = __values(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameterNames(title)), false), __read(extractParameterNames(description || '')), false), __read(extractParameterNames(content)), false), __read(extractParameterNames(preparedContent || '')), false)), _e = _d.next(); !_e.done; _e = _d.next()) {
2624
+ var parameterName = _e.value;
2625
+ parameterNames.add(parameterName);
2626
+ }
2627
+ }
2628
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2629
+ finally {
2630
+ try {
2631
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2632
+ }
2633
+ finally { if (e_1) throw e_1.error; }
2634
+ }
2635
+ if (templateType === 'SCRIPT_TEMPLATE') {
2636
+ try {
2637
+ for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2638
+ var parameterName = _g.value;
2639
+ parameterNames.add(parameterName);
2640
+ }
2641
+ }
2642
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2643
+ finally {
2644
+ try {
2645
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2646
+ }
2647
+ finally { if (e_2) throw e_2.error; }
2648
+ }
2649
+ }
2650
+ try {
2651
+ for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2652
+ var jokerName = _j.value;
2653
+ parameterNames.add(jokerName);
2654
+ }
2655
+ }
2656
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
2657
+ finally {
2658
+ try {
2659
+ if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2660
+ }
2661
+ finally { if (e_3) throw e_3.error; }
2662
+ }
2663
+ parameterNames.delete('content');
2664
+ // <- Note {websiteContent} is used in `preparedContent`
2665
+ // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2666
+ if (foreach !== undefined) {
2667
+ if (parameterNames.has(foreach.subparameterName)) {
2668
+ parameterNames.delete(foreach.subparameterName);
2669
+ parameterNames.add(foreach.parameterName);
2670
+ // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2671
+ }
2672
+ }
2673
+ return parameterNames;
2674
+ }
2675
+ /**
2676
+ * TODO: [🔣] If script require contentLanguage
2677
+ */
2678
+
2679
+ /**
2680
+ * Function isValidJsonString will tell you if the string is valid JSON or not
2681
+ *
2682
+ * @public exported from `@promptbook/utils`
2683
+ */
2684
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
2685
+ try {
2686
+ JSON.parse(value);
2687
+ return true;
2688
+ }
2689
+ catch (error) {
2690
+ if (!(error instanceof Error)) {
2691
+ throw error;
2692
+ }
2693
+ if (error.message.includes('Unexpected token')) {
2694
+ return false;
2695
+ }
2696
+ return false;
2697
+ }
2698
+ }
2699
+
2700
+ /**
2701
+ * Extracts all code blocks from markdown.
2702
+ *
2703
+ * Note: There are multiple simmilar function:
2704
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2705
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
2706
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2707
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2708
+ *
2709
+ * @param markdown any valid markdown
2710
+ * @returns code blocks with language and content
2711
+ * @throws {ParseError} if block is not closed properly
2712
+ * @public exported from `@promptbook/markdown-utils`
2713
+ */
2714
+ function extractAllBlocksFromMarkdown(markdown) {
2715
+ var e_1, _a;
2716
+ var codeBlocks = [];
2717
+ var lines = markdown.split('\n');
2718
+ // Note: [0] Ensure that the last block notated by gt > will be closed
2719
+ lines.push('');
2720
+ var currentCodeBlock = null;
2721
+ try {
2722
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2723
+ var line = lines_1_1.value;
2724
+ if (line.startsWith('> ') || line === '>') {
2725
+ if (currentCodeBlock === null) {
2726
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2727
+ } /* not else */
2728
+ if (currentCodeBlock.blockNotation === '>') {
2729
+ if (currentCodeBlock.content !== '') {
2730
+ currentCodeBlock.content += '\n';
2731
+ }
2732
+ currentCodeBlock.content += line.slice(2);
2733
+ }
2734
+ }
2735
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2736
+ codeBlocks.push(currentCodeBlock);
2737
+ currentCodeBlock = null;
2738
+ }
2739
+ /* not else */
2740
+ if (line.startsWith('```')) {
2741
+ var language = line.slice(3).trim() || null;
2742
+ if (currentCodeBlock === null) {
2743
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2744
+ }
2745
+ else {
2746
+ if (language !== null) {
2747
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2748
+ }
2749
+ codeBlocks.push(currentCodeBlock);
2750
+ currentCodeBlock = null;
2751
+ }
2752
+ }
2753
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2754
+ if (currentCodeBlock.content !== '') {
2755
+ currentCodeBlock.content += '\n';
2756
+ }
2757
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2758
+ }
2759
+ }
2760
+ }
2761
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2762
+ finally {
2763
+ try {
2764
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2765
+ }
2766
+ finally { if (e_1) throw e_1.error; }
2767
+ }
2768
+ if (currentCodeBlock !== null) {
2769
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2770
+ }
2771
+ return codeBlocks;
2772
+ }
2773
+ /**
2774
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2775
+ */
2776
+
2777
+ /**
2778
+ * Extracts extracts exactly one valid JSON code block
2779
+ *
2780
+ * - When given string is a valid JSON as it is, it just returns it
2781
+ * - When there is no JSON code block the function throws a `ParseError`
2730
2782
  * - When there are multiple JSON code blocks the function throws a `ParseError`
2731
2783
  *
2732
2784
  * Note: It is not important if marked as ```json BUT if it is VALID JSON
@@ -2761,57 +2813,6 @@ function extractJsonBlock(markdown) {
2761
2813
  * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2762
2814
  */
2763
2815
 
2764
- /**
2765
- * Determine if the pipeline is fully prepared
2766
- *
2767
- * @public exported from `@promptbook/core`
2768
- */
2769
- function isPipelinePrepared(pipeline) {
2770
- // Note: Ignoring `pipeline.preparations` @@@
2771
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2772
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2773
- return false;
2774
- }
2775
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2776
- return false;
2777
- }
2778
- /*
2779
- TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2780
- > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2781
- > return false;
2782
- > }
2783
- */
2784
- return true;
2785
- }
2786
- /**
2787
- * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2788
- * TODO: [🐠] Maybe base this on `makeValidator`
2789
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2790
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2791
- * - [🏍] ? Is context in each template
2792
- * - [♨] Are samples prepared
2793
- * - [♨] Are templates prepared
2794
- */
2795
-
2796
- /**
2797
- * Takes an item or an array of items and returns an array of items
2798
- *
2799
- * 1) Any item except array and undefined returns array with that one item (also null)
2800
- * 2) Undefined returns empty array
2801
- * 3) Array returns itself
2802
- *
2803
- * @private internal utility
2804
- */
2805
- function arrayableToArray(input) {
2806
- if (input === undefined) {
2807
- return [];
2808
- }
2809
- if (input instanceof Array) {
2810
- return input;
2811
- }
2812
- return [input];
2813
- }
2814
-
2815
2816
  /**
2816
2817
  * Just says that the variable is not used but should be kept
2817
2818
  * No side effects.
@@ -2833,23 +2834,6 @@ function keepUnused() {
2833
2834
  }
2834
2835
  }
2835
2836
 
2836
- /**
2837
- * Just marks a place of place where should be something implemented
2838
- * No side effects.
2839
- *
2840
- * Note: It can be usefull suppressing eslint errors of unused variables
2841
- *
2842
- * @param value any values
2843
- * @returns void
2844
- * @private within the repository
2845
- */
2846
- function TODO_USE() {
2847
- var value = [];
2848
- for (var _i = 0; _i < arguments.length; _i++) {
2849
- value[_i] = arguments[_i];
2850
- }
2851
- }
2852
-
2853
2837
  /**
2854
2838
  * Replaces parameters in template with values from parameters object
2855
2839
  *
@@ -3079,44 +3063,659 @@ function countWords(text) {
3079
3063
  text = removeDiacritics(text);
3080
3064
  return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3081
3065
  }
3082
-
3066
+
3067
+ /**
3068
+ * Index of all counter functions
3069
+ *
3070
+ * @public exported from `@promptbook/utils`
3071
+ */
3072
+ var CountUtils = {
3073
+ CHARACTERS: countCharacters,
3074
+ WORDS: countWords,
3075
+ SENTENCES: countSentences,
3076
+ PARAGRAPHS: countParagraphs,
3077
+ LINES: countLines,
3078
+ PAGES: countPages,
3079
+ };
3080
+
3081
+ /**
3082
+ * Function checkExpectations will check if the expectations on given value are met
3083
+ *
3084
+ * Note: There are two simmilar functions:
3085
+ * - `checkExpectations` which throws an error if the expectations are not met
3086
+ * - `isPassingExpectations` which returns a boolean
3087
+ *
3088
+ * @throws {ExpectError} if the expectations are not met
3089
+ * @returns {void} Nothing
3090
+ * @private internal function of `createPipelineExecutor`
3091
+ */
3092
+ function checkExpectations(expectations, value) {
3093
+ var e_1, _a;
3094
+ try {
3095
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3096
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3097
+ var amount = CountUtils[unit.toUpperCase()](value);
3098
+ if (min && amount < min) {
3099
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3100
+ } /* not else */
3101
+ if (max && amount > max) {
3102
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3103
+ }
3104
+ }
3105
+ }
3106
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3107
+ finally {
3108
+ try {
3109
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3110
+ }
3111
+ finally { if (e_1) throw e_1.error; }
3112
+ }
3113
+ }
3114
+ /**
3115
+ * TODO: [💝] Unite object for expecting amount and format
3116
+ */
3117
+
3118
+ /**
3119
+ * Just marks a place of place where should be something implemented
3120
+ * No side effects.
3121
+ *
3122
+ * Note: It can be usefull suppressing eslint errors of unused variables
3123
+ *
3124
+ * @param value any values
3125
+ * @returns void
3126
+ * @private within the repository
3127
+ */
3128
+ function TODO_USE() {
3129
+ var value = [];
3130
+ for (var _i = 0; _i < arguments.length; _i++) {
3131
+ value[_i] = arguments[_i];
3132
+ }
3133
+ }
3134
+
3135
+ /**
3136
+ * @@@
3137
+ *
3138
+ * @private internal utility of `createPipelineExecutor`
3139
+ */
3140
+ function getContextForTemplate(template) {
3141
+ return __awaiter(this, void 0, void 0, function () {
3142
+ return __generator(this, function (_a) {
3143
+ TODO_USE(template);
3144
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3145
+ });
3146
+ });
3147
+ }
3148
+
3149
+ /**
3150
+ * @@@
3151
+ *
3152
+ * @private internal utility of `createPipelineExecutor`
3153
+ */
3154
+ function getKnowledgeForTemplate(options) {
3155
+ return __awaiter(this, void 0, void 0, function () {
3156
+ var preparedPipeline, template;
3157
+ return __generator(this, function (_a) {
3158
+ preparedPipeline = options.preparedPipeline, template = options.template;
3159
+ // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3160
+ TODO_USE(template);
3161
+ return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3162
+ var content = _a.content;
3163
+ return "- ".concat(content);
3164
+ }).join('\n')];
3165
+ });
3166
+ });
3167
+ }
3168
+
3169
+ /**
3170
+ * @@@
3171
+ *
3172
+ * @private internal utility of `createPipelineExecutor`
3173
+ */
3174
+ function getSamplesForTemplate(template) {
3175
+ return __awaiter(this, void 0, void 0, function () {
3176
+ return __generator(this, function (_a) {
3177
+ // TODO: [♨] Implement Better - use real index and keyword search
3178
+ TODO_USE(template);
3179
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3180
+ });
3181
+ });
3182
+ }
3183
+
3184
+ /**
3185
+ * @@@
3186
+ *
3187
+ * @private internal utility of `createPipelineExecutor`
3188
+ */
3189
+ function getReservedParametersForTemplate(options) {
3190
+ return __awaiter(this, void 0, void 0, function () {
3191
+ var preparedPipeline, template, pipelineIdentification, context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3192
+ var e_1, _a;
3193
+ return __generator(this, function (_b) {
3194
+ switch (_b.label) {
3195
+ case 0:
3196
+ preparedPipeline = options.preparedPipeline, template = options.template, pipelineIdentification = options.pipelineIdentification;
3197
+ return [4 /*yield*/, getContextForTemplate(template)];
3198
+ case 1:
3199
+ context = _b.sent();
3200
+ return [4 /*yield*/, getKnowledgeForTemplate({ preparedPipeline: preparedPipeline, template: template })];
3201
+ case 2:
3202
+ knowledge = _b.sent();
3203
+ return [4 /*yield*/, getSamplesForTemplate(template)];
3204
+ case 3:
3205
+ samples = _b.sent();
3206
+ currentDate = new Date().toISOString();
3207
+ modelName = RESERVED_PARAMETER_MISSING_VALUE;
3208
+ reservedParameters = {
3209
+ content: RESERVED_PARAMETER_RESTRICTED,
3210
+ context: context,
3211
+ knowledge: knowledge,
3212
+ samples: samples,
3213
+ currentDate: currentDate,
3214
+ modelName: modelName,
3215
+ };
3216
+ _loop_1 = function (parameterName) {
3217
+ if (reservedParameters[parameterName] === undefined) {
3218
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3219
+ }
3220
+ };
3221
+ try {
3222
+ // Note: Doublecheck that ALL reserved parameters are defined:
3223
+ for (RESERVED_PARAMETER_NAMES_1 = __values(RESERVED_PARAMETER_NAMES), RESERVED_PARAMETER_NAMES_1_1 = RESERVED_PARAMETER_NAMES_1.next(); !RESERVED_PARAMETER_NAMES_1_1.done; RESERVED_PARAMETER_NAMES_1_1 = RESERVED_PARAMETER_NAMES_1.next()) {
3224
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3225
+ _loop_1(parameterName);
3226
+ }
3227
+ }
3228
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3229
+ finally {
3230
+ try {
3231
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3232
+ }
3233
+ finally { if (e_1) throw e_1.error; }
3234
+ }
3235
+ return [2 /*return*/, reservedParameters];
3236
+ }
3237
+ });
3238
+ });
3239
+ }
3240
+
3241
+ /**
3242
+ * @@@
3243
+ *
3244
+ * @private internal utility of `createPipelineExecutor`
3245
+ */
3246
+ function executeTemplate(options) {
3247
+ return __awaiter(this, void 0, void 0, function () {
3248
+ var currentTemplate, preparedPipeline, parametersToPass, tools, llmTools, onProgress, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, name, title, priority, usedParameterNames, dependentParameterNames, definedParameters, _a, _b, _c, definedParameterNames, parameters, _loop_1, _d, _e, parameterName, prompt, chatResult, completionResult, embeddingResult, result, resultString, expectError, scriptPipelineExecutionErrors, maxAttempts, jokerParameterNames, preparedContent, _loop_2, attempt, state_1;
3249
+ var e_1, _f, _g;
3250
+ return __generator(this, function (_h) {
3251
+ switch (_h.label) {
3252
+ case 0:
3253
+ currentTemplate = options.currentTemplate, preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, tools = options.tools, llmTools = options.llmTools, onProgress = options.onProgress, settings = options.settings, $executionReport = options.$executionReport, pipelineIdentification = options.pipelineIdentification;
3254
+ maxExecutionAttempts = settings.maxExecutionAttempts;
3255
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
3256
+ title = currentTemplate.title;
3257
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3258
+ return [4 /*yield*/, onProgress({
3259
+ name: name,
3260
+ title: title,
3261
+ isStarted: false,
3262
+ isDone: false,
3263
+ templateType: currentTemplate.templateType,
3264
+ parameterName: currentTemplate.resultingParameterName,
3265
+ parameterValue: null,
3266
+ // <- [🍸]
3267
+ })];
3268
+ case 1:
3269
+ _h.sent();
3270
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3271
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3272
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3273
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Dependent parameters:\n ").concat(Array.from(dependentParameterNames)
3274
+ .map(function (name) { return "{".concat(name, "}"); })
3275
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3276
+ .map(function (name) { return "{".concat(name, "}"); })
3277
+ .join(', '), "\n\n "); }));
3278
+ }
3279
+ _b = (_a = Object).freeze;
3280
+ _c = [{}];
3281
+ return [4 /*yield*/, getReservedParametersForTemplate({
3282
+ preparedPipeline: preparedPipeline,
3283
+ template: currentTemplate,
3284
+ pipelineIdentification: pipelineIdentification,
3285
+ })];
3286
+ case 2:
3287
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3288
+ definedParameterNames = new Set(Object.keys(definedParameters));
3289
+ parameters = {};
3290
+ _loop_1 = function (parameterName) {
3291
+ // Situation: Parameter is defined and used
3292
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3293
+ parameters[parameterName] = definedParameters[parameterName];
3294
+ }
3295
+ // Situation: Parameter is defined but NOT used
3296
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3297
+ // Situation: Parameter is NOT defined BUT used
3298
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3299
+ // Houston, we have a problem
3300
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3301
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is NOT defined\n BUT used in template \"").concat(currentTemplate.title || currentTemplate.name, "\"\n\n This should be catched in `validatePipeline`\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3302
+ }
3303
+ };
3304
+ try {
3305
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3306
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3307
+ parameterName = _e.value;
3308
+ _loop_1(parameterName);
3309
+ }
3310
+ }
3311
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3312
+ finally {
3313
+ try {
3314
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3315
+ }
3316
+ finally { if (e_1) throw e_1.error; }
3317
+ }
3318
+ // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3319
+ Object.freeze(parameters);
3320
+ result = null;
3321
+ resultString = null;
3322
+ expectError = null;
3323
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3324
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
3325
+ preparedContent = (currentTemplate.preparedContent || '{content}')
3326
+ .split('{content}')
3327
+ .join(currentTemplate.content);
3328
+ _loop_2 = function (attempt) {
3329
+ var isJokerAttempt, jokerParameterName, _j, modelRequirements, _k, _l, _m, scriptTools, error_1, e_2_1, _o, _p, functionName, postprocessingError, _q, _r, scriptTools, error_2, e_3_1, e_4_1, error_3;
3330
+ var e_2, _s, e_4, _t, e_3, _u;
3331
+ return __generator(this, function (_v) {
3332
+ switch (_v.label) {
3333
+ case 0:
3334
+ isJokerAttempt = attempt < 0;
3335
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3336
+ // TODO: [🧠] !!!!!! JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3337
+ if (isJokerAttempt && !jokerParameterName) {
3338
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3339
+ }
3340
+ result = null;
3341
+ resultString = null;
3342
+ expectError = null;
3343
+ if (isJokerAttempt) {
3344
+ if (parameters[jokerParameterName] === undefined) {
3345
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3346
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3347
+ }
3348
+ else {
3349
+ resultString = parameters[jokerParameterName];
3350
+ }
3351
+ }
3352
+ _v.label = 1;
3353
+ case 1:
3354
+ _v.trys.push([1, 44, 45, 46]);
3355
+ if (!!isJokerAttempt) return [3 /*break*/, 26];
3356
+ _j = currentTemplate.templateType;
3357
+ switch (_j) {
3358
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3359
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3360
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3361
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3362
+ }
3363
+ return [3 /*break*/, 25];
3364
+ case 2:
3365
+ resultString = replaceParameters(preparedContent, parameters);
3366
+ return [3 /*break*/, 26];
3367
+ case 3:
3368
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3369
+ prompt = {
3370
+ title: currentTemplate.title,
3371
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3372
+ ? preparedPipeline.pipelineUrl
3373
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3374
+ parameters: parameters,
3375
+ content: preparedContent,
3376
+ modelRequirements: modelRequirements,
3377
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3378
+ var name = _a.name;
3379
+ return name === currentTemplate.personaName;
3380
+ }) || {})), currentTemplate.expectations),
3381
+ format: currentTemplate.format,
3382
+ postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3383
+ }; // <- TODO: Not very good type guard
3384
+ _k = modelRequirements.modelVariant;
3385
+ switch (_k) {
3386
+ case 'CHAT': return [3 /*break*/, 4];
3387
+ case 'COMPLETION': return [3 /*break*/, 6];
3388
+ case 'EMBEDDING': return [3 /*break*/, 8];
3389
+ }
3390
+ return [3 /*break*/, 10];
3391
+ case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3392
+ case 5:
3393
+ chatResult = _v.sent();
3394
+ // TODO: [🍬] Destroy chatThread
3395
+ result = chatResult;
3396
+ resultString = chatResult.content;
3397
+ return [3 /*break*/, 11];
3398
+ case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3399
+ case 7:
3400
+ completionResult = _v.sent();
3401
+ result = completionResult;
3402
+ resultString = completionResult.content;
3403
+ return [3 /*break*/, 11];
3404
+ case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3405
+ case 9:
3406
+ // TODO: [🧠] This is weird, embedding model can not be used such a way in the pipeline
3407
+ embeddingResult = _v.sent();
3408
+ result = embeddingResult;
3409
+ resultString = embeddingResult.content.join(',');
3410
+ return [3 /*break*/, 11];
3411
+ case 10: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements.modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3412
+ case 11: return [3 /*break*/, 26];
3413
+ case 12:
3414
+ if (arrayableToArray(tools.script).length === 0) {
3415
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3416
+ }
3417
+ if (!currentTemplate.contentLanguage) {
3418
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(currentTemplate.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3419
+ }
3420
+ // TODO: DRY [1]
3421
+ scriptPipelineExecutionErrors = [];
3422
+ _v.label = 13;
3423
+ case 13:
3424
+ _v.trys.push([13, 20, 21, 22]);
3425
+ _l = (e_2 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3426
+ _v.label = 14;
3427
+ case 14:
3428
+ if (!!_m.done) return [3 /*break*/, 19];
3429
+ scriptTools = _m.value;
3430
+ _v.label = 15;
3431
+ case 15:
3432
+ _v.trys.push([15, 17, , 18]);
3433
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3434
+ scriptLanguage: currentTemplate.contentLanguage,
3435
+ script: preparedContent,
3436
+ parameters: parameters,
3437
+ }))];
3438
+ case 16:
3439
+ resultString = _v.sent();
3440
+ return [3 /*break*/, 19];
3441
+ case 17:
3442
+ error_1 = _v.sent();
3443
+ if (!(error_1 instanceof Error)) {
3444
+ throw error_1;
3445
+ }
3446
+ if (error_1 instanceof UnexpectedError) {
3447
+ throw error_1;
3448
+ }
3449
+ scriptPipelineExecutionErrors.push(error_1);
3450
+ return [3 /*break*/, 18];
3451
+ case 18:
3452
+ _m = _l.next();
3453
+ return [3 /*break*/, 14];
3454
+ case 19: return [3 /*break*/, 22];
3455
+ case 20:
3456
+ e_2_1 = _v.sent();
3457
+ e_2 = { error: e_2_1 };
3458
+ return [3 /*break*/, 22];
3459
+ case 21:
3460
+ try {
3461
+ if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3462
+ }
3463
+ finally { if (e_2) throw e_2.error; }
3464
+ return [7 /*endfinally*/];
3465
+ case 22:
3466
+ if (resultString !== null) {
3467
+ return [3 /*break*/, 26];
3468
+ }
3469
+ if (scriptPipelineExecutionErrors.length === 1) {
3470
+ throw scriptPipelineExecutionErrors[0];
3471
+ }
3472
+ else {
3473
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptPipelineExecutionErrors.length, " times\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block(scriptPipelineExecutionErrors
3474
+ .map(function (error) { return '- ' + error.message; })
3475
+ .join('\n\n')), "\n "); }));
3476
+ }
3477
+ case 23:
3478
+ if (tools.userInterface === undefined) {
3479
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3480
+ }
3481
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3482
+ promptTitle: currentTemplate.title,
3483
+ promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3484
+ defaultValue: replaceParameters(preparedContent, parameters),
3485
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3486
+ placeholder: undefined,
3487
+ priority: priority,
3488
+ }))];
3489
+ case 24:
3490
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3491
+ resultString = _v.sent();
3492
+ return [3 /*break*/, 26];
3493
+ case 25: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3494
+ case 26:
3495
+ if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3496
+ _v.label = 27;
3497
+ case 27:
3498
+ _v.trys.push([27, 41, 42, 43]);
3499
+ _o = (e_4 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3500
+ _v.label = 28;
3501
+ case 28:
3502
+ if (!!_p.done) return [3 /*break*/, 40];
3503
+ functionName = _p.value;
3504
+ // TODO: DRY [1]
3505
+ scriptPipelineExecutionErrors = [];
3506
+ postprocessingError = null;
3507
+ _v.label = 29;
3508
+ case 29:
3509
+ _v.trys.push([29, 36, 37, 38]);
3510
+ _q = (e_3 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3511
+ _v.label = 30;
3512
+ case 30:
3513
+ if (!!_r.done) return [3 /*break*/, 35];
3514
+ scriptTools = _r.value;
3515
+ _v.label = 31;
3516
+ case 31:
3517
+ _v.trys.push([31, 33, , 34]);
3518
+ return [4 /*yield*/, scriptTools.execute({
3519
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3520
+ script: "".concat(functionName, "(resultString)"),
3521
+ parameters: {
3522
+ resultString: resultString || '',
3523
+ // Note: No ...parametersForTemplate, because working with result only
3524
+ },
3525
+ })];
3526
+ case 32:
3527
+ resultString = _v.sent();
3528
+ postprocessingError = null;
3529
+ return [3 /*break*/, 35];
3530
+ case 33:
3531
+ error_2 = _v.sent();
3532
+ if (!(error_2 instanceof Error)) {
3533
+ throw error_2;
3534
+ }
3535
+ if (error_2 instanceof UnexpectedError) {
3536
+ throw error_2;
3537
+ }
3538
+ postprocessingError = error_2;
3539
+ scriptPipelineExecutionErrors.push(error_2);
3540
+ return [3 /*break*/, 34];
3541
+ case 34:
3542
+ _r = _q.next();
3543
+ return [3 /*break*/, 30];
3544
+ case 35: return [3 /*break*/, 38];
3545
+ case 36:
3546
+ e_3_1 = _v.sent();
3547
+ e_3 = { error: e_3_1 };
3548
+ return [3 /*break*/, 38];
3549
+ case 37:
3550
+ try {
3551
+ if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3552
+ }
3553
+ finally { if (e_3) throw e_3.error; }
3554
+ return [7 /*endfinally*/];
3555
+ case 38:
3556
+ if (postprocessingError) {
3557
+ throw postprocessingError;
3558
+ }
3559
+ _v.label = 39;
3560
+ case 39:
3561
+ _p = _o.next();
3562
+ return [3 /*break*/, 28];
3563
+ case 40: return [3 /*break*/, 43];
3564
+ case 41:
3565
+ e_4_1 = _v.sent();
3566
+ e_4 = { error: e_4_1 };
3567
+ return [3 /*break*/, 43];
3568
+ case 42:
3569
+ try {
3570
+ if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3571
+ }
3572
+ finally { if (e_4) throw e_4.error; }
3573
+ return [7 /*endfinally*/];
3574
+ case 43:
3575
+ // TODO: [💝] Unite object for expecting amount and format
3576
+ if (currentTemplate.format) {
3577
+ if (currentTemplate.format === 'JSON') {
3578
+ if (!isValidJsonString(resultString || '')) {
3579
+ // TODO: [🏢] Do more universally via `FormatDefinition`
3580
+ try {
3581
+ resultString = extractJsonBlock(resultString || '');
3582
+ }
3583
+ catch (error) {
3584
+ keepUnused(error);
3585
+ throw new ExpectError(spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3586
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3587
+ }
3588
+ }
3589
+ }
3590
+ else {
3591
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3592
+ }
3593
+ }
3594
+ // TODO: [💝] Unite object for expecting amount and format
3595
+ if (currentTemplate.expectations) {
3596
+ checkExpectations(currentTemplate.expectations, resultString || '');
3597
+ }
3598
+ return [2 /*return*/, "break-attempts"];
3599
+ case 44:
3600
+ error_3 = _v.sent();
3601
+ if (!(error_3 instanceof ExpectError)) {
3602
+ throw error_3;
3603
+ }
3604
+ expectError = error_3;
3605
+ return [3 /*break*/, 46];
3606
+ case 45:
3607
+ if (!isJokerAttempt &&
3608
+ currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3609
+ prompt
3610
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3611
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
3612
+ ) {
3613
+ // TODO: [🧠] Maybe put other templateTypes into report
3614
+ $executionReport.promptExecutions.push({
3615
+ prompt: __assign({}, prompt),
3616
+ result: result || undefined,
3617
+ error: expectError === null ? undefined : serializeError(expectError),
3618
+ });
3619
+ }
3620
+ return [7 /*endfinally*/];
3621
+ case 46:
3622
+ if (expectError !== null && attempt === maxAttempts - 1) {
3623
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ").concat(block(pipelineIdentification), "\n\n ---\n The Prompt:\n ").concat(block(prompt.content
3624
+ .split('\n')
3625
+ .map(function (line) { return "> ".concat(line); })
3626
+ .join('\n')), "\n\n Last error ").concat((expectError === null || expectError === void 0 ? void 0 : expectError.name) || '', ":\n ").concat(block(((expectError === null || expectError === void 0 ? void 0 : expectError.message) || '')
3627
+ .split('\n')
3628
+ .map(function (line) { return "> ".concat(line); })
3629
+ .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3630
+ ? 'null'
3631
+ : resultString
3632
+ .split('\n')
3633
+ .map(function (line) { return "> ".concat(line); })
3634
+ .join('\n')), "\n ---\n "); }));
3635
+ }
3636
+ return [2 /*return*/];
3637
+ }
3638
+ });
3639
+ };
3640
+ attempt = -jokerParameterNames.length;
3641
+ _h.label = 3;
3642
+ case 3:
3643
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 6];
3644
+ return [5 /*yield**/, _loop_2(attempt)];
3645
+ case 4:
3646
+ state_1 = _h.sent();
3647
+ switch (state_1) {
3648
+ case "break-attempts": return [3 /*break*/, 6];
3649
+ }
3650
+ _h.label = 5;
3651
+ case 5:
3652
+ attempt++;
3653
+ return [3 /*break*/, 3];
3654
+ case 6:
3655
+ //------------------------------------
3656
+ /*
3657
+
3658
+
3659
+
3660
+
3661
+
3662
+
3663
+
3664
+
3665
+
3666
+ */
3667
+ //------------------------------------
3668
+ if (resultString === null) {
3669
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3670
+ }
3671
+ return [4 /*yield*/, onProgress({
3672
+ name: name,
3673
+ title: title,
3674
+ isStarted: true,
3675
+ isDone: true,
3676
+ templateType: currentTemplate.templateType,
3677
+ parameterName: currentTemplate.resultingParameterName,
3678
+ parameterValue: resultString,
3679
+ // <- [🍸]
3680
+ })];
3681
+ case 7:
3682
+ _h.sent();
3683
+ return [2 /*return*/, Object.freeze((_g = {},
3684
+ _g[currentTemplate.resultingParameterName] = resultString /* <- Note: Not need to detect parameter collision here because pipeline checks logic consistency during construction */,
3685
+ _g))];
3686
+ }
3687
+ });
3688
+ });
3689
+ }
3083
3690
  /**
3084
- * Index of all counter functions
3085
- *
3086
- * @public exported from `@promptbook/utils`
3691
+ * TODO: [🤹‍♂️]
3087
3692
  */
3088
- var CountUtils = {
3089
- CHARACTERS: countCharacters,
3090
- WORDS: countWords,
3091
- SENTENCES: countSentences,
3092
- PARAGRAPHS: countParagraphs,
3093
- LINES: countLines,
3094
- PAGES: countPages,
3095
- };
3096
3693
 
3097
3694
  /**
3098
- * Function checkExpectations will check if the expectations on given value are met
3099
- *
3100
- * Note: There are two simmilar functions:
3101
- * - `checkExpectations` which throws an error if the expectations are not met
3102
- * - `isPassingExpectations` which returns a boolean
3695
+ * @@@
3103
3696
  *
3104
- * @throws {ExpectError} if the expectations are not met
3105
- * @returns {void} Nothing
3106
- * @private internal function of `createPipelineExecutor`
3697
+ * @private internal utility of `createPipelineExecutor`
3107
3698
  */
3108
- function checkExpectations(expectations, value) {
3699
+ function filterJustOutputParameters(options) {
3109
3700
  var e_1, _a;
3701
+ var preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, $warnings = options.$warnings, pipelineIdentification = options.pipelineIdentification;
3702
+ var outputParameters = {};
3703
+ var _loop_1 = function (parameter) {
3704
+ if (parametersToPass[parameter.name] === undefined) {
3705
+ // [4]
3706
+ $warnings.push(new PipelineExecutionError(spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution\n\n ").concat(block(pipelineIdentification), "\n "); })));
3707
+ return "continue";
3708
+ }
3709
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3710
+ };
3110
3711
  try {
3111
- for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3112
- var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3113
- var amount = CountUtils[unit.toUpperCase()](value);
3114
- if (min && amount < min) {
3115
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3116
- } /* not else */
3117
- if (max && amount > max) {
3118
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3119
- }
3712
+ // Note: Filter ONLY output parameters
3713
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3714
+ var isOutput = _a.isOutput;
3715
+ return isOutput;
3716
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
3717
+ var parameter = _c.value;
3718
+ _loop_1(parameter);
3120
3719
  }
3121
3720
  }
3122
3721
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
@@ -3126,614 +3725,27 @@ function checkExpectations(expectations, value) {
3126
3725
  }
3127
3726
  finally { if (e_1) throw e_1.error; }
3128
3727
  }
3728
+ return outputParameters;
3129
3729
  }
3130
- /**
3131
- * TODO: [💝] Unite object for expecting amount and format
3132
- */
3133
3730
 
3134
3731
  /**
3135
- * Creates executor function from pipeline and execution tools.
3732
+ * @@@
3136
3733
  *
3137
- * @returns The executor function
3138
- * @throws {PipelineLogicError} on logical error in the pipeline
3139
- * @public exported from `@promptbook/core`
3734
+ * Note: This is not a `PipelineExecutor` (which is binded with one exact pipeline), but a utility function of `createPipelineExecutor` which creates `PipelineExecutor`
3735
+ *
3736
+ * @private internal utility of `createPipelineExecutor`
3140
3737
  */
3141
- function createPipelineExecutor(options) {
3142
- var _this = this;
3143
- var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
3144
- var _b = settings.maxExecutionAttempts, maxExecutionAttempts = _b === void 0 ? MAX_EXECUTION_ATTEMPTS : _b, _c = settings.maxParallelCount, maxParallelCount = _c === void 0 ? MAX_PARALLEL_COUNT : _c, _d = settings.isVerbose, isVerbose = _d === void 0 ? IS_VERBOSE : _d, _e = settings.isNotPreparedWarningSupressed, isNotPreparedWarningSupressed = _e === void 0 ? false : _e;
3145
- validatePipeline(pipeline);
3146
- var pipelineIdentification = (function () {
3147
- // Note: This is a 😐 implementation of [🚞]
3148
- var _ = [];
3149
- if (pipeline.sourceFile !== undefined) {
3150
- _.push("File: ".concat(pipeline.sourceFile));
3151
- }
3152
- if (pipeline.pipelineUrl !== undefined) {
3153
- _.push("Url: ".concat(pipeline.pipelineUrl));
3154
- }
3155
- return _.join('\n');
3156
- })();
3157
- var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3158
- var preparedPipeline;
3159
- if (isPipelinePrepared(pipeline)) {
3160
- preparedPipeline = pipeline;
3161
- }
3162
- else if (isNotPreparedWarningSupressed !== true) {
3163
- console.warn(spaceTrim(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
3164
- }
3165
- var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
3166
- // TODO: !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
3167
- function getContextForTemplate(template) {
3168
- return __awaiter(this, void 0, void 0, function () {
3169
- return __generator(this, function (_a) {
3170
- TODO_USE(template);
3171
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3172
- });
3173
- });
3174
- }
3175
- function getKnowledgeForTemplate(template) {
3176
- return __awaiter(this, void 0, void 0, function () {
3177
- return __generator(this, function (_a) {
3178
- // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3179
- TODO_USE(template);
3180
- return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3181
- var content = _a.content;
3182
- return "- ".concat(content);
3183
- }).join('\n')];
3184
- });
3185
- });
3186
- }
3187
- function getSamplesForTemplate(template) {
3188
- return __awaiter(this, void 0, void 0, function () {
3189
- return __generator(this, function (_a) {
3190
- // TODO: [♨] Implement Better - use real index and keyword search
3191
- TODO_USE(template);
3192
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3193
- });
3194
- });
3195
- }
3196
- function getReservedParametersForTemplate(template) {
3197
- return __awaiter(this, void 0, void 0, function () {
3198
- var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3199
- var e_3, _a;
3200
- return __generator(this, function (_b) {
3201
- switch (_b.label) {
3202
- case 0: return [4 /*yield*/, getContextForTemplate(template)];
3203
- case 1:
3204
- context = _b.sent();
3205
- return [4 /*yield*/, getKnowledgeForTemplate(template)];
3206
- case 2:
3207
- knowledge = _b.sent();
3208
- return [4 /*yield*/, getSamplesForTemplate(template)];
3209
- case 3:
3210
- samples = _b.sent();
3211
- currentDate = new Date().toISOString();
3212
- modelName = RESERVED_PARAMETER_MISSING_VALUE;
3213
- reservedParameters = {
3214
- content: RESERVED_PARAMETER_RESTRICTED,
3215
- context: context,
3216
- knowledge: knowledge,
3217
- samples: samples,
3218
- currentDate: currentDate,
3219
- modelName: modelName,
3220
- };
3221
- _loop_3 = function (parameterName) {
3222
- if (reservedParameters[parameterName] === undefined) {
3223
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3224
- }
3225
- };
3226
- try {
3227
- // Note: Doublecheck that ALL reserved parameters are defined:
3228
- for (RESERVED_PARAMETER_NAMES_1 = __values(RESERVED_PARAMETER_NAMES), RESERVED_PARAMETER_NAMES_1_1 = RESERVED_PARAMETER_NAMES_1.next(); !RESERVED_PARAMETER_NAMES_1_1.done; RESERVED_PARAMETER_NAMES_1_1 = RESERVED_PARAMETER_NAMES_1.next()) {
3229
- parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3230
- _loop_3(parameterName);
3231
- }
3232
- }
3233
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
3234
- finally {
3235
- try {
3236
- if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3237
- }
3238
- finally { if (e_3) throw e_3.error; }
3239
- }
3240
- return [2 /*return*/, reservedParameters];
3241
- }
3242
- });
3243
- });
3244
- }
3245
- function executeSingleTemplate(currentTemplate) {
3246
- return __awaiter(this, void 0, void 0, function () {
3247
- var name, title, priority, progress_1, usedParameterNames, dependentParameterNames, definedParameters, _a, _b, _c, definedParameterNames, parameters, _loop_4, _d, _e, parameterName, prompt, chatResult, completionResult, embeddingResult, result, resultString, expectError, scriptPipelineExecutionErrors, maxAttempts, jokerParameterNames, preparedContent, _loop_5, attempt, state_2, progress_2;
3248
- var e_4, _f, _g;
3249
- return __generator(this, function (_h) {
3250
- switch (_h.label) {
3251
- case 0:
3252
- name = "pipeline-executor-frame-".concat(currentTemplate.name);
3253
- title = currentTemplate.title;
3254
- priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3255
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
3256
- progress_1 = {
3257
- name: name,
3258
- title: title,
3259
- isStarted: false,
3260
- isDone: false,
3261
- templateType: currentTemplate.templateType,
3262
- parameterName: currentTemplate.resultingParameterName,
3263
- parameterValue: null,
3264
- // <- [3]
3265
- };
3266
- if (isReturned) {
3267
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4F\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_1, null, 4)
3268
- .split('\n')
3269
- .map(function (line) { return "> ".concat(line); })
3270
- .join('\n')), "\n "); }));
3271
- }
3272
- return [4 /*yield*/, onProgress(progress_1)];
3273
- case 1:
3274
- _h.sent();
3275
- _h.label = 2;
3276
- case 2:
3277
- usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3278
- dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3279
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3280
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Dependent parameters:\n ").concat(Array.from(dependentParameterNames)
3281
- .map(function (name) { return "{".concat(name, "}"); })
3282
- .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3283
- .map(function (name) { return "{".concat(name, "}"); })
3284
- .join(', '), "\n\n "); }));
3285
- }
3286
- _b = (_a = Object).freeze;
3287
- _c = [{}];
3288
- return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
3289
- case 3:
3290
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3291
- definedParameterNames = new Set(Object.keys(definedParameters));
3292
- parameters = {};
3293
- _loop_4 = function (parameterName) {
3294
- // Situation: Parameter is defined and used
3295
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3296
- parameters[parameterName] = definedParameters[parameterName];
3297
- }
3298
- // Situation: Parameter is defined but NOT used
3299
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3300
- // Situation: Parameter is NOT defined BUT used
3301
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3302
- // Houston, we have a problem
3303
- // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3304
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is NOT defined\n BUT used in template \"").concat(currentTemplate.title || currentTemplate.name, "\"\n\n This should be catched in `validatePipeline`\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3305
- }
3306
- };
3307
- try {
3308
- // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3309
- for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3310
- parameterName = _e.value;
3311
- _loop_4(parameterName);
3312
- }
3313
- }
3314
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
3315
- finally {
3316
- try {
3317
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3318
- }
3319
- finally { if (e_4) throw e_4.error; }
3320
- }
3321
- // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3322
- Object.freeze(parameters);
3323
- result = null;
3324
- resultString = null;
3325
- expectError = null;
3326
- maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3327
- jokerParameterNames = currentTemplate.jokerParameterNames || [];
3328
- preparedContent = (currentTemplate.preparedContent || '{content}')
3329
- .split('{content}')
3330
- .join(currentTemplate.content);
3331
- _loop_5 = function (attempt) {
3332
- var isJokerAttempt, jokerParameterName, _j, modelRequirements, _k, _l, _m, scriptTools, error_2, e_5_1, _o, _p, functionName, postprocessingError, _q, _r, scriptTools, error_3, e_6_1, e_7_1, error_4;
3333
- var e_5, _s, e_7, _t, e_6, _u;
3334
- return __generator(this, function (_v) {
3335
- switch (_v.label) {
3336
- case 0:
3337
- isJokerAttempt = attempt < 0;
3338
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3339
- // TODO: [🧠] !!!!!! JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3340
- if (isJokerAttempt && !jokerParameterName) {
3341
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3342
- }
3343
- result = null;
3344
- resultString = null;
3345
- expectError = null;
3346
- if (isJokerAttempt) {
3347
- if (parameters[jokerParameterName] === undefined) {
3348
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3349
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3350
- }
3351
- else {
3352
- resultString = parameters[jokerParameterName];
3353
- }
3354
- }
3355
- _v.label = 1;
3356
- case 1:
3357
- _v.trys.push([1, 44, 45, 46]);
3358
- if (!!isJokerAttempt) return [3 /*break*/, 26];
3359
- _j = currentTemplate.templateType;
3360
- switch (_j) {
3361
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3362
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3363
- case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3364
- case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3365
- }
3366
- return [3 /*break*/, 25];
3367
- case 2:
3368
- resultString = replaceParameters(preparedContent, parameters);
3369
- return [3 /*break*/, 26];
3370
- case 3:
3371
- modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (pipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3372
- prompt = {
3373
- title: currentTemplate.title,
3374
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3375
- ? preparedPipeline.pipelineUrl
3376
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3377
- parameters: parameters,
3378
- content: preparedContent,
3379
- modelRequirements: modelRequirements,
3380
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3381
- var name = _a.name;
3382
- return name === currentTemplate.personaName;
3383
- }) || {})), currentTemplate.expectations),
3384
- format: currentTemplate.format,
3385
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3386
- }; // <- TODO: Not very good type guard
3387
- _k = modelRequirements.modelVariant;
3388
- switch (_k) {
3389
- case 'CHAT': return [3 /*break*/, 4];
3390
- case 'COMPLETION': return [3 /*break*/, 6];
3391
- case 'EMBEDDING': return [3 /*break*/, 8];
3392
- }
3393
- return [3 /*break*/, 10];
3394
- case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3395
- case 5:
3396
- chatResult = _v.sent();
3397
- // TODO: [🍬] Destroy chatThread
3398
- result = chatResult;
3399
- resultString = chatResult.content;
3400
- return [3 /*break*/, 11];
3401
- case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3402
- case 7:
3403
- completionResult = _v.sent();
3404
- result = completionResult;
3405
- resultString = completionResult.content;
3406
- return [3 /*break*/, 11];
3407
- case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3408
- case 9:
3409
- embeddingResult = _v.sent();
3410
- result = embeddingResult;
3411
- resultString = embeddingResult.content.join(',');
3412
- return [3 /*break*/, 11];
3413
- case 10: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements
3414
- .modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3415
- case 11: return [3 /*break*/, 26];
3416
- case 12:
3417
- if (arrayableToArray(tools.script).length === 0) {
3418
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3419
- }
3420
- if (!currentTemplate.contentLanguage) {
3421
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(currentTemplate.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3422
- }
3423
- // TODO: DRY [1]
3424
- scriptPipelineExecutionErrors = [];
3425
- _v.label = 13;
3426
- case 13:
3427
- _v.trys.push([13, 20, 21, 22]);
3428
- _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3429
- _v.label = 14;
3430
- case 14:
3431
- if (!!_m.done) return [3 /*break*/, 19];
3432
- scriptTools = _m.value;
3433
- _v.label = 15;
3434
- case 15:
3435
- _v.trys.push([15, 17, , 18]);
3436
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3437
- scriptLanguage: currentTemplate.contentLanguage,
3438
- script: preparedContent,
3439
- parameters: parameters,
3440
- }))];
3441
- case 16:
3442
- resultString = _v.sent();
3443
- return [3 /*break*/, 19];
3444
- case 17:
3445
- error_2 = _v.sent();
3446
- if (!(error_2 instanceof Error)) {
3447
- throw error_2;
3448
- }
3449
- if (error_2 instanceof UnexpectedError) {
3450
- throw error_2;
3451
- }
3452
- scriptPipelineExecutionErrors.push(error_2);
3453
- return [3 /*break*/, 18];
3454
- case 18:
3455
- _m = _l.next();
3456
- return [3 /*break*/, 14];
3457
- case 19: return [3 /*break*/, 22];
3458
- case 20:
3459
- e_5_1 = _v.sent();
3460
- e_5 = { error: e_5_1 };
3461
- return [3 /*break*/, 22];
3462
- case 21:
3463
- try {
3464
- if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3465
- }
3466
- finally { if (e_5) throw e_5.error; }
3467
- return [7 /*endfinally*/];
3468
- case 22:
3469
- if (resultString !== null) {
3470
- return [3 /*break*/, 26];
3471
- }
3472
- if (scriptPipelineExecutionErrors.length === 1) {
3473
- throw scriptPipelineExecutionErrors[0];
3474
- }
3475
- else {
3476
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptPipelineExecutionErrors.length, " times\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block(scriptPipelineExecutionErrors
3477
- .map(function (error) { return '- ' + error.message; })
3478
- .join('\n\n')), "\n "); }));
3479
- }
3480
- case 23:
3481
- if (tools.userInterface === undefined) {
3482
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3483
- }
3484
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3485
- promptTitle: currentTemplate.title,
3486
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3487
- defaultValue: replaceParameters(preparedContent, parameters),
3488
- // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3489
- placeholder: undefined,
3490
- priority: priority,
3491
- }))];
3492
- case 24:
3493
- // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3494
- resultString = _v.sent();
3495
- return [3 /*break*/, 26];
3496
- case 25: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3497
- case 26:
3498
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3499
- _v.label = 27;
3500
- case 27:
3501
- _v.trys.push([27, 41, 42, 43]);
3502
- _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3503
- _v.label = 28;
3504
- case 28:
3505
- if (!!_p.done) return [3 /*break*/, 40];
3506
- functionName = _p.value;
3507
- // TODO: DRY [1]
3508
- scriptPipelineExecutionErrors = [];
3509
- postprocessingError = null;
3510
- _v.label = 29;
3511
- case 29:
3512
- _v.trys.push([29, 36, 37, 38]);
3513
- _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3514
- _v.label = 30;
3515
- case 30:
3516
- if (!!_r.done) return [3 /*break*/, 35];
3517
- scriptTools = _r.value;
3518
- _v.label = 31;
3519
- case 31:
3520
- _v.trys.push([31, 33, , 34]);
3521
- return [4 /*yield*/, scriptTools.execute({
3522
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3523
- script: "".concat(functionName, "(resultString)"),
3524
- parameters: {
3525
- resultString: resultString || '',
3526
- // Note: No ...parametersForTemplate, because working with result only
3527
- },
3528
- })];
3529
- case 32:
3530
- resultString = _v.sent();
3531
- postprocessingError = null;
3532
- return [3 /*break*/, 35];
3533
- case 33:
3534
- error_3 = _v.sent();
3535
- if (!(error_3 instanceof Error)) {
3536
- throw error_3;
3537
- }
3538
- if (error_3 instanceof UnexpectedError) {
3539
- throw error_3;
3540
- }
3541
- postprocessingError = error_3;
3542
- scriptPipelineExecutionErrors.push(error_3);
3543
- return [3 /*break*/, 34];
3544
- case 34:
3545
- _r = _q.next();
3546
- return [3 /*break*/, 30];
3547
- case 35: return [3 /*break*/, 38];
3548
- case 36:
3549
- e_6_1 = _v.sent();
3550
- e_6 = { error: e_6_1 };
3551
- return [3 /*break*/, 38];
3552
- case 37:
3553
- try {
3554
- if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3555
- }
3556
- finally { if (e_6) throw e_6.error; }
3557
- return [7 /*endfinally*/];
3558
- case 38:
3559
- if (postprocessingError) {
3560
- throw postprocessingError;
3561
- }
3562
- _v.label = 39;
3563
- case 39:
3564
- _p = _o.next();
3565
- return [3 /*break*/, 28];
3566
- case 40: return [3 /*break*/, 43];
3567
- case 41:
3568
- e_7_1 = _v.sent();
3569
- e_7 = { error: e_7_1 };
3570
- return [3 /*break*/, 43];
3571
- case 42:
3572
- try {
3573
- if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3574
- }
3575
- finally { if (e_7) throw e_7.error; }
3576
- return [7 /*endfinally*/];
3577
- case 43:
3578
- // TODO: [💝] Unite object for expecting amount and format
3579
- if (currentTemplate.format) {
3580
- if (currentTemplate.format === 'JSON') {
3581
- if (!isValidJsonString(resultString || '')) {
3582
- // TODO: [🏢] Do more universally via `FormatDefinition`
3583
- try {
3584
- resultString = extractJsonBlock(resultString || '');
3585
- }
3586
- catch (error) {
3587
- keepUnused(error);
3588
- throw new ExpectError(spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3589
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3590
- }
3591
- }
3592
- }
3593
- else {
3594
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3595
- }
3596
- }
3597
- // TODO: [💝] Unite object for expecting amount and format
3598
- if (currentTemplate.expectations) {
3599
- checkExpectations(currentTemplate.expectations, resultString || '');
3600
- }
3601
- return [2 /*return*/, "break-attempts"];
3602
- case 44:
3603
- error_4 = _v.sent();
3604
- if (!(error_4 instanceof ExpectError)) {
3605
- throw error_4;
3606
- }
3607
- expectError = error_4;
3608
- return [3 /*break*/, 46];
3609
- case 45:
3610
- if (!isJokerAttempt &&
3611
- currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3612
- prompt
3613
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3614
- // In that case we don’t want to make a report about it because it’s not a llm execution error
3615
- ) {
3616
- // TODO: [🧠] Maybe put other templateTypes into report
3617
- executionReport.promptExecutions.push({
3618
- prompt: __assign({}, prompt),
3619
- result: result || undefined,
3620
- error: expectError === null ? undefined : serializeError(expectError),
3621
- });
3622
- }
3623
- return [7 /*endfinally*/];
3624
- case 46:
3625
- if (expectError !== null && attempt === maxAttempts - 1) {
3626
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ").concat(block(pipelineIdentification), "\n\n ---\n The Prompt:\n ").concat(block(prompt.content
3627
- .split('\n')
3628
- .map(function (line) { return "> ".concat(line); })
3629
- .join('\n')), "\n\n Last error ").concat((expectError === null || expectError === void 0 ? void 0 : expectError.name) || '', ":\n ").concat(block(((expectError === null || expectError === void 0 ? void 0 : expectError.message) || '')
3630
- .split('\n')
3631
- .map(function (line) { return "> ".concat(line); })
3632
- .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3633
- ? 'null'
3634
- : resultString
3635
- .split('\n')
3636
- .map(function (line) { return "> ".concat(line); })
3637
- .join('\n')), "\n ---\n "); }));
3638
- }
3639
- return [2 /*return*/];
3640
- }
3641
- });
3642
- };
3643
- attempt = -jokerParameterNames.length;
3644
- _h.label = 4;
3645
- case 4:
3646
- if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3647
- return [5 /*yield**/, _loop_5(attempt)];
3648
- case 5:
3649
- state_2 = _h.sent();
3650
- switch (state_2) {
3651
- case "break-attempts": return [3 /*break*/, 7];
3652
- }
3653
- _h.label = 6;
3654
- case 6:
3655
- attempt++;
3656
- return [3 /*break*/, 4];
3657
- case 7:
3658
- //------------------------------------
3659
- /*
3660
-
3661
-
3662
-
3663
-
3664
-
3665
-
3666
-
3667
-
3668
-
3669
- */
3670
- //------------------------------------
3671
- if (resultString === null) {
3672
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3673
- }
3674
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 9]; /* <- [3] */
3675
- progress_2 = {
3676
- name: name,
3677
- title: title,
3678
- isStarted: true,
3679
- isDone: true,
3680
- templateType: currentTemplate.templateType,
3681
- parameterName: currentTemplate.resultingParameterName,
3682
- parameterValue: resultString,
3683
- // <- [3]
3684
- };
3685
- if (isReturned) {
3686
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4E\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_2, null, 4)
3687
- .split('\n')
3688
- .map(function (line) { return "> ".concat(line); })
3689
- .join('\n')), "\n\n "); }));
3690
- }
3691
- return [4 /*yield*/, onProgress(progress_2)];
3692
- case 8:
3693
- _h.sent();
3694
- _h.label = 9;
3695
- case 9:
3696
- parametersToPass = Object.freeze(__assign(__assign({}, parametersToPass), (_g = {}, _g[currentTemplate.resultingParameterName] = resultString /* <- Note: Not need to detect parameter collision here because pipeline checks logic consistency during construction */, _g)));
3697
- return [2 /*return*/];
3698
- }
3699
- });
3700
- });
3701
- }
3702
- function filterJustOutputParameters() {
3703
- var e_8, _a;
3704
- var outputParameters = {};
3705
- var _loop_6 = function (parameter) {
3706
- if (parametersToPass[parameter.name] === undefined) {
3707
- // [4]
3708
- warnings.push(new PipelineExecutionError(spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution\n\n ").concat(block(pipelineIdentification), "\n "); })));
3709
- return "continue";
3710
- }
3711
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3712
- };
3713
- try {
3714
- // Note: Filter ONLY output parameters
3715
- for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3716
- var isOutput = _a.isOutput;
3717
- return isOutput;
3718
- })), _c = _b.next(); !_c.done; _c = _b.next()) {
3719
- var parameter = _c.value;
3720
- _loop_6(parameter);
3721
- }
3722
- }
3723
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
3724
- finally {
3725
- try {
3726
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3727
- }
3728
- finally { if (e_8) throw e_8.error; }
3729
- }
3730
- return outputParameters;
3731
- }
3732
- var errors, warnings, executionReport, isReturned, _a, _b, parameter, e_1_1, _loop_1, _c, _d, parameterName, state_1, e_2_1, parametersToPass, resovedParameterNames_1, unresovedTemplates_1, resolving_1, loopLimit, _loop_2, error_1, usage_1, outputParameters_1, usage, outputParameters;
3738
+ function executePipeline(options) {
3739
+ return __awaiter(this, void 0, void 0, function () {
3740
+ var inputParameters, tools, onProgress, pipeline, setPreparedPipeline, pipelineIdentification, settings, maxParallelCount, isVerbose, preparedPipeline, llmTools, errors, warnings, executionReport, isReturned, _a, _b, parameter, e_1_1, _loop_1, _c, _d, parameterName, state_1, e_2_1, parametersToPass, resovedParameterNames_1, unresovedTemplates_1, resolving_1, loopLimit, _loop_2, error_1, usage_1, outputParameters_1, usage, outputParameters;
3733
3741
  var e_1, _e, e_2, _f;
3734
3742
  return __generator(this, function (_g) {
3735
3743
  switch (_g.label) {
3736
3744
  case 0:
3745
+ inputParameters = options.inputParameters, tools = options.tools, onProgress = options.onProgress, pipeline = options.pipeline, setPreparedPipeline = options.setPreparedPipeline, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
3746
+ maxParallelCount = settings.maxParallelCount, isVerbose = settings.isVerbose;
3747
+ preparedPipeline = options.preparedPipeline;
3748
+ llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3737
3749
  if (!(preparedPipeline === undefined)) return [3 /*break*/, 2];
3738
3750
  return [4 /*yield*/, preparePipeline(pipeline, {
3739
3751
  llmTools: llmTools,
@@ -3742,6 +3754,7 @@ function createPipelineExecutor(options) {
3742
3754
  })];
3743
3755
  case 1:
3744
3756
  preparedPipeline = _g.sent();
3757
+ setPreparedPipeline(preparedPipeline);
3745
3758
  _g.label = 2;
3746
3759
  case 2:
3747
3760
  errors = [];
@@ -3811,7 +3824,7 @@ function createPipelineExecutor(options) {
3811
3824
  return name === parameterName;
3812
3825
  });
3813
3826
  if (!(parameter === undefined)) return [3 /*break*/, 1];
3814
- warnings.push(new PipelineExecutionError(spaceTrim(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
3827
+ warnings.push(new PipelineExecutionError(spaceTrim(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
3815
3828
  return [3 /*break*/, 4];
3816
3829
  case 1:
3817
3830
  if (!(parameter.isInput === false)) return [3 /*break*/, 4];
@@ -3823,10 +3836,10 @@ function createPipelineExecutor(options) {
3823
3836
  // Note: Wait a short time to prevent race conditions
3824
3837
  _h.sent();
3825
3838
  _h.label = 3;
3826
- case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
3839
+ case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
3827
3840
  isSuccessful: false,
3828
3841
  errors: __spreadArray([
3829
- new PipelineExecutionError(spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
3842
+ new PipelineExecutionError(spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
3830
3843
  ], __read(errors), false).map(serializeError),
3831
3844
  warnings: warnings.map(serializeError),
3832
3845
  executionReport: executionReport,
@@ -3890,7 +3903,7 @@ function createPipelineExecutor(options) {
3890
3903
  case 0:
3891
3904
  if (loopLimit-- < 0) {
3892
3905
  // Note: Really UnexpectedError not LimitReachedError - this should be catched during validatePipeline
3893
- throw new UnexpectedError(spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
3906
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
3894
3907
  }
3895
3908
  currentTemplate = unresovedTemplates_1.find(function (template) {
3896
3909
  return template.dependentParameterNames.every(function (name) {
@@ -3900,24 +3913,45 @@ function createPipelineExecutor(options) {
3900
3913
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
3901
3914
  throw new UnexpectedError(
3902
3915
  // TODO: [🐎] DRY
3903
- spaceTrim(function (block) { return "\n Can not resolve some parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Can not resolve:\n ").concat(block(unresovedTemplates_1
3916
+ spaceTrim(function (block) { return "\n Can not resolve some parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Can not resolve:\n ").concat(block(unresovedTemplates_1
3904
3917
  .map(function (_a) {
3905
3918
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
3906
3919
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
3907
3920
  .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
3908
3921
  .join(' and '));
3909
3922
  })
3910
- .join('\n')), "\n\n Resolved:\n ").concat(block(resovedParameterNames_1.map(function (name) { return "- Parameter {".concat(name, "}"); }).join('\n')), "\n\n Note: This should be catched in `validatePipeline`\n "); }));
3923
+ .join('\n')), "\n\n Resolved:\n ").concat(block(resovedParameterNames_1.map(function (name) { return "- Parameter {".concat(name, "}"); }).join('\n')), "\n\n Note: This should be catched in `validatePipeline`\n "); }));
3911
3924
  case 1:
3912
3925
  if (!!currentTemplate) return [3 /*break*/, 3];
3913
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
3926
+ /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
3914
3927
  case 2:
3915
- /* [5] */ _j.sent();
3928
+ /* [🤹‍♂️] */ _j.sent();
3916
3929
  return [3 /*break*/, 4];
3917
3930
  case 3:
3918
3931
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
3919
- work_1 = executeSingleTemplate(currentTemplate)
3920
- .then(function () {
3932
+ work_1 = executeTemplate({
3933
+ currentTemplate: currentTemplate,
3934
+ preparedPipeline: preparedPipeline,
3935
+ parametersToPass: parametersToPass,
3936
+ tools: tools,
3937
+ llmTools: llmTools,
3938
+ onProgress: function (progress) {
3939
+ if (isReturned) {
3940
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress, null, 4)
3941
+ .split('\n')
3942
+ .map(function (line) { return "> ".concat(line); })
3943
+ .join('\n')), "\n "); }));
3944
+ }
3945
+ if (onProgress) {
3946
+ onProgress(progress);
3947
+ }
3948
+ },
3949
+ settings: settings,
3950
+ $executionReport: executionReport,
3951
+ pipelineIdentification: pipelineIdentification,
3952
+ })
3953
+ .then(function (newParametersToPass) {
3954
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
3921
3955
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
3922
3956
  })
3923
3957
  .then(function () {
@@ -3949,7 +3983,12 @@ function createPipelineExecutor(options) {
3949
3983
  var result = _a.result;
3950
3984
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3951
3985
  })), false));
3952
- outputParameters_1 = filterJustOutputParameters();
3986
+ outputParameters_1 = filterJustOutputParameters({
3987
+ preparedPipeline: preparedPipeline,
3988
+ parametersToPass: parametersToPass,
3989
+ $warnings: warnings,
3990
+ pipelineIdentification: pipelineIdentification,
3991
+ });
3953
3992
  isReturned = true;
3954
3993
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
3955
3994
  // Note: Wait a short time to prevent race conditions
@@ -3972,7 +4011,12 @@ function createPipelineExecutor(options) {
3972
4011
  var result = _a.result;
3973
4012
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3974
4013
  })), false));
3975
- outputParameters = filterJustOutputParameters();
4014
+ outputParameters = filterJustOutputParameters({
4015
+ preparedPipeline: preparedPipeline,
4016
+ parametersToPass: parametersToPass,
4017
+ $warnings: warnings,
4018
+ pipelineIdentification: pipelineIdentification,
4019
+ });
3976
4020
  isReturned = true;
3977
4021
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
3978
4022
  // Note: Wait a short time to prevent race conditions
@@ -3992,22 +4036,62 @@ function createPipelineExecutor(options) {
3992
4036
  })];
3993
4037
  }
3994
4038
  });
3995
- }); };
3996
- return pipelineExecutor;
4039
+ });
3997
4040
  }
4041
+
3998
4042
  /**
3999
- * TODO: !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
4000
- * TODO: Use isVerbose here (not only pass to `preparePipeline`)
4001
- * TODO: [🧠][🌳] Use here `countTotalUsage` and put preparation and prepared pipiline to report
4002
- * TODO: [🪂] Use maxParallelCount here (not only pass to `preparePipeline`)
4003
- * TODO: [♈] Probbably move expectations from templates to parameters
4004
- * TODO: [🧠] When not meet expectations in DIALOG_TEMPLATE, make some way to tell the user
4005
- * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
4006
- * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
4007
- * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
4008
- * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
4009
- * TODO: [🧠][💷] `assertsExecutionSuccessful` should be the method of `PipelineExecutor` result BUT maybe NOT to preserve pure JSON object
4043
+ * Creates executor function from pipeline and execution tools.
4044
+ *
4045
+ * @returns The executor function
4046
+ * @throws {PipelineLogicError} on logical error in the pipeline
4047
+ * @public exported from `@promptbook/core`
4010
4048
  */
4049
+ function createPipelineExecutor(options) {
4050
+ var _this = this;
4051
+ var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
4052
+ var _b = settings.maxExecutionAttempts, maxExecutionAttempts = _b === void 0 ? MAX_EXECUTION_ATTEMPTS : _b, _c = settings.maxParallelCount, maxParallelCount = _c === void 0 ? MAX_PARALLEL_COUNT : _c, _d = settings.isVerbose, isVerbose = _d === void 0 ? IS_VERBOSE : _d, _e = settings.isNotPreparedWarningSupressed, isNotPreparedWarningSupressed = _e === void 0 ? false : _e;
4053
+ validatePipeline(pipeline);
4054
+ var pipelineIdentification = (function () {
4055
+ // Note: This is a 😐 implementation of [🚞]
4056
+ var _ = [];
4057
+ if (pipeline.sourceFile !== undefined) {
4058
+ _.push("File: ".concat(pipeline.sourceFile));
4059
+ }
4060
+ if (pipeline.pipelineUrl !== undefined) {
4061
+ _.push("Url: ".concat(pipeline.pipelineUrl));
4062
+ }
4063
+ return _.join('\n');
4064
+ })();
4065
+ var preparedPipeline;
4066
+ if (isPipelinePrepared(pipeline)) {
4067
+ preparedPipeline = pipeline;
4068
+ }
4069
+ else if (isNotPreparedWarningSupressed !== true) {
4070
+ console.warn(spaceTrim(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
4071
+ }
4072
+ var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4073
+ return __generator(this, function (_a) {
4074
+ return [2 /*return*/, executePipeline({
4075
+ pipeline: pipeline,
4076
+ preparedPipeline: preparedPipeline,
4077
+ setPreparedPipeline: function (newPreparedPipeline) {
4078
+ preparedPipeline = newPreparedPipeline;
4079
+ },
4080
+ inputParameters: inputParameters,
4081
+ tools: tools,
4082
+ onProgress: onProgress,
4083
+ pipelineIdentification: pipelineIdentification,
4084
+ settings: {
4085
+ maxExecutionAttempts: maxExecutionAttempts,
4086
+ maxParallelCount: maxParallelCount,
4087
+ isVerbose: isVerbose,
4088
+ isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4089
+ },
4090
+ })];
4091
+ });
4092
+ }); };
4093
+ return pipelineExecutor;
4094
+ }
4011
4095
 
4012
4096
  /**
4013
4097
  * @@@
@@ -5264,6 +5348,8 @@ var foreachCommandParser = {
5264
5348
  */
5265
5349
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5266
5350
  var formatName = command.formatName, cellName = command.cellName, parameterName = command.parameterName, subparameterName = command.subparameterName;
5351
+ // TODO: !!!!!! Detect double use
5352
+ // TODO: !!!!!! Detect usage with JOKER and don't allow it
5267
5353
  $templateJson.foreach = { formatName: formatName, cellName: cellName, parameterName: parameterName, subparameterName: subparameterName };
5268
5354
  keepUnused($pipelineJson); // <- TODO: !!!!!! BUT Maybe register subparameter from foreach into parameters of the pipeline
5269
5355
  // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase