@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/umd/index.umd.js CHANGED
@@ -35,7 +35,7 @@
35
35
  /**
36
36
  * The version of the Promptbook library
37
37
  */
38
- var PROMPTBOOK_VERSION = '0.67.0';
38
+ var PROMPTBOOK_VERSION = '0.67.2';
39
39
  // TODO: !!!! List here all the versions and annotate + put into script
40
40
 
41
41
  /*! *****************************************************************************
@@ -889,7 +889,7 @@
889
889
  });
890
890
  }
891
891
 
892
- 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"}];
892
+ 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"}];
893
893
 
894
894
  /**
895
895
  * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
@@ -1916,6 +1916,25 @@
1916
1916
  return EnvironmentMismatchError;
1917
1917
  }(Error));
1918
1918
 
1919
+ /**
1920
+ * This error occurs when some expectation is not met in the execution of the pipeline
1921
+ *
1922
+ * @public exported from `@promptbook/core`
1923
+ * Note: Do not throw this error, its reserved for `checkExpectations` and `createPipelineExecutor` and public ONLY to be serializable through remote server
1924
+ * Note: Always thrown in `checkExpectations` and catched in `createPipelineExecutor` and rethrown as `PipelineExecutionError`
1925
+ * Note: This is a kindof subtype of PipelineExecutionError
1926
+ */
1927
+ var ExpectError = /** @class */ (function (_super) {
1928
+ __extends(ExpectError, _super);
1929
+ function ExpectError(message) {
1930
+ var _this = _super.call(this, message) || this;
1931
+ _this.name = 'ExpectError';
1932
+ Object.setPrototypeOf(_this, ExpectError.prototype);
1933
+ return _this;
1934
+ }
1935
+ return ExpectError;
1936
+ }(Error));
1937
+
1919
1938
  /**
1920
1939
  * This error type indicates that some limit was reached
1921
1940
  *
@@ -1954,6 +1973,7 @@
1954
1973
  * @public exported from `@promptbook/core`
1955
1974
  */
1956
1975
  var ERRORS = {
1976
+ ExpectError: ExpectError,
1957
1977
  CollectionError: CollectionError,
1958
1978
  EnvironmentMismatchError: EnvironmentMismatchError,
1959
1979
  LimitReachedError: LimitReachedError,
@@ -2121,24 +2141,6 @@
2121
2141
  * TODO: [πŸ”£] If script require contentLanguage
2122
2142
  */
2123
2143
 
2124
- /**
2125
- * This error occurs when some expectation is not met in the execution of the pipeline
2126
- *
2127
- * @private error of `checkExpectations` and `createPipelineExecutor`
2128
- * Note: Always thrown in `checkExpectations` and catched in `createPipelineExecutor` and rethrown as `PipelineExecutionError`
2129
- * Note: This is a kindof subtype of PipelineExecutionError
2130
- */
2131
- var ExpectError = /** @class */ (function (_super) {
2132
- __extends(ExpectError, _super);
2133
- function ExpectError(message) {
2134
- var _this = _super.call(this, message) || this;
2135
- _this.name = 'ExpectError';
2136
- Object.setPrototypeOf(_this, ExpectError.prototype);
2137
- return _this;
2138
- }
2139
- return ExpectError;
2140
- }(Error));
2141
-
2142
2144
  /**
2143
2145
  * Serializes an error into a [πŸš‰] JSON-serializable object
2144
2146
  *
@@ -2831,13 +2833,24 @@
2831
2833
  var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
2832
2834
  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;
2833
2835
  validatePipeline(pipeline);
2836
+ var pipelineIdentification = (function () {
2837
+ // Note: This is a 😐 implementation of [🚞]
2838
+ var _ = [];
2839
+ if (pipeline.sourceFile !== undefined) {
2840
+ _.push("File: ".concat(pipeline.sourceFile));
2841
+ }
2842
+ if (pipeline.pipelineUrl !== undefined) {
2843
+ _.push("Url: ".concat(pipeline.pipelineUrl));
2844
+ }
2845
+ return _.join('\n');
2846
+ })();
2834
2847
  var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
2835
2848
  var preparedPipeline;
2836
2849
  if (isPipelinePrepared(pipeline)) {
2837
2850
  preparedPipeline = pipeline;
2838
2851
  }
2839
2852
  else if (isNotPreparedWarningSupressed !== true) {
2840
- console.warn(spaceTrim.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 ")));
2853
+ console.warn(spaceTrim.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 "); }));
2841
2854
  }
2842
2855
  var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
2843
2856
  // TODO: !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
@@ -2875,7 +2888,7 @@
2875
2888
  }
2876
2889
  function getReservedParametersForTemplate(template) {
2877
2890
  return __awaiter(this, void 0, void 0, function () {
2878
- var context, knowledge, samples, currentDate, modelName, reservedParameters, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
2891
+ var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
2879
2892
  var e_3, _a;
2880
2893
  return __generator(this, function (_b) {
2881
2894
  switch (_b.label) {
@@ -2898,13 +2911,16 @@
2898
2911
  currentDate: currentDate,
2899
2912
  modelName: modelName,
2900
2913
  };
2914
+ _loop_3 = function (parameterName) {
2915
+ if (reservedParameters[parameterName] === undefined) {
2916
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
2917
+ }
2918
+ };
2901
2919
  try {
2902
2920
  // Note: Doublecheck that ALL reserved parameters are defined:
2903
2921
  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()) {
2904
2922
  parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
2905
- if (reservedParameters[parameterName] === undefined) {
2906
- throw new UnexpectedError("Reserved parameter {".concat(parameterName, "} is not defined"));
2907
- }
2923
+ _loop_3(parameterName);
2908
2924
  }
2909
2925
  }
2910
2926
  catch (e_3_1) { e_3 = { error: e_3_1 }; }
@@ -2921,10 +2937,10 @@
2921
2937
  }
2922
2938
  function executeSingleTemplate(currentTemplate) {
2923
2939
  return __awaiter(this, void 0, void 0, function () {
2924
- 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;
2925
- var e_7, _p, e_4, _q, e_6, _r, e_5, _s, _t;
2926
- return __generator(this, function (_u) {
2927
- switch (_u.label) {
2940
+ 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;
2941
+ var e_4, _f, _g;
2942
+ return __generator(this, function (_h) {
2943
+ switch (_h.label) {
2928
2944
  case 0:
2929
2945
  name = "pipeline-executor-frame-".concat(currentTemplate.name);
2930
2946
  title = currentTemplate.title;
@@ -2941,47 +2957,48 @@
2941
2957
  // <- [3]
2942
2958
  })];
2943
2959
  case 1:
2944
- _u.sent();
2945
- _u.label = 2;
2960
+ _h.sent();
2961
+ _h.label = 2;
2946
2962
  case 2:
2947
2963
  usedParameterNames = extractParameterNamesFromPromptTemplate(currentTemplate);
2948
2964
  dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
2949
2965
  if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
2950
- throw new UnexpectedError(spaceTrim.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 ")));
2966
+ throw new UnexpectedError(spaceTrim.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 "); }));
2951
2967
  }
2952
2968
  _b = (_a = Object).freeze;
2953
2969
  _c = [{}];
2954
2970
  return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
2955
2971
  case 3:
2956
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_u.sent())])), parametersToPass])]);
2972
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
2957
2973
  definedParameterNames = new Set(Object.keys(definedParameters));
2958
2974
  parameters = {};
2975
+ _loop_4 = function (parameterName) {
2976
+ // Situation: Parameter is defined and used
2977
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
2978
+ parameters[parameterName] = definedParameters[parameterName];
2979
+ }
2980
+ // Situation: Parameter is defined but NOT used
2981
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
2982
+ // Situation: Parameter is NOT defined BUT used
2983
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
2984
+ // Houston, we have a problem
2985
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
2986
+ throw new UnexpectedError(spaceTrim.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 "); }));
2987
+ }
2988
+ };
2959
2989
  try {
2960
2990
  // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
2961
2991
  for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
2962
2992
  parameterName = _e.value;
2963
- // Situation: Parameter is defined and used
2964
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
2965
- parameters[parameterName] = definedParameters[parameterName];
2966
- }
2967
- // Situation: Parameter is defined but NOT used
2968
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) {
2969
- // Do not pass this parameter to prompt
2970
- }
2971
- // Situation: Parameter is NOT defined BUT used
2972
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
2973
- // Houston, we have a problem
2974
- // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
2975
- throw new UnexpectedError(spaceTrim.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 ")));
2976
- }
2993
+ _loop_4(parameterName);
2977
2994
  }
2978
2995
  }
2979
- catch (e_7_1) { e_7 = { error: e_7_1 }; }
2996
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
2980
2997
  finally {
2981
2998
  try {
2982
- if (_e && !_e.done && (_p = _d.return)) _p.call(_d);
2999
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
2983
3000
  }
2984
- finally { if (e_7) throw e_7.error; }
3001
+ finally { if (e_4) throw e_4.error; }
2985
3002
  }
2986
3003
  // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
2987
3004
  Object.freeze(parameters);
@@ -2993,297 +3010,310 @@
2993
3010
  preparedContent = (currentTemplate.preparedContent || '{content}')
2994
3011
  .split('{content}')
2995
3012
  .join(currentTemplate.content);
3013
+ _loop_5 = function (attempt) {
3014
+ 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;
3015
+ var e_5, _s, e_7, _t, e_6, _u;
3016
+ return __generator(this, function (_v) {
3017
+ switch (_v.label) {
3018
+ case 0:
3019
+ isJokerAttempt = attempt < 0;
3020
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3021
+ if (isJokerAttempt && !jokerParameterName) {
3022
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3023
+ }
3024
+ result = null;
3025
+ resultString = null;
3026
+ expectError = null;
3027
+ if (isJokerAttempt) {
3028
+ if (parameters[jokerParameterName] === undefined) {
3029
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3030
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3031
+ }
3032
+ else {
3033
+ resultString = parameters[jokerParameterName];
3034
+ }
3035
+ }
3036
+ _v.label = 1;
3037
+ case 1:
3038
+ _v.trys.push([1, 44, 45, 46]);
3039
+ if (!!isJokerAttempt) return [3 /*break*/, 26];
3040
+ _j = currentTemplate.blockType;
3041
+ switch (_j) {
3042
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3043
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3044
+ case 'SCRIPT': return [3 /*break*/, 12];
3045
+ case 'PROMPT_DIALOG': return [3 /*break*/, 23];
3046
+ }
3047
+ return [3 /*break*/, 25];
3048
+ case 2:
3049
+ resultString = replaceParameters(preparedContent, parameters);
3050
+ return [3 /*break*/, 26];
3051
+ case 3:
3052
+ prompt = {
3053
+ title: currentTemplate.title,
3054
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3055
+ ? preparedPipeline.pipelineUrl
3056
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3057
+ parameters: parameters,
3058
+ content: preparedContent,
3059
+ modelRequirements: currentTemplate.modelRequirements,
3060
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3061
+ var name = _a.name;
3062
+ return name === currentTemplate.personaName;
3063
+ }) || {})), currentTemplate.expectations),
3064
+ expectFormat: currentTemplate.expectFormat,
3065
+ postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3066
+ }; // <- TODO: Not very good type guard
3067
+ _k = currentTemplate.modelRequirements.modelVariant;
3068
+ switch (_k) {
3069
+ case 'CHAT': return [3 /*break*/, 4];
3070
+ case 'COMPLETION': return [3 /*break*/, 6];
3071
+ case 'EMBEDDING': return [3 /*break*/, 8];
3072
+ }
3073
+ return [3 /*break*/, 10];
3074
+ case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3075
+ case 5:
3076
+ chatResult = _v.sent();
3077
+ // TODO: [🍬] Destroy chatThread
3078
+ result = chatResult;
3079
+ resultString = chatResult.content;
3080
+ return [3 /*break*/, 11];
3081
+ case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3082
+ case 7:
3083
+ completionResult = _v.sent();
3084
+ result = completionResult;
3085
+ resultString = completionResult.content;
3086
+ return [3 /*break*/, 11];
3087
+ case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3088
+ case 9:
3089
+ embeddingResult = _v.sent();
3090
+ result = embeddingResult;
3091
+ resultString = embeddingResult.content.join(',');
3092
+ return [3 /*break*/, 11];
3093
+ case 10: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements.modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n\n "); }));
3094
+ case 11: return [3 /*break*/, 26];
3095
+ case 12:
3096
+ if (arrayableToArray(tools.script).length === 0) {
3097
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3098
+ }
3099
+ if (!currentTemplate.contentLanguage) {
3100
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script language is not defined for prompt template \"".concat(currentTemplate.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3101
+ }
3102
+ // TODO: DRY [1]
3103
+ scriptPipelineExecutionErrors = [];
3104
+ _v.label = 13;
3105
+ case 13:
3106
+ _v.trys.push([13, 20, 21, 22]);
3107
+ _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3108
+ _v.label = 14;
3109
+ case 14:
3110
+ if (!!_m.done) return [3 /*break*/, 19];
3111
+ scriptTools = _m.value;
3112
+ _v.label = 15;
3113
+ case 15:
3114
+ _v.trys.push([15, 17, , 18]);
3115
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3116
+ scriptLanguage: currentTemplate.contentLanguage,
3117
+ script: preparedContent,
3118
+ parameters: parameters,
3119
+ }))];
3120
+ case 16:
3121
+ resultString = _v.sent();
3122
+ return [3 /*break*/, 19];
3123
+ case 17:
3124
+ error_2 = _v.sent();
3125
+ if (!(error_2 instanceof Error)) {
3126
+ throw error_2;
3127
+ }
3128
+ if (error_2 instanceof UnexpectedError) {
3129
+ throw error_2;
3130
+ }
3131
+ scriptPipelineExecutionErrors.push(error_2);
3132
+ return [3 /*break*/, 18];
3133
+ case 18:
3134
+ _m = _l.next();
3135
+ return [3 /*break*/, 14];
3136
+ case 19: return [3 /*break*/, 22];
3137
+ case 20:
3138
+ e_5_1 = _v.sent();
3139
+ e_5 = { error: e_5_1 };
3140
+ return [3 /*break*/, 22];
3141
+ case 21:
3142
+ try {
3143
+ if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3144
+ }
3145
+ finally { if (e_5) throw e_5.error; }
3146
+ return [7 /*endfinally*/];
3147
+ case 22:
3148
+ if (resultString !== null) {
3149
+ return [3 /*break*/, 26];
3150
+ }
3151
+ if (scriptPipelineExecutionErrors.length === 1) {
3152
+ throw scriptPipelineExecutionErrors[0];
3153
+ }
3154
+ else {
3155
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptPipelineExecutionErrors.length, " times\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block(scriptPipelineExecutionErrors
3156
+ .map(function (error) { return '- ' + error.message; })
3157
+ .join('\n\n')), "\n "); }));
3158
+ }
3159
+ case 23:
3160
+ if (tools.userInterface === undefined) {
3161
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3162
+ }
3163
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3164
+ promptTitle: currentTemplate.title,
3165
+ promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3166
+ defaultValue: replaceParameters(preparedContent, parameters),
3167
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3168
+ placeholder: undefined,
3169
+ priority: priority,
3170
+ }))];
3171
+ case 24:
3172
+ // TODO: [🌹] When making next attempt for `PROMPT DIALOG`, preserve the previous user input
3173
+ resultString = _v.sent();
3174
+ return [3 /*break*/, 26];
3175
+ case 25: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.blockType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3176
+ case 26:
3177
+ if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3178
+ _v.label = 27;
3179
+ case 27:
3180
+ _v.trys.push([27, 41, 42, 43]);
3181
+ _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3182
+ _v.label = 28;
3183
+ case 28:
3184
+ if (!!_p.done) return [3 /*break*/, 40];
3185
+ functionName = _p.value;
3186
+ // TODO: DRY [1]
3187
+ scriptPipelineExecutionErrors = [];
3188
+ postprocessingError = null;
3189
+ _v.label = 29;
3190
+ case 29:
3191
+ _v.trys.push([29, 36, 37, 38]);
3192
+ _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3193
+ _v.label = 30;
3194
+ case 30:
3195
+ if (!!_r.done) return [3 /*break*/, 35];
3196
+ scriptTools = _r.value;
3197
+ _v.label = 31;
3198
+ case 31:
3199
+ _v.trys.push([31, 33, , 34]);
3200
+ return [4 /*yield*/, scriptTools.execute({
3201
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3202
+ script: "".concat(functionName, "(resultString)"),
3203
+ parameters: {
3204
+ resultString: resultString || '',
3205
+ // Note: No ...parametersForTemplate, because working with result only
3206
+ },
3207
+ })];
3208
+ case 32:
3209
+ resultString = _v.sent();
3210
+ postprocessingError = null;
3211
+ return [3 /*break*/, 35];
3212
+ case 33:
3213
+ error_3 = _v.sent();
3214
+ if (!(error_3 instanceof Error)) {
3215
+ throw error_3;
3216
+ }
3217
+ if (error_3 instanceof UnexpectedError) {
3218
+ throw error_3;
3219
+ }
3220
+ postprocessingError = error_3;
3221
+ scriptPipelineExecutionErrors.push(error_3);
3222
+ return [3 /*break*/, 34];
3223
+ case 34:
3224
+ _r = _q.next();
3225
+ return [3 /*break*/, 30];
3226
+ case 35: return [3 /*break*/, 38];
3227
+ case 36:
3228
+ e_6_1 = _v.sent();
3229
+ e_6 = { error: e_6_1 };
3230
+ return [3 /*break*/, 38];
3231
+ case 37:
3232
+ try {
3233
+ if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3234
+ }
3235
+ finally { if (e_6) throw e_6.error; }
3236
+ return [7 /*endfinally*/];
3237
+ case 38:
3238
+ if (postprocessingError) {
3239
+ throw postprocessingError;
3240
+ }
3241
+ _v.label = 39;
3242
+ case 39:
3243
+ _p = _o.next();
3244
+ return [3 /*break*/, 28];
3245
+ case 40: return [3 /*break*/, 43];
3246
+ case 41:
3247
+ e_7_1 = _v.sent();
3248
+ e_7 = { error: e_7_1 };
3249
+ return [3 /*break*/, 43];
3250
+ case 42:
3251
+ try {
3252
+ if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3253
+ }
3254
+ finally { if (e_7) throw e_7.error; }
3255
+ return [7 /*endfinally*/];
3256
+ case 43:
3257
+ // TODO: [πŸ’] Unite object for expecting amount and format
3258
+ if (currentTemplate.expectFormat) {
3259
+ if (currentTemplate.expectFormat === 'JSON') {
3260
+ if (!isValidJsonString(resultString || '')) {
3261
+ throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(pipelineIdentification), "\n "); }));
3262
+ }
3263
+ }
3264
+ }
3265
+ // TODO: [πŸ’] Unite object for expecting amount and format
3266
+ if (currentTemplate.expectations) {
3267
+ checkExpectations(currentTemplate.expectations, resultString || '');
3268
+ }
3269
+ return [2 /*return*/, "break-attempts"];
3270
+ case 44:
3271
+ error_4 = _v.sent();
3272
+ if (!(error_4 instanceof ExpectError)) {
3273
+ throw error_4;
3274
+ }
3275
+ expectError = error_4;
3276
+ return [3 /*break*/, 46];
3277
+ case 45:
3278
+ if (!isJokerAttempt &&
3279
+ currentTemplate.blockType === 'PROMPT_TEMPLATE' &&
3280
+ prompt
3281
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3282
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
3283
+ ) {
3284
+ // TODO: [🧠] Maybe put other blockTypes into report
3285
+ executionReport.promptExecutions.push({
3286
+ prompt: __assign({}, prompt),
3287
+ result: result || undefined,
3288
+ error: expectError === null ? undefined : serializeError(expectError),
3289
+ });
3290
+ }
3291
+ return [7 /*endfinally*/];
3292
+ case 46:
3293
+ if (expectError !== null && attempt === maxAttempts - 1) {
3294
+ throw new PipelineExecutionError(spaceTrim.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 "); }));
3295
+ }
3296
+ return [2 /*return*/];
3297
+ }
3298
+ });
3299
+ };
2996
3300
  attempt = -jokerParameterNames.length;
2997
- _u.label = 4;
3301
+ _h.label = 4;
2998
3302
  case 4:
2999
- if (!(attempt < maxAttempts)) return [3 /*break*/, 52];
3000
- isJokerAttempt = attempt < 0;
3001
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3002
- if (isJokerAttempt && !jokerParameterName) {
3003
- throw new UnexpectedError("Joker not found in attempt ".concat(attempt));
3004
- }
3005
- result = null;
3006
- resultString = null;
3007
- expectError = null;
3008
- if (isJokerAttempt) {
3009
- if (parameters[jokerParameterName] === undefined) {
3010
- throw new PipelineExecutionError("Joker parameter {".concat(jokerParameterName, "} not defined"));
3011
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3012
- }
3013
- else {
3014
- resultString = parameters[jokerParameterName];
3015
- }
3016
- }
3017
- _u.label = 5;
3303
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3304
+ return [5 /*yield**/, _loop_5(attempt)];
3018
3305
  case 5:
3019
- _u.trys.push([5, 48, 49, 50]);
3020
- if (!!isJokerAttempt) return [3 /*break*/, 30];
3021
- _f = currentTemplate.blockType;
3022
- switch (_f) {
3023
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 6];
3024
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 7];
3025
- case 'SCRIPT': return [3 /*break*/, 16];
3026
- case 'PROMPT_DIALOG': return [3 /*break*/, 27];
3306
+ state_2 = _h.sent();
3307
+ switch (state_2) {
3308
+ case "break-attempts": return [3 /*break*/, 7];
3027
3309
  }
3028
- return [3 /*break*/, 29];
3310
+ _h.label = 6;
3029
3311
  case 6:
3030
- resultString = replaceParameters(preparedContent, parameters);
3031
- return [3 /*break*/, 30];
3032
- case 7:
3033
- prompt = {
3034
- title: currentTemplate.title,
3035
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3036
- ? preparedPipeline.pipelineUrl
3037
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3038
- parameters: parameters,
3039
- content: preparedContent,
3040
- modelRequirements: currentTemplate.modelRequirements,
3041
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3042
- var name = _a.name;
3043
- return name === currentTemplate.personaName;
3044
- }) || {})), currentTemplate.expectations),
3045
- expectFormat: currentTemplate.expectFormat,
3046
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3047
- }; // <- TODO: Not very good type guard
3048
- _g = currentTemplate.modelRequirements.modelVariant;
3049
- switch (_g) {
3050
- case 'CHAT': return [3 /*break*/, 8];
3051
- case 'COMPLETION': return [3 /*break*/, 10];
3052
- case 'EMBEDDING': return [3 /*break*/, 12];
3053
- }
3054
- return [3 /*break*/, 14];
3055
- case 8: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3056
- case 9:
3057
- chatResult = _u.sent();
3058
- // TODO: [🍬] Destroy chatThread
3059
- result = chatResult;
3060
- resultString = chatResult.content;
3061
- return [3 /*break*/, 15];
3062
- case 10: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3063
- case 11:
3064
- completionResult = _u.sent();
3065
- result = completionResult;
3066
- resultString = completionResult.content;
3067
- return [3 /*break*/, 15];
3068
- case 12: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3069
- case 13:
3070
- embeddingResult = _u.sent();
3071
- result = embeddingResult;
3072
- resultString = embeddingResult.content.join(',');
3073
- return [3 /*break*/, 15];
3074
- case 14: throw new PipelineExecutionError("Unknown model variant \"".concat(currentTemplate.modelRequirements.modelVariant, "\""));
3075
- case 15: return [3 /*break*/, 30];
3076
- case 16:
3077
- if (arrayableToArray(tools.script).length === 0) {
3078
- throw new PipelineExecutionError('No script execution tools are available');
3079
- }
3080
- if (!currentTemplate.contentLanguage) {
3081
- throw new PipelineExecutionError("Script language is not defined for prompt template \"".concat(currentTemplate.name, "\""));
3082
- }
3083
- // TODO: DRY [1]
3084
- scriptPipelineExecutionErrors = [];
3085
- _u.label = 17;
3086
- case 17:
3087
- _u.trys.push([17, 24, 25, 26]);
3088
- _h = (e_4 = void 0, __values(arrayableToArray(tools.script))), _j = _h.next();
3089
- _u.label = 18;
3090
- case 18:
3091
- if (!!_j.done) return [3 /*break*/, 23];
3092
- scriptTools = _j.value;
3093
- _u.label = 19;
3094
- case 19:
3095
- _u.trys.push([19, 21, , 22]);
3096
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3097
- scriptLanguage: currentTemplate.contentLanguage,
3098
- script: preparedContent,
3099
- parameters: parameters,
3100
- }))];
3101
- case 20:
3102
- resultString = _u.sent();
3103
- return [3 /*break*/, 23];
3104
- case 21:
3105
- error_2 = _u.sent();
3106
- if (!(error_2 instanceof Error)) {
3107
- throw error_2;
3108
- }
3109
- if (error_2 instanceof UnexpectedError) {
3110
- throw error_2;
3111
- }
3112
- scriptPipelineExecutionErrors.push(error_2);
3113
- return [3 /*break*/, 22];
3114
- case 22:
3115
- _j = _h.next();
3116
- return [3 /*break*/, 18];
3117
- case 23: return [3 /*break*/, 26];
3118
- case 24:
3119
- e_4_1 = _u.sent();
3120
- e_4 = { error: e_4_1 };
3121
- return [3 /*break*/, 26];
3122
- case 25:
3123
- try {
3124
- if (_j && !_j.done && (_q = _h.return)) _q.call(_h);
3125
- }
3126
- finally { if (e_4) throw e_4.error; }
3127
- return [7 /*endfinally*/];
3128
- case 26:
3129
- if (resultString !== null) {
3130
- return [3 /*break*/, 30];
3131
- }
3132
- if (scriptPipelineExecutionErrors.length === 1) {
3133
- throw scriptPipelineExecutionErrors[0];
3134
- }
3135
- else {
3136
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptPipelineExecutionErrors.length, " times\n\n ").concat(block(scriptPipelineExecutionErrors
3137
- .map(function (error) { return '- ' + error.message; })
3138
- .join('\n\n')), "\n "); }));
3139
- }
3140
- case 27:
3141
- if (tools.userInterface === undefined) {
3142
- throw new PipelineExecutionError('User interface tools are not available');
3143
- }
3144
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3145
- promptTitle: currentTemplate.title,
3146
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3147
- defaultValue: replaceParameters(preparedContent, parameters),
3148
- // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3149
- placeholder: undefined,
3150
- priority: priority,
3151
- }))];
3152
- case 28:
3153
- // TODO: [🌹] When making next attempt for `PROMPT DIALOG`, preserve the previous user input
3154
- resultString = _u.sent();
3155
- return [3 /*break*/, 30];
3156
- case 29: throw new PipelineExecutionError("Unknown execution type \"".concat(currentTemplate.blockType, "\""));
3157
- case 30:
3158
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 47];
3159
- _u.label = 31;
3160
- case 31:
3161
- _u.trys.push([31, 45, 46, 47]);
3162
- _k = (e_6 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _l = _k.next();
3163
- _u.label = 32;
3164
- case 32:
3165
- if (!!_l.done) return [3 /*break*/, 44];
3166
- functionName = _l.value;
3167
- // TODO: DRY [1]
3168
- scriptPipelineExecutionErrors = [];
3169
- postprocessingError = null;
3170
- _u.label = 33;
3171
- case 33:
3172
- _u.trys.push([33, 40, 41, 42]);
3173
- _m = (e_5 = void 0, __values(arrayableToArray(tools.script))), _o = _m.next();
3174
- _u.label = 34;
3175
- case 34:
3176
- if (!!_o.done) return [3 /*break*/, 39];
3177
- scriptTools = _o.value;
3178
- _u.label = 35;
3179
- case 35:
3180
- _u.trys.push([35, 37, , 38]);
3181
- return [4 /*yield*/, scriptTools.execute({
3182
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3183
- script: "".concat(functionName, "(resultString)"),
3184
- parameters: {
3185
- resultString: resultString || '',
3186
- // Note: No ...parametersForTemplate, because working with result only
3187
- },
3188
- })];
3189
- case 36:
3190
- resultString = _u.sent();
3191
- postprocessingError = null;
3192
- return [3 /*break*/, 39];
3193
- case 37:
3194
- error_3 = _u.sent();
3195
- if (!(error_3 instanceof Error)) {
3196
- throw error_3;
3197
- }
3198
- if (error_3 instanceof UnexpectedError) {
3199
- throw error_3;
3200
- }
3201
- postprocessingError = error_3;
3202
- scriptPipelineExecutionErrors.push(error_3);
3203
- return [3 /*break*/, 38];
3204
- case 38:
3205
- _o = _m.next();
3206
- return [3 /*break*/, 34];
3207
- case 39: return [3 /*break*/, 42];
3208
- case 40:
3209
- e_5_1 = _u.sent();
3210
- e_5 = { error: e_5_1 };
3211
- return [3 /*break*/, 42];
3212
- case 41:
3213
- try {
3214
- if (_o && !_o.done && (_s = _m.return)) _s.call(_m);
3215
- }
3216
- finally { if (e_5) throw e_5.error; }
3217
- return [7 /*endfinally*/];
3218
- case 42:
3219
- if (postprocessingError) {
3220
- throw postprocessingError;
3221
- }
3222
- _u.label = 43;
3223
- case 43:
3224
- _l = _k.next();
3225
- return [3 /*break*/, 32];
3226
- case 44: return [3 /*break*/, 47];
3227
- case 45:
3228
- e_6_1 = _u.sent();
3229
- e_6 = { error: e_6_1 };
3230
- return [3 /*break*/, 47];
3231
- case 46:
3232
- try {
3233
- if (_l && !_l.done && (_r = _k.return)) _r.call(_k);
3234
- }
3235
- finally { if (e_6) throw e_6.error; }
3236
- return [7 /*endfinally*/];
3237
- case 47:
3238
- // TODO: [πŸ’] Unite object for expecting amount and format
3239
- if (currentTemplate.expectFormat) {
3240
- if (currentTemplate.expectFormat === 'JSON') {
3241
- if (!isValidJsonString(resultString || '')) {
3242
- throw new ExpectError('Expected valid JSON string');
3243
- }
3244
- }
3245
- }
3246
- // TODO: [πŸ’] Unite object for expecting amount and format
3247
- if (currentTemplate.expectations) {
3248
- checkExpectations(currentTemplate.expectations, resultString || '');
3249
- }
3250
- return [3 /*break*/, 52];
3251
- case 48:
3252
- error_4 = _u.sent();
3253
- if (!(error_4 instanceof ExpectError)) {
3254
- throw error_4;
3255
- }
3256
- if (error_4 instanceof UnexpectedError) {
3257
- throw error_4;
3258
- }
3259
- expectError = error_4;
3260
- return [3 /*break*/, 50];
3261
- case 49:
3262
- if (!isJokerAttempt &&
3263
- currentTemplate.blockType === 'PROMPT_TEMPLATE' &&
3264
- prompt
3265
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3266
- // In that case we don’t want to make a report about it because it’s not a llm execution error
3267
- ) {
3268
- // TODO: [🧠] Maybe put other blockTypes into report
3269
- executionReport.promptExecutions.push({
3270
- prompt: __assign({}, prompt),
3271
- result: result || undefined,
3272
- error: expectError === null ? undefined : serializeError(expectError),
3273
- });
3274
- }
3275
- return [7 /*endfinally*/];
3276
- case 50:
3277
- if (expectError !== null && attempt === maxAttempts - 1) {
3278
- throw new PipelineExecutionError(spaceTrim.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 "); }));
3279
- }
3280
- _u.label = 51;
3281
- case 51:
3282
3312
  attempt++;
3283
3313
  return [3 /*break*/, 4];
3284
- case 52:
3314
+ case 7:
3285
3315
  if (resultString === null) {
3286
- throw new UnexpectedError('Something went wrong and prompt result is null');
3316
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3287
3317
  }
3288
3318
  if (onProgress /* <- [3] */) {
3289
3319
  onProgress({
@@ -3297,7 +3327,7 @@
3297
3327
  // <- [3]
3298
3328
  });
3299
3329
  }
3300
- 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)));
3330
+ 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)));
3301
3331
  return [2 /*return*/];
3302
3332
  }
3303
3333
  });
@@ -3306,6 +3336,14 @@
3306
3336
  function filterJustOutputParameters() {
3307
3337
  var e_8, _a;
3308
3338
  var outputParameters = {};
3339
+ var _loop_6 = function (parameter) {
3340
+ if (parametersToPass[parameter.name] === undefined) {
3341
+ // [4]
3342
+ warnings.push(new PipelineExecutionError(spaceTrim.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 "); })));
3343
+ return "continue";
3344
+ }
3345
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3346
+ };
3309
3347
  try {
3310
3348
  // Note: Filter ONLY output parameters
3311
3349
  for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
@@ -3313,12 +3351,7 @@
3313
3351
  return isOutput;
3314
3352
  })), _c = _b.next(); !_c.done; _c = _b.next()) {
3315
3353
  var parameter = _c.value;
3316
- if (parametersToPass[parameter.name] === undefined) {
3317
- // [4]
3318
- warnings.push(new PipelineExecutionError("Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution")));
3319
- continue;
3320
- }
3321
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3354
+ _loop_6(parameter);
3322
3355
  }
3323
3356
  }
3324
3357
  catch (e_8_1) { e_8 = { error: e_8_1 }; }
@@ -3390,13 +3423,13 @@
3390
3423
  return name === parameterName;
3391
3424
  });
3392
3425
  if (parameter === undefined) {
3393
- warnings.push(new PipelineExecutionError("Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.")));
3426
+ warnings.push(new PipelineExecutionError(spaceTrim.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 "); })));
3394
3427
  }
3395
3428
  else if (parameter.isInput === false) {
3396
- return { value: $asDeeplyFrozenSerializableJson("Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult"), {
3429
+ return { value: $asDeeplyFrozenSerializableJson(spaceTrim.spaceTrim(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
3397
3430
  isSuccessful: false,
3398
3431
  errors: __spreadArray([
3399
- new PipelineExecutionError("Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input"))
3432
+ new PipelineExecutionError(spaceTrim.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 "); }))
3400
3433
  ], __read(errors), false).map(serializeError),
3401
3434
  warnings: warnings.map(serializeError),
3402
3435
  executionReport: executionReport,
@@ -3445,7 +3478,7 @@
3445
3478
  case 0:
3446
3479
  if (loopLimit-- < 0) {
3447
3480
  // Note: Really UnexpectedError not LimitReachedError - this should be catched during validatePipeline
3448
- throw new UnexpectedError('Loop limit reached during resolving parameters pipeline execution');
3481
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
3449
3482
  }
3450
3483
  currentTemplate = unresovedTemplates_1.find(function (template) {
3451
3484
  return template.dependentParameterNames.every(function (name) {
@@ -3455,7 +3488,7 @@
3455
3488
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
3456
3489
  throw new UnexpectedError(
3457
3490
  // TODO: [🐎] DRY
3458
- spaceTrim.spaceTrim(function (block) { return "\n Can not resolve some parameters:\n\n Can not resolve:\n ".concat(block(unresovedTemplates_1
3491
+ spaceTrim.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
3459
3492
  .map(function (_a) {
3460
3493
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
3461
3494
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
@@ -3535,6 +3568,7 @@
3535
3568
  return pipelineExecutor;
3536
3569
  }
3537
3570
  /**
3571
+ * TODO: !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
3538
3572
  * TODO: Use isVerbose here (not only pass to `preparePipeline`)
3539
3573
  * TODO: [🧠][🌳] Use here `countTotalUsage` and put preparation and prepared pipiline to report
3540
3574
  * TODO: [πŸͺ‚] Use maxParallelCount here (not only pass to `preparePipeline`)
@@ -4074,6 +4108,8 @@
4074
4108
  * TODO: [🏏] Leverage the batch API and build queues @see https://platform.openai.com/docs/guides/batch
4075
4109
  * TODO: [🧊] In future one preparation can take data from previous preparation and save tokens and time
4076
4110
  * TODO: [πŸ› ] Actions, instruments (and maybe knowledge) => Functions and tools
4111
+ * TODO: [🧠][♏] Maybe if expecting JSON (In Anthropic Claude and other models without non-json) and its not specified in prompt content, append the instructions
4112
+ * @see https://docs.anthropic.com/en/docs/test-and-evaluate/strengthen-guardrails/increase-consistency#specify-the-desired-output-format
4077
4113
  */
4078
4114
 
4079
4115
  /**