@promptbook/core 0.70.0-1 → 0.71.0-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +22 -59
  2. package/esm/index.es.js +1997 -1235
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/promptbook-collection/index.d.ts +0 -3
  5. package/esm/typings/src/_packages/core.index.d.ts +9 -1
  6. package/esm/typings/src/_packages/types.index.d.ts +12 -0
  7. package/esm/typings/src/_packages/utils.index.d.ts +4 -4
  8. package/esm/typings/src/cli/cli-commands/make.d.ts +1 -1
  9. package/esm/typings/src/collection/constructors/createCollectionFromUrl.d.ts +1 -1
  10. package/esm/typings/src/commands/FOREACH/ForeachCommand.d.ts +3 -7
  11. package/esm/typings/src/commands/FOREACH/ForeachJson.d.ts +23 -0
  12. package/esm/typings/src/commands/FOREACH/foreachCommandParser.d.ts +1 -2
  13. package/esm/typings/src/commands/_common/types/CommandParser.d.ts +4 -4
  14. package/esm/typings/src/config.d.ts +16 -3
  15. package/esm/typings/src/conversion/pipelineStringToJsonSync.d.ts +1 -1
  16. package/esm/typings/src/conversion/prettify/renderPipelineMermaidOptions.d.ts +3 -0
  17. package/esm/typings/src/conversion/utils/extractParameterNamesFromTemplate.d.ts +2 -1
  18. package/esm/typings/src/conversion/validation/validatePipeline.d.ts +10 -5
  19. package/esm/typings/src/execution/PipelineExecutorResult.d.ts +9 -8
  20. package/esm/typings/src/execution/createPipelineExecutor/$OngoingTemplateResult.d.ts +45 -0
  21. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorOptions.d.ts +20 -0
  22. package/esm/typings/src/execution/createPipelineExecutor/00-CreatePipelineExecutorSettings.d.ts +40 -0
  23. package/esm/typings/src/execution/createPipelineExecutor/00-createPipelineExecutor.d.ts +10 -0
  24. package/esm/typings/src/execution/createPipelineExecutor/10-executePipeline.d.ts +55 -0
  25. package/esm/typings/src/execution/createPipelineExecutor/20-executeTemplate.d.ts +62 -0
  26. package/esm/typings/src/execution/createPipelineExecutor/30-executeFormatCells.d.ts +19 -0
  27. package/esm/typings/src/execution/createPipelineExecutor/40-executeAttempts.d.ts +74 -0
  28. package/esm/typings/src/execution/createPipelineExecutor/filterJustOutputParameters.d.ts +34 -0
  29. package/esm/typings/src/execution/createPipelineExecutor/getContextForTemplate.d.ts +10 -0
  30. package/esm/typings/src/execution/createPipelineExecutor/getKnowledgeForTemplate.d.ts +27 -0
  31. package/esm/typings/src/execution/createPipelineExecutor/getReservedParametersForTemplate.d.ts +30 -0
  32. package/esm/typings/src/execution/createPipelineExecutor/getSamplesForTemplate.d.ts +10 -0
  33. package/esm/typings/src/execution/utils/checkExpectations.d.ts +2 -0
  34. package/esm/typings/src/execution/utils/usageToHuman.d.ts +3 -4
  35. package/esm/typings/src/formats/_common/FormatDefinition.d.ts +14 -15
  36. package/esm/typings/src/formats/_common/FormatSubvalueDefinition.d.ts +30 -0
  37. package/esm/typings/src/formats/csv/{ListFormatDefinition.d.ts → CsvFormatDefinition.d.ts} +6 -3
  38. package/esm/typings/src/formats/csv/CsvSettings.d.ts +13 -0
  39. package/esm/typings/src/formats/index.d.ts +1 -1
  40. package/esm/typings/src/formats/json/JsonFormatDefinition.d.ts +4 -3
  41. package/esm/typings/src/formats/text/TextFormatDefinition.d.ts +19 -0
  42. package/esm/typings/src/formats/xml/XmlFormatDefinition.d.ts +4 -3
  43. package/esm/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +1 -1
  44. package/esm/typings/src/knowledge/prepare-knowledge/pdf/prepareKnowledgeFromPdf.d.ts +1 -1
  45. package/esm/typings/src/llm-providers/_common/utils/cache/CacheItem.d.ts +1 -1
  46. package/esm/typings/src/llm-providers/anthropic-claude/anthropic-claude-models.d.ts +1 -1
  47. package/esm/typings/src/llm-providers/anthropic-claude/createAnthropicClaudeExecutionTools.d.ts +2 -2
  48. package/esm/typings/src/llm-providers/anthropic-claude/playground/playground.d.ts +2 -2
  49. package/esm/typings/src/llm-providers/openai/playground/playground.d.ts +1 -1
  50. package/esm/typings/src/personas/preparePersona.d.ts +1 -1
  51. package/esm/typings/src/prepare/isPipelinePrepared.d.ts +1 -1
  52. package/esm/typings/src/prepare/prepareTemplates.d.ts +1 -1
  53. package/esm/typings/src/types/PipelineJson/KnowledgeSourceJson.d.ts +9 -2
  54. package/esm/typings/src/types/PipelineJson/ParameterJson.d.ts +1 -0
  55. package/esm/typings/src/types/PipelineJson/PipelineJson.d.ts +1 -1
  56. package/esm/typings/src/types/PipelineJson/TemplateJsonCommon.d.ts +5 -0
  57. package/esm/typings/src/types/execution-report/ExecutionReportJson.d.ts +3 -0
  58. package/esm/typings/src/types/typeAliases.d.ts +1 -1
  59. package/esm/typings/src/utils/expectation-counters/index.d.ts +3 -0
  60. package/esm/typings/src/utils/organization/{f.d.ts → empty_object.d.ts} +5 -1
  61. package/esm/typings/src/utils/organization/just_empty_object.d.ts +12 -0
  62. package/esm/typings/src/utils/{extractParameterNames.d.ts → parameters/extractParameterNames.d.ts} +2 -2
  63. package/esm/typings/src/utils/parameters/mapAvailableToExpectedParameters.d.ts +27 -0
  64. package/esm/typings/src/utils/{replaceParameters.d.ts → parameters/replaceParameters.d.ts} +2 -2
  65. package/esm/typings/src/utils/serialization/checkSerializableAsJson.d.ts +1 -1
  66. package/esm/typings/src/utils/serialization/isSerializableAsJson.d.ts +1 -1
  67. package/esm/typings/src/utils/validators/parameterName/validateParameterName.d.ts +10 -0
  68. package/package.json +17 -12
  69. package/umd/index.umd.js +2003 -1238
  70. package/umd/index.umd.js.map +1 -1
  71. package/esm/typings/src/execution/createPipelineExecutor.d.ts +0 -72
  72. package/esm/typings/src/formats/list/ListFormatDefinition.d.ts +0 -16
  73. /package/esm/typings/src/utils/{extractParameterNames.test.d.ts → parameters/extractParameterNames.test.d.ts} +0 -0
  74. /package/esm/typings/src/{execution/utils/usageToHuman.test.d.ts → utils/parameters/mapAvailableToExpectedParameters.test.d.ts} +0 -0
  75. /package/esm/typings/src/utils/{replaceParameters.test.d.ts → parameters/replaceParameters.test.d.ts} +0 -0
  76. /package/esm/typings/src/{personas/preparePersona.test.d.ts → utils/validators/parameterName/validateParameterName.test.d.ts} +0 -0
package/esm/index.es.js CHANGED
@@ -2,6 +2,7 @@ import spaceTrim, { spaceTrim as spaceTrim$1 } from 'spacetrim';
2
2
  import { format } from 'prettier';
3
3
  import parserHtml from 'prettier/parser-html';
4
4
  import { forTime } from 'waitasecond';
5
+ import { unparse, parse } from 'papaparse';
5
6
  import hexEncoder from 'crypto-js/enc-hex';
6
7
  import sha256 from 'crypto-js/sha256';
7
8
  import moment from 'moment';
@@ -10,8 +11,8 @@ import moment from 'moment';
10
11
  /**
11
12
  * The version of the Promptbook library
12
13
  */
13
- var PROMPTBOOK_VERSION = '0.70.0-0';
14
- // TODO: !!!! List here all the versions and annotate + put into script
14
+ var PROMPTBOOK_VERSION = '0.70.0-1';
15
+ // TODO:[main] !!!! List here all the versions and annotate + put into script
15
16
 
16
17
  /*! *****************************************************************************
17
18
  Copyright (c) Microsoft Corporation.
@@ -223,7 +224,7 @@ function pipelineJsonToString(pipelineJson) {
223
224
  commands.push("PIPELINE URL ".concat(pipelineUrl));
224
225
  }
225
226
  commands.push("PROMPTBOOK VERSION ".concat(promptbookVersion));
226
- // TODO: !!! This increase size of the bundle and is probbably not necessary
227
+ // TODO:[main] !!! This increase size of the bundle and is probbably not necessary
227
228
  pipelineString = prettifyMarkdown(pipelineString);
228
229
  try {
229
230
  for (var _g = __values(parameters.filter(function (_a) {
@@ -371,12 +372,12 @@ function pipelineJsonToString(pipelineJson) {
371
372
  pipelineString += '```' + contentLanguage;
372
373
  pipelineString += '\n';
373
374
  pipelineString += spaceTrim(content);
374
- // <- TODO: !!! Escape
375
+ // <- TODO:[main] !!! Escape
375
376
  // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
376
377
  pipelineString += '\n';
377
378
  pipelineString += '```';
378
379
  pipelineString += '\n\n';
379
- pipelineString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO: !!! If the parameter here has description, add it and use templateParameterJsonToString
380
+ pipelineString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO:[main] !!! If the parameter here has description, add it and use templateParameterJsonToString
380
381
  }
381
382
  }
382
383
  catch (e_3_1) { e_3 = { error: e_3_1 }; }
@@ -596,7 +597,7 @@ function checkSerializableAsJson(name, value) {
596
597
  }
597
598
  /**
598
599
  * TODO: [🧠][🛣] More elegant way to tracking than passing `name`
599
- * TODO: [🧠] !!! In-memory cache of same values to prevent multiple checks
600
+ * TODO: [🧠][main] !!! In-memory cache of same values to prevent multiple checks
600
601
  * Note: [🐠] This is how `checkSerializableAsJson` + `isSerializableAsJson` together can just retun true/false or rich error message
601
602
  */
602
603
 
@@ -652,13 +653,13 @@ var IMMEDIATE_TIME = 10;
652
653
  *
653
654
  * @public exported from `@promptbook/core`
654
655
  */
655
- var MAX_PARALLEL_COUNT = 5;
656
+ var MAX_PARALLEL_COUNT = 5; // <- TODO: [🤹‍♂️]
656
657
  /**
657
658
  * The maximum number of attempts to execute LLM task before giving up
658
659
  *
659
660
  * @public exported from `@promptbook/core`
660
661
  */
661
- var MAX_EXECUTION_ATTEMPTS = 3;
662
+ var MAX_EXECUTION_ATTEMPTS = 3; // <- TODO: [🤹‍♂️]
662
663
  /**
663
664
  * The maximum length of the (generated) filename
664
665
  *
@@ -667,14 +668,14 @@ var MAX_EXECUTION_ATTEMPTS = 3;
667
668
  var MAX_FILENAME_LENGTH = 30;
668
669
  /**
669
670
  * @@@
670
- * TODO: [🐝] !!! Use
671
+ * TODO: [🐝][main] !!! Use
671
672
  *
672
673
  * @public exported from `@promptbook/core`
673
674
  */
674
675
  var MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH = 3;
675
676
  /**
676
677
  * @@@
677
- * TODO: [🐝] !!! Use
678
+ * TODO: [🐝][main] !!! Use
678
679
  *
679
680
  * @public exported from `@promptbook/core`
680
681
  */
@@ -709,6 +710,7 @@ var RESERVED_PARAMETER_NAMES = $asDeeplyFrozenSerializableJson('RESERVED_PARAMET
709
710
  'samples',
710
711
  'modelName',
711
712
  'currentDate',
713
+ // <- TODO: !!!!! list here all command names
712
714
  // <- TODO: Add more like 'date', 'modelName',...
713
715
  // <- TODO: Add [emoji] + instructions ACRY when adding new reserved parameter
714
716
  ]);
@@ -746,12 +748,32 @@ var DEFAULT_REMOTE_URL = 'https://api.pavolhejny.com/';
746
748
  */
747
749
  var DEFAULT_REMOTE_URL_PATH = '/promptbook/socket.io';
748
750
  // <- TODO: [🧜‍♂️]
751
+ /**
752
+ * @@@
753
+ *
754
+ * @public exported from `@promptbook/core`
755
+ */
756
+ var DEFAULT_CSV_SETTINGS = Object.freeze({
757
+ delimiter: ',',
758
+ quoteChar: '"',
759
+ newline: '\n',
760
+ skipEmptyLines: true,
761
+ });
749
762
  /**
750
763
  * @@@
751
764
  *
752
765
  * @public exported from `@promptbook/core`
753
766
  */
754
767
  var IS_VERBOSE = false;
768
+ /**
769
+ * @@@
770
+ *
771
+ * @private within the repository
772
+ */
773
+ var IS_PIPELINE_LOGIC_VALIDATED = just(
774
+ /**/
775
+ // Note: In normal situations, we check the pipeline logic:
776
+ true);
755
777
  /**
756
778
  * TODO: [🧠][🧜‍♂️] Maybe join remoteUrl and path into single value
757
779
  */
@@ -829,7 +851,7 @@ function isValidPromptbookVersion(version) {
829
851
  if ( /* version === '1.0.0' || */version === '2.0.0' || version === '3.0.0') {
830
852
  return false;
831
853
  }
832
- // <- TODO: !!! Check isValidPromptbookVersion against PROMPTBOOK_VERSIONS
854
+ // <- TODO:[main] !!! Check isValidPromptbookVersion against PROMPTBOOK_VERSIONS
833
855
  return true;
834
856
  }
835
857
 
@@ -961,6 +983,26 @@ function isValidPipelineUrl(url) {
961
983
  * @public exported from `@promptbook/core`
962
984
  */
963
985
  function validatePipeline(pipeline) {
986
+ if (IS_PIPELINE_LOGIC_VALIDATED) {
987
+ validatePipelineCore(pipeline);
988
+ }
989
+ else {
990
+ try {
991
+ validatePipelineCore(pipeline);
992
+ }
993
+ catch (error) {
994
+ if (!(error instanceof PipelineLogicError)) {
995
+ throw error;
996
+ }
997
+ console.error(spaceTrim$1(function (block) { return "\n Pipeline is not valid but logic errors are temporarily disabled via `IS_PIPELINE_LOGIC_VALIDATED`\n\n ".concat(block(error.message), "\n "); }));
998
+ }
999
+ }
1000
+ return pipeline;
1001
+ }
1002
+ /**
1003
+ * @private internal function for `validatePipeline`
1004
+ */
1005
+ function validatePipelineCore(pipeline) {
964
1006
  // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
965
1007
  var e_1, _a, e_2, _b, e_3, _c;
966
1008
  var pipelineIdentification = (function () {
@@ -978,19 +1020,19 @@ function validatePipeline(pipeline) {
978
1020
  // <- Note: [🚲]
979
1021
  throw new PipelineLogicError(spaceTrim$1(function (block) { return "\n Invalid promptbook URL \"".concat(pipeline.pipelineUrl, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
980
1022
  }
981
- if (!isValidPromptbookVersion(pipeline.promptbookVersion)) {
1023
+ if (pipeline.promptbookVersion !== undefined && !isValidPromptbookVersion(pipeline.promptbookVersion)) {
982
1024
  // <- Note: [🚲]
983
1025
  throw new PipelineLogicError(spaceTrim$1(function (block) { return "\n Invalid Promptbook Version \"".concat(pipeline.promptbookVersion, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
984
1026
  }
985
1027
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
986
1028
  if (!Array.isArray(pipeline.parameters)) {
987
1029
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
988
- throw new ParseError(spaceTrim$1(function (block) { return "\n Promptbook is valid JSON but with wrong structure\n\n `promptbook.parameters` expected to be an array, but got ".concat(typeof pipeline.parameters, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1030
+ throw new ParseError(spaceTrim$1(function (block) { return "\n Pipeline is valid JSON but with wrong structure\n\n `PipelineJson.parameters` expected to be an array, but got ".concat(typeof pipeline.parameters, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
989
1031
  }
990
1032
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
991
1033
  if (!Array.isArray(pipeline.templates)) {
992
1034
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
993
- throw new ParseError(spaceTrim$1(function (block) { return "\n Promptbook is valid JSON but with wrong structure\n\n `promptbook.templates` expected to be an array, but got ".concat(typeof pipeline.templates, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1035
+ throw new ParseError(spaceTrim$1(function (block) { return "\n Pipeline is valid JSON but with wrong structure\n\n `PipelineJson.templates` expected to be an array, but got ".concat(typeof pipeline.templates, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
994
1036
  }
995
1037
  var _loop_1 = function (parameter) {
996
1038
  if (parameter.isInput && parameter.isOutput) {
@@ -1159,9 +1201,9 @@ function validatePipeline(pipeline) {
1159
1201
  while (unresovedTemplates.length > 0) {
1160
1202
  _loop_3();
1161
1203
  }
1162
- return pipeline;
1163
1204
  }
1164
1205
  /**
1206
+ * TODO: !!!!! [🧞‍♀️] Do not allow joker + foreach
1165
1207
  * TODO: [🧠] Work with promptbookVersion
1166
1208
  * TODO: Use here some json-schema, Zod or something similar and change it to:
1167
1209
  * > /**
@@ -1173,11 +1215,11 @@ function validatePipeline(pipeline) {
1173
1215
  * > ex port function validatePipeline(promptbook: really_unknown): asserts promptbook is PipelineJson {
1174
1216
  */
1175
1217
  /**
1176
- * TODO: [🐣] !!!! Validate that all samples match expectations
1177
- * TODO: [🐣][🐝] !!!! Validate that knowledge is valid (non-void)
1178
- * TODO: [🐣] !!!! Validate that persona can be used only with CHAT variant
1179
- * TODO: [🐣] !!!! Validate that parameter with reserved name not used RESERVED_PARAMETER_NAMES
1180
- * TODO: [🐣] !!!! Validate that reserved parameter is not used as joker
1218
+ * TODO: [🐣][main] !!!! Validate that all samples match expectations
1219
+ * TODO: [🐣][🐝][main] !!!! Validate that knowledge is valid (non-void)
1220
+ * TODO: [🐣][main] !!!! Validate that persona can be used only with CHAT variant
1221
+ * TODO: [🐣][main] !!!! Validate that parameter with reserved name not used RESERVED_PARAMETER_NAMES
1222
+ * TODO: [🐣][main] !!!! Validate that reserved parameter is not used as joker
1181
1223
  * TODO: [🧠] Validation not only logic itself but imports around - files and websites and rerefenced pipelines exists
1182
1224
  * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
1183
1225
  */
@@ -1491,7 +1533,7 @@ function createCollectionFromUrl(url, options) {
1491
1533
  });
1492
1534
  }
1493
1535
  /**
1494
- * TODO: !!!! [🧠] Library precompilation and do not mix markdown and json promptbooks
1536
+ * TODO:[main] !!!! [🧠] Library precompilation and do not mix markdown and json promptbooks
1495
1537
  */
1496
1538
 
1497
1539
  /**
@@ -1788,7 +1830,7 @@ function forEachAsync(array, options, callbackfunction) {
1788
1830
  });
1789
1831
  }
1790
1832
 
1791
- var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.70.0-0",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",resultingParameterName:"knowledgePieces",dependentParameterNames:["knowledgeContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",promptbookVersion:"0.70.0-0",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",resultingParameterName:"keywords",dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",promptbookVersion:"0.70.0-0",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",resultingParameterName:"title",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",promptbookVersion:"0.70.0-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}],templates:[{templateType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
1833
+ var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",resultingParameterName:"knowledgePieces",dependentParameterNames:["knowledgeContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",resultingParameterName:"keywords",dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",resultingParameterName:"title",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
1792
1834
 
1793
1835
  var defaultDiacriticsRemovalMap = [
1794
1836
  {
@@ -2317,113 +2359,35 @@ function assertsExecutionSuccessful(executionResult) {
2317
2359
  */
2318
2360
 
2319
2361
  /**
2320
- * Parses the given script and returns the list of all used variables that are not defined in the script
2321
- *
2322
- * @param script from which to extract the variables
2323
- * @returns the list of variable names
2324
- * @throws {ParseError} if the script is invalid
2325
- * @public exported from `@promptbook/utils`
2326
- */
2327
- function extractVariables(script) {
2328
- var variables = new Set();
2329
- script = "(()=>{".concat(script, "})()");
2330
- try {
2331
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2332
- try {
2333
- eval(script);
2334
- }
2335
- catch (error) {
2336
- if (!(error instanceof ReferenceError)) {
2337
- throw error;
2338
- }
2339
- var undefinedName = error.message.split(' ')[0];
2340
- /*
2341
- Note: Parsing the error
2342
- [PipelineUrlError: thing is not defined]
2343
- */
2344
- if (!undefinedName) {
2345
- throw error;
2346
- }
2347
- if (script.includes(undefinedName + '(')) {
2348
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2349
- }
2350
- else {
2351
- variables.add(undefinedName);
2352
- script = "const ".concat(undefinedName, " = '';") + script;
2353
- }
2354
- }
2355
- }
2356
- catch (error) {
2357
- if (!(error instanceof Error)) {
2358
- throw error;
2359
- }
2360
- throw new ParseError(spaceTrim$1(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2361
- }
2362
- return variables;
2363
- }
2364
- /**
2365
- * TODO: [🔣] Support for multiple languages - python, java,...
2366
- */
2367
-
2368
- /**
2369
- * Parses the template and returns the set of all used parameters
2362
+ * Determine if the pipeline is fully prepared
2370
2363
  *
2371
- * @param template the template with used parameters
2372
- * @returns the set of parameter names
2373
- * @throws {ParseError} if the script is invalid
2374
- * @public exported from `@promptbook/utils`
2364
+ * @public exported from `@promptbook/core`
2375
2365
  */
2376
- function extractParameterNamesFromTemplate(template) {
2377
- var e_1, _a, e_2, _b, e_3, _c;
2378
- var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames;
2379
- var parameterNames = new Set();
2380
- try {
2381
- for (var _d = __values(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameterNames(title)), false), __read(extractParameterNames(description || '')), false), __read(extractParameterNames(content)), false), __read(extractParameterNames(preparedContent || '')), false)), _e = _d.next(); !_e.done; _e = _d.next()) {
2382
- var parameterName = _e.value;
2383
- parameterNames.add(parameterName);
2384
- }
2385
- }
2386
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2387
- finally {
2388
- try {
2389
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2390
- }
2391
- finally { if (e_1) throw e_1.error; }
2392
- }
2393
- if (templateType === 'SCRIPT_TEMPLATE') {
2394
- try {
2395
- for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2396
- var parameterName = _g.value;
2397
- parameterNames.add(parameterName);
2398
- }
2399
- }
2400
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2401
- finally {
2402
- try {
2403
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2404
- }
2405
- finally { if (e_2) throw e_2.error; }
2406
- }
2407
- }
2408
- try {
2409
- for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2410
- var jokerName = _j.value;
2411
- parameterNames.add(jokerName);
2412
- }
2366
+ function isPipelinePrepared(pipeline) {
2367
+ // Note: Ignoring `pipeline.preparations` @@@
2368
+ // Note: Ignoring `pipeline.knowledgePieces` @@@
2369
+ if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2370
+ return false;
2413
2371
  }
2414
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2415
- finally {
2416
- try {
2417
- if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2418
- }
2419
- finally { if (e_3) throw e_3.error; }
2372
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2373
+ return false;
2420
2374
  }
2421
- parameterNames.delete('content');
2422
- // <- Note {websiteContent} is used in `preparedContent`
2423
- return parameterNames;
2375
+ /*
2376
+ TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2377
+ > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2378
+ > return false;
2379
+ > }
2380
+ */
2381
+ return true;
2424
2382
  }
2425
2383
  /**
2426
- * TODO: [🔣] If script require contentLanguage
2384
+ * TODO: [🔃][main] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2385
+ * TODO: [🐠] Maybe base this on `makeValidator`
2386
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2387
+ * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2388
+ * - [🏍] ? Is context in each template
2389
+ * - [♨] Are samples prepared
2390
+ * - [♨] Are templates prepared
2427
2391
  */
2428
2392
 
2429
2393
  /**
@@ -2443,27 +2407,6 @@ function serializeError(error) {
2443
2407
  };
2444
2408
  }
2445
2409
 
2446
- /**
2447
- * Function isValidJsonString will tell you if the string is valid JSON or not
2448
- *
2449
- * @public exported from `@promptbook/utils`
2450
- */
2451
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
2452
- try {
2453
- JSON.parse(value);
2454
- return true;
2455
- }
2456
- catch (error) {
2457
- if (!(error instanceof Error)) {
2458
- throw error;
2459
- }
2460
- if (error.message.includes('Unexpected token')) {
2461
- return false;
2462
- }
2463
- return false;
2464
- }
2465
- }
2466
-
2467
2410
  /**
2468
2411
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2469
2412
  *
@@ -2490,9 +2433,10 @@ var MultipleLlmExecutionTools = /** @class */ (function () {
2490
2433
  });
2491
2434
  Object.defineProperty(MultipleLlmExecutionTools.prototype, "description", {
2492
2435
  get: function () {
2493
- return this.llmExecutionTools
2494
- .map(function (tools, index) { return "".concat(index + 1, ") ").concat(tools.title, " ").concat(tools.description || ''); })
2495
- .join('\n');
2436
+ return this.llmExecutionTools.map(function (_a, index) {
2437
+ var title = _a.title;
2438
+ return "".concat(index + 1, ") `").concat(title, "`");
2439
+ }).join('\n');
2496
2440
  },
2497
2441
  enumerable: false,
2498
2442
  configurable: true
@@ -2690,9 +2634,7 @@ var MultipleLlmExecutionTools = /** @class */ (function () {
2690
2634
  throw new PipelineExecutionError("You have not provided any `LlmExecutionTools`");
2691
2635
  }
2692
2636
  else {
2693
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n You have not provided any `LlmExecutionTools` that support model variant \"".concat(prompt.modelRequirements.modelVariant, "\n\n Available `LlmExecutionTools`:\n ").concat(block(_this.llmExecutionTools
2694
- .map(function (tools) { return "- ".concat(tools.title, " ").concat(tools.description || ''); })
2695
- .join('\n')), "\n\n "); }));
2637
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n You have not provided any `LlmExecutionTools` that support model variant \"".concat(prompt.modelRequirements.modelVariant, "\"\n\n Available `LlmExecutionTools`:\n ").concat(block(_this.description), "\n\n "); }));
2696
2638
  }
2697
2639
  }
2698
2640
  });
@@ -2758,288 +2700,153 @@ function joinLlmExecutionTools() {
2758
2700
  */
2759
2701
 
2760
2702
  /**
2761
- * Extracts all code blocks from markdown.
2703
+ * Takes an item or an array of items and returns an array of items
2762
2704
  *
2763
- * Note: There are multiple simmilar function:
2764
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2765
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2766
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2767
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2705
+ * 1) Any item except array and undefined returns array with that one item (also null)
2706
+ * 2) Undefined returns empty array
2707
+ * 3) Array returns itself
2768
2708
  *
2769
- * @param markdown any valid markdown
2770
- * @returns code blocks with language and content
2771
- * @throws {ParseError} if block is not closed properly
2772
- * @public exported from `@promptbook/markdown-utils`
2709
+ * @private internal utility
2773
2710
  */
2774
- function extractAllBlocksFromMarkdown(markdown) {
2775
- var e_1, _a;
2776
- var codeBlocks = [];
2777
- var lines = markdown.split('\n');
2778
- // Note: [0] Ensure that the last block notated by gt > will be closed
2779
- lines.push('');
2780
- var currentCodeBlock = null;
2781
- try {
2782
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2783
- var line = lines_1_1.value;
2784
- if (line.startsWith('> ') || line === '>') {
2785
- if (currentCodeBlock === null) {
2786
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2787
- } /* not else */
2788
- if (currentCodeBlock.blockNotation === '>') {
2789
- if (currentCodeBlock.content !== '') {
2790
- currentCodeBlock.content += '\n';
2791
- }
2792
- currentCodeBlock.content += line.slice(2);
2793
- }
2794
- }
2795
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2796
- codeBlocks.push(currentCodeBlock);
2797
- currentCodeBlock = null;
2798
- }
2799
- /* not else */
2800
- if (line.startsWith('```')) {
2801
- var language = line.slice(3).trim() || null;
2802
- if (currentCodeBlock === null) {
2803
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2804
- }
2805
- else {
2806
- if (language !== null) {
2807
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2808
- }
2809
- codeBlocks.push(currentCodeBlock);
2810
- currentCodeBlock = null;
2811
- }
2812
- }
2813
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2814
- if (currentCodeBlock.content !== '') {
2815
- currentCodeBlock.content += '\n';
2816
- }
2817
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2818
- }
2819
- }
2820
- }
2821
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2822
- finally {
2823
- try {
2824
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2825
- }
2826
- finally { if (e_1) throw e_1.error; }
2711
+ function arrayableToArray(input) {
2712
+ if (input === undefined) {
2713
+ return [];
2827
2714
  }
2828
- if (currentCodeBlock !== null) {
2829
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2715
+ if (input instanceof Array) {
2716
+ return input;
2830
2717
  }
2831
- return codeBlocks;
2718
+ return [input];
2832
2719
  }
2833
- /**
2834
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2835
- */
2836
2720
 
2837
2721
  /**
2838
- * Extracts extracts exactly one valid JSON code block
2839
- *
2840
- * - When given string is a valid JSON as it is, it just returns it
2841
- * - When there is no JSON code block the function throws a `ParseError`
2842
- * - When there are multiple JSON code blocks the function throws a `ParseError`
2843
- *
2844
- * Note: It is not important if marked as ```json BUT if it is VALID JSON
2845
- * Note: There are multiple simmilar function:
2846
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2847
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2848
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2849
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2722
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2850
2723
  *
2851
- * @public exported from `@promptbook/markdown-utils`
2852
- * @throws {ParseError} if there is no valid JSON block in the markdown
2853
- */
2854
- function extractJsonBlock(markdown) {
2855
- if (isValidJsonString(markdown)) {
2856
- return markdown;
2857
- }
2858
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2859
- var jsonBlocks = codeBlocks.filter(function (_a) {
2860
- var content = _a.content;
2861
- return isValidJsonString(content);
2862
- });
2863
- if (jsonBlocks.length === 0) {
2864
- throw new Error('There is no valid JSON block in the markdown');
2865
- }
2866
- if (jsonBlocks.length > 1) {
2867
- throw new Error('There are multiple JSON code blocks in the markdown');
2868
- }
2869
- return jsonBlocks[0].content;
2870
- }
2871
- /**
2872
- * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
2873
- * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2874
- */
2875
-
2876
- /**
2877
- * Determine if the pipeline is fully prepared
2878
- *
2879
- * @public exported from `@promptbook/core`
2880
- */
2881
- function isPipelinePrepared(pipeline) {
2882
- // Note: Ignoring `pipeline.preparations` @@@
2883
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2884
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2885
- return false;
2886
- }
2887
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2888
- return false;
2889
- }
2890
- /*
2891
- TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2892
- > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2893
- > return false;
2894
- > }
2895
- */
2896
- return true;
2897
- }
2898
- /**
2899
- * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2900
- * TODO: [🐠] Maybe base this on `makeValidator`
2901
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2902
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2903
- * - [🏍] ? Is context in each template
2904
- * - [♨] Are samples prepared
2905
- * - [♨] Are templates prepared
2906
- */
2907
-
2908
- /**
2909
- * Takes an item or an array of items and returns an array of items
2910
- *
2911
- * 1) Any item except array and undefined returns array with that one item (also null)
2912
- * 2) Undefined returns empty array
2913
- * 3) Array returns itself
2914
- *
2915
- * @private internal utility
2724
+ * @param script from which to extract the variables
2725
+ * @returns the list of variable names
2726
+ * @throws {ParseError} if the script is invalid
2727
+ * @public exported from `@promptbook/utils`
2916
2728
  */
2917
- function arrayableToArray(input) {
2918
- if (input === undefined) {
2919
- return [];
2920
- }
2921
- if (input instanceof Array) {
2922
- return input;
2729
+ function extractVariables(script) {
2730
+ var variables = new Set();
2731
+ script = "(()=>{".concat(script, "})()");
2732
+ try {
2733
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2734
+ try {
2735
+ eval(script);
2736
+ }
2737
+ catch (error) {
2738
+ if (!(error instanceof ReferenceError)) {
2739
+ throw error;
2740
+ }
2741
+ var undefinedName = error.message.split(' ')[0];
2742
+ /*
2743
+ Note: Parsing the error
2744
+ [PipelineUrlError: thing is not defined]
2745
+ */
2746
+ if (!undefinedName) {
2747
+ throw error;
2748
+ }
2749
+ if (script.includes(undefinedName + '(')) {
2750
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2751
+ }
2752
+ else {
2753
+ variables.add(undefinedName);
2754
+ script = "const ".concat(undefinedName, " = '';") + script;
2755
+ }
2756
+ }
2923
2757
  }
2924
- return [input];
2925
- }
2926
-
2927
- /**
2928
- * Just says that the variable is not used but should be kept
2929
- * No side effects.
2930
- *
2931
- * Note: It can be usefull for:
2932
- *
2933
- * 1) Suppressing eager optimization of unused imports
2934
- * 2) Suppressing eslint errors of unused variables in the tests
2935
- * 3) Keeping the type of the variable for type testing
2936
- *
2937
- * @param value any values
2938
- * @returns void
2939
- * @private within the repository
2940
- */
2941
- function keepUnused() {
2942
- var valuesToKeep = [];
2943
- for (var _i = 0; _i < arguments.length; _i++) {
2944
- valuesToKeep[_i] = arguments[_i];
2758
+ catch (error) {
2759
+ if (!(error instanceof Error)) {
2760
+ throw error;
2761
+ }
2762
+ throw new ParseError(spaceTrim$1(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2945
2763
  }
2764
+ return variables;
2946
2765
  }
2947
-
2948
2766
  /**
2949
- * Just marks a place of place where should be something implemented
2950
- * No side effects.
2951
- *
2952
- * Note: It can be usefull suppressing eslint errors of unused variables
2953
- *
2954
- * @param value any values
2955
- * @returns void
2956
- * @private within the repository
2767
+ * TODO: [🔣] Support for multiple languages - python, java,...
2957
2768
  */
2958
- function TODO_USE() {
2959
- var value = [];
2960
- for (var _i = 0; _i < arguments.length; _i++) {
2961
- value[_i] = arguments[_i];
2962
- }
2963
- }
2964
2769
 
2965
2770
  /**
2966
- * Replaces parameters in template with values from parameters object
2771
+ * Parses the template and returns the set of all used parameters
2967
2772
  *
2968
- * @param template the template with parameters in {curly} braces
2969
- * @param parameters the object with parameters
2970
- * @returns the template with replaced parameters
2971
- * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
2773
+ * @param template the template with used parameters
2774
+ * @returns the set of parameter names
2775
+ * @throws {ParseError} if the script is invalid
2972
2776
  * @public exported from `@promptbook/utils`
2973
2777
  */
2974
- function replaceParameters(template, parameters) {
2975
- var e_1, _a;
2778
+ function extractParameterNamesFromTemplate(template) {
2779
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
2780
+ var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2781
+ var parameterNames = new Set();
2976
2782
  try {
2977
- for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
2978
- var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
2979
- if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
2980
- throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
2981
- }
2982
- else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
2983
- // TODO: [🍵]
2984
- throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
2985
- }
2783
+ for (var _e = __values(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameterNames(title)), false), __read(extractParameterNames(description || '')), false), __read(extractParameterNames(content)), false), __read(extractParameterNames(preparedContent || '')), false)), _f = _e.next(); !_f.done; _f = _e.next()) {
2784
+ var parameterName = _f.value;
2785
+ parameterNames.add(parameterName);
2986
2786
  }
2987
2787
  }
2988
2788
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
2989
2789
  finally {
2990
2790
  try {
2991
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2791
+ if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
2992
2792
  }
2993
2793
  finally { if (e_1) throw e_1.error; }
2994
2794
  }
2995
- var replacedTemplate = template;
2996
- var match;
2997
- var loopLimit = LOOP_LIMIT;
2998
- var _loop_1 = function () {
2999
- if (loopLimit-- < 0) {
3000
- throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
2795
+ if (templateType === 'SCRIPT_TEMPLATE') {
2796
+ try {
2797
+ for (var _g = __values(extractVariables(content)), _h = _g.next(); !_h.done; _h = _g.next()) {
2798
+ var parameterName = _h.value;
2799
+ parameterNames.add(parameterName);
2800
+ }
3001
2801
  }
3002
- var precol = match.groups.precol;
3003
- var parameterName = match.groups.parameterName;
3004
- if (parameterName === '') {
3005
- return "continue";
2802
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2803
+ finally {
2804
+ try {
2805
+ if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
2806
+ }
2807
+ finally { if (e_2) throw e_2.error; }
3006
2808
  }
3007
- if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
3008
- throw new PipelineExecutionError('Parameter is already opened or not closed');
2809
+ }
2810
+ try {
2811
+ for (var _j = __values(jokerParameterNames || []), _k = _j.next(); !_k.done; _k = _j.next()) {
2812
+ var jokerName = _k.value;
2813
+ parameterNames.add(jokerName);
3009
2814
  }
3010
- if (parameters[parameterName] === undefined) {
3011
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2815
+ }
2816
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
2817
+ finally {
2818
+ try {
2819
+ if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
3012
2820
  }
3013
- var parameterValue = parameters[parameterName];
3014
- if (parameterValue === undefined) {
3015
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2821
+ finally { if (e_3) throw e_3.error; }
2822
+ }
2823
+ parameterNames.delete('content');
2824
+ // <- Note {websiteContent} is used in `preparedContent`
2825
+ // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2826
+ if (foreach !== undefined) {
2827
+ try {
2828
+ for (var _l = __values(foreach.subparameterNames), _m = _l.next(); !_m.done; _m = _l.next()) {
2829
+ var subparameterName = _m.value;
2830
+ if (parameterNames.has(subparameterName)) {
2831
+ parameterNames.delete(subparameterName);
2832
+ parameterNames.add(foreach.parameterName);
2833
+ // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2834
+ }
2835
+ }
3016
2836
  }
3017
- parameterValue = parameterValue.toString();
3018
- if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
3019
- parameterValue = parameterValue
3020
- .split('\n')
3021
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
3022
- .join('\n');
2837
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
2838
+ finally {
2839
+ try {
2840
+ if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
2841
+ }
2842
+ finally { if (e_4) throw e_4.error; }
3023
2843
  }
3024
- replacedTemplate =
3025
- replacedTemplate.substring(0, match.index + precol.length) +
3026
- parameterValue +
3027
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
3028
- };
3029
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
3030
- .exec(replacedTemplate))) {
3031
- _loop_1();
3032
- }
3033
- // [💫] Check if there are parameters that are not closed properly
3034
- if (/{\w+$/.test(replacedTemplate)) {
3035
- throw new PipelineExecutionError('Parameter is not closed');
3036
2844
  }
3037
- // [💫] Check if there are parameters that are not opened properly
3038
- if (/^\w+}/.test(replacedTemplate)) {
3039
- throw new PipelineExecutionError('Parameter is not opened');
3040
- }
3041
- return replacedTemplate;
2845
+ return parameterNames;
3042
2846
  }
2847
+ /**
2848
+ * TODO: [🔣] If script require contentLanguage
2849
+ */
3043
2850
 
3044
2851
  /**
3045
2852
  * Create difference set of two sets.
@@ -3117,117 +2924,351 @@ function union() {
3117
2924
  }
3118
2925
 
3119
2926
  /**
3120
- * Counts number of characters in the text
2927
+ * Just marks a place of place where should be something implemented
2928
+ * No side effects.
3121
2929
  *
3122
- * @public exported from `@promptbook/utils`
2930
+ * Note: It can be usefull suppressing eslint errors of unused variables
2931
+ *
2932
+ * @param value any values
2933
+ * @returns void
2934
+ * @private within the repository
3123
2935
  */
3124
- function countCharacters(text) {
3125
- // Remove null characters
3126
- text = text.replace(/\0/g, '');
3127
- // Replace emojis (and also ZWJ sequence) with hyphens
3128
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3129
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
3130
- text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
3131
- return text.length;
2936
+ function TODO_USE() {
2937
+ var value = [];
2938
+ for (var _i = 0; _i < arguments.length; _i++) {
2939
+ value[_i] = arguments[_i];
2940
+ }
3132
2941
  }
3133
2942
 
3134
2943
  /**
3135
- * Counts number of lines in the text
2944
+ * @@@
3136
2945
  *
3137
- * @public exported from `@promptbook/utils`
2946
+ * @public exported from `@promptbook/core`
3138
2947
  */
3139
- function countLines(text) {
3140
- if (text === '') {
3141
- return 0;
3142
- }
3143
- return text.split('\n').length;
3144
- }
2948
+ var MANDATORY_CSV_SETTINGS = Object.freeze({
2949
+ header: true,
2950
+ // encoding: 'utf8',
2951
+ });
3145
2952
 
3146
2953
  /**
3147
- * Counts number of pages in the text
2954
+ * Definition for CSV spreadsheet
3148
2955
  *
3149
- * @public exported from `@promptbook/utils`
2956
+ * @public exported from `@promptbook/core`
2957
+ * <- TODO: [🏢] Export from package `@promptbook/csv`
2958
+ */
2959
+ var CsvFormatDefinition = {
2960
+ formatName: 'CSV',
2961
+ aliases: ['SPREADSHEET', 'TABLE'],
2962
+ isValid: function (value, settings, schema) {
2963
+ // TODO: !!!!!! Implement CSV validation
2964
+ TODO_USE(value /* <- TODO: Use value here */);
2965
+ TODO_USE(settings /* <- TODO: Use settings here */);
2966
+ TODO_USE(schema /* <- TODO: Use schema here */);
2967
+ return true;
2968
+ },
2969
+ canBeValid: function (partialValue, settings, schema) {
2970
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2971
+ TODO_USE(settings /* <- TODO: Use settings here */);
2972
+ TODO_USE(schema /* <- TODO: Use schema here */);
2973
+ return true;
2974
+ },
2975
+ heal: function (value, settings, schema) {
2976
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2977
+ TODO_USE(settings /* <- TODO: Use settings here */);
2978
+ TODO_USE(schema /* <- TODO: Use schema here */);
2979
+ throw new Error('Not implemented');
2980
+ },
2981
+ subvalueDefinitions: [
2982
+ {
2983
+ subvalueName: 'ROW',
2984
+ mapValues: function (value, settings, mapCallback) {
2985
+ return __awaiter(this, void 0, void 0, function () {
2986
+ var csv, mappedData;
2987
+ var _this = this;
2988
+ return __generator(this, function (_a) {
2989
+ switch (_a.label) {
2990
+ case 0:
2991
+ csv = parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
2992
+ if (csv.errors.length !== 0) {
2993
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2994
+ spaceTrim(function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
2995
+ }
2996
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, index) { return __awaiter(_this, void 0, void 0, function () {
2997
+ var _a;
2998
+ var _b;
2999
+ return __generator(this, function (_c) {
3000
+ switch (_c.label) {
3001
+ case 0:
3002
+ _a = [__assign({}, row)];
3003
+ _b = {};
3004
+ // <- TODO: !!!!!! Dynamic new column name and position
3005
+ // <- TODO: !!!!!! Check name collisions
3006
+ return [4 /*yield*/, mapCallback(row, index)];
3007
+ case 1: return [2 /*return*/, (__assign.apply(void 0, _a.concat([(_b.newColumn =
3008
+ // <- TODO: !!!!!! Dynamic new column name and position
3009
+ // <- TODO: !!!!!! Check name collisions
3010
+ _c.sent(), _b)])))];
3011
+ }
3012
+ });
3013
+ }); }))];
3014
+ case 1:
3015
+ mappedData = _a.sent();
3016
+ return [2 /*return*/, unparse(mappedData, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS))];
3017
+ }
3018
+ });
3019
+ });
3020
+ },
3021
+ },
3022
+ {
3023
+ subvalueName: 'CELL',
3024
+ mapValues: function (value, settings, mapCallback) {
3025
+ return __awaiter(this, void 0, void 0, function () {
3026
+ var csv, mappedData;
3027
+ var _this = this;
3028
+ return __generator(this, function (_a) {
3029
+ switch (_a.label) {
3030
+ case 0:
3031
+ csv = parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
3032
+ if (csv.errors.length !== 0) {
3033
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
3034
+ spaceTrim(function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
3035
+ }
3036
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, rowIndex) { return __awaiter(_this, void 0, void 0, function () {
3037
+ var _this = this;
3038
+ return __generator(this, function (_a) {
3039
+ return [2 /*return*/, /* not await */ Promise.all(Object.entries(row).map(function (_a, columnIndex) {
3040
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
3041
+ return __awaiter(_this, void 0, void 0, function () {
3042
+ var index;
3043
+ var _c;
3044
+ return __generator(this, function (_d) {
3045
+ index = rowIndex * Object.keys(row).length + columnIndex;
3046
+ return [2 /*return*/, /* not await */ mapCallback((_c = {}, _c[key] = value, _c), index)];
3047
+ });
3048
+ });
3049
+ }))];
3050
+ });
3051
+ }); }))];
3052
+ case 1:
3053
+ mappedData = _a.sent();
3054
+ return [2 /*return*/, unparse(mappedData, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS))];
3055
+ }
3056
+ });
3057
+ });
3058
+ },
3059
+ },
3060
+ ],
3061
+ };
3062
+ /**
3063
+ * TODO: [🍓] In `CsvFormatDefinition` implement simple `isValid`
3064
+ * TODO: [🍓] In `CsvFormatDefinition` implement partial `canBeValid`
3065
+ * TODO: [🍓] In `CsvFormatDefinition` implement `heal
3066
+ * TODO: [🍓] In `CsvFormatDefinition` implement `subvalueDefinitions`
3067
+ * TODO: [🏢] Allow to expect something inside CSV objects and other formats
3150
3068
  */
3151
- function countPages(text) {
3152
- var sentencesPerPage = 5; // Assuming each page has 5 sentences
3153
- var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3154
- var pageCount = Math.ceil(sentences.length / sentencesPerPage);
3155
- return pageCount;
3156
- }
3157
3069
 
3158
3070
  /**
3159
- * Counts number of paragraphs in the text
3071
+ * Function isValidJsonString will tell you if the string is valid JSON or not
3160
3072
  *
3161
3073
  * @public exported from `@promptbook/utils`
3162
3074
  */
3163
- function countParagraphs(text) {
3164
- return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
3075
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
3076
+ try {
3077
+ JSON.parse(value);
3078
+ return true;
3079
+ }
3080
+ catch (error) {
3081
+ if (!(error instanceof Error)) {
3082
+ throw error;
3083
+ }
3084
+ if (error.message.includes('Unexpected token')) {
3085
+ return false;
3086
+ }
3087
+ return false;
3088
+ }
3165
3089
  }
3166
3090
 
3167
3091
  /**
3168
- * Split text into sentences
3092
+ * Definition for JSON format
3169
3093
  *
3170
- * @public exported from `@promptbook/utils`
3094
+ * @private still in development [🏢]
3171
3095
  */
3172
- function splitIntoSentences(text) {
3173
- return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3174
- }
3096
+ var JsonFormatDefinition = {
3097
+ formatName: 'JSON',
3098
+ mimeType: 'application/json',
3099
+ isValid: function (value, settings, schema) {
3100
+ TODO_USE(schema /* <- TODO: Use schema here */);
3101
+ TODO_USE(settings /* <- TODO: Use settings here */);
3102
+ return isValidJsonString(value);
3103
+ },
3104
+ canBeValid: function (partialValue, settings, schema) {
3105
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
3106
+ TODO_USE(settings /* <- TODO: Use settings here */);
3107
+ TODO_USE(schema /* <- TODO: Use schema here */);
3108
+ return true;
3109
+ },
3110
+ heal: function (value, settings, schema) {
3111
+ TODO_USE(value /* <- TODO: Use partialValue here */);
3112
+ TODO_USE(settings /* <- TODO: Use settings here */);
3113
+ TODO_USE(schema /* <- TODO: Use schema here */);
3114
+ throw new Error('Not implemented');
3115
+ },
3116
+ subvalueDefinitions: [],
3117
+ };
3175
3118
  /**
3176
- * Counts number of sentences in the text
3177
- *
3178
- * @public exported from `@promptbook/utils`
3119
+ * TODO: [🧠] Maybe propper instance of object
3120
+ * TODO: [0] Make string_serialized_json
3121
+ * TODO: [1] Make type for JSON Settings and Schema
3122
+ * TODO: [🧠] What to use for validating JSONs - JSON Schema, ZoD, typescript types/interfaces,...?
3123
+ * TODO: [🍓] In `JsonFormatDefinition` implement simple `isValid`
3124
+ * TODO: [🍓] In `JsonFormatDefinition` implement partial `canBeValid`
3125
+ * TODO: [🍓] In `JsonFormatDefinition` implement `heal
3126
+ * TODO: [🍓] In `JsonFormatDefinition` implement `subvalueDefinitions`
3127
+ * TODO: [🏢] Allow to expect something inside JSON objects and other formats
3179
3128
  */
3180
- function countSentences(text) {
3181
- return splitIntoSentences(text).length;
3182
- }
3183
3129
 
3184
3130
  /**
3185
- * Counts number of words in the text
3131
+ * Definition for any text - this will be always valid
3186
3132
  *
3187
- * @public exported from `@promptbook/utils`
3133
+ * Note: This is not useful for validation, but for splitting and mapping with `subvalueDefinitions`
3134
+ *
3135
+ * @public exported from `@promptbook/core`
3136
+ */
3137
+ var TextFormatDefinition = {
3138
+ formatName: 'TEXT',
3139
+ isValid: function (value) {
3140
+ return typeof value === 'string';
3141
+ },
3142
+ canBeValid: function (partialValue) {
3143
+ return typeof partialValue === 'string';
3144
+ },
3145
+ heal: function () {
3146
+ throw new UnexpectedError('It does not make sense to call `TextFormatDefinition.heal`');
3147
+ },
3148
+ subvalueDefinitions: [
3149
+ {
3150
+ subvalueName: 'LINE',
3151
+ mapValues: function (value, settings, mapCallback) {
3152
+ return __awaiter(this, void 0, void 0, function () {
3153
+ var lines, mappedLines;
3154
+ return __generator(this, function (_a) {
3155
+ switch (_a.label) {
3156
+ case 0:
3157
+ lines = value.split('\n');
3158
+ return [4 /*yield*/, Promise.all(lines.map(function (lineContent, lineNumber) {
3159
+ // TODO: [🧠] Maybe option to skip empty line
3160
+ /* not await */ return mapCallback({
3161
+ lineContent: lineContent,
3162
+ // TODO: [🧠] Maybe also put here `lineNumber`
3163
+ }, lineNumber);
3164
+ }))];
3165
+ case 1:
3166
+ mappedLines = _a.sent();
3167
+ return [2 /*return*/, mappedLines.join('\n')];
3168
+ }
3169
+ });
3170
+ });
3171
+ },
3172
+ },
3173
+ // <- TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3174
+ ],
3175
+ };
3176
+ /**
3177
+ * TODO: [1] Make type for XML Text and Schema
3178
+ * TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3179
+ * TODO: [🍓] In `TextFormatDefinition` implement simple `isValid`
3180
+ * TODO: [🍓] In `TextFormatDefinition` implement partial `canBeValid`
3181
+ * TODO: [🍓] In `TextFormatDefinition` implement `heal
3182
+ * TODO: [🍓] In `TextFormatDefinition` implement `subvalueDefinitions`
3183
+ * TODO: [🏢] Allow to expect something inside each item of list and other formats
3188
3184
  */
3189
- function countWords(text) {
3190
- text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3191
- text = removeDiacritics(text);
3192
- return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3193
- }
3194
3185
 
3195
3186
  /**
3196
- * Index of all counter functions
3187
+ * Definition for XML format
3197
3188
  *
3198
- * @public exported from `@promptbook/utils`
3189
+ * @private still in development [🏢]
3199
3190
  */
3200
- var CountUtils = {
3201
- CHARACTERS: countCharacters,
3202
- WORDS: countWords,
3203
- SENTENCES: countSentences,
3204
- PARAGRAPHS: countParagraphs,
3205
- LINES: countLines,
3206
- PAGES: countPages,
3191
+ var XmlFormatDefinition = {
3192
+ formatName: 'XML',
3193
+ mimeType: 'application/xml',
3194
+ isValid: function (value, settings, schema) {
3195
+ TODO_USE(value /* <- TODO: Use value here */);
3196
+ TODO_USE(settings /* <- TODO: Use settings here */);
3197
+ TODO_USE(schema /* <- TODO: Use schema here */);
3198
+ return true;
3199
+ },
3200
+ canBeValid: function (partialValue, settings, schema) {
3201
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
3202
+ TODO_USE(settings /* <- TODO: Use settings here */);
3203
+ TODO_USE(schema /* <- TODO: Use schema here */);
3204
+ return true;
3205
+ },
3206
+ heal: function (value, settings, schema) {
3207
+ TODO_USE(value /* <- TODO: Use partialValue here */);
3208
+ TODO_USE(settings /* <- TODO: Use settings here */);
3209
+ TODO_USE(schema /* <- TODO: Use schema here */);
3210
+ throw new Error('Not implemented');
3211
+ },
3212
+ subvalueDefinitions: [],
3207
3213
  };
3214
+ /**
3215
+ * TODO: [🧠] Maybe propper instance of object
3216
+ * TODO: [0] Make string_serialized_xml
3217
+ * TODO: [1] Make type for XML Settings and Schema
3218
+ * TODO: [🧠] What to use for validating XMLs - XSD,...
3219
+ * TODO: [🍓] In `XmlFormatDefinition` implement simple `isValid`
3220
+ * TODO: [🍓] In `XmlFormatDefinition` implement partial `canBeValid`
3221
+ * TODO: [🍓] In `XmlFormatDefinition` implement `heal
3222
+ * TODO: [🍓] In `XmlFormatDefinition` implement `subvalueDefinitions`
3223
+ * TODO: [🏢] Allow to expect something inside XML and other formats
3224
+ */
3208
3225
 
3209
3226
  /**
3210
- * Function checkExpectations will check if the expectations on given value are met
3227
+ * Definitions for all formats supported by Promptbook
3211
3228
  *
3212
- * Note: There are two simmilar functions:
3213
- * - `checkExpectations` which throws an error if the expectations are not met
3214
- * - `isPassingExpectations` which returns a boolean
3229
+ * @private internal index of `...` <- TODO [🏢]
3230
+ */
3231
+ var FORMAT_DEFINITIONS = [
3232
+ JsonFormatDefinition,
3233
+ XmlFormatDefinition,
3234
+ TextFormatDefinition,
3235
+ CsvFormatDefinition,
3236
+ ];
3237
+
3238
+ /**
3239
+ * Maps available parameters to expected parameters
3215
3240
  *
3216
- * @throws {ExpectError} if the expectations are not met
3217
- * @returns {void} Nothing
3218
- * @private internal function of `createPipelineExecutor`
3241
+ * The strategy is:
3242
+ * 1) @@@
3243
+ * 2) @@@
3244
+ *
3245
+ * @throws {PipelineExecutionError} @@@
3246
+ * @private within the repository used in `createPipelineExecutor`
3219
3247
  */
3220
- function checkExpectations(expectations, value) {
3248
+ function mapAvailableToExpectedParameters(options) {
3221
3249
  var e_1, _a;
3250
+ var expectedParameters = options.expectedParameters, availableParameters = options.availableParameters;
3251
+ var availableParametersNames = new Set(Object.keys(availableParameters));
3252
+ var expectedParameterNames = new Set(Object.keys(expectedParameters));
3253
+ var mappedParameters = {};
3222
3254
  try {
3223
- for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3224
- var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3225
- var amount = CountUtils[unit.toUpperCase()](value);
3226
- if (min && amount < min) {
3227
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3228
- } /* not else */
3229
- if (max && amount > max) {
3230
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3255
+ // Phase 1️⃣: Matching mapping
3256
+ for (var _b = __values(Array.from(union(availableParametersNames, expectedParameterNames))), _c = _b.next(); !_c.done; _c = _b.next()) {
3257
+ var parameterName = _c.value;
3258
+ // Situation: Parameter is available and expected
3259
+ if (availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3260
+ mappedParameters[parameterName] = availableParameters[parameterName];
3261
+ // <- Note: [👩‍👩‍👧] Maybe detect parameter collision here?
3262
+ availableParametersNames.delete(parameterName);
3263
+ expectedParameterNames.delete(parameterName);
3264
+ }
3265
+ // Situation: Parameter is available but NOT expected
3266
+ else if (availableParametersNames.has(parameterName) && !expectedParameterNames.has(parameterName)) {
3267
+ // [🐱‍👤] Do not pass this parameter to prompt - Maybe use it non-matching mapping
3268
+ }
3269
+ // Situation: Parameter is NOT available BUT expected
3270
+ else if (!availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3271
+ // Do nothing here - this will be maybe fixed in the non-matching mapping
3231
3272
  }
3232
3273
  }
3233
3274
  }
@@ -3238,622 +3279,1139 @@ function checkExpectations(expectations, value) {
3238
3279
  }
3239
3280
  finally { if (e_1) throw e_1.error; }
3240
3281
  }
3282
+ if (expectedParameterNames.size === 0) {
3283
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3284
+ Object.freeze(mappedParameters);
3285
+ return mappedParameters;
3286
+ }
3287
+ // Phase 2️⃣: Non-matching mapping
3288
+ if (expectedParameterNames.size !== availableParametersNames.size) {
3289
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n Can not map available parameters to expected parameters\n\n Mapped parameters:\n ".concat(block(Object.keys(mappedParameters)
3290
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3291
+ .join('\n')), "\n\n Expected parameters which can not be mapped:\n ").concat(block(Array.from(expectedParameterNames)
3292
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3293
+ .join('\n')), "\n\n Remaining available parameters:\n ").concat(block(Array.from(availableParametersNames)
3294
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3295
+ .join('\n')), "\n\n "); }));
3296
+ }
3297
+ var expectedParameterNamesArray = Array.from(expectedParameterNames);
3298
+ var availableParametersNamesArray = Array.from(availableParametersNames);
3299
+ for (var i = 0; i < expectedParameterNames.size; i++) {
3300
+ mappedParameters[expectedParameterNamesArray[i]] = availableParameters[availableParametersNamesArray[i]];
3301
+ }
3302
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3303
+ Object.freeze(mappedParameters);
3304
+ return mappedParameters;
3241
3305
  }
3306
+
3242
3307
  /**
3243
- * Function checkExpectations will check if the expectations on given value are met
3308
+ * Extracts all code blocks from markdown.
3244
3309
  *
3245
- * Note: There are two simmilar functions:
3246
- * - `checkExpectations` which throws an error if the expectations are not met
3247
- * - `isPassingExpectations` which returns a boolean
3310
+ * Note: There are multiple simmilar function:
3311
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3312
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3313
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3314
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3248
3315
  *
3249
- * @returns {boolean} True if the expectations are met
3250
- * @public exported from `@promptbook/core`
3316
+ * @param markdown any valid markdown
3317
+ * @returns code blocks with language and content
3318
+ * @throws {ParseError} if block is not closed properly
3319
+ * @public exported from `@promptbook/markdown-utils`
3251
3320
  */
3252
- function isPassingExpectations(expectations, value) {
3321
+ function extractAllBlocksFromMarkdown(markdown) {
3322
+ var e_1, _a;
3323
+ var codeBlocks = [];
3324
+ var lines = markdown.split('\n');
3325
+ // Note: [0] Ensure that the last block notated by gt > will be closed
3326
+ lines.push('');
3327
+ var currentCodeBlock = null;
3253
3328
  try {
3254
- checkExpectations(expectations, value);
3255
- return true;
3329
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
3330
+ var line = lines_1_1.value;
3331
+ if (line.startsWith('> ') || line === '>') {
3332
+ if (currentCodeBlock === null) {
3333
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
3334
+ } /* not else */
3335
+ if (currentCodeBlock.blockNotation === '>') {
3336
+ if (currentCodeBlock.content !== '') {
3337
+ currentCodeBlock.content += '\n';
3338
+ }
3339
+ currentCodeBlock.content += line.slice(2);
3340
+ }
3341
+ }
3342
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
3343
+ codeBlocks.push(currentCodeBlock);
3344
+ currentCodeBlock = null;
3345
+ }
3346
+ /* not else */
3347
+ if (line.startsWith('```')) {
3348
+ var language = line.slice(3).trim() || null;
3349
+ if (currentCodeBlock === null) {
3350
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
3351
+ }
3352
+ else {
3353
+ if (language !== null) {
3354
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
3355
+ }
3356
+ codeBlocks.push(currentCodeBlock);
3357
+ currentCodeBlock = null;
3358
+ }
3359
+ }
3360
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
3361
+ if (currentCodeBlock.content !== '') {
3362
+ currentCodeBlock.content += '\n';
3363
+ }
3364
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
3365
+ }
3366
+ }
3256
3367
  }
3257
- catch (error) {
3258
- if (!(error instanceof ExpectError)) {
3259
- throw error;
3368
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3369
+ finally {
3370
+ try {
3371
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
3260
3372
  }
3261
- return false;
3373
+ finally { if (e_1) throw e_1.error; }
3374
+ }
3375
+ if (currentCodeBlock !== null) {
3376
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
3262
3377
  }
3378
+ return codeBlocks;
3263
3379
  }
3264
3380
  /**
3265
- * TODO: [💝] Unite object for expecting amount and format
3381
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
3266
3382
  */
3267
3383
 
3268
3384
  /**
3269
- * Creates executor function from pipeline and execution tools.
3385
+ * Extracts extracts exactly one valid JSON code block
3270
3386
  *
3271
- * @returns The executor function
3272
- * @throws {PipelineLogicError} on logical error in the pipeline
3273
- * @public exported from `@promptbook/core`
3387
+ * - When given string is a valid JSON as it is, it just returns it
3388
+ * - When there is no JSON code block the function throws a `ParseError`
3389
+ * - When there are multiple JSON code blocks the function throws a `ParseError`
3390
+ *
3391
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
3392
+ * Note: There are multiple simmilar function:
3393
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3394
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3395
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3396
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3397
+ *
3398
+ * @public exported from `@promptbook/markdown-utils`
3399
+ * @throws {ParseError} if there is no valid JSON block in the markdown
3274
3400
  */
3275
- function createPipelineExecutor(options) {
3276
- var _this = this;
3277
- var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
3278
- 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;
3279
- validatePipeline(pipeline);
3280
- var pipelineIdentification = (function () {
3281
- // Note: This is a 😐 implementation of [🚞]
3282
- var _ = [];
3283
- if (pipeline.sourceFile !== undefined) {
3284
- _.push("File: ".concat(pipeline.sourceFile));
3285
- }
3286
- if (pipeline.pipelineUrl !== undefined) {
3287
- _.push("Url: ".concat(pipeline.pipelineUrl));
3288
- }
3289
- return _.join('\n');
3290
- })();
3291
- var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3292
- var preparedPipeline;
3293
- if (isPipelinePrepared(pipeline)) {
3294
- preparedPipeline = pipeline;
3401
+ function extractJsonBlock(markdown) {
3402
+ if (isValidJsonString(markdown)) {
3403
+ return markdown;
3295
3404
  }
3296
- else if (isNotPreparedWarningSupressed !== true) {
3297
- console.warn(spaceTrim$1(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 "); }));
3405
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
3406
+ var jsonBlocks = codeBlocks.filter(function (_a) {
3407
+ var content = _a.content;
3408
+ return isValidJsonString(content);
3409
+ });
3410
+ if (jsonBlocks.length === 0) {
3411
+ throw new Error('There is no valid JSON block in the markdown');
3298
3412
  }
3299
- var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
3300
- // TODO: !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
3301
- function getContextForTemplate(template) {
3302
- return __awaiter(this, void 0, void 0, function () {
3303
- return __generator(this, function (_a) {
3304
- TODO_USE(template);
3305
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3306
- });
3307
- });
3413
+ if (jsonBlocks.length > 1) {
3414
+ throw new Error('There are multiple JSON code blocks in the markdown');
3415
+ }
3416
+ return jsonBlocks[0].content;
3417
+ }
3418
+ /**
3419
+ * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
3420
+ * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
3421
+ */
3422
+
3423
+ /**
3424
+ * Just says that the variable is not used but should be kept
3425
+ * No side effects.
3426
+ *
3427
+ * Note: It can be usefull for:
3428
+ *
3429
+ * 1) Suppressing eager optimization of unused imports
3430
+ * 2) Suppressing eslint errors of unused variables in the tests
3431
+ * 3) Keeping the type of the variable for type testing
3432
+ *
3433
+ * @param value any values
3434
+ * @returns void
3435
+ * @private within the repository
3436
+ */
3437
+ function keepUnused() {
3438
+ var valuesToKeep = [];
3439
+ for (var _i = 0; _i < arguments.length; _i++) {
3440
+ valuesToKeep[_i] = arguments[_i];
3441
+ }
3442
+ }
3443
+
3444
+ /**
3445
+ * Replaces parameters in template with values from parameters object
3446
+ *
3447
+ * @param template the template with parameters in {curly} braces
3448
+ * @param parameters the object with parameters
3449
+ * @returns the template with replaced parameters
3450
+ * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
3451
+ * @public exported from `@promptbook/utils`
3452
+ */
3453
+ function replaceParameters(template, parameters) {
3454
+ var e_1, _a;
3455
+ try {
3456
+ for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
3457
+ var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
3458
+ if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
3459
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
3460
+ }
3461
+ else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
3462
+ // TODO: [🍵]
3463
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
3464
+ }
3308
3465
  }
3309
- function getKnowledgeForTemplate(template) {
3310
- return __awaiter(this, void 0, void 0, function () {
3311
- return __generator(this, function (_a) {
3312
- // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3313
- TODO_USE(template);
3314
- return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3315
- var content = _a.content;
3316
- return "- ".concat(content);
3317
- }).join('\n')];
3318
- });
3319
- });
3466
+ }
3467
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3468
+ finally {
3469
+ try {
3470
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3320
3471
  }
3321
- function getSamplesForTemplate(template) {
3322
- return __awaiter(this, void 0, void 0, function () {
3323
- return __generator(this, function (_a) {
3324
- // TODO: [♨] Implement Better - use real index and keyword search
3325
- TODO_USE(template);
3326
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3327
- });
3328
- });
3472
+ finally { if (e_1) throw e_1.error; }
3473
+ }
3474
+ var replacedTemplate = template;
3475
+ var match;
3476
+ var loopLimit = LOOP_LIMIT;
3477
+ var _loop_1 = function () {
3478
+ if (loopLimit-- < 0) {
3479
+ throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
3329
3480
  }
3330
- function getReservedParametersForTemplate(template) {
3331
- return __awaiter(this, void 0, void 0, function () {
3332
- var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3333
- var e_3, _a;
3334
- return __generator(this, function (_b) {
3335
- switch (_b.label) {
3336
- case 0: return [4 /*yield*/, getContextForTemplate(template)];
3337
- case 1:
3338
- context = _b.sent();
3339
- return [4 /*yield*/, getKnowledgeForTemplate(template)];
3340
- case 2:
3341
- knowledge = _b.sent();
3342
- return [4 /*yield*/, getSamplesForTemplate(template)];
3343
- case 3:
3344
- samples = _b.sent();
3345
- currentDate = new Date().toISOString();
3346
- modelName = RESERVED_PARAMETER_MISSING_VALUE;
3347
- reservedParameters = {
3348
- content: RESERVED_PARAMETER_RESTRICTED,
3349
- context: context,
3350
- knowledge: knowledge,
3351
- samples: samples,
3352
- currentDate: currentDate,
3353
- modelName: modelName,
3354
- };
3355
- _loop_3 = function (parameterName) {
3356
- if (reservedParameters[parameterName] === undefined) {
3357
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3358
- }
3359
- };
3360
- try {
3361
- // Note: Doublecheck that ALL reserved parameters are defined:
3362
- 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()) {
3363
- parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3364
- _loop_3(parameterName);
3365
- }
3366
- }
3367
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
3368
- finally {
3369
- try {
3370
- if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3371
- }
3372
- finally { if (e_3) throw e_3.error; }
3373
- }
3374
- return [2 /*return*/, reservedParameters];
3375
- }
3376
- });
3377
- });
3481
+ var precol = match.groups.precol;
3482
+ var parameterName = match.groups.parameterName;
3483
+ if (parameterName === '') {
3484
+ return "continue";
3378
3485
  }
3379
- function executeSingleTemplate(currentTemplate) {
3380
- return __awaiter(this, void 0, void 0, function () {
3381
- var name, title, priority, progress_1, usedParameterNames, dependentParameterNames, definedParameters, _a, _b, _c, definedParameterNames, parameters, _loop_4, _d, _e, parameterName, prompt, chatResult, completionResult, embeddingResult, result, resultString, expectError, scriptPipelineExecutionErrors, maxAttempts, jokerParameterNames, preparedContent, _loop_5, attempt, state_2, progress_2;
3382
- var e_4, _f, _g;
3383
- return __generator(this, function (_h) {
3384
- switch (_h.label) {
3385
- case 0:
3386
- name = "pipeline-executor-frame-".concat(currentTemplate.name);
3387
- title = currentTemplate.title;
3388
- priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3389
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
3390
- progress_1 = {
3391
- name: name,
3392
- title: title,
3393
- isStarted: false,
3394
- isDone: false,
3395
- templateType: currentTemplate.templateType,
3396
- parameterName: currentTemplate.resultingParameterName,
3397
- parameterValue: null,
3398
- // <- [3]
3399
- };
3400
- if (isReturned) {
3401
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4F\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_1, null, 4)
3402
- .split('\n')
3403
- .map(function (line) { return "> ".concat(line); })
3404
- .join('\n')), "\n "); }));
3405
- }
3406
- return [4 /*yield*/, onProgress(progress_1)];
3407
- case 1:
3408
- _h.sent();
3409
- _h.label = 2;
3410
- case 2:
3411
- usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3412
- dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3413
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3414
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Dependent parameters:\n ").concat(Array.from(dependentParameterNames)
3415
- .map(function (name) { return "{".concat(name, "}"); })
3416
- .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3417
- .map(function (name) { return "{".concat(name, "}"); })
3418
- .join(', '), "\n\n "); }));
3419
- }
3420
- _b = (_a = Object).freeze;
3421
- _c = [{}];
3422
- return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
3423
- case 3:
3424
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3425
- definedParameterNames = new Set(Object.keys(definedParameters));
3426
- parameters = {};
3427
- _loop_4 = function (parameterName) {
3428
- // Situation: Parameter is defined and used
3429
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3430
- parameters[parameterName] = definedParameters[parameterName];
3431
- }
3432
- // Situation: Parameter is defined but NOT used
3433
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3434
- // Situation: Parameter is NOT defined BUT used
3435
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3436
- // Houston, we have a problem
3437
- // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3438
- throw new UnexpectedError(spaceTrim$1(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 "); }));
3439
- }
3440
- };
3441
- try {
3442
- // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3443
- for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3444
- parameterName = _e.value;
3445
- _loop_4(parameterName);
3446
- }
3447
- }
3448
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
3449
- finally {
3450
- try {
3451
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3452
- }
3453
- finally { if (e_4) throw e_4.error; }
3454
- }
3455
- // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3456
- Object.freeze(parameters);
3457
- result = null;
3458
- resultString = null;
3459
- expectError = null;
3460
- maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3461
- jokerParameterNames = currentTemplate.jokerParameterNames || [];
3462
- preparedContent = (currentTemplate.preparedContent || '{content}')
3463
- .split('{content}')
3464
- .join(currentTemplate.content);
3465
- _loop_5 = function (attempt) {
3466
- var isJokerAttempt, jokerParameterName, _j, modelRequirements, _k, _l, _m, scriptTools, error_2, e_5_1, _o, _p, functionName, postprocessingError, _q, _r, scriptTools, error_3, e_6_1, e_7_1, error_4;
3467
- var e_5, _s, e_7, _t, e_6, _u;
3468
- return __generator(this, function (_v) {
3469
- switch (_v.label) {
3470
- case 0:
3471
- isJokerAttempt = attempt < 0;
3472
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3473
- if (isJokerAttempt && !jokerParameterName) {
3474
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3475
- }
3476
- result = null;
3477
- resultString = null;
3478
- expectError = null;
3479
- if (isJokerAttempt) {
3480
- if (parameters[jokerParameterName] === undefined) {
3481
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3482
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3483
- }
3484
- else {
3485
- resultString = parameters[jokerParameterName];
3486
- }
3487
- }
3488
- _v.label = 1;
3489
- case 1:
3490
- _v.trys.push([1, 44, 45, 46]);
3491
- if (!!isJokerAttempt) return [3 /*break*/, 26];
3492
- _j = currentTemplate.templateType;
3493
- switch (_j) {
3494
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3495
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3496
- case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3497
- case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3498
- }
3499
- return [3 /*break*/, 25];
3500
- case 2:
3501
- resultString = replaceParameters(preparedContent, parameters);
3502
- return [3 /*break*/, 26];
3503
- case 3:
3504
- modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (pipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3505
- prompt = {
3506
- title: currentTemplate.title,
3507
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3508
- ? preparedPipeline.pipelineUrl
3509
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3510
- parameters: parameters,
3511
- content: preparedContent,
3512
- modelRequirements: modelRequirements,
3513
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3514
- var name = _a.name;
3515
- return name === currentTemplate.personaName;
3516
- }) || {})), currentTemplate.expectations),
3517
- format: currentTemplate.format,
3518
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3519
- }; // <- TODO: Not very good type guard
3520
- _k = modelRequirements.modelVariant;
3521
- switch (_k) {
3522
- case 'CHAT': return [3 /*break*/, 4];
3523
- case 'COMPLETION': return [3 /*break*/, 6];
3524
- case 'EMBEDDING': return [3 /*break*/, 8];
3525
- }
3526
- return [3 /*break*/, 10];
3527
- case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3528
- case 5:
3529
- chatResult = _v.sent();
3530
- // TODO: [🍬] Destroy chatThread
3531
- result = chatResult;
3532
- resultString = chatResult.content;
3533
- return [3 /*break*/, 11];
3534
- case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3535
- case 7:
3536
- completionResult = _v.sent();
3537
- result = completionResult;
3538
- resultString = completionResult.content;
3539
- return [3 /*break*/, 11];
3540
- case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3541
- case 9:
3542
- embeddingResult = _v.sent();
3543
- result = embeddingResult;
3544
- resultString = embeddingResult.content.join(',');
3545
- return [3 /*break*/, 11];
3546
- case 10: throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements
3547
- .modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3548
- case 11: return [3 /*break*/, 26];
3549
- case 12:
3550
- if (arrayableToArray(tools.script).length === 0) {
3551
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3552
- }
3553
- if (!currentTemplate.contentLanguage) {
3554
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(currentTemplate.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3555
- }
3556
- // TODO: DRY [1]
3557
- scriptPipelineExecutionErrors = [];
3558
- _v.label = 13;
3559
- case 13:
3560
- _v.trys.push([13, 20, 21, 22]);
3561
- _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3562
- _v.label = 14;
3563
- case 14:
3564
- if (!!_m.done) return [3 /*break*/, 19];
3565
- scriptTools = _m.value;
3566
- _v.label = 15;
3567
- case 15:
3568
- _v.trys.push([15, 17, , 18]);
3569
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3570
- scriptLanguage: currentTemplate.contentLanguage,
3571
- script: preparedContent,
3572
- parameters: parameters,
3573
- }))];
3574
- case 16:
3575
- resultString = _v.sent();
3576
- return [3 /*break*/, 19];
3577
- case 17:
3578
- error_2 = _v.sent();
3579
- if (!(error_2 instanceof Error)) {
3580
- throw error_2;
3581
- }
3582
- if (error_2 instanceof UnexpectedError) {
3583
- throw error_2;
3584
- }
3585
- scriptPipelineExecutionErrors.push(error_2);
3586
- return [3 /*break*/, 18];
3587
- case 18:
3588
- _m = _l.next();
3589
- return [3 /*break*/, 14];
3590
- case 19: return [3 /*break*/, 22];
3591
- case 20:
3592
- e_5_1 = _v.sent();
3593
- e_5 = { error: e_5_1 };
3594
- return [3 /*break*/, 22];
3595
- case 21:
3596
- try {
3597
- if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3598
- }
3599
- finally { if (e_5) throw e_5.error; }
3600
- return [7 /*endfinally*/];
3601
- case 22:
3602
- if (resultString !== null) {
3603
- return [3 /*break*/, 26];
3604
- }
3605
- if (scriptPipelineExecutionErrors.length === 1) {
3606
- throw scriptPipelineExecutionErrors[0];
3607
- }
3608
- else {
3609
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Script execution failed ".concat(scriptPipelineExecutionErrors.length, " times\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block(scriptPipelineExecutionErrors
3610
- .map(function (error) { return '- ' + error.message; })
3611
- .join('\n\n')), "\n "); }));
3612
- }
3613
- case 23:
3614
- if (tools.userInterface === undefined) {
3615
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3616
- }
3617
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3618
- promptTitle: currentTemplate.title,
3619
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3620
- defaultValue: replaceParameters(preparedContent, parameters),
3621
- // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3622
- placeholder: undefined,
3623
- priority: priority,
3624
- }))];
3625
- case 24:
3626
- // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3627
- resultString = _v.sent();
3628
- return [3 /*break*/, 26];
3629
- case 25: throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3630
- case 26:
3631
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3632
- _v.label = 27;
3633
- case 27:
3634
- _v.trys.push([27, 41, 42, 43]);
3635
- _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3636
- _v.label = 28;
3637
- case 28:
3638
- if (!!_p.done) return [3 /*break*/, 40];
3639
- functionName = _p.value;
3640
- // TODO: DRY [1]
3641
- scriptPipelineExecutionErrors = [];
3642
- postprocessingError = null;
3643
- _v.label = 29;
3644
- case 29:
3645
- _v.trys.push([29, 36, 37, 38]);
3646
- _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3647
- _v.label = 30;
3648
- case 30:
3649
- if (!!_r.done) return [3 /*break*/, 35];
3650
- scriptTools = _r.value;
3651
- _v.label = 31;
3652
- case 31:
3653
- _v.trys.push([31, 33, , 34]);
3654
- return [4 /*yield*/, scriptTools.execute({
3655
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3656
- script: "".concat(functionName, "(resultString)"),
3657
- parameters: {
3658
- resultString: resultString || '',
3659
- // Note: No ...parametersForTemplate, because working with result only
3660
- },
3661
- })];
3662
- case 32:
3663
- resultString = _v.sent();
3664
- postprocessingError = null;
3665
- return [3 /*break*/, 35];
3666
- case 33:
3667
- error_3 = _v.sent();
3668
- if (!(error_3 instanceof Error)) {
3669
- throw error_3;
3670
- }
3671
- if (error_3 instanceof UnexpectedError) {
3672
- throw error_3;
3673
- }
3674
- postprocessingError = error_3;
3675
- scriptPipelineExecutionErrors.push(error_3);
3676
- return [3 /*break*/, 34];
3677
- case 34:
3678
- _r = _q.next();
3679
- return [3 /*break*/, 30];
3680
- case 35: return [3 /*break*/, 38];
3681
- case 36:
3682
- e_6_1 = _v.sent();
3683
- e_6 = { error: e_6_1 };
3684
- return [3 /*break*/, 38];
3685
- case 37:
3686
- try {
3687
- if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3688
- }
3689
- finally { if (e_6) throw e_6.error; }
3690
- return [7 /*endfinally*/];
3691
- case 38:
3692
- if (postprocessingError) {
3693
- throw postprocessingError;
3694
- }
3695
- _v.label = 39;
3696
- case 39:
3697
- _p = _o.next();
3698
- return [3 /*break*/, 28];
3699
- case 40: return [3 /*break*/, 43];
3700
- case 41:
3701
- e_7_1 = _v.sent();
3702
- e_7 = { error: e_7_1 };
3703
- return [3 /*break*/, 43];
3704
- case 42:
3705
- try {
3706
- if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3707
- }
3708
- finally { if (e_7) throw e_7.error; }
3709
- return [7 /*endfinally*/];
3710
- case 43:
3711
- // TODO: [💝] Unite object for expecting amount and format
3712
- if (currentTemplate.format) {
3713
- if (currentTemplate.format === 'JSON') {
3714
- if (!isValidJsonString(resultString || '')) {
3715
- // TODO: [🏢] Do more universally via `FormatDefinition`
3716
- try {
3717
- resultString = extractJsonBlock(resultString || '');
3718
- }
3719
- catch (error) {
3720
- keepUnused(error);
3721
- throw new ExpectError(spaceTrim$1(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3722
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3723
- }
3724
- }
3486
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
3487
+ throw new PipelineExecutionError('Parameter is already opened or not closed');
3488
+ }
3489
+ if (parameters[parameterName] === undefined) {
3490
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3491
+ }
3492
+ var parameterValue = parameters[parameterName];
3493
+ if (parameterValue === undefined) {
3494
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3495
+ }
3496
+ parameterValue = parameterValue.toString();
3497
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
3498
+ parameterValue = parameterValue
3499
+ .split('\n')
3500
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
3501
+ .join('\n');
3502
+ }
3503
+ replacedTemplate =
3504
+ replacedTemplate.substring(0, match.index + precol.length) +
3505
+ parameterValue +
3506
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
3507
+ };
3508
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
3509
+ .exec(replacedTemplate))) {
3510
+ _loop_1();
3511
+ }
3512
+ // [💫] Check if there are parameters that are not closed properly
3513
+ if (/{\w+$/.test(replacedTemplate)) {
3514
+ throw new PipelineExecutionError('Parameter is not closed');
3515
+ }
3516
+ // [💫] Check if there are parameters that are not opened properly
3517
+ if (/^\w+}/.test(replacedTemplate)) {
3518
+ throw new PipelineExecutionError('Parameter is not opened');
3519
+ }
3520
+ return replacedTemplate;
3521
+ }
3522
+
3523
+ /**
3524
+ * Counts number of characters in the text
3525
+ *
3526
+ * @public exported from `@promptbook/utils`
3527
+ */
3528
+ function countCharacters(text) {
3529
+ // Remove null characters
3530
+ text = text.replace(/\0/g, '');
3531
+ // Replace emojis (and also ZWJ sequence) with hyphens
3532
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3533
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
3534
+ text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
3535
+ return text.length;
3536
+ }
3537
+
3538
+ /**
3539
+ * Counts number of lines in the text
3540
+ *
3541
+ * @public exported from `@promptbook/utils`
3542
+ */
3543
+ function countLines(text) {
3544
+ if (text === '') {
3545
+ return 0;
3546
+ }
3547
+ return text.split('\n').length;
3548
+ }
3549
+
3550
+ /**
3551
+ * Counts number of pages in the text
3552
+ *
3553
+ * @public exported from `@promptbook/utils`
3554
+ */
3555
+ function countPages(text) {
3556
+ var sentencesPerPage = 5; // Assuming each page has 5 sentences
3557
+ var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3558
+ var pageCount = Math.ceil(sentences.length / sentencesPerPage);
3559
+ return pageCount;
3560
+ }
3561
+
3562
+ /**
3563
+ * Counts number of paragraphs in the text
3564
+ *
3565
+ * @public exported from `@promptbook/utils`
3566
+ */
3567
+ function countParagraphs(text) {
3568
+ return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
3569
+ }
3570
+
3571
+ /**
3572
+ * Split text into sentences
3573
+ *
3574
+ * @public exported from `@promptbook/utils`
3575
+ */
3576
+ function splitIntoSentences(text) {
3577
+ return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3578
+ }
3579
+ /**
3580
+ * Counts number of sentences in the text
3581
+ *
3582
+ * @public exported from `@promptbook/utils`
3583
+ */
3584
+ function countSentences(text) {
3585
+ return splitIntoSentences(text).length;
3586
+ }
3587
+
3588
+ /**
3589
+ * Counts number of words in the text
3590
+ *
3591
+ * @public exported from `@promptbook/utils`
3592
+ */
3593
+ function countWords(text) {
3594
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3595
+ text = removeDiacritics(text);
3596
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3597
+ }
3598
+
3599
+ /**
3600
+ * Index of all counter functions
3601
+ *
3602
+ * @public exported from `@promptbook/utils`
3603
+ */
3604
+ var CountUtils = {
3605
+ CHARACTERS: countCharacters,
3606
+ WORDS: countWords,
3607
+ SENTENCES: countSentences,
3608
+ PARAGRAPHS: countParagraphs,
3609
+ LINES: countLines,
3610
+ PAGES: countPages,
3611
+ };
3612
+ /**
3613
+ * TODO: [🧠][🤠] This should be probbably as part of `TextFormatDefinition`
3614
+ */
3615
+
3616
+ /**
3617
+ * Function checkExpectations will check if the expectations on given value are met
3618
+ *
3619
+ * Note: There are two simmilar functions:
3620
+ * - `checkExpectations` which throws an error if the expectations are not met
3621
+ * - `isPassingExpectations` which returns a boolean
3622
+ *
3623
+ * @throws {ExpectError} if the expectations are not met
3624
+ * @returns {void} Nothing
3625
+ * @private internal function of `createPipelineExecutor`
3626
+ */
3627
+ function checkExpectations(expectations, value) {
3628
+ var e_1, _a;
3629
+ try {
3630
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3631
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3632
+ var amount = CountUtils[unit.toUpperCase()](value);
3633
+ if (min && amount < min) {
3634
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3635
+ } /* not else */
3636
+ if (max && amount > max) {
3637
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3638
+ }
3639
+ }
3640
+ }
3641
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3642
+ finally {
3643
+ try {
3644
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3645
+ }
3646
+ finally { if (e_1) throw e_1.error; }
3647
+ }
3648
+ }
3649
+ /**
3650
+ * Function checkExpectations will check if the expectations on given value are met
3651
+ *
3652
+ * Note: There are two simmilar functions:
3653
+ * - `checkExpectations` which throws an error if the expectations are not met
3654
+ * - `isPassingExpectations` which returns a boolean
3655
+ *
3656
+ * @returns {boolean} True if the expectations are met
3657
+ * @public exported from `@promptbook/core`
3658
+ */
3659
+ function isPassingExpectations(expectations, value) {
3660
+ try {
3661
+ checkExpectations(expectations, value);
3662
+ return true;
3663
+ }
3664
+ catch (error) {
3665
+ if (!(error instanceof ExpectError)) {
3666
+ throw error;
3667
+ }
3668
+ return false;
3669
+ }
3670
+ }
3671
+ /**
3672
+ * TODO: [💝] Unite object for expecting amount and format
3673
+ * TODO: [🧠][🤠] This should be part of `TextFormatDefinition`
3674
+ * Note: [💝] and [🤠] are interconnected together
3675
+ */
3676
+
3677
+ /**
3678
+ * @@@
3679
+ *
3680
+ * @private internal utility of `createPipelineExecutor`
3681
+ */
3682
+ function executeAttempts(options) {
3683
+ return __awaiter(this, void 0, void 0, function () {
3684
+ var jokerParameterNames, priority, maxAttempts, preparedContent, parameters, template, preparedPipeline, tools, llmTools, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, $ongoingTemplateResult, _loop_1, attempt, state_1;
3685
+ return __generator(this, function (_a) {
3686
+ switch (_a.label) {
3687
+ case 0:
3688
+ jokerParameterNames = options.jokerParameterNames, priority = options.priority, maxAttempts = options.maxAttempts, preparedContent = options.preparedContent, parameters = options.parameters, template = options.template, preparedPipeline = options.preparedPipeline, tools = options.tools, llmTools = options.llmTools, settings = options.settings, $executionReport = options.$executionReport, pipelineIdentification = options.pipelineIdentification;
3689
+ maxExecutionAttempts = settings.maxExecutionAttempts;
3690
+ $ongoingTemplateResult = {
3691
+ $result: null,
3692
+ $resultString: null,
3693
+ $expectError: null,
3694
+ $scriptPipelineExecutionErrors: [],
3695
+ };
3696
+ _loop_1 = function (attempt) {
3697
+ var isJokerAttempt, jokerParameterName, _b, modelRequirements, _c, _d, _e, _f, _g, scriptTools, _h, error_1, e_1_1, _j, _k, _l, functionName, postprocessingError, _m, _o, scriptTools, _p, error_2, e_2_1, e_3_1, error_3;
3698
+ var e_1, _q, e_3, _r, e_2, _s;
3699
+ return __generator(this, function (_t) {
3700
+ switch (_t.label) {
3701
+ case 0:
3702
+ isJokerAttempt = attempt < 0;
3703
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3704
+ // TODO: [🧠][🍭] JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3705
+ if (isJokerAttempt && !jokerParameterName) {
3706
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3707
+ }
3708
+ $ongoingTemplateResult.$result = null;
3709
+ $ongoingTemplateResult.$resultString = null;
3710
+ $ongoingTemplateResult.$expectError = null;
3711
+ if (isJokerAttempt) {
3712
+ if (parameters[jokerParameterName] === undefined) {
3713
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3714
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3715
+ }
3716
+ else {
3717
+ $ongoingTemplateResult.$resultString = parameters[jokerParameterName];
3718
+ }
3719
+ }
3720
+ _t.label = 1;
3721
+ case 1:
3722
+ _t.trys.push([1, 43, 44, 45]);
3723
+ if (!!isJokerAttempt) return [3 /*break*/, 25];
3724
+ _b = template.templateType;
3725
+ switch (_b) {
3726
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3727
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3728
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 11];
3729
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 22];
3730
+ }
3731
+ return [3 /*break*/, 24];
3732
+ case 2:
3733
+ $ongoingTemplateResult.$resultString = replaceParameters(preparedContent, parameters);
3734
+ return [3 /*break*/, 25];
3735
+ case 3:
3736
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (template.modelRequirements || {}));
3737
+ $ongoingTemplateResult.$prompt = {
3738
+ title: template.title,
3739
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3740
+ ? preparedPipeline.pipelineUrl
3741
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(template.name),
3742
+ parameters: parameters,
3743
+ content: preparedContent,
3744
+ modelRequirements: modelRequirements,
3745
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3746
+ var name = _a.name;
3747
+ return name === template.personaName;
3748
+ }) ||
3749
+ {})), template.expectations),
3750
+ format: template.format,
3751
+ postprocessingFunctionNames: template.postprocessingFunctionNames,
3752
+ }; // <- TODO: Not very good type guard
3753
+ _c = modelRequirements.modelVariant;
3754
+ switch (_c) {
3755
+ case 'CHAT': return [3 /*break*/, 4];
3756
+ case 'COMPLETION': return [3 /*break*/, 6];
3757
+ case 'EMBEDDING': return [3 /*break*/, 8];
3758
+ }
3759
+ return [3 /*break*/, 9];
3760
+ case 4:
3761
+ _d = $ongoingTemplateResult;
3762
+ return [4 /*yield*/, llmTools.callChatModel($deepFreeze($ongoingTemplateResult.$prompt))];
3763
+ case 5:
3764
+ _d.$chatResult = _t.sent();
3765
+ // TODO: [🍬] Destroy chatThread
3766
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$chatResult;
3767
+ $ongoingTemplateResult.$resultString = $ongoingTemplateResult.$chatResult.content;
3768
+ return [3 /*break*/, 10];
3769
+ case 6:
3770
+ _e = $ongoingTemplateResult;
3771
+ return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze($ongoingTemplateResult.$prompt))];
3772
+ case 7:
3773
+ _e.$completionResult = _t.sent();
3774
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$completionResult;
3775
+ $ongoingTemplateResult.$resultString =
3776
+ $ongoingTemplateResult.$completionResult.content;
3777
+ return [3 /*break*/, 10];
3778
+ case 8: throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Embedding model can not be used in pipeline\n\n This should be catched during parsing\n\n ".concat(block(pipelineIdentification), "\n\n "); }));
3779
+ case 9: throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Unknown model variant \"".concat(template.modelRequirements.modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3780
+ case 10: return [3 /*break*/, 25];
3781
+ case 11:
3782
+ if (arrayableToArray(tools.script).length === 0) {
3783
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3784
+ }
3785
+ if (!template.contentLanguage) {
3786
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(template.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3787
+ }
3788
+ _t.label = 12;
3789
+ case 12:
3790
+ _t.trys.push([12, 19, 20, 21]);
3791
+ _f = (e_1 = void 0, __values(arrayableToArray(tools.script))), _g = _f.next();
3792
+ _t.label = 13;
3793
+ case 13:
3794
+ if (!!_g.done) return [3 /*break*/, 18];
3795
+ scriptTools = _g.value;
3796
+ _t.label = 14;
3797
+ case 14:
3798
+ _t.trys.push([14, 16, , 17]);
3799
+ _h = $ongoingTemplateResult;
3800
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3801
+ scriptLanguage: template.contentLanguage,
3802
+ script: preparedContent,
3803
+ parameters: parameters,
3804
+ }))];
3805
+ case 15:
3806
+ _h.$resultString = _t.sent();
3807
+ return [3 /*break*/, 18];
3808
+ case 16:
3809
+ error_1 = _t.sent();
3810
+ if (!(error_1 instanceof Error)) {
3811
+ throw error_1;
3812
+ }
3813
+ if (error_1 instanceof UnexpectedError) {
3814
+ throw error_1;
3815
+ }
3816
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_1);
3817
+ return [3 /*break*/, 17];
3818
+ case 17:
3819
+ _g = _f.next();
3820
+ return [3 /*break*/, 13];
3821
+ case 18: return [3 /*break*/, 21];
3822
+ case 19:
3823
+ e_1_1 = _t.sent();
3824
+ e_1 = { error: e_1_1 };
3825
+ return [3 /*break*/, 21];
3826
+ case 20:
3827
+ try {
3828
+ if (_g && !_g.done && (_q = _f.return)) _q.call(_f);
3829
+ }
3830
+ finally { if (e_1) throw e_1.error; }
3831
+ return [7 /*endfinally*/];
3832
+ case 21:
3833
+ if ($ongoingTemplateResult.$resultString !== null) {
3834
+ return [3 /*break*/, 25];
3835
+ }
3836
+ if ($ongoingTemplateResult.$scriptPipelineExecutionErrors.length === 1) {
3837
+ throw $ongoingTemplateResult.$scriptPipelineExecutionErrors[0];
3838
+ }
3839
+ else {
3840
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Script execution failed ".concat($ongoingTemplateResult.$scriptPipelineExecutionErrors.length, "x\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block($ongoingTemplateResult.$scriptPipelineExecutionErrors
3841
+ .map(function (error) { return '- ' + error.message; })
3842
+ .join('\n\n')), "\n "); }));
3843
+ }
3844
+ case 22:
3845
+ if (tools.userInterface === undefined) {
3846
+ throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3847
+ }
3848
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3849
+ _j = $ongoingTemplateResult;
3850
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3851
+ promptTitle: template.title,
3852
+ promptMessage: replaceParameters(template.description || '', parameters),
3853
+ defaultValue: replaceParameters(preparedContent, parameters),
3854
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3855
+ placeholder: undefined,
3856
+ priority: priority,
3857
+ }))];
3858
+ case 23:
3859
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3860
+ _j.$resultString = _t.sent();
3861
+ return [3 /*break*/, 25];
3862
+ case 24: throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Unknown execution type \"".concat(template.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3863
+ case 25:
3864
+ if (!(!isJokerAttempt && template.postprocessingFunctionNames)) return [3 /*break*/, 42];
3865
+ _t.label = 26;
3866
+ case 26:
3867
+ _t.trys.push([26, 40, 41, 42]);
3868
+ _k = (e_3 = void 0, __values(template.postprocessingFunctionNames)), _l = _k.next();
3869
+ _t.label = 27;
3870
+ case 27:
3871
+ if (!!_l.done) return [3 /*break*/, 39];
3872
+ functionName = _l.value;
3873
+ postprocessingError = null;
3874
+ _t.label = 28;
3875
+ case 28:
3876
+ _t.trys.push([28, 35, 36, 37]);
3877
+ _m = (e_2 = void 0, __values(arrayableToArray(tools.script))), _o = _m.next();
3878
+ _t.label = 29;
3879
+ case 29:
3880
+ if (!!_o.done) return [3 /*break*/, 34];
3881
+ scriptTools = _o.value;
3882
+ _t.label = 30;
3883
+ case 30:
3884
+ _t.trys.push([30, 32, , 33]);
3885
+ _p = $ongoingTemplateResult;
3886
+ return [4 /*yield*/, scriptTools.execute({
3887
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3888
+ script: "".concat(functionName, "(resultString)"),
3889
+ parameters: {
3890
+ resultString: $ongoingTemplateResult.$resultString || '',
3891
+ // Note: No ...parametersForTemplate, because working with result only
3892
+ },
3893
+ })];
3894
+ case 31:
3895
+ _p.$resultString = _t.sent();
3896
+ postprocessingError = null;
3897
+ return [3 /*break*/, 34];
3898
+ case 32:
3899
+ error_2 = _t.sent();
3900
+ if (!(error_2 instanceof Error)) {
3901
+ throw error_2;
3902
+ }
3903
+ if (error_2 instanceof UnexpectedError) {
3904
+ throw error_2;
3905
+ }
3906
+ postprocessingError = error_2;
3907
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_2);
3908
+ return [3 /*break*/, 33];
3909
+ case 33:
3910
+ _o = _m.next();
3911
+ return [3 /*break*/, 29];
3912
+ case 34: return [3 /*break*/, 37];
3913
+ case 35:
3914
+ e_2_1 = _t.sent();
3915
+ e_2 = { error: e_2_1 };
3916
+ return [3 /*break*/, 37];
3917
+ case 36:
3918
+ try {
3919
+ if (_o && !_o.done && (_s = _m.return)) _s.call(_m);
3920
+ }
3921
+ finally { if (e_2) throw e_2.error; }
3922
+ return [7 /*endfinally*/];
3923
+ case 37:
3924
+ if (postprocessingError) {
3925
+ throw postprocessingError;
3926
+ }
3927
+ _t.label = 38;
3928
+ case 38:
3929
+ _l = _k.next();
3930
+ return [3 /*break*/, 27];
3931
+ case 39: return [3 /*break*/, 42];
3932
+ case 40:
3933
+ e_3_1 = _t.sent();
3934
+ e_3 = { error: e_3_1 };
3935
+ return [3 /*break*/, 42];
3936
+ case 41:
3937
+ try {
3938
+ if (_l && !_l.done && (_r = _k.return)) _r.call(_k);
3939
+ }
3940
+ finally { if (e_3) throw e_3.error; }
3941
+ return [7 /*endfinally*/];
3942
+ case 42:
3943
+ // TODO: [💝] Unite object for expecting amount and format
3944
+ if (template.format) {
3945
+ if (template.format === 'JSON') {
3946
+ if (!isValidJsonString($ongoingTemplateResult.$resultString || '')) {
3947
+ // TODO: [🏢] Do more universally via `FormatDefinition`
3948
+ try {
3949
+ $ongoingTemplateResult.$resultString = extractJsonBlock($ongoingTemplateResult.$resultString || '');
3725
3950
  }
3726
- else {
3727
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3951
+ catch (error) {
3952
+ keepUnused(error);
3953
+ throw new ExpectError(spaceTrim$1(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3954
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3728
3955
  }
3729
3956
  }
3730
- // TODO: [💝] Unite object for expecting amount and format
3731
- if (currentTemplate.expectations) {
3732
- checkExpectations(currentTemplate.expectations, resultString || '');
3733
- }
3734
- return [2 /*return*/, "break-attempts"];
3735
- case 44:
3736
- error_4 = _v.sent();
3737
- if (!(error_4 instanceof ExpectError)) {
3738
- throw error_4;
3739
- }
3740
- expectError = error_4;
3741
- return [3 /*break*/, 46];
3742
- case 45:
3743
- if (!isJokerAttempt &&
3744
- currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3745
- prompt
3746
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3747
- // In that case we don’t want to make a report about it because it’s not a llm execution error
3748
- ) {
3749
- // TODO: [🧠] Maybe put other templateTypes into report
3750
- executionReport.promptExecutions.push({
3751
- prompt: __assign({}, prompt),
3752
- result: result || undefined,
3753
- error: expectError === null ? undefined : serializeError(expectError),
3754
- });
3755
- }
3756
- return [7 /*endfinally*/];
3757
- case 46:
3758
- if (expectError !== null && attempt === maxAttempts - 1) {
3759
- throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ").concat(block(pipelineIdentification), "\n\n ---\n The Prompt:\n ").concat(block(prompt.content
3760
- .split('\n')
3761
- .map(function (line) { return "> ".concat(line); })
3762
- .join('\n')), "\n\n Last error ").concat((expectError === null || expectError === void 0 ? void 0 : expectError.name) || '', ":\n ").concat(block(((expectError === null || expectError === void 0 ? void 0 : expectError.message) || '')
3957
+ }
3958
+ else {
3959
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Unknown format \"".concat(template.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3960
+ }
3961
+ }
3962
+ // TODO: [💝] Unite object for expecting amount and format
3963
+ if (template.expectations) {
3964
+ checkExpectations(template.expectations, $ongoingTemplateResult.$resultString || '');
3965
+ }
3966
+ return [2 /*return*/, "break-attempts"];
3967
+ case 43:
3968
+ error_3 = _t.sent();
3969
+ if (!(error_3 instanceof ExpectError)) {
3970
+ throw error_3;
3971
+ }
3972
+ $ongoingTemplateResult.$expectError = error_3;
3973
+ return [3 /*break*/, 45];
3974
+ case 44:
3975
+ if (!isJokerAttempt &&
3976
+ template.templateType === 'PROMPT_TEMPLATE' &&
3977
+ $ongoingTemplateResult.$prompt
3978
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3979
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
3980
+ ) {
3981
+ // TODO: [🧠] Maybe put other templateTypes into report
3982
+ $executionReport.promptExecutions.push({
3983
+ prompt: __assign({}, $ongoingTemplateResult.$prompt),
3984
+ result: $ongoingTemplateResult.$result || undefined,
3985
+ error: $ongoingTemplateResult.$expectError === null
3986
+ ? undefined
3987
+ : serializeError($ongoingTemplateResult.$expectError),
3988
+ });
3989
+ }
3990
+ return [7 /*endfinally*/];
3991
+ case 45:
3992
+ if ($ongoingTemplateResult.$expectError !== null && attempt === maxAttempts - 1) {
3993
+ throw new PipelineExecutionError(spaceTrim$1(function (block) {
3994
+ var _a, _b, _c;
3995
+ return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ").concat(block(pipelineIdentification), "\n\n ---\n The Prompt:\n ").concat(block((((_a = $ongoingTemplateResult.$prompt) === null || _a === void 0 ? void 0 : _a.content) || '')
3996
+ .split('\n')
3997
+ .map(function (line) { return "> ".concat(line); })
3998
+ .join('\n')), "\n\n Last error ").concat(((_b = $ongoingTemplateResult.$expectError) === null || _b === void 0 ? void 0 : _b.name) || '', ":\n ").concat(block((((_c = $ongoingTemplateResult.$expectError) === null || _c === void 0 ? void 0 : _c.message) || '')
3999
+ .split('\n')
4000
+ .map(function (line) { return "> ".concat(line); })
4001
+ .join('\n')), "\n\n Last result:\n ").concat(block($ongoingTemplateResult.$resultString === null
4002
+ ? 'null'
4003
+ : $ongoingTemplateResult.$resultString
3763
4004
  .split('\n')
3764
4005
  .map(function (line) { return "> ".concat(line); })
3765
- .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3766
- ? 'null'
3767
- : resultString
3768
- .split('\n')
3769
- .map(function (line) { return "> ".concat(line); })
3770
- .join('\n')), "\n ---\n "); }));
3771
- }
3772
- return [2 /*return*/];
4006
+ .join('\n')), "\n ---\n ");
4007
+ }));
3773
4008
  }
3774
- });
3775
- };
3776
- attempt = -jokerParameterNames.length;
3777
- _h.label = 4;
3778
- case 4:
3779
- if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3780
- return [5 /*yield**/, _loop_5(attempt)];
3781
- case 5:
3782
- state_2 = _h.sent();
3783
- switch (state_2) {
3784
- case "break-attempts": return [3 /*break*/, 7];
3785
- }
3786
- _h.label = 6;
3787
- case 6:
3788
- attempt++;
3789
- return [3 /*break*/, 4];
3790
- case 7:
3791
- if (resultString === null) {
3792
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3793
- }
3794
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 9]; /* <- [3] */
3795
- progress_2 = {
3796
- name: name,
3797
- title: title,
3798
- isStarted: true,
3799
- isDone: true,
3800
- templateType: currentTemplate.templateType,
3801
- parameterName: currentTemplate.resultingParameterName,
3802
- parameterValue: resultString,
3803
- // <- [3]
3804
- };
3805
- if (isReturned) {
3806
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4E\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_2, null, 4)
3807
- .split('\n')
3808
- .map(function (line) { return "> ".concat(line); })
3809
- .join('\n')), "\n\n "); }));
4009
+ return [2 /*return*/];
3810
4010
  }
3811
- return [4 /*yield*/, onProgress(progress_2)];
3812
- case 8:
3813
- _h.sent();
3814
- _h.label = 9;
3815
- case 9:
3816
- 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)));
3817
- return [2 /*return*/];
4011
+ });
4012
+ };
4013
+ attempt = -jokerParameterNames.length;
4014
+ _a.label = 1;
4015
+ case 1:
4016
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 4];
4017
+ return [5 /*yield**/, _loop_1(attempt)];
4018
+ case 2:
4019
+ state_1 = _a.sent();
4020
+ switch (state_1) {
4021
+ case "break-attempts": return [3 /*break*/, 4];
3818
4022
  }
3819
- });
3820
- });
3821
- }
3822
- function filterJustOutputParameters() {
3823
- var e_8, _a;
3824
- var outputParameters = {};
3825
- var _loop_6 = function (parameter) {
3826
- if (parametersToPass[parameter.name] === undefined) {
3827
- // [4]
3828
- warnings.push(new PipelineExecutionError(spaceTrim$1(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 "); })));
3829
- return "continue";
3830
- }
3831
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3832
- };
3833
- try {
3834
- // Note: Filter ONLY output parameters
3835
- for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3836
- var isOutput = _a.isOutput;
3837
- return isOutput;
3838
- })), _c = _b.next(); !_c.done; _c = _b.next()) {
3839
- var parameter = _c.value;
3840
- _loop_6(parameter);
3841
- }
4023
+ _a.label = 3;
4024
+ case 3:
4025
+ attempt++;
4026
+ return [3 /*break*/, 1];
4027
+ case 4:
4028
+ if ($ongoingTemplateResult.$resultString === null) {
4029
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
4030
+ }
4031
+ return [2 /*return*/, $ongoingTemplateResult.$resultString];
3842
4032
  }
3843
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
3844
- finally {
3845
- try {
3846
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3847
- }
3848
- finally { if (e_8) throw e_8.error; }
4033
+ });
4034
+ });
4035
+ }
4036
+ /**
4037
+ * TODO: Break into smaller functions
4038
+ */
4039
+
4040
+ /**
4041
+ * @@@
4042
+ *
4043
+ * @private internal utility of `createPipelineExecutor`
4044
+ */
4045
+ function executeFormatCells(options) {
4046
+ return __awaiter(this, void 0, void 0, function () {
4047
+ var template, jokerParameterNames, parameters, priority, pipelineIdentification, settings, parameterValue, formatDefinition, subvalueDefinition, formatSettings, resultString;
4048
+ var _this = this;
4049
+ return __generator(this, function (_a) {
4050
+ switch (_a.label) {
4051
+ case 0:
4052
+ template = options.template, jokerParameterNames = options.jokerParameterNames, parameters = options.parameters, priority = options.priority, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
4053
+ if (template.foreach === undefined) {
4054
+ return [2 /*return*/, /* not await */ executeAttempts(options)];
4055
+ }
4056
+ if (jokerParameterNames.length !== 0) {
4057
+ throw new UnexpectedError(spaceTrim(function (block) { return "\n JOKER parameters are not supported together with FOREACH command\n\n [\uD83E\uDDDE\u200D\u2640\uFE0F] This should be prevented in `validatePipeline`\n\n ".concat(block(pipelineIdentification), "\n "); }));
4058
+ }
4059
+ parameterValue = parameters[template.foreach.parameterName] || '';
4060
+ formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
4061
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(template.foreach.formatName);
4062
+ });
4063
+ if (formatDefinition === undefined) {
4064
+ throw new UnexpectedError(
4065
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
4066
+ spaceTrim(function (block) { return "\n Unsupported format \"".concat(template.foreach.formatName, "\"\n\n Available formats:\n ").concat(block(FORMAT_DEFINITIONS.map(function (formatDefinition) { return formatDefinition.formatName; })
4067
+ .map(function (formatName) { return "- ".concat(formatName); })
4068
+ .join('\n')), "\n\n [\u26F7] This should never happen because format name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
4069
+ }
4070
+ subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
4071
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(template.foreach.subformatName);
4072
+ });
4073
+ if (subvalueDefinition === undefined) {
4074
+ throw new UnexpectedError(
4075
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
4076
+ spaceTrim(function (block) { return "\n Unsupported subformat name \"".concat(template.foreach.subformatName, "\" for format \"").concat(template.foreach.formatName, "\"\n\n Available subformat names for format \"").concat(formatDefinition.formatName, "\":\n ").concat(block(formatDefinition.subvalueDefinitions
4077
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
4078
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
4079
+ .join('\n')), "\n\n [\u26F7] This should never happen because subformat name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
4080
+ }
4081
+ if (formatDefinition.formatName === 'CSV') {
4082
+ formatSettings = settings.csvSettings;
4083
+ // <- TODO: !!!!!! More universal, make simmilar pattern for other formats for example \n vs \r\n in text
4084
+ }
4085
+ return [4 /*yield*/, subvalueDefinition.mapValues(parameterValue, formatSettings, function (subparameters, index) { return __awaiter(_this, void 0, void 0, function () {
4086
+ var mappedParameters, allSubparameters, subresultString;
4087
+ return __generator(this, function (_a) {
4088
+ switch (_a.label) {
4089
+ case 0:
4090
+ // TODO: !!!!!!! Limit to N concurrent executions
4091
+ // TODO: !!!!!!! Report progress
4092
+ try {
4093
+ mappedParameters = mapAvailableToExpectedParameters({
4094
+ expectedParameters: Object.fromEntries(template.foreach.subparameterNames.map(function (subparameterName) { return [subparameterName, null]; })),
4095
+ availableParameters: subparameters,
4096
+ });
4097
+ }
4098
+ catch (error) {
4099
+ if (!(error instanceof PipelineExecutionError)) {
4100
+ throw error;
4101
+ }
4102
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n ".concat(error.message, "\n\n This is error in FOREACH command\n You have probbably passed wrong data to pipeline or wrong data was generated which are processed by FOREACH command\n\n ").concat(block(pipelineIdentification), "\n "); }));
4103
+ }
4104
+ allSubparameters = __assign(__assign({}, parameters), mappedParameters);
4105
+ // Note: [👨‍👨‍👧] Now we can freeze `subparameters` because we are sure that all and only used parameters are defined and are not going to be changed
4106
+ Object.freeze(allSubparameters);
4107
+ return [4 /*yield*/, executeAttempts(__assign(__assign({}, options), { priority: priority + index, parameters: allSubparameters, pipelineIdentification: pipelineIdentification }))];
4108
+ case 1:
4109
+ subresultString = _a.sent();
4110
+ return [2 /*return*/, subresultString];
4111
+ }
4112
+ });
4113
+ }); })];
4114
+ case 1:
4115
+ resultString = _a.sent();
4116
+ return [2 /*return*/, resultString];
4117
+ }
4118
+ });
4119
+ });
4120
+ }
4121
+ /**
4122
+ * TODO: !!!!!! Make pipelineIdentification more precise
4123
+ * TODO: !!!!!! How FOREACH execution looks in the report
4124
+ */
4125
+
4126
+ /**
4127
+ * @@@
4128
+ *
4129
+ * @private internal utility of `createPipelineExecutor`
4130
+ */
4131
+ function getContextForTemplate(template) {
4132
+ return __awaiter(this, void 0, void 0, function () {
4133
+ return __generator(this, function (_a) {
4134
+ TODO_USE(template);
4135
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
4136
+ });
4137
+ });
4138
+ }
4139
+
4140
+ /**
4141
+ * @@@
4142
+ *
4143
+ * @private internal utility of `createPipelineExecutor`
4144
+ */
4145
+ function getKnowledgeForTemplate(options) {
4146
+ return __awaiter(this, void 0, void 0, function () {
4147
+ var preparedPipeline, template;
4148
+ return __generator(this, function (_a) {
4149
+ preparedPipeline = options.preparedPipeline, template = options.template;
4150
+ // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
4151
+ TODO_USE(template);
4152
+ return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
4153
+ var content = _a.content;
4154
+ return "- ".concat(content);
4155
+ }).join('\n')];
4156
+ });
4157
+ });
4158
+ }
4159
+
4160
+ /**
4161
+ * @@@
4162
+ *
4163
+ * @private internal utility of `createPipelineExecutor`
4164
+ */
4165
+ function getSamplesForTemplate(template) {
4166
+ return __awaiter(this, void 0, void 0, function () {
4167
+ return __generator(this, function (_a) {
4168
+ // TODO: [♨] Implement Better - use real index and keyword search
4169
+ TODO_USE(template);
4170
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
4171
+ });
4172
+ });
4173
+ }
4174
+
4175
+ /**
4176
+ * @@@
4177
+ *
4178
+ * @private internal utility of `createPipelineExecutor`
4179
+ */
4180
+ function getReservedParametersForTemplate(options) {
4181
+ return __awaiter(this, void 0, void 0, function () {
4182
+ var preparedPipeline, template, pipelineIdentification, context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
4183
+ var e_1, _a;
4184
+ return __generator(this, function (_b) {
4185
+ switch (_b.label) {
4186
+ case 0:
4187
+ preparedPipeline = options.preparedPipeline, template = options.template, pipelineIdentification = options.pipelineIdentification;
4188
+ return [4 /*yield*/, getContextForTemplate(template)];
4189
+ case 1:
4190
+ context = _b.sent();
4191
+ return [4 /*yield*/, getKnowledgeForTemplate({ preparedPipeline: preparedPipeline, template: template })];
4192
+ case 2:
4193
+ knowledge = _b.sent();
4194
+ return [4 /*yield*/, getSamplesForTemplate(template)];
4195
+ case 3:
4196
+ samples = _b.sent();
4197
+ currentDate = new Date().toISOString();
4198
+ modelName = RESERVED_PARAMETER_MISSING_VALUE;
4199
+ reservedParameters = {
4200
+ content: RESERVED_PARAMETER_RESTRICTED,
4201
+ context: context,
4202
+ knowledge: knowledge,
4203
+ samples: samples,
4204
+ currentDate: currentDate,
4205
+ modelName: modelName,
4206
+ };
4207
+ _loop_1 = function (parameterName) {
4208
+ if (reservedParameters[parameterName] === undefined) {
4209
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
4210
+ }
4211
+ };
4212
+ try {
4213
+ // Note: Doublecheck that ALL reserved parameters are defined:
4214
+ 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()) {
4215
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
4216
+ _loop_1(parameterName);
4217
+ }
4218
+ }
4219
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4220
+ finally {
4221
+ try {
4222
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
4223
+ }
4224
+ finally { if (e_1) throw e_1.error; }
4225
+ }
4226
+ return [2 /*return*/, reservedParameters];
4227
+ }
4228
+ });
4229
+ });
4230
+ }
4231
+
4232
+ /**
4233
+ * @@@
4234
+ *
4235
+ * @private internal utility of `createPipelineExecutor`
4236
+ */
4237
+ function executeTemplate(options) {
4238
+ return __awaiter(this, void 0, void 0, function () {
4239
+ var currentTemplate, preparedPipeline, parametersToPass, tools, llmTools, onProgress, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, name, title, priority, usedParameterNames, dependentParameterNames, definedParameters, _a, _b, _c, definedParameterNames, parameters, _loop_1, _d, _e, parameterName, maxAttempts, jokerParameterNames, preparedContent, resultString;
4240
+ var e_1, _f, _g;
4241
+ return __generator(this, function (_h) {
4242
+ switch (_h.label) {
4243
+ case 0:
4244
+ currentTemplate = options.currentTemplate, preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, tools = options.tools, llmTools = options.llmTools, onProgress = options.onProgress, settings = options.settings, $executionReport = options.$executionReport, pipelineIdentification = options.pipelineIdentification;
4245
+ maxExecutionAttempts = settings.maxExecutionAttempts;
4246
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
4247
+ title = currentTemplate.title;
4248
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
4249
+ return [4 /*yield*/, onProgress({
4250
+ name: name,
4251
+ title: title,
4252
+ isStarted: false,
4253
+ isDone: false,
4254
+ templateType: currentTemplate.templateType,
4255
+ parameterName: currentTemplate.resultingParameterName,
4256
+ parameterValue: null,
4257
+ // <- [🍸]
4258
+ })];
4259
+ case 1:
4260
+ _h.sent();
4261
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
4262
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
4263
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4264
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
4265
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n Dependent parameters:\n ".concat(Array.from(dependentParameterNames)
4266
+ .map(function (name) { return "{".concat(name, "}"); })
4267
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
4268
+ .map(function (name) { return "{".concat(name, "}"); })
4269
+ .join(', '), "\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
4270
+ }
4271
+ _b = (_a = Object).freeze;
4272
+ _c = [{}];
4273
+ return [4 /*yield*/, getReservedParametersForTemplate({
4274
+ preparedPipeline: preparedPipeline,
4275
+ template: currentTemplate,
4276
+ pipelineIdentification: pipelineIdentification,
4277
+ })];
4278
+ case 2:
4279
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
4280
+ definedParameterNames = new Set(Object.keys(definedParameters));
4281
+ parameters = {};
4282
+ _loop_1 = function (parameterName) {
4283
+ // Situation: Parameter is defined and used
4284
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4285
+ parameters[parameterName] = definedParameters[parameterName];
4286
+ }
4287
+ // Situation: Parameter is defined but NOT used
4288
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
4289
+ // Situation: Parameter is NOT defined BUT used
4290
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4291
+ // Houston, we have a problem
4292
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
4293
+ throw new UnexpectedError(spaceTrim$1(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 "); }));
4294
+ }
4295
+ };
4296
+ try {
4297
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
4298
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4299
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
4300
+ parameterName = _e.value;
4301
+ _loop_1(parameterName);
4302
+ }
4303
+ }
4304
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4305
+ finally {
4306
+ try {
4307
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
4308
+ }
4309
+ finally { if (e_1) throw e_1.error; }
4310
+ }
4311
+ // Note: [👨‍👨‍👧] Now we can freeze `parameters` because we are sure that all and only used parameters are defined and are not going to be changed
4312
+ Object.freeze(parameters);
4313
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
4314
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
4315
+ preparedContent = (currentTemplate.preparedContent || '{content}')
4316
+ .split('{content}')
4317
+ .join(currentTemplate.content);
4318
+ return [4 /*yield*/, executeFormatCells({
4319
+ jokerParameterNames: jokerParameterNames,
4320
+ priority: priority,
4321
+ maxAttempts: maxAttempts,
4322
+ preparedContent: preparedContent,
4323
+ parameters: parameters,
4324
+ template: currentTemplate,
4325
+ preparedPipeline: preparedPipeline,
4326
+ tools: tools,
4327
+ llmTools: llmTools,
4328
+ settings: settings,
4329
+ $executionReport: $executionReport,
4330
+ pipelineIdentification: pipelineIdentification,
4331
+ })];
4332
+ case 3:
4333
+ resultString = _h.sent();
4334
+ return [4 /*yield*/, onProgress({
4335
+ name: name,
4336
+ title: title,
4337
+ isStarted: true,
4338
+ isDone: true,
4339
+ templateType: currentTemplate.templateType,
4340
+ parameterName: currentTemplate.resultingParameterName,
4341
+ parameterValue: resultString,
4342
+ // <- [🍸]
4343
+ })];
4344
+ case 4:
4345
+ _h.sent();
4346
+ return [2 /*return*/, Object.freeze((_g = {},
4347
+ _g[currentTemplate.resultingParameterName] =
4348
+ // <- Note: [👩‍👩‍👧] No need to detect parameter collision here because pipeline checks logic consistency during construction
4349
+ resultString,
4350
+ _g))];
3849
4351
  }
3850
- return outputParameters;
4352
+ });
4353
+ });
4354
+ }
4355
+ /**
4356
+ * TODO: [🤹‍♂️]
4357
+ */
4358
+
4359
+ /**
4360
+ * @@@
4361
+ *
4362
+ * @private internal utility of `createPipelineExecutor`
4363
+ */
4364
+ function filterJustOutputParameters(options) {
4365
+ var e_1, _a;
4366
+ var preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, $warnings = options.$warnings, pipelineIdentification = options.pipelineIdentification;
4367
+ var outputParameters = {};
4368
+ var _loop_1 = function (parameter) {
4369
+ if (parametersToPass[parameter.name] === undefined) {
4370
+ // [4]
4371
+ $warnings.push(new PipelineExecutionError(spaceTrim$1(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 "); })));
4372
+ return "continue";
4373
+ }
4374
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
4375
+ };
4376
+ try {
4377
+ // Note: Filter ONLY output parameters
4378
+ // TODO: [👩🏾‍🤝‍👩🏻] Maybe use here `mapAvailableToExpectedParameters`
4379
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
4380
+ var isOutput = _a.isOutput;
4381
+ return isOutput;
4382
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
4383
+ var parameter = _c.value;
4384
+ _loop_1(parameter);
4385
+ }
4386
+ }
4387
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4388
+ finally {
4389
+ try {
4390
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3851
4391
  }
3852
- var errors, warnings, executionReport, isReturned, _a, _b, parameter, e_1_1, _loop_1, _c, _d, parameterName, state_1, e_2_1, parametersToPass, resovedParameterNames_1, unresovedTemplates_1, resolving_1, loopLimit, _loop_2, error_1, usage_1, outputParameters_1, usage, outputParameters;
4392
+ finally { if (e_1) throw e_1.error; }
4393
+ }
4394
+ return outputParameters;
4395
+ }
4396
+
4397
+ /**
4398
+ * @@@
4399
+ *
4400
+ * Note: This is not a `PipelineExecutor` (which is binded with one exact pipeline), but a utility function of `createPipelineExecutor` which creates `PipelineExecutor`
4401
+ *
4402
+ * @private internal utility of `createPipelineExecutor`
4403
+ */
4404
+ function executePipeline(options) {
4405
+ return __awaiter(this, void 0, void 0, function () {
4406
+ var inputParameters, tools, onProgress, pipeline, setPreparedPipeline, pipelineIdentification, settings, maxParallelCount, isVerbose, preparedPipeline, llmTools, errors, warnings, executionReport, isReturned, _a, _b, parameter, e_1_1, _loop_1, _c, _d, parameterName, state_1, e_2_1, parametersToPass, resovedParameterNames_1, unresovedTemplates_1, resolving_1, loopLimit, _loop_2, error_1, usage_1, outputParameters_1, usage, outputParameters;
3853
4407
  var e_1, _e, e_2, _f;
3854
4408
  return __generator(this, function (_g) {
3855
4409
  switch (_g.label) {
3856
4410
  case 0:
4411
+ inputParameters = options.inputParameters, tools = options.tools, onProgress = options.onProgress, pipeline = options.pipeline, setPreparedPipeline = options.setPreparedPipeline, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
4412
+ maxParallelCount = settings.maxParallelCount, isVerbose = settings.isVerbose;
4413
+ preparedPipeline = options.preparedPipeline;
4414
+ llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3857
4415
  if (!(preparedPipeline === undefined)) return [3 /*break*/, 2];
3858
4416
  return [4 /*yield*/, preparePipeline(pipeline, {
3859
4417
  llmTools: llmTools,
@@ -3862,6 +4420,7 @@ function createPipelineExecutor(options) {
3862
4420
  })];
3863
4421
  case 1:
3864
4422
  preparedPipeline = _g.sent();
4423
+ setPreparedPipeline(preparedPipeline);
3865
4424
  _g.label = 2;
3866
4425
  case 2:
3867
4426
  errors = [];
@@ -3931,7 +4490,7 @@ function createPipelineExecutor(options) {
3931
4490
  return name === parameterName;
3932
4491
  });
3933
4492
  if (!(parameter === undefined)) return [3 /*break*/, 1];
3934
- warnings.push(new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
4493
+ warnings.push(new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
3935
4494
  return [3 /*break*/, 4];
3936
4495
  case 1:
3937
4496
  if (!(parameter.isInput === false)) return [3 /*break*/, 4];
@@ -3943,10 +4502,10 @@ function createPipelineExecutor(options) {
3943
4502
  // Note: Wait a short time to prevent race conditions
3944
4503
  _h.sent();
3945
4504
  _h.label = 3;
3946
- case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim$1(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
4505
+ case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim$1(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
3947
4506
  isSuccessful: false,
3948
4507
  errors: __spreadArray([
3949
- new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
4508
+ new PipelineExecutionError(spaceTrim$1(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
3950
4509
  ], __read(errors), false).map(serializeError),
3951
4510
  warnings: warnings.map(serializeError),
3952
4511
  executionReport: executionReport,
@@ -4010,7 +4569,7 @@ function createPipelineExecutor(options) {
4010
4569
  case 0:
4011
4570
  if (loopLimit-- < 0) {
4012
4571
  // Note: Really UnexpectedError not LimitReachedError - this should be catched during validatePipeline
4013
- throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4572
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4014
4573
  }
4015
4574
  currentTemplate = unresovedTemplates_1.find(function (template) {
4016
4575
  return template.dependentParameterNames.every(function (name) {
@@ -4020,29 +4579,52 @@ function createPipelineExecutor(options) {
4020
4579
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
4021
4580
  throw new UnexpectedError(
4022
4581
  // TODO: [🐎] DRY
4023
- spaceTrim$1(function (block) { return "\n Can not resolve some parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Can not resolve:\n ").concat(block(unresovedTemplates_1
4582
+ spaceTrim$1(function (block) { return "\n Can not resolve some parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Can not resolve:\n ").concat(block(unresovedTemplates_1
4024
4583
  .map(function (_a) {
4025
4584
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
4026
4585
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
4027
4586
  .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
4028
4587
  .join(' and '));
4029
4588
  })
4030
- .join('\n')), "\n\n Resolved:\n ").concat(block(resovedParameterNames_1.map(function (name) { return "- Parameter {".concat(name, "}"); }).join('\n')), "\n\n Note: This should be catched in `validatePipeline`\n "); }));
4589
+ .join('\n')), "\n\n Resolved:\n ").concat(block(resovedParameterNames_1.map(function (name) { return "- Parameter {".concat(name, "}"); }).join('\n')), "\n\n Note: This should be catched in `validatePipeline`\n "); }));
4031
4590
  case 1:
4032
4591
  if (!!currentTemplate) return [3 /*break*/, 3];
4033
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
4592
+ /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
4034
4593
  case 2:
4035
- /* [5] */ _j.sent();
4594
+ /* [🤹‍♂️] */ _j.sent();
4036
4595
  return [3 /*break*/, 4];
4037
4596
  case 3:
4038
4597
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
4039
- work_1 = executeSingleTemplate(currentTemplate)
4040
- .then(function () {
4598
+ work_1 = executeTemplate({
4599
+ currentTemplate: currentTemplate,
4600
+ preparedPipeline: preparedPipeline,
4601
+ parametersToPass: parametersToPass,
4602
+ tools: tools,
4603
+ llmTools: llmTools,
4604
+ onProgress: function (progress) {
4605
+ if (isReturned) {
4606
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress, null, 4)
4607
+ .split('\n')
4608
+ .map(function (line) { return "> ".concat(line); })
4609
+ .join('\n')), "\n "); }));
4610
+ }
4611
+ if (onProgress) {
4612
+ onProgress(progress);
4613
+ }
4614
+ },
4615
+ settings: settings,
4616
+ $executionReport: executionReport,
4617
+ pipelineIdentification: pipelineIdentification,
4618
+ })
4619
+ .then(function (newParametersToPass) {
4620
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
4041
4621
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
4042
4622
  })
4043
4623
  .then(function () {
4044
4624
  resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
4045
4625
  });
4626
+ // <- Note: Errors are catched here [3]
4627
+ // TODO: BUT if in multiple templates are errors, only the first one is catched so maybe we should catch errors here and save them to errors array here
4046
4628
  resolving_1.push(work_1);
4047
4629
  _j.label = 4;
4048
4630
  case 4: return [2 /*return*/];
@@ -4069,7 +4651,12 @@ function createPipelineExecutor(options) {
4069
4651
  var result = _a.result;
4070
4652
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
4071
4653
  })), false));
4072
- outputParameters_1 = filterJustOutputParameters();
4654
+ outputParameters_1 = filterJustOutputParameters({
4655
+ preparedPipeline: preparedPipeline,
4656
+ parametersToPass: parametersToPass,
4657
+ $warnings: warnings,
4658
+ pipelineIdentification: pipelineIdentification,
4659
+ });
4073
4660
  isReturned = true;
4074
4661
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
4075
4662
  // Note: Wait a short time to prevent race conditions
@@ -4092,7 +4679,12 @@ function createPipelineExecutor(options) {
4092
4679
  var result = _a.result;
4093
4680
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
4094
4681
  })), false));
4095
- outputParameters = filterJustOutputParameters();
4682
+ outputParameters = filterJustOutputParameters({
4683
+ preparedPipeline: preparedPipeline,
4684
+ parametersToPass: parametersToPass,
4685
+ $warnings: warnings,
4686
+ pipelineIdentification: pipelineIdentification,
4687
+ });
4096
4688
  isReturned = true;
4097
4689
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
4098
4690
  // Note: Wait a short time to prevent race conditions
@@ -4112,22 +4704,63 @@ function createPipelineExecutor(options) {
4112
4704
  })];
4113
4705
  }
4114
4706
  });
4115
- }); };
4116
- return pipelineExecutor;
4707
+ });
4117
4708
  }
4709
+
4118
4710
  /**
4119
- * TODO: !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
4120
- * TODO: Use isVerbose here (not only pass to `preparePipeline`)
4121
- * TODO: [🧠][🌳] Use here `countTotalUsage` and put preparation and prepared pipiline to report
4122
- * TODO: [🪂] Use maxParallelCount here (not only pass to `preparePipeline`)
4123
- * TODO: [♈] Probbably move expectations from templates to parameters
4124
- * TODO: [🧠] When not meet expectations in DIALOG_TEMPLATE, make some way to tell the user
4125
- * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
4126
- * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
4127
- * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
4128
- * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
4129
- * TODO: [🧠][💷] `assertsExecutionSuccessful` should be the method of `PipelineExecutor` result BUT maybe NOT to preserve pure JSON object
4711
+ * Creates executor function from pipeline and execution tools.
4712
+ *
4713
+ * @returns The executor function
4714
+ * @throws {PipelineLogicError} on logical error in the pipeline
4715
+ * @public exported from `@promptbook/core`
4130
4716
  */
4717
+ function createPipelineExecutor(options) {
4718
+ var _this = this;
4719
+ var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
4720
+ 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.csvSettings, csvSettings = _d === void 0 ? DEFAULT_CSV_SETTINGS : _d, _e = settings.isVerbose, isVerbose = _e === void 0 ? IS_VERBOSE : _e, _f = settings.isNotPreparedWarningSupressed, isNotPreparedWarningSupressed = _f === void 0 ? false : _f;
4721
+ validatePipeline(pipeline);
4722
+ var pipelineIdentification = (function () {
4723
+ // Note: This is a 😐 implementation of [🚞]
4724
+ var _ = [];
4725
+ if (pipeline.sourceFile !== undefined) {
4726
+ _.push("File: ".concat(pipeline.sourceFile));
4727
+ }
4728
+ if (pipeline.pipelineUrl !== undefined) {
4729
+ _.push("Url: ".concat(pipeline.pipelineUrl));
4730
+ }
4731
+ return _.join('\n');
4732
+ })();
4733
+ var preparedPipeline;
4734
+ if (isPipelinePrepared(pipeline)) {
4735
+ preparedPipeline = pipeline;
4736
+ }
4737
+ else if (isNotPreparedWarningSupressed !== true) {
4738
+ console.warn(spaceTrim$1(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 "); }));
4739
+ }
4740
+ var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4741
+ return __generator(this, function (_a) {
4742
+ return [2 /*return*/, executePipeline({
4743
+ pipeline: pipeline,
4744
+ preparedPipeline: preparedPipeline,
4745
+ setPreparedPipeline: function (newPreparedPipeline) {
4746
+ preparedPipeline = newPreparedPipeline;
4747
+ },
4748
+ inputParameters: inputParameters,
4749
+ tools: tools,
4750
+ onProgress: onProgress,
4751
+ pipelineIdentification: pipelineIdentification,
4752
+ settings: {
4753
+ maxExecutionAttempts: maxExecutionAttempts,
4754
+ maxParallelCount: maxParallelCount,
4755
+ csvSettings: csvSettings,
4756
+ isVerbose: isVerbose,
4757
+ isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4758
+ },
4759
+ })];
4760
+ });
4761
+ }); };
4762
+ return pipelineExecutor;
4763
+ }
4131
4764
 
4132
4765
  /**
4133
4766
  * @@@
@@ -4179,7 +4812,7 @@ function prepareKnowledgeFromMarkdown(knowledgeContent /* <- TODO: [🖖] (?mayb
4179
4812
  outputParameters = result.outputParameters;
4180
4813
  knowledgePiecesRaw = outputParameters.knowledgePieces;
4181
4814
  knowledgeTextPieces = (knowledgePiecesRaw || '').split('\n---\n');
4182
- // <- TODO: !!!!! Smarter split and filter out empty pieces
4815
+ // <- TODO:[main] !!!!! Smarter split and filter out empty pieces
4183
4816
  if (isVerbose) {
4184
4817
  console.info('knowledgeTextPieces:', knowledgeTextPieces);
4185
4818
  }
@@ -4237,8 +4870,13 @@ function prepareKnowledgeFromMarkdown(knowledgeContent /* <- TODO: [🖖] (?mayb
4237
4870
  case 6: return [3 /*break*/, 8];
4238
4871
  case 7:
4239
4872
  error_1 = _c.sent();
4873
+ // Note: Here is expected error:
4874
+ // > PipelineExecutionError: You have not provided any `LlmExecutionTools` that support model variant "EMBEDDING
4875
+ if (!(error_1 instanceof PipelineExecutionError)) {
4876
+ throw error_1;
4877
+ }
4240
4878
  // TODO: [🟥] Detect browser / node and make it colorfull
4241
- console.error(error_1);
4879
+ console.error(error_1, "<- Note: This error is not critical to prepare the pipeline, just knowledge pieces won't have embeddings");
4242
4880
  return [3 /*break*/, 8];
4243
4881
  case 8: return [2 /*return*/, {
4244
4882
  name: name,
@@ -4259,7 +4897,7 @@ function prepareKnowledgeFromMarkdown(knowledgeContent /* <- TODO: [🖖] (?mayb
4259
4897
  });
4260
4898
  }
4261
4899
  /**
4262
- * TODO: [🐝][🔼] !!! Export via `@promptbook/markdown`
4900
+ * TODO: [🐝][🔼][main] !!! Export via `@promptbook/markdown`
4263
4901
  * TODO: [🪂] Do it in parallel 11:11
4264
4902
  * Note: No need to aggregate usage here, it is done by intercepting the llmTools
4265
4903
  */
@@ -4283,7 +4921,7 @@ function prepareKnowledgePieces(knowledgeSources, options) {
4283
4921
  var partialPieces, pieces;
4284
4922
  return __generator(this, function (_a) {
4285
4923
  switch (_a.label) {
4286
- case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝] !!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
4924
+ case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝] !!!!!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
4287
4925
  options)];
4288
4926
  case 1:
4289
4927
  partialPieces = _a.sent();
@@ -4475,7 +5113,7 @@ function preparePersona(personaDescription, options) {
4475
5113
  });
4476
5114
  }
4477
5115
  /**
4478
- * TODO: [🔃] !!!!! If the persona was prepared with different version or different set of models, prepare it once again
5116
+ * TODO: [🔃][main] !!!!! If the persona was prepared with different version or different set of models, prepare it once again
4479
5117
  * TODO: [🏢] !! Check validity of `modelName` in pipeline
4480
5118
  * TODO: [🏢] !! Check validity of `systemMessage` in pipeline
4481
5119
  * TODO: [🏢] !! Check validity of `temperature` in pipeline
@@ -4524,7 +5162,7 @@ function prepareTemplates(pipeline, options) {
4524
5162
  case 0:
4525
5163
  _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a;
4526
5164
  templates = pipeline.templates, parameters = pipeline.parameters, knowledgePiecesCount = pipeline.knowledgePiecesCount;
4527
- // TODO: !!!!! Apply samples to each template (if missing and is for the template defined)
5165
+ // TODO:[main] !!!!! Apply samples to each template (if missing and is for the template defined)
4528
5166
  TODO_USE(parameters);
4529
5167
  templatesPrepared = new Array(
4530
5168
  // <- TODO: [🧱] Implement in a functional (not new Class) way
@@ -4556,7 +5194,7 @@ function prepareTemplates(pipeline, options) {
4556
5194
  /**
4557
5195
  * TODO: [🧠] Add context to each template (if missing)
4558
5196
  * TODO: [🧠] What is better name `prepareTemplate` or `prepareTemplateAndParameters`
4559
- * TODO: [♨] !!! Prepare index the samples and maybe templates
5197
+ * TODO: [♨][main] !!! Prepare index the samples and maybe templates
4560
5198
  * TODO: Write tests for `preparePipeline`
4561
5199
  * TODO: [🏏] Leverage the batch API and build queues @see https://platform.openai.com/docs/guides/batch
4562
5200
  * TODO: [🧊] In future one preparation can take data from previous preparation and save tokens and time
@@ -4728,7 +5366,7 @@ var knowledgeCommandParser = {
4728
5366
  if (sourceContent === '') {
4729
5367
  throw new ParseError("Source is not defined");
4730
5368
  }
4731
- // TODO: !!!! Following checks should be applied every link in the `sourceContent`
5369
+ // TODO:[main] !!!! Following checks should be applied every link in the `sourceContent`
4732
5370
  if (sourceContent.startsWith('http://')) {
4733
5371
  throw new ParseError("Source is not secure");
4734
5372
  }
@@ -4913,7 +5551,7 @@ var templateCommandParser = {
4913
5551
  if (command.templateType === 'KNOWLEDGE') {
4914
5552
  knowledgeCommandParser.$applyToPipelineJson({
4915
5553
  type: 'KNOWLEDGE',
4916
- sourceContent: $templateJson.content, // <- TODO: [🐝] !!! Work with KNOWLEDGE which not referring to the source file or website, but its content itself
5554
+ sourceContent: $templateJson.content, // <- TODO: [🐝][main] !!! Work with KNOWLEDGE which not referring to the source file or website, but its content itself
4917
5555
  }, $pipelineJson);
4918
5556
  $templateJson.isTemplate = false;
4919
5557
  return;
@@ -5263,6 +5901,171 @@ function normalizeTo_SCREAMING_CASE(text) {
5263
5901
  * TODO: [🌺] Use some intermediate util splitWords
5264
5902
  */
5265
5903
 
5904
+ /**
5905
+ * @@@
5906
+ *
5907
+ * @param text @@@
5908
+ * @param _isFirstLetterCapital @@@
5909
+ * @returns @@@
5910
+ * @example 'helloWorld'
5911
+ * @example 'iLovePromptbook'
5912
+ * @public exported from `@promptbook/utils`
5913
+ */
5914
+ function normalizeTo_camelCase(text, _isFirstLetterCapital) {
5915
+ var e_1, _a;
5916
+ if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
5917
+ var charType;
5918
+ var lastCharType = null;
5919
+ var normalizedName = '';
5920
+ try {
5921
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5922
+ var char = text_1_1.value;
5923
+ var normalizedChar = void 0;
5924
+ if (/^[a-z]$/.test(char)) {
5925
+ charType = 'LOWERCASE';
5926
+ normalizedChar = char;
5927
+ }
5928
+ else if (/^[A-Z]$/.test(char)) {
5929
+ charType = 'UPPERCASE';
5930
+ normalizedChar = char.toLowerCase();
5931
+ }
5932
+ else if (/^[0-9]$/.test(char)) {
5933
+ charType = 'NUMBER';
5934
+ normalizedChar = char;
5935
+ }
5936
+ else {
5937
+ charType = 'OTHER';
5938
+ normalizedChar = '';
5939
+ }
5940
+ if (!lastCharType) {
5941
+ if (_isFirstLetterCapital) {
5942
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
5943
+ }
5944
+ }
5945
+ else if (charType !== lastCharType &&
5946
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
5947
+ !(lastCharType === 'NUMBER') &&
5948
+ !(charType === 'NUMBER')) {
5949
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
5950
+ }
5951
+ normalizedName += normalizedChar;
5952
+ lastCharType = charType;
5953
+ }
5954
+ }
5955
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5956
+ finally {
5957
+ try {
5958
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5959
+ }
5960
+ finally { if (e_1) throw e_1.error; }
5961
+ }
5962
+ return normalizedName;
5963
+ }
5964
+ /**
5965
+ * TODO: [🌺] Use some intermediate util splitWords
5966
+ */
5967
+
5968
+ /**
5969
+ * Removes quotes from a string
5970
+ *
5971
+ * Tip: This is very usefull for post-processing of the result of the LLM model
5972
+ * Note: This function removes only the same quotes from the beginning and the end of the string
5973
+ * Note: There are two simmilar functions:
5974
+ * - `removeQuotes` which removes only bounding quotes
5975
+ * - `unwrapResult` which removes whole introduce sentence
5976
+ *
5977
+ * @param text optionally quoted text
5978
+ * @returns text without quotes
5979
+ * @public exported from `@promptbook/utils`
5980
+ */
5981
+ function removeQuotes(text) {
5982
+ if (text.startsWith('"') && text.endsWith('"')) {
5983
+ return text.slice(1, -1);
5984
+ }
5985
+ if (text.startsWith('\'') && text.endsWith('\'')) {
5986
+ return text.slice(1, -1);
5987
+ }
5988
+ return text;
5989
+ }
5990
+
5991
+ /**
5992
+ * Function `validateParameterName` will @@@
5993
+ *
5994
+ * @param parameterName @@@
5995
+ * @returns @@@
5996
+ * @throws {ParseError} @@@
5997
+ * @private within the repository
5998
+ */
5999
+ function validateParameterName(parameterName) {
6000
+ var e_1, _a;
6001
+ var rawParameterName = parameterName;
6002
+ try {
6003
+ for (var _b = __values([
6004
+ ['`', '`'],
6005
+ ['{', '}'],
6006
+ ['[', ']'],
6007
+ ['(', ')'],
6008
+ ['<', '>'],
6009
+ ]), _c = _b.next(); !_c.done; _c = _b.next()) {
6010
+ var _d = __read(_c.value, 2), start = _d[0], end = _d[1];
6011
+ if (parameterName.substring(0, 1) === start &&
6012
+ parameterName.substring(parameterName.length - 1, parameterName.length) === end
6013
+ // <- TODO: More universal that 1 character
6014
+ ) {
6015
+ parameterName = parameterName.substring(1, parameterName.length - 1);
6016
+ // <- TODO: More universal that 1 character
6017
+ }
6018
+ }
6019
+ }
6020
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
6021
+ finally {
6022
+ try {
6023
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
6024
+ }
6025
+ finally { if (e_1) throw e_1.error; }
6026
+ }
6027
+ // TODO: [🐠] Following try-catch block should be part of common validators logic
6028
+ try {
6029
+ /*
6030
+ Note: We don't need to check for spaces because we are going to normalize the parameter name to camelCase
6031
+ if (parameterName.includes(' ')) {
6032
+ throw new ParseError(`Parameter name cannot contain spaces`);
6033
+ }
6034
+ */
6035
+ if (parameterName.includes('.')) {
6036
+ throw new ParseError("Parameter name cannot contain dots");
6037
+ }
6038
+ if (parameterName.includes('/') || parameterName.includes('\\')) {
6039
+ throw new ParseError("Parameter name cannot contain slashes");
6040
+ }
6041
+ if (parameterName.includes('(') ||
6042
+ parameterName.includes(')') ||
6043
+ parameterName.includes('{') ||
6044
+ parameterName.includes('}') ||
6045
+ parameterName.includes('[') ||
6046
+ parameterName.includes(']')) {
6047
+ throw new ParseError("Parameter name cannot contain braces");
6048
+ }
6049
+ parameterName = removeDiacritics(parameterName);
6050
+ parameterName = removeEmojis(parameterName);
6051
+ parameterName = removeQuotes(parameterName);
6052
+ parameterName = normalizeTo_camelCase(parameterName);
6053
+ if (parameterName === '') {
6054
+ throw new ParseError("Parameter name cannot be empty");
6055
+ }
6056
+ if (RESERVED_PARAMETER_NAMES.includes(parameterName)) {
6057
+ throw new ParseError("{".concat(parameterName, "} is a reserved parameter name"));
6058
+ }
6059
+ }
6060
+ catch (error) {
6061
+ if (!(error instanceof ParseError)) {
6062
+ throw error;
6063
+ }
6064
+ throw new ParseError(spaceTrim(function (block) { return "\n ".concat(block(error.message), "\n\n Tried to validate parameter name:\n ").concat(block(rawParameterName), "\n "); }));
6065
+ }
6066
+ return parameterName;
6067
+ }
6068
+
5266
6069
  /**
5267
6070
  * Parses the foreach command
5268
6071
  *
@@ -5292,67 +6095,61 @@ var foreachCommandParser = {
5292
6095
  /**
5293
6096
  * Link to discussion
5294
6097
  */
5295
- documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/@@',
6098
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/148',
5296
6099
  /**
5297
6100
  * Example usages of the FOREACH command
5298
6101
  */
5299
6102
  examples: [
5300
- 'FOREACH List Line -> `{customer}`',
5301
- 'FOR List Line -> `{customer}`',
5302
- 'EACH List Line -> `{customer}`',
5303
- // <- TODO: [🍭] !!!!!! More
6103
+ 'FOREACH Text Line `{customers}` -> `{customer}`',
6104
+ 'FOR Csv Row `{customers}` -> `{firstName}`, `{lastName}`',
6105
+ 'EACH Csv Cell `{customers}` -> `{subformat}`',
5304
6106
  ],
5305
6107
  /**
5306
6108
  * Parses the FOREACH command
5307
6109
  */
5308
6110
  parse: function (input) {
5309
- var args = input.args, rawArgs = input.rawArgs;
6111
+ var args = input.args;
5310
6112
  var formatName = normalizeTo_SCREAMING_CASE(args[0] || '');
5311
- var cellName = normalizeTo_SCREAMING_CASE(args[1] || '');
5312
- var assignSign = args[2];
5313
- var parameter = args[3];
5314
- if (![
5315
- 'LIST',
5316
- 'CSV',
5317
- // <- TODO: [🏢] Unhardcode formats
5318
- ].includes(formatName)) {
5319
- console.info({ args: args, formatName: formatName });
5320
- throw new Error("Unsupported format \"".concat(formatName, "\""));
6113
+ var subformatName = normalizeTo_SCREAMING_CASE(args[1] || '');
6114
+ var parameterNameArg = args[2] || '';
6115
+ var assignSign = args[3];
6116
+ var formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
6117
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(formatName);
6118
+ });
6119
+ if (formatDefinition === undefined) {
6120
+ throw new ParseError(spaceTrim(function (block) { return "\n Unsupported format \"".concat(formatName, "\"\n\n Available formats:\n ").concat(block(FORMAT_DEFINITIONS.map(function (formatDefinition) { return formatDefinition.formatName; })
6121
+ .map(function (formatName) { return "- ".concat(formatName); })
6122
+ .join('\n')), "\n "); }));
5321
6123
  // <- TODO: [🏢] List all supported format names
5322
6124
  }
5323
- if (![
5324
- 'LINE',
5325
- 'ROW',
5326
- 'COLUMN',
5327
- 'CELL',
5328
- // <- TODO: [🏢] Unhardcode format cekks
5329
- ].includes(cellName)) {
5330
- console.info({ args: args, cellName: cellName });
5331
- throw new Error("Format ".concat(formatName, " does not support cell \"").concat(cellName, "\""));
5332
- // <- TODO: [🏢] List all supported cell names for the format
6125
+ var subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
6126
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(subformatName);
6127
+ });
6128
+ if (subvalueDefinition === undefined) {
6129
+ throw new ParseError(spaceTrim(function (block) { return "\n Unsupported subformat name \"".concat(subformatName, "\" for format \"").concat(formatName, "\"\n\n Available subformat names for format \"").concat(formatDefinition.formatName, "\":\n ").concat(block(formatDefinition.subvalueDefinitions
6130
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
6131
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
6132
+ .join('\n')), "\n "); }));
6133
+ // <- TODO: [🏢] List all supported subformat names for the format
5333
6134
  }
5334
6135
  if (assignSign !== '->') {
5335
- console.info({ args: args, assignSign: assignSign });
5336
- throw new Error("FOREACH command must have '->' to assign the value to the parameter");
5337
- }
5338
- var parameterNames = extractParameterNames(parameter || rawArgs);
5339
- if (parameterNames.size !== 1) {
5340
- console.info({ args: args, parameter: parameter, rawArgs: rawArgs });
5341
- throw new Error("FOREACH command contain exactly one parameter, but found ".concat(parameterNames.size));
5342
- }
5343
- var parameterName = parameterNames.values().next().value;
5344
- if (typeof parameterName !== 'string'
5345
- // <- TODO: !!!!!! Replace with propper parameter name validation
5346
- ) {
5347
- console.info({ args: args, parameterName: parameterName });
5348
- throw new Error("Invalid parameter name");
5349
- // <- TODO: !!!!!! Better error (with rules and precise error) from validateParameterName
6136
+ throw new ParseError("FOREACH command must have '->' to assign the value to the parameter");
6137
+ }
6138
+ var parameterName = validateParameterName(parameterNameArg);
6139
+ var subparameterNames = args
6140
+ .slice(4)
6141
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
6142
+ .filter(function (parameterName) { return parameterName !== ''; })
6143
+ .map(validateParameterName);
6144
+ if (subparameterNames.length === 0) {
6145
+ throw new ParseError("FOREACH command must have at least one subparameter");
5350
6146
  }
5351
6147
  return {
5352
6148
  type: 'FOREACH',
5353
6149
  formatName: formatName,
5354
- cellName: cellName,
6150
+ subformatName: subformatName,
5355
6151
  parameterName: parameterName,
6152
+ subparameterNames: subparameterNames,
5356
6153
  };
5357
6154
  },
5358
6155
  /**
@@ -5361,8 +6158,12 @@ var foreachCommandParser = {
5361
6158
  * Note: `$` is used to indicate that this function mutates given `templateJson`
5362
6159
  */
5363
6160
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5364
- keepUnused(command, $templateJson, $pipelineJson);
5365
- // <- TODO: [🍭] !!!!!! Implement
6161
+ var formatName = command.formatName, subformatName = command.subformatName, parameterName = command.parameterName, subparameterNames = command.subparameterNames;
6162
+ // TODO: [🍭] Detect double use
6163
+ // TODO: [🍭] Detect usage with JOKER and don't allow it
6164
+ $templateJson.foreach = { formatName: formatName, subformatName: subformatName, parameterName: parameterName, subparameterNames: subparameterNames };
6165
+ keepUnused($pipelineJson); // <- TODO: [🧠] Maybe register subparameter from foreach into parameters of the pipeline
6166
+ // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase
5366
6167
  },
5367
6168
  /**
5368
6169
  * Converts the FOREACH command back to string
@@ -5371,8 +6172,7 @@ var foreachCommandParser = {
5371
6172
  */
5372
6173
  stringify: function (command) {
5373
6174
  keepUnused(command);
5374
- return "";
5375
- // <- TODO: [🍭] !!!!!! Implement
6175
+ return "---"; // <- TODO: [🛋] Implement
5376
6176
  },
5377
6177
  /**
5378
6178
  * Reads the FOREACH command from the `TemplateJson`
@@ -5381,13 +6181,11 @@ var foreachCommandParser = {
5381
6181
  */
5382
6182
  takeFromTemplateJson: function ($templateJson) {
5383
6183
  keepUnused($templateJson);
5384
- return [];
5385
- // <- TODO: [🍭] !!!!!! Implement
6184
+ throw new NotYetImplementedError("[\uD83D\uDECB] Not implemented yet"); // <- TODO: [🛋] Implement
5386
6185
  },
5387
6186
  };
5388
6187
  /**
5389
- * TODO: !!!!!! Comment console logs
5390
- * TODO: [🍭] !!!!!! Make .ptbk.md file with examples of the FOREACH command and also with wrong parsing and logic
6188
+ * TODO: [🍭] Make .ptbk.md file with examples of the FOREACH with wrong parsing and logic
5391
6189
  */
5392
6190
 
5393
6191
  /**
@@ -5497,11 +6295,11 @@ var jokerCommandParser = {
5497
6295
  */
5498
6296
  parse: function (input) {
5499
6297
  var args = input.args;
5500
- var parametersMatch = (args.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
5501
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5502
- throw new ParseError("Invalid joker");
6298
+ if (args.length !== 1) {
6299
+ throw new ParseError("JOKE command expects exactly one parameter name");
5503
6300
  }
5504
- var parameterName = parametersMatch.groups.parameterName;
6301
+ var parameterNameArg = args[0] || '';
6302
+ var parameterName = validateParameterName(parameterNameArg);
5505
6303
  return {
5506
6304
  type: 'JOKER',
5507
6305
  parameterName: parameterName,
@@ -5576,6 +6374,9 @@ var modelCommandParser = {
5576
6374
  */
5577
6375
  parse: function (input) {
5578
6376
  var args = input.args, normalized = input.normalized;
6377
+ var availableVariantsMessage = spaceTrim(function (block) { return "\n Available variants are:\n ".concat(block(MODEL_VARIANTS.map(function (variantName) {
6378
+ return "- ".concat(variantName).concat(variantName !== 'EMBEDDING' ? '' : ' (Not available in pipeline)');
6379
+ }).join('\n')), "\n "); });
5579
6380
  // TODO: Make this more elegant and dynamically
5580
6381
  if (normalized.startsWith('MODEL_VARIANT')) {
5581
6382
  if (normalized === 'MODEL_VARIANT_CHAT') {
@@ -5591,17 +6392,13 @@ var modelCommandParser = {
5591
6392
  key: 'modelVariant',
5592
6393
  value: 'COMPLETION',
5593
6394
  };
6395
+ // <- Note: [🤖]
5594
6396
  }
5595
6397
  else if (normalized.startsWith('MODEL_VARIANT_EMBED')) {
5596
- return {
5597
- type: 'MODEL',
5598
- key: 'modelVariant',
5599
- value: 'EMBEDDING',
5600
- };
5601
- // <- Note: [🤖]
6398
+ spaceTrim(function (block) { return "\n Embedding model can not be used in pipeline\n\n ".concat(block(availableVariantsMessage), "\n "); });
5602
6399
  }
5603
6400
  else {
5604
- throw new ParseError(spaceTrim(function (block) { return "\n Unknown model variant in command:\n\n Supported variants are:\n ".concat(block(MODEL_VARIANTS.map(function (variantName) { return "- ".concat(variantName); }).join('\n')), "\n "); }));
6401
+ throw new ParseError(spaceTrim(function (block) { return "\n Unknown model variant in command:\n\n ".concat(block(availableVariantsMessage), "\n "); }));
5605
6402
  }
5606
6403
  }
5607
6404
  if (normalized.startsWith('MODEL_NAME')) {
@@ -5626,6 +6423,7 @@ var modelCommandParser = {
5626
6423
  if ($pipelineJson.defaultModelRequirements[command.key] !== undefined) {
5627
6424
  if ($pipelineJson.defaultModelRequirements[command.key] === command.value) {
5628
6425
  console.warn("Multiple commands `MODEL ".concat(command.key, " ").concat(command.value, "` in the pipeline head"));
6426
+ // <- TODO: [🚎] Some better way how to get warnings from pipeline parsing / logic
5629
6427
  }
5630
6428
  else {
5631
6429
  throw new ParseError(spaceTrim("\n Redefinition of MODEL `".concat(command.key, "` in the pipeline head\n\n You have used:\n - MODEL ").concat(command.key, " ").concat($pipelineJson.defaultModelRequirements[command.key], "\n - MODEL ").concat(command.key, " ").concat(command.value, "\n ")));
@@ -5725,14 +6523,13 @@ var parameterCommandParser = {
5725
6523
  * Parses the PARAMETER command
5726
6524
  */
5727
6525
  parse: function (input) {
5728
- var normalized = input.normalized, raw = input.raw;
5729
- var parametersMatch = raw.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
5730
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5731
- throw new ParseError("Invalid parameter");
5732
- }
5733
- var _a = parametersMatch.groups, parameterName = _a.parameterName, parameterDescription = _a.parameterDescription;
5734
- if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
5735
- throw new ParseError("Parameter {".concat(parameterName, "} can not contain another parameter in description"));
6526
+ var normalized = input.normalized, args = input.args, raw = input.raw;
6527
+ var parameterNameRaw = args.shift() || '';
6528
+ var parameterDescriptionRaw = args.join(' ');
6529
+ // <- TODO: When [🥶] fixed, change to:
6530
+ // > const parameterDescriptionRaw = rawArgs.split(parameterNameRaw).join('').trim();
6531
+ if (parameterDescriptionRaw && parameterDescriptionRaw.match(/\{(?<embeddedParameterName>[a-z0-9_]+)\}/im)) {
6532
+ throw new ParseError(spaceTrim(function (block) { return "\n Parameter {".concat(parameterNameRaw, "} can not contain another parameter in description\n\n The description:\n ").concat(block(parameterDescriptionRaw), "\n "); }));
5736
6533
  }
5737
6534
  var isInput = normalized.startsWith('INPUT');
5738
6535
  var isOutput = normalized.startsWith('OUTPUT');
@@ -5740,11 +6537,12 @@ var parameterCommandParser = {
5740
6537
  isInput = false;
5741
6538
  isOutput = false;
5742
6539
  }
5743
- // TODO: !!!!!! Add parameter name validation
6540
+ var parameterName = validateParameterName(parameterNameRaw);
6541
+ var parameterDescription = parameterDescriptionRaw.trim() || null;
5744
6542
  return {
5745
6543
  type: 'PARAMETER',
5746
6544
  parameterName: parameterName,
5747
- parameterDescription: parameterDescription.trim() || null,
6545
+ parameterDescription: parameterDescription,
5748
6546
  isInput: isInput,
5749
6547
  isOutput: isOutput,
5750
6548
  };
@@ -6069,6 +6867,7 @@ var promptbookVersionCommandParser = {
6069
6867
  * Note: `$` is used to indicate that this function mutates given `pipelineJson`
6070
6868
  */
6071
6869
  $applyToPipelineJson: function (command, $pipelineJson) {
6870
+ // TODO: Warn if the version is overridden
6072
6871
  $pipelineJson.promptbookVersion = command.promptbookVersion;
6073
6872
  },
6074
6873
  /**
@@ -6551,7 +7350,9 @@ function parseCommand(raw, usagePlace) {
6551
7350
  for (var commandNameSegmentsCount = 0; commandNameSegmentsCount < Math.min(items.length, 3); commandNameSegmentsCount++) {
6552
7351
  var commandNameRaw = items.slice(0, commandNameSegmentsCount + 1).join('_');
6553
7352
  var args = items.slice(commandNameSegmentsCount + 1);
6554
- var rawArgs = raw.substring(commandNameRaw.length).trim();
7353
+ var rawArgs = raw
7354
+ .substring(commandNameRaw.length)
7355
+ .trim();
6555
7356
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6556
7357
  if (command !== null) {
6557
7358
  return command;
@@ -6562,7 +7363,9 @@ function parseCommand(raw, usagePlace) {
6562
7363
  {
6563
7364
  var commandNameRaw = items.slice(-1).join('_');
6564
7365
  var args = items.slice(0, -1); // <- Note: This is probbably not correct
6565
- var rawArgs = raw.substring(0, raw.length - commandNameRaw.length).trim();
7366
+ var rawArgs = raw
7367
+ .substring(0, raw.length - commandNameRaw.length)
7368
+ .trim();
6566
7369
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6567
7370
  if (command !== null) {
6568
7371
  return command;
@@ -6702,7 +7505,7 @@ function extractAllListItemsFromMarkdown(markdown) {
6702
7505
  function extractOneBlockFromMarkdown(markdown) {
6703
7506
  var codeBlocks = extractAllBlocksFromMarkdown(markdown);
6704
7507
  if (codeBlocks.length !== 1) {
6705
- throw new ParseError(spaceTrim(function (block) { return "\n There should be exactly 1 code block, found ".concat(codeBlocks.length, " code blocks\n\n ").concat(block(codeBlocks.map(function (block, i) { return "Block ".concat(i + 1, ":\n").concat(block.content); }).join('\n\n\n')), "\n "); }));
7508
+ throw new ParseError(spaceTrim(function (block) { return "\n There should be exactly 1 code block in template, found ".concat(codeBlocks.length, " code blocks\n\n ").concat(block(codeBlocks.map(function (block, i) { return "Block ".concat(i + 1, ":\n").concat(block.content); }).join('\n\n\n')), "\n "); }));
6706
7509
  }
6707
7510
  return codeBlocks[0];
6708
7511
  }
@@ -6889,7 +7692,7 @@ function pipelineStringToJsonSync(pipelineString) {
6889
7692
  var $pipelineJson = {
6890
7693
  title: undefined /* <- Note: [🍙] Putting here placeholder to keep `title` on top at final JSON */,
6891
7694
  pipelineUrl: undefined /* <- Note: Putting here placeholder to keep `pipelineUrl` on top at final JSON */,
6892
- promptbookVersion: PROMPTBOOK_VERSION,
7695
+ promptbookVersion: undefined /* <- Note: By default no explicit version */,
6893
7696
  description: undefined /* <- Note: [🍙] Putting here placeholder to keep `description` on top at final JSON */,
6894
7697
  parameters: [],
6895
7698
  templates: [],
@@ -7180,7 +7983,7 @@ function pipelineStringToJsonSync(pipelineString) {
7180
7983
  return $asDeeplyFrozenSerializableJson('pipelineJson', $pipelineJson);
7181
7984
  }
7182
7985
  /**
7183
- * TODO: !!!! Warn if used only sync version
7986
+ * TODO:[main] !!!! Warn if used only sync version
7184
7987
  * TODO: [🚞] Report here line/column of error
7185
7988
  * TODO: Use spaceTrim more effectively
7186
7989
  * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
@@ -7261,70 +8064,6 @@ function addAutoGeneratedSection(content, options) {
7261
8064
  * TODO: [🏛] This can be part of markdown builder
7262
8065
  */
7263
8066
 
7264
- /**
7265
- * @@@
7266
- *
7267
- * @param text @@@
7268
- * @param _isFirstLetterCapital @@@
7269
- * @returns @@@
7270
- * @example 'helloWorld'
7271
- * @example 'iLovePromptbook'
7272
- * @public exported from `@promptbook/utils`
7273
- */
7274
- function normalizeTo_camelCase(text, _isFirstLetterCapital) {
7275
- var e_1, _a;
7276
- if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
7277
- var charType;
7278
- var lastCharType = null;
7279
- var normalizedName = '';
7280
- try {
7281
- for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
7282
- var char = text_1_1.value;
7283
- var normalizedChar = void 0;
7284
- if (/^[a-z]$/.test(char)) {
7285
- charType = 'LOWERCASE';
7286
- normalizedChar = char;
7287
- }
7288
- else if (/^[A-Z]$/.test(char)) {
7289
- charType = 'UPPERCASE';
7290
- normalizedChar = char.toLowerCase();
7291
- }
7292
- else if (/^[0-9]$/.test(char)) {
7293
- charType = 'NUMBER';
7294
- normalizedChar = char;
7295
- }
7296
- else {
7297
- charType = 'OTHER';
7298
- normalizedChar = '';
7299
- }
7300
- if (!lastCharType) {
7301
- if (_isFirstLetterCapital) {
7302
- normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
7303
- }
7304
- }
7305
- else if (charType !== lastCharType &&
7306
- !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
7307
- !(lastCharType === 'NUMBER') &&
7308
- !(charType === 'NUMBER')) {
7309
- normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
7310
- }
7311
- normalizedName += normalizedChar;
7312
- lastCharType = charType;
7313
- }
7314
- }
7315
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
7316
- finally {
7317
- try {
7318
- if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
7319
- }
7320
- finally { if (e_1) throw e_1.error; }
7321
- }
7322
- return normalizedName;
7323
- }
7324
- /**
7325
- * TODO: [🌺] Use some intermediate util splitWords
7326
- */
7327
-
7328
8067
  /**
7329
8068
  * Creates a Mermaid graph based on the promptbook
7330
8069
  *
@@ -7381,6 +8120,9 @@ function renderPromptbookMermaid(pipelineJson, options) {
7381
8120
  return promptbookMermaid;
7382
8121
  }
7383
8122
  /**
8123
+ * TODO: !!!!! FOREACH in mermaid graph
8124
+ * TODO: !!!!! Knowledge in mermaid graph
8125
+ * TODO: !!!!! Personas in mermaid graph
7384
8126
  * TODO: Maybe use some Mermaid package instead of string templating
7385
8127
  * TODO: [🕌] When more than 2 functionalities, split into separate functions
7386
8128
  */
@@ -7455,7 +8197,7 @@ function isSerializableAsJson(value) {
7455
8197
  }
7456
8198
  }
7457
8199
  /**
7458
- * TODO: [🧠] !!! In-memory cache of same values to prevent multiple checks
8200
+ * TODO: [🧠][main] !!! In-memory cache of same values to prevent multiple checks
7459
8201
  * TODO: [🧠][💺] Can be done this on type-level?
7460
8202
  */
7461
8203
 
@@ -7522,21 +8264,41 @@ function usageToWorktime(usage) {
7522
8264
  * @public exported from `@promptbook/core`
7523
8265
  */
7524
8266
  function usageToHuman(usage) {
7525
- var report = 'Usage:';
8267
+ var reportItems = [];
7526
8268
  var uncertainNumberToHuman = function (_a) {
7527
8269
  var value = _a.value, isUncertain = _a.isUncertain;
7528
8270
  return "".concat(isUncertain ? 'approximately ' : '').concat(Math.round(value * 100) / 100);
7529
8271
  };
7530
- report += '\n' + "- Cost ".concat(uncertainNumberToHuman(usage.price), " USD");
7531
- report += '\n' + "- Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time");
7532
- return spaceTrim(report);
8272
+ if (usage.price.value > 0.01
8273
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻] Configure negligible value - default value to config + value to `UsageToHumanSettings`
8274
+ ) {
8275
+ reportItems.push("Cost ".concat(uncertainNumberToHuman(usage.price), " USD"));
8276
+ }
8277
+ else {
8278
+ reportItems.push("Negligible cost");
8279
+ }
8280
+ var worktime = usageToWorktime(usage);
8281
+ if (worktime.value >
8282
+ 1 / 60
8283
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻]
8284
+ ) {
8285
+ reportItems.push("Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time"));
8286
+ // TODO: [🍓][🧞‍♂️] Show minutes, seconds, days NOT 0.1 hours
8287
+ }
8288
+ if (usage.output.charactersCount.value > 0) {
8289
+ reportItems.push("Written ".concat(uncertainNumberToHuman(usage.output.charactersCount), " characters"));
8290
+ }
8291
+ if (reportItems.length === 0) {
8292
+ // Note: For negligible usage, we report at least something
8293
+ reportItems.push('Negligible');
8294
+ }
8295
+ return spaceTrim(function (block) { return "\n Usage:\n ".concat(block(reportItems.map(function (item) { return "- ".concat(item); }).join('\n')), "\n "); });
7533
8296
  }
7534
8297
  /**
7535
- * TODO: Use "$1" not "1 USD"
7536
- * TODO: Use markdown formatting like "Cost approximately **$1**"
7537
- * TODO: Report in minutes, seconds, days NOT 0.1 hours
8298
+ * TODO: [🍓][🧞‍♂️] Use "$1" not "1 USD"
8299
+ * TODO: [🍓][🧞‍♂️] Use markdown formatting like "Cost approximately **$1**"
8300
+ * TODO: [🍓][🧞‍♂️] Report in minutes, seconds, days NOT 0.1 hours
7538
8301
  * TODO: [🧠] Maybe make from `uncertainNumberToHuman` separate exported utility
7539
- * TODO: When negligible usage, report "Negligible" or just don't report it
7540
8302
  * TODO: [🧠] Maybe use "~" instead of "approximately"
7541
8303
  * TODO: [🏛] Maybe make some markdown builder
7542
8304
  */
@@ -8185,8 +8947,8 @@ function formatNumber(value) {
8185
8947
  */
8186
8948
  function createMarkdownTable(table) {
8187
8949
  var columnWidths = table.reduce(function (widths, row) {
8188
- row.forEach(function (cell, columnIndex) {
8189
- var cellLength = cell.length;
8950
+ row.forEach(function (subformat, columnIndex) {
8951
+ var cellLength = subformat.length;
8190
8952
  if (!widths[columnIndex] || cellLength > widths[columnIndex]) {
8191
8953
  widths[columnIndex] = cellLength;
8192
8954
  }
@@ -8194,12 +8956,12 @@ function createMarkdownTable(table) {
8194
8956
  return widths;
8195
8957
  }, []);
8196
8958
  var header = "| ".concat(table[0]
8197
- .map(function (cell, columnIndex) { return cell.padEnd(columnWidths[columnIndex]); })
8959
+ .map(function (subformat, columnIndex) { return subformat.padEnd(columnWidths[columnIndex]); })
8198
8960
  .join(' | '), " |");
8199
8961
  var separator = "|".concat(columnWidths.map(function (width) { return '-'.repeat(width + 2); }).join('|'), "|");
8200
8962
  var rows = table.slice(1).map(function (row) {
8201
- var paddedRow = row.map(function (cell, columnIndex) {
8202
- return cell.padEnd(columnWidths[columnIndex]);
8963
+ var paddedRow = row.map(function (subformat, columnIndex) {
8964
+ return subformat.padEnd(columnWidths[columnIndex]);
8203
8965
  });
8204
8966
  return "| ".concat(paddedRow.join(' | '), " |");
8205
8967
  });
@@ -8475,5 +9237,5 @@ function executionReportJsonToString(executionReportJson, options) {
8475
9237
  * TODO: [🧠] Should be in generated file GENERATOR_WARNING
8476
9238
  */
8477
9239
 
8478
- export { $llmToolsMetadataRegister, $llmToolsRegister, CLAIM, CallbackInterfaceTools, CollectionError, DEFAULT_REMOTE_URL, DEFAULT_REMOTE_URL_PATH, ERRORS, EXECUTIONS_CACHE_DIRNAME, EXPECTATION_UNITS, EnvironmentMismatchError, ExecutionReportStringOptionsDefaults, ExpectError, IS_VERBOSE, LimitReachedError, MAX_EXECUTION_ATTEMPTS, MAX_FILENAME_LENGTH, MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH, MAX_KNOWLEDGE_SOURCES_SCRAPING_TOTAL, MAX_PARALLEL_COUNT, MODEL_VARIANTS, MemoryStorage, NotFoundError, NotYetImplementedError, PIPELINE_COLLECTION_BASE_FILENAME, PROMPTBOOK_VERSION, ParseError, PipelineExecutionError, PipelineLogicError, PipelineUrlError, PrefixStorage, RESERVED_PARAMETER_NAMES, TemplateTypes, UnexpectedError, ZERO_USAGE, _AnthropicClaudeMetadataRegistration, _AzureOpenAiMetadataRegistration, _OpenAiMetadataRegistration, addUsage, assertsExecutionSuccessful, cacheLlmTools, collectionToJson, countTotalUsage, createCollectionFromJson, createCollectionFromPromise, createCollectionFromUrl, createLlmToolsFromConfiguration, createPipelineExecutor, createSubcollection, embeddingVectorToString, executionReportJsonToString, isPassingExpectations, isPipelinePrepared, joinLlmExecutionTools, limitTotalUsage, pipelineJsonToString, pipelineStringToJson, pipelineStringToJsonSync, prepareKnowledgeFromMarkdown, prepareKnowledgePieces, preparePersona, preparePipeline, prepareTemplates, prettifyPipelineString, stringifyPipelineJson, unpreparePipeline, usageToHuman, usageToWorktime, validatePipeline };
9240
+ export { $llmToolsMetadataRegister, $llmToolsRegister, CLAIM, CallbackInterfaceTools, CollectionError, CsvFormatDefinition, DEFAULT_CSV_SETTINGS, DEFAULT_REMOTE_URL, DEFAULT_REMOTE_URL_PATH, ERRORS, EXECUTIONS_CACHE_DIRNAME, EXPECTATION_UNITS, EnvironmentMismatchError, ExecutionReportStringOptionsDefaults, ExpectError, IS_VERBOSE, LimitReachedError, MANDATORY_CSV_SETTINGS, MAX_EXECUTION_ATTEMPTS, MAX_FILENAME_LENGTH, MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH, MAX_KNOWLEDGE_SOURCES_SCRAPING_TOTAL, MAX_PARALLEL_COUNT, MODEL_VARIANTS, MemoryStorage, NotFoundError, NotYetImplementedError, PIPELINE_COLLECTION_BASE_FILENAME, PROMPTBOOK_VERSION, ParseError, PipelineExecutionError, PipelineLogicError, PipelineUrlError, PrefixStorage, RESERVED_PARAMETER_NAMES, TemplateTypes, TextFormatDefinition, UnexpectedError, ZERO_USAGE, _AnthropicClaudeMetadataRegistration, _AzureOpenAiMetadataRegistration, _OpenAiMetadataRegistration, addUsage, assertsExecutionSuccessful, cacheLlmTools, collectionToJson, countTotalUsage, createCollectionFromJson, createCollectionFromPromise, createCollectionFromUrl, createLlmToolsFromConfiguration, createPipelineExecutor, createSubcollection, embeddingVectorToString, executionReportJsonToString, isPassingExpectations, isPipelinePrepared, joinLlmExecutionTools, limitTotalUsage, pipelineJsonToString, pipelineStringToJson, pipelineStringToJsonSync, prepareKnowledgeFromMarkdown, prepareKnowledgePieces, preparePersona, preparePipeline, prepareTemplates, prettifyPipelineString, stringifyPipelineJson, unpreparePipeline, usageToHuman, usageToWorktime, validatePipeline };
8479
9241
  //# sourceMappingURL=index.es.js.map