@promptbook/node 0.67.1 β†’ 0.67.3

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.
package/esm/index.es.js CHANGED
@@ -13,7 +13,7 @@ import * as dotenv from 'dotenv';
13
13
  /**
14
14
  * The version of the Promptbook library
15
15
  */
16
- var PROMPTBOOK_VERSION = '0.67.0';
16
+ var PROMPTBOOK_VERSION = '0.67.2';
17
17
  // TODO: !!!! List here all the versions and annotate + put into script
18
18
 
19
19
  /*! *****************************************************************************
@@ -867,7 +867,7 @@ function forEachAsync(array, options, callbackfunction) {
867
867
  });
868
868
  }
869
869
 
870
- var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.67.0",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",modelRequirements:{modelVariant:"CHAT",modelName:"claude-3-opus-20240229"},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}",dependentParameterNames:["knowledgeContent"],resultingParameterName:"knowledgePieces"}],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.67.0",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",modelRequirements:{modelVariant:"CHAT",modelName:"claude-3-opus-20240229"},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}",dependentParameterNames:["knowledgePieceContent"],resultingParameterName:"keywords"}],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.67.0",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",modelRequirements:{modelVariant:"CHAT",modelName:"claude-3-opus-20240229"},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}",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"],resultingParameterName:"title"}],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.67.0",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}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",modelRequirements:{modelVariant:"CHAT"},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### Option `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Option `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### Option `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}",expectFormat:"JSON",dependentParameterNames:["availableModelNames","personaDescription"],resultingParameterName:"modelRequirements"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
870
+ var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.67.2",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",modelRequirements:{modelVariant:"CHAT"},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}",dependentParameterNames:["knowledgeContent"],resultingParameterName:"knowledgePieces"}],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.67.2",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",modelRequirements:{modelVariant:"CHAT"},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}",dependentParameterNames:["knowledgePieceContent"],resultingParameterName:"keywords"}],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.67.2",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",modelRequirements:{modelVariant:"CHAT"},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}",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"],resultingParameterName:"title"}],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.67.2",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}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",modelRequirements:{modelVariant:"CHAT"},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}",expectFormat:"JSON",dependentParameterNames:["availableModelNames","personaDescription"],resultingParameterName:"modelRequirements"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
871
871
 
872
872
  /**
873
873
  * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
@@ -1894,6 +1894,25 @@ var EnvironmentMismatchError = /** @class */ (function (_super) {
1894
1894
  return EnvironmentMismatchError;
1895
1895
  }(Error));
1896
1896
 
1897
+ /**
1898
+ * This error occurs when some expectation is not met in the execution of the pipeline
1899
+ *
1900
+ * @public exported from `@promptbook/core`
1901
+ * Note: Do not throw this error, its reserved for `checkExpectations` and `createPipelineExecutor` and public ONLY to be serializable through remote server
1902
+ * Note: Always thrown in `checkExpectations` and catched in `createPipelineExecutor` and rethrown as `PipelineExecutionError`
1903
+ * Note: This is a kindof subtype of PipelineExecutionError
1904
+ */
1905
+ var ExpectError = /** @class */ (function (_super) {
1906
+ __extends(ExpectError, _super);
1907
+ function ExpectError(message) {
1908
+ var _this = _super.call(this, message) || this;
1909
+ _this.name = 'ExpectError';
1910
+ Object.setPrototypeOf(_this, ExpectError.prototype);
1911
+ return _this;
1912
+ }
1913
+ return ExpectError;
1914
+ }(Error));
1915
+
1897
1916
  /**
1898
1917
  * This error type indicates that some limit was reached
1899
1918
  *
@@ -1932,6 +1951,7 @@ var NotYetImplementedError = /** @class */ (function (_super) {
1932
1951
  * @public exported from `@promptbook/core`
1933
1952
  */
1934
1953
  var ERRORS = {
1954
+ ExpectError: ExpectError,
1935
1955
  CollectionError: CollectionError,
1936
1956
  EnvironmentMismatchError: EnvironmentMismatchError,
1937
1957
  LimitReachedError: LimitReachedError,
@@ -2099,24 +2119,6 @@ function extractParameterNamesFromPromptTemplate(promptTemplate) {
2099
2119
  * TODO: [πŸ”£] If script require contentLanguage
2100
2120
  */
2101
2121
 
2102
- /**
2103
- * This error occurs when some expectation is not met in the execution of the pipeline
2104
- *
2105
- * @private error of `checkExpectations` and `createPipelineExecutor`
2106
- * Note: Always thrown in `checkExpectations` and catched in `createPipelineExecutor` and rethrown as `PipelineExecutionError`
2107
- * Note: This is a kindof subtype of PipelineExecutionError
2108
- */
2109
- var ExpectError = /** @class */ (function (_super) {
2110
- __extends(ExpectError, _super);
2111
- function ExpectError(message) {
2112
- var _this = _super.call(this, message) || this;
2113
- _this.name = 'ExpectError';
2114
- Object.setPrototypeOf(_this, ExpectError.prototype);
2115
- return _this;
2116
- }
2117
- return ExpectError;
2118
- }(Error));
2119
-
2120
2122
  /**
2121
2123
  * Serializes an error into a [πŸš‰] JSON-serializable object
2122
2124
  *
@@ -2809,13 +2811,24 @@ function createPipelineExecutor(options) {
2809
2811
  var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
2810
2812
  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;
2811
2813
  validatePipeline(pipeline);
2814
+ var pipelineIdentification = (function () {
2815
+ // Note: This is a 😐 implementation of [🚞]
2816
+ var _ = [];
2817
+ if (pipeline.sourceFile !== undefined) {
2818
+ _.push("File: ".concat(pipeline.sourceFile));
2819
+ }
2820
+ if (pipeline.pipelineUrl !== undefined) {
2821
+ _.push("Url: ".concat(pipeline.pipelineUrl));
2822
+ }
2823
+ return _.join('\n');
2824
+ })();
2812
2825
  var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
2813
2826
  var preparedPipeline;
2814
2827
  if (isPipelinePrepared(pipeline)) {
2815
2828
  preparedPipeline = pipeline;
2816
2829
  }
2817
2830
  else if (isNotPreparedWarningSupressed !== true) {
2818
- console.warn(spaceTrim("\n Pipeline ".concat(pipeline.pipelineUrl || pipeline.sourceFile || pipeline.title, " is not prepared\n\n ").concat(pipeline.sourceFile, "\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 ")));
2831
+ 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 "); }));
2819
2832
  }
2820
2833
  var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
2821
2834
  // TODO: !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
@@ -2853,7 +2866,7 @@ function createPipelineExecutor(options) {
2853
2866
  }
2854
2867
  function getReservedParametersForTemplate(template) {
2855
2868
  return __awaiter(this, void 0, void 0, function () {
2856
- var context, knowledge, samples, currentDate, modelName, reservedParameters, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
2869
+ var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
2857
2870
  var e_3, _a;
2858
2871
  return __generator(this, function (_b) {
2859
2872
  switch (_b.label) {
@@ -2876,13 +2889,16 @@ function createPipelineExecutor(options) {
2876
2889
  currentDate: currentDate,
2877
2890
  modelName: modelName,
2878
2891
  };
2892
+ _loop_3 = function (parameterName) {
2893
+ if (reservedParameters[parameterName] === undefined) {
2894
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
2895
+ }
2896
+ };
2879
2897
  try {
2880
2898
  // Note: Doublecheck that ALL reserved parameters are defined:
2881
2899
  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()) {
2882
2900
  parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
2883
- if (reservedParameters[parameterName] === undefined) {
2884
- throw new UnexpectedError("Reserved parameter {".concat(parameterName, "} is not defined"));
2885
- }
2901
+ _loop_3(parameterName);
2886
2902
  }
2887
2903
  }
2888
2904
  catch (e_3_1) { e_3 = { error: e_3_1 }; }
@@ -2899,10 +2915,10 @@ function createPipelineExecutor(options) {
2899
2915
  }
2900
2916
  function executeSingleTemplate(currentTemplate) {
2901
2917
  return __awaiter(this, void 0, void 0, function () {
2902
- var name, title, priority, usedParameterNames, dependentParameterNames, definedParameters, _a, _b, _c, definedParameterNames, parameters, _d, _e, parameterName, prompt, chatResult, completionResult, embeddingResult, result, resultString, expectError, scriptPipelineExecutionErrors, maxAttempts, jokerParameterNames, preparedContent, attempt, isJokerAttempt, jokerParameterName, _f, _g, _h, _j, scriptTools, error_2, e_4_1, _k, _l, functionName, postprocessingError, _m, _o, scriptTools, error_3, e_5_1, e_6_1, error_4;
2903
- var e_7, _p, e_4, _q, e_6, _r, e_5, _s, _t;
2904
- return __generator(this, function (_u) {
2905
- switch (_u.label) {
2918
+ var name, title, priority, 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;
2919
+ var e_4, _f, _g;
2920
+ return __generator(this, function (_h) {
2921
+ switch (_h.label) {
2906
2922
  case 0:
2907
2923
  name = "pipeline-executor-frame-".concat(currentTemplate.name);
2908
2924
  title = currentTemplate.title;
@@ -2919,47 +2935,48 @@ function createPipelineExecutor(options) {
2919
2935
  // <- [3]
2920
2936
  })];
2921
2937
  case 1:
2922
- _u.sent();
2923
- _u.label = 2;
2938
+ _h.sent();
2939
+ _h.label = 2;
2924
2940
  case 2:
2925
2941
  usedParameterNames = extractParameterNamesFromPromptTemplate(currentTemplate);
2926
2942
  dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
2927
2943
  if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
2928
- throw new UnexpectedError(spaceTrim("\n Dependent parameters are not consistent used parameters:\n\n Dependent parameters:\n ".concat(Array.from(dependentParameterNames).join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames).join(', '), "\n\n ")));
2944
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Dependent parameters are not consistent used parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Dependent parameters:\n ").concat(Array.from(dependentParameterNames).join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames).join(', '), "\n\n "); }));
2929
2945
  }
2930
2946
  _b = (_a = Object).freeze;
2931
2947
  _c = [{}];
2932
2948
  return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
2933
2949
  case 3:
2934
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_u.sent())])), parametersToPass])]);
2950
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
2935
2951
  definedParameterNames = new Set(Object.keys(definedParameters));
2936
2952
  parameters = {};
2953
+ _loop_4 = function (parameterName) {
2954
+ // Situation: Parameter is defined and used
2955
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
2956
+ parameters[parameterName] = definedParameters[parameterName];
2957
+ }
2958
+ // Situation: Parameter is defined but NOT used
2959
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
2960
+ // Situation: Parameter is NOT defined BUT used
2961
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
2962
+ // Houston, we have a problem
2963
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
2964
+ 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 "); }));
2965
+ }
2966
+ };
2937
2967
  try {
2938
2968
  // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
2939
2969
  for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
2940
2970
  parameterName = _e.value;
2941
- // Situation: Parameter is defined and used
2942
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
2943
- parameters[parameterName] = definedParameters[parameterName];
2944
- }
2945
- // Situation: Parameter is defined but NOT used
2946
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) {
2947
- // Do not pass this parameter to prompt
2948
- }
2949
- // Situation: Parameter is NOT defined BUT used
2950
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
2951
- // Houston, we have a problem
2952
- // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
2953
- throw new UnexpectedError(spaceTrim("\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 ")));
2954
- }
2971
+ _loop_4(parameterName);
2955
2972
  }
2956
2973
  }
2957
- catch (e_7_1) { e_7 = { error: e_7_1 }; }
2974
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
2958
2975
  finally {
2959
2976
  try {
2960
- if (_e && !_e.done && (_p = _d.return)) _p.call(_d);
2977
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
2961
2978
  }
2962
- finally { if (e_7) throw e_7.error; }
2979
+ finally { if (e_4) throw e_4.error; }
2963
2980
  }
2964
2981
  // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
2965
2982
  Object.freeze(parameters);
@@ -2971,297 +2988,310 @@ function createPipelineExecutor(options) {
2971
2988
  preparedContent = (currentTemplate.preparedContent || '{content}')
2972
2989
  .split('{content}')
2973
2990
  .join(currentTemplate.content);
2991
+ _loop_5 = function (attempt) {
2992
+ var isJokerAttempt, jokerParameterName, _j, _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;
2993
+ var e_5, _s, e_7, _t, e_6, _u;
2994
+ return __generator(this, function (_v) {
2995
+ switch (_v.label) {
2996
+ case 0:
2997
+ isJokerAttempt = attempt < 0;
2998
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
2999
+ if (isJokerAttempt && !jokerParameterName) {
3000
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3001
+ }
3002
+ result = null;
3003
+ resultString = null;
3004
+ expectError = null;
3005
+ if (isJokerAttempt) {
3006
+ if (parameters[jokerParameterName] === undefined) {
3007
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3008
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3009
+ }
3010
+ else {
3011
+ resultString = parameters[jokerParameterName];
3012
+ }
3013
+ }
3014
+ _v.label = 1;
3015
+ case 1:
3016
+ _v.trys.push([1, 44, 45, 46]);
3017
+ if (!!isJokerAttempt) return [3 /*break*/, 26];
3018
+ _j = currentTemplate.blockType;
3019
+ switch (_j) {
3020
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3021
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3022
+ case 'SCRIPT': return [3 /*break*/, 12];
3023
+ case 'PROMPT_DIALOG': return [3 /*break*/, 23];
3024
+ }
3025
+ return [3 /*break*/, 25];
3026
+ case 2:
3027
+ resultString = replaceParameters(preparedContent, parameters);
3028
+ return [3 /*break*/, 26];
3029
+ case 3:
3030
+ prompt = {
3031
+ title: currentTemplate.title,
3032
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3033
+ ? preparedPipeline.pipelineUrl
3034
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3035
+ parameters: parameters,
3036
+ content: preparedContent,
3037
+ modelRequirements: currentTemplate.modelRequirements,
3038
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3039
+ var name = _a.name;
3040
+ return name === currentTemplate.personaName;
3041
+ }) || {})), currentTemplate.expectations),
3042
+ expectFormat: currentTemplate.expectFormat,
3043
+ postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3044
+ }; // <- TODO: Not very good type guard
3045
+ _k = currentTemplate.modelRequirements.modelVariant;
3046
+ switch (_k) {
3047
+ case 'CHAT': return [3 /*break*/, 4];
3048
+ case 'COMPLETION': return [3 /*break*/, 6];
3049
+ case 'EMBEDDING': return [3 /*break*/, 8];
3050
+ }
3051
+ return [3 /*break*/, 10];
3052
+ case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3053
+ case 5:
3054
+ chatResult = _v.sent();
3055
+ // TODO: [🍬] Destroy chatThread
3056
+ result = chatResult;
3057
+ resultString = chatResult.content;
3058
+ return [3 /*break*/, 11];
3059
+ case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3060
+ case 7:
3061
+ completionResult = _v.sent();
3062
+ result = completionResult;
3063
+ resultString = completionResult.content;
3064
+ return [3 /*break*/, 11];
3065
+ case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3066
+ case 9:
3067
+ embeddingResult = _v.sent();
3068
+ result = embeddingResult;
3069
+ resultString = embeddingResult.content.join(',');
3070
+ return [3 /*break*/, 11];
3071
+ case 10: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements.modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n\n "); }));
3072
+ case 11: return [3 /*break*/, 26];
3073
+ case 12:
3074
+ if (arrayableToArray(tools.script).length === 0) {
3075
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3076
+ }
3077
+ if (!currentTemplate.contentLanguage) {
3078
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Script language is not defined for prompt template \"".concat(currentTemplate.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3079
+ }
3080
+ // TODO: DRY [1]
3081
+ scriptPipelineExecutionErrors = [];
3082
+ _v.label = 13;
3083
+ case 13:
3084
+ _v.trys.push([13, 20, 21, 22]);
3085
+ _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3086
+ _v.label = 14;
3087
+ case 14:
3088
+ if (!!_m.done) return [3 /*break*/, 19];
3089
+ scriptTools = _m.value;
3090
+ _v.label = 15;
3091
+ case 15:
3092
+ _v.trys.push([15, 17, , 18]);
3093
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3094
+ scriptLanguage: currentTemplate.contentLanguage,
3095
+ script: preparedContent,
3096
+ parameters: parameters,
3097
+ }))];
3098
+ case 16:
3099
+ resultString = _v.sent();
3100
+ return [3 /*break*/, 19];
3101
+ case 17:
3102
+ error_2 = _v.sent();
3103
+ if (!(error_2 instanceof Error)) {
3104
+ throw error_2;
3105
+ }
3106
+ if (error_2 instanceof UnexpectedError) {
3107
+ throw error_2;
3108
+ }
3109
+ scriptPipelineExecutionErrors.push(error_2);
3110
+ return [3 /*break*/, 18];
3111
+ case 18:
3112
+ _m = _l.next();
3113
+ return [3 /*break*/, 14];
3114
+ case 19: return [3 /*break*/, 22];
3115
+ case 20:
3116
+ e_5_1 = _v.sent();
3117
+ e_5 = { error: e_5_1 };
3118
+ return [3 /*break*/, 22];
3119
+ case 21:
3120
+ try {
3121
+ if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3122
+ }
3123
+ finally { if (e_5) throw e_5.error; }
3124
+ return [7 /*endfinally*/];
3125
+ case 22:
3126
+ if (resultString !== null) {
3127
+ return [3 /*break*/, 26];
3128
+ }
3129
+ if (scriptPipelineExecutionErrors.length === 1) {
3130
+ throw scriptPipelineExecutionErrors[0];
3131
+ }
3132
+ else {
3133
+ 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
3134
+ .map(function (error) { return '- ' + error.message; })
3135
+ .join('\n\n')), "\n "); }));
3136
+ }
3137
+ case 23:
3138
+ if (tools.userInterface === undefined) {
3139
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3140
+ }
3141
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3142
+ promptTitle: currentTemplate.title,
3143
+ promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3144
+ defaultValue: replaceParameters(preparedContent, parameters),
3145
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3146
+ placeholder: undefined,
3147
+ priority: priority,
3148
+ }))];
3149
+ case 24:
3150
+ // TODO: [🌹] When making next attempt for `PROMPT DIALOG`, preserve the previous user input
3151
+ resultString = _v.sent();
3152
+ return [3 /*break*/, 26];
3153
+ case 25: throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.blockType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3154
+ case 26:
3155
+ if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3156
+ _v.label = 27;
3157
+ case 27:
3158
+ _v.trys.push([27, 41, 42, 43]);
3159
+ _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3160
+ _v.label = 28;
3161
+ case 28:
3162
+ if (!!_p.done) return [3 /*break*/, 40];
3163
+ functionName = _p.value;
3164
+ // TODO: DRY [1]
3165
+ scriptPipelineExecutionErrors = [];
3166
+ postprocessingError = null;
3167
+ _v.label = 29;
3168
+ case 29:
3169
+ _v.trys.push([29, 36, 37, 38]);
3170
+ _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3171
+ _v.label = 30;
3172
+ case 30:
3173
+ if (!!_r.done) return [3 /*break*/, 35];
3174
+ scriptTools = _r.value;
3175
+ _v.label = 31;
3176
+ case 31:
3177
+ _v.trys.push([31, 33, , 34]);
3178
+ return [4 /*yield*/, scriptTools.execute({
3179
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3180
+ script: "".concat(functionName, "(resultString)"),
3181
+ parameters: {
3182
+ resultString: resultString || '',
3183
+ // Note: No ...parametersForTemplate, because working with result only
3184
+ },
3185
+ })];
3186
+ case 32:
3187
+ resultString = _v.sent();
3188
+ postprocessingError = null;
3189
+ return [3 /*break*/, 35];
3190
+ case 33:
3191
+ error_3 = _v.sent();
3192
+ if (!(error_3 instanceof Error)) {
3193
+ throw error_3;
3194
+ }
3195
+ if (error_3 instanceof UnexpectedError) {
3196
+ throw error_3;
3197
+ }
3198
+ postprocessingError = error_3;
3199
+ scriptPipelineExecutionErrors.push(error_3);
3200
+ return [3 /*break*/, 34];
3201
+ case 34:
3202
+ _r = _q.next();
3203
+ return [3 /*break*/, 30];
3204
+ case 35: return [3 /*break*/, 38];
3205
+ case 36:
3206
+ e_6_1 = _v.sent();
3207
+ e_6 = { error: e_6_1 };
3208
+ return [3 /*break*/, 38];
3209
+ case 37:
3210
+ try {
3211
+ if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3212
+ }
3213
+ finally { if (e_6) throw e_6.error; }
3214
+ return [7 /*endfinally*/];
3215
+ case 38:
3216
+ if (postprocessingError) {
3217
+ throw postprocessingError;
3218
+ }
3219
+ _v.label = 39;
3220
+ case 39:
3221
+ _p = _o.next();
3222
+ return [3 /*break*/, 28];
3223
+ case 40: return [3 /*break*/, 43];
3224
+ case 41:
3225
+ e_7_1 = _v.sent();
3226
+ e_7 = { error: e_7_1 };
3227
+ return [3 /*break*/, 43];
3228
+ case 42:
3229
+ try {
3230
+ if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3231
+ }
3232
+ finally { if (e_7) throw e_7.error; }
3233
+ return [7 /*endfinally*/];
3234
+ case 43:
3235
+ // TODO: [πŸ’] Unite object for expecting amount and format
3236
+ if (currentTemplate.expectFormat) {
3237
+ if (currentTemplate.expectFormat === 'JSON') {
3238
+ if (!isValidJsonString(resultString || '')) {
3239
+ throw new ExpectError(spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(pipelineIdentification), "\n "); }));
3240
+ }
3241
+ }
3242
+ }
3243
+ // TODO: [πŸ’] Unite object for expecting amount and format
3244
+ if (currentTemplate.expectations) {
3245
+ checkExpectations(currentTemplate.expectations, resultString || '');
3246
+ }
3247
+ return [2 /*return*/, "break-attempts"];
3248
+ case 44:
3249
+ error_4 = _v.sent();
3250
+ if (!(error_4 instanceof ExpectError)) {
3251
+ throw error_4;
3252
+ }
3253
+ expectError = error_4;
3254
+ return [3 /*break*/, 46];
3255
+ case 45:
3256
+ if (!isJokerAttempt &&
3257
+ currentTemplate.blockType === 'PROMPT_TEMPLATE' &&
3258
+ prompt
3259
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3260
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
3261
+ ) {
3262
+ // TODO: [🧠] Maybe put other blockTypes into report
3263
+ executionReport.promptExecutions.push({
3264
+ prompt: __assign({}, prompt),
3265
+ result: result || undefined,
3266
+ error: expectError === null ? undefined : serializeError(expectError),
3267
+ });
3268
+ }
3269
+ return [7 /*endfinally*/];
3270
+ case 46:
3271
+ if (expectError !== null && attempt === maxAttempts - 1) {
3272
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\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) || ''), "\n\n Last result:\n ").concat(resultString, "\n ---\n "); }));
3273
+ }
3274
+ return [2 /*return*/];
3275
+ }
3276
+ });
3277
+ };
2974
3278
  attempt = -jokerParameterNames.length;
2975
- _u.label = 4;
3279
+ _h.label = 4;
2976
3280
  case 4:
2977
- if (!(attempt < maxAttempts)) return [3 /*break*/, 52];
2978
- isJokerAttempt = attempt < 0;
2979
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
2980
- if (isJokerAttempt && !jokerParameterName) {
2981
- throw new UnexpectedError("Joker not found in attempt ".concat(attempt));
2982
- }
2983
- result = null;
2984
- resultString = null;
2985
- expectError = null;
2986
- if (isJokerAttempt) {
2987
- if (parameters[jokerParameterName] === undefined) {
2988
- throw new PipelineExecutionError("Joker parameter {".concat(jokerParameterName, "} not defined"));
2989
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
2990
- }
2991
- else {
2992
- resultString = parameters[jokerParameterName];
2993
- }
2994
- }
2995
- _u.label = 5;
3281
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3282
+ return [5 /*yield**/, _loop_5(attempt)];
2996
3283
  case 5:
2997
- _u.trys.push([5, 48, 49, 50]);
2998
- if (!!isJokerAttempt) return [3 /*break*/, 30];
2999
- _f = currentTemplate.blockType;
3000
- switch (_f) {
3001
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 6];
3002
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 7];
3003
- case 'SCRIPT': return [3 /*break*/, 16];
3004
- case 'PROMPT_DIALOG': return [3 /*break*/, 27];
3284
+ state_2 = _h.sent();
3285
+ switch (state_2) {
3286
+ case "break-attempts": return [3 /*break*/, 7];
3005
3287
  }
3006
- return [3 /*break*/, 29];
3288
+ _h.label = 6;
3007
3289
  case 6:
3008
- resultString = replaceParameters(preparedContent, parameters);
3009
- return [3 /*break*/, 30];
3010
- case 7:
3011
- prompt = {
3012
- title: currentTemplate.title,
3013
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3014
- ? preparedPipeline.pipelineUrl
3015
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3016
- parameters: parameters,
3017
- content: preparedContent,
3018
- modelRequirements: currentTemplate.modelRequirements,
3019
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3020
- var name = _a.name;
3021
- return name === currentTemplate.personaName;
3022
- }) || {})), currentTemplate.expectations),
3023
- expectFormat: currentTemplate.expectFormat,
3024
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3025
- }; // <- TODO: Not very good type guard
3026
- _g = currentTemplate.modelRequirements.modelVariant;
3027
- switch (_g) {
3028
- case 'CHAT': return [3 /*break*/, 8];
3029
- case 'COMPLETION': return [3 /*break*/, 10];
3030
- case 'EMBEDDING': return [3 /*break*/, 12];
3031
- }
3032
- return [3 /*break*/, 14];
3033
- case 8: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3034
- case 9:
3035
- chatResult = _u.sent();
3036
- // TODO: [🍬] Destroy chatThread
3037
- result = chatResult;
3038
- resultString = chatResult.content;
3039
- return [3 /*break*/, 15];
3040
- case 10: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3041
- case 11:
3042
- completionResult = _u.sent();
3043
- result = completionResult;
3044
- resultString = completionResult.content;
3045
- return [3 /*break*/, 15];
3046
- case 12: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3047
- case 13:
3048
- embeddingResult = _u.sent();
3049
- result = embeddingResult;
3050
- resultString = embeddingResult.content.join(',');
3051
- return [3 /*break*/, 15];
3052
- case 14: throw new PipelineExecutionError("Unknown model variant \"".concat(currentTemplate.modelRequirements.modelVariant, "\""));
3053
- case 15: return [3 /*break*/, 30];
3054
- case 16:
3055
- if (arrayableToArray(tools.script).length === 0) {
3056
- throw new PipelineExecutionError('No script execution tools are available');
3057
- }
3058
- if (!currentTemplate.contentLanguage) {
3059
- throw new PipelineExecutionError("Script language is not defined for prompt template \"".concat(currentTemplate.name, "\""));
3060
- }
3061
- // TODO: DRY [1]
3062
- scriptPipelineExecutionErrors = [];
3063
- _u.label = 17;
3064
- case 17:
3065
- _u.trys.push([17, 24, 25, 26]);
3066
- _h = (e_4 = void 0, __values(arrayableToArray(tools.script))), _j = _h.next();
3067
- _u.label = 18;
3068
- case 18:
3069
- if (!!_j.done) return [3 /*break*/, 23];
3070
- scriptTools = _j.value;
3071
- _u.label = 19;
3072
- case 19:
3073
- _u.trys.push([19, 21, , 22]);
3074
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3075
- scriptLanguage: currentTemplate.contentLanguage,
3076
- script: preparedContent,
3077
- parameters: parameters,
3078
- }))];
3079
- case 20:
3080
- resultString = _u.sent();
3081
- return [3 /*break*/, 23];
3082
- case 21:
3083
- error_2 = _u.sent();
3084
- if (!(error_2 instanceof Error)) {
3085
- throw error_2;
3086
- }
3087
- if (error_2 instanceof UnexpectedError) {
3088
- throw error_2;
3089
- }
3090
- scriptPipelineExecutionErrors.push(error_2);
3091
- return [3 /*break*/, 22];
3092
- case 22:
3093
- _j = _h.next();
3094
- return [3 /*break*/, 18];
3095
- case 23: return [3 /*break*/, 26];
3096
- case 24:
3097
- e_4_1 = _u.sent();
3098
- e_4 = { error: e_4_1 };
3099
- return [3 /*break*/, 26];
3100
- case 25:
3101
- try {
3102
- if (_j && !_j.done && (_q = _h.return)) _q.call(_h);
3103
- }
3104
- finally { if (e_4) throw e_4.error; }
3105
- return [7 /*endfinally*/];
3106
- case 26:
3107
- if (resultString !== null) {
3108
- return [3 /*break*/, 30];
3109
- }
3110
- if (scriptPipelineExecutionErrors.length === 1) {
3111
- throw scriptPipelineExecutionErrors[0];
3112
- }
3113
- else {
3114
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptPipelineExecutionErrors.length, " times\n\n ").concat(block(scriptPipelineExecutionErrors
3115
- .map(function (error) { return '- ' + error.message; })
3116
- .join('\n\n')), "\n "); }));
3117
- }
3118
- case 27:
3119
- if (tools.userInterface === undefined) {
3120
- throw new PipelineExecutionError('User interface tools are not available');
3121
- }
3122
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3123
- promptTitle: currentTemplate.title,
3124
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3125
- defaultValue: replaceParameters(preparedContent, parameters),
3126
- // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3127
- placeholder: undefined,
3128
- priority: priority,
3129
- }))];
3130
- case 28:
3131
- // TODO: [🌹] When making next attempt for `PROMPT DIALOG`, preserve the previous user input
3132
- resultString = _u.sent();
3133
- return [3 /*break*/, 30];
3134
- case 29: throw new PipelineExecutionError("Unknown execution type \"".concat(currentTemplate.blockType, "\""));
3135
- case 30:
3136
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 47];
3137
- _u.label = 31;
3138
- case 31:
3139
- _u.trys.push([31, 45, 46, 47]);
3140
- _k = (e_6 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _l = _k.next();
3141
- _u.label = 32;
3142
- case 32:
3143
- if (!!_l.done) return [3 /*break*/, 44];
3144
- functionName = _l.value;
3145
- // TODO: DRY [1]
3146
- scriptPipelineExecutionErrors = [];
3147
- postprocessingError = null;
3148
- _u.label = 33;
3149
- case 33:
3150
- _u.trys.push([33, 40, 41, 42]);
3151
- _m = (e_5 = void 0, __values(arrayableToArray(tools.script))), _o = _m.next();
3152
- _u.label = 34;
3153
- case 34:
3154
- if (!!_o.done) return [3 /*break*/, 39];
3155
- scriptTools = _o.value;
3156
- _u.label = 35;
3157
- case 35:
3158
- _u.trys.push([35, 37, , 38]);
3159
- return [4 /*yield*/, scriptTools.execute({
3160
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3161
- script: "".concat(functionName, "(resultString)"),
3162
- parameters: {
3163
- resultString: resultString || '',
3164
- // Note: No ...parametersForTemplate, because working with result only
3165
- },
3166
- })];
3167
- case 36:
3168
- resultString = _u.sent();
3169
- postprocessingError = null;
3170
- return [3 /*break*/, 39];
3171
- case 37:
3172
- error_3 = _u.sent();
3173
- if (!(error_3 instanceof Error)) {
3174
- throw error_3;
3175
- }
3176
- if (error_3 instanceof UnexpectedError) {
3177
- throw error_3;
3178
- }
3179
- postprocessingError = error_3;
3180
- scriptPipelineExecutionErrors.push(error_3);
3181
- return [3 /*break*/, 38];
3182
- case 38:
3183
- _o = _m.next();
3184
- return [3 /*break*/, 34];
3185
- case 39: return [3 /*break*/, 42];
3186
- case 40:
3187
- e_5_1 = _u.sent();
3188
- e_5 = { error: e_5_1 };
3189
- return [3 /*break*/, 42];
3190
- case 41:
3191
- try {
3192
- if (_o && !_o.done && (_s = _m.return)) _s.call(_m);
3193
- }
3194
- finally { if (e_5) throw e_5.error; }
3195
- return [7 /*endfinally*/];
3196
- case 42:
3197
- if (postprocessingError) {
3198
- throw postprocessingError;
3199
- }
3200
- _u.label = 43;
3201
- case 43:
3202
- _l = _k.next();
3203
- return [3 /*break*/, 32];
3204
- case 44: return [3 /*break*/, 47];
3205
- case 45:
3206
- e_6_1 = _u.sent();
3207
- e_6 = { error: e_6_1 };
3208
- return [3 /*break*/, 47];
3209
- case 46:
3210
- try {
3211
- if (_l && !_l.done && (_r = _k.return)) _r.call(_k);
3212
- }
3213
- finally { if (e_6) throw e_6.error; }
3214
- return [7 /*endfinally*/];
3215
- case 47:
3216
- // TODO: [πŸ’] Unite object for expecting amount and format
3217
- if (currentTemplate.expectFormat) {
3218
- if (currentTemplate.expectFormat === 'JSON') {
3219
- if (!isValidJsonString(resultString || '')) {
3220
- throw new ExpectError('Expected valid JSON string');
3221
- }
3222
- }
3223
- }
3224
- // TODO: [πŸ’] Unite object for expecting amount and format
3225
- if (currentTemplate.expectations) {
3226
- checkExpectations(currentTemplate.expectations, resultString || '');
3227
- }
3228
- return [3 /*break*/, 52];
3229
- case 48:
3230
- error_4 = _u.sent();
3231
- if (!(error_4 instanceof ExpectError)) {
3232
- throw error_4;
3233
- }
3234
- if (error_4 instanceof UnexpectedError) {
3235
- throw error_4;
3236
- }
3237
- expectError = error_4;
3238
- return [3 /*break*/, 50];
3239
- case 49:
3240
- if (!isJokerAttempt &&
3241
- currentTemplate.blockType === 'PROMPT_TEMPLATE' &&
3242
- prompt
3243
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3244
- // In that case we don’t want to make a report about it because it’s not a llm execution error
3245
- ) {
3246
- // TODO: [🧠] Maybe put other blockTypes into report
3247
- executionReport.promptExecutions.push({
3248
- prompt: __assign({}, prompt),
3249
- result: result || undefined,
3250
- error: expectError === null ? undefined : serializeError(expectError),
3251
- });
3252
- }
3253
- return [7 /*endfinally*/];
3254
- case 50:
3255
- if (expectError !== null && attempt === maxAttempts - 1) {
3256
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\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) || ''), "\n\n Last result:\n ").concat(resultString, "\n ---\n "); }));
3257
- }
3258
- _u.label = 51;
3259
- case 51:
3260
3290
  attempt++;
3261
3291
  return [3 /*break*/, 4];
3262
- case 52:
3292
+ case 7:
3263
3293
  if (resultString === null) {
3264
- throw new UnexpectedError('Something went wrong and prompt result is null');
3294
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3265
3295
  }
3266
3296
  if (onProgress /* <- [3] */) {
3267
3297
  onProgress({
@@ -3275,7 +3305,7 @@ function createPipelineExecutor(options) {
3275
3305
  // <- [3]
3276
3306
  });
3277
3307
  }
3278
- parametersToPass = Object.freeze(__assign(__assign({}, parametersToPass), (_t = {}, _t[currentTemplate.resultingParameterName] = resultString /* <- Note: Not need to detect parameter collision here because pipeline checks logic consistency during construction */, _t)));
3308
+ 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)));
3279
3309
  return [2 /*return*/];
3280
3310
  }
3281
3311
  });
@@ -3284,6 +3314,14 @@ function createPipelineExecutor(options) {
3284
3314
  function filterJustOutputParameters() {
3285
3315
  var e_8, _a;
3286
3316
  var outputParameters = {};
3317
+ var _loop_6 = function (parameter) {
3318
+ if (parametersToPass[parameter.name] === undefined) {
3319
+ // [4]
3320
+ 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 "); })));
3321
+ return "continue";
3322
+ }
3323
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3324
+ };
3287
3325
  try {
3288
3326
  // Note: Filter ONLY output parameters
3289
3327
  for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
@@ -3291,12 +3329,7 @@ function createPipelineExecutor(options) {
3291
3329
  return isOutput;
3292
3330
  })), _c = _b.next(); !_c.done; _c = _b.next()) {
3293
3331
  var parameter = _c.value;
3294
- if (parametersToPass[parameter.name] === undefined) {
3295
- // [4]
3296
- warnings.push(new PipelineExecutionError("Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution")));
3297
- continue;
3298
- }
3299
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3332
+ _loop_6(parameter);
3300
3333
  }
3301
3334
  }
3302
3335
  catch (e_8_1) { e_8 = { error: e_8_1 }; }
@@ -3368,13 +3401,13 @@ function createPipelineExecutor(options) {
3368
3401
  return name === parameterName;
3369
3402
  });
3370
3403
  if (parameter === undefined) {
3371
- warnings.push(new PipelineExecutionError("Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.")));
3404
+ 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 "); })));
3372
3405
  }
3373
3406
  else if (parameter.isInput === false) {
3374
- return { value: $asDeeplyFrozenSerializableJson("Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult"), {
3407
+ return { value: $asDeeplyFrozenSerializableJson(spaceTrim(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
3375
3408
  isSuccessful: false,
3376
3409
  errors: __spreadArray([
3377
- new PipelineExecutionError("Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input"))
3410
+ 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 "); }))
3378
3411
  ], __read(errors), false).map(serializeError),
3379
3412
  warnings: warnings.map(serializeError),
3380
3413
  executionReport: executionReport,
@@ -3423,7 +3456,7 @@ function createPipelineExecutor(options) {
3423
3456
  case 0:
3424
3457
  if (loopLimit-- < 0) {
3425
3458
  // Note: Really UnexpectedError not LimitReachedError - this should be catched during validatePipeline
3426
- throw new UnexpectedError('Loop limit reached during resolving parameters pipeline execution');
3459
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
3427
3460
  }
3428
3461
  currentTemplate = unresovedTemplates_1.find(function (template) {
3429
3462
  return template.dependentParameterNames.every(function (name) {
@@ -3433,7 +3466,7 @@ function createPipelineExecutor(options) {
3433
3466
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
3434
3467
  throw new UnexpectedError(
3435
3468
  // TODO: [🐎] DRY
3436
- spaceTrim(function (block) { return "\n Can not resolve some parameters:\n\n Can not resolve:\n ".concat(block(unresovedTemplates_1
3469
+ 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
3437
3470
  .map(function (_a) {
3438
3471
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
3439
3472
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
@@ -3513,6 +3546,7 @@ function createPipelineExecutor(options) {
3513
3546
  return pipelineExecutor;
3514
3547
  }
3515
3548
  /**
3549
+ * TODO: !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
3516
3550
  * TODO: Use isVerbose here (not only pass to `preparePipeline`)
3517
3551
  * TODO: [🧠][🌳] Use here `countTotalUsage` and put preparation and prepared pipiline to report
3518
3552
  * TODO: [πŸͺ‚] Use maxParallelCount here (not only pass to `preparePipeline`)
@@ -4052,6 +4086,8 @@ function preparePipeline(pipeline, options) {
4052
4086
  * TODO: [🏏] Leverage the batch API and build queues @see https://platform.openai.com/docs/guides/batch
4053
4087
  * TODO: [🧊] In future one preparation can take data from previous preparation and save tokens and time
4054
4088
  * TODO: [πŸ› ] Actions, instruments (and maybe knowledge) => Functions and tools
4089
+ * TODO: [🧠][♏] Maybe if expecting JSON (In Anthropic Claude and other models without non-json) and its not specified in prompt content, append the instructions
4090
+ * @see https://docs.anthropic.com/en/docs/test-and-evaluate/strengthen-guardrails/increase-consistency#specify-the-desired-output-format
4055
4091
  */
4056
4092
 
4057
4093
  /**