@promptbook/core 0.69.0-2 → 0.69.0-21

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 (75) hide show
  1. package/README.md +21 -58
  2. package/esm/index.es.js +2002 -1260
  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 +10 -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 +1 -1
  11. package/esm/typings/src/commands/FOREACH/ForeachJson.d.ts +6 -5
  12. package/esm/typings/src/commands/FOREACH/foreachCommandParser.d.ts +1 -2
  13. package/esm/typings/src/commands/_common/types/CommandParser.d.ts +1 -1
  14. package/esm/typings/src/config.d.ts +11 -4
  15. package/esm/typings/src/conversion/pipelineStringToJsonSync.d.ts +1 -1
  16. package/esm/typings/src/conversion/prettify/renderPipelineMermaidOptions.d.ts +3 -3
  17. package/esm/typings/src/conversion/utils/extractParameterNamesFromTemplate.d.ts +2 -1
  18. package/esm/typings/src/conversion/validation/validatePipeline.d.ts +6 -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/embeddingVectorToString.d.ts +1 -1
  34. package/esm/typings/src/execution/utils/checkExpectations.d.ts +2 -0
  35. package/esm/typings/src/execution/utils/usageToHuman.d.ts +3 -4
  36. package/esm/typings/src/formats/_common/FormatDefinition.d.ts +14 -15
  37. package/esm/typings/src/formats/_common/FormatSubvalueDefinition.d.ts +31 -0
  38. package/esm/typings/src/formats/csv/{ListFormatDefinition.d.ts → CsvFormatDefinition.d.ts} +6 -3
  39. package/esm/typings/src/formats/csv/CsvSettings.d.ts +13 -0
  40. package/esm/typings/src/formats/index.d.ts +1 -1
  41. package/esm/typings/src/formats/json/JsonFormatDefinition.d.ts +4 -3
  42. package/esm/typings/src/formats/text/TextFormatDefinition.d.ts +19 -0
  43. package/esm/typings/src/formats/xml/XmlFormatDefinition.d.ts +4 -3
  44. package/esm/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +1 -1
  45. package/esm/typings/src/knowledge/prepare-knowledge/pdf/prepareKnowledgeFromPdf.d.ts +1 -1
  46. package/esm/typings/src/llm-providers/_common/utils/cache/CacheItem.d.ts +1 -1
  47. package/esm/typings/src/llm-providers/anthropic-claude/anthropic-claude-models.d.ts +1 -1
  48. package/esm/typings/src/llm-providers/anthropic-claude/createAnthropicClaudeExecutionTools.d.ts +2 -2
  49. package/esm/typings/src/llm-providers/anthropic-claude/playground/playground.d.ts +2 -2
  50. package/esm/typings/src/llm-providers/openai/playground/playground.d.ts +1 -1
  51. package/esm/typings/src/personas/preparePersona.d.ts +1 -1
  52. package/esm/typings/src/prepare/isPipelinePrepared.d.ts +1 -1
  53. package/esm/typings/src/prepare/prepareTemplates.d.ts +1 -1
  54. package/esm/typings/src/types/PipelineJson/ParameterJson.d.ts +1 -1
  55. package/esm/typings/src/types/PipelineJson/PipelineJson.d.ts +1 -1
  56. package/esm/typings/src/types/execution-report/executionReportJsonToString.d.ts +2 -1
  57. package/esm/typings/src/types/typeAliases.d.ts +1 -1
  58. package/esm/typings/src/utils/expectation-counters/index.d.ts +3 -0
  59. package/esm/typings/src/utils/organization/{f.d.ts → empty_object.d.ts} +5 -1
  60. package/esm/typings/src/utils/organization/just_empty_object.d.ts +12 -0
  61. package/esm/typings/src/utils/{extractParameterNames.d.ts → parameters/extractParameterNames.d.ts} +2 -2
  62. package/esm/typings/src/utils/parameters/mapAvailableToExpectedParameters.d.ts +27 -0
  63. package/esm/typings/src/utils/{replaceParameters.d.ts → parameters/replaceParameters.d.ts} +2 -2
  64. package/esm/typings/src/utils/serialization/checkSerializableAsJson.d.ts +1 -1
  65. package/esm/typings/src/utils/serialization/isSerializableAsJson.d.ts +1 -1
  66. package/esm/typings/src/utils/validators/parameterName/validateParameterName.d.ts +10 -0
  67. package/package.json +17 -12
  68. package/umd/index.umd.js +2008 -1263
  69. package/umd/index.umd.js.map +1 -1
  70. package/esm/typings/src/execution/createPipelineExecutor.d.ts +0 -72
  71. package/esm/typings/src/formats/list/ListFormatDefinition.d.ts +0 -16
  72. /package/esm/typings/src/utils/{extractParameterNames.test.d.ts → parameters/extractParameterNames.test.d.ts} +0 -0
  73. /package/esm/typings/src/{execution/utils/usageToHuman.test.d.ts → utils/parameters/mapAvailableToExpectedParameters.test.d.ts} +0 -0
  74. /package/esm/typings/src/utils/{replaceParameters.test.d.ts → parameters/replaceParameters.test.d.ts} +0 -0
  75. /package/esm/typings/src/{personas/preparePersona.test.d.ts → utils/validators/parameterName/validateParameterName.test.d.ts} +0 -0
package/umd/index.umd.js CHANGED
@@ -1,8 +1,8 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('waitasecond'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('moment')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'spacetrim', 'prettier', 'prettier/parser-html', 'waitasecond', 'crypto-js/enc-hex', 'crypto-js/sha256', 'moment'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-core"] = {}, global.spaceTrim, global.prettier, global.parserHtml, global.waitasecond, global.hexEncoder, global.sha256, global.moment));
5
- })(this, (function (exports, spaceTrim, prettier, parserHtml, waitasecond, hexEncoder, sha256, moment) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('waitasecond'), require('papaparse'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('moment')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'spacetrim', 'prettier', 'prettier/parser-html', 'waitasecond', 'papaparse', 'crypto-js/enc-hex', 'crypto-js/sha256', 'moment'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-core"] = {}, global.spaceTrim, global.prettier, global.parserHtml, global.waitasecond, global.papaparse, global.hexEncoder, global.sha256, global.moment));
5
+ })(this, (function (exports, spaceTrim, prettier, parserHtml, waitasecond, papaparse, hexEncoder, sha256, moment) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
@@ -16,8 +16,8 @@
16
16
  /**
17
17
  * The version of the Promptbook library
18
18
  */
19
- var PROMPTBOOK_VERSION = '0.69.0-1';
20
- // TODO: !!!! List here all the versions and annotate + put into script
19
+ var PROMPTBOOK_VERSION = '0.69.0-20';
20
+ // TODO:[main] !!!! List here all the versions and annotate + put into script
21
21
 
22
22
  /*! *****************************************************************************
23
23
  Copyright (c) Microsoft Corporation.
@@ -229,7 +229,7 @@
229
229
  commands.push("PIPELINE URL ".concat(pipelineUrl));
230
230
  }
231
231
  commands.push("PROMPTBOOK VERSION ".concat(promptbookVersion));
232
- // TODO: !!! This increase size of the bundle and is probbably not necessary
232
+ // TODO:[main] !!! This increase size of the bundle and is probbably not necessary
233
233
  pipelineString = prettifyMarkdown(pipelineString);
234
234
  try {
235
235
  for (var _g = __values(parameters.filter(function (_a) {
@@ -377,12 +377,12 @@
377
377
  pipelineString += '```' + contentLanguage;
378
378
  pipelineString += '\n';
379
379
  pipelineString += spaceTrim__default["default"](content);
380
- // <- TODO: !!! Escape
380
+ // <- TODO:[main] !!! Escape
381
381
  // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
382
382
  pipelineString += '\n';
383
383
  pipelineString += '```';
384
384
  pipelineString += '\n\n';
385
- pipelineString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO: !!! If the parameter here has description, add it and use templateParameterJsonToString
385
+ pipelineString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO:[main] !!! If the parameter here has description, add it and use templateParameterJsonToString
386
386
  }
387
387
  }
388
388
  catch (e_3_1) { e_3 = { error: e_3_1 }; }
@@ -602,7 +602,7 @@
602
602
  }
603
603
  /**
604
604
  * TODO: [🧠][🛣] More elegant way to tracking than passing `name`
605
- * TODO: [🧠] !!! In-memory cache of same values to prevent multiple checks
605
+ * TODO: [🧠][main] !!! In-memory cache of same values to prevent multiple checks
606
606
  * Note: [🐠] This is how `checkSerializableAsJson` + `isSerializableAsJson` together can just retun true/false or rich error message
607
607
  */
608
608
 
@@ -658,13 +658,13 @@
658
658
  *
659
659
  * @public exported from `@promptbook/core`
660
660
  */
661
- var MAX_PARALLEL_COUNT = 5;
661
+ var MAX_PARALLEL_COUNT = 5; // <- TODO: [🤹‍♂️]
662
662
  /**
663
663
  * The maximum number of attempts to execute LLM task before giving up
664
664
  *
665
665
  * @public exported from `@promptbook/core`
666
666
  */
667
- var MAX_EXECUTION_ATTEMPTS = 3;
667
+ var MAX_EXECUTION_ATTEMPTS = 3; // <- TODO: [🤹‍♂️]
668
668
  /**
669
669
  * The maximum length of the (generated) filename
670
670
  *
@@ -673,14 +673,14 @@
673
673
  var MAX_FILENAME_LENGTH = 30;
674
674
  /**
675
675
  * @@@
676
- * TODO: [🐝] !!! Use
676
+ * TODO: [🐝][main] !!! Use
677
677
  *
678
678
  * @public exported from `@promptbook/core`
679
679
  */
680
680
  var MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH = 3;
681
681
  /**
682
682
  * @@@
683
- * TODO: [🐝] !!! Use
683
+ * TODO: [🐝][main] !!! Use
684
684
  *
685
685
  * @public exported from `@promptbook/core`
686
686
  */
@@ -715,6 +715,7 @@
715
715
  'samples',
716
716
  'modelName',
717
717
  'currentDate',
718
+ // <- TODO: !!!!! list here all command names
718
719
  // <- TODO: Add more like 'date', 'modelName',...
719
720
  // <- TODO: Add [emoji] + instructions ACRY when adding new reserved parameter
720
721
  ]);
@@ -752,6 +753,17 @@
752
753
  */
753
754
  var DEFAULT_REMOTE_URL_PATH = '/promptbook/socket.io';
754
755
  // <- TODO: [🧜‍♂️]
756
+ /**
757
+ * @@@
758
+ *
759
+ * @public exported from `@promptbook/core`
760
+ */
761
+ var DEFAULT_CSV_SETTINGS = Object.freeze({
762
+ delimiter: ',',
763
+ quoteChar: '"',
764
+ newline: '\n',
765
+ skipEmptyLines: true,
766
+ });
755
767
  /**
756
768
  * @@@
757
769
  *
@@ -844,7 +856,7 @@
844
856
  if ( /* version === '1.0.0' || */version === '2.0.0' || version === '3.0.0') {
845
857
  return false;
846
858
  }
847
- // <- TODO: !!! Check isValidPromptbookVersion against PROMPTBOOK_VERSIONS
859
+ // <- TODO:[main] !!! Check isValidPromptbookVersion against PROMPTBOOK_VERSIONS
848
860
  return true;
849
861
  }
850
862
 
@@ -1013,19 +1025,19 @@
1013
1025
  // <- Note: [🚲]
1014
1026
  throw new PipelineLogicError(spaceTrim.spaceTrim(function (block) { return "\n Invalid promptbook URL \"".concat(pipeline.pipelineUrl, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
1015
1027
  }
1016
- if (!isValidPromptbookVersion(pipeline.promptbookVersion)) {
1028
+ if (pipeline.promptbookVersion !== undefined && !isValidPromptbookVersion(pipeline.promptbookVersion)) {
1017
1029
  // <- Note: [🚲]
1018
1030
  throw new PipelineLogicError(spaceTrim.spaceTrim(function (block) { return "\n Invalid Promptbook Version \"".concat(pipeline.promptbookVersion, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
1019
1031
  }
1020
1032
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1021
1033
  if (!Array.isArray(pipeline.parameters)) {
1022
1034
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1023
- throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Promptbook is valid JSON but with wrong structure\n\n `promptbook.parameters` expected to be an array, but got ".concat(typeof pipeline.parameters, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1035
+ throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is valid JSON but with wrong structure\n\n `PipelineJson.parameters` expected to be an array, but got ".concat(typeof pipeline.parameters, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1024
1036
  }
1025
1037
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1026
1038
  if (!Array.isArray(pipeline.templates)) {
1027
1039
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1028
- throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Promptbook is valid JSON but with wrong structure\n\n `promptbook.templates` expected to be an array, but got ".concat(typeof pipeline.templates, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1040
+ throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is valid JSON but with wrong structure\n\n `PipelineJson.templates` expected to be an array, but got ".concat(typeof pipeline.templates, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
1029
1041
  }
1030
1042
  var _loop_1 = function (parameter) {
1031
1043
  if (parameter.isInput && parameter.isOutput) {
@@ -1196,6 +1208,7 @@
1196
1208
  }
1197
1209
  }
1198
1210
  /**
1211
+ * TODO: !!!!! [🧞‍♀️] Do not allow joker + foreach
1199
1212
  * TODO: [🧠] Work with promptbookVersion
1200
1213
  * TODO: Use here some json-schema, Zod or something similar and change it to:
1201
1214
  * > /**
@@ -1207,11 +1220,11 @@
1207
1220
  * > ex port function validatePipeline(promptbook: really_unknown): asserts promptbook is PipelineJson {
1208
1221
  */
1209
1222
  /**
1210
- * TODO: [🐣] !!!! Validate that all samples match expectations
1211
- * TODO: [🐣][🐝] !!!! Validate that knowledge is valid (non-void)
1212
- * TODO: [🐣] !!!! Validate that persona can be used only with CHAT variant
1213
- * TODO: [🐣] !!!! Validate that parameter with reserved name not used RESERVED_PARAMETER_NAMES
1214
- * TODO: [🐣] !!!! Validate that reserved parameter is not used as joker
1223
+ * TODO: [🐣][main] !!!! Validate that all samples match expectations
1224
+ * TODO: [🐣][🐝][main] !!!! Validate that knowledge is valid (non-void)
1225
+ * TODO: [🐣][main] !!!! Validate that persona can be used only with CHAT variant
1226
+ * TODO: [🐣][main] !!!! Validate that parameter with reserved name not used RESERVED_PARAMETER_NAMES
1227
+ * TODO: [🐣][main] !!!! Validate that reserved parameter is not used as joker
1215
1228
  * TODO: [🧠] Validation not only logic itself but imports around - files and websites and rerefenced pipelines exists
1216
1229
  * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
1217
1230
  */
@@ -1525,7 +1538,7 @@
1525
1538
  });
1526
1539
  }
1527
1540
  /**
1528
- * TODO: !!!! [🧠] Library precompilation and do not mix markdown and json promptbooks
1541
+ * TODO:[main] !!!! [🧠] Library precompilation and do not mix markdown and json promptbooks
1529
1542
  */
1530
1543
 
1531
1544
  /**
@@ -1822,7 +1835,7 @@
1822
1835
  });
1823
1836
  }
1824
1837
 
1825
- var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.69.0-1",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",resultingParameterName:"knowledgePieces",dependentParameterNames:["knowledgeContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",promptbookVersion:"0.69.0-1",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",resultingParameterName:"keywords",dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",promptbookVersion:"0.69.0-1",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",resultingParameterName:"title",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",promptbookVersion:"0.69.0-1",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],templates:[{templateType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
1838
+ 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"}];
1826
1839
 
1827
1840
  var defaultDiacriticsRemovalMap = [
1828
1841
  {
@@ -2351,121 +2364,35 @@
2351
2364
  */
2352
2365
 
2353
2366
  /**
2354
- * Parses the given script and returns the list of all used variables that are not defined in the script
2355
- *
2356
- * @param script from which to extract the variables
2357
- * @returns the list of variable names
2358
- * @throws {ParseError} if the script is invalid
2359
- * @public exported from `@promptbook/utils`
2360
- */
2361
- function extractVariables(script) {
2362
- var variables = new Set();
2363
- script = "(()=>{".concat(script, "})()");
2364
- try {
2365
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2366
- try {
2367
- eval(script);
2368
- }
2369
- catch (error) {
2370
- if (!(error instanceof ReferenceError)) {
2371
- throw error;
2372
- }
2373
- var undefinedName = error.message.split(' ')[0];
2374
- /*
2375
- Note: Parsing the error
2376
- [PipelineUrlError: thing is not defined]
2377
- */
2378
- if (!undefinedName) {
2379
- throw error;
2380
- }
2381
- if (script.includes(undefinedName + '(')) {
2382
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2383
- }
2384
- else {
2385
- variables.add(undefinedName);
2386
- script = "const ".concat(undefinedName, " = '';") + script;
2387
- }
2388
- }
2389
- }
2390
- catch (error) {
2391
- if (!(error instanceof Error)) {
2392
- throw error;
2393
- }
2394
- throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2395
- }
2396
- return variables;
2397
- }
2398
- /**
2399
- * TODO: [🔣] Support for multiple languages - python, java,...
2400
- */
2401
-
2402
- /**
2403
- * Parses the template and returns the set of all used parameters
2367
+ * Determine if the pipeline is fully prepared
2404
2368
  *
2405
- * @param template the template with used parameters
2406
- * @returns the set of parameter names
2407
- * @throws {ParseError} if the script is invalid
2408
- * @public exported from `@promptbook/utils`
2369
+ * @public exported from `@promptbook/core`
2409
2370
  */
2410
- function extractParameterNamesFromTemplate(template) {
2411
- var e_1, _a, e_2, _b, e_3, _c;
2412
- var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2413
- var parameterNames = new Set();
2414
- try {
2415
- 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()) {
2416
- var parameterName = _e.value;
2417
- parameterNames.add(parameterName);
2418
- }
2419
- }
2420
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2421
- finally {
2422
- try {
2423
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2424
- }
2425
- finally { if (e_1) throw e_1.error; }
2426
- }
2427
- if (templateType === 'SCRIPT_TEMPLATE') {
2428
- try {
2429
- for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2430
- var parameterName = _g.value;
2431
- parameterNames.add(parameterName);
2432
- }
2433
- }
2434
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2435
- finally {
2436
- try {
2437
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2438
- }
2439
- finally { if (e_2) throw e_2.error; }
2440
- }
2441
- }
2442
- try {
2443
- for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2444
- var jokerName = _j.value;
2445
- parameterNames.add(jokerName);
2446
- }
2447
- }
2448
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2449
- finally {
2450
- try {
2451
- if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2452
- }
2453
- finally { if (e_3) throw e_3.error; }
2371
+ function isPipelinePrepared(pipeline) {
2372
+ // Note: Ignoring `pipeline.preparations` @@@
2373
+ // Note: Ignoring `pipeline.knowledgePieces` @@@
2374
+ if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2375
+ return false;
2454
2376
  }
2455
- parameterNames.delete('content');
2456
- // <- Note {websiteContent} is used in `preparedContent`
2457
- // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2458
- if (foreach !== undefined) {
2459
- if (parameterNames.has(foreach.subparameterName)) {
2460
- parameterNames.delete(foreach.subparameterName);
2461
- parameterNames.add(foreach.parameterName);
2462
- // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2463
- }
2377
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2378
+ return false;
2464
2379
  }
2465
- return parameterNames;
2380
+ /*
2381
+ TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2382
+ > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2383
+ > return false;
2384
+ > }
2385
+ */
2386
+ return true;
2466
2387
  }
2467
2388
  /**
2468
- * TODO: [🔣] If script require contentLanguage
2389
+ * TODO: [🔃][main] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2390
+ * TODO: [🐠] Maybe base this on `makeValidator`
2391
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2392
+ * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2393
+ * - [🏍] ? Is context in each template
2394
+ * - [♨] Are samples prepared
2395
+ * - [♨] Are templates prepared
2469
2396
  */
2470
2397
 
2471
2398
  /**
@@ -2485,27 +2412,6 @@
2485
2412
  };
2486
2413
  }
2487
2414
 
2488
- /**
2489
- * Function isValidJsonString will tell you if the string is valid JSON or not
2490
- *
2491
- * @public exported from `@promptbook/utils`
2492
- */
2493
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
2494
- try {
2495
- JSON.parse(value);
2496
- return true;
2497
- }
2498
- catch (error) {
2499
- if (!(error instanceof Error)) {
2500
- throw error;
2501
- }
2502
- if (error.message.includes('Unexpected token')) {
2503
- return false;
2504
- }
2505
- return false;
2506
- }
2507
- }
2508
-
2509
2415
  /**
2510
2416
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2511
2417
  *
@@ -2532,9 +2438,10 @@
2532
2438
  });
2533
2439
  Object.defineProperty(MultipleLlmExecutionTools.prototype, "description", {
2534
2440
  get: function () {
2535
- return this.llmExecutionTools
2536
- .map(function (tools, index) { return "".concat(index + 1, ") ").concat(tools.title, " ").concat(tools.description || ''); })
2537
- .join('\n');
2441
+ return this.llmExecutionTools.map(function (_a, index) {
2442
+ var title = _a.title;
2443
+ return "".concat(index + 1, ") `").concat(title, "`");
2444
+ }).join('\n');
2538
2445
  },
2539
2446
  enumerable: false,
2540
2447
  configurable: true
@@ -2732,9 +2639,7 @@
2732
2639
  throw new PipelineExecutionError("You have not provided any `LlmExecutionTools`");
2733
2640
  }
2734
2641
  else {
2735
- throw new PipelineExecutionError(spaceTrim__default["default"](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
2736
- .map(function (tools) { return "- ".concat(tools.title, " ").concat(tools.description || ''); })
2737
- .join('\n')), "\n\n "); }));
2642
+ throw new PipelineExecutionError(spaceTrim__default["default"](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 "); }));
2738
2643
  }
2739
2644
  }
2740
2645
  });
@@ -2800,288 +2705,153 @@
2800
2705
  */
2801
2706
 
2802
2707
  /**
2803
- * Extracts all code blocks from markdown.
2708
+ * Takes an item or an array of items and returns an array of items
2804
2709
  *
2805
- * Note: There are multiple simmilar function:
2806
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2807
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2808
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2809
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2710
+ * 1) Any item except array and undefined returns array with that one item (also null)
2711
+ * 2) Undefined returns empty array
2712
+ * 3) Array returns itself
2810
2713
  *
2811
- * @param markdown any valid markdown
2812
- * @returns code blocks with language and content
2813
- * @throws {ParseError} if block is not closed properly
2814
- * @public exported from `@promptbook/markdown-utils`
2714
+ * @private internal utility
2815
2715
  */
2816
- function extractAllBlocksFromMarkdown(markdown) {
2817
- var e_1, _a;
2818
- var codeBlocks = [];
2819
- var lines = markdown.split('\n');
2820
- // Note: [0] Ensure that the last block notated by gt > will be closed
2821
- lines.push('');
2822
- var currentCodeBlock = null;
2716
+ function arrayableToArray(input) {
2717
+ if (input === undefined) {
2718
+ return [];
2719
+ }
2720
+ if (input instanceof Array) {
2721
+ return input;
2722
+ }
2723
+ return [input];
2724
+ }
2725
+
2726
+ /**
2727
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2728
+ *
2729
+ * @param script from which to extract the variables
2730
+ * @returns the list of variable names
2731
+ * @throws {ParseError} if the script is invalid
2732
+ * @public exported from `@promptbook/utils`
2733
+ */
2734
+ function extractVariables(script) {
2735
+ var variables = new Set();
2736
+ script = "(()=>{".concat(script, "})()");
2823
2737
  try {
2824
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2825
- var line = lines_1_1.value;
2826
- if (line.startsWith('> ') || line === '>') {
2827
- if (currentCodeBlock === null) {
2828
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2829
- } /* not else */
2830
- if (currentCodeBlock.blockNotation === '>') {
2831
- if (currentCodeBlock.content !== '') {
2832
- currentCodeBlock.content += '\n';
2833
- }
2834
- currentCodeBlock.content += line.slice(2);
2835
- }
2836
- }
2837
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2838
- codeBlocks.push(currentCodeBlock);
2839
- currentCodeBlock = null;
2738
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2739
+ try {
2740
+ eval(script);
2840
2741
  }
2841
- /* not else */
2842
- if (line.startsWith('```')) {
2843
- var language = line.slice(3).trim() || null;
2844
- if (currentCodeBlock === null) {
2845
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2742
+ catch (error) {
2743
+ if (!(error instanceof ReferenceError)) {
2744
+ throw error;
2846
2745
  }
2847
- else {
2848
- if (language !== null) {
2849
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2850
- }
2851
- codeBlocks.push(currentCodeBlock);
2852
- currentCodeBlock = null;
2746
+ var undefinedName = error.message.split(' ')[0];
2747
+ /*
2748
+ Note: Parsing the error
2749
+ [PipelineUrlError: thing is not defined]
2750
+ */
2751
+ if (!undefinedName) {
2752
+ throw error;
2853
2753
  }
2854
- }
2855
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2856
- if (currentCodeBlock.content !== '') {
2857
- currentCodeBlock.content += '\n';
2754
+ if (script.includes(undefinedName + '(')) {
2755
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2756
+ }
2757
+ else {
2758
+ variables.add(undefinedName);
2759
+ script = "const ".concat(undefinedName, " = '';") + script;
2858
2760
  }
2859
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2860
2761
  }
2861
- }
2862
2762
  }
2863
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2864
- finally {
2865
- try {
2866
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2763
+ catch (error) {
2764
+ if (!(error instanceof Error)) {
2765
+ throw error;
2867
2766
  }
2868
- finally { if (e_1) throw e_1.error; }
2869
- }
2870
- if (currentCodeBlock !== null) {
2871
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2872
- }
2873
- return codeBlocks;
2874
- }
2875
- /**
2876
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2877
- */
2878
-
2879
- /**
2880
- * Extracts extracts exactly one valid JSON code block
2881
- *
2882
- * - When given string is a valid JSON as it is, it just returns it
2883
- * - When there is no JSON code block the function throws a `ParseError`
2884
- * - When there are multiple JSON code blocks the function throws a `ParseError`
2885
- *
2886
- * Note: It is not important if marked as ```json BUT if it is VALID JSON
2887
- * Note: There are multiple simmilar function:
2888
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2889
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2890
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2891
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2892
- *
2893
- * @public exported from `@promptbook/markdown-utils`
2894
- * @throws {ParseError} if there is no valid JSON block in the markdown
2895
- */
2896
- function extractJsonBlock(markdown) {
2897
- if (isValidJsonString(markdown)) {
2898
- return markdown;
2899
- }
2900
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2901
- var jsonBlocks = codeBlocks.filter(function (_a) {
2902
- var content = _a.content;
2903
- return isValidJsonString(content);
2904
- });
2905
- if (jsonBlocks.length === 0) {
2906
- throw new Error('There is no valid JSON block in the markdown');
2907
- }
2908
- if (jsonBlocks.length > 1) {
2909
- throw new Error('There are multiple JSON code blocks in the markdown');
2910
- }
2911
- return jsonBlocks[0].content;
2912
- }
2913
- /**
2914
- * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
2915
- * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2916
- */
2917
-
2918
- /**
2919
- * Determine if the pipeline is fully prepared
2920
- *
2921
- * @public exported from `@promptbook/core`
2922
- */
2923
- function isPipelinePrepared(pipeline) {
2924
- // Note: Ignoring `pipeline.preparations` @@@
2925
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2926
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2927
- return false;
2928
- }
2929
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2930
- return false;
2931
- }
2932
- /*
2933
- TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2934
- > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2935
- > return false;
2936
- > }
2937
- */
2938
- return true;
2939
- }
2940
- /**
2941
- * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2942
- * TODO: [🐠] Maybe base this on `makeValidator`
2943
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2944
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2945
- * - [🏍] ? Is context in each template
2946
- * - [♨] Are samples prepared
2947
- * - [♨] Are templates prepared
2948
- */
2949
-
2950
- /**
2951
- * Takes an item or an array of items and returns an array of items
2952
- *
2953
- * 1) Any item except array and undefined returns array with that one item (also null)
2954
- * 2) Undefined returns empty array
2955
- * 3) Array returns itself
2956
- *
2957
- * @private internal utility
2958
- */
2959
- function arrayableToArray(input) {
2960
- if (input === undefined) {
2961
- return [];
2962
- }
2963
- if (input instanceof Array) {
2964
- return input;
2965
- }
2966
- return [input];
2967
- }
2968
-
2969
- /**
2970
- * Just says that the variable is not used but should be kept
2971
- * No side effects.
2972
- *
2973
- * Note: It can be usefull for:
2974
- *
2975
- * 1) Suppressing eager optimization of unused imports
2976
- * 2) Suppressing eslint errors of unused variables in the tests
2977
- * 3) Keeping the type of the variable for type testing
2978
- *
2979
- * @param value any values
2980
- * @returns void
2981
- * @private within the repository
2982
- */
2983
- function keepUnused() {
2984
- var valuesToKeep = [];
2985
- for (var _i = 0; _i < arguments.length; _i++) {
2986
- valuesToKeep[_i] = arguments[_i];
2767
+ throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2987
2768
  }
2769
+ return variables;
2988
2770
  }
2989
-
2990
2771
  /**
2991
- * Just marks a place of place where should be something implemented
2992
- * No side effects.
2993
- *
2994
- * Note: It can be usefull suppressing eslint errors of unused variables
2995
- *
2996
- * @param value any values
2997
- * @returns void
2998
- * @private within the repository
2772
+ * TODO: [🔣] Support for multiple languages - python, java,...
2999
2773
  */
3000
- function TODO_USE() {
3001
- var value = [];
3002
- for (var _i = 0; _i < arguments.length; _i++) {
3003
- value[_i] = arguments[_i];
3004
- }
3005
- }
3006
2774
 
3007
2775
  /**
3008
- * Replaces parameters in template with values from parameters object
2776
+ * Parses the template and returns the set of all used parameters
3009
2777
  *
3010
- * @param template the template with parameters in {curly} braces
3011
- * @param parameters the object with parameters
3012
- * @returns the template with replaced parameters
3013
- * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
2778
+ * @param template the template with used parameters
2779
+ * @returns the set of parameter names
2780
+ * @throws {ParseError} if the script is invalid
3014
2781
  * @public exported from `@promptbook/utils`
3015
2782
  */
3016
- function replaceParameters(template, parameters) {
3017
- var e_1, _a;
2783
+ function extractParameterNamesFromTemplate(template) {
2784
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
2785
+ var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2786
+ var parameterNames = new Set();
3018
2787
  try {
3019
- for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
3020
- var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
3021
- if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
3022
- throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
3023
- }
3024
- else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
3025
- // TODO: [🍵]
3026
- throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
3027
- }
2788
+ 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()) {
2789
+ var parameterName = _f.value;
2790
+ parameterNames.add(parameterName);
3028
2791
  }
3029
2792
  }
3030
2793
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
3031
2794
  finally {
3032
2795
  try {
3033
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2796
+ if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
3034
2797
  }
3035
2798
  finally { if (e_1) throw e_1.error; }
3036
2799
  }
3037
- var replacedTemplate = template;
3038
- var match;
3039
- var loopLimit = LOOP_LIMIT;
3040
- var _loop_1 = function () {
3041
- if (loopLimit-- < 0) {
3042
- throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
2800
+ if (templateType === 'SCRIPT_TEMPLATE') {
2801
+ try {
2802
+ for (var _g = __values(extractVariables(content)), _h = _g.next(); !_h.done; _h = _g.next()) {
2803
+ var parameterName = _h.value;
2804
+ parameterNames.add(parameterName);
2805
+ }
3043
2806
  }
3044
- var precol = match.groups.precol;
3045
- var parameterName = match.groups.parameterName;
3046
- if (parameterName === '') {
3047
- return "continue";
2807
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2808
+ finally {
2809
+ try {
2810
+ if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
2811
+ }
2812
+ finally { if (e_2) throw e_2.error; }
3048
2813
  }
3049
- if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
3050
- throw new PipelineExecutionError('Parameter is already opened or not closed');
2814
+ }
2815
+ try {
2816
+ for (var _j = __values(jokerParameterNames || []), _k = _j.next(); !_k.done; _k = _j.next()) {
2817
+ var jokerName = _k.value;
2818
+ parameterNames.add(jokerName);
3051
2819
  }
3052
- if (parameters[parameterName] === undefined) {
3053
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2820
+ }
2821
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
2822
+ finally {
2823
+ try {
2824
+ if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
3054
2825
  }
3055
- var parameterValue = parameters[parameterName];
3056
- if (parameterValue === undefined) {
3057
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2826
+ finally { if (e_3) throw e_3.error; }
2827
+ }
2828
+ parameterNames.delete('content');
2829
+ // <- Note {websiteContent} is used in `preparedContent`
2830
+ // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2831
+ if (foreach !== undefined) {
2832
+ try {
2833
+ for (var _l = __values(foreach.inputSubparameterNames), _m = _l.next(); !_m.done; _m = _l.next()) {
2834
+ var subparameterName = _m.value;
2835
+ if (parameterNames.has(subparameterName)) {
2836
+ parameterNames.delete(subparameterName);
2837
+ parameterNames.add(foreach.parameterName);
2838
+ // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2839
+ }
2840
+ }
3058
2841
  }
3059
- parameterValue = parameterValue.toString();
3060
- if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
3061
- parameterValue = parameterValue
3062
- .split('\n')
3063
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
3064
- .join('\n');
2842
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
2843
+ finally {
2844
+ try {
2845
+ if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
2846
+ }
2847
+ finally { if (e_4) throw e_4.error; }
3065
2848
  }
3066
- replacedTemplate =
3067
- replacedTemplate.substring(0, match.index + precol.length) +
3068
- parameterValue +
3069
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
3070
- };
3071
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
3072
- .exec(replacedTemplate))) {
3073
- _loop_1();
3074
- }
3075
- // [💫] Check if there are parameters that are not closed properly
3076
- if (/{\w+$/.test(replacedTemplate)) {
3077
- throw new PipelineExecutionError('Parameter is not closed');
3078
- }
3079
- // [💫] Check if there are parameters that are not opened properly
3080
- if (/^\w+}/.test(replacedTemplate)) {
3081
- throw new PipelineExecutionError('Parameter is not opened');
3082
2849
  }
3083
- return replacedTemplate;
2850
+ return parameterNames;
3084
2851
  }
2852
+ /**
2853
+ * TODO: [🔣] If script require contentLanguage
2854
+ */
3085
2855
 
3086
2856
  /**
3087
2857
  * Create difference set of two sets.
@@ -3159,117 +2929,351 @@
3159
2929
  }
3160
2930
 
3161
2931
  /**
3162
- * Counts number of characters in the text
2932
+ * Just marks a place of place where should be something implemented
2933
+ * No side effects.
3163
2934
  *
3164
- * @public exported from `@promptbook/utils`
2935
+ * Note: It can be usefull suppressing eslint errors of unused variables
2936
+ *
2937
+ * @param value any values
2938
+ * @returns void
2939
+ * @private within the repository
3165
2940
  */
3166
- function countCharacters(text) {
3167
- // Remove null characters
3168
- text = text.replace(/\0/g, '');
3169
- // Replace emojis (and also ZWJ sequence) with hyphens
3170
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3171
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
3172
- text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
3173
- return text.length;
2941
+ function TODO_USE() {
2942
+ var value = [];
2943
+ for (var _i = 0; _i < arguments.length; _i++) {
2944
+ value[_i] = arguments[_i];
2945
+ }
3174
2946
  }
3175
2947
 
3176
2948
  /**
3177
- * Counts number of lines in the text
2949
+ * @@@
3178
2950
  *
3179
- * @public exported from `@promptbook/utils`
2951
+ * @public exported from `@promptbook/core`
3180
2952
  */
3181
- function countLines(text) {
3182
- if (text === '') {
3183
- return 0;
3184
- }
3185
- return text.split('\n').length;
3186
- }
2953
+ var MANDATORY_CSV_SETTINGS = Object.freeze({
2954
+ header: true,
2955
+ // encoding: 'utf8',
2956
+ });
3187
2957
 
3188
2958
  /**
3189
- * Counts number of pages in the text
2959
+ * Definition for CSV spreadsheet
3190
2960
  *
3191
- * @public exported from `@promptbook/utils`
2961
+ * @public exported from `@promptbook/core`
2962
+ * <- TODO: [🏢] Export from package `@promptbook/csv`
2963
+ */
2964
+ var CsvFormatDefinition = {
2965
+ formatName: 'CSV',
2966
+ aliases: ['SPREADSHEET', 'TABLE'],
2967
+ isValid: function (value, settings, schema) {
2968
+ // TODO: !!!!!! Implement CSV validation
2969
+ TODO_USE(value /* <- TODO: Use value here */);
2970
+ TODO_USE(settings /* <- TODO: Use settings here */);
2971
+ TODO_USE(schema /* <- TODO: Use schema here */);
2972
+ return true;
2973
+ },
2974
+ canBeValid: function (partialValue, settings, schema) {
2975
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2976
+ TODO_USE(settings /* <- TODO: Use settings here */);
2977
+ TODO_USE(schema /* <- TODO: Use schema here */);
2978
+ return true;
2979
+ },
2980
+ heal: function (value, settings, schema) {
2981
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2982
+ TODO_USE(settings /* <- TODO: Use settings here */);
2983
+ TODO_USE(schema /* <- TODO: Use schema here */);
2984
+ throw new Error('Not implemented');
2985
+ },
2986
+ subvalueDefinitions: [
2987
+ {
2988
+ subvalueName: 'ROW',
2989
+ mapValues: function (value, outputParameterName, settings, mapCallback) {
2990
+ return __awaiter(this, void 0, void 0, function () {
2991
+ var csv, mappedData;
2992
+ var _this = this;
2993
+ return __generator(this, function (_a) {
2994
+ switch (_a.label) {
2995
+ case 0:
2996
+ csv = papaparse.parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
2997
+ if (csv.errors.length !== 0) {
2998
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2999
+ spaceTrim__default["default"](function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
3000
+ }
3001
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, index) { return __awaiter(_this, void 0, void 0, function () {
3002
+ var _a, _b;
3003
+ var _c;
3004
+ return __generator(this, function (_d) {
3005
+ switch (_d.label) {
3006
+ case 0:
3007
+ if (row[outputParameterName]) {
3008
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
3009
+ "Can not overwrite existing column \"".concat(outputParameterName, "\" in CSV row"));
3010
+ }
3011
+ _a = [__assign({}, row)];
3012
+ _c = {};
3013
+ _b = outputParameterName;
3014
+ return [4 /*yield*/, mapCallback(row, index)];
3015
+ case 1: return [2 /*return*/, __assign.apply(void 0, _a.concat([(_c[_b] = _d.sent(), _c)]))];
3016
+ }
3017
+ });
3018
+ }); }))];
3019
+ case 1:
3020
+ mappedData = _a.sent();
3021
+ return [2 /*return*/, papaparse.unparse(mappedData, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS))];
3022
+ }
3023
+ });
3024
+ });
3025
+ },
3026
+ },
3027
+ {
3028
+ subvalueName: 'CELL',
3029
+ mapValues: function (value, outputParameterName, settings, mapCallback) {
3030
+ return __awaiter(this, void 0, void 0, function () {
3031
+ var csv, mappedData;
3032
+ var _this = this;
3033
+ return __generator(this, function (_a) {
3034
+ switch (_a.label) {
3035
+ case 0:
3036
+ csv = papaparse.parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
3037
+ if (csv.errors.length !== 0) {
3038
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
3039
+ spaceTrim__default["default"](function (block) { return "\n CSV parsing error\n\n ".concat(block(csv.errors.map(function (error) { return error.message; }).join('\n\n')), "\n "); }));
3040
+ }
3041
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, rowIndex) { return __awaiter(_this, void 0, void 0, function () {
3042
+ var _this = this;
3043
+ return __generator(this, function (_a) {
3044
+ return [2 /*return*/, /* not await */ Promise.all(Object.entries(row).map(function (_a, columnIndex) {
3045
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
3046
+ return __awaiter(_this, void 0, void 0, function () {
3047
+ var index;
3048
+ var _c;
3049
+ return __generator(this, function (_d) {
3050
+ index = rowIndex * Object.keys(row).length + columnIndex;
3051
+ return [2 /*return*/, /* not await */ mapCallback((_c = {}, _c[key] = value, _c), index)];
3052
+ });
3053
+ });
3054
+ }))];
3055
+ });
3056
+ }); }))];
3057
+ case 1:
3058
+ mappedData = _a.sent();
3059
+ return [2 /*return*/, papaparse.unparse(mappedData, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS))];
3060
+ }
3061
+ });
3062
+ });
3063
+ },
3064
+ },
3065
+ ],
3066
+ };
3067
+ /**
3068
+ * TODO: [🍓] In `CsvFormatDefinition` implement simple `isValid`
3069
+ * TODO: [🍓] In `CsvFormatDefinition` implement partial `canBeValid`
3070
+ * TODO: [🍓] In `CsvFormatDefinition` implement `heal
3071
+ * TODO: [🍓] In `CsvFormatDefinition` implement `subvalueDefinitions`
3072
+ * TODO: [🏢] Allow to expect something inside CSV objects and other formats
3192
3073
  */
3193
- function countPages(text) {
3194
- var sentencesPerPage = 5; // Assuming each page has 5 sentences
3195
- var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3196
- var pageCount = Math.ceil(sentences.length / sentencesPerPage);
3197
- return pageCount;
3198
- }
3199
3074
 
3200
3075
  /**
3201
- * Counts number of paragraphs in the text
3076
+ * Function isValidJsonString will tell you if the string is valid JSON or not
3202
3077
  *
3203
3078
  * @public exported from `@promptbook/utils`
3204
3079
  */
3205
- function countParagraphs(text) {
3206
- return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
3080
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
3081
+ try {
3082
+ JSON.parse(value);
3083
+ return true;
3084
+ }
3085
+ catch (error) {
3086
+ if (!(error instanceof Error)) {
3087
+ throw error;
3088
+ }
3089
+ if (error.message.includes('Unexpected token')) {
3090
+ return false;
3091
+ }
3092
+ return false;
3093
+ }
3207
3094
  }
3208
3095
 
3209
3096
  /**
3210
- * Split text into sentences
3097
+ * Definition for JSON format
3211
3098
  *
3212
- * @public exported from `@promptbook/utils`
3099
+ * @private still in development [🏢]
3213
3100
  */
3214
- function splitIntoSentences(text) {
3215
- return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3216
- }
3101
+ var JsonFormatDefinition = {
3102
+ formatName: 'JSON',
3103
+ mimeType: 'application/json',
3104
+ isValid: function (value, settings, schema) {
3105
+ TODO_USE(schema /* <- TODO: Use schema here */);
3106
+ TODO_USE(settings /* <- TODO: Use settings here */);
3107
+ return isValidJsonString(value);
3108
+ },
3109
+ canBeValid: function (partialValue, settings, schema) {
3110
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
3111
+ TODO_USE(settings /* <- TODO: Use settings here */);
3112
+ TODO_USE(schema /* <- TODO: Use schema here */);
3113
+ return true;
3114
+ },
3115
+ heal: function (value, settings, schema) {
3116
+ TODO_USE(value /* <- TODO: Use partialValue here */);
3117
+ TODO_USE(settings /* <- TODO: Use settings here */);
3118
+ TODO_USE(schema /* <- TODO: Use schema here */);
3119
+ throw new Error('Not implemented');
3120
+ },
3121
+ subvalueDefinitions: [],
3122
+ };
3217
3123
  /**
3218
- * Counts number of sentences in the text
3219
- *
3220
- * @public exported from `@promptbook/utils`
3124
+ * TODO: [🧠] Maybe propper instance of object
3125
+ * TODO: [0] Make string_serialized_json
3126
+ * TODO: [1] Make type for JSON Settings and Schema
3127
+ * TODO: [🧠] What to use for validating JSONs - JSON Schema, ZoD, typescript types/interfaces,...?
3128
+ * TODO: [🍓] In `JsonFormatDefinition` implement simple `isValid`
3129
+ * TODO: [🍓] In `JsonFormatDefinition` implement partial `canBeValid`
3130
+ * TODO: [🍓] In `JsonFormatDefinition` implement `heal
3131
+ * TODO: [🍓] In `JsonFormatDefinition` implement `subvalueDefinitions`
3132
+ * TODO: [🏢] Allow to expect something inside JSON objects and other formats
3221
3133
  */
3222
- function countSentences(text) {
3223
- return splitIntoSentences(text).length;
3224
- }
3225
3134
 
3226
3135
  /**
3227
- * Counts number of words in the text
3136
+ * Definition for any text - this will be always valid
3228
3137
  *
3229
- * @public exported from `@promptbook/utils`
3138
+ * Note: This is not useful for validation, but for splitting and mapping with `subvalueDefinitions`
3139
+ *
3140
+ * @public exported from `@promptbook/core`
3141
+ */
3142
+ var TextFormatDefinition = {
3143
+ formatName: 'TEXT',
3144
+ isValid: function (value) {
3145
+ return typeof value === 'string';
3146
+ },
3147
+ canBeValid: function (partialValue) {
3148
+ return typeof partialValue === 'string';
3149
+ },
3150
+ heal: function () {
3151
+ throw new UnexpectedError('It does not make sense to call `TextFormatDefinition.heal`');
3152
+ },
3153
+ subvalueDefinitions: [
3154
+ {
3155
+ subvalueName: 'LINE',
3156
+ mapValues: function (value, outputParameterName, settings, mapCallback) {
3157
+ return __awaiter(this, void 0, void 0, function () {
3158
+ var lines, mappedLines;
3159
+ return __generator(this, function (_a) {
3160
+ switch (_a.label) {
3161
+ case 0:
3162
+ lines = value.split('\n');
3163
+ return [4 /*yield*/, Promise.all(lines.map(function (lineContent, lineNumber) {
3164
+ // TODO: [🧠] Maybe option to skip empty line
3165
+ /* not await */ return mapCallback({
3166
+ lineContent: lineContent,
3167
+ // TODO: [🧠] Maybe also put here `lineNumber`
3168
+ }, lineNumber);
3169
+ }))];
3170
+ case 1:
3171
+ mappedLines = _a.sent();
3172
+ return [2 /*return*/, mappedLines.join('\n')];
3173
+ }
3174
+ });
3175
+ });
3176
+ },
3177
+ },
3178
+ // <- TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3179
+ ],
3180
+ };
3181
+ /**
3182
+ * TODO: [1] Make type for XML Text and Schema
3183
+ * TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3184
+ * TODO: [🍓] In `TextFormatDefinition` implement simple `isValid`
3185
+ * TODO: [🍓] In `TextFormatDefinition` implement partial `canBeValid`
3186
+ * TODO: [🍓] In `TextFormatDefinition` implement `heal
3187
+ * TODO: [🍓] In `TextFormatDefinition` implement `subvalueDefinitions`
3188
+ * TODO: [🏢] Allow to expect something inside each item of list and other formats
3230
3189
  */
3231
- function countWords(text) {
3232
- text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3233
- text = removeDiacritics(text);
3234
- return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3235
- }
3236
3190
 
3237
3191
  /**
3238
- * Index of all counter functions
3192
+ * Definition for XML format
3239
3193
  *
3240
- * @public exported from `@promptbook/utils`
3194
+ * @private still in development [🏢]
3241
3195
  */
3242
- var CountUtils = {
3243
- CHARACTERS: countCharacters,
3244
- WORDS: countWords,
3245
- SENTENCES: countSentences,
3246
- PARAGRAPHS: countParagraphs,
3247
- LINES: countLines,
3248
- PAGES: countPages,
3196
+ var XmlFormatDefinition = {
3197
+ formatName: 'XML',
3198
+ mimeType: 'application/xml',
3199
+ isValid: function (value, settings, schema) {
3200
+ TODO_USE(value /* <- TODO: Use value here */);
3201
+ TODO_USE(settings /* <- TODO: Use settings here */);
3202
+ TODO_USE(schema /* <- TODO: Use schema here */);
3203
+ return true;
3204
+ },
3205
+ canBeValid: function (partialValue, settings, schema) {
3206
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
3207
+ TODO_USE(settings /* <- TODO: Use settings here */);
3208
+ TODO_USE(schema /* <- TODO: Use schema here */);
3209
+ return true;
3210
+ },
3211
+ heal: function (value, settings, schema) {
3212
+ TODO_USE(value /* <- TODO: Use partialValue here */);
3213
+ TODO_USE(settings /* <- TODO: Use settings here */);
3214
+ TODO_USE(schema /* <- TODO: Use schema here */);
3215
+ throw new Error('Not implemented');
3216
+ },
3217
+ subvalueDefinitions: [],
3249
3218
  };
3219
+ /**
3220
+ * TODO: [🧠] Maybe propper instance of object
3221
+ * TODO: [0] Make string_serialized_xml
3222
+ * TODO: [1] Make type for XML Settings and Schema
3223
+ * TODO: [🧠] What to use for validating XMLs - XSD,...
3224
+ * TODO: [🍓] In `XmlFormatDefinition` implement simple `isValid`
3225
+ * TODO: [🍓] In `XmlFormatDefinition` implement partial `canBeValid`
3226
+ * TODO: [🍓] In `XmlFormatDefinition` implement `heal
3227
+ * TODO: [🍓] In `XmlFormatDefinition` implement `subvalueDefinitions`
3228
+ * TODO: [🏢] Allow to expect something inside XML and other formats
3229
+ */
3250
3230
 
3251
3231
  /**
3252
- * Function checkExpectations will check if the expectations on given value are met
3232
+ * Definitions for all formats supported by Promptbook
3253
3233
  *
3254
- * Note: There are two simmilar functions:
3255
- * - `checkExpectations` which throws an error if the expectations are not met
3256
- * - `isPassingExpectations` which returns a boolean
3234
+ * @private internal index of `...` <- TODO [🏢]
3235
+ */
3236
+ var FORMAT_DEFINITIONS = [
3237
+ JsonFormatDefinition,
3238
+ XmlFormatDefinition,
3239
+ TextFormatDefinition,
3240
+ CsvFormatDefinition,
3241
+ ];
3242
+
3243
+ /**
3244
+ * Maps available parameters to expected parameters
3257
3245
  *
3258
- * @throws {ExpectError} if the expectations are not met
3259
- * @returns {void} Nothing
3260
- * @private internal function of `createPipelineExecutor`
3246
+ * The strategy is:
3247
+ * 1) @@@
3248
+ * 2) @@@
3249
+ *
3250
+ * @throws {PipelineExecutionError} @@@
3251
+ * @private within the repository used in `createPipelineExecutor`
3261
3252
  */
3262
- function checkExpectations(expectations, value) {
3253
+ function mapAvailableToExpectedParameters(options) {
3263
3254
  var e_1, _a;
3255
+ var expectedParameters = options.expectedParameters, availableParameters = options.availableParameters;
3256
+ var availableParametersNames = new Set(Object.keys(availableParameters));
3257
+ var expectedParameterNames = new Set(Object.keys(expectedParameters));
3258
+ var mappedParameters = {};
3264
3259
  try {
3265
- for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3266
- var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3267
- var amount = CountUtils[unit.toUpperCase()](value);
3268
- if (min && amount < min) {
3269
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3270
- } /* not else */
3271
- if (max && amount > max) {
3272
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3260
+ // Phase 1️⃣: Matching mapping
3261
+ for (var _b = __values(Array.from(union(availableParametersNames, expectedParameterNames))), _c = _b.next(); !_c.done; _c = _b.next()) {
3262
+ var parameterName = _c.value;
3263
+ // Situation: Parameter is available and expected
3264
+ if (availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3265
+ mappedParameters[parameterName] = availableParameters[parameterName];
3266
+ // <- Note: [👩‍👩‍👧] Maybe detect parameter collision here?
3267
+ availableParametersNames.delete(parameterName);
3268
+ expectedParameterNames.delete(parameterName);
3269
+ }
3270
+ // Situation: Parameter is available but NOT expected
3271
+ else if (availableParametersNames.has(parameterName) && !expectedParameterNames.has(parameterName)) {
3272
+ // [🐱‍👤] Do not pass this parameter to prompt - Maybe use it non-matching mapping
3273
+ }
3274
+ // Situation: Parameter is NOT available BUT expected
3275
+ else if (!availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3276
+ // Do nothing here - this will be maybe fixed in the non-matching mapping
3273
3277
  }
3274
3278
  }
3275
3279
  }
@@ -3280,636 +3284,1139 @@
3280
3284
  }
3281
3285
  finally { if (e_1) throw e_1.error; }
3282
3286
  }
3287
+ if (expectedParameterNames.size === 0) {
3288
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3289
+ Object.freeze(mappedParameters);
3290
+ return mappedParameters;
3291
+ }
3292
+ // Phase 2️⃣: Non-matching mapping
3293
+ if (expectedParameterNames.size !== availableParametersNames.size) {
3294
+ throw new PipelineExecutionError(spaceTrim__default["default"](function (block) { return "\n Can not map available parameters to expected parameters\n\n Mapped parameters:\n ".concat(block(Object.keys(mappedParameters)
3295
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3296
+ .join('\n')), "\n\n Expected parameters which can not be mapped:\n ").concat(block(Array.from(expectedParameterNames)
3297
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3298
+ .join('\n')), "\n\n Remaining available parameters:\n ").concat(block(Array.from(availableParametersNames)
3299
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3300
+ .join('\n')), "\n\n "); }));
3301
+ }
3302
+ var expectedParameterNamesArray = Array.from(expectedParameterNames);
3303
+ var availableParametersNamesArray = Array.from(availableParametersNames);
3304
+ for (var i = 0; i < expectedParameterNames.size; i++) {
3305
+ mappedParameters[expectedParameterNamesArray[i]] = availableParameters[availableParametersNamesArray[i]];
3306
+ }
3307
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3308
+ Object.freeze(mappedParameters);
3309
+ return mappedParameters;
3283
3310
  }
3311
+
3284
3312
  /**
3285
- * Function checkExpectations will check if the expectations on given value are met
3313
+ * Extracts all code blocks from markdown.
3286
3314
  *
3287
- * Note: There are two simmilar functions:
3288
- * - `checkExpectations` which throws an error if the expectations are not met
3289
- * - `isPassingExpectations` which returns a boolean
3315
+ * Note: There are multiple simmilar function:
3316
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3317
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3318
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3319
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3290
3320
  *
3291
- * @returns {boolean} True if the expectations are met
3292
- * @public exported from `@promptbook/core`
3321
+ * @param markdown any valid markdown
3322
+ * @returns code blocks with language and content
3323
+ * @throws {ParseError} if block is not closed properly
3324
+ * @public exported from `@promptbook/markdown-utils`
3293
3325
  */
3294
- function isPassingExpectations(expectations, value) {
3326
+ function extractAllBlocksFromMarkdown(markdown) {
3327
+ var e_1, _a;
3328
+ var codeBlocks = [];
3329
+ var lines = markdown.split('\n');
3330
+ // Note: [0] Ensure that the last block notated by gt > will be closed
3331
+ lines.push('');
3332
+ var currentCodeBlock = null;
3295
3333
  try {
3296
- checkExpectations(expectations, value);
3297
- return true;
3334
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
3335
+ var line = lines_1_1.value;
3336
+ if (line.startsWith('> ') || line === '>') {
3337
+ if (currentCodeBlock === null) {
3338
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
3339
+ } /* not else */
3340
+ if (currentCodeBlock.blockNotation === '>') {
3341
+ if (currentCodeBlock.content !== '') {
3342
+ currentCodeBlock.content += '\n';
3343
+ }
3344
+ currentCodeBlock.content += line.slice(2);
3345
+ }
3346
+ }
3347
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
3348
+ codeBlocks.push(currentCodeBlock);
3349
+ currentCodeBlock = null;
3350
+ }
3351
+ /* not else */
3352
+ if (line.startsWith('```')) {
3353
+ var language = line.slice(3).trim() || null;
3354
+ if (currentCodeBlock === null) {
3355
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
3356
+ }
3357
+ else {
3358
+ if (language !== null) {
3359
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
3360
+ }
3361
+ codeBlocks.push(currentCodeBlock);
3362
+ currentCodeBlock = null;
3363
+ }
3364
+ }
3365
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
3366
+ if (currentCodeBlock.content !== '') {
3367
+ currentCodeBlock.content += '\n';
3368
+ }
3369
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
3370
+ }
3371
+ }
3298
3372
  }
3299
- catch (error) {
3300
- if (!(error instanceof ExpectError)) {
3301
- throw error;
3373
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3374
+ finally {
3375
+ try {
3376
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
3302
3377
  }
3303
- return false;
3378
+ finally { if (e_1) throw e_1.error; }
3379
+ }
3380
+ if (currentCodeBlock !== null) {
3381
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
3304
3382
  }
3383
+ return codeBlocks;
3305
3384
  }
3306
3385
  /**
3307
- * TODO: [💝] Unite object for expecting amount and format
3386
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
3308
3387
  */
3309
3388
 
3310
3389
  /**
3311
- * Creates executor function from pipeline and execution tools.
3390
+ * Extracts extracts exactly one valid JSON code block
3312
3391
  *
3313
- * @returns The executor function
3314
- * @throws {PipelineLogicError} on logical error in the pipeline
3315
- * @public exported from `@promptbook/core`
3392
+ * - When given string is a valid JSON as it is, it just returns it
3393
+ * - When there is no JSON code block the function throws a `ParseError`
3394
+ * - When there are multiple JSON code blocks the function throws a `ParseError`
3395
+ *
3396
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
3397
+ * Note: There are multiple simmilar function:
3398
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3399
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3400
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3401
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3402
+ *
3403
+ * @public exported from `@promptbook/markdown-utils`
3404
+ * @throws {ParseError} if there is no valid JSON block in the markdown
3316
3405
  */
3317
- function createPipelineExecutor(options) {
3318
- var _this = this;
3319
- var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
3320
- 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;
3321
- validatePipeline(pipeline);
3322
- var pipelineIdentification = (function () {
3323
- // Note: This is a 😐 implementation of [🚞]
3324
- var _ = [];
3325
- if (pipeline.sourceFile !== undefined) {
3326
- _.push("File: ".concat(pipeline.sourceFile));
3327
- }
3328
- if (pipeline.pipelineUrl !== undefined) {
3329
- _.push("Url: ".concat(pipeline.pipelineUrl));
3330
- }
3331
- return _.join('\n');
3332
- })();
3333
- var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3334
- var preparedPipeline;
3335
- if (isPipelinePrepared(pipeline)) {
3336
- preparedPipeline = pipeline;
3406
+ function extractJsonBlock(markdown) {
3407
+ if (isValidJsonString(markdown)) {
3408
+ return markdown;
3337
3409
  }
3338
- else if (isNotPreparedWarningSupressed !== true) {
3339
- console.warn(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
3410
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
3411
+ var jsonBlocks = codeBlocks.filter(function (_a) {
3412
+ var content = _a.content;
3413
+ return isValidJsonString(content);
3414
+ });
3415
+ if (jsonBlocks.length === 0) {
3416
+ throw new Error('There is no valid JSON block in the markdown');
3340
3417
  }
3341
- var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
3342
- // TODO: !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
3343
- function getContextForTemplate(template) {
3344
- return __awaiter(this, void 0, void 0, function () {
3345
- return __generator(this, function (_a) {
3346
- TODO_USE(template);
3347
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3348
- });
3349
- });
3418
+ if (jsonBlocks.length > 1) {
3419
+ throw new Error('There are multiple JSON code blocks in the markdown');
3420
+ }
3421
+ return jsonBlocks[0].content;
3422
+ }
3423
+ /**
3424
+ * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
3425
+ * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
3426
+ */
3427
+
3428
+ /**
3429
+ * Just says that the variable is not used but should be kept
3430
+ * No side effects.
3431
+ *
3432
+ * Note: It can be usefull for:
3433
+ *
3434
+ * 1) Suppressing eager optimization of unused imports
3435
+ * 2) Suppressing eslint errors of unused variables in the tests
3436
+ * 3) Keeping the type of the variable for type testing
3437
+ *
3438
+ * @param value any values
3439
+ * @returns void
3440
+ * @private within the repository
3441
+ */
3442
+ function keepUnused() {
3443
+ var valuesToKeep = [];
3444
+ for (var _i = 0; _i < arguments.length; _i++) {
3445
+ valuesToKeep[_i] = arguments[_i];
3446
+ }
3447
+ }
3448
+
3449
+ /**
3450
+ * Replaces parameters in template with values from parameters object
3451
+ *
3452
+ * @param template the template with parameters in {curly} braces
3453
+ * @param parameters the object with parameters
3454
+ * @returns the template with replaced parameters
3455
+ * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
3456
+ * @public exported from `@promptbook/utils`
3457
+ */
3458
+ function replaceParameters(template, parameters) {
3459
+ var e_1, _a;
3460
+ try {
3461
+ for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
3462
+ var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
3463
+ if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
3464
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
3465
+ }
3466
+ else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
3467
+ // TODO: [🍵]
3468
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
3469
+ }
3350
3470
  }
3351
- function getKnowledgeForTemplate(template) {
3352
- return __awaiter(this, void 0, void 0, function () {
3353
- return __generator(this, function (_a) {
3354
- // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3355
- TODO_USE(template);
3356
- return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3357
- var content = _a.content;
3358
- return "- ".concat(content);
3359
- }).join('\n')];
3360
- });
3361
- });
3471
+ }
3472
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3473
+ finally {
3474
+ try {
3475
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3362
3476
  }
3363
- function getSamplesForTemplate(template) {
3364
- return __awaiter(this, void 0, void 0, function () {
3365
- return __generator(this, function (_a) {
3366
- // TODO: [♨] Implement Better - use real index and keyword search
3367
- TODO_USE(template);
3368
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3369
- });
3370
- });
3477
+ finally { if (e_1) throw e_1.error; }
3478
+ }
3479
+ var replacedTemplate = template;
3480
+ var match;
3481
+ var loopLimit = LOOP_LIMIT;
3482
+ var _loop_1 = function () {
3483
+ if (loopLimit-- < 0) {
3484
+ throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
3371
3485
  }
3372
- function getReservedParametersForTemplate(template) {
3373
- return __awaiter(this, void 0, void 0, function () {
3374
- var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3375
- var e_3, _a;
3376
- return __generator(this, function (_b) {
3377
- switch (_b.label) {
3378
- case 0: return [4 /*yield*/, getContextForTemplate(template)];
3379
- case 1:
3380
- context = _b.sent();
3381
- return [4 /*yield*/, getKnowledgeForTemplate(template)];
3382
- case 2:
3383
- knowledge = _b.sent();
3384
- return [4 /*yield*/, getSamplesForTemplate(template)];
3385
- case 3:
3386
- samples = _b.sent();
3387
- currentDate = new Date().toISOString();
3388
- modelName = RESERVED_PARAMETER_MISSING_VALUE;
3389
- reservedParameters = {
3390
- content: RESERVED_PARAMETER_RESTRICTED,
3391
- context: context,
3392
- knowledge: knowledge,
3393
- samples: samples,
3394
- currentDate: currentDate,
3395
- modelName: modelName,
3396
- };
3397
- _loop_3 = function (parameterName) {
3398
- if (reservedParameters[parameterName] === undefined) {
3399
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3400
- }
3401
- };
3402
- try {
3403
- // Note: Doublecheck that ALL reserved parameters are defined:
3404
- 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()) {
3405
- parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3406
- _loop_3(parameterName);
3407
- }
3408
- }
3409
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
3410
- finally {
3411
- try {
3412
- if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3413
- }
3414
- finally { if (e_3) throw e_3.error; }
3415
- }
3416
- return [2 /*return*/, reservedParameters];
3417
- }
3418
- });
3419
- });
3486
+ var precol = match.groups.precol;
3487
+ var parameterName = match.groups.parameterName;
3488
+ if (parameterName === '') {
3489
+ return "continue";
3420
3490
  }
3421
- function executeSingleTemplate(currentTemplate) {
3422
- return __awaiter(this, void 0, void 0, function () {
3423
- 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;
3424
- var e_4, _f, _g;
3425
- return __generator(this, function (_h) {
3426
- switch (_h.label) {
3427
- case 0:
3428
- name = "pipeline-executor-frame-".concat(currentTemplate.name);
3429
- title = currentTemplate.title;
3430
- priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3431
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
3432
- progress_1 = {
3433
- name: name,
3434
- title: title,
3435
- isStarted: false,
3436
- isDone: false,
3437
- templateType: currentTemplate.templateType,
3438
- parameterName: currentTemplate.resultingParameterName,
3439
- parameterValue: null,
3440
- // <- [3]
3441
- };
3442
- if (isReturned) {
3443
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4F\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_1, null, 4)
3444
- .split('\n')
3445
- .map(function (line) { return "> ".concat(line); })
3446
- .join('\n')), "\n "); }));
3447
- }
3448
- return [4 /*yield*/, onProgress(progress_1)];
3449
- case 1:
3450
- _h.sent();
3451
- _h.label = 2;
3452
- case 2:
3453
- usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3454
- dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3455
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3456
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Dependent parameters:\n ").concat(Array.from(dependentParameterNames)
3457
- .map(function (name) { return "{".concat(name, "}"); })
3458
- .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3459
- .map(function (name) { return "{".concat(name, "}"); })
3460
- .join(', '), "\n\n "); }));
3461
- }
3462
- _b = (_a = Object).freeze;
3463
- _c = [{}];
3464
- return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
3465
- case 3:
3466
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3467
- definedParameterNames = new Set(Object.keys(definedParameters));
3468
- parameters = {};
3469
- _loop_4 = function (parameterName) {
3470
- // Situation: Parameter is defined and used
3471
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3472
- parameters[parameterName] = definedParameters[parameterName];
3473
- }
3474
- // Situation: Parameter is defined but NOT used
3475
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3476
- // Situation: Parameter is NOT defined BUT used
3477
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3478
- // Houston, we have a problem
3479
- // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3480
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is NOT defined\n BUT used in template \"").concat(currentTemplate.title || currentTemplate.name, "\"\n\n This should be catched in `validatePipeline`\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3481
- }
3482
- };
3483
- try {
3484
- // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3485
- for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3486
- parameterName = _e.value;
3487
- _loop_4(parameterName);
3488
- }
3489
- }
3490
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
3491
- finally {
3492
- try {
3493
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3494
- }
3495
- finally { if (e_4) throw e_4.error; }
3496
- }
3497
- // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3498
- Object.freeze(parameters);
3499
- result = null;
3500
- resultString = null;
3501
- expectError = null;
3502
- maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3503
- jokerParameterNames = currentTemplate.jokerParameterNames || [];
3504
- preparedContent = (currentTemplate.preparedContent || '{content}')
3505
- .split('{content}')
3506
- .join(currentTemplate.content);
3507
- _loop_5 = function (attempt) {
3508
- 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;
3509
- var e_5, _s, e_7, _t, e_6, _u;
3510
- return __generator(this, function (_v) {
3511
- switch (_v.label) {
3512
- case 0:
3513
- isJokerAttempt = attempt < 0;
3514
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3515
- // TODO: [🧠] !!!!!! JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3516
- if (isJokerAttempt && !jokerParameterName) {
3517
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3518
- }
3519
- result = null;
3520
- resultString = null;
3521
- expectError = null;
3522
- if (isJokerAttempt) {
3523
- if (parameters[jokerParameterName] === undefined) {
3524
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3525
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3526
- }
3527
- else {
3528
- resultString = parameters[jokerParameterName];
3529
- }
3530
- }
3531
- _v.label = 1;
3532
- case 1:
3533
- _v.trys.push([1, 44, 45, 46]);
3534
- if (!!isJokerAttempt) return [3 /*break*/, 26];
3535
- _j = currentTemplate.templateType;
3536
- switch (_j) {
3537
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3538
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3539
- case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3540
- case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3541
- }
3542
- return [3 /*break*/, 25];
3543
- case 2:
3544
- resultString = replaceParameters(preparedContent, parameters);
3545
- return [3 /*break*/, 26];
3546
- case 3:
3547
- modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (pipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3548
- prompt = {
3549
- title: currentTemplate.title,
3550
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3551
- ? preparedPipeline.pipelineUrl
3552
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3553
- parameters: parameters,
3554
- content: preparedContent,
3555
- modelRequirements: modelRequirements,
3556
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3557
- var name = _a.name;
3558
- return name === currentTemplate.personaName;
3559
- }) || {})), currentTemplate.expectations),
3560
- format: currentTemplate.format,
3561
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3562
- }; // <- TODO: Not very good type guard
3563
- _k = modelRequirements.modelVariant;
3564
- switch (_k) {
3565
- case 'CHAT': return [3 /*break*/, 4];
3566
- case 'COMPLETION': return [3 /*break*/, 6];
3567
- case 'EMBEDDING': return [3 /*break*/, 8];
3568
- }
3569
- return [3 /*break*/, 10];
3570
- case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3571
- case 5:
3572
- chatResult = _v.sent();
3573
- // TODO: [🍬] Destroy chatThread
3574
- result = chatResult;
3575
- resultString = chatResult.content;
3576
- return [3 /*break*/, 11];
3577
- case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3578
- case 7:
3579
- completionResult = _v.sent();
3580
- result = completionResult;
3581
- resultString = completionResult.content;
3582
- return [3 /*break*/, 11];
3583
- case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3584
- case 9:
3585
- embeddingResult = _v.sent();
3586
- result = embeddingResult;
3587
- resultString = embeddingResult.content.join(',');
3588
- return [3 /*break*/, 11];
3589
- case 10: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements
3590
- .modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3591
- case 11: return [3 /*break*/, 26];
3592
- case 12:
3593
- if (arrayableToArray(tools.script).length === 0) {
3594
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3595
- }
3596
- if (!currentTemplate.contentLanguage) {
3597
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(currentTemplate.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3598
- }
3599
- // TODO: DRY [1]
3600
- scriptPipelineExecutionErrors = [];
3601
- _v.label = 13;
3602
- case 13:
3603
- _v.trys.push([13, 20, 21, 22]);
3604
- _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3605
- _v.label = 14;
3606
- case 14:
3607
- if (!!_m.done) return [3 /*break*/, 19];
3608
- scriptTools = _m.value;
3609
- _v.label = 15;
3610
- case 15:
3611
- _v.trys.push([15, 17, , 18]);
3612
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3613
- scriptLanguage: currentTemplate.contentLanguage,
3614
- script: preparedContent,
3615
- parameters: parameters,
3616
- }))];
3617
- case 16:
3618
- resultString = _v.sent();
3619
- return [3 /*break*/, 19];
3620
- case 17:
3621
- error_2 = _v.sent();
3622
- if (!(error_2 instanceof Error)) {
3623
- throw error_2;
3624
- }
3625
- if (error_2 instanceof UnexpectedError) {
3626
- throw error_2;
3627
- }
3628
- scriptPipelineExecutionErrors.push(error_2);
3629
- return [3 /*break*/, 18];
3630
- case 18:
3631
- _m = _l.next();
3632
- return [3 /*break*/, 14];
3633
- case 19: return [3 /*break*/, 22];
3634
- case 20:
3635
- e_5_1 = _v.sent();
3636
- e_5 = { error: e_5_1 };
3637
- return [3 /*break*/, 22];
3638
- case 21:
3639
- try {
3640
- if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3641
- }
3642
- finally { if (e_5) throw e_5.error; }
3643
- return [7 /*endfinally*/];
3644
- case 22:
3645
- if (resultString !== null) {
3646
- return [3 /*break*/, 26];
3647
- }
3648
- if (scriptPipelineExecutionErrors.length === 1) {
3649
- throw scriptPipelineExecutionErrors[0];
3650
- }
3651
- else {
3652
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptPipelineExecutionErrors.length, " times\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block(scriptPipelineExecutionErrors
3653
- .map(function (error) { return '- ' + error.message; })
3654
- .join('\n\n')), "\n "); }));
3655
- }
3656
- case 23:
3657
- if (tools.userInterface === undefined) {
3658
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3659
- }
3660
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3661
- promptTitle: currentTemplate.title,
3662
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3663
- defaultValue: replaceParameters(preparedContent, parameters),
3664
- // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3665
- placeholder: undefined,
3666
- priority: priority,
3667
- }))];
3668
- case 24:
3669
- // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3670
- resultString = _v.sent();
3671
- return [3 /*break*/, 26];
3672
- case 25: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3673
- case 26:
3674
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3675
- _v.label = 27;
3676
- case 27:
3677
- _v.trys.push([27, 41, 42, 43]);
3678
- _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3679
- _v.label = 28;
3680
- case 28:
3681
- if (!!_p.done) return [3 /*break*/, 40];
3682
- functionName = _p.value;
3683
- // TODO: DRY [1]
3684
- scriptPipelineExecutionErrors = [];
3685
- postprocessingError = null;
3686
- _v.label = 29;
3687
- case 29:
3688
- _v.trys.push([29, 36, 37, 38]);
3689
- _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3690
- _v.label = 30;
3691
- case 30:
3692
- if (!!_r.done) return [3 /*break*/, 35];
3693
- scriptTools = _r.value;
3694
- _v.label = 31;
3695
- case 31:
3696
- _v.trys.push([31, 33, , 34]);
3697
- return [4 /*yield*/, scriptTools.execute({
3698
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3699
- script: "".concat(functionName, "(resultString)"),
3700
- parameters: {
3701
- resultString: resultString || '',
3702
- // Note: No ...parametersForTemplate, because working with result only
3703
- },
3704
- })];
3705
- case 32:
3706
- resultString = _v.sent();
3707
- postprocessingError = null;
3708
- return [3 /*break*/, 35];
3709
- case 33:
3710
- error_3 = _v.sent();
3711
- if (!(error_3 instanceof Error)) {
3712
- throw error_3;
3713
- }
3714
- if (error_3 instanceof UnexpectedError) {
3715
- throw error_3;
3716
- }
3717
- postprocessingError = error_3;
3718
- scriptPipelineExecutionErrors.push(error_3);
3719
- return [3 /*break*/, 34];
3720
- case 34:
3721
- _r = _q.next();
3722
- return [3 /*break*/, 30];
3723
- case 35: return [3 /*break*/, 38];
3724
- case 36:
3725
- e_6_1 = _v.sent();
3726
- e_6 = { error: e_6_1 };
3727
- return [3 /*break*/, 38];
3728
- case 37:
3729
- try {
3730
- if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3731
- }
3732
- finally { if (e_6) throw e_6.error; }
3733
- return [7 /*endfinally*/];
3734
- case 38:
3735
- if (postprocessingError) {
3736
- throw postprocessingError;
3737
- }
3738
- _v.label = 39;
3739
- case 39:
3740
- _p = _o.next();
3741
- return [3 /*break*/, 28];
3742
- case 40: return [3 /*break*/, 43];
3743
- case 41:
3744
- e_7_1 = _v.sent();
3745
- e_7 = { error: e_7_1 };
3746
- return [3 /*break*/, 43];
3747
- case 42:
3748
- try {
3749
- if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3750
- }
3751
- finally { if (e_7) throw e_7.error; }
3752
- return [7 /*endfinally*/];
3753
- case 43:
3754
- // TODO: [💝] Unite object for expecting amount and format
3755
- if (currentTemplate.format) {
3756
- if (currentTemplate.format === 'JSON') {
3757
- if (!isValidJsonString(resultString || '')) {
3758
- // TODO: [🏢] Do more universally via `FormatDefinition`
3759
- try {
3760
- resultString = extractJsonBlock(resultString || '');
3761
- }
3762
- catch (error) {
3763
- keepUnused(error);
3764
- throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3765
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3766
- }
3767
- }
3491
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
3492
+ throw new PipelineExecutionError('Parameter is already opened or not closed');
3493
+ }
3494
+ if (parameters[parameterName] === undefined) {
3495
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3496
+ }
3497
+ var parameterValue = parameters[parameterName];
3498
+ if (parameterValue === undefined) {
3499
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3500
+ }
3501
+ parameterValue = parameterValue.toString();
3502
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
3503
+ parameterValue = parameterValue
3504
+ .split('\n')
3505
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
3506
+ .join('\n');
3507
+ }
3508
+ replacedTemplate =
3509
+ replacedTemplate.substring(0, match.index + precol.length) +
3510
+ parameterValue +
3511
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
3512
+ };
3513
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
3514
+ .exec(replacedTemplate))) {
3515
+ _loop_1();
3516
+ }
3517
+ // [💫] Check if there are parameters that are not closed properly
3518
+ if (/{\w+$/.test(replacedTemplate)) {
3519
+ throw new PipelineExecutionError('Parameter is not closed');
3520
+ }
3521
+ // [💫] Check if there are parameters that are not opened properly
3522
+ if (/^\w+}/.test(replacedTemplate)) {
3523
+ throw new PipelineExecutionError('Parameter is not opened');
3524
+ }
3525
+ return replacedTemplate;
3526
+ }
3527
+
3528
+ /**
3529
+ * Counts number of characters in the text
3530
+ *
3531
+ * @public exported from `@promptbook/utils`
3532
+ */
3533
+ function countCharacters(text) {
3534
+ // Remove null characters
3535
+ text = text.replace(/\0/g, '');
3536
+ // Replace emojis (and also ZWJ sequence) with hyphens
3537
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3538
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
3539
+ text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
3540
+ return text.length;
3541
+ }
3542
+
3543
+ /**
3544
+ * Counts number of lines in the text
3545
+ *
3546
+ * @public exported from `@promptbook/utils`
3547
+ */
3548
+ function countLines(text) {
3549
+ if (text === '') {
3550
+ return 0;
3551
+ }
3552
+ return text.split('\n').length;
3553
+ }
3554
+
3555
+ /**
3556
+ * Counts number of pages in the text
3557
+ *
3558
+ * @public exported from `@promptbook/utils`
3559
+ */
3560
+ function countPages(text) {
3561
+ var sentencesPerPage = 5; // Assuming each page has 5 sentences
3562
+ var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3563
+ var pageCount = Math.ceil(sentences.length / sentencesPerPage);
3564
+ return pageCount;
3565
+ }
3566
+
3567
+ /**
3568
+ * Counts number of paragraphs in the text
3569
+ *
3570
+ * @public exported from `@promptbook/utils`
3571
+ */
3572
+ function countParagraphs(text) {
3573
+ return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
3574
+ }
3575
+
3576
+ /**
3577
+ * Split text into sentences
3578
+ *
3579
+ * @public exported from `@promptbook/utils`
3580
+ */
3581
+ function splitIntoSentences(text) {
3582
+ return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3583
+ }
3584
+ /**
3585
+ * Counts number of sentences in the text
3586
+ *
3587
+ * @public exported from `@promptbook/utils`
3588
+ */
3589
+ function countSentences(text) {
3590
+ return splitIntoSentences(text).length;
3591
+ }
3592
+
3593
+ /**
3594
+ * Counts number of words in the text
3595
+ *
3596
+ * @public exported from `@promptbook/utils`
3597
+ */
3598
+ function countWords(text) {
3599
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3600
+ text = removeDiacritics(text);
3601
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3602
+ }
3603
+
3604
+ /**
3605
+ * Index of all counter functions
3606
+ *
3607
+ * @public exported from `@promptbook/utils`
3608
+ */
3609
+ var CountUtils = {
3610
+ CHARACTERS: countCharacters,
3611
+ WORDS: countWords,
3612
+ SENTENCES: countSentences,
3613
+ PARAGRAPHS: countParagraphs,
3614
+ LINES: countLines,
3615
+ PAGES: countPages,
3616
+ };
3617
+ /**
3618
+ * TODO: [🧠][🤠] This should be probbably as part of `TextFormatDefinition`
3619
+ */
3620
+
3621
+ /**
3622
+ * Function checkExpectations will check if the expectations on given value are met
3623
+ *
3624
+ * Note: There are two simmilar functions:
3625
+ * - `checkExpectations` which throws an error if the expectations are not met
3626
+ * - `isPassingExpectations` which returns a boolean
3627
+ *
3628
+ * @throws {ExpectError} if the expectations are not met
3629
+ * @returns {void} Nothing
3630
+ * @private internal function of `createPipelineExecutor`
3631
+ */
3632
+ function checkExpectations(expectations, value) {
3633
+ var e_1, _a;
3634
+ try {
3635
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3636
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3637
+ var amount = CountUtils[unit.toUpperCase()](value);
3638
+ if (min && amount < min) {
3639
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3640
+ } /* not else */
3641
+ if (max && amount > max) {
3642
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3643
+ }
3644
+ }
3645
+ }
3646
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3647
+ finally {
3648
+ try {
3649
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3650
+ }
3651
+ finally { if (e_1) throw e_1.error; }
3652
+ }
3653
+ }
3654
+ /**
3655
+ * Function checkExpectations will check if the expectations on given value are met
3656
+ *
3657
+ * Note: There are two simmilar functions:
3658
+ * - `checkExpectations` which throws an error if the expectations are not met
3659
+ * - `isPassingExpectations` which returns a boolean
3660
+ *
3661
+ * @returns {boolean} True if the expectations are met
3662
+ * @public exported from `@promptbook/core`
3663
+ */
3664
+ function isPassingExpectations(expectations, value) {
3665
+ try {
3666
+ checkExpectations(expectations, value);
3667
+ return true;
3668
+ }
3669
+ catch (error) {
3670
+ if (!(error instanceof ExpectError)) {
3671
+ throw error;
3672
+ }
3673
+ return false;
3674
+ }
3675
+ }
3676
+ /**
3677
+ * TODO: [💝] Unite object for expecting amount and format
3678
+ * TODO: [🧠][🤠] This should be part of `TextFormatDefinition`
3679
+ * Note: [💝] and [🤠] are interconnected together
3680
+ */
3681
+
3682
+ /**
3683
+ * @@@
3684
+ *
3685
+ * @private internal utility of `createPipelineExecutor`
3686
+ */
3687
+ function executeAttempts(options) {
3688
+ return __awaiter(this, void 0, void 0, function () {
3689
+ var jokerParameterNames, priority, maxAttempts, preparedContent, parameters, template, preparedPipeline, tools, llmTools, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, $ongoingTemplateResult, _loop_1, attempt, state_1;
3690
+ return __generator(this, function (_a) {
3691
+ switch (_a.label) {
3692
+ case 0:
3693
+ 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;
3694
+ maxExecutionAttempts = settings.maxExecutionAttempts;
3695
+ $ongoingTemplateResult = {
3696
+ $result: null,
3697
+ $resultString: null,
3698
+ $expectError: null,
3699
+ $scriptPipelineExecutionErrors: [],
3700
+ };
3701
+ _loop_1 = function (attempt) {
3702
+ 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;
3703
+ var e_1, _q, e_3, _r, e_2, _s;
3704
+ return __generator(this, function (_t) {
3705
+ switch (_t.label) {
3706
+ case 0:
3707
+ isJokerAttempt = attempt < 0;
3708
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3709
+ // TODO: [🧠][🍭] JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3710
+ if (isJokerAttempt && !jokerParameterName) {
3711
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3712
+ }
3713
+ $ongoingTemplateResult.$result = null;
3714
+ $ongoingTemplateResult.$resultString = null;
3715
+ $ongoingTemplateResult.$expectError = null;
3716
+ if (isJokerAttempt) {
3717
+ if (parameters[jokerParameterName] === undefined) {
3718
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3719
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3720
+ }
3721
+ else {
3722
+ $ongoingTemplateResult.$resultString = parameters[jokerParameterName];
3723
+ }
3724
+ }
3725
+ _t.label = 1;
3726
+ case 1:
3727
+ _t.trys.push([1, 43, 44, 45]);
3728
+ if (!!isJokerAttempt) return [3 /*break*/, 25];
3729
+ _b = template.templateType;
3730
+ switch (_b) {
3731
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3732
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3733
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 11];
3734
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 22];
3735
+ }
3736
+ return [3 /*break*/, 24];
3737
+ case 2:
3738
+ $ongoingTemplateResult.$resultString = replaceParameters(preparedContent, parameters);
3739
+ return [3 /*break*/, 25];
3740
+ case 3:
3741
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (template.modelRequirements || {}));
3742
+ $ongoingTemplateResult.$prompt = {
3743
+ title: template.title,
3744
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3745
+ ? preparedPipeline.pipelineUrl
3746
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(template.name),
3747
+ parameters: parameters,
3748
+ content: preparedContent,
3749
+ modelRequirements: modelRequirements,
3750
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3751
+ var name = _a.name;
3752
+ return name === template.personaName;
3753
+ }) ||
3754
+ {})), template.expectations),
3755
+ format: template.format,
3756
+ postprocessingFunctionNames: template.postprocessingFunctionNames,
3757
+ }; // <- TODO: Not very good type guard
3758
+ _c = modelRequirements.modelVariant;
3759
+ switch (_c) {
3760
+ case 'CHAT': return [3 /*break*/, 4];
3761
+ case 'COMPLETION': return [3 /*break*/, 6];
3762
+ case 'EMBEDDING': return [3 /*break*/, 8];
3763
+ }
3764
+ return [3 /*break*/, 9];
3765
+ case 4:
3766
+ _d = $ongoingTemplateResult;
3767
+ return [4 /*yield*/, llmTools.callChatModel($deepFreeze($ongoingTemplateResult.$prompt))];
3768
+ case 5:
3769
+ _d.$chatResult = _t.sent();
3770
+ // TODO: [🍬] Destroy chatThread
3771
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$chatResult;
3772
+ $ongoingTemplateResult.$resultString = $ongoingTemplateResult.$chatResult.content;
3773
+ return [3 /*break*/, 10];
3774
+ case 6:
3775
+ _e = $ongoingTemplateResult;
3776
+ return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze($ongoingTemplateResult.$prompt))];
3777
+ case 7:
3778
+ _e.$completionResult = _t.sent();
3779
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$completionResult;
3780
+ $ongoingTemplateResult.$resultString =
3781
+ $ongoingTemplateResult.$completionResult.content;
3782
+ return [3 /*break*/, 10];
3783
+ case 8: throw new PipelineExecutionError(spaceTrim.spaceTrim(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 "); }));
3784
+ case 9: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model variant \"".concat(template.modelRequirements.modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3785
+ case 10: return [3 /*break*/, 25];
3786
+ case 11:
3787
+ if (arrayableToArray(tools.script).length === 0) {
3788
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3789
+ }
3790
+ if (!template.contentLanguage) {
3791
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script language is not defined for SCRIPT TEMPLATE \"".concat(template.name, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3792
+ }
3793
+ _t.label = 12;
3794
+ case 12:
3795
+ _t.trys.push([12, 19, 20, 21]);
3796
+ _f = (e_1 = void 0, __values(arrayableToArray(tools.script))), _g = _f.next();
3797
+ _t.label = 13;
3798
+ case 13:
3799
+ if (!!_g.done) return [3 /*break*/, 18];
3800
+ scriptTools = _g.value;
3801
+ _t.label = 14;
3802
+ case 14:
3803
+ _t.trys.push([14, 16, , 17]);
3804
+ _h = $ongoingTemplateResult;
3805
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3806
+ scriptLanguage: template.contentLanguage,
3807
+ script: preparedContent,
3808
+ parameters: parameters,
3809
+ }))];
3810
+ case 15:
3811
+ _h.$resultString = _t.sent();
3812
+ return [3 /*break*/, 18];
3813
+ case 16:
3814
+ error_1 = _t.sent();
3815
+ if (!(error_1 instanceof Error)) {
3816
+ throw error_1;
3817
+ }
3818
+ if (error_1 instanceof UnexpectedError) {
3819
+ throw error_1;
3820
+ }
3821
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_1);
3822
+ return [3 /*break*/, 17];
3823
+ case 17:
3824
+ _g = _f.next();
3825
+ return [3 /*break*/, 13];
3826
+ case 18: return [3 /*break*/, 21];
3827
+ case 19:
3828
+ e_1_1 = _t.sent();
3829
+ e_1 = { error: e_1_1 };
3830
+ return [3 /*break*/, 21];
3831
+ case 20:
3832
+ try {
3833
+ if (_g && !_g.done && (_q = _f.return)) _q.call(_f);
3834
+ }
3835
+ finally { if (e_1) throw e_1.error; }
3836
+ return [7 /*endfinally*/];
3837
+ case 21:
3838
+ if ($ongoingTemplateResult.$resultString !== null) {
3839
+ return [3 /*break*/, 25];
3840
+ }
3841
+ if ($ongoingTemplateResult.$scriptPipelineExecutionErrors.length === 1) {
3842
+ throw $ongoingTemplateResult.$scriptPipelineExecutionErrors[0];
3843
+ }
3844
+ else {
3845
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script execution failed ".concat($ongoingTemplateResult.$scriptPipelineExecutionErrors.length, "x\n\n ").concat(block(pipelineIdentification), "\n\n ").concat(block($ongoingTemplateResult.$scriptPipelineExecutionErrors
3846
+ .map(function (error) { return '- ' + error.message; })
3847
+ .join('\n\n')), "\n "); }));
3848
+ }
3849
+ case 22:
3850
+ if (tools.userInterface === undefined) {
3851
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3852
+ }
3853
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3854
+ _j = $ongoingTemplateResult;
3855
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3856
+ promptTitle: template.title,
3857
+ promptMessage: replaceParameters(template.description || '', parameters),
3858
+ defaultValue: replaceParameters(preparedContent, parameters),
3859
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3860
+ placeholder: undefined,
3861
+ priority: priority,
3862
+ }))];
3863
+ case 23:
3864
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3865
+ _j.$resultString = _t.sent();
3866
+ return [3 /*break*/, 25];
3867
+ case 24: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type \"".concat(template.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3868
+ case 25:
3869
+ if (!(!isJokerAttempt && template.postprocessingFunctionNames)) return [3 /*break*/, 42];
3870
+ _t.label = 26;
3871
+ case 26:
3872
+ _t.trys.push([26, 40, 41, 42]);
3873
+ _k = (e_3 = void 0, __values(template.postprocessingFunctionNames)), _l = _k.next();
3874
+ _t.label = 27;
3875
+ case 27:
3876
+ if (!!_l.done) return [3 /*break*/, 39];
3877
+ functionName = _l.value;
3878
+ postprocessingError = null;
3879
+ _t.label = 28;
3880
+ case 28:
3881
+ _t.trys.push([28, 35, 36, 37]);
3882
+ _m = (e_2 = void 0, __values(arrayableToArray(tools.script))), _o = _m.next();
3883
+ _t.label = 29;
3884
+ case 29:
3885
+ if (!!_o.done) return [3 /*break*/, 34];
3886
+ scriptTools = _o.value;
3887
+ _t.label = 30;
3888
+ case 30:
3889
+ _t.trys.push([30, 32, , 33]);
3890
+ _p = $ongoingTemplateResult;
3891
+ return [4 /*yield*/, scriptTools.execute({
3892
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3893
+ script: "".concat(functionName, "(resultString)"),
3894
+ parameters: {
3895
+ resultString: $ongoingTemplateResult.$resultString || '',
3896
+ // Note: No ...parametersForTemplate, because working with result only
3897
+ },
3898
+ })];
3899
+ case 31:
3900
+ _p.$resultString = _t.sent();
3901
+ postprocessingError = null;
3902
+ return [3 /*break*/, 34];
3903
+ case 32:
3904
+ error_2 = _t.sent();
3905
+ if (!(error_2 instanceof Error)) {
3906
+ throw error_2;
3907
+ }
3908
+ if (error_2 instanceof UnexpectedError) {
3909
+ throw error_2;
3910
+ }
3911
+ postprocessingError = error_2;
3912
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_2);
3913
+ return [3 /*break*/, 33];
3914
+ case 33:
3915
+ _o = _m.next();
3916
+ return [3 /*break*/, 29];
3917
+ case 34: return [3 /*break*/, 37];
3918
+ case 35:
3919
+ e_2_1 = _t.sent();
3920
+ e_2 = { error: e_2_1 };
3921
+ return [3 /*break*/, 37];
3922
+ case 36:
3923
+ try {
3924
+ if (_o && !_o.done && (_s = _m.return)) _s.call(_m);
3925
+ }
3926
+ finally { if (e_2) throw e_2.error; }
3927
+ return [7 /*endfinally*/];
3928
+ case 37:
3929
+ if (postprocessingError) {
3930
+ throw postprocessingError;
3931
+ }
3932
+ _t.label = 38;
3933
+ case 38:
3934
+ _l = _k.next();
3935
+ return [3 /*break*/, 27];
3936
+ case 39: return [3 /*break*/, 42];
3937
+ case 40:
3938
+ e_3_1 = _t.sent();
3939
+ e_3 = { error: e_3_1 };
3940
+ return [3 /*break*/, 42];
3941
+ case 41:
3942
+ try {
3943
+ if (_l && !_l.done && (_r = _k.return)) _r.call(_k);
3944
+ }
3945
+ finally { if (e_3) throw e_3.error; }
3946
+ return [7 /*endfinally*/];
3947
+ case 42:
3948
+ // TODO: [💝] Unite object for expecting amount and format
3949
+ if (template.format) {
3950
+ if (template.format === 'JSON') {
3951
+ if (!isValidJsonString($ongoingTemplateResult.$resultString || '')) {
3952
+ // TODO: [🏢] Do more universally via `FormatDefinition`
3953
+ try {
3954
+ $ongoingTemplateResult.$resultString = extractJsonBlock($ongoingTemplateResult.$resultString || '');
3768
3955
  }
3769
- else {
3770
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3956
+ catch (error) {
3957
+ keepUnused(error);
3958
+ throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3959
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3771
3960
  }
3772
3961
  }
3773
- // TODO: [💝] Unite object for expecting amount and format
3774
- if (currentTemplate.expectations) {
3775
- checkExpectations(currentTemplate.expectations, resultString || '');
3776
- }
3777
- return [2 /*return*/, "break-attempts"];
3778
- case 44:
3779
- error_4 = _v.sent();
3780
- if (!(error_4 instanceof ExpectError)) {
3781
- throw error_4;
3782
- }
3783
- expectError = error_4;
3784
- return [3 /*break*/, 46];
3785
- case 45:
3786
- if (!isJokerAttempt &&
3787
- currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3788
- prompt
3789
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3790
- // In that case we don’t want to make a report about it because it’s not a llm execution error
3791
- ) {
3792
- // TODO: [🧠] Maybe put other templateTypes into report
3793
- executionReport.promptExecutions.push({
3794
- prompt: __assign({}, prompt),
3795
- result: result || undefined,
3796
- error: expectError === null ? undefined : serializeError(expectError),
3797
- });
3798
- }
3799
- return [7 /*endfinally*/];
3800
- case 46:
3801
- if (expectError !== null && attempt === maxAttempts - 1) {
3802
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ").concat(block(pipelineIdentification), "\n\n ---\n The Prompt:\n ").concat(block(prompt.content
3803
- .split('\n')
3804
- .map(function (line) { return "> ".concat(line); })
3805
- .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) || '')
3962
+ }
3963
+ else {
3964
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown format \"".concat(template.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3965
+ }
3966
+ }
3967
+ // TODO: [💝] Unite object for expecting amount and format
3968
+ if (template.expectations) {
3969
+ checkExpectations(template.expectations, $ongoingTemplateResult.$resultString || '');
3970
+ }
3971
+ return [2 /*return*/, "break-attempts"];
3972
+ case 43:
3973
+ error_3 = _t.sent();
3974
+ if (!(error_3 instanceof ExpectError)) {
3975
+ throw error_3;
3976
+ }
3977
+ $ongoingTemplateResult.$expectError = error_3;
3978
+ return [3 /*break*/, 45];
3979
+ case 44:
3980
+ if (!isJokerAttempt &&
3981
+ template.templateType === 'PROMPT_TEMPLATE' &&
3982
+ $ongoingTemplateResult.$prompt
3983
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3984
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
3985
+ ) {
3986
+ // TODO: [🧠] Maybe put other templateTypes into report
3987
+ $executionReport.promptExecutions.push({
3988
+ prompt: __assign({}, $ongoingTemplateResult.$prompt),
3989
+ result: $ongoingTemplateResult.$result || undefined,
3990
+ error: $ongoingTemplateResult.$expectError === null
3991
+ ? undefined
3992
+ : serializeError($ongoingTemplateResult.$expectError),
3993
+ });
3994
+ }
3995
+ return [7 /*endfinally*/];
3996
+ case 45:
3997
+ if ($ongoingTemplateResult.$expectError !== null && attempt === maxAttempts - 1) {
3998
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) {
3999
+ var _a, _b, _c;
4000
+ 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) || '')
4001
+ .split('\n')
4002
+ .map(function (line) { return "> ".concat(line); })
4003
+ .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) || '')
4004
+ .split('\n')
4005
+ .map(function (line) { return "> ".concat(line); })
4006
+ .join('\n')), "\n\n Last result:\n ").concat(block($ongoingTemplateResult.$resultString === null
4007
+ ? 'null'
4008
+ : $ongoingTemplateResult.$resultString
3806
4009
  .split('\n')
3807
4010
  .map(function (line) { return "> ".concat(line); })
3808
- .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3809
- ? 'null'
3810
- : resultString
3811
- .split('\n')
3812
- .map(function (line) { return "> ".concat(line); })
3813
- .join('\n')), "\n ---\n "); }));
3814
- }
3815
- return [2 /*return*/];
4011
+ .join('\n')), "\n ---\n ");
4012
+ }));
3816
4013
  }
3817
- });
3818
- };
3819
- attempt = -jokerParameterNames.length;
3820
- _h.label = 4;
3821
- case 4:
3822
- if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3823
- return [5 /*yield**/, _loop_5(attempt)];
3824
- case 5:
3825
- state_2 = _h.sent();
3826
- switch (state_2) {
3827
- case "break-attempts": return [3 /*break*/, 7];
4014
+ return [2 /*return*/];
3828
4015
  }
3829
- _h.label = 6;
3830
- case 6:
3831
- attempt++;
3832
- return [3 /*break*/, 4];
3833
- case 7:
3834
- //------------------------------------
3835
- /*
3836
-
3837
-
3838
-
3839
-
3840
-
3841
-
3842
-
3843
-
3844
-
3845
- */
3846
- //------------------------------------
3847
- if (resultString === null) {
3848
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3849
- }
3850
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 9]; /* <- [3] */
3851
- progress_2 = {
3852
- name: name,
3853
- title: title,
3854
- isStarted: true,
3855
- isDone: true,
3856
- templateType: currentTemplate.templateType,
3857
- parameterName: currentTemplate.resultingParameterName,
3858
- parameterValue: resultString,
3859
- // <- [3]
3860
- };
3861
- if (isReturned) {
3862
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished \uD83C\uDF4E\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress_2, null, 4)
3863
- .split('\n')
3864
- .map(function (line) { return "> ".concat(line); })
3865
- .join('\n')), "\n\n "); }));
3866
- }
3867
- return [4 /*yield*/, onProgress(progress_2)];
3868
- case 8:
3869
- _h.sent();
3870
- _h.label = 9;
3871
- case 9:
3872
- 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)));
3873
- return [2 /*return*/];
4016
+ });
4017
+ };
4018
+ attempt = -jokerParameterNames.length;
4019
+ _a.label = 1;
4020
+ case 1:
4021
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 4];
4022
+ return [5 /*yield**/, _loop_1(attempt)];
4023
+ case 2:
4024
+ state_1 = _a.sent();
4025
+ switch (state_1) {
4026
+ case "break-attempts": return [3 /*break*/, 4];
3874
4027
  }
3875
- });
3876
- });
3877
- }
3878
- function filterJustOutputParameters() {
3879
- var e_8, _a;
3880
- var outputParameters = {};
3881
- var _loop_6 = function (parameter) {
3882
- if (parametersToPass[parameter.name] === undefined) {
3883
- // [4]
3884
- warnings.push(new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution\n\n ").concat(block(pipelineIdentification), "\n "); })));
3885
- return "continue";
3886
- }
3887
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3888
- };
3889
- try {
3890
- // Note: Filter ONLY output parameters
3891
- for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3892
- var isOutput = _a.isOutput;
3893
- return isOutput;
3894
- })), _c = _b.next(); !_c.done; _c = _b.next()) {
3895
- var parameter = _c.value;
3896
- _loop_6(parameter);
3897
- }
4028
+ _a.label = 3;
4029
+ case 3:
4030
+ attempt++;
4031
+ return [3 /*break*/, 1];
4032
+ case 4:
4033
+ if ($ongoingTemplateResult.$resultString === null) {
4034
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
4035
+ }
4036
+ return [2 /*return*/, $ongoingTemplateResult.$resultString];
3898
4037
  }
3899
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
3900
- finally {
3901
- try {
3902
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3903
- }
3904
- finally { if (e_8) throw e_8.error; }
4038
+ });
4039
+ });
4040
+ }
4041
+ /**
4042
+ * TODO: Break into smaller functions
4043
+ */
4044
+
4045
+ /**
4046
+ * @@@
4047
+ *
4048
+ * @private internal utility of `createPipelineExecutor`
4049
+ */
4050
+ function executeFormatCells(options) {
4051
+ return __awaiter(this, void 0, void 0, function () {
4052
+ var template, jokerParameterNames, parameters, priority, pipelineIdentification, settings, parameterValue, formatDefinition, subvalueDefinition, formatSettings, resultString;
4053
+ var _this = this;
4054
+ return __generator(this, function (_a) {
4055
+ switch (_a.label) {
4056
+ case 0:
4057
+ template = options.template, jokerParameterNames = options.jokerParameterNames, parameters = options.parameters, priority = options.priority, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
4058
+ if (template.foreach === undefined) {
4059
+ return [2 /*return*/, /* not await */ executeAttempts(options)];
4060
+ }
4061
+ if (jokerParameterNames.length !== 0) {
4062
+ throw new UnexpectedError(spaceTrim__default["default"](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 "); }));
4063
+ }
4064
+ parameterValue = parameters[template.foreach.parameterName] || '';
4065
+ formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
4066
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(template.foreach.formatName);
4067
+ });
4068
+ if (formatDefinition === undefined) {
4069
+ throw new UnexpectedError(
4070
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
4071
+ spaceTrim__default["default"](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; })
4072
+ .map(function (formatName) { return "- ".concat(formatName); })
4073
+ .join('\n')), "\n\n [\u26F7] This should never happen because format name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
4074
+ }
4075
+ subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
4076
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(template.foreach.subformatName);
4077
+ });
4078
+ if (subvalueDefinition === undefined) {
4079
+ throw new UnexpectedError(
4080
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
4081
+ spaceTrim__default["default"](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
4082
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
4083
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
4084
+ .join('\n')), "\n\n [\u26F7] This should never happen because subformat name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
4085
+ }
4086
+ if (formatDefinition.formatName === 'CSV') {
4087
+ formatSettings = settings.csvSettings;
4088
+ // <- TODO: !!!!!! More universal, make simmilar pattern for other formats for example \n vs \r\n in text
4089
+ }
4090
+ return [4 /*yield*/, subvalueDefinition.mapValues(parameterValue, template.foreach.outputSubparameterName, formatSettings, function (subparameters, index) { return __awaiter(_this, void 0, void 0, function () {
4091
+ var mappedParameters, allSubparameters, subresultString;
4092
+ return __generator(this, function (_a) {
4093
+ switch (_a.label) {
4094
+ case 0:
4095
+ // TODO: !!!!!!! Limit to N concurrent executions
4096
+ // TODO: !!!!!!! Report progress
4097
+ try {
4098
+ mappedParameters = mapAvailableToExpectedParameters({
4099
+ expectedParameters: Object.fromEntries(template.foreach.inputSubparameterNames.map(function (subparameterName) { return [subparameterName, null]; })),
4100
+ availableParameters: subparameters,
4101
+ });
4102
+ }
4103
+ catch (error) {
4104
+ if (!(error instanceof PipelineExecutionError)) {
4105
+ throw error;
4106
+ }
4107
+ throw new PipelineExecutionError(spaceTrim__default["default"](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 Subparameter index: ").concat(index, "\n "); }));
4108
+ }
4109
+ allSubparameters = __assign(__assign({}, parameters), mappedParameters);
4110
+ // 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
4111
+ Object.freeze(allSubparameters);
4112
+ return [4 /*yield*/, executeAttempts(__assign(__assign({}, options), { priority: priority + index, parameters: allSubparameters, pipelineIdentification: spaceTrim__default["default"](function (block) { return "\n ".concat(block(pipelineIdentification), "\n Subparameter index: ").concat(index, "\n "); }) }))];
4113
+ case 1:
4114
+ subresultString = _a.sent();
4115
+ return [2 /*return*/, subresultString];
4116
+ }
4117
+ });
4118
+ }); })];
4119
+ case 1:
4120
+ resultString = _a.sent();
4121
+ return [2 /*return*/, resultString];
4122
+ }
4123
+ });
4124
+ });
4125
+ }
4126
+ /**
4127
+ * TODO: !!!!!! Make pipelineIdentification more precise
4128
+ * TODO: !!!!!! How FOREACH execution looks in the report
4129
+ */
4130
+
4131
+ /**
4132
+ * @@@
4133
+ *
4134
+ * @private internal utility of `createPipelineExecutor`
4135
+ */
4136
+ function getContextForTemplate(template) {
4137
+ return __awaiter(this, void 0, void 0, function () {
4138
+ return __generator(this, function (_a) {
4139
+ TODO_USE(template);
4140
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
4141
+ });
4142
+ });
4143
+ }
4144
+
4145
+ /**
4146
+ * @@@
4147
+ *
4148
+ * @private internal utility of `createPipelineExecutor`
4149
+ */
4150
+ function getKnowledgeForTemplate(options) {
4151
+ return __awaiter(this, void 0, void 0, function () {
4152
+ var preparedPipeline, template;
4153
+ return __generator(this, function (_a) {
4154
+ preparedPipeline = options.preparedPipeline, template = options.template;
4155
+ // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
4156
+ TODO_USE(template);
4157
+ return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
4158
+ var content = _a.content;
4159
+ return "- ".concat(content);
4160
+ }).join('\n')];
4161
+ });
4162
+ });
4163
+ }
4164
+
4165
+ /**
4166
+ * @@@
4167
+ *
4168
+ * @private internal utility of `createPipelineExecutor`
4169
+ */
4170
+ function getSamplesForTemplate(template) {
4171
+ return __awaiter(this, void 0, void 0, function () {
4172
+ return __generator(this, function (_a) {
4173
+ // TODO: [♨] Implement Better - use real index and keyword search
4174
+ TODO_USE(template);
4175
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
4176
+ });
4177
+ });
4178
+ }
4179
+
4180
+ /**
4181
+ * @@@
4182
+ *
4183
+ * @private internal utility of `createPipelineExecutor`
4184
+ */
4185
+ function getReservedParametersForTemplate(options) {
4186
+ return __awaiter(this, void 0, void 0, function () {
4187
+ var preparedPipeline, template, pipelineIdentification, context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
4188
+ var e_1, _a;
4189
+ return __generator(this, function (_b) {
4190
+ switch (_b.label) {
4191
+ case 0:
4192
+ preparedPipeline = options.preparedPipeline, template = options.template, pipelineIdentification = options.pipelineIdentification;
4193
+ return [4 /*yield*/, getContextForTemplate(template)];
4194
+ case 1:
4195
+ context = _b.sent();
4196
+ return [4 /*yield*/, getKnowledgeForTemplate({ preparedPipeline: preparedPipeline, template: template })];
4197
+ case 2:
4198
+ knowledge = _b.sent();
4199
+ return [4 /*yield*/, getSamplesForTemplate(template)];
4200
+ case 3:
4201
+ samples = _b.sent();
4202
+ currentDate = new Date().toISOString();
4203
+ modelName = RESERVED_PARAMETER_MISSING_VALUE;
4204
+ reservedParameters = {
4205
+ content: RESERVED_PARAMETER_RESTRICTED,
4206
+ context: context,
4207
+ knowledge: knowledge,
4208
+ samples: samples,
4209
+ currentDate: currentDate,
4210
+ modelName: modelName,
4211
+ };
4212
+ _loop_1 = function (parameterName) {
4213
+ if (reservedParameters[parameterName] === undefined) {
4214
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
4215
+ }
4216
+ };
4217
+ try {
4218
+ // Note: Doublecheck that ALL reserved parameters are defined:
4219
+ 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()) {
4220
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
4221
+ _loop_1(parameterName);
4222
+ }
4223
+ }
4224
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4225
+ finally {
4226
+ try {
4227
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
4228
+ }
4229
+ finally { if (e_1) throw e_1.error; }
4230
+ }
4231
+ return [2 /*return*/, reservedParameters];
4232
+ }
4233
+ });
4234
+ });
4235
+ }
4236
+
4237
+ /**
4238
+ * @@@
4239
+ *
4240
+ * @private internal utility of `createPipelineExecutor`
4241
+ */
4242
+ function executeTemplate(options) {
4243
+ return __awaiter(this, void 0, void 0, function () {
4244
+ 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;
4245
+ var e_1, _f, _g;
4246
+ return __generator(this, function (_h) {
4247
+ switch (_h.label) {
4248
+ case 0:
4249
+ 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;
4250
+ maxExecutionAttempts = settings.maxExecutionAttempts;
4251
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
4252
+ title = currentTemplate.title;
4253
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
4254
+ return [4 /*yield*/, onProgress({
4255
+ name: name,
4256
+ title: title,
4257
+ isStarted: false,
4258
+ isDone: false,
4259
+ templateType: currentTemplate.templateType,
4260
+ parameterName: currentTemplate.resultingParameterName,
4261
+ parameterValue: null,
4262
+ // <- [🍸]
4263
+ })];
4264
+ case 1:
4265
+ _h.sent();
4266
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
4267
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
4268
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4269
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
4270
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n Dependent parameters:\n ".concat(Array.from(dependentParameterNames)
4271
+ .map(function (name) { return "{".concat(name, "}"); })
4272
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
4273
+ .map(function (name) { return "{".concat(name, "}"); })
4274
+ .join(', '), "\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
4275
+ }
4276
+ _b = (_a = Object).freeze;
4277
+ _c = [{}];
4278
+ return [4 /*yield*/, getReservedParametersForTemplate({
4279
+ preparedPipeline: preparedPipeline,
4280
+ template: currentTemplate,
4281
+ pipelineIdentification: pipelineIdentification,
4282
+ })];
4283
+ case 2:
4284
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
4285
+ definedParameterNames = new Set(Object.keys(definedParameters));
4286
+ parameters = {};
4287
+ _loop_1 = function (parameterName) {
4288
+ // Situation: Parameter is defined and used
4289
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4290
+ parameters[parameterName] = definedParameters[parameterName];
4291
+ }
4292
+ // Situation: Parameter is defined but NOT used
4293
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
4294
+ // Situation: Parameter is NOT defined BUT used
4295
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4296
+ // Houston, we have a problem
4297
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
4298
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is NOT defined\n BUT used in template \"").concat(currentTemplate.title || currentTemplate.name, "\"\n\n This should be catched in `validatePipeline`\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
4299
+ }
4300
+ };
4301
+ try {
4302
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
4303
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4304
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
4305
+ parameterName = _e.value;
4306
+ _loop_1(parameterName);
4307
+ }
4308
+ }
4309
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4310
+ finally {
4311
+ try {
4312
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
4313
+ }
4314
+ finally { if (e_1) throw e_1.error; }
4315
+ }
4316
+ // 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
4317
+ Object.freeze(parameters);
4318
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
4319
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
4320
+ preparedContent = (currentTemplate.preparedContent || '{content}')
4321
+ .split('{content}')
4322
+ .join(currentTemplate.content);
4323
+ return [4 /*yield*/, executeFormatCells({
4324
+ jokerParameterNames: jokerParameterNames,
4325
+ priority: priority,
4326
+ maxAttempts: maxAttempts,
4327
+ preparedContent: preparedContent,
4328
+ parameters: parameters,
4329
+ template: currentTemplate,
4330
+ preparedPipeline: preparedPipeline,
4331
+ tools: tools,
4332
+ llmTools: llmTools,
4333
+ settings: settings,
4334
+ $executionReport: $executionReport,
4335
+ pipelineIdentification: pipelineIdentification,
4336
+ })];
4337
+ case 3:
4338
+ resultString = _h.sent();
4339
+ return [4 /*yield*/, onProgress({
4340
+ name: name,
4341
+ title: title,
4342
+ isStarted: true,
4343
+ isDone: true,
4344
+ templateType: currentTemplate.templateType,
4345
+ parameterName: currentTemplate.resultingParameterName,
4346
+ parameterValue: resultString,
4347
+ // <- [🍸]
4348
+ })];
4349
+ case 4:
4350
+ _h.sent();
4351
+ return [2 /*return*/, Object.freeze((_g = {},
4352
+ _g[currentTemplate.resultingParameterName] =
4353
+ // <- Note: [👩‍👩‍👧] No need to detect parameter collision here because pipeline checks logic consistency during construction
4354
+ resultString,
4355
+ _g))];
3905
4356
  }
3906
- return outputParameters;
4357
+ });
4358
+ });
4359
+ }
4360
+ /**
4361
+ * TODO: [🤹‍♂️]
4362
+ */
4363
+
4364
+ /**
4365
+ * @@@
4366
+ *
4367
+ * @private internal utility of `createPipelineExecutor`
4368
+ */
4369
+ function filterJustOutputParameters(options) {
4370
+ var e_1, _a;
4371
+ var preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, $warnings = options.$warnings, pipelineIdentification = options.pipelineIdentification;
4372
+ var outputParameters = {};
4373
+ var _loop_1 = function (parameter) {
4374
+ if (parametersToPass[parameter.name] === undefined) {
4375
+ // [4]
4376
+ $warnings.push(new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} should be an output parameter, but it was not generated during pipeline execution\n\n ").concat(block(pipelineIdentification), "\n "); })));
4377
+ return "continue";
4378
+ }
4379
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
4380
+ };
4381
+ try {
4382
+ // Note: Filter ONLY output parameters
4383
+ // TODO: [👩🏾‍🤝‍👩🏻] Maybe use here `mapAvailableToExpectedParameters`
4384
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
4385
+ var isOutput = _a.isOutput;
4386
+ return isOutput;
4387
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
4388
+ var parameter = _c.value;
4389
+ _loop_1(parameter);
4390
+ }
4391
+ }
4392
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4393
+ finally {
4394
+ try {
4395
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3907
4396
  }
3908
- 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;
4397
+ finally { if (e_1) throw e_1.error; }
4398
+ }
4399
+ return outputParameters;
4400
+ }
4401
+
4402
+ /**
4403
+ * @@@
4404
+ *
4405
+ * Note: This is not a `PipelineExecutor` (which is binded with one exact pipeline), but a utility function of `createPipelineExecutor` which creates `PipelineExecutor`
4406
+ *
4407
+ * @private internal utility of `createPipelineExecutor`
4408
+ */
4409
+ function executePipeline(options) {
4410
+ return __awaiter(this, void 0, void 0, function () {
4411
+ 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;
3909
4412
  var e_1, _e, e_2, _f;
3910
4413
  return __generator(this, function (_g) {
3911
4414
  switch (_g.label) {
3912
4415
  case 0:
4416
+ inputParameters = options.inputParameters, tools = options.tools, onProgress = options.onProgress, pipeline = options.pipeline, setPreparedPipeline = options.setPreparedPipeline, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
4417
+ maxParallelCount = settings.maxParallelCount, isVerbose = settings.isVerbose;
4418
+ preparedPipeline = options.preparedPipeline;
4419
+ llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3913
4420
  if (!(preparedPipeline === undefined)) return [3 /*break*/, 2];
3914
4421
  return [4 /*yield*/, preparePipeline(pipeline, {
3915
4422
  llmTools: llmTools,
@@ -3918,6 +4425,7 @@
3918
4425
  })];
3919
4426
  case 1:
3920
4427
  preparedPipeline = _g.sent();
4428
+ setPreparedPipeline(preparedPipeline);
3921
4429
  _g.label = 2;
3922
4430
  case 2:
3923
4431
  errors = [];
@@ -3987,7 +4495,7 @@
3987
4495
  return name === parameterName;
3988
4496
  });
3989
4497
  if (!(parameter === undefined)) return [3 /*break*/, 1];
3990
- warnings.push(new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
4498
+ warnings.push(new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Extra parameter {".concat(parameterName, "} is being passed which is not part of the pipeline.\n\n ").concat(block(pipelineIdentification), "\n "); })));
3991
4499
  return [3 /*break*/, 4];
3992
4500
  case 1:
3993
4501
  if (!(parameter.isInput === false)) return [3 /*break*/, 4];
@@ -3999,10 +4507,10 @@
3999
4507
  // Note: Wait a short time to prevent race conditions
4000
4508
  _h.sent();
4001
4509
  _h.label = 3;
4002
- case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim.spaceTrim(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
4510
+ case 3: return [2 /*return*/, { value: $asDeeplyFrozenSerializableJson(spaceTrim.spaceTrim(function (block) { return "\n Unuccessful PipelineExecutorResult (with extra parameter {".concat(parameter.name, "}) PipelineExecutorResult\n\n ").concat(block(pipelineIdentification), "\n "); }), {
4003
4511
  isSuccessful: false,
4004
4512
  errors: __spreadArray([
4005
- new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
4513
+ new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Parameter {".concat(parameter.name, "} is passed as input parameter but it is not input\n\n ").concat(block(pipelineIdentification), "\n "); }))
4006
4514
  ], __read(errors), false).map(serializeError),
4007
4515
  warnings: warnings.map(serializeError),
4008
4516
  executionReport: executionReport,
@@ -4066,7 +4574,7 @@
4066
4574
  case 0:
4067
4575
  if (loopLimit-- < 0) {
4068
4576
  // Note: Really UnexpectedError not LimitReachedError - this should be catched during validatePipeline
4069
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4577
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4070
4578
  }
4071
4579
  currentTemplate = unresovedTemplates_1.find(function (template) {
4072
4580
  return template.dependentParameterNames.every(function (name) {
@@ -4076,29 +4584,52 @@
4076
4584
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
4077
4585
  throw new UnexpectedError(
4078
4586
  // TODO: [🐎] DRY
4079
- spaceTrim.spaceTrim(function (block) { return "\n Can not resolve some parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Can not resolve:\n ").concat(block(unresovedTemplates_1
4587
+ spaceTrim.spaceTrim(function (block) { return "\n Can not resolve some parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Can not resolve:\n ").concat(block(unresovedTemplates_1
4080
4588
  .map(function (_a) {
4081
4589
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
4082
4590
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
4083
4591
  .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
4084
4592
  .join(' and '));
4085
4593
  })
4086
- .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 "); }));
4594
+ .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 "); }));
4087
4595
  case 1:
4088
4596
  if (!!currentTemplate) return [3 /*break*/, 3];
4089
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
4597
+ /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
4090
4598
  case 2:
4091
- /* [5] */ _j.sent();
4599
+ /* [🤹‍♂️] */ _j.sent();
4092
4600
  return [3 /*break*/, 4];
4093
4601
  case 3:
4094
4602
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
4095
- work_1 = executeSingleTemplate(currentTemplate)
4096
- .then(function () {
4603
+ work_1 = executeTemplate({
4604
+ currentTemplate: currentTemplate,
4605
+ preparedPipeline: preparedPipeline,
4606
+ parametersToPass: parametersToPass,
4607
+ tools: tools,
4608
+ llmTools: llmTools,
4609
+ onProgress: function (progress) {
4610
+ if (isReturned) {
4611
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress, null, 4)
4612
+ .split('\n')
4613
+ .map(function (line) { return "> ".concat(line); })
4614
+ .join('\n')), "\n "); }));
4615
+ }
4616
+ if (onProgress) {
4617
+ onProgress(progress);
4618
+ }
4619
+ },
4620
+ settings: settings,
4621
+ $executionReport: executionReport,
4622
+ pipelineIdentification: spaceTrim.spaceTrim(function (block) { return "\n ".concat(block(pipelineIdentification), "\n Template name: ").concat(currentTemplate.name, "\n Template title: ").concat(currentTemplate.title, "\n "); }),
4623
+ })
4624
+ .then(function (newParametersToPass) {
4625
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
4097
4626
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
4098
4627
  })
4099
4628
  .then(function () {
4100
4629
  resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
4101
4630
  });
4631
+ // <- Note: Errors are catched here [3]
4632
+ // 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
4102
4633
  resolving_1.push(work_1);
4103
4634
  _j.label = 4;
4104
4635
  case 4: return [2 /*return*/];
@@ -4125,7 +4656,12 @@
4125
4656
  var result = _a.result;
4126
4657
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
4127
4658
  })), false));
4128
- outputParameters_1 = filterJustOutputParameters();
4659
+ outputParameters_1 = filterJustOutputParameters({
4660
+ preparedPipeline: preparedPipeline,
4661
+ parametersToPass: parametersToPass,
4662
+ $warnings: warnings,
4663
+ pipelineIdentification: pipelineIdentification,
4664
+ });
4129
4665
  isReturned = true;
4130
4666
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
4131
4667
  // Note: Wait a short time to prevent race conditions
@@ -4148,7 +4684,12 @@
4148
4684
  var result = _a.result;
4149
4685
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
4150
4686
  })), false));
4151
- outputParameters = filterJustOutputParameters();
4687
+ outputParameters = filterJustOutputParameters({
4688
+ preparedPipeline: preparedPipeline,
4689
+ parametersToPass: parametersToPass,
4690
+ $warnings: warnings,
4691
+ pipelineIdentification: pipelineIdentification,
4692
+ });
4152
4693
  isReturned = true;
4153
4694
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
4154
4695
  // Note: Wait a short time to prevent race conditions
@@ -4168,22 +4709,65 @@
4168
4709
  })];
4169
4710
  }
4170
4711
  });
4171
- }); };
4172
- return pipelineExecutor;
4712
+ });
4173
4713
  }
4714
+
4174
4715
  /**
4175
- * TODO: !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
4176
- * TODO: Use isVerbose here (not only pass to `preparePipeline`)
4177
- * TODO: [🧠][🌳] Use here `countTotalUsage` and put preparation and prepared pipiline to report
4178
- * TODO: [🪂] Use maxParallelCount here (not only pass to `preparePipeline`)
4179
- * TODO: [♈] Probbably move expectations from templates to parameters
4180
- * TODO: [🧠] When not meet expectations in DIALOG_TEMPLATE, make some way to tell the user
4181
- * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
4182
- * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
4183
- * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
4184
- * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
4185
- * TODO: [🧠][💷] `assertsExecutionSuccessful` should be the method of `PipelineExecutor` result BUT maybe NOT to preserve pure JSON object
4716
+ * Creates executor function from pipeline and execution tools.
4717
+ *
4718
+ * @returns The executor function
4719
+ * @throws {PipelineLogicError} on logical error in the pipeline
4720
+ * @public exported from `@promptbook/core`
4186
4721
  */
4722
+ function createPipelineExecutor(options) {
4723
+ var _this = this;
4724
+ var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
4725
+ 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;
4726
+ validatePipeline(pipeline);
4727
+ var pipelineIdentification = (function () {
4728
+ // Note: This is a 😐 implementation of [🚞]
4729
+ var _ = [];
4730
+ if (pipeline.sourceFile !== undefined) {
4731
+ _.push("File: ".concat(pipeline.sourceFile));
4732
+ }
4733
+ if (pipeline.pipelineUrl !== undefined) {
4734
+ _.push("Url: ".concat(pipeline.pipelineUrl));
4735
+ }
4736
+ return _.join('\n');
4737
+ })();
4738
+ var preparedPipeline;
4739
+ if (isPipelinePrepared(pipeline)) {
4740
+ preparedPipeline = pipeline;
4741
+ }
4742
+ else if (isNotPreparedWarningSupressed !== true) {
4743
+ console.warn(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
4744
+ }
4745
+ var runCount = 0;
4746
+ var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4747
+ return __generator(this, function (_a) {
4748
+ runCount++;
4749
+ return [2 /*return*/, /* not await */ executePipeline({
4750
+ pipeline: pipeline,
4751
+ preparedPipeline: preparedPipeline,
4752
+ setPreparedPipeline: function (newPreparedPipeline) {
4753
+ preparedPipeline = newPreparedPipeline;
4754
+ },
4755
+ inputParameters: inputParameters,
4756
+ tools: tools,
4757
+ onProgress: onProgress,
4758
+ pipelineIdentification: spaceTrim.spaceTrim(function (block) { return "\n ".concat(block(pipelineIdentification), "\n ").concat(runCount === 1 ? '' : "Run #".concat(runCount), "\n "); }),
4759
+ settings: {
4760
+ maxExecutionAttempts: maxExecutionAttempts,
4761
+ maxParallelCount: maxParallelCount,
4762
+ csvSettings: csvSettings,
4763
+ isVerbose: isVerbose,
4764
+ isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4765
+ },
4766
+ })];
4767
+ });
4768
+ }); };
4769
+ return pipelineExecutor;
4770
+ }
4187
4771
 
4188
4772
  /**
4189
4773
  * @@@
@@ -4235,7 +4819,7 @@
4235
4819
  outputParameters = result.outputParameters;
4236
4820
  knowledgePiecesRaw = outputParameters.knowledgePieces;
4237
4821
  knowledgeTextPieces = (knowledgePiecesRaw || '').split('\n---\n');
4238
- // <- TODO: !!!!! Smarter split and filter out empty pieces
4822
+ // <- TODO:[main] !!!!! Smarter split and filter out empty pieces
4239
4823
  if (isVerbose) {
4240
4824
  console.info('knowledgeTextPieces:', knowledgeTextPieces);
4241
4825
  }
@@ -4293,8 +4877,13 @@
4293
4877
  case 6: return [3 /*break*/, 8];
4294
4878
  case 7:
4295
4879
  error_1 = _c.sent();
4880
+ // Note: Here is expected error:
4881
+ // > PipelineExecutionError: You have not provided any `LlmExecutionTools` that support model variant "EMBEDDING
4882
+ if (!(error_1 instanceof PipelineExecutionError)) {
4883
+ throw error_1;
4884
+ }
4296
4885
  // TODO: [🟥] Detect browser / node and make it colorfull
4297
- console.error(error_1);
4886
+ console.error(error_1, "<- Note: This error is not critical to prepare the pipeline, just knowledge pieces won't have embeddings");
4298
4887
  return [3 /*break*/, 8];
4299
4888
  case 8: return [2 /*return*/, {
4300
4889
  name: name,
@@ -4315,7 +4904,7 @@
4315
4904
  });
4316
4905
  }
4317
4906
  /**
4318
- * TODO: [🐝][🔼] !!! Export via `@promptbook/markdown`
4907
+ * TODO: [🐝][🔼][main] !!! Export via `@promptbook/markdown`
4319
4908
  * TODO: [🪂] Do it in parallel 11:11
4320
4909
  * Note: No need to aggregate usage here, it is done by intercepting the llmTools
4321
4910
  */
@@ -4339,7 +4928,7 @@
4339
4928
  var partialPieces, pieces;
4340
4929
  return __generator(this, function (_a) {
4341
4930
  switch (_a.label) {
4342
- case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝] !!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
4931
+ case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝][main] !!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
4343
4932
  options)];
4344
4933
  case 1:
4345
4934
  partialPieces = _a.sent();
@@ -4531,7 +5120,7 @@
4531
5120
  });
4532
5121
  }
4533
5122
  /**
4534
- * TODO: [🔃] !!!!! If the persona was prepared with different version or different set of models, prepare it once again
5123
+ * TODO: [🔃][main] !!!!! If the persona was prepared with different version or different set of models, prepare it once again
4535
5124
  * TODO: [🏢] !! Check validity of `modelName` in pipeline
4536
5125
  * TODO: [🏢] !! Check validity of `systemMessage` in pipeline
4537
5126
  * TODO: [🏢] !! Check validity of `temperature` in pipeline
@@ -4580,7 +5169,7 @@
4580
5169
  case 0:
4581
5170
  _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a;
4582
5171
  templates = pipeline.templates, parameters = pipeline.parameters, knowledgePiecesCount = pipeline.knowledgePiecesCount;
4583
- // TODO: !!!!! Apply samples to each template (if missing and is for the template defined)
5172
+ // TODO:[main] !!!!! Apply samples to each template (if missing and is for the template defined)
4584
5173
  TODO_USE(parameters);
4585
5174
  templatesPrepared = new Array(
4586
5175
  // <- TODO: [🧱] Implement in a functional (not new Class) way
@@ -4612,7 +5201,7 @@
4612
5201
  /**
4613
5202
  * TODO: [🧠] Add context to each template (if missing)
4614
5203
  * TODO: [🧠] What is better name `prepareTemplate` or `prepareTemplateAndParameters`
4615
- * TODO: [♨] !!! Prepare index the samples and maybe templates
5204
+ * TODO: [♨][main] !!! Prepare index the samples and maybe templates
4616
5205
  * TODO: Write tests for `preparePipeline`
4617
5206
  * TODO: [🏏] Leverage the batch API and build queues @see https://platform.openai.com/docs/guides/batch
4618
5207
  * TODO: [🧊] In future one preparation can take data from previous preparation and save tokens and time
@@ -4784,7 +5373,7 @@
4784
5373
  if (sourceContent === '') {
4785
5374
  throw new ParseError("Source is not defined");
4786
5375
  }
4787
- // TODO: !!!! Following checks should be applied every link in the `sourceContent`
5376
+ // TODO:[main] !!!! Following checks should be applied every link in the `sourceContent`
4788
5377
  if (sourceContent.startsWith('http://')) {
4789
5378
  throw new ParseError("Source is not secure");
4790
5379
  }
@@ -4969,7 +5558,7 @@
4969
5558
  if (command.templateType === 'KNOWLEDGE') {
4970
5559
  knowledgeCommandParser.$applyToPipelineJson({
4971
5560
  type: 'KNOWLEDGE',
4972
- sourceContent: $templateJson.content, // <- TODO: [🐝] !!! Work with KNOWLEDGE which not referring to the source file or website, but its content itself
5561
+ sourceContent: $templateJson.content, // <- TODO: [🐝][main] !!! Work with KNOWLEDGE which not referring to the source file or website, but its content itself
4973
5562
  }, $pipelineJson);
4974
5563
  $templateJson.isTemplate = false;
4975
5564
  return;
@@ -5319,6 +5908,171 @@
5319
5908
  * TODO: [🌺] Use some intermediate util splitWords
5320
5909
  */
5321
5910
 
5911
+ /**
5912
+ * @@@
5913
+ *
5914
+ * @param text @@@
5915
+ * @param _isFirstLetterCapital @@@
5916
+ * @returns @@@
5917
+ * @example 'helloWorld'
5918
+ * @example 'iLovePromptbook'
5919
+ * @public exported from `@promptbook/utils`
5920
+ */
5921
+ function normalizeTo_camelCase(text, _isFirstLetterCapital) {
5922
+ var e_1, _a;
5923
+ if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
5924
+ var charType;
5925
+ var lastCharType = null;
5926
+ var normalizedName = '';
5927
+ try {
5928
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5929
+ var char = text_1_1.value;
5930
+ var normalizedChar = void 0;
5931
+ if (/^[a-z]$/.test(char)) {
5932
+ charType = 'LOWERCASE';
5933
+ normalizedChar = char;
5934
+ }
5935
+ else if (/^[A-Z]$/.test(char)) {
5936
+ charType = 'UPPERCASE';
5937
+ normalizedChar = char.toLowerCase();
5938
+ }
5939
+ else if (/^[0-9]$/.test(char)) {
5940
+ charType = 'NUMBER';
5941
+ normalizedChar = char;
5942
+ }
5943
+ else {
5944
+ charType = 'OTHER';
5945
+ normalizedChar = '';
5946
+ }
5947
+ if (!lastCharType) {
5948
+ if (_isFirstLetterCapital) {
5949
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
5950
+ }
5951
+ }
5952
+ else if (charType !== lastCharType &&
5953
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
5954
+ !(lastCharType === 'NUMBER') &&
5955
+ !(charType === 'NUMBER')) {
5956
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
5957
+ }
5958
+ normalizedName += normalizedChar;
5959
+ lastCharType = charType;
5960
+ }
5961
+ }
5962
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5963
+ finally {
5964
+ try {
5965
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5966
+ }
5967
+ finally { if (e_1) throw e_1.error; }
5968
+ }
5969
+ return normalizedName;
5970
+ }
5971
+ /**
5972
+ * TODO: [🌺] Use some intermediate util splitWords
5973
+ */
5974
+
5975
+ /**
5976
+ * Removes quotes from a string
5977
+ *
5978
+ * Tip: This is very usefull for post-processing of the result of the LLM model
5979
+ * Note: This function removes only the same quotes from the beginning and the end of the string
5980
+ * Note: There are two simmilar functions:
5981
+ * - `removeQuotes` which removes only bounding quotes
5982
+ * - `unwrapResult` which removes whole introduce sentence
5983
+ *
5984
+ * @param text optionally quoted text
5985
+ * @returns text without quotes
5986
+ * @public exported from `@promptbook/utils`
5987
+ */
5988
+ function removeQuotes(text) {
5989
+ if (text.startsWith('"') && text.endsWith('"')) {
5990
+ return text.slice(1, -1);
5991
+ }
5992
+ if (text.startsWith('\'') && text.endsWith('\'')) {
5993
+ return text.slice(1, -1);
5994
+ }
5995
+ return text;
5996
+ }
5997
+
5998
+ /**
5999
+ * Function `validateParameterName` will @@@
6000
+ *
6001
+ * @param parameterName @@@
6002
+ * @returns @@@
6003
+ * @throws {ParseError} @@@
6004
+ * @private within the repository
6005
+ */
6006
+ function validateParameterName(parameterName) {
6007
+ var e_1, _a;
6008
+ var rawParameterName = parameterName;
6009
+ try {
6010
+ for (var _b = __values([
6011
+ ['`', '`'],
6012
+ ['{', '}'],
6013
+ ['[', ']'],
6014
+ ['(', ')'],
6015
+ ['<', '>'],
6016
+ ]), _c = _b.next(); !_c.done; _c = _b.next()) {
6017
+ var _d = __read(_c.value, 2), start = _d[0], end = _d[1];
6018
+ if (parameterName.substring(0, 1) === start &&
6019
+ parameterName.substring(parameterName.length - 1, parameterName.length) === end
6020
+ // <- TODO: More universal that 1 character
6021
+ ) {
6022
+ parameterName = parameterName.substring(1, parameterName.length - 1);
6023
+ // <- TODO: More universal that 1 character
6024
+ }
6025
+ }
6026
+ }
6027
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
6028
+ finally {
6029
+ try {
6030
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
6031
+ }
6032
+ finally { if (e_1) throw e_1.error; }
6033
+ }
6034
+ // TODO: [🐠] Following try-catch block should be part of common validators logic
6035
+ try {
6036
+ /*
6037
+ Note: We don't need to check for spaces because we are going to normalize the parameter name to camelCase
6038
+ if (parameterName.includes(' ')) {
6039
+ throw new ParseError(`Parameter name cannot contain spaces`);
6040
+ }
6041
+ */
6042
+ if (parameterName.includes('.')) {
6043
+ throw new ParseError("Parameter name cannot contain dots");
6044
+ }
6045
+ if (parameterName.includes('/') || parameterName.includes('\\')) {
6046
+ throw new ParseError("Parameter name cannot contain slashes");
6047
+ }
6048
+ if (parameterName.includes('(') ||
6049
+ parameterName.includes(')') ||
6050
+ parameterName.includes('{') ||
6051
+ parameterName.includes('}') ||
6052
+ parameterName.includes('[') ||
6053
+ parameterName.includes(']')) {
6054
+ throw new ParseError("Parameter name cannot contain braces");
6055
+ }
6056
+ parameterName = removeDiacritics(parameterName);
6057
+ parameterName = removeEmojis(parameterName);
6058
+ parameterName = removeQuotes(parameterName);
6059
+ parameterName = normalizeTo_camelCase(parameterName);
6060
+ if (parameterName === '') {
6061
+ throw new ParseError("Parameter name cannot be empty");
6062
+ }
6063
+ if (RESERVED_PARAMETER_NAMES.includes(parameterName)) {
6064
+ throw new ParseError("{".concat(parameterName, "} is a reserved parameter name"));
6065
+ }
6066
+ }
6067
+ catch (error) {
6068
+ if (!(error instanceof ParseError)) {
6069
+ throw error;
6070
+ }
6071
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n ".concat(block(error.message), "\n\n Tried to validate parameter name:\n ").concat(block(rawParameterName), "\n "); }));
6072
+ }
6073
+ return parameterName;
6074
+ }
6075
+
5322
6076
  /**
5323
6077
  * Parses the foreach command
5324
6078
  *
@@ -5348,15 +6102,16 @@
5348
6102
  /**
5349
6103
  * Link to discussion
5350
6104
  */
5351
- documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/@@',
6105
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/148',
5352
6106
  /**
5353
6107
  * Example usages of the FOREACH command
5354
6108
  */
5355
6109
  examples: [
5356
- 'FOREACH List Line `{customers}` -> `{customer}`',
5357
- 'FOR List Line `{customers}` -> `{customer}`',
5358
- 'EACH List Line `{customers}` -> `{customer}`',
5359
- // <- TODO: [🍭] !!!!!! More
6110
+ 'FOREACH Text Line `{customers}` -> `{customer}`',
6111
+ 'FOREACH Csv Cell `{customers}` -> `{cell}`',
6112
+ 'FOREACH Csv Row `{customers}` -> `{firstName}`, `{lastName}`, `+{email}`',
6113
+ 'FOR Text Line `{customers}` -> `{customer}`',
6114
+ 'EACH Text Line `{customers}` -> `{customer}`',
5360
6115
  ],
5361
6116
  /**
5362
6117
  * Parses the FOREACH command
@@ -5364,55 +6119,75 @@
5364
6119
  parse: function (input) {
5365
6120
  var args = input.args;
5366
6121
  var formatName = normalizeTo_SCREAMING_CASE(args[0] || '');
5367
- var cellName = normalizeTo_SCREAMING_CASE(args[1] || '');
5368
- var parameterNameWrapped = args[2];
6122
+ var subformatName = normalizeTo_SCREAMING_CASE(args[1] || '');
6123
+ var parameterNameArg = args[2] || '';
5369
6124
  var assignSign = args[3];
5370
- var subparameterNameWrapped = args[4];
5371
- if (![
5372
- 'LIST',
5373
- 'CSV',
5374
- // <- TODO: [🏢] Unhardcode formats
5375
- ].includes(formatName)) {
5376
- console.info({ args: args, formatName: formatName });
5377
- throw new Error("Unsupported format \"".concat(formatName, "\""));
6125
+ var formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
6126
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(formatName);
6127
+ });
6128
+ if (formatDefinition === undefined) {
6129
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Unsupported format \"".concat(formatName, "\"\n\n Available formats:\n ").concat(block(FORMAT_DEFINITIONS.map(function (formatDefinition) { return formatDefinition.formatName; })
6130
+ .map(function (formatName) { return "- ".concat(formatName); })
6131
+ .join('\n')), "\n "); }));
5378
6132
  // <- TODO: [🏢] List all supported format names
5379
6133
  }
5380
- if (![
5381
- 'LINE',
5382
- 'ROW',
5383
- 'COLUMN',
5384
- 'CELL',
5385
- // <- TODO: [🏢] Unhardcode format cells
5386
- ].includes(cellName)) {
5387
- console.info({ args: args, cellName: cellName });
5388
- throw new Error("Format ".concat(formatName, " does not support cell \"").concat(cellName, "\""));
5389
- // <- TODO: [🏢] List all supported cell names for the format
6134
+ var subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
6135
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(subformatName);
6136
+ });
6137
+ if (subvalueDefinition === undefined) {
6138
+ throw new ParseError(spaceTrim__default["default"](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
6139
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
6140
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
6141
+ .join('\n')), "\n "); }));
6142
+ // <- TODO: [🏢] List all supported subformat names for the format
5390
6143
  }
5391
6144
  if (assignSign !== '->') {
5392
- console.info({ args: args, assignSign: assignSign });
5393
- throw new Error("FOREACH command must have '->' to assign the value to the parameter");
5394
- }
5395
- // TODO: !!!!!! Replace with propper parameter name validation
5396
- if ((parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(0, 1)) !== '{' ||
5397
- (parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(parameterNameWrapped.length - 1, parameterNameWrapped.length)) !== '}') {
5398
- console.info({ args: args, parameterNameWrapped: parameterNameWrapped }, parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(0, 1), parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(parameterNameWrapped.length - 1, parameterNameWrapped.length));
5399
- throw new Error("!!!!!! 1 Here will be error (with rules and precise error) from validateParameterName");
5400
- }
5401
- var parameterName = parameterNameWrapped.substring(1, parameterNameWrapped.length - 1);
5402
- // TODO: !!!!!! Replace with propper parameter name validation
5403
- if ((subparameterNameWrapped === null || subparameterNameWrapped === void 0 ? void 0 : subparameterNameWrapped.substring(0, 1)) !== '{' ||
5404
- (subparameterNameWrapped === null || subparameterNameWrapped === void 0 ? void 0 : subparameterNameWrapped.substring(subparameterNameWrapped.length - 1, subparameterNameWrapped.length)) !==
5405
- '}') {
5406
- console.info({ args: args, subparameterNameWrapped: subparameterNameWrapped });
5407
- throw new Error("!!!!!! 2 Here will be error (with rules and precise error) from validateParameterName");
5408
- }
5409
- var subparameterName = subparameterNameWrapped.substring(1, subparameterNameWrapped.length - 1);
6145
+ throw new ParseError("FOREACH command must have '->' to assign the value to the parameter");
6146
+ }
6147
+ var parameterName = validateParameterName(parameterNameArg);
6148
+ var outputSubparameterName = null;
6149
+ // TODO: [4] DRY
6150
+ var inputSubparameterNames = args
6151
+ .slice(4)
6152
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
6153
+ .filter(function (parameterName) { return !parameterName.includes('+'); })
6154
+ .filter(function (parameterName) { return parameterName !== ''; })
6155
+ .map(validateParameterName);
6156
+ // TODO: [4] DRY
6157
+ var outputSubparameterNames = args
6158
+ .slice(4)
6159
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
6160
+ .filter(function (parameterName) { return parameterName.includes('+'); })
6161
+ .map(function (parameterName) { return parameterName.split('+').join(''); })
6162
+ .map(validateParameterName);
6163
+ if (outputSubparameterNames.length === 1) {
6164
+ outputSubparameterName = outputSubparameterNames[0];
6165
+ }
6166
+ else if (outputSubparameterNames.length > 1) {
6167
+ throw new ParseError("FOREACH command can not have more than one output subparameter");
6168
+ }
6169
+ if (inputSubparameterNames.length === 0) {
6170
+ throw new ParseError("FOREACH command must have at least one input subparameter");
6171
+ }
6172
+ if (outputSubparameterName === null) {
6173
+ // TODO: Following code should be unhardcoded from here and moved to the format definition
6174
+ if (formatName === 'CSV' && subformatName === 'CELL') {
6175
+ outputSubparameterName = 'newCell';
6176
+ }
6177
+ else if (formatName === 'TEXT' && subformatName === 'LINE') {
6178
+ outputSubparameterName = 'newLine';
6179
+ }
6180
+ else {
6181
+ throw new ParseError(spaceTrim__default["default"]("\n FOREACH ".concat(formatName, " ").concat(subformatName, " must specify output subparameter\n\n Correct example:\n - FOREACH ").concat(formatName, " ").concat(subformatName, " {").concat(parameterName, "} -> {inputSubparameterName1}, {inputSubparameterName2}, +{outputSubparameterName}\n\n ")));
6182
+ }
6183
+ }
5410
6184
  return {
5411
6185
  type: 'FOREACH',
5412
6186
  formatName: formatName,
5413
- cellName: cellName,
6187
+ subformatName: subformatName,
5414
6188
  parameterName: parameterName,
5415
- subparameterName: subparameterName,
6189
+ inputSubparameterNames: inputSubparameterNames,
6190
+ outputSubparameterName: outputSubparameterName,
5416
6191
  };
5417
6192
  },
5418
6193
  /**
@@ -5421,9 +6196,17 @@
5421
6196
  * Note: `$` is used to indicate that this function mutates given `templateJson`
5422
6197
  */
5423
6198
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5424
- var formatName = command.formatName, cellName = command.cellName, parameterName = command.parameterName, subparameterName = command.subparameterName;
5425
- $templateJson.foreach = { formatName: formatName, cellName: cellName, parameterName: parameterName, subparameterName: subparameterName };
5426
- keepUnused($pipelineJson); // <- TODO: !!!!!! BUT Maybe register subparameter from foreach into parameters of the pipeline
6199
+ var formatName = command.formatName, subformatName = command.subformatName, parameterName = command.parameterName, inputSubparameterNames = command.inputSubparameterNames, outputSubparameterName = command.outputSubparameterName;
6200
+ // TODO: [🍭] Detect double use
6201
+ // TODO: [🍭] Detect usage with JOKER and don't allow it
6202
+ $templateJson.foreach = {
6203
+ formatName: formatName,
6204
+ subformatName: subformatName,
6205
+ parameterName: parameterName,
6206
+ inputSubparameterNames: inputSubparameterNames,
6207
+ outputSubparameterName: outputSubparameterName,
6208
+ };
6209
+ keepUnused($pipelineJson); // <- TODO: [🧠] Maybe register subparameter from foreach into parameters of the pipeline
5427
6210
  // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase
5428
6211
  },
5429
6212
  /**
@@ -5446,8 +6229,7 @@
5446
6229
  },
5447
6230
  };
5448
6231
  /**
5449
- * TODO: !!!!!! Comment console logs
5450
- * TODO: [🍭] !!!!!! Make .ptbk.md file with examples of the FOREACH command and also with wrong parsing and logic
6232
+ * TODO: [🍭] Make .ptbk.md file with examples of the FOREACH with wrong parsing and logic
5451
6233
  */
5452
6234
 
5453
6235
  /**
@@ -5557,12 +6339,11 @@
5557
6339
  */
5558
6340
  parse: function (input) {
5559
6341
  var args = input.args;
5560
- // TODO: !!!!!! Replace with propper parameter name validation
5561
- var parametersMatch = (args.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
5562
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5563
- throw new ParseError("Invalid joker");
6342
+ if (args.length !== 1) {
6343
+ throw new ParseError("JOKE command expects exactly one parameter name");
5564
6344
  }
5565
- var parameterName = parametersMatch.groups.parameterName;
6345
+ var parameterNameArg = args[0] || '';
6346
+ var parameterName = validateParameterName(parameterNameArg);
5566
6347
  return {
5567
6348
  type: 'JOKER',
5568
6349
  parameterName: parameterName,
@@ -5637,6 +6418,9 @@
5637
6418
  */
5638
6419
  parse: function (input) {
5639
6420
  var args = input.args, normalized = input.normalized;
6421
+ var availableVariantsMessage = spaceTrim__default["default"](function (block) { return "\n Available variants are:\n ".concat(block(MODEL_VARIANTS.map(function (variantName) {
6422
+ return "- ".concat(variantName).concat(variantName !== 'EMBEDDING' ? '' : ' (Not available in pipeline)');
6423
+ }).join('\n')), "\n "); });
5640
6424
  // TODO: Make this more elegant and dynamically
5641
6425
  if (normalized.startsWith('MODEL_VARIANT')) {
5642
6426
  if (normalized === 'MODEL_VARIANT_CHAT') {
@@ -5652,17 +6436,13 @@
5652
6436
  key: 'modelVariant',
5653
6437
  value: 'COMPLETION',
5654
6438
  };
6439
+ // <- Note: [🤖]
5655
6440
  }
5656
6441
  else if (normalized.startsWith('MODEL_VARIANT_EMBED')) {
5657
- return {
5658
- type: 'MODEL',
5659
- key: 'modelVariant',
5660
- value: 'EMBEDDING',
5661
- };
5662
- // <- Note: [🤖]
6442
+ spaceTrim__default["default"](function (block) { return "\n Embedding model can not be used in pipeline\n\n ".concat(block(availableVariantsMessage), "\n "); });
5663
6443
  }
5664
6444
  else {
5665
- throw new ParseError(spaceTrim__default["default"](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 "); }));
6445
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Unknown model variant in command:\n\n ".concat(block(availableVariantsMessage), "\n "); }));
5666
6446
  }
5667
6447
  }
5668
6448
  if (normalized.startsWith('MODEL_NAME')) {
@@ -5787,14 +6567,13 @@
5787
6567
  * Parses the PARAMETER command
5788
6568
  */
5789
6569
  parse: function (input) {
5790
- var normalized = input.normalized, raw = input.raw;
5791
- var parametersMatch = raw.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
5792
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5793
- throw new ParseError("Invalid parameter");
5794
- }
5795
- var _a = parametersMatch.groups, parameterName = _a.parameterName, parameterDescription = _a.parameterDescription;
5796
- if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
5797
- throw new ParseError("Parameter {".concat(parameterName, "} can not contain another parameter in description"));
6570
+ var normalized = input.normalized, args = input.args, raw = input.raw;
6571
+ var parameterNameRaw = args.shift() || '';
6572
+ var parameterDescriptionRaw = args.join(' ');
6573
+ // <- TODO: When [🥶] fixed, change to:
6574
+ // > const parameterDescriptionRaw = rawArgs.split(parameterNameRaw).join('').trim();
6575
+ if (parameterDescriptionRaw && parameterDescriptionRaw.match(/\{(?<embeddedParameterName>[a-z0-9_]+)\}/im)) {
6576
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Parameter {".concat(parameterNameRaw, "} can not contain another parameter in description\n\n The description:\n ").concat(block(parameterDescriptionRaw), "\n "); }));
5798
6577
  }
5799
6578
  var isInput = normalized.startsWith('INPUT');
5800
6579
  var isOutput = normalized.startsWith('OUTPUT');
@@ -5802,11 +6581,12 @@
5802
6581
  isInput = false;
5803
6582
  isOutput = false;
5804
6583
  }
5805
- // TODO: !!!!!! Add parameter name validation
6584
+ var parameterName = validateParameterName(parameterNameRaw);
6585
+ var parameterDescription = parameterDescriptionRaw.trim() || null;
5806
6586
  return {
5807
6587
  type: 'PARAMETER',
5808
6588
  parameterName: parameterName,
5809
- parameterDescription: parameterDescription.trim() || null,
6589
+ parameterDescription: parameterDescription,
5810
6590
  isInput: isInput,
5811
6591
  isOutput: isOutput,
5812
6592
  };
@@ -6131,6 +6911,7 @@
6131
6911
  * Note: `$` is used to indicate that this function mutates given `pipelineJson`
6132
6912
  */
6133
6913
  $applyToPipelineJson: function (command, $pipelineJson) {
6914
+ // TODO: Warn if the version is overridden
6134
6915
  $pipelineJson.promptbookVersion = command.promptbookVersion;
6135
6916
  },
6136
6917
  /**
@@ -6613,7 +7394,9 @@
6613
7394
  for (var commandNameSegmentsCount = 0; commandNameSegmentsCount < Math.min(items.length, 3); commandNameSegmentsCount++) {
6614
7395
  var commandNameRaw = items.slice(0, commandNameSegmentsCount + 1).join('_');
6615
7396
  var args = items.slice(commandNameSegmentsCount + 1);
6616
- var rawArgs = raw.substring(commandNameRaw.length).trim();
7397
+ var rawArgs = raw
7398
+ .substring(commandNameRaw.length)
7399
+ .trim();
6617
7400
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6618
7401
  if (command !== null) {
6619
7402
  return command;
@@ -6624,7 +7407,9 @@
6624
7407
  {
6625
7408
  var commandNameRaw = items.slice(-1).join('_');
6626
7409
  var args = items.slice(0, -1); // <- Note: This is probbably not correct
6627
- var rawArgs = raw.substring(0, raw.length - commandNameRaw.length).trim();
7410
+ var rawArgs = raw
7411
+ .substring(0, raw.length - commandNameRaw.length)
7412
+ .trim();
6628
7413
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6629
7414
  if (command !== null) {
6630
7415
  return command;
@@ -6764,7 +7549,7 @@
6764
7549
  function extractOneBlockFromMarkdown(markdown) {
6765
7550
  var codeBlocks = extractAllBlocksFromMarkdown(markdown);
6766
7551
  if (codeBlocks.length !== 1) {
6767
- throw new ParseError(spaceTrim__default["default"](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 "); }));
7552
+ throw new ParseError(spaceTrim__default["default"](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 "); }));
6768
7553
  }
6769
7554
  return codeBlocks[0];
6770
7555
  }
@@ -6951,7 +7736,7 @@
6951
7736
  var $pipelineJson = {
6952
7737
  title: undefined /* <- Note: [🍙] Putting here placeholder to keep `title` on top at final JSON */,
6953
7738
  pipelineUrl: undefined /* <- Note: Putting here placeholder to keep `pipelineUrl` on top at final JSON */,
6954
- promptbookVersion: PROMPTBOOK_VERSION,
7739
+ promptbookVersion: undefined /* <- Note: By default no explicit version */,
6955
7740
  description: undefined /* <- Note: [🍙] Putting here placeholder to keep `description` on top at final JSON */,
6956
7741
  parameters: [],
6957
7742
  templates: [],
@@ -7242,7 +8027,7 @@
7242
8027
  return $asDeeplyFrozenSerializableJson('pipelineJson', $pipelineJson);
7243
8028
  }
7244
8029
  /**
7245
- * TODO: !!!! Warn if used only sync version
8030
+ * TODO:[main] !!!! Warn if used only sync version
7246
8031
  * TODO: [🚞] Report here line/column of error
7247
8032
  * TODO: Use spaceTrim more effectively
7248
8033
  * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
@@ -7323,70 +8108,6 @@
7323
8108
  * TODO: [🏛] This can be part of markdown builder
7324
8109
  */
7325
8110
 
7326
- /**
7327
- * @@@
7328
- *
7329
- * @param text @@@
7330
- * @param _isFirstLetterCapital @@@
7331
- * @returns @@@
7332
- * @example 'helloWorld'
7333
- * @example 'iLovePromptbook'
7334
- * @public exported from `@promptbook/utils`
7335
- */
7336
- function normalizeTo_camelCase(text, _isFirstLetterCapital) {
7337
- var e_1, _a;
7338
- if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
7339
- var charType;
7340
- var lastCharType = null;
7341
- var normalizedName = '';
7342
- try {
7343
- for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
7344
- var char = text_1_1.value;
7345
- var normalizedChar = void 0;
7346
- if (/^[a-z]$/.test(char)) {
7347
- charType = 'LOWERCASE';
7348
- normalizedChar = char;
7349
- }
7350
- else if (/^[A-Z]$/.test(char)) {
7351
- charType = 'UPPERCASE';
7352
- normalizedChar = char.toLowerCase();
7353
- }
7354
- else if (/^[0-9]$/.test(char)) {
7355
- charType = 'NUMBER';
7356
- normalizedChar = char;
7357
- }
7358
- else {
7359
- charType = 'OTHER';
7360
- normalizedChar = '';
7361
- }
7362
- if (!lastCharType) {
7363
- if (_isFirstLetterCapital) {
7364
- normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
7365
- }
7366
- }
7367
- else if (charType !== lastCharType &&
7368
- !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
7369
- !(lastCharType === 'NUMBER') &&
7370
- !(charType === 'NUMBER')) {
7371
- normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
7372
- }
7373
- normalizedName += normalizedChar;
7374
- lastCharType = charType;
7375
- }
7376
- }
7377
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
7378
- finally {
7379
- try {
7380
- if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
7381
- }
7382
- finally { if (e_1) throw e_1.error; }
7383
- }
7384
- return normalizedName;
7385
- }
7386
- /**
7387
- * TODO: [🌺] Use some intermediate util splitWords
7388
- */
7389
-
7390
8111
  /**
7391
8112
  * Creates a Mermaid graph based on the promptbook
7392
8113
  *
@@ -7443,9 +8164,9 @@
7443
8164
  return promptbookMermaid;
7444
8165
  }
7445
8166
  /**
7446
- * TODO: !!!!!! FOREACH in mermaid graph
7447
- * TODO: !!!!!! Knowledge in mermaid graph
7448
- * TODO: !!!!!! Personas in mermaid graph
8167
+ * TODO: !!!!! FOREACH in mermaid graph
8168
+ * TODO: !!!!! Knowledge in mermaid graph
8169
+ * TODO: !!!!! Personas in mermaid graph
7449
8170
  * TODO: Maybe use some Mermaid package instead of string templating
7450
8171
  * TODO: [🕌] When more than 2 functionalities, split into separate functions
7451
8172
  */
@@ -7520,7 +8241,7 @@
7520
8241
  }
7521
8242
  }
7522
8243
  /**
7523
- * TODO: [🧠] !!! In-memory cache of same values to prevent multiple checks
8244
+ * TODO: [🧠][main] !!! In-memory cache of same values to prevent multiple checks
7524
8245
  * TODO: [🧠][💺] Can be done this on type-level?
7525
8246
  */
7526
8247
 
@@ -7587,21 +8308,41 @@
7587
8308
  * @public exported from `@promptbook/core`
7588
8309
  */
7589
8310
  function usageToHuman(usage) {
7590
- var report = 'Usage:';
8311
+ var reportItems = [];
7591
8312
  var uncertainNumberToHuman = function (_a) {
7592
8313
  var value = _a.value, isUncertain = _a.isUncertain;
7593
8314
  return "".concat(isUncertain ? 'approximately ' : '').concat(Math.round(value * 100) / 100);
7594
8315
  };
7595
- report += '\n' + "- Cost ".concat(uncertainNumberToHuman(usage.price), " USD");
7596
- report += '\n' + "- Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time");
7597
- return spaceTrim__default["default"](report);
8316
+ if (usage.price.value > 0.01
8317
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻] Configure negligible value - default value to config + value to `UsageToHumanSettings`
8318
+ ) {
8319
+ reportItems.push("Cost ".concat(uncertainNumberToHuman(usage.price), " USD"));
8320
+ }
8321
+ else {
8322
+ reportItems.push("Negligible cost");
8323
+ }
8324
+ var worktime = usageToWorktime(usage);
8325
+ if (worktime.value >
8326
+ 1 / 60
8327
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻]
8328
+ ) {
8329
+ reportItems.push("Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time"));
8330
+ // TODO: [🍓][🧞‍♂️] Show minutes, seconds, days NOT 0.1 hours
8331
+ }
8332
+ if (usage.output.charactersCount.value > 0) {
8333
+ reportItems.push("Written ".concat(uncertainNumberToHuman(usage.output.charactersCount), " characters"));
8334
+ }
8335
+ if (reportItems.length === 0) {
8336
+ // Note: For negligible usage, we report at least something
8337
+ reportItems.push('Negligible');
8338
+ }
8339
+ return spaceTrim__default["default"](function (block) { return "\n Usage:\n ".concat(block(reportItems.map(function (item) { return "- ".concat(item); }).join('\n')), "\n "); });
7598
8340
  }
7599
8341
  /**
7600
- * TODO: Use "$1" not "1 USD"
7601
- * TODO: Use markdown formatting like "Cost approximately **$1**"
7602
- * TODO: Report in minutes, seconds, days NOT 0.1 hours
8342
+ * TODO: [🍓][🧞‍♂️] Use "$1" not "1 USD"
8343
+ * TODO: [🍓][🧞‍♂️] Use markdown formatting like "Cost approximately **$1**"
8344
+ * TODO: [🍓][🧞‍♂️] Report in minutes, seconds, days NOT 0.1 hours
7603
8345
  * TODO: [🧠] Maybe make from `uncertainNumberToHuman` separate exported utility
7604
- * TODO: When negligible usage, report "Negligible" or just don't report it
7605
8346
  * TODO: [🧠] Maybe use "~" instead of "approximately"
7606
8347
  * TODO: [🏛] Maybe make some markdown builder
7607
8348
  */
@@ -8250,8 +8991,8 @@
8250
8991
  */
8251
8992
  function createMarkdownTable(table) {
8252
8993
  var columnWidths = table.reduce(function (widths, row) {
8253
- row.forEach(function (cell, columnIndex) {
8254
- var cellLength = cell.length;
8994
+ row.forEach(function (subformat, columnIndex) {
8995
+ var cellLength = subformat.length;
8255
8996
  if (!widths[columnIndex] || cellLength > widths[columnIndex]) {
8256
8997
  widths[columnIndex] = cellLength;
8257
8998
  }
@@ -8259,12 +9000,12 @@
8259
9000
  return widths;
8260
9001
  }, []);
8261
9002
  var header = "| ".concat(table[0]
8262
- .map(function (cell, columnIndex) { return cell.padEnd(columnWidths[columnIndex]); })
9003
+ .map(function (subformat, columnIndex) { return subformat.padEnd(columnWidths[columnIndex]); })
8263
9004
  .join(' | '), " |");
8264
9005
  var separator = "|".concat(columnWidths.map(function (width) { return '-'.repeat(width + 2); }).join('|'), "|");
8265
9006
  var rows = table.slice(1).map(function (row) {
8266
- var paddedRow = row.map(function (cell, columnIndex) {
8267
- return cell.padEnd(columnWidths[columnIndex]);
9007
+ var paddedRow = row.map(function (subformat, columnIndex) {
9008
+ return subformat.padEnd(columnWidths[columnIndex]);
8268
9009
  });
8269
9010
  return "| ".concat(paddedRow.join(' | '), " |");
8270
9011
  });
@@ -8545,6 +9286,8 @@
8545
9286
  exports.CLAIM = CLAIM;
8546
9287
  exports.CallbackInterfaceTools = CallbackInterfaceTools;
8547
9288
  exports.CollectionError = CollectionError;
9289
+ exports.CsvFormatDefinition = CsvFormatDefinition;
9290
+ exports.DEFAULT_CSV_SETTINGS = DEFAULT_CSV_SETTINGS;
8548
9291
  exports.DEFAULT_REMOTE_URL = DEFAULT_REMOTE_URL;
8549
9292
  exports.DEFAULT_REMOTE_URL_PATH = DEFAULT_REMOTE_URL_PATH;
8550
9293
  exports.ERRORS = ERRORS;
@@ -8555,6 +9298,7 @@
8555
9298
  exports.ExpectError = ExpectError;
8556
9299
  exports.IS_VERBOSE = IS_VERBOSE;
8557
9300
  exports.LimitReachedError = LimitReachedError;
9301
+ exports.MANDATORY_CSV_SETTINGS = MANDATORY_CSV_SETTINGS;
8558
9302
  exports.MAX_EXECUTION_ATTEMPTS = MAX_EXECUTION_ATTEMPTS;
8559
9303
  exports.MAX_FILENAME_LENGTH = MAX_FILENAME_LENGTH;
8560
9304
  exports.MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH = MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH;
@@ -8573,6 +9317,7 @@
8573
9317
  exports.PrefixStorage = PrefixStorage;
8574
9318
  exports.RESERVED_PARAMETER_NAMES = RESERVED_PARAMETER_NAMES;
8575
9319
  exports.TemplateTypes = TemplateTypes;
9320
+ exports.TextFormatDefinition = TextFormatDefinition;
8576
9321
  exports.UnexpectedError = UnexpectedError;
8577
9322
  exports.ZERO_USAGE = ZERO_USAGE;
8578
9323
  exports._AnthropicClaudeMetadataRegistration = _AnthropicClaudeMetadataRegistration;