@promptbook/cli 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 +2039 -1249
  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 +2042 -1253
  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('commander'), require('spacetrim'), require('colors'), require('waitasecond'), require('fs/promises'), require('path'), require('prettier'), require('prettier/parser-html'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('path/posix'), require('dotenv'), require('glob-promise'), require('socket.io-client'), require('@anthropic-ai/sdk'), require('@azure/openai'), require('openai')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'commander', 'spacetrim', 'colors', 'waitasecond', 'fs/promises', 'path', 'prettier', 'prettier/parser-html', 'crypto-js/enc-hex', 'crypto-js/sha256', 'path/posix', 'dotenv', 'glob-promise', 'socket.io-client', '@anthropic-ai/sdk', '@azure/openai', 'openai'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-cli"] = {}, global.commander, global.spaceTrim, global.colors, global.waitasecond, global.promises, global.path, global.prettier, global.parserHtml, global.hexEncoder, global.sha256, global.posix, global.dotenv, global.glob, global.socket_ioClient, global.Anthropic, global.openai, global.OpenAI));
5
- })(this, (function (exports, commander, spaceTrim, colors, waitasecond, promises, path, prettier, parserHtml, hexEncoder, sha256, posix, dotenv, glob, socket_ioClient, Anthropic, openai, OpenAI) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('commander'), require('spacetrim'), require('colors'), require('waitasecond'), require('fs/promises'), require('path'), require('prettier'), require('prettier/parser-html'), require('papaparse'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('path/posix'), require('dotenv'), require('glob-promise'), require('socket.io-client'), require('@anthropic-ai/sdk'), require('@azure/openai'), require('openai')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'commander', 'spacetrim', 'colors', 'waitasecond', 'fs/promises', 'path', 'prettier', 'prettier/parser-html', 'papaparse', 'crypto-js/enc-hex', 'crypto-js/sha256', 'path/posix', 'dotenv', 'glob-promise', 'socket.io-client', '@anthropic-ai/sdk', '@azure/openai', 'openai'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-cli"] = {}, global.commander, global.spaceTrim, global.colors, global.waitasecond, global.promises, global.path, global.prettier, global.parserHtml, global.papaparse, global.hexEncoder, global.sha256, global.posix, global.dotenv, global.glob, global.socket_ioClient, global.Anthropic, global.openai, global.OpenAI));
5
+ })(this, (function (exports, commander, spaceTrim, colors, waitasecond, promises, path, prettier, parserHtml, papaparse, hexEncoder, sha256, posix, dotenv, glob, socket_ioClient, Anthropic, openai, OpenAI) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
@@ -39,8 +39,8 @@
39
39
  /**
40
40
  * The version of the Promptbook library
41
41
  */
42
- var PROMPTBOOK_VERSION = '0.69.0-1';
43
- // TODO: !!!! List here all the versions and annotate + put into script
42
+ var PROMPTBOOK_VERSION = '0.69.0-20';
43
+ // TODO:[main] !!!! List here all the versions and annotate + put into script
44
44
 
45
45
  /*! *****************************************************************************
46
46
  Copyright (c) Microsoft Corporation.
@@ -375,7 +375,7 @@
375
375
  }
376
376
  /**
377
377
  * TODO: [🧠][🛣] More elegant way to tracking than passing `name`
378
- * TODO: [🧠] !!! In-memory cache of same values to prevent multiple checks
378
+ * TODO: [🧠][main] !!! In-memory cache of same values to prevent multiple checks
379
379
  * Note: [🐠] This is how `checkSerializableAsJson` + `isSerializableAsJson` together can just retun true/false or rich error message
380
380
  */
381
381
 
@@ -449,13 +449,13 @@
449
449
  *
450
450
  * @public exported from `@promptbook/core`
451
451
  */
452
- var MAX_PARALLEL_COUNT = 5;
452
+ var MAX_PARALLEL_COUNT = 5; // <- TODO: [🤹‍♂️]
453
453
  /**
454
454
  * The maximum number of attempts to execute LLM task before giving up
455
455
  *
456
456
  * @public exported from `@promptbook/core`
457
457
  */
458
- var MAX_EXECUTION_ATTEMPTS = 3;
458
+ var MAX_EXECUTION_ATTEMPTS = 3; // <- TODO: [🤹‍♂️]
459
459
  /**
460
460
  * The maximum length of the (generated) filename
461
461
  *
@@ -492,6 +492,7 @@
492
492
  'samples',
493
493
  'modelName',
494
494
  'currentDate',
495
+ // <- TODO: !!!!! list here all command names
495
496
  // <- TODO: Add more like 'date', 'modelName',...
496
497
  // <- TODO: Add [emoji] + instructions ACRY when adding new reserved parameter
497
498
  ]);
@@ -520,6 +521,17 @@
520
521
  */
521
522
  var DEFAULT_REMOTE_URL_PATH = '/promptbook/socket.io';
522
523
  // <- TODO: [🧜‍♂️]
524
+ /**
525
+ * @@@
526
+ *
527
+ * @public exported from `@promptbook/core`
528
+ */
529
+ var DEFAULT_CSV_SETTINGS = Object.freeze({
530
+ delimiter: ',',
531
+ quoteChar: '"',
532
+ newline: '\n',
533
+ skipEmptyLines: true,
534
+ });
523
535
  /**
524
536
  * @@@
525
537
  *
@@ -688,7 +700,7 @@
688
700
  commands.push("PIPELINE URL ".concat(pipelineUrl));
689
701
  }
690
702
  commands.push("PROMPTBOOK VERSION ".concat(promptbookVersion));
691
- // TODO: !!! This increase size of the bundle and is probbably not necessary
703
+ // TODO:[main] !!! This increase size of the bundle and is probbably not necessary
692
704
  pipelineString = prettifyMarkdown(pipelineString);
693
705
  try {
694
706
  for (var _g = __values(parameters.filter(function (_a) {
@@ -836,12 +848,12 @@
836
848
  pipelineString += '```' + contentLanguage;
837
849
  pipelineString += '\n';
838
850
  pipelineString += spaceTrim__default["default"](content);
839
- // <- TODO: !!! Escape
851
+ // <- TODO:[main] !!! Escape
840
852
  // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
841
853
  pipelineString += '\n';
842
854
  pipelineString += '```';
843
855
  pipelineString += '\n\n';
844
- pipelineString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO: !!! If the parameter here has description, add it and use templateParameterJsonToString
856
+ pipelineString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO:[main] !!! If the parameter here has description, add it and use templateParameterJsonToString
845
857
  }
846
858
  }
847
859
  catch (e_3_1) { e_3 = { error: e_3_1 }; }
@@ -1068,7 +1080,7 @@
1068
1080
  });
1069
1081
  }
1070
1082
 
1071
- 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"}];
1083
+ 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"}];
1072
1084
 
1073
1085
  /**
1074
1086
  * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
@@ -1143,7 +1155,7 @@
1143
1155
  if ( /* version === '1.0.0' || */version === '2.0.0' || version === '3.0.0') {
1144
1156
  return false;
1145
1157
  }
1146
- // <- TODO: !!! Check isValidPromptbookVersion against PROMPTBOOK_VERSIONS
1158
+ // <- TODO:[main] !!! Check isValidPromptbookVersion against PROMPTBOOK_VERSIONS
1147
1159
  return true;
1148
1160
  }
1149
1161
 
@@ -1312,19 +1324,19 @@
1312
1324
  // <- Note: [🚲]
1313
1325
  throw new PipelineLogicError(spaceTrim.spaceTrim(function (block) { return "\n Invalid promptbook URL \"".concat(pipeline.pipelineUrl, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
1314
1326
  }
1315
- if (!isValidPromptbookVersion(pipeline.promptbookVersion)) {
1327
+ if (pipeline.promptbookVersion !== undefined && !isValidPromptbookVersion(pipeline.promptbookVersion)) {
1316
1328
  // <- Note: [🚲]
1317
1329
  throw new PipelineLogicError(spaceTrim.spaceTrim(function (block) { return "\n Invalid Promptbook Version \"".concat(pipeline.promptbookVersion, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
1318
1330
  }
1319
1331
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1320
1332
  if (!Array.isArray(pipeline.parameters)) {
1321
1333
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1322
- 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 "); }));
1334
+ 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 "); }));
1323
1335
  }
1324
1336
  // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1325
1337
  if (!Array.isArray(pipeline.templates)) {
1326
1338
  // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1327
- 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 "); }));
1339
+ 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 "); }));
1328
1340
  }
1329
1341
  var _loop_1 = function (parameter) {
1330
1342
  if (parameter.isInput && parameter.isOutput) {
@@ -1495,6 +1507,7 @@
1495
1507
  }
1496
1508
  }
1497
1509
  /**
1510
+ * TODO: !!!!! [🧞‍♀️] Do not allow joker + foreach
1498
1511
  * TODO: [🧠] Work with promptbookVersion
1499
1512
  * TODO: Use here some json-schema, Zod or something similar and change it to:
1500
1513
  * > /**
@@ -1506,11 +1519,11 @@
1506
1519
  * > ex port function validatePipeline(promptbook: really_unknown): asserts promptbook is PipelineJson {
1507
1520
  */
1508
1521
  /**
1509
- * TODO: [🐣] !!!! Validate that all samples match expectations
1510
- * TODO: [🐣][🐝] !!!! Validate that knowledge is valid (non-void)
1511
- * TODO: [🐣] !!!! Validate that persona can be used only with CHAT variant
1512
- * TODO: [🐣] !!!! Validate that parameter with reserved name not used RESERVED_PARAMETER_NAMES
1513
- * TODO: [🐣] !!!! Validate that reserved parameter is not used as joker
1522
+ * TODO: [🐣][main] !!!! Validate that all samples match expectations
1523
+ * TODO: [🐣][🐝][main] !!!! Validate that knowledge is valid (non-void)
1524
+ * TODO: [🐣][main] !!!! Validate that persona can be used only with CHAT variant
1525
+ * TODO: [🐣][main] !!!! Validate that parameter with reserved name not used RESERVED_PARAMETER_NAMES
1526
+ * TODO: [🐣][main] !!!! Validate that reserved parameter is not used as joker
1514
1527
  * TODO: [🧠] Validation not only logic itself but imports around - files and websites and rerefenced pipelines exists
1515
1528
  * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
1516
1529
  */
@@ -2216,121 +2229,35 @@
2216
2229
  */
2217
2230
 
2218
2231
  /**
2219
- * Parses the given script and returns the list of all used variables that are not defined in the script
2220
- *
2221
- * @param script from which to extract the variables
2222
- * @returns the list of variable names
2223
- * @throws {ParseError} if the script is invalid
2224
- * @public exported from `@promptbook/utils`
2225
- */
2226
- function extractVariables(script) {
2227
- var variables = new Set();
2228
- script = "(()=>{".concat(script, "})()");
2229
- try {
2230
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2231
- try {
2232
- eval(script);
2233
- }
2234
- catch (error) {
2235
- if (!(error instanceof ReferenceError)) {
2236
- throw error;
2237
- }
2238
- var undefinedName = error.message.split(' ')[0];
2239
- /*
2240
- Note: Parsing the error
2241
- [PipelineUrlError: thing is not defined]
2242
- */
2243
- if (!undefinedName) {
2244
- throw error;
2245
- }
2246
- if (script.includes(undefinedName + '(')) {
2247
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
2248
- }
2249
- else {
2250
- variables.add(undefinedName);
2251
- script = "const ".concat(undefinedName, " = '';") + script;
2252
- }
2253
- }
2254
- }
2255
- catch (error) {
2256
- if (!(error instanceof Error)) {
2257
- throw error;
2258
- }
2259
- throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2260
- }
2261
- return variables;
2262
- }
2263
- /**
2264
- * TODO: [🔣] Support for multiple languages - python, java,...
2265
- */
2266
-
2267
- /**
2268
- * Parses the template and returns the set of all used parameters
2232
+ * Determine if the pipeline is fully prepared
2269
2233
  *
2270
- * @param template the template with used parameters
2271
- * @returns the set of parameter names
2272
- * @throws {ParseError} if the script is invalid
2273
- * @public exported from `@promptbook/utils`
2234
+ * @public exported from `@promptbook/core`
2274
2235
  */
2275
- function extractParameterNamesFromTemplate(template) {
2276
- var e_1, _a, e_2, _b, e_3, _c;
2277
- var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2278
- var parameterNames = new Set();
2279
- try {
2280
- 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()) {
2281
- var parameterName = _e.value;
2282
- parameterNames.add(parameterName);
2283
- }
2284
- }
2285
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2286
- finally {
2287
- try {
2288
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2289
- }
2290
- finally { if (e_1) throw e_1.error; }
2291
- }
2292
- if (templateType === 'SCRIPT_TEMPLATE') {
2293
- try {
2294
- for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
2295
- var parameterName = _g.value;
2296
- parameterNames.add(parameterName);
2297
- }
2298
- }
2299
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
2300
- finally {
2301
- try {
2302
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
2303
- }
2304
- finally { if (e_2) throw e_2.error; }
2305
- }
2306
- }
2307
- try {
2308
- for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
2309
- var jokerName = _j.value;
2310
- parameterNames.add(jokerName);
2311
- }
2312
- }
2313
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2314
- finally {
2315
- try {
2316
- if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
2317
- }
2318
- finally { if (e_3) throw e_3.error; }
2236
+ function isPipelinePrepared(pipeline) {
2237
+ // Note: Ignoring `pipeline.preparations` @@@
2238
+ // Note: Ignoring `pipeline.knowledgePieces` @@@
2239
+ if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2240
+ return false;
2319
2241
  }
2320
- parameterNames.delete('content');
2321
- // <- Note {websiteContent} is used in `preparedContent`
2322
- // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2323
- if (foreach !== undefined) {
2324
- if (parameterNames.has(foreach.subparameterName)) {
2325
- parameterNames.delete(foreach.subparameterName);
2326
- parameterNames.add(foreach.parameterName);
2327
- // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2328
- }
2242
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2243
+ return false;
2329
2244
  }
2330
- return parameterNames;
2245
+ /*
2246
+ TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2247
+ > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2248
+ > return false;
2249
+ > }
2250
+ */
2251
+ return true;
2331
2252
  }
2332
2253
  /**
2333
- * TODO: [🔣] If script require contentLanguage
2254
+ * TODO: [🔃][main] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2255
+ * TODO: [🐠] Maybe base this on `makeValidator`
2256
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2257
+ * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2258
+ * - [🏍] ? Is context in each template
2259
+ * - [♨] Are samples prepared
2260
+ * - [♨] Are templates prepared
2334
2261
  */
2335
2262
 
2336
2263
  /**
@@ -2350,27 +2277,6 @@
2350
2277
  };
2351
2278
  }
2352
2279
 
2353
- /**
2354
- * Function isValidJsonString will tell you if the string is valid JSON or not
2355
- *
2356
- * @public exported from `@promptbook/utils`
2357
- */
2358
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
2359
- try {
2360
- JSON.parse(value);
2361
- return true;
2362
- }
2363
- catch (error) {
2364
- if (!(error instanceof Error)) {
2365
- throw error;
2366
- }
2367
- if (error.message.includes('Unexpected token')) {
2368
- return false;
2369
- }
2370
- return false;
2371
- }
2372
- }
2373
-
2374
2280
  /**
2375
2281
  * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
2376
2282
  *
@@ -2397,9 +2303,10 @@
2397
2303
  });
2398
2304
  Object.defineProperty(MultipleLlmExecutionTools.prototype, "description", {
2399
2305
  get: function () {
2400
- return this.llmExecutionTools
2401
- .map(function (tools, index) { return "".concat(index + 1, ") ").concat(tools.title, " ").concat(tools.description || ''); })
2402
- .join('\n');
2306
+ return this.llmExecutionTools.map(function (_a, index) {
2307
+ var title = _a.title;
2308
+ return "".concat(index + 1, ") `").concat(title, "`");
2309
+ }).join('\n');
2403
2310
  },
2404
2311
  enumerable: false,
2405
2312
  configurable: true
@@ -2597,9 +2504,7 @@
2597
2504
  throw new PipelineExecutionError("You have not provided any `LlmExecutionTools`");
2598
2505
  }
2599
2506
  else {
2600
- 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
2601
- .map(function (tools) { return "- ".concat(tools.title, " ").concat(tools.description || ''); })
2602
- .join('\n')), "\n\n "); }));
2507
+ 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 "); }));
2603
2508
  }
2604
2509
  }
2605
2510
  });
@@ -2665,288 +2570,153 @@
2665
2570
  */
2666
2571
 
2667
2572
  /**
2668
- * Extracts all code blocks from markdown.
2573
+ * Takes an item or an array of items and returns an array of items
2669
2574
  *
2670
- * Note: There are multiple simmilar function:
2671
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2672
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2673
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2674
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2575
+ * 1) Any item except array and undefined returns array with that one item (also null)
2576
+ * 2) Undefined returns empty array
2577
+ * 3) Array returns itself
2675
2578
  *
2676
- * @param markdown any valid markdown
2677
- * @returns code blocks with language and content
2678
- * @throws {ParseError} if block is not closed properly
2679
- * @public exported from `@promptbook/markdown-utils`
2579
+ * @private internal utility
2680
2580
  */
2681
- function extractAllBlocksFromMarkdown(markdown) {
2682
- var e_1, _a;
2683
- var codeBlocks = [];
2684
- var lines = markdown.split('\n');
2685
- // Note: [0] Ensure that the last block notated by gt > will be closed
2686
- lines.push('');
2687
- var currentCodeBlock = null;
2581
+ function arrayableToArray(input) {
2582
+ if (input === undefined) {
2583
+ return [];
2584
+ }
2585
+ if (input instanceof Array) {
2586
+ return input;
2587
+ }
2588
+ return [input];
2589
+ }
2590
+
2591
+ /**
2592
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2593
+ *
2594
+ * @param script from which to extract the variables
2595
+ * @returns the list of variable names
2596
+ * @throws {ParseError} if the script is invalid
2597
+ * @public exported from `@promptbook/utils`
2598
+ */
2599
+ function extractVariables(script) {
2600
+ var variables = new Set();
2601
+ script = "(()=>{".concat(script, "})()");
2688
2602
  try {
2689
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2690
- var line = lines_1_1.value;
2691
- if (line.startsWith('> ') || line === '>') {
2692
- if (currentCodeBlock === null) {
2693
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2694
- } /* not else */
2695
- if (currentCodeBlock.blockNotation === '>') {
2696
- if (currentCodeBlock.content !== '') {
2697
- currentCodeBlock.content += '\n';
2698
- }
2699
- currentCodeBlock.content += line.slice(2);
2700
- }
2701
- }
2702
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2703
- codeBlocks.push(currentCodeBlock);
2704
- currentCodeBlock = null;
2603
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2604
+ try {
2605
+ eval(script);
2705
2606
  }
2706
- /* not else */
2707
- if (line.startsWith('```')) {
2708
- var language = line.slice(3).trim() || null;
2709
- if (currentCodeBlock === null) {
2710
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2607
+ catch (error) {
2608
+ if (!(error instanceof ReferenceError)) {
2609
+ throw error;
2711
2610
  }
2712
- else {
2713
- if (language !== null) {
2714
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2715
- }
2716
- codeBlocks.push(currentCodeBlock);
2717
- currentCodeBlock = null;
2611
+ var undefinedName = error.message.split(' ')[0];
2612
+ /*
2613
+ Note: Parsing the error
2614
+ [PipelineUrlError: thing is not defined]
2615
+ */
2616
+ if (!undefinedName) {
2617
+ throw error;
2718
2618
  }
2719
- }
2720
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2721
- if (currentCodeBlock.content !== '') {
2722
- currentCodeBlock.content += '\n';
2619
+ if (script.includes(undefinedName + '(')) {
2620
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2621
+ }
2622
+ else {
2623
+ variables.add(undefinedName);
2624
+ script = "const ".concat(undefinedName, " = '';") + script;
2723
2625
  }
2724
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2725
2626
  }
2726
- }
2727
2627
  }
2728
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2729
- finally {
2730
- try {
2731
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2628
+ catch (error) {
2629
+ if (!(error instanceof Error)) {
2630
+ throw error;
2732
2631
  }
2733
- finally { if (e_1) throw e_1.error; }
2734
- }
2735
- if (currentCodeBlock !== null) {
2736
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2737
- }
2738
- return codeBlocks;
2739
- }
2740
- /**
2741
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2742
- */
2743
-
2744
- /**
2745
- * Extracts extracts exactly one valid JSON code block
2746
- *
2747
- * - When given string is a valid JSON as it is, it just returns it
2748
- * - When there is no JSON code block the function throws a `ParseError`
2749
- * - When there are multiple JSON code blocks the function throws a `ParseError`
2750
- *
2751
- * Note: It is not important if marked as ```json BUT if it is VALID JSON
2752
- * Note: There are multiple simmilar function:
2753
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2754
- * - `extractJsonBlock` extracts exactly one valid JSON code block
2755
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2756
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2757
- *
2758
- * @public exported from `@promptbook/markdown-utils`
2759
- * @throws {ParseError} if there is no valid JSON block in the markdown
2760
- */
2761
- function extractJsonBlock(markdown) {
2762
- if (isValidJsonString(markdown)) {
2763
- return markdown;
2764
- }
2765
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2766
- var jsonBlocks = codeBlocks.filter(function (_a) {
2767
- var content = _a.content;
2768
- return isValidJsonString(content);
2769
- });
2770
- if (jsonBlocks.length === 0) {
2771
- throw new Error('There is no valid JSON block in the markdown');
2772
- }
2773
- if (jsonBlocks.length > 1) {
2774
- throw new Error('There are multiple JSON code blocks in the markdown');
2775
- }
2776
- return jsonBlocks[0].content;
2777
- }
2778
- /**
2779
- * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
2780
- * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2781
- */
2782
-
2783
- /**
2784
- * Determine if the pipeline is fully prepared
2785
- *
2786
- * @public exported from `@promptbook/core`
2787
- */
2788
- function isPipelinePrepared(pipeline) {
2789
- // Note: Ignoring `pipeline.preparations` @@@
2790
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2791
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2792
- return false;
2793
- }
2794
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2795
- return false;
2796
- }
2797
- /*
2798
- TODO: [🧠][🍫] `templates` can not be determined if they are fully prepared SO ignoring them
2799
- > if (!pipeline.templates.every(({ preparedContent }) => preparedContent === undefined)) {
2800
- > return false;
2801
- > }
2802
- */
2803
- return true;
2804
- }
2805
- /**
2806
- * TODO: [🔃] !!!!! If the pipeline was prepared with different version or different set of models, prepare it once again
2807
- * TODO: [🐠] Maybe base this on `makeValidator`
2808
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2809
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2810
- * - [🏍] ? Is context in each template
2811
- * - [♨] Are samples prepared
2812
- * - [♨] Are templates prepared
2813
- */
2814
-
2815
- /**
2816
- * Takes an item or an array of items and returns an array of items
2817
- *
2818
- * 1) Any item except array and undefined returns array with that one item (also null)
2819
- * 2) Undefined returns empty array
2820
- * 3) Array returns itself
2821
- *
2822
- * @private internal utility
2823
- */
2824
- function arrayableToArray(input) {
2825
- if (input === undefined) {
2826
- return [];
2827
- }
2828
- if (input instanceof Array) {
2829
- return input;
2830
- }
2831
- return [input];
2832
- }
2833
-
2834
- /**
2835
- * Just says that the variable is not used but should be kept
2836
- * No side effects.
2837
- *
2838
- * Note: It can be usefull for:
2839
- *
2840
- * 1) Suppressing eager optimization of unused imports
2841
- * 2) Suppressing eslint errors of unused variables in the tests
2842
- * 3) Keeping the type of the variable for type testing
2843
- *
2844
- * @param value any values
2845
- * @returns void
2846
- * @private within the repository
2847
- */
2848
- function keepUnused() {
2849
- var valuesToKeep = [];
2850
- for (var _i = 0; _i < arguments.length; _i++) {
2851
- valuesToKeep[_i] = arguments[_i];
2632
+ throw new ParseError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.toString()), "}\n "); }));
2852
2633
  }
2634
+ return variables;
2853
2635
  }
2854
-
2855
2636
  /**
2856
- * Just marks a place of place where should be something implemented
2857
- * No side effects.
2858
- *
2859
- * Note: It can be usefull suppressing eslint errors of unused variables
2860
- *
2861
- * @param value any values
2862
- * @returns void
2863
- * @private within the repository
2637
+ * TODO: [🔣] Support for multiple languages - python, java,...
2864
2638
  */
2865
- function TODO_USE() {
2866
- var value = [];
2867
- for (var _i = 0; _i < arguments.length; _i++) {
2868
- value[_i] = arguments[_i];
2869
- }
2870
- }
2871
2639
 
2872
2640
  /**
2873
- * Replaces parameters in template with values from parameters object
2641
+ * Parses the template and returns the set of all used parameters
2874
2642
  *
2875
- * @param template the template with parameters in {curly} braces
2876
- * @param parameters the object with parameters
2877
- * @returns the template with replaced parameters
2878
- * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
2643
+ * @param template the template with used parameters
2644
+ * @returns the set of parameter names
2645
+ * @throws {ParseError} if the script is invalid
2879
2646
  * @public exported from `@promptbook/utils`
2880
2647
  */
2881
- function replaceParameters(template, parameters) {
2882
- var e_1, _a;
2648
+ function extractParameterNamesFromTemplate(template) {
2649
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
2650
+ var title = template.title, description = template.description, templateType = template.templateType, content = template.content, preparedContent = template.preparedContent, jokerParameterNames = template.jokerParameterNames, foreach = template.foreach;
2651
+ var parameterNames = new Set();
2883
2652
  try {
2884
- for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
2885
- var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
2886
- if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
2887
- throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
2888
- }
2889
- else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
2890
- // TODO: [🍵]
2891
- throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
2892
- }
2653
+ 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()) {
2654
+ var parameterName = _f.value;
2655
+ parameterNames.add(parameterName);
2893
2656
  }
2894
2657
  }
2895
2658
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
2896
2659
  finally {
2897
2660
  try {
2898
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2661
+ if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
2899
2662
  }
2900
2663
  finally { if (e_1) throw e_1.error; }
2901
2664
  }
2902
- var replacedTemplate = template;
2903
- var match;
2904
- var loopLimit = LOOP_LIMIT;
2905
- var _loop_1 = function () {
2906
- if (loopLimit-- < 0) {
2907
- throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
2665
+ if (templateType === 'SCRIPT_TEMPLATE') {
2666
+ try {
2667
+ for (var _g = __values(extractVariables(content)), _h = _g.next(); !_h.done; _h = _g.next()) {
2668
+ var parameterName = _h.value;
2669
+ parameterNames.add(parameterName);
2670
+ }
2908
2671
  }
2909
- var precol = match.groups.precol;
2910
- var parameterName = match.groups.parameterName;
2911
- if (parameterName === '') {
2912
- return "continue";
2672
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2673
+ finally {
2674
+ try {
2675
+ if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
2676
+ }
2677
+ finally { if (e_2) throw e_2.error; }
2913
2678
  }
2914
- if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
2915
- throw new PipelineExecutionError('Parameter is already opened or not closed');
2679
+ }
2680
+ try {
2681
+ for (var _j = __values(jokerParameterNames || []), _k = _j.next(); !_k.done; _k = _j.next()) {
2682
+ var jokerName = _k.value;
2683
+ parameterNames.add(jokerName);
2916
2684
  }
2917
- if (parameters[parameterName] === undefined) {
2918
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2685
+ }
2686
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
2687
+ finally {
2688
+ try {
2689
+ if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
2919
2690
  }
2920
- var parameterValue = parameters[parameterName];
2921
- if (parameterValue === undefined) {
2922
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2691
+ finally { if (e_3) throw e_3.error; }
2692
+ }
2693
+ parameterNames.delete('content');
2694
+ // <- Note {websiteContent} is used in `preparedContent`
2695
+ // Note: [🍭] Fixing dependent subparameterName from FOREACH command
2696
+ if (foreach !== undefined) {
2697
+ try {
2698
+ for (var _l = __values(foreach.inputSubparameterNames), _m = _l.next(); !_m.done; _m = _l.next()) {
2699
+ var subparameterName = _m.value;
2700
+ if (parameterNames.has(subparameterName)) {
2701
+ parameterNames.delete(subparameterName);
2702
+ parameterNames.add(foreach.parameterName);
2703
+ // <- TODO: [🚎] Warn/logic error when `subparameterName` not used
2704
+ }
2705
+ }
2923
2706
  }
2924
- parameterValue = parameterValue.toString();
2925
- if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
2926
- parameterValue = parameterValue
2927
- .split('\n')
2928
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
2929
- .join('\n');
2707
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
2708
+ finally {
2709
+ try {
2710
+ if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
2711
+ }
2712
+ finally { if (e_4) throw e_4.error; }
2930
2713
  }
2931
- replacedTemplate =
2932
- replacedTemplate.substring(0, match.index + precol.length) +
2933
- parameterValue +
2934
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
2935
- };
2936
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
2937
- .exec(replacedTemplate))) {
2938
- _loop_1();
2939
- }
2940
- // [💫] Check if there are parameters that are not closed properly
2941
- if (/{\w+$/.test(replacedTemplate)) {
2942
- throw new PipelineExecutionError('Parameter is not closed');
2943
- }
2944
- // [💫] Check if there are parameters that are not opened properly
2945
- if (/^\w+}/.test(replacedTemplate)) {
2946
- throw new PipelineExecutionError('Parameter is not opened');
2947
2714
  }
2948
- return replacedTemplate;
2715
+ return parameterNames;
2949
2716
  }
2717
+ /**
2718
+ * TODO: [🔣] If script require contentLanguage
2719
+ */
2950
2720
 
2951
2721
  /**
2952
2722
  * Create difference set of two sets.
@@ -3024,24 +2794,621 @@
3024
2794
  }
3025
2795
 
3026
2796
  /**
3027
- * Counts number of characters in the text
2797
+ * Just marks a place of place where should be something implemented
2798
+ * No side effects.
3028
2799
  *
3029
- * @public exported from `@promptbook/utils`
2800
+ * Note: It can be usefull suppressing eslint errors of unused variables
2801
+ *
2802
+ * @param value any values
2803
+ * @returns void
2804
+ * @private within the repository
3030
2805
  */
3031
- function countCharacters(text) {
3032
- // Remove null characters
3033
- text = text.replace(/\0/g, '');
3034
- // Replace emojis (and also ZWJ sequence) with hyphens
3035
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3036
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
3037
- text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
3038
- return text.length;
2806
+ function TODO_USE() {
2807
+ var value = [];
2808
+ for (var _i = 0; _i < arguments.length; _i++) {
2809
+ value[_i] = arguments[_i];
2810
+ }
3039
2811
  }
3040
2812
 
3041
2813
  /**
3042
- * Counts number of lines in the text
2814
+ * @@@
3043
2815
  *
3044
- * @public exported from `@promptbook/utils`
2816
+ * @public exported from `@promptbook/core`
2817
+ */
2818
+ var MANDATORY_CSV_SETTINGS = Object.freeze({
2819
+ header: true,
2820
+ // encoding: 'utf8',
2821
+ });
2822
+
2823
+ /**
2824
+ * Definition for CSV spreadsheet
2825
+ *
2826
+ * @public exported from `@promptbook/core`
2827
+ * <- TODO: [🏢] Export from package `@promptbook/csv`
2828
+ */
2829
+ var CsvFormatDefinition = {
2830
+ formatName: 'CSV',
2831
+ aliases: ['SPREADSHEET', 'TABLE'],
2832
+ isValid: function (value, settings, schema) {
2833
+ // TODO: !!!!!! Implement CSV validation
2834
+ TODO_USE(value /* <- TODO: Use value here */);
2835
+ TODO_USE(settings /* <- TODO: Use settings here */);
2836
+ TODO_USE(schema /* <- TODO: Use schema here */);
2837
+ return true;
2838
+ },
2839
+ canBeValid: function (partialValue, settings, schema) {
2840
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
2841
+ TODO_USE(settings /* <- TODO: Use settings here */);
2842
+ TODO_USE(schema /* <- TODO: Use schema here */);
2843
+ return true;
2844
+ },
2845
+ heal: function (value, settings, schema) {
2846
+ TODO_USE(value /* <- TODO: Use partialValue here */);
2847
+ TODO_USE(settings /* <- TODO: Use settings here */);
2848
+ TODO_USE(schema /* <- TODO: Use schema here */);
2849
+ throw new Error('Not implemented');
2850
+ },
2851
+ subvalueDefinitions: [
2852
+ {
2853
+ subvalueName: 'ROW',
2854
+ mapValues: function (value, outputParameterName, settings, mapCallback) {
2855
+ return __awaiter(this, void 0, void 0, function () {
2856
+ var csv, mappedData;
2857
+ var _this = this;
2858
+ return __generator(this, function (_a) {
2859
+ switch (_a.label) {
2860
+ case 0:
2861
+ csv = papaparse.parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
2862
+ if (csv.errors.length !== 0) {
2863
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2864
+ 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 "); }));
2865
+ }
2866
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, index) { return __awaiter(_this, void 0, void 0, function () {
2867
+ var _a, _b;
2868
+ var _c;
2869
+ return __generator(this, function (_d) {
2870
+ switch (_d.label) {
2871
+ case 0:
2872
+ if (row[outputParameterName]) {
2873
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2874
+ "Can not overwrite existing column \"".concat(outputParameterName, "\" in CSV row"));
2875
+ }
2876
+ _a = [__assign({}, row)];
2877
+ _c = {};
2878
+ _b = outputParameterName;
2879
+ return [4 /*yield*/, mapCallback(row, index)];
2880
+ case 1: return [2 /*return*/, __assign.apply(void 0, _a.concat([(_c[_b] = _d.sent(), _c)]))];
2881
+ }
2882
+ });
2883
+ }); }))];
2884
+ case 1:
2885
+ mappedData = _a.sent();
2886
+ return [2 /*return*/, papaparse.unparse(mappedData, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS))];
2887
+ }
2888
+ });
2889
+ });
2890
+ },
2891
+ },
2892
+ {
2893
+ subvalueName: 'CELL',
2894
+ mapValues: function (value, outputParameterName, settings, mapCallback) {
2895
+ return __awaiter(this, void 0, void 0, function () {
2896
+ var csv, mappedData;
2897
+ var _this = this;
2898
+ return __generator(this, function (_a) {
2899
+ switch (_a.label) {
2900
+ case 0:
2901
+ csv = papaparse.parse(value, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS));
2902
+ if (csv.errors.length !== 0) {
2903
+ throw new ParseError(// <- TODO: !!!!!! Split PipelineParseError and FormatParseError -> CsvParseError
2904
+ 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 "); }));
2905
+ }
2906
+ return [4 /*yield*/, Promise.all(csv.data.map(function (row, rowIndex) { return __awaiter(_this, void 0, void 0, function () {
2907
+ var _this = this;
2908
+ return __generator(this, function (_a) {
2909
+ return [2 /*return*/, /* not await */ Promise.all(Object.entries(row).map(function (_a, columnIndex) {
2910
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
2911
+ return __awaiter(_this, void 0, void 0, function () {
2912
+ var index;
2913
+ var _c;
2914
+ return __generator(this, function (_d) {
2915
+ index = rowIndex * Object.keys(row).length + columnIndex;
2916
+ return [2 /*return*/, /* not await */ mapCallback((_c = {}, _c[key] = value, _c), index)];
2917
+ });
2918
+ });
2919
+ }))];
2920
+ });
2921
+ }); }))];
2922
+ case 1:
2923
+ mappedData = _a.sent();
2924
+ return [2 /*return*/, papaparse.unparse(mappedData, __assign(__assign({}, settings), MANDATORY_CSV_SETTINGS))];
2925
+ }
2926
+ });
2927
+ });
2928
+ },
2929
+ },
2930
+ ],
2931
+ };
2932
+ /**
2933
+ * TODO: [🍓] In `CsvFormatDefinition` implement simple `isValid`
2934
+ * TODO: [🍓] In `CsvFormatDefinition` implement partial `canBeValid`
2935
+ * TODO: [🍓] In `CsvFormatDefinition` implement `heal
2936
+ * TODO: [🍓] In `CsvFormatDefinition` implement `subvalueDefinitions`
2937
+ * TODO: [🏢] Allow to expect something inside CSV objects and other formats
2938
+ */
2939
+
2940
+ /**
2941
+ * Function isValidJsonString will tell you if the string is valid JSON or not
2942
+ *
2943
+ * @public exported from `@promptbook/utils`
2944
+ */
2945
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
2946
+ try {
2947
+ JSON.parse(value);
2948
+ return true;
2949
+ }
2950
+ catch (error) {
2951
+ if (!(error instanceof Error)) {
2952
+ throw error;
2953
+ }
2954
+ if (error.message.includes('Unexpected token')) {
2955
+ return false;
2956
+ }
2957
+ return false;
2958
+ }
2959
+ }
2960
+
2961
+ /**
2962
+ * Definition for JSON format
2963
+ *
2964
+ * @private still in development [🏢]
2965
+ */
2966
+ var JsonFormatDefinition = {
2967
+ formatName: 'JSON',
2968
+ mimeType: 'application/json',
2969
+ isValid: function (value, settings, schema) {
2970
+ TODO_USE(schema /* <- TODO: Use schema here */);
2971
+ TODO_USE(settings /* <- TODO: Use settings here */);
2972
+ return isValidJsonString(value);
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
+ /**
2989
+ * TODO: [🧠] Maybe propper instance of object
2990
+ * TODO: [0] Make string_serialized_json
2991
+ * TODO: [1] Make type for JSON Settings and Schema
2992
+ * TODO: [🧠] What to use for validating JSONs - JSON Schema, ZoD, typescript types/interfaces,...?
2993
+ * TODO: [🍓] In `JsonFormatDefinition` implement simple `isValid`
2994
+ * TODO: [🍓] In `JsonFormatDefinition` implement partial `canBeValid`
2995
+ * TODO: [🍓] In `JsonFormatDefinition` implement `heal
2996
+ * TODO: [🍓] In `JsonFormatDefinition` implement `subvalueDefinitions`
2997
+ * TODO: [🏢] Allow to expect something inside JSON objects and other formats
2998
+ */
2999
+
3000
+ /**
3001
+ * Definition for any text - this will be always valid
3002
+ *
3003
+ * Note: This is not useful for validation, but for splitting and mapping with `subvalueDefinitions`
3004
+ *
3005
+ * @public exported from `@promptbook/core`
3006
+ */
3007
+ var TextFormatDefinition = {
3008
+ formatName: 'TEXT',
3009
+ isValid: function (value) {
3010
+ return typeof value === 'string';
3011
+ },
3012
+ canBeValid: function (partialValue) {
3013
+ return typeof partialValue === 'string';
3014
+ },
3015
+ heal: function () {
3016
+ throw new UnexpectedError('It does not make sense to call `TextFormatDefinition.heal`');
3017
+ },
3018
+ subvalueDefinitions: [
3019
+ {
3020
+ subvalueName: 'LINE',
3021
+ mapValues: function (value, outputParameterName, settings, mapCallback) {
3022
+ return __awaiter(this, void 0, void 0, function () {
3023
+ var lines, mappedLines;
3024
+ return __generator(this, function (_a) {
3025
+ switch (_a.label) {
3026
+ case 0:
3027
+ lines = value.split('\n');
3028
+ return [4 /*yield*/, Promise.all(lines.map(function (lineContent, lineNumber) {
3029
+ // TODO: [🧠] Maybe option to skip empty line
3030
+ /* not await */ return mapCallback({
3031
+ lineContent: lineContent,
3032
+ // TODO: [🧠] Maybe also put here `lineNumber`
3033
+ }, lineNumber);
3034
+ }))];
3035
+ case 1:
3036
+ mappedLines = _a.sent();
3037
+ return [2 /*return*/, mappedLines.join('\n')];
3038
+ }
3039
+ });
3040
+ });
3041
+ },
3042
+ },
3043
+ // <- TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3044
+ ],
3045
+ };
3046
+ /**
3047
+ * TODO: [1] Make type for XML Text and Schema
3048
+ * TODO: [🧠][🤠] Here should be all words, characters, lines, paragraphs, pages aviable as subvalues
3049
+ * TODO: [🍓] In `TextFormatDefinition` implement simple `isValid`
3050
+ * TODO: [🍓] In `TextFormatDefinition` implement partial `canBeValid`
3051
+ * TODO: [🍓] In `TextFormatDefinition` implement `heal
3052
+ * TODO: [🍓] In `TextFormatDefinition` implement `subvalueDefinitions`
3053
+ * TODO: [🏢] Allow to expect something inside each item of list and other formats
3054
+ */
3055
+
3056
+ /**
3057
+ * Definition for XML format
3058
+ *
3059
+ * @private still in development [🏢]
3060
+ */
3061
+ var XmlFormatDefinition = {
3062
+ formatName: 'XML',
3063
+ mimeType: 'application/xml',
3064
+ isValid: function (value, settings, schema) {
3065
+ TODO_USE(value /* <- TODO: Use value here */);
3066
+ TODO_USE(settings /* <- TODO: Use settings here */);
3067
+ TODO_USE(schema /* <- TODO: Use schema here */);
3068
+ return true;
3069
+ },
3070
+ canBeValid: function (partialValue, settings, schema) {
3071
+ TODO_USE(partialValue /* <- TODO: Use partialValue here */);
3072
+ TODO_USE(settings /* <- TODO: Use settings here */);
3073
+ TODO_USE(schema /* <- TODO: Use schema here */);
3074
+ return true;
3075
+ },
3076
+ heal: function (value, settings, schema) {
3077
+ TODO_USE(value /* <- TODO: Use partialValue here */);
3078
+ TODO_USE(settings /* <- TODO: Use settings here */);
3079
+ TODO_USE(schema /* <- TODO: Use schema here */);
3080
+ throw new Error('Not implemented');
3081
+ },
3082
+ subvalueDefinitions: [],
3083
+ };
3084
+ /**
3085
+ * TODO: [🧠] Maybe propper instance of object
3086
+ * TODO: [0] Make string_serialized_xml
3087
+ * TODO: [1] Make type for XML Settings and Schema
3088
+ * TODO: [🧠] What to use for validating XMLs - XSD,...
3089
+ * TODO: [🍓] In `XmlFormatDefinition` implement simple `isValid`
3090
+ * TODO: [🍓] In `XmlFormatDefinition` implement partial `canBeValid`
3091
+ * TODO: [🍓] In `XmlFormatDefinition` implement `heal
3092
+ * TODO: [🍓] In `XmlFormatDefinition` implement `subvalueDefinitions`
3093
+ * TODO: [🏢] Allow to expect something inside XML and other formats
3094
+ */
3095
+
3096
+ /**
3097
+ * Definitions for all formats supported by Promptbook
3098
+ *
3099
+ * @private internal index of `...` <- TODO [🏢]
3100
+ */
3101
+ var FORMAT_DEFINITIONS = [
3102
+ JsonFormatDefinition,
3103
+ XmlFormatDefinition,
3104
+ TextFormatDefinition,
3105
+ CsvFormatDefinition,
3106
+ ];
3107
+
3108
+ /**
3109
+ * Maps available parameters to expected parameters
3110
+ *
3111
+ * The strategy is:
3112
+ * 1) @@@
3113
+ * 2) @@@
3114
+ *
3115
+ * @throws {PipelineExecutionError} @@@
3116
+ * @private within the repository used in `createPipelineExecutor`
3117
+ */
3118
+ function mapAvailableToExpectedParameters(options) {
3119
+ var e_1, _a;
3120
+ var expectedParameters = options.expectedParameters, availableParameters = options.availableParameters;
3121
+ var availableParametersNames = new Set(Object.keys(availableParameters));
3122
+ var expectedParameterNames = new Set(Object.keys(expectedParameters));
3123
+ var mappedParameters = {};
3124
+ try {
3125
+ // Phase 1️⃣: Matching mapping
3126
+ for (var _b = __values(Array.from(union(availableParametersNames, expectedParameterNames))), _c = _b.next(); !_c.done; _c = _b.next()) {
3127
+ var parameterName = _c.value;
3128
+ // Situation: Parameter is available and expected
3129
+ if (availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3130
+ mappedParameters[parameterName] = availableParameters[parameterName];
3131
+ // <- Note: [👩‍👩‍👧] Maybe detect parameter collision here?
3132
+ availableParametersNames.delete(parameterName);
3133
+ expectedParameterNames.delete(parameterName);
3134
+ }
3135
+ // Situation: Parameter is available but NOT expected
3136
+ else if (availableParametersNames.has(parameterName) && !expectedParameterNames.has(parameterName)) {
3137
+ // [🐱‍👤] Do not pass this parameter to prompt - Maybe use it non-matching mapping
3138
+ }
3139
+ // Situation: Parameter is NOT available BUT expected
3140
+ else if (!availableParametersNames.has(parameterName) && expectedParameterNames.has(parameterName)) {
3141
+ // Do nothing here - this will be maybe fixed in the non-matching mapping
3142
+ }
3143
+ }
3144
+ }
3145
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3146
+ finally {
3147
+ try {
3148
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3149
+ }
3150
+ finally { if (e_1) throw e_1.error; }
3151
+ }
3152
+ if (expectedParameterNames.size === 0) {
3153
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3154
+ Object.freeze(mappedParameters);
3155
+ return mappedParameters;
3156
+ }
3157
+ // Phase 2️⃣: Non-matching mapping
3158
+ if (expectedParameterNames.size !== availableParametersNames.size) {
3159
+ 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)
3160
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3161
+ .join('\n')), "\n\n Expected parameters which can not be mapped:\n ").concat(block(Array.from(expectedParameterNames)
3162
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3163
+ .join('\n')), "\n\n Remaining available parameters:\n ").concat(block(Array.from(availableParametersNames)
3164
+ .map(function (parameterName) { return "- {".concat(parameterName, "}"); })
3165
+ .join('\n')), "\n\n "); }));
3166
+ }
3167
+ var expectedParameterNamesArray = Array.from(expectedParameterNames);
3168
+ var availableParametersNamesArray = Array.from(availableParametersNames);
3169
+ for (var i = 0; i < expectedParameterNames.size; i++) {
3170
+ mappedParameters[expectedParameterNamesArray[i]] = availableParameters[availableParametersNamesArray[i]];
3171
+ }
3172
+ // Note: [👨‍👨‍👧] Now we can freeze `mappedParameters` to prevent @@@
3173
+ Object.freeze(mappedParameters);
3174
+ return mappedParameters;
3175
+ }
3176
+
3177
+ /**
3178
+ * Extracts all code blocks from markdown.
3179
+ *
3180
+ * Note: There are multiple simmilar function:
3181
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3182
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3183
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3184
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3185
+ *
3186
+ * @param markdown any valid markdown
3187
+ * @returns code blocks with language and content
3188
+ * @throws {ParseError} if block is not closed properly
3189
+ * @public exported from `@promptbook/markdown-utils`
3190
+ */
3191
+ function extractAllBlocksFromMarkdown(markdown) {
3192
+ var e_1, _a;
3193
+ var codeBlocks = [];
3194
+ var lines = markdown.split('\n');
3195
+ // Note: [0] Ensure that the last block notated by gt > will be closed
3196
+ lines.push('');
3197
+ var currentCodeBlock = null;
3198
+ try {
3199
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
3200
+ var line = lines_1_1.value;
3201
+ if (line.startsWith('> ') || line === '>') {
3202
+ if (currentCodeBlock === null) {
3203
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
3204
+ } /* not else */
3205
+ if (currentCodeBlock.blockNotation === '>') {
3206
+ if (currentCodeBlock.content !== '') {
3207
+ currentCodeBlock.content += '\n';
3208
+ }
3209
+ currentCodeBlock.content += line.slice(2);
3210
+ }
3211
+ }
3212
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
3213
+ codeBlocks.push(currentCodeBlock);
3214
+ currentCodeBlock = null;
3215
+ }
3216
+ /* not else */
3217
+ if (line.startsWith('```')) {
3218
+ var language = line.slice(3).trim() || null;
3219
+ if (currentCodeBlock === null) {
3220
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
3221
+ }
3222
+ else {
3223
+ if (language !== null) {
3224
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
3225
+ }
3226
+ codeBlocks.push(currentCodeBlock);
3227
+ currentCodeBlock = null;
3228
+ }
3229
+ }
3230
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
3231
+ if (currentCodeBlock.content !== '') {
3232
+ currentCodeBlock.content += '\n';
3233
+ }
3234
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
3235
+ }
3236
+ }
3237
+ }
3238
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3239
+ finally {
3240
+ try {
3241
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
3242
+ }
3243
+ finally { if (e_1) throw e_1.error; }
3244
+ }
3245
+ if (currentCodeBlock !== null) {
3246
+ throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
3247
+ }
3248
+ return codeBlocks;
3249
+ }
3250
+ /**
3251
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
3252
+ */
3253
+
3254
+ /**
3255
+ * Extracts extracts exactly one valid JSON code block
3256
+ *
3257
+ * - When given string is a valid JSON as it is, it just returns it
3258
+ * - When there is no JSON code block the function throws a `ParseError`
3259
+ * - When there are multiple JSON code blocks the function throws a `ParseError`
3260
+ *
3261
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
3262
+ * Note: There are multiple simmilar function:
3263
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
3264
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
3265
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
3266
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
3267
+ *
3268
+ * @public exported from `@promptbook/markdown-utils`
3269
+ * @throws {ParseError} if there is no valid JSON block in the markdown
3270
+ */
3271
+ function extractJsonBlock(markdown) {
3272
+ if (isValidJsonString(markdown)) {
3273
+ return markdown;
3274
+ }
3275
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
3276
+ var jsonBlocks = codeBlocks.filter(function (_a) {
3277
+ var content = _a.content;
3278
+ return isValidJsonString(content);
3279
+ });
3280
+ if (jsonBlocks.length === 0) {
3281
+ throw new Error('There is no valid JSON block in the markdown');
3282
+ }
3283
+ if (jsonBlocks.length > 1) {
3284
+ throw new Error('There are multiple JSON code blocks in the markdown');
3285
+ }
3286
+ return jsonBlocks[0].content;
3287
+ }
3288
+ /**
3289
+ * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
3290
+ * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
3291
+ */
3292
+
3293
+ /**
3294
+ * Just says that the variable is not used but should be kept
3295
+ * No side effects.
3296
+ *
3297
+ * Note: It can be usefull for:
3298
+ *
3299
+ * 1) Suppressing eager optimization of unused imports
3300
+ * 2) Suppressing eslint errors of unused variables in the tests
3301
+ * 3) Keeping the type of the variable for type testing
3302
+ *
3303
+ * @param value any values
3304
+ * @returns void
3305
+ * @private within the repository
3306
+ */
3307
+ function keepUnused() {
3308
+ var valuesToKeep = [];
3309
+ for (var _i = 0; _i < arguments.length; _i++) {
3310
+ valuesToKeep[_i] = arguments[_i];
3311
+ }
3312
+ }
3313
+
3314
+ /**
3315
+ * Replaces parameters in template with values from parameters object
3316
+ *
3317
+ * @param template the template with parameters in {curly} braces
3318
+ * @param parameters the object with parameters
3319
+ * @returns the template with replaced parameters
3320
+ * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
3321
+ * @public exported from `@promptbook/utils`
3322
+ */
3323
+ function replaceParameters(template, parameters) {
3324
+ var e_1, _a;
3325
+ try {
3326
+ for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
3327
+ var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
3328
+ if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
3329
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} has missing value"));
3330
+ }
3331
+ else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
3332
+ // TODO: [🍵]
3333
+ throw new UnexpectedError("Parameter {".concat(parameterName, "} is restricted to use"));
3334
+ }
3335
+ }
3336
+ }
3337
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3338
+ finally {
3339
+ try {
3340
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3341
+ }
3342
+ finally { if (e_1) throw e_1.error; }
3343
+ }
3344
+ var replacedTemplate = template;
3345
+ var match;
3346
+ var loopLimit = LOOP_LIMIT;
3347
+ var _loop_1 = function () {
3348
+ if (loopLimit-- < 0) {
3349
+ throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
3350
+ }
3351
+ var precol = match.groups.precol;
3352
+ var parameterName = match.groups.parameterName;
3353
+ if (parameterName === '') {
3354
+ return "continue";
3355
+ }
3356
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
3357
+ throw new PipelineExecutionError('Parameter is already opened or not closed');
3358
+ }
3359
+ if (parameters[parameterName] === undefined) {
3360
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3361
+ }
3362
+ var parameterValue = parameters[parameterName];
3363
+ if (parameterValue === undefined) {
3364
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
3365
+ }
3366
+ parameterValue = parameterValue.toString();
3367
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
3368
+ parameterValue = parameterValue
3369
+ .split('\n')
3370
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
3371
+ .join('\n');
3372
+ }
3373
+ replacedTemplate =
3374
+ replacedTemplate.substring(0, match.index + precol.length) +
3375
+ parameterValue +
3376
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
3377
+ };
3378
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
3379
+ .exec(replacedTemplate))) {
3380
+ _loop_1();
3381
+ }
3382
+ // [💫] Check if there are parameters that are not closed properly
3383
+ if (/{\w+$/.test(replacedTemplate)) {
3384
+ throw new PipelineExecutionError('Parameter is not closed');
3385
+ }
3386
+ // [💫] Check if there are parameters that are not opened properly
3387
+ if (/^\w+}/.test(replacedTemplate)) {
3388
+ throw new PipelineExecutionError('Parameter is not opened');
3389
+ }
3390
+ return replacedTemplate;
3391
+ }
3392
+
3393
+ /**
3394
+ * Counts number of characters in the text
3395
+ *
3396
+ * @public exported from `@promptbook/utils`
3397
+ */
3398
+ function countCharacters(text) {
3399
+ // Remove null characters
3400
+ text = text.replace(/\0/g, '');
3401
+ // Replace emojis (and also ZWJ sequence) with hyphens
3402
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3403
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
3404
+ text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
3405
+ return text.length;
3406
+ }
3407
+
3408
+ /**
3409
+ * Counts number of lines in the text
3410
+ *
3411
+ * @public exported from `@promptbook/utils`
3045
3412
  */
3046
3413
  function countLines(text) {
3047
3414
  if (text === '') {
@@ -3080,62 +3447,789 @@
3080
3447
  return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
3081
3448
  }
3082
3449
  /**
3083
- * Counts number of sentences in the text
3450
+ * Counts number of sentences in the text
3451
+ *
3452
+ * @public exported from `@promptbook/utils`
3453
+ */
3454
+ function countSentences(text) {
3455
+ return splitIntoSentences(text).length;
3456
+ }
3457
+
3458
+ /**
3459
+ * Counts number of words in the text
3460
+ *
3461
+ * @public exported from `@promptbook/utils`
3462
+ */
3463
+ function countWords(text) {
3464
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3465
+ text = removeDiacritics(text);
3466
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
3467
+ }
3468
+
3469
+ /**
3470
+ * Index of all counter functions
3471
+ *
3472
+ * @public exported from `@promptbook/utils`
3473
+ */
3474
+ var CountUtils = {
3475
+ CHARACTERS: countCharacters,
3476
+ WORDS: countWords,
3477
+ SENTENCES: countSentences,
3478
+ PARAGRAPHS: countParagraphs,
3479
+ LINES: countLines,
3480
+ PAGES: countPages,
3481
+ };
3482
+ /**
3483
+ * TODO: [🧠][🤠] This should be probbably as part of `TextFormatDefinition`
3484
+ */
3485
+
3486
+ /**
3487
+ * Function checkExpectations will check if the expectations on given value are met
3488
+ *
3489
+ * Note: There are two simmilar functions:
3490
+ * - `checkExpectations` which throws an error if the expectations are not met
3491
+ * - `isPassingExpectations` which returns a boolean
3492
+ *
3493
+ * @throws {ExpectError} if the expectations are not met
3494
+ * @returns {void} Nothing
3495
+ * @private internal function of `createPipelineExecutor`
3496
+ */
3497
+ function checkExpectations(expectations, value) {
3498
+ var e_1, _a;
3499
+ try {
3500
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3501
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3502
+ var amount = CountUtils[unit.toUpperCase()](value);
3503
+ if (min && amount < min) {
3504
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3505
+ } /* not else */
3506
+ if (max && amount > max) {
3507
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3508
+ }
3509
+ }
3510
+ }
3511
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3512
+ finally {
3513
+ try {
3514
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3515
+ }
3516
+ finally { if (e_1) throw e_1.error; }
3517
+ }
3518
+ }
3519
+ /**
3520
+ * TODO: [💝] Unite object for expecting amount and format
3521
+ * TODO: [🧠][🤠] This should be part of `TextFormatDefinition`
3522
+ * Note: [💝] and [🤠] are interconnected together
3523
+ */
3524
+
3525
+ /**
3526
+ * @@@
3527
+ *
3528
+ * @private internal utility of `createPipelineExecutor`
3529
+ */
3530
+ function executeAttempts(options) {
3531
+ return __awaiter(this, void 0, void 0, function () {
3532
+ var jokerParameterNames, priority, maxAttempts, preparedContent, parameters, template, preparedPipeline, tools, llmTools, settings, $executionReport, pipelineIdentification, maxExecutionAttempts, $ongoingTemplateResult, _loop_1, attempt, state_1;
3533
+ return __generator(this, function (_a) {
3534
+ switch (_a.label) {
3535
+ case 0:
3536
+ 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;
3537
+ maxExecutionAttempts = settings.maxExecutionAttempts;
3538
+ $ongoingTemplateResult = {
3539
+ $result: null,
3540
+ $resultString: null,
3541
+ $expectError: null,
3542
+ $scriptPipelineExecutionErrors: [],
3543
+ };
3544
+ _loop_1 = function (attempt) {
3545
+ 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;
3546
+ var e_1, _q, e_3, _r, e_2, _s;
3547
+ return __generator(this, function (_t) {
3548
+ switch (_t.label) {
3549
+ case 0:
3550
+ isJokerAttempt = attempt < 0;
3551
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3552
+ // TODO: [🧠][🍭] JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3553
+ if (isJokerAttempt && !jokerParameterName) {
3554
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3555
+ }
3556
+ $ongoingTemplateResult.$result = null;
3557
+ $ongoingTemplateResult.$resultString = null;
3558
+ $ongoingTemplateResult.$expectError = null;
3559
+ if (isJokerAttempt) {
3560
+ if (parameters[jokerParameterName] === undefined) {
3561
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3562
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3563
+ }
3564
+ else {
3565
+ $ongoingTemplateResult.$resultString = parameters[jokerParameterName];
3566
+ }
3567
+ }
3568
+ _t.label = 1;
3569
+ case 1:
3570
+ _t.trys.push([1, 43, 44, 45]);
3571
+ if (!!isJokerAttempt) return [3 /*break*/, 25];
3572
+ _b = template.templateType;
3573
+ switch (_b) {
3574
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3575
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3576
+ case 'SCRIPT_TEMPLATE': return [3 /*break*/, 11];
3577
+ case 'DIALOG_TEMPLATE': return [3 /*break*/, 22];
3578
+ }
3579
+ return [3 /*break*/, 24];
3580
+ case 2:
3581
+ $ongoingTemplateResult.$resultString = replaceParameters(preparedContent, parameters);
3582
+ return [3 /*break*/, 25];
3583
+ case 3:
3584
+ modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (preparedPipeline.defaultModelRequirements || {})), (template.modelRequirements || {}));
3585
+ $ongoingTemplateResult.$prompt = {
3586
+ title: template.title,
3587
+ pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3588
+ ? preparedPipeline.pipelineUrl
3589
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(template.name),
3590
+ parameters: parameters,
3591
+ content: preparedContent,
3592
+ modelRequirements: modelRequirements,
3593
+ expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3594
+ var name = _a.name;
3595
+ return name === template.personaName;
3596
+ }) ||
3597
+ {})), template.expectations),
3598
+ format: template.format,
3599
+ postprocessingFunctionNames: template.postprocessingFunctionNames,
3600
+ }; // <- TODO: Not very good type guard
3601
+ _c = modelRequirements.modelVariant;
3602
+ switch (_c) {
3603
+ case 'CHAT': return [3 /*break*/, 4];
3604
+ case 'COMPLETION': return [3 /*break*/, 6];
3605
+ case 'EMBEDDING': return [3 /*break*/, 8];
3606
+ }
3607
+ return [3 /*break*/, 9];
3608
+ case 4:
3609
+ _d = $ongoingTemplateResult;
3610
+ return [4 /*yield*/, llmTools.callChatModel($deepFreeze($ongoingTemplateResult.$prompt))];
3611
+ case 5:
3612
+ _d.$chatResult = _t.sent();
3613
+ // TODO: [🍬] Destroy chatThread
3614
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$chatResult;
3615
+ $ongoingTemplateResult.$resultString = $ongoingTemplateResult.$chatResult.content;
3616
+ return [3 /*break*/, 10];
3617
+ case 6:
3618
+ _e = $ongoingTemplateResult;
3619
+ return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze($ongoingTemplateResult.$prompt))];
3620
+ case 7:
3621
+ _e.$completionResult = _t.sent();
3622
+ $ongoingTemplateResult.$result = $ongoingTemplateResult.$completionResult;
3623
+ $ongoingTemplateResult.$resultString =
3624
+ $ongoingTemplateResult.$completionResult.content;
3625
+ return [3 /*break*/, 10];
3626
+ 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 "); }));
3627
+ 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 "); }));
3628
+ case 10: return [3 /*break*/, 25];
3629
+ case 11:
3630
+ if (arrayableToArray(tools.script).length === 0) {
3631
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3632
+ }
3633
+ if (!template.contentLanguage) {
3634
+ 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 "); }));
3635
+ }
3636
+ _t.label = 12;
3637
+ case 12:
3638
+ _t.trys.push([12, 19, 20, 21]);
3639
+ _f = (e_1 = void 0, __values(arrayableToArray(tools.script))), _g = _f.next();
3640
+ _t.label = 13;
3641
+ case 13:
3642
+ if (!!_g.done) return [3 /*break*/, 18];
3643
+ scriptTools = _g.value;
3644
+ _t.label = 14;
3645
+ case 14:
3646
+ _t.trys.push([14, 16, , 17]);
3647
+ _h = $ongoingTemplateResult;
3648
+ return [4 /*yield*/, scriptTools.execute($deepFreeze({
3649
+ scriptLanguage: template.contentLanguage,
3650
+ script: preparedContent,
3651
+ parameters: parameters,
3652
+ }))];
3653
+ case 15:
3654
+ _h.$resultString = _t.sent();
3655
+ return [3 /*break*/, 18];
3656
+ case 16:
3657
+ error_1 = _t.sent();
3658
+ if (!(error_1 instanceof Error)) {
3659
+ throw error_1;
3660
+ }
3661
+ if (error_1 instanceof UnexpectedError) {
3662
+ throw error_1;
3663
+ }
3664
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_1);
3665
+ return [3 /*break*/, 17];
3666
+ case 17:
3667
+ _g = _f.next();
3668
+ return [3 /*break*/, 13];
3669
+ case 18: return [3 /*break*/, 21];
3670
+ case 19:
3671
+ e_1_1 = _t.sent();
3672
+ e_1 = { error: e_1_1 };
3673
+ return [3 /*break*/, 21];
3674
+ case 20:
3675
+ try {
3676
+ if (_g && !_g.done && (_q = _f.return)) _q.call(_f);
3677
+ }
3678
+ finally { if (e_1) throw e_1.error; }
3679
+ return [7 /*endfinally*/];
3680
+ case 21:
3681
+ if ($ongoingTemplateResult.$resultString !== null) {
3682
+ return [3 /*break*/, 25];
3683
+ }
3684
+ if ($ongoingTemplateResult.$scriptPipelineExecutionErrors.length === 1) {
3685
+ throw $ongoingTemplateResult.$scriptPipelineExecutionErrors[0];
3686
+ }
3687
+ else {
3688
+ 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
3689
+ .map(function (error) { return '- ' + error.message; })
3690
+ .join('\n\n')), "\n "); }));
3691
+ }
3692
+ case 22:
3693
+ if (tools.userInterface === undefined) {
3694
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3695
+ }
3696
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3697
+ _j = $ongoingTemplateResult;
3698
+ return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3699
+ promptTitle: template.title,
3700
+ promptMessage: replaceParameters(template.description || '', parameters),
3701
+ defaultValue: replaceParameters(preparedContent, parameters),
3702
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3703
+ placeholder: undefined,
3704
+ priority: priority,
3705
+ }))];
3706
+ case 23:
3707
+ // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3708
+ _j.$resultString = _t.sent();
3709
+ return [3 /*break*/, 25];
3710
+ case 24: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type \"".concat(template.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3711
+ case 25:
3712
+ if (!(!isJokerAttempt && template.postprocessingFunctionNames)) return [3 /*break*/, 42];
3713
+ _t.label = 26;
3714
+ case 26:
3715
+ _t.trys.push([26, 40, 41, 42]);
3716
+ _k = (e_3 = void 0, __values(template.postprocessingFunctionNames)), _l = _k.next();
3717
+ _t.label = 27;
3718
+ case 27:
3719
+ if (!!_l.done) return [3 /*break*/, 39];
3720
+ functionName = _l.value;
3721
+ postprocessingError = null;
3722
+ _t.label = 28;
3723
+ case 28:
3724
+ _t.trys.push([28, 35, 36, 37]);
3725
+ _m = (e_2 = void 0, __values(arrayableToArray(tools.script))), _o = _m.next();
3726
+ _t.label = 29;
3727
+ case 29:
3728
+ if (!!_o.done) return [3 /*break*/, 34];
3729
+ scriptTools = _o.value;
3730
+ _t.label = 30;
3731
+ case 30:
3732
+ _t.trys.push([30, 32, , 33]);
3733
+ _p = $ongoingTemplateResult;
3734
+ return [4 /*yield*/, scriptTools.execute({
3735
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3736
+ script: "".concat(functionName, "(resultString)"),
3737
+ parameters: {
3738
+ resultString: $ongoingTemplateResult.$resultString || '',
3739
+ // Note: No ...parametersForTemplate, because working with result only
3740
+ },
3741
+ })];
3742
+ case 31:
3743
+ _p.$resultString = _t.sent();
3744
+ postprocessingError = null;
3745
+ return [3 /*break*/, 34];
3746
+ case 32:
3747
+ error_2 = _t.sent();
3748
+ if (!(error_2 instanceof Error)) {
3749
+ throw error_2;
3750
+ }
3751
+ if (error_2 instanceof UnexpectedError) {
3752
+ throw error_2;
3753
+ }
3754
+ postprocessingError = error_2;
3755
+ $ongoingTemplateResult.$scriptPipelineExecutionErrors.push(error_2);
3756
+ return [3 /*break*/, 33];
3757
+ case 33:
3758
+ _o = _m.next();
3759
+ return [3 /*break*/, 29];
3760
+ case 34: return [3 /*break*/, 37];
3761
+ case 35:
3762
+ e_2_1 = _t.sent();
3763
+ e_2 = { error: e_2_1 };
3764
+ return [3 /*break*/, 37];
3765
+ case 36:
3766
+ try {
3767
+ if (_o && !_o.done && (_s = _m.return)) _s.call(_m);
3768
+ }
3769
+ finally { if (e_2) throw e_2.error; }
3770
+ return [7 /*endfinally*/];
3771
+ case 37:
3772
+ if (postprocessingError) {
3773
+ throw postprocessingError;
3774
+ }
3775
+ _t.label = 38;
3776
+ case 38:
3777
+ _l = _k.next();
3778
+ return [3 /*break*/, 27];
3779
+ case 39: return [3 /*break*/, 42];
3780
+ case 40:
3781
+ e_3_1 = _t.sent();
3782
+ e_3 = { error: e_3_1 };
3783
+ return [3 /*break*/, 42];
3784
+ case 41:
3785
+ try {
3786
+ if (_l && !_l.done && (_r = _k.return)) _r.call(_k);
3787
+ }
3788
+ finally { if (e_3) throw e_3.error; }
3789
+ return [7 /*endfinally*/];
3790
+ case 42:
3791
+ // TODO: [💝] Unite object for expecting amount and format
3792
+ if (template.format) {
3793
+ if (template.format === 'JSON') {
3794
+ if (!isValidJsonString($ongoingTemplateResult.$resultString || '')) {
3795
+ // TODO: [🏢] Do more universally via `FormatDefinition`
3796
+ try {
3797
+ $ongoingTemplateResult.$resultString = extractJsonBlock($ongoingTemplateResult.$resultString || '');
3798
+ }
3799
+ catch (error) {
3800
+ keepUnused(error);
3801
+ throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3802
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3803
+ }
3804
+ }
3805
+ }
3806
+ else {
3807
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown format \"".concat(template.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3808
+ }
3809
+ }
3810
+ // TODO: [💝] Unite object for expecting amount and format
3811
+ if (template.expectations) {
3812
+ checkExpectations(template.expectations, $ongoingTemplateResult.$resultString || '');
3813
+ }
3814
+ return [2 /*return*/, "break-attempts"];
3815
+ case 43:
3816
+ error_3 = _t.sent();
3817
+ if (!(error_3 instanceof ExpectError)) {
3818
+ throw error_3;
3819
+ }
3820
+ $ongoingTemplateResult.$expectError = error_3;
3821
+ return [3 /*break*/, 45];
3822
+ case 44:
3823
+ if (!isJokerAttempt &&
3824
+ template.templateType === 'PROMPT_TEMPLATE' &&
3825
+ $ongoingTemplateResult.$prompt
3826
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3827
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
3828
+ ) {
3829
+ // TODO: [🧠] Maybe put other templateTypes into report
3830
+ $executionReport.promptExecutions.push({
3831
+ prompt: __assign({}, $ongoingTemplateResult.$prompt),
3832
+ result: $ongoingTemplateResult.$result || undefined,
3833
+ error: $ongoingTemplateResult.$expectError === null
3834
+ ? undefined
3835
+ : serializeError($ongoingTemplateResult.$expectError),
3836
+ });
3837
+ }
3838
+ return [7 /*endfinally*/];
3839
+ case 45:
3840
+ if ($ongoingTemplateResult.$expectError !== null && attempt === maxAttempts - 1) {
3841
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) {
3842
+ var _a, _b, _c;
3843
+ 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) || '')
3844
+ .split('\n')
3845
+ .map(function (line) { return "> ".concat(line); })
3846
+ .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) || '')
3847
+ .split('\n')
3848
+ .map(function (line) { return "> ".concat(line); })
3849
+ .join('\n')), "\n\n Last result:\n ").concat(block($ongoingTemplateResult.$resultString === null
3850
+ ? 'null'
3851
+ : $ongoingTemplateResult.$resultString
3852
+ .split('\n')
3853
+ .map(function (line) { return "> ".concat(line); })
3854
+ .join('\n')), "\n ---\n ");
3855
+ }));
3856
+ }
3857
+ return [2 /*return*/];
3858
+ }
3859
+ });
3860
+ };
3861
+ attempt = -jokerParameterNames.length;
3862
+ _a.label = 1;
3863
+ case 1:
3864
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 4];
3865
+ return [5 /*yield**/, _loop_1(attempt)];
3866
+ case 2:
3867
+ state_1 = _a.sent();
3868
+ switch (state_1) {
3869
+ case "break-attempts": return [3 /*break*/, 4];
3870
+ }
3871
+ _a.label = 3;
3872
+ case 3:
3873
+ attempt++;
3874
+ return [3 /*break*/, 1];
3875
+ case 4:
3876
+ if ($ongoingTemplateResult.$resultString === null) {
3877
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3878
+ }
3879
+ return [2 /*return*/, $ongoingTemplateResult.$resultString];
3880
+ }
3881
+ });
3882
+ });
3883
+ }
3884
+ /**
3885
+ * TODO: Break into smaller functions
3886
+ */
3887
+
3888
+ /**
3889
+ * @@@
3890
+ *
3891
+ * @private internal utility of `createPipelineExecutor`
3892
+ */
3893
+ function executeFormatCells(options) {
3894
+ return __awaiter(this, void 0, void 0, function () {
3895
+ var template, jokerParameterNames, parameters, priority, pipelineIdentification, settings, parameterValue, formatDefinition, subvalueDefinition, formatSettings, resultString;
3896
+ var _this = this;
3897
+ return __generator(this, function (_a) {
3898
+ switch (_a.label) {
3899
+ case 0:
3900
+ template = options.template, jokerParameterNames = options.jokerParameterNames, parameters = options.parameters, priority = options.priority, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
3901
+ if (template.foreach === undefined) {
3902
+ return [2 /*return*/, /* not await */ executeAttempts(options)];
3903
+ }
3904
+ if (jokerParameterNames.length !== 0) {
3905
+ 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 "); }));
3906
+ }
3907
+ parameterValue = parameters[template.foreach.parameterName] || '';
3908
+ formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
3909
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(template.foreach.formatName);
3910
+ });
3911
+ if (formatDefinition === undefined) {
3912
+ throw new UnexpectedError(
3913
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
3914
+ 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; })
3915
+ .map(function (formatName) { return "- ".concat(formatName); })
3916
+ .join('\n')), "\n\n [\u26F7] This should never happen because format name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
3917
+ }
3918
+ subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
3919
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(template.foreach.subformatName);
3920
+ });
3921
+ if (subvalueDefinition === undefined) {
3922
+ throw new UnexpectedError(
3923
+ // <- TODO: [🧠][🧐] Should be formats fixed per promptbook version or behave as plugins (=> change UnexpectedError)
3924
+ 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
3925
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
3926
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
3927
+ .join('\n')), "\n\n [\u26F7] This should never happen because subformat name should be validated during parsing\n\n ").concat(block(pipelineIdentification), "\n "); }));
3928
+ }
3929
+ if (formatDefinition.formatName === 'CSV') {
3930
+ formatSettings = settings.csvSettings;
3931
+ // <- TODO: !!!!!! More universal, make simmilar pattern for other formats for example \n vs \r\n in text
3932
+ }
3933
+ return [4 /*yield*/, subvalueDefinition.mapValues(parameterValue, template.foreach.outputSubparameterName, formatSettings, function (subparameters, index) { return __awaiter(_this, void 0, void 0, function () {
3934
+ var mappedParameters, allSubparameters, subresultString;
3935
+ return __generator(this, function (_a) {
3936
+ switch (_a.label) {
3937
+ case 0:
3938
+ // TODO: !!!!!!! Limit to N concurrent executions
3939
+ // TODO: !!!!!!! Report progress
3940
+ try {
3941
+ mappedParameters = mapAvailableToExpectedParameters({
3942
+ expectedParameters: Object.fromEntries(template.foreach.inputSubparameterNames.map(function (subparameterName) { return [subparameterName, null]; })),
3943
+ availableParameters: subparameters,
3944
+ });
3945
+ }
3946
+ catch (error) {
3947
+ if (!(error instanceof PipelineExecutionError)) {
3948
+ throw error;
3949
+ }
3950
+ 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 "); }));
3951
+ }
3952
+ allSubparameters = __assign(__assign({}, parameters), mappedParameters);
3953
+ // 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
3954
+ Object.freeze(allSubparameters);
3955
+ 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 "); }) }))];
3956
+ case 1:
3957
+ subresultString = _a.sent();
3958
+ return [2 /*return*/, subresultString];
3959
+ }
3960
+ });
3961
+ }); })];
3962
+ case 1:
3963
+ resultString = _a.sent();
3964
+ return [2 /*return*/, resultString];
3965
+ }
3966
+ });
3967
+ });
3968
+ }
3969
+ /**
3970
+ * TODO: !!!!!! Make pipelineIdentification more precise
3971
+ * TODO: !!!!!! How FOREACH execution looks in the report
3972
+ */
3973
+
3974
+ /**
3975
+ * @@@
3976
+ *
3977
+ * @private internal utility of `createPipelineExecutor`
3978
+ */
3979
+ function getContextForTemplate(template) {
3980
+ return __awaiter(this, void 0, void 0, function () {
3981
+ return __generator(this, function (_a) {
3982
+ TODO_USE(template);
3983
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3984
+ });
3985
+ });
3986
+ }
3987
+
3988
+ /**
3989
+ * @@@
3990
+ *
3991
+ * @private internal utility of `createPipelineExecutor`
3992
+ */
3993
+ function getKnowledgeForTemplate(options) {
3994
+ return __awaiter(this, void 0, void 0, function () {
3995
+ var preparedPipeline, template;
3996
+ return __generator(this, function (_a) {
3997
+ preparedPipeline = options.preparedPipeline, template = options.template;
3998
+ // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3999
+ TODO_USE(template);
4000
+ return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
4001
+ var content = _a.content;
4002
+ return "- ".concat(content);
4003
+ }).join('\n')];
4004
+ });
4005
+ });
4006
+ }
4007
+
4008
+ /**
4009
+ * @@@
4010
+ *
4011
+ * @private internal utility of `createPipelineExecutor`
4012
+ */
4013
+ function getSamplesForTemplate(template) {
4014
+ return __awaiter(this, void 0, void 0, function () {
4015
+ return __generator(this, function (_a) {
4016
+ // TODO: [♨] Implement Better - use real index and keyword search
4017
+ TODO_USE(template);
4018
+ return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
4019
+ });
4020
+ });
4021
+ }
4022
+
4023
+ /**
4024
+ * @@@
3084
4025
  *
3085
- * @public exported from `@promptbook/utils`
4026
+ * @private internal utility of `createPipelineExecutor`
3086
4027
  */
3087
- function countSentences(text) {
3088
- return splitIntoSentences(text).length;
4028
+ function getReservedParametersForTemplate(options) {
4029
+ return __awaiter(this, void 0, void 0, function () {
4030
+ var preparedPipeline, template, pipelineIdentification, context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_1, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
4031
+ var e_1, _a;
4032
+ return __generator(this, function (_b) {
4033
+ switch (_b.label) {
4034
+ case 0:
4035
+ preparedPipeline = options.preparedPipeline, template = options.template, pipelineIdentification = options.pipelineIdentification;
4036
+ return [4 /*yield*/, getContextForTemplate(template)];
4037
+ case 1:
4038
+ context = _b.sent();
4039
+ return [4 /*yield*/, getKnowledgeForTemplate({ preparedPipeline: preparedPipeline, template: template })];
4040
+ case 2:
4041
+ knowledge = _b.sent();
4042
+ return [4 /*yield*/, getSamplesForTemplate(template)];
4043
+ case 3:
4044
+ samples = _b.sent();
4045
+ currentDate = new Date().toISOString();
4046
+ modelName = RESERVED_PARAMETER_MISSING_VALUE;
4047
+ reservedParameters = {
4048
+ content: RESERVED_PARAMETER_RESTRICTED,
4049
+ context: context,
4050
+ knowledge: knowledge,
4051
+ samples: samples,
4052
+ currentDate: currentDate,
4053
+ modelName: modelName,
4054
+ };
4055
+ _loop_1 = function (parameterName) {
4056
+ if (reservedParameters[parameterName] === undefined) {
4057
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
4058
+ }
4059
+ };
4060
+ try {
4061
+ // Note: Doublecheck that ALL reserved parameters are defined:
4062
+ 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()) {
4063
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
4064
+ _loop_1(parameterName);
4065
+ }
4066
+ }
4067
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4068
+ finally {
4069
+ try {
4070
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
4071
+ }
4072
+ finally { if (e_1) throw e_1.error; }
4073
+ }
4074
+ return [2 /*return*/, reservedParameters];
4075
+ }
4076
+ });
4077
+ });
3089
4078
  }
3090
4079
 
3091
4080
  /**
3092
- * Counts number of words in the text
4081
+ * @@@
3093
4082
  *
3094
- * @public exported from `@promptbook/utils`
4083
+ * @private internal utility of `createPipelineExecutor`
3095
4084
  */
3096
- function countWords(text) {
3097
- text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
3098
- text = removeDiacritics(text);
3099
- return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
4085
+ function executeTemplate(options) {
4086
+ return __awaiter(this, void 0, void 0, function () {
4087
+ 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;
4088
+ var e_1, _f, _g;
4089
+ return __generator(this, function (_h) {
4090
+ switch (_h.label) {
4091
+ case 0:
4092
+ 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;
4093
+ maxExecutionAttempts = settings.maxExecutionAttempts;
4094
+ name = "pipeline-executor-frame-".concat(currentTemplate.name);
4095
+ title = currentTemplate.title;
4096
+ priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
4097
+ return [4 /*yield*/, onProgress({
4098
+ name: name,
4099
+ title: title,
4100
+ isStarted: false,
4101
+ isDone: false,
4102
+ templateType: currentTemplate.templateType,
4103
+ parameterName: currentTemplate.resultingParameterName,
4104
+ parameterValue: null,
4105
+ // <- [🍸]
4106
+ })];
4107
+ case 1:
4108
+ _h.sent();
4109
+ usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
4110
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
4111
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4112
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
4113
+ 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)
4114
+ .map(function (name) { return "{".concat(name, "}"); })
4115
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
4116
+ .map(function (name) { return "{".concat(name, "}"); })
4117
+ .join(', '), "\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
4118
+ }
4119
+ _b = (_a = Object).freeze;
4120
+ _c = [{}];
4121
+ return [4 /*yield*/, getReservedParametersForTemplate({
4122
+ preparedPipeline: preparedPipeline,
4123
+ template: currentTemplate,
4124
+ pipelineIdentification: pipelineIdentification,
4125
+ })];
4126
+ case 2:
4127
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
4128
+ definedParameterNames = new Set(Object.keys(definedParameters));
4129
+ parameters = {};
4130
+ _loop_1 = function (parameterName) {
4131
+ // Situation: Parameter is defined and used
4132
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4133
+ parameters[parameterName] = definedParameters[parameterName];
4134
+ }
4135
+ // Situation: Parameter is defined but NOT used
4136
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
4137
+ // Situation: Parameter is NOT defined BUT used
4138
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
4139
+ // Houston, we have a problem
4140
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
4141
+ 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 "); }));
4142
+ }
4143
+ };
4144
+ try {
4145
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
4146
+ // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
4147
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
4148
+ parameterName = _e.value;
4149
+ _loop_1(parameterName);
4150
+ }
4151
+ }
4152
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4153
+ finally {
4154
+ try {
4155
+ if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
4156
+ }
4157
+ finally { if (e_1) throw e_1.error; }
4158
+ }
4159
+ // 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
4160
+ Object.freeze(parameters);
4161
+ maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
4162
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
4163
+ preparedContent = (currentTemplate.preparedContent || '{content}')
4164
+ .split('{content}')
4165
+ .join(currentTemplate.content);
4166
+ return [4 /*yield*/, executeFormatCells({
4167
+ jokerParameterNames: jokerParameterNames,
4168
+ priority: priority,
4169
+ maxAttempts: maxAttempts,
4170
+ preparedContent: preparedContent,
4171
+ parameters: parameters,
4172
+ template: currentTemplate,
4173
+ preparedPipeline: preparedPipeline,
4174
+ tools: tools,
4175
+ llmTools: llmTools,
4176
+ settings: settings,
4177
+ $executionReport: $executionReport,
4178
+ pipelineIdentification: pipelineIdentification,
4179
+ })];
4180
+ case 3:
4181
+ resultString = _h.sent();
4182
+ return [4 /*yield*/, onProgress({
4183
+ name: name,
4184
+ title: title,
4185
+ isStarted: true,
4186
+ isDone: true,
4187
+ templateType: currentTemplate.templateType,
4188
+ parameterName: currentTemplate.resultingParameterName,
4189
+ parameterValue: resultString,
4190
+ // <- [🍸]
4191
+ })];
4192
+ case 4:
4193
+ _h.sent();
4194
+ return [2 /*return*/, Object.freeze((_g = {},
4195
+ _g[currentTemplate.resultingParameterName] =
4196
+ // <- Note: [👩‍👩‍👧] No need to detect parameter collision here because pipeline checks logic consistency during construction
4197
+ resultString,
4198
+ _g))];
4199
+ }
4200
+ });
4201
+ });
3100
4202
  }
3101
-
3102
4203
  /**
3103
- * Index of all counter functions
3104
- *
3105
- * @public exported from `@promptbook/utils`
4204
+ * TODO: [🤹‍♂️]
3106
4205
  */
3107
- var CountUtils = {
3108
- CHARACTERS: countCharacters,
3109
- WORDS: countWords,
3110
- SENTENCES: countSentences,
3111
- PARAGRAPHS: countParagraphs,
3112
- LINES: countLines,
3113
- PAGES: countPages,
3114
- };
3115
4206
 
3116
4207
  /**
3117
- * Function checkExpectations will check if the expectations on given value are met
3118
- *
3119
- * Note: There are two simmilar functions:
3120
- * - `checkExpectations` which throws an error if the expectations are not met
3121
- * - `isPassingExpectations` which returns a boolean
4208
+ * @@@
3122
4209
  *
3123
- * @throws {ExpectError} if the expectations are not met
3124
- * @returns {void} Nothing
3125
- * @private internal function of `createPipelineExecutor`
4210
+ * @private internal utility of `createPipelineExecutor`
3126
4211
  */
3127
- function checkExpectations(expectations, value) {
4212
+ function filterJustOutputParameters(options) {
3128
4213
  var e_1, _a;
4214
+ var preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, $warnings = options.$warnings, pipelineIdentification = options.pipelineIdentification;
4215
+ var outputParameters = {};
4216
+ var _loop_1 = function (parameter) {
4217
+ if (parametersToPass[parameter.name] === undefined) {
4218
+ // [4]
4219
+ $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 "); })));
4220
+ return "continue";
4221
+ }
4222
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
4223
+ };
3129
4224
  try {
3130
- for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
3131
- var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
3132
- var amount = CountUtils[unit.toUpperCase()](value);
3133
- if (min && amount < min) {
3134
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
3135
- } /* not else */
3136
- if (max && amount > max) {
3137
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
3138
- }
4225
+ // Note: Filter ONLY output parameters
4226
+ // TODO: [👩🏾‍🤝‍👩🏻] Maybe use here `mapAvailableToExpectedParameters`
4227
+ for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
4228
+ var isOutput = _a.isOutput;
4229
+ return isOutput;
4230
+ })), _c = _b.next(); !_c.done; _c = _b.next()) {
4231
+ var parameter = _c.value;
4232
+ _loop_1(parameter);
3139
4233
  }
3140
4234
  }
3141
4235
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
@@ -3145,614 +4239,27 @@
3145
4239
  }
3146
4240
  finally { if (e_1) throw e_1.error; }
3147
4241
  }
4242
+ return outputParameters;
3148
4243
  }
3149
- /**
3150
- * TODO: [💝] Unite object for expecting amount and format
3151
- */
3152
4244
 
3153
4245
  /**
3154
- * Creates executor function from pipeline and execution tools.
4246
+ * @@@
3155
4247
  *
3156
- * @returns The executor function
3157
- * @throws {PipelineLogicError} on logical error in the pipeline
3158
- * @public exported from `@promptbook/core`
4248
+ * Note: This is not a `PipelineExecutor` (which is binded with one exact pipeline), but a utility function of `createPipelineExecutor` which creates `PipelineExecutor`
4249
+ *
4250
+ * @private internal utility of `createPipelineExecutor`
3159
4251
  */
3160
- function createPipelineExecutor(options) {
3161
- var _this = this;
3162
- var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
3163
- 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;
3164
- validatePipeline(pipeline);
3165
- var pipelineIdentification = (function () {
3166
- // Note: This is a 😐 implementation of [🚞]
3167
- var _ = [];
3168
- if (pipeline.sourceFile !== undefined) {
3169
- _.push("File: ".concat(pipeline.sourceFile));
3170
- }
3171
- if (pipeline.pipelineUrl !== undefined) {
3172
- _.push("Url: ".concat(pipeline.pipelineUrl));
3173
- }
3174
- return _.join('\n');
3175
- })();
3176
- var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3177
- var preparedPipeline;
3178
- if (isPipelinePrepared(pipeline)) {
3179
- preparedPipeline = pipeline;
3180
- }
3181
- else if (isNotPreparedWarningSupressed !== true) {
3182
- 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 "); }));
3183
- }
3184
- var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
3185
- // TODO: !!! Extract to separate functions and files - ALL FUNCTIONS BELOW
3186
- function getContextForTemplate(template) {
3187
- return __awaiter(this, void 0, void 0, function () {
3188
- return __generator(this, function (_a) {
3189
- TODO_USE(template);
3190
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [🏍] Implement */];
3191
- });
3192
- });
3193
- }
3194
- function getKnowledgeForTemplate(template) {
3195
- return __awaiter(this, void 0, void 0, function () {
3196
- return __generator(this, function (_a) {
3197
- // TODO: [♨] Implement Better - use real index and keyword search from `template` and {samples}
3198
- TODO_USE(template);
3199
- return [2 /*return*/, preparedPipeline.knowledgePieces.map(function (_a) {
3200
- var content = _a.content;
3201
- return "- ".concat(content);
3202
- }).join('\n')];
3203
- });
3204
- });
3205
- }
3206
- function getSamplesForTemplate(template) {
3207
- return __awaiter(this, void 0, void 0, function () {
3208
- return __generator(this, function (_a) {
3209
- // TODO: [♨] Implement Better - use real index and keyword search
3210
- TODO_USE(template);
3211
- return [2 /*return*/, RESERVED_PARAMETER_MISSING_VALUE /* <- TODO: [♨] Implement */];
3212
- });
3213
- });
3214
- }
3215
- function getReservedParametersForTemplate(template) {
3216
- return __awaiter(this, void 0, void 0, function () {
3217
- var context, knowledge, samples, currentDate, modelName, reservedParameters, _loop_3, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
3218
- var e_3, _a;
3219
- return __generator(this, function (_b) {
3220
- switch (_b.label) {
3221
- case 0: return [4 /*yield*/, getContextForTemplate(template)];
3222
- case 1:
3223
- context = _b.sent();
3224
- return [4 /*yield*/, getKnowledgeForTemplate(template)];
3225
- case 2:
3226
- knowledge = _b.sent();
3227
- return [4 /*yield*/, getSamplesForTemplate(template)];
3228
- case 3:
3229
- samples = _b.sent();
3230
- currentDate = new Date().toISOString();
3231
- modelName = RESERVED_PARAMETER_MISSING_VALUE;
3232
- reservedParameters = {
3233
- content: RESERVED_PARAMETER_RESTRICTED,
3234
- context: context,
3235
- knowledge: knowledge,
3236
- samples: samples,
3237
- currentDate: currentDate,
3238
- modelName: modelName,
3239
- };
3240
- _loop_3 = function (parameterName) {
3241
- if (reservedParameters[parameterName] === undefined) {
3242
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Reserved parameter {".concat(parameterName, "} is not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3243
- }
3244
- };
3245
- try {
3246
- // Note: Doublecheck that ALL reserved parameters are defined:
3247
- 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()) {
3248
- parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
3249
- _loop_3(parameterName);
3250
- }
3251
- }
3252
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
3253
- finally {
3254
- try {
3255
- if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
3256
- }
3257
- finally { if (e_3) throw e_3.error; }
3258
- }
3259
- return [2 /*return*/, reservedParameters];
3260
- }
3261
- });
3262
- });
3263
- }
3264
- function executeSingleTemplate(currentTemplate) {
3265
- return __awaiter(this, void 0, void 0, function () {
3266
- 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;
3267
- var e_4, _f, _g;
3268
- return __generator(this, function (_h) {
3269
- switch (_h.label) {
3270
- case 0:
3271
- name = "pipeline-executor-frame-".concat(currentTemplate.name);
3272
- title = currentTemplate.title;
3273
- priority = preparedPipeline.templates.length - preparedPipeline.templates.indexOf(currentTemplate);
3274
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
3275
- progress_1 = {
3276
- name: name,
3277
- title: title,
3278
- isStarted: false,
3279
- isDone: false,
3280
- templateType: currentTemplate.templateType,
3281
- parameterName: currentTemplate.resultingParameterName,
3282
- parameterValue: null,
3283
- // <- [3]
3284
- };
3285
- if (isReturned) {
3286
- 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)
3287
- .split('\n')
3288
- .map(function (line) { return "> ".concat(line); })
3289
- .join('\n')), "\n "); }));
3290
- }
3291
- return [4 /*yield*/, onProgress(progress_1)];
3292
- case 1:
3293
- _h.sent();
3294
- _h.label = 2;
3295
- case 2:
3296
- usedParameterNames = extractParameterNamesFromTemplate(currentTemplate);
3297
- dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3298
- if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3299
- 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)
3300
- .map(function (name) { return "{".concat(name, "}"); })
3301
- .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3302
- .map(function (name) { return "{".concat(name, "}"); })
3303
- .join(', '), "\n\n "); }));
3304
- }
3305
- _b = (_a = Object).freeze;
3306
- _c = [{}];
3307
- return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
3308
- case 3:
3309
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
3310
- definedParameterNames = new Set(Object.keys(definedParameters));
3311
- parameters = {};
3312
- _loop_4 = function (parameterName) {
3313
- // Situation: Parameter is defined and used
3314
- if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3315
- parameters[parameterName] = definedParameters[parameterName];
3316
- }
3317
- // Situation: Parameter is defined but NOT used
3318
- else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) ;
3319
- // Situation: Parameter is NOT defined BUT used
3320
- else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
3321
- // Houston, we have a problem
3322
- // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
3323
- 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 "); }));
3324
- }
3325
- };
3326
- try {
3327
- // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
3328
- for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
3329
- parameterName = _e.value;
3330
- _loop_4(parameterName);
3331
- }
3332
- }
3333
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
3334
- finally {
3335
- try {
3336
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
3337
- }
3338
- finally { if (e_4) throw e_4.error; }
3339
- }
3340
- // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
3341
- Object.freeze(parameters);
3342
- result = null;
3343
- resultString = null;
3344
- expectError = null;
3345
- maxAttempts = currentTemplate.templateType === 'DIALOG_TEMPLATE' ? Infinity : maxExecutionAttempts;
3346
- jokerParameterNames = currentTemplate.jokerParameterNames || [];
3347
- preparedContent = (currentTemplate.preparedContent || '{content}')
3348
- .split('{content}')
3349
- .join(currentTemplate.content);
3350
- _loop_5 = function (attempt) {
3351
- 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;
3352
- var e_5, _s, e_7, _t, e_6, _u;
3353
- return __generator(this, function (_v) {
3354
- switch (_v.label) {
3355
- case 0:
3356
- isJokerAttempt = attempt < 0;
3357
- jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
3358
- // TODO: [🧠] !!!!!! JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
3359
- if (isJokerAttempt && !jokerParameterName) {
3360
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Joker not found in attempt ".concat(attempt, "\n\n ").concat(block(pipelineIdentification), "\n "); }));
3361
- }
3362
- result = null;
3363
- resultString = null;
3364
- expectError = null;
3365
- if (isJokerAttempt) {
3366
- if (parameters[jokerParameterName] === undefined) {
3367
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Joker parameter {".concat(jokerParameterName, "} not defined\n\n ").concat(block(pipelineIdentification), "\n "); }));
3368
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
3369
- }
3370
- else {
3371
- resultString = parameters[jokerParameterName];
3372
- }
3373
- }
3374
- _v.label = 1;
3375
- case 1:
3376
- _v.trys.push([1, 44, 45, 46]);
3377
- if (!!isJokerAttempt) return [3 /*break*/, 26];
3378
- _j = currentTemplate.templateType;
3379
- switch (_j) {
3380
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 2];
3381
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 3];
3382
- case 'SCRIPT_TEMPLATE': return [3 /*break*/, 12];
3383
- case 'DIALOG_TEMPLATE': return [3 /*break*/, 23];
3384
- }
3385
- return [3 /*break*/, 25];
3386
- case 2:
3387
- resultString = replaceParameters(preparedContent, parameters);
3388
- return [3 /*break*/, 26];
3389
- case 3:
3390
- modelRequirements = __assign(__assign({ modelVariant: 'CHAT' }, (pipeline.defaultModelRequirements || {})), (currentTemplate.modelRequirements || {}));
3391
- prompt = {
3392
- title: currentTemplate.title,
3393
- pipelineUrl: "".concat(preparedPipeline.pipelineUrl
3394
- ? preparedPipeline.pipelineUrl
3395
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
3396
- parameters: parameters,
3397
- content: preparedContent,
3398
- modelRequirements: modelRequirements,
3399
- expectations: __assign(__assign({}, (preparedPipeline.personas.find(function (_a) {
3400
- var name = _a.name;
3401
- return name === currentTemplate.personaName;
3402
- }) || {})), currentTemplate.expectations),
3403
- format: currentTemplate.format,
3404
- postprocessingFunctionNames: currentTemplate.postprocessingFunctionNames,
3405
- }; // <- TODO: Not very good type guard
3406
- _k = modelRequirements.modelVariant;
3407
- switch (_k) {
3408
- case 'CHAT': return [3 /*break*/, 4];
3409
- case 'COMPLETION': return [3 /*break*/, 6];
3410
- case 'EMBEDDING': return [3 /*break*/, 8];
3411
- }
3412
- return [3 /*break*/, 10];
3413
- case 4: return [4 /*yield*/, llmTools.callChatModel($deepFreeze(prompt))];
3414
- case 5:
3415
- chatResult = _v.sent();
3416
- // TODO: [🍬] Destroy chatThread
3417
- result = chatResult;
3418
- resultString = chatResult.content;
3419
- return [3 /*break*/, 11];
3420
- case 6: return [4 /*yield*/, llmTools.callCompletionModel($deepFreeze(prompt))];
3421
- case 7:
3422
- completionResult = _v.sent();
3423
- result = completionResult;
3424
- resultString = completionResult.content;
3425
- return [3 /*break*/, 11];
3426
- case 8: return [4 /*yield*/, llmTools.callEmbeddingModel($deepFreeze(prompt))];
3427
- case 9:
3428
- embeddingResult = _v.sent();
3429
- result = embeddingResult;
3430
- resultString = embeddingResult.content.join(',');
3431
- return [3 /*break*/, 11];
3432
- case 10: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model variant \"".concat(currentTemplate.modelRequirements
3433
- .modelVariant, "\"\n\n ").concat(block(pipelineIdentification), "\n\n "); }));
3434
- case 11: return [3 /*break*/, 26];
3435
- case 12:
3436
- if (arrayableToArray(tools.script).length === 0) {
3437
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n No script execution tools are available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3438
- }
3439
- if (!currentTemplate.contentLanguage) {
3440
- 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 "); }));
3441
- }
3442
- // TODO: DRY [1]
3443
- scriptPipelineExecutionErrors = [];
3444
- _v.label = 13;
3445
- case 13:
3446
- _v.trys.push([13, 20, 21, 22]);
3447
- _l = (e_5 = void 0, __values(arrayableToArray(tools.script))), _m = _l.next();
3448
- _v.label = 14;
3449
- case 14:
3450
- if (!!_m.done) return [3 /*break*/, 19];
3451
- scriptTools = _m.value;
3452
- _v.label = 15;
3453
- case 15:
3454
- _v.trys.push([15, 17, , 18]);
3455
- return [4 /*yield*/, scriptTools.execute($deepFreeze({
3456
- scriptLanguage: currentTemplate.contentLanguage,
3457
- script: preparedContent,
3458
- parameters: parameters,
3459
- }))];
3460
- case 16:
3461
- resultString = _v.sent();
3462
- return [3 /*break*/, 19];
3463
- case 17:
3464
- error_2 = _v.sent();
3465
- if (!(error_2 instanceof Error)) {
3466
- throw error_2;
3467
- }
3468
- if (error_2 instanceof UnexpectedError) {
3469
- throw error_2;
3470
- }
3471
- scriptPipelineExecutionErrors.push(error_2);
3472
- return [3 /*break*/, 18];
3473
- case 18:
3474
- _m = _l.next();
3475
- return [3 /*break*/, 14];
3476
- case 19: return [3 /*break*/, 22];
3477
- case 20:
3478
- e_5_1 = _v.sent();
3479
- e_5 = { error: e_5_1 };
3480
- return [3 /*break*/, 22];
3481
- case 21:
3482
- try {
3483
- if (_m && !_m.done && (_s = _l.return)) _s.call(_l);
3484
- }
3485
- finally { if (e_5) throw e_5.error; }
3486
- return [7 /*endfinally*/];
3487
- case 22:
3488
- if (resultString !== null) {
3489
- return [3 /*break*/, 26];
3490
- }
3491
- if (scriptPipelineExecutionErrors.length === 1) {
3492
- throw scriptPipelineExecutionErrors[0];
3493
- }
3494
- else {
3495
- 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
3496
- .map(function (error) { return '- ' + error.message; })
3497
- .join('\n\n')), "\n "); }));
3498
- }
3499
- case 23:
3500
- if (tools.userInterface === undefined) {
3501
- throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n User interface tools are not available\n\n ".concat(block(pipelineIdentification), "\n "); }));
3502
- }
3503
- return [4 /*yield*/, tools.userInterface.promptDialog($deepFreeze({
3504
- promptTitle: currentTemplate.title,
3505
- promptMessage: replaceParameters(currentTemplate.description || '', parameters),
3506
- defaultValue: replaceParameters(preparedContent, parameters),
3507
- // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
3508
- placeholder: undefined,
3509
- priority: priority,
3510
- }))];
3511
- case 24:
3512
- // TODO: [🌹] When making next attempt for `DIALOG TEMPLATE`, preserve the previous user input
3513
- resultString = _v.sent();
3514
- return [3 /*break*/, 26];
3515
- case 25: throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type \"".concat(currentTemplate.templateType, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3516
- case 26:
3517
- if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 43];
3518
- _v.label = 27;
3519
- case 27:
3520
- _v.trys.push([27, 41, 42, 43]);
3521
- _o = (e_7 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _p = _o.next();
3522
- _v.label = 28;
3523
- case 28:
3524
- if (!!_p.done) return [3 /*break*/, 40];
3525
- functionName = _p.value;
3526
- // TODO: DRY [1]
3527
- scriptPipelineExecutionErrors = [];
3528
- postprocessingError = null;
3529
- _v.label = 29;
3530
- case 29:
3531
- _v.trys.push([29, 36, 37, 38]);
3532
- _q = (e_6 = void 0, __values(arrayableToArray(tools.script))), _r = _q.next();
3533
- _v.label = 30;
3534
- case 30:
3535
- if (!!_r.done) return [3 /*break*/, 35];
3536
- scriptTools = _r.value;
3537
- _v.label = 31;
3538
- case 31:
3539
- _v.trys.push([31, 33, , 34]);
3540
- return [4 /*yield*/, scriptTools.execute({
3541
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
3542
- script: "".concat(functionName, "(resultString)"),
3543
- parameters: {
3544
- resultString: resultString || '',
3545
- // Note: No ...parametersForTemplate, because working with result only
3546
- },
3547
- })];
3548
- case 32:
3549
- resultString = _v.sent();
3550
- postprocessingError = null;
3551
- return [3 /*break*/, 35];
3552
- case 33:
3553
- error_3 = _v.sent();
3554
- if (!(error_3 instanceof Error)) {
3555
- throw error_3;
3556
- }
3557
- if (error_3 instanceof UnexpectedError) {
3558
- throw error_3;
3559
- }
3560
- postprocessingError = error_3;
3561
- scriptPipelineExecutionErrors.push(error_3);
3562
- return [3 /*break*/, 34];
3563
- case 34:
3564
- _r = _q.next();
3565
- return [3 /*break*/, 30];
3566
- case 35: return [3 /*break*/, 38];
3567
- case 36:
3568
- e_6_1 = _v.sent();
3569
- e_6 = { error: e_6_1 };
3570
- return [3 /*break*/, 38];
3571
- case 37:
3572
- try {
3573
- if (_r && !_r.done && (_u = _q.return)) _u.call(_q);
3574
- }
3575
- finally { if (e_6) throw e_6.error; }
3576
- return [7 /*endfinally*/];
3577
- case 38:
3578
- if (postprocessingError) {
3579
- throw postprocessingError;
3580
- }
3581
- _v.label = 39;
3582
- case 39:
3583
- _p = _o.next();
3584
- return [3 /*break*/, 28];
3585
- case 40: return [3 /*break*/, 43];
3586
- case 41:
3587
- e_7_1 = _v.sent();
3588
- e_7 = { error: e_7_1 };
3589
- return [3 /*break*/, 43];
3590
- case 42:
3591
- try {
3592
- if (_p && !_p.done && (_t = _o.return)) _t.call(_o);
3593
- }
3594
- finally { if (e_7) throw e_7.error; }
3595
- return [7 /*endfinally*/];
3596
- case 43:
3597
- // TODO: [💝] Unite object for expecting amount and format
3598
- if (currentTemplate.format) {
3599
- if (currentTemplate.format === 'JSON') {
3600
- if (!isValidJsonString(resultString || '')) {
3601
- // TODO: [🏢] Do more universally via `FormatDefinition`
3602
- try {
3603
- resultString = extractJsonBlock(resultString || '');
3604
- }
3605
- catch (error) {
3606
- keepUnused(error);
3607
- throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3608
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3609
- }
3610
- }
3611
- }
3612
- else {
3613
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown format \"".concat(currentTemplate.format, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3614
- }
3615
- }
3616
- // TODO: [💝] Unite object for expecting amount and format
3617
- if (currentTemplate.expectations) {
3618
- checkExpectations(currentTemplate.expectations, resultString || '');
3619
- }
3620
- return [2 /*return*/, "break-attempts"];
3621
- case 44:
3622
- error_4 = _v.sent();
3623
- if (!(error_4 instanceof ExpectError)) {
3624
- throw error_4;
3625
- }
3626
- expectError = error_4;
3627
- return [3 /*break*/, 46];
3628
- case 45:
3629
- if (!isJokerAttempt &&
3630
- currentTemplate.templateType === 'PROMPT_TEMPLATE' &&
3631
- prompt
3632
- // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
3633
- // In that case we don’t want to make a report about it because it’s not a llm execution error
3634
- ) {
3635
- // TODO: [🧠] Maybe put other templateTypes into report
3636
- executionReport.promptExecutions.push({
3637
- prompt: __assign({}, prompt),
3638
- result: result || undefined,
3639
- error: expectError === null ? undefined : serializeError(expectError),
3640
- });
3641
- }
3642
- return [7 /*endfinally*/];
3643
- case 46:
3644
- if (expectError !== null && attempt === maxAttempts - 1) {
3645
- 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
3646
- .split('\n')
3647
- .map(function (line) { return "> ".concat(line); })
3648
- .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) || '')
3649
- .split('\n')
3650
- .map(function (line) { return "> ".concat(line); })
3651
- .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3652
- ? 'null'
3653
- : resultString
3654
- .split('\n')
3655
- .map(function (line) { return "> ".concat(line); })
3656
- .join('\n')), "\n ---\n "); }));
3657
- }
3658
- return [2 /*return*/];
3659
- }
3660
- });
3661
- };
3662
- attempt = -jokerParameterNames.length;
3663
- _h.label = 4;
3664
- case 4:
3665
- if (!(attempt < maxAttempts)) return [3 /*break*/, 7];
3666
- return [5 /*yield**/, _loop_5(attempt)];
3667
- case 5:
3668
- state_2 = _h.sent();
3669
- switch (state_2) {
3670
- case "break-attempts": return [3 /*break*/, 7];
3671
- }
3672
- _h.label = 6;
3673
- case 6:
3674
- attempt++;
3675
- return [3 /*break*/, 4];
3676
- case 7:
3677
- //------------------------------------
3678
- /*
3679
-
3680
-
3681
-
3682
-
3683
-
3684
-
3685
-
3686
-
3687
-
3688
- */
3689
- //------------------------------------
3690
- if (resultString === null) {
3691
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Something went wrong and prompt result is null\n\n ".concat(block(pipelineIdentification), "\n "); }));
3692
- }
3693
- if (!(onProgress !== undefined) /* <- [3] */) return [3 /*break*/, 9]; /* <- [3] */
3694
- progress_2 = {
3695
- name: name,
3696
- title: title,
3697
- isStarted: true,
3698
- isDone: true,
3699
- templateType: currentTemplate.templateType,
3700
- parameterName: currentTemplate.resultingParameterName,
3701
- parameterValue: resultString,
3702
- // <- [3]
3703
- };
3704
- if (isReturned) {
3705
- 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)
3706
- .split('\n')
3707
- .map(function (line) { return "> ".concat(line); })
3708
- .join('\n')), "\n\n "); }));
3709
- }
3710
- return [4 /*yield*/, onProgress(progress_2)];
3711
- case 8:
3712
- _h.sent();
3713
- _h.label = 9;
3714
- case 9:
3715
- 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)));
3716
- return [2 /*return*/];
3717
- }
3718
- });
3719
- });
3720
- }
3721
- function filterJustOutputParameters() {
3722
- var e_8, _a;
3723
- var outputParameters = {};
3724
- var _loop_6 = function (parameter) {
3725
- if (parametersToPass[parameter.name] === undefined) {
3726
- // [4]
3727
- 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 "); })));
3728
- return "continue";
3729
- }
3730
- outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
3731
- };
3732
- try {
3733
- // Note: Filter ONLY output parameters
3734
- for (var _b = __values(preparedPipeline.parameters.filter(function (_a) {
3735
- var isOutput = _a.isOutput;
3736
- return isOutput;
3737
- })), _c = _b.next(); !_c.done; _c = _b.next()) {
3738
- var parameter = _c.value;
3739
- _loop_6(parameter);
3740
- }
3741
- }
3742
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
3743
- finally {
3744
- try {
3745
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3746
- }
3747
- finally { if (e_8) throw e_8.error; }
3748
- }
3749
- return outputParameters;
3750
- }
3751
- 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;
4252
+ function executePipeline(options) {
4253
+ return __awaiter(this, void 0, void 0, function () {
4254
+ 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;
3752
4255
  var e_1, _e, e_2, _f;
3753
4256
  return __generator(this, function (_g) {
3754
4257
  switch (_g.label) {
3755
4258
  case 0:
4259
+ inputParameters = options.inputParameters, tools = options.tools, onProgress = options.onProgress, pipeline = options.pipeline, setPreparedPipeline = options.setPreparedPipeline, pipelineIdentification = options.pipelineIdentification, settings = options.settings;
4260
+ maxParallelCount = settings.maxParallelCount, isVerbose = settings.isVerbose;
4261
+ preparedPipeline = options.preparedPipeline;
4262
+ llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
3756
4263
  if (!(preparedPipeline === undefined)) return [3 /*break*/, 2];
3757
4264
  return [4 /*yield*/, preparePipeline(pipeline, {
3758
4265
  llmTools: llmTools,
@@ -3761,6 +4268,7 @@
3761
4268
  })];
3762
4269
  case 1:
3763
4270
  preparedPipeline = _g.sent();
4271
+ setPreparedPipeline(preparedPipeline);
3764
4272
  _g.label = 2;
3765
4273
  case 2:
3766
4274
  errors = [];
@@ -3830,7 +4338,7 @@
3830
4338
  return name === parameterName;
3831
4339
  });
3832
4340
  if (!(parameter === undefined)) return [3 /*break*/, 1];
3833
- 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 "); })));
4341
+ 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 "); })));
3834
4342
  return [3 /*break*/, 4];
3835
4343
  case 1:
3836
4344
  if (!(parameter.isInput === false)) return [3 /*break*/, 4];
@@ -3842,10 +4350,10 @@
3842
4350
  // Note: Wait a short time to prevent race conditions
3843
4351
  _h.sent();
3844
4352
  _h.label = 3;
3845
- 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 "); }), {
4353
+ 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 "); }), {
3846
4354
  isSuccessful: false,
3847
4355
  errors: __spreadArray([
3848
- 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 "); }))
4356
+ 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 "); }))
3849
4357
  ], __read(errors), false).map(serializeError),
3850
4358
  warnings: warnings.map(serializeError),
3851
4359
  executionReport: executionReport,
@@ -3909,7 +4417,7 @@
3909
4417
  case 0:
3910
4418
  if (loopLimit-- < 0) {
3911
4419
  // Note: Really UnexpectedError not LimitReachedError - this should be catched during validatePipeline
3912
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
4420
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Loop limit reached during resolving parameters pipeline execution\n\n ".concat(block(pipelineIdentification), "\n "); }));
3913
4421
  }
3914
4422
  currentTemplate = unresovedTemplates_1.find(function (template) {
3915
4423
  return template.dependentParameterNames.every(function (name) {
@@ -3919,29 +4427,52 @@
3919
4427
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
3920
4428
  throw new UnexpectedError(
3921
4429
  // TODO: [🐎] DRY
3922
- 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
4430
+ 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
3923
4431
  .map(function (_a) {
3924
4432
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
3925
4433
  return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
3926
4434
  .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
3927
4435
  .join(' and '));
3928
4436
  })
3929
- .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 "); }));
4437
+ .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 "); }));
3930
4438
  case 1:
3931
4439
  if (!!currentTemplate) return [3 /*break*/, 3];
3932
- /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
4440
+ /* [🤹‍♂️] */ return [4 /*yield*/, Promise.race(resolving_1)];
3933
4441
  case 2:
3934
- /* [5] */ _j.sent();
4442
+ /* [🤹‍♂️] */ _j.sent();
3935
4443
  return [3 /*break*/, 4];
3936
4444
  case 3:
3937
4445
  unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
3938
- work_1 = executeSingleTemplate(currentTemplate)
3939
- .then(function () {
4446
+ work_1 = executeTemplate({
4447
+ currentTemplate: currentTemplate,
4448
+ preparedPipeline: preparedPipeline,
4449
+ parametersToPass: parametersToPass,
4450
+ tools: tools,
4451
+ llmTools: llmTools,
4452
+ onProgress: function (progress) {
4453
+ if (isReturned) {
4454
+ 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)
4455
+ .split('\n')
4456
+ .map(function (line) { return "> ".concat(line); })
4457
+ .join('\n')), "\n "); }));
4458
+ }
4459
+ if (onProgress) {
4460
+ onProgress(progress);
4461
+ }
4462
+ },
4463
+ settings: settings,
4464
+ $executionReport: executionReport,
4465
+ pipelineIdentification: spaceTrim.spaceTrim(function (block) { return "\n ".concat(block(pipelineIdentification), "\n Template name: ").concat(currentTemplate.name, "\n Template title: ").concat(currentTemplate.title, "\n "); }),
4466
+ })
4467
+ .then(function (newParametersToPass) {
4468
+ parametersToPass = __assign(__assign({}, newParametersToPass), parametersToPass);
3940
4469
  resovedParameterNames_1 = __spreadArray(__spreadArray([], __read(resovedParameterNames_1), false), [currentTemplate.resultingParameterName], false);
3941
4470
  })
3942
4471
  .then(function () {
3943
4472
  resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
3944
4473
  });
4474
+ // <- Note: Errors are catched here [3]
4475
+ // 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
3945
4476
  resolving_1.push(work_1);
3946
4477
  _j.label = 4;
3947
4478
  case 4: return [2 /*return*/];
@@ -3968,7 +4499,12 @@
3968
4499
  var result = _a.result;
3969
4500
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3970
4501
  })), false));
3971
- outputParameters_1 = filterJustOutputParameters();
4502
+ outputParameters_1 = filterJustOutputParameters({
4503
+ preparedPipeline: preparedPipeline,
4504
+ parametersToPass: parametersToPass,
4505
+ $warnings: warnings,
4506
+ pipelineIdentification: pipelineIdentification,
4507
+ });
3972
4508
  isReturned = true;
3973
4509
  if (!(onProgress !== undefined)) return [3 /*break*/, 27];
3974
4510
  // Note: Wait a short time to prevent race conditions
@@ -3991,7 +4527,12 @@
3991
4527
  var result = _a.result;
3992
4528
  return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
3993
4529
  })), false));
3994
- outputParameters = filterJustOutputParameters();
4530
+ outputParameters = filterJustOutputParameters({
4531
+ preparedPipeline: preparedPipeline,
4532
+ parametersToPass: parametersToPass,
4533
+ $warnings: warnings,
4534
+ pipelineIdentification: pipelineIdentification,
4535
+ });
3995
4536
  isReturned = true;
3996
4537
  if (!(onProgress !== undefined)) return [3 /*break*/, 30];
3997
4538
  // Note: Wait a short time to prevent race conditions
@@ -4011,22 +4552,65 @@
4011
4552
  })];
4012
4553
  }
4013
4554
  });
4555
+ });
4556
+ }
4557
+
4558
+ /**
4559
+ * Creates executor function from pipeline and execution tools.
4560
+ *
4561
+ * @returns The executor function
4562
+ * @throws {PipelineLogicError} on logical error in the pipeline
4563
+ * @public exported from `@promptbook/core`
4564
+ */
4565
+ function createPipelineExecutor(options) {
4566
+ var _this = this;
4567
+ var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
4568
+ 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;
4569
+ validatePipeline(pipeline);
4570
+ var pipelineIdentification = (function () {
4571
+ // Note: This is a 😐 implementation of [🚞]
4572
+ var _ = [];
4573
+ if (pipeline.sourceFile !== undefined) {
4574
+ _.push("File: ".concat(pipeline.sourceFile));
4575
+ }
4576
+ if (pipeline.pipelineUrl !== undefined) {
4577
+ _.push("Url: ".concat(pipeline.pipelineUrl));
4578
+ }
4579
+ return _.join('\n');
4580
+ })();
4581
+ var preparedPipeline;
4582
+ if (isPipelinePrepared(pipeline)) {
4583
+ preparedPipeline = pipeline;
4584
+ }
4585
+ else if (isNotPreparedWarningSupressed !== true) {
4586
+ 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 "); }));
4587
+ }
4588
+ var runCount = 0;
4589
+ var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4590
+ return __generator(this, function (_a) {
4591
+ runCount++;
4592
+ return [2 /*return*/, /* not await */ executePipeline({
4593
+ pipeline: pipeline,
4594
+ preparedPipeline: preparedPipeline,
4595
+ setPreparedPipeline: function (newPreparedPipeline) {
4596
+ preparedPipeline = newPreparedPipeline;
4597
+ },
4598
+ inputParameters: inputParameters,
4599
+ tools: tools,
4600
+ onProgress: onProgress,
4601
+ pipelineIdentification: spaceTrim.spaceTrim(function (block) { return "\n ".concat(block(pipelineIdentification), "\n ").concat(runCount === 1 ? '' : "Run #".concat(runCount), "\n "); }),
4602
+ settings: {
4603
+ maxExecutionAttempts: maxExecutionAttempts,
4604
+ maxParallelCount: maxParallelCount,
4605
+ csvSettings: csvSettings,
4606
+ isVerbose: isVerbose,
4607
+ isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4608
+ },
4609
+ })];
4610
+ });
4014
4611
  }); };
4015
4612
  return pipelineExecutor;
4016
4613
  }
4017
- /**
4018
- * TODO: !!! Identify not only pipeline BUT exact template ${block(pipelineIdentification)}
4019
- * TODO: Use isVerbose here (not only pass to `preparePipeline`)
4020
- * TODO: [🧠][🌳] Use here `countTotalUsage` and put preparation and prepared pipiline to report
4021
- * TODO: [🪂] Use maxParallelCount here (not only pass to `preparePipeline`)
4022
- * TODO: [♈] Probbably move expectations from templates to parameters
4023
- * TODO: [🧠] When not meet expectations in DIALOG_TEMPLATE, make some way to tell the user
4024
- * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
4025
- * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
4026
- * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
4027
- * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
4028
- * TODO: [🧠][💷] `assertsExecutionSuccessful` should be the method of `PipelineExecutor` result BUT maybe NOT to preserve pure JSON object
4029
- */
4030
4614
 
4031
4615
  /**
4032
4616
  * @@@
@@ -4078,7 +4662,7 @@
4078
4662
  outputParameters = result.outputParameters;
4079
4663
  knowledgePiecesRaw = outputParameters.knowledgePieces;
4080
4664
  knowledgeTextPieces = (knowledgePiecesRaw || '').split('\n---\n');
4081
- // <- TODO: !!!!! Smarter split and filter out empty pieces
4665
+ // <- TODO:[main] !!!!! Smarter split and filter out empty pieces
4082
4666
  if (isVerbose) {
4083
4667
  console.info('knowledgeTextPieces:', knowledgeTextPieces);
4084
4668
  }
@@ -4136,8 +4720,13 @@
4136
4720
  case 6: return [3 /*break*/, 8];
4137
4721
  case 7:
4138
4722
  error_1 = _c.sent();
4723
+ // Note: Here is expected error:
4724
+ // > PipelineExecutionError: You have not provided any `LlmExecutionTools` that support model variant "EMBEDDING
4725
+ if (!(error_1 instanceof PipelineExecutionError)) {
4726
+ throw error_1;
4727
+ }
4139
4728
  // TODO: [🟥] Detect browser / node and make it colorfull
4140
- console.error(error_1);
4729
+ console.error(error_1, "<- Note: This error is not critical to prepare the pipeline, just knowledge pieces won't have embeddings");
4141
4730
  return [3 /*break*/, 8];
4142
4731
  case 8: return [2 /*return*/, {
4143
4732
  name: name,
@@ -4158,7 +4747,7 @@
4158
4747
  });
4159
4748
  }
4160
4749
  /**
4161
- * TODO: [🐝][🔼] !!! Export via `@promptbook/markdown`
4750
+ * TODO: [🐝][🔼][main] !!! Export via `@promptbook/markdown`
4162
4751
  * TODO: [🪂] Do it in parallel 11:11
4163
4752
  * Note: No need to aggregate usage here, it is done by intercepting the llmTools
4164
4753
  */
@@ -4182,7 +4771,7 @@
4182
4771
  var partialPieces, pieces;
4183
4772
  return __generator(this, function (_a) {
4184
4773
  switch (_a.label) {
4185
- case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝] !!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
4774
+ case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.sourceContent, // <- TODO: [🐝][main] !!! Unhardcode markdown, detect which type it is - BE AWARE of big package size
4186
4775
  options)];
4187
4776
  case 1:
4188
4777
  partialPieces = _a.sent();
@@ -4374,7 +4963,7 @@
4374
4963
  });
4375
4964
  }
4376
4965
  /**
4377
- * TODO: [🔃] !!!!! If the persona was prepared with different version or different set of models, prepare it once again
4966
+ * TODO: [🔃][main] !!!!! If the persona was prepared with different version or different set of models, prepare it once again
4378
4967
  * TODO: [🏢] !! Check validity of `modelName` in pipeline
4379
4968
  * TODO: [🏢] !! Check validity of `systemMessage` in pipeline
4380
4969
  * TODO: [🏢] !! Check validity of `temperature` in pipeline
@@ -4423,7 +5012,7 @@
4423
5012
  case 0:
4424
5013
  _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a;
4425
5014
  templates = pipeline.templates, parameters = pipeline.parameters, knowledgePiecesCount = pipeline.knowledgePiecesCount;
4426
- // TODO: !!!!! Apply samples to each template (if missing and is for the template defined)
5015
+ // TODO:[main] !!!!! Apply samples to each template (if missing and is for the template defined)
4427
5016
  TODO_USE(parameters);
4428
5017
  templatesPrepared = new Array(
4429
5018
  // <- TODO: [🧱] Implement in a functional (not new Class) way
@@ -4455,7 +5044,7 @@
4455
5044
  /**
4456
5045
  * TODO: [🧠] Add context to each template (if missing)
4457
5046
  * TODO: [🧠] What is better name `prepareTemplate` or `prepareTemplateAndParameters`
4458
- * TODO: [♨] !!! Prepare index the samples and maybe templates
5047
+ * TODO: [♨][main] !!! Prepare index the samples and maybe templates
4459
5048
  * TODO: Write tests for `preparePipeline`
4460
5049
  * TODO: [🏏] Leverage the batch API and build queues @see https://platform.openai.com/docs/guides/batch
4461
5050
  * TODO: [🧊] In future one preparation can take data from previous preparation and save tokens and time
@@ -4627,7 +5216,7 @@
4627
5216
  if (sourceContent === '') {
4628
5217
  throw new ParseError("Source is not defined");
4629
5218
  }
4630
- // TODO: !!!! Following checks should be applied every link in the `sourceContent`
5219
+ // TODO:[main] !!!! Following checks should be applied every link in the `sourceContent`
4631
5220
  if (sourceContent.startsWith('http://')) {
4632
5221
  throw new ParseError("Source is not secure");
4633
5222
  }
@@ -4830,7 +5419,7 @@
4830
5419
  if (command.templateType === 'KNOWLEDGE') {
4831
5420
  knowledgeCommandParser.$applyToPipelineJson({
4832
5421
  type: 'KNOWLEDGE',
4833
- sourceContent: $templateJson.content, // <- TODO: [🐝] !!! Work with KNOWLEDGE which not referring to the source file or website, but its content itself
5422
+ sourceContent: $templateJson.content, // <- TODO: [🐝][main] !!! Work with KNOWLEDGE which not referring to the source file or website, but its content itself
4834
5423
  }, $pipelineJson);
4835
5424
  $templateJson.isTemplate = false;
4836
5425
  return;
@@ -5180,6 +5769,171 @@
5180
5769
  * TODO: [🌺] Use some intermediate util splitWords
5181
5770
  */
5182
5771
 
5772
+ /**
5773
+ * @@@
5774
+ *
5775
+ * @param text @@@
5776
+ * @param _isFirstLetterCapital @@@
5777
+ * @returns @@@
5778
+ * @example 'helloWorld'
5779
+ * @example 'iLovePromptbook'
5780
+ * @public exported from `@promptbook/utils`
5781
+ */
5782
+ function normalizeTo_camelCase(text, _isFirstLetterCapital) {
5783
+ var e_1, _a;
5784
+ if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
5785
+ var charType;
5786
+ var lastCharType = null;
5787
+ var normalizedName = '';
5788
+ try {
5789
+ for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
5790
+ var char = text_1_1.value;
5791
+ var normalizedChar = void 0;
5792
+ if (/^[a-z]$/.test(char)) {
5793
+ charType = 'LOWERCASE';
5794
+ normalizedChar = char;
5795
+ }
5796
+ else if (/^[A-Z]$/.test(char)) {
5797
+ charType = 'UPPERCASE';
5798
+ normalizedChar = char.toLowerCase();
5799
+ }
5800
+ else if (/^[0-9]$/.test(char)) {
5801
+ charType = 'NUMBER';
5802
+ normalizedChar = char;
5803
+ }
5804
+ else {
5805
+ charType = 'OTHER';
5806
+ normalizedChar = '';
5807
+ }
5808
+ if (!lastCharType) {
5809
+ if (_isFirstLetterCapital) {
5810
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
5811
+ }
5812
+ }
5813
+ else if (charType !== lastCharType &&
5814
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
5815
+ !(lastCharType === 'NUMBER') &&
5816
+ !(charType === 'NUMBER')) {
5817
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
5818
+ }
5819
+ normalizedName += normalizedChar;
5820
+ lastCharType = charType;
5821
+ }
5822
+ }
5823
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5824
+ finally {
5825
+ try {
5826
+ if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
5827
+ }
5828
+ finally { if (e_1) throw e_1.error; }
5829
+ }
5830
+ return normalizedName;
5831
+ }
5832
+ /**
5833
+ * TODO: [🌺] Use some intermediate util splitWords
5834
+ */
5835
+
5836
+ /**
5837
+ * Removes quotes from a string
5838
+ *
5839
+ * Tip: This is very usefull for post-processing of the result of the LLM model
5840
+ * Note: This function removes only the same quotes from the beginning and the end of the string
5841
+ * Note: There are two simmilar functions:
5842
+ * - `removeQuotes` which removes only bounding quotes
5843
+ * - `unwrapResult` which removes whole introduce sentence
5844
+ *
5845
+ * @param text optionally quoted text
5846
+ * @returns text without quotes
5847
+ * @public exported from `@promptbook/utils`
5848
+ */
5849
+ function removeQuotes(text) {
5850
+ if (text.startsWith('"') && text.endsWith('"')) {
5851
+ return text.slice(1, -1);
5852
+ }
5853
+ if (text.startsWith('\'') && text.endsWith('\'')) {
5854
+ return text.slice(1, -1);
5855
+ }
5856
+ return text;
5857
+ }
5858
+
5859
+ /**
5860
+ * Function `validateParameterName` will @@@
5861
+ *
5862
+ * @param parameterName @@@
5863
+ * @returns @@@
5864
+ * @throws {ParseError} @@@
5865
+ * @private within the repository
5866
+ */
5867
+ function validateParameterName(parameterName) {
5868
+ var e_1, _a;
5869
+ var rawParameterName = parameterName;
5870
+ try {
5871
+ for (var _b = __values([
5872
+ ['`', '`'],
5873
+ ['{', '}'],
5874
+ ['[', ']'],
5875
+ ['(', ')'],
5876
+ ['<', '>'],
5877
+ ]), _c = _b.next(); !_c.done; _c = _b.next()) {
5878
+ var _d = __read(_c.value, 2), start = _d[0], end = _d[1];
5879
+ if (parameterName.substring(0, 1) === start &&
5880
+ parameterName.substring(parameterName.length - 1, parameterName.length) === end
5881
+ // <- TODO: More universal that 1 character
5882
+ ) {
5883
+ parameterName = parameterName.substring(1, parameterName.length - 1);
5884
+ // <- TODO: More universal that 1 character
5885
+ }
5886
+ }
5887
+ }
5888
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5889
+ finally {
5890
+ try {
5891
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
5892
+ }
5893
+ finally { if (e_1) throw e_1.error; }
5894
+ }
5895
+ // TODO: [🐠] Following try-catch block should be part of common validators logic
5896
+ try {
5897
+ /*
5898
+ Note: We don't need to check for spaces because we are going to normalize the parameter name to camelCase
5899
+ if (parameterName.includes(' ')) {
5900
+ throw new ParseError(`Parameter name cannot contain spaces`);
5901
+ }
5902
+ */
5903
+ if (parameterName.includes('.')) {
5904
+ throw new ParseError("Parameter name cannot contain dots");
5905
+ }
5906
+ if (parameterName.includes('/') || parameterName.includes('\\')) {
5907
+ throw new ParseError("Parameter name cannot contain slashes");
5908
+ }
5909
+ if (parameterName.includes('(') ||
5910
+ parameterName.includes(')') ||
5911
+ parameterName.includes('{') ||
5912
+ parameterName.includes('}') ||
5913
+ parameterName.includes('[') ||
5914
+ parameterName.includes(']')) {
5915
+ throw new ParseError("Parameter name cannot contain braces");
5916
+ }
5917
+ parameterName = removeDiacritics(parameterName);
5918
+ parameterName = removeEmojis(parameterName);
5919
+ parameterName = removeQuotes(parameterName);
5920
+ parameterName = normalizeTo_camelCase(parameterName);
5921
+ if (parameterName === '') {
5922
+ throw new ParseError("Parameter name cannot be empty");
5923
+ }
5924
+ if (RESERVED_PARAMETER_NAMES.includes(parameterName)) {
5925
+ throw new ParseError("{".concat(parameterName, "} is a reserved parameter name"));
5926
+ }
5927
+ }
5928
+ catch (error) {
5929
+ if (!(error instanceof ParseError)) {
5930
+ throw error;
5931
+ }
5932
+ 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 "); }));
5933
+ }
5934
+ return parameterName;
5935
+ }
5936
+
5183
5937
  /**
5184
5938
  * Parses the foreach command
5185
5939
  *
@@ -5209,15 +5963,16 @@
5209
5963
  /**
5210
5964
  * Link to discussion
5211
5965
  */
5212
- documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/@@',
5966
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/148',
5213
5967
  /**
5214
5968
  * Example usages of the FOREACH command
5215
5969
  */
5216
5970
  examples: [
5217
- 'FOREACH List Line `{customers}` -> `{customer}`',
5218
- 'FOR List Line `{customers}` -> `{customer}`',
5219
- 'EACH List Line `{customers}` -> `{customer}`',
5220
- // <- TODO: [🍭] !!!!!! More
5971
+ 'FOREACH Text Line `{customers}` -> `{customer}`',
5972
+ 'FOREACH Csv Cell `{customers}` -> `{cell}`',
5973
+ 'FOREACH Csv Row `{customers}` -> `{firstName}`, `{lastName}`, `+{email}`',
5974
+ 'FOR Text Line `{customers}` -> `{customer}`',
5975
+ 'EACH Text Line `{customers}` -> `{customer}`',
5221
5976
  ],
5222
5977
  /**
5223
5978
  * Parses the FOREACH command
@@ -5225,55 +5980,75 @@
5225
5980
  parse: function (input) {
5226
5981
  var args = input.args;
5227
5982
  var formatName = normalizeTo_SCREAMING_CASE(args[0] || '');
5228
- var cellName = normalizeTo_SCREAMING_CASE(args[1] || '');
5229
- var parameterNameWrapped = args[2];
5983
+ var subformatName = normalizeTo_SCREAMING_CASE(args[1] || '');
5984
+ var parameterNameArg = args[2] || '';
5230
5985
  var assignSign = args[3];
5231
- var subparameterNameWrapped = args[4];
5232
- if (![
5233
- 'LIST',
5234
- 'CSV',
5235
- // <- TODO: [🏢] Unhardcode formats
5236
- ].includes(formatName)) {
5237
- console.info({ args: args, formatName: formatName });
5238
- throw new Error("Unsupported format \"".concat(formatName, "\""));
5986
+ var formatDefinition = FORMAT_DEFINITIONS.find(function (formatDefinition) {
5987
+ return __spreadArray([formatDefinition.formatName], __read((formatDefinition.aliases || [])), false).includes(formatName);
5988
+ });
5989
+ if (formatDefinition === undefined) {
5990
+ 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; })
5991
+ .map(function (formatName) { return "- ".concat(formatName); })
5992
+ .join('\n')), "\n "); }));
5239
5993
  // <- TODO: [🏢] List all supported format names
5240
5994
  }
5241
- if (![
5242
- 'LINE',
5243
- 'ROW',
5244
- 'COLUMN',
5245
- 'CELL',
5246
- // <- TODO: [🏢] Unhardcode format cells
5247
- ].includes(cellName)) {
5248
- console.info({ args: args, cellName: cellName });
5249
- throw new Error("Format ".concat(formatName, " does not support cell \"").concat(cellName, "\""));
5250
- // <- TODO: [🏢] List all supported cell names for the format
5995
+ var subvalueDefinition = formatDefinition.subvalueDefinitions.find(function (subvalueDefinition) {
5996
+ return __spreadArray([subvalueDefinition.subvalueName], __read((subvalueDefinition.aliases || [])), false).includes(subformatName);
5997
+ });
5998
+ if (subvalueDefinition === undefined) {
5999
+ 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
6000
+ .map(function (subvalueDefinition) { return subvalueDefinition.subvalueName; })
6001
+ .map(function (subvalueName) { return "- ".concat(subvalueName); })
6002
+ .join('\n')), "\n "); }));
6003
+ // <- TODO: [🏢] List all supported subformat names for the format
5251
6004
  }
5252
6005
  if (assignSign !== '->') {
5253
- console.info({ args: args, assignSign: assignSign });
5254
- throw new Error("FOREACH command must have '->' to assign the value to the parameter");
5255
- }
5256
- // TODO: !!!!!! Replace with propper parameter name validation
5257
- if ((parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(0, 1)) !== '{' ||
5258
- (parameterNameWrapped === null || parameterNameWrapped === void 0 ? void 0 : parameterNameWrapped.substring(parameterNameWrapped.length - 1, parameterNameWrapped.length)) !== '}') {
5259
- 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));
5260
- throw new Error("!!!!!! 1 Here will be error (with rules and precise error) from validateParameterName");
5261
- }
5262
- var parameterName = parameterNameWrapped.substring(1, parameterNameWrapped.length - 1);
5263
- // TODO: !!!!!! Replace with propper parameter name validation
5264
- if ((subparameterNameWrapped === null || subparameterNameWrapped === void 0 ? void 0 : subparameterNameWrapped.substring(0, 1)) !== '{' ||
5265
- (subparameterNameWrapped === null || subparameterNameWrapped === void 0 ? void 0 : subparameterNameWrapped.substring(subparameterNameWrapped.length - 1, subparameterNameWrapped.length)) !==
5266
- '}') {
5267
- console.info({ args: args, subparameterNameWrapped: subparameterNameWrapped });
5268
- throw new Error("!!!!!! 2 Here will be error (with rules and precise error) from validateParameterName");
5269
- }
5270
- var subparameterName = subparameterNameWrapped.substring(1, subparameterNameWrapped.length - 1);
6006
+ throw new ParseError("FOREACH command must have '->' to assign the value to the parameter");
6007
+ }
6008
+ var parameterName = validateParameterName(parameterNameArg);
6009
+ var outputSubparameterName = null;
6010
+ // TODO: [4] DRY
6011
+ var inputSubparameterNames = args
6012
+ .slice(4)
6013
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
6014
+ .filter(function (parameterName) { return !parameterName.includes('+'); })
6015
+ .filter(function (parameterName) { return parameterName !== ''; })
6016
+ .map(validateParameterName);
6017
+ // TODO: [4] DRY
6018
+ var outputSubparameterNames = args
6019
+ .slice(4)
6020
+ .map(function (parameterName) { return parameterName.split(',').join(' ').trim(); })
6021
+ .filter(function (parameterName) { return parameterName.includes('+'); })
6022
+ .map(function (parameterName) { return parameterName.split('+').join(''); })
6023
+ .map(validateParameterName);
6024
+ if (outputSubparameterNames.length === 1) {
6025
+ outputSubparameterName = outputSubparameterNames[0];
6026
+ }
6027
+ else if (outputSubparameterNames.length > 1) {
6028
+ throw new ParseError("FOREACH command can not have more than one output subparameter");
6029
+ }
6030
+ if (inputSubparameterNames.length === 0) {
6031
+ throw new ParseError("FOREACH command must have at least one input subparameter");
6032
+ }
6033
+ if (outputSubparameterName === null) {
6034
+ // TODO: Following code should be unhardcoded from here and moved to the format definition
6035
+ if (formatName === 'CSV' && subformatName === 'CELL') {
6036
+ outputSubparameterName = 'newCell';
6037
+ }
6038
+ else if (formatName === 'TEXT' && subformatName === 'LINE') {
6039
+ outputSubparameterName = 'newLine';
6040
+ }
6041
+ else {
6042
+ 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 ")));
6043
+ }
6044
+ }
5271
6045
  return {
5272
6046
  type: 'FOREACH',
5273
6047
  formatName: formatName,
5274
- cellName: cellName,
6048
+ subformatName: subformatName,
5275
6049
  parameterName: parameterName,
5276
- subparameterName: subparameterName,
6050
+ inputSubparameterNames: inputSubparameterNames,
6051
+ outputSubparameterName: outputSubparameterName,
5277
6052
  };
5278
6053
  },
5279
6054
  /**
@@ -5282,9 +6057,17 @@
5282
6057
  * Note: `$` is used to indicate that this function mutates given `templateJson`
5283
6058
  */
5284
6059
  $applyToTemplateJson: function (command, $templateJson, $pipelineJson) {
5285
- var formatName = command.formatName, cellName = command.cellName, parameterName = command.parameterName, subparameterName = command.subparameterName;
5286
- $templateJson.foreach = { formatName: formatName, cellName: cellName, parameterName: parameterName, subparameterName: subparameterName };
5287
- keepUnused($pipelineJson); // <- TODO: !!!!!! BUT Maybe register subparameter from foreach into parameters of the pipeline
6060
+ var formatName = command.formatName, subformatName = command.subformatName, parameterName = command.parameterName, inputSubparameterNames = command.inputSubparameterNames, outputSubparameterName = command.outputSubparameterName;
6061
+ // TODO: [🍭] Detect double use
6062
+ // TODO: [🍭] Detect usage with JOKER and don't allow it
6063
+ $templateJson.foreach = {
6064
+ formatName: formatName,
6065
+ subformatName: subformatName,
6066
+ parameterName: parameterName,
6067
+ inputSubparameterNames: inputSubparameterNames,
6068
+ outputSubparameterName: outputSubparameterName,
6069
+ };
6070
+ keepUnused($pipelineJson); // <- TODO: [🧠] Maybe register subparameter from foreach into parameters of the pipeline
5288
6071
  // Note: [🍭] FOREACH apply has some sideeffects on different places in codebase
5289
6072
  },
5290
6073
  /**
@@ -5307,8 +6090,7 @@
5307
6090
  },
5308
6091
  };
5309
6092
  /**
5310
- * TODO: !!!!!! Comment console logs
5311
- * TODO: [🍭] !!!!!! Make .ptbk.md file with examples of the FOREACH command and also with wrong parsing and logic
6093
+ * TODO: [🍭] Make .ptbk.md file with examples of the FOREACH with wrong parsing and logic
5312
6094
  */
5313
6095
 
5314
6096
  /**
@@ -5418,12 +6200,11 @@
5418
6200
  */
5419
6201
  parse: function (input) {
5420
6202
  var args = input.args;
5421
- // TODO: !!!!!! Replace with propper parameter name validation
5422
- var parametersMatch = (args.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
5423
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5424
- throw new ParseError("Invalid joker");
6203
+ if (args.length !== 1) {
6204
+ throw new ParseError("JOKE command expects exactly one parameter name");
5425
6205
  }
5426
- var parameterName = parametersMatch.groups.parameterName;
6206
+ var parameterNameArg = args[0] || '';
6207
+ var parameterName = validateParameterName(parameterNameArg);
5427
6208
  return {
5428
6209
  type: 'JOKER',
5429
6210
  parameterName: parameterName,
@@ -5498,6 +6279,9 @@
5498
6279
  */
5499
6280
  parse: function (input) {
5500
6281
  var args = input.args, normalized = input.normalized;
6282
+ var availableVariantsMessage = spaceTrim__default["default"](function (block) { return "\n Available variants are:\n ".concat(block(MODEL_VARIANTS.map(function (variantName) {
6283
+ return "- ".concat(variantName).concat(variantName !== 'EMBEDDING' ? '' : ' (Not available in pipeline)');
6284
+ }).join('\n')), "\n "); });
5501
6285
  // TODO: Make this more elegant and dynamically
5502
6286
  if (normalized.startsWith('MODEL_VARIANT')) {
5503
6287
  if (normalized === 'MODEL_VARIANT_CHAT') {
@@ -5513,17 +6297,13 @@
5513
6297
  key: 'modelVariant',
5514
6298
  value: 'COMPLETION',
5515
6299
  };
6300
+ // <- Note: [🤖]
5516
6301
  }
5517
6302
  else if (normalized.startsWith('MODEL_VARIANT_EMBED')) {
5518
- return {
5519
- type: 'MODEL',
5520
- key: 'modelVariant',
5521
- value: 'EMBEDDING',
5522
- };
5523
- // <- Note: [🤖]
6303
+ spaceTrim__default["default"](function (block) { return "\n Embedding model can not be used in pipeline\n\n ".concat(block(availableVariantsMessage), "\n "); });
5524
6304
  }
5525
6305
  else {
5526
- 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 "); }));
6306
+ throw new ParseError(spaceTrim__default["default"](function (block) { return "\n Unknown model variant in command:\n\n ".concat(block(availableVariantsMessage), "\n "); }));
5527
6307
  }
5528
6308
  }
5529
6309
  if (normalized.startsWith('MODEL_NAME')) {
@@ -5648,14 +6428,13 @@
5648
6428
  * Parses the PARAMETER command
5649
6429
  */
5650
6430
  parse: function (input) {
5651
- var normalized = input.normalized, raw = input.raw;
5652
- var parametersMatch = raw.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
5653
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
5654
- throw new ParseError("Invalid parameter");
5655
- }
5656
- var _a = parametersMatch.groups, parameterName = _a.parameterName, parameterDescription = _a.parameterDescription;
5657
- if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
5658
- throw new ParseError("Parameter {".concat(parameterName, "} can not contain another parameter in description"));
6431
+ var normalized = input.normalized, args = input.args, raw = input.raw;
6432
+ var parameterNameRaw = args.shift() || '';
6433
+ var parameterDescriptionRaw = args.join(' ');
6434
+ // <- TODO: When [🥶] fixed, change to:
6435
+ // > const parameterDescriptionRaw = rawArgs.split(parameterNameRaw).join('').trim();
6436
+ if (parameterDescriptionRaw && parameterDescriptionRaw.match(/\{(?<embeddedParameterName>[a-z0-9_]+)\}/im)) {
6437
+ 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 "); }));
5659
6438
  }
5660
6439
  var isInput = normalized.startsWith('INPUT');
5661
6440
  var isOutput = normalized.startsWith('OUTPUT');
@@ -5663,11 +6442,12 @@
5663
6442
  isInput = false;
5664
6443
  isOutput = false;
5665
6444
  }
5666
- // TODO: !!!!!! Add parameter name validation
6445
+ var parameterName = validateParameterName(parameterNameRaw);
6446
+ var parameterDescription = parameterDescriptionRaw.trim() || null;
5667
6447
  return {
5668
6448
  type: 'PARAMETER',
5669
6449
  parameterName: parameterName,
5670
- parameterDescription: parameterDescription.trim() || null,
6450
+ parameterDescription: parameterDescription,
5671
6451
  isInput: isInput,
5672
6452
  isOutput: isOutput,
5673
6453
  };
@@ -5992,6 +6772,7 @@
5992
6772
  * Note: `$` is used to indicate that this function mutates given `pipelineJson`
5993
6773
  */
5994
6774
  $applyToPipelineJson: function (command, $pipelineJson) {
6775
+ // TODO: Warn if the version is overridden
5995
6776
  $pipelineJson.promptbookVersion = command.promptbookVersion;
5996
6777
  },
5997
6778
  /**
@@ -6474,7 +7255,9 @@
6474
7255
  for (var commandNameSegmentsCount = 0; commandNameSegmentsCount < Math.min(items.length, 3); commandNameSegmentsCount++) {
6475
7256
  var commandNameRaw = items.slice(0, commandNameSegmentsCount + 1).join('_');
6476
7257
  var args = items.slice(commandNameSegmentsCount + 1);
6477
- var rawArgs = raw.substring(commandNameRaw.length).trim();
7258
+ var rawArgs = raw
7259
+ .substring(commandNameRaw.length)
7260
+ .trim();
6478
7261
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6479
7262
  if (command !== null) {
6480
7263
  return command;
@@ -6485,7 +7268,9 @@
6485
7268
  {
6486
7269
  var commandNameRaw = items.slice(-1).join('_');
6487
7270
  var args = items.slice(0, -1); // <- Note: This is probbably not correct
6488
- var rawArgs = raw.substring(0, raw.length - commandNameRaw.length).trim();
7271
+ var rawArgs = raw
7272
+ .substring(0, raw.length - commandNameRaw.length)
7273
+ .trim();
6489
7274
  var command = parseCommandVariant({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args, commandNameRaw: commandNameRaw });
6490
7275
  if (command !== null) {
6491
7276
  return command;
@@ -6625,7 +7410,7 @@
6625
7410
  function extractOneBlockFromMarkdown(markdown) {
6626
7411
  var codeBlocks = extractAllBlocksFromMarkdown(markdown);
6627
7412
  if (codeBlocks.length !== 1) {
6628
- 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 "); }));
7413
+ 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 "); }));
6629
7414
  }
6630
7415
  return codeBlocks[0];
6631
7416
  }
@@ -6812,7 +7597,7 @@
6812
7597
  var $pipelineJson = {
6813
7598
  title: undefined /* <- Note: [🍙] Putting here placeholder to keep `title` on top at final JSON */,
6814
7599
  pipelineUrl: undefined /* <- Note: Putting here placeholder to keep `pipelineUrl` on top at final JSON */,
6815
- promptbookVersion: PROMPTBOOK_VERSION,
7600
+ promptbookVersion: undefined /* <- Note: By default no explicit version */,
6816
7601
  description: undefined /* <- Note: [🍙] Putting here placeholder to keep `description` on top at final JSON */,
6817
7602
  parameters: [],
6818
7603
  templates: [],
@@ -7103,7 +7888,7 @@
7103
7888
  return $asDeeplyFrozenSerializableJson('pipelineJson', $pipelineJson);
7104
7889
  }
7105
7890
  /**
7106
- * TODO: !!!! Warn if used only sync version
7891
+ * TODO:[main] !!!! Warn if used only sync version
7107
7892
  * TODO: [🚞] Report here line/column of error
7108
7893
  * TODO: Use spaceTrim more effectively
7109
7894
  * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
@@ -7608,7 +8393,7 @@
7608
8393
  }
7609
8394
  }
7610
8395
  /**
7611
- * TODO: [🧠] !!! In-memory cache of same values to prevent multiple checks
8396
+ * TODO: [🧠][main] !!! In-memory cache of same values to prevent multiple checks
7612
8397
  * TODO: [🧠][💺] Can be done this on type-level?
7613
8398
  */
7614
8399
 
@@ -7665,21 +8450,41 @@
7665
8450
  * @public exported from `@promptbook/core`
7666
8451
  */
7667
8452
  function usageToHuman(usage) {
7668
- var report = 'Usage:';
8453
+ var reportItems = [];
7669
8454
  var uncertainNumberToHuman = function (_a) {
7670
8455
  var value = _a.value, isUncertain = _a.isUncertain;
7671
8456
  return "".concat(isUncertain ? 'approximately ' : '').concat(Math.round(value * 100) / 100);
7672
8457
  };
7673
- report += '\n' + "- Cost ".concat(uncertainNumberToHuman(usage.price), " USD");
7674
- report += '\n' + "- Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time");
7675
- return spaceTrim__default["default"](report);
8458
+ if (usage.price.value > 0.01
8459
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻] Configure negligible value - default value to config + value to `UsageToHumanSettings`
8460
+ ) {
8461
+ reportItems.push("Cost ".concat(uncertainNumberToHuman(usage.price), " USD"));
8462
+ }
8463
+ else {
8464
+ reportItems.push("Negligible cost");
8465
+ }
8466
+ var worktime = usageToWorktime(usage);
8467
+ if (worktime.value >
8468
+ 1 / 60
8469
+ // <- TODO: [🍓][🧞‍♂️][👩🏽‍🤝‍🧑🏻]
8470
+ ) {
8471
+ reportItems.push("Saved ".concat(uncertainNumberToHuman(usageToWorktime(usage)), " hours of human time"));
8472
+ // TODO: [🍓][🧞‍♂️] Show minutes, seconds, days NOT 0.1 hours
8473
+ }
8474
+ if (usage.output.charactersCount.value > 0) {
8475
+ reportItems.push("Written ".concat(uncertainNumberToHuman(usage.output.charactersCount), " characters"));
8476
+ }
8477
+ if (reportItems.length === 0) {
8478
+ // Note: For negligible usage, we report at least something
8479
+ reportItems.push('Negligible');
8480
+ }
8481
+ return spaceTrim__default["default"](function (block) { return "\n Usage:\n ".concat(block(reportItems.map(function (item) { return "- ".concat(item); }).join('\n')), "\n "); });
7676
8482
  }
7677
8483
  /**
7678
- * TODO: Use "$1" not "1 USD"
7679
- * TODO: Use markdown formatting like "Cost approximately **$1**"
7680
- * TODO: Report in minutes, seconds, days NOT 0.1 hours
8484
+ * TODO: [🍓][🧞‍♂️] Use "$1" not "1 USD"
8485
+ * TODO: [🍓][🧞‍♂️] Use markdown formatting like "Cost approximately **$1**"
8486
+ * TODO: [🍓][🧞‍♂️] Report in minutes, seconds, days NOT 0.1 hours
7681
8487
  * TODO: [🧠] Maybe make from `uncertainNumberToHuman` separate exported utility
7682
- * TODO: When negligible usage, report "Negligible" or just don't report it
7683
8488
  * TODO: [🧠] Maybe use "~" instead of "approximately"
7684
8489
  * TODO: [🏛] Maybe make some markdown builder
7685
8490
  */
@@ -8449,7 +9254,7 @@
8449
9254
  });
8450
9255
  }
8451
9256
  /**
8452
- * TODO: [🥃] !!! Allow `ptbk make` without configuring any llm tools
9257
+ * TODO: [🥃][main] !!! Allow `ptbk make` without configuring any llm tools
8453
9258
  * TODO: Maybe remove this command - "about" command should be enough?
8454
9259
  * TODO: [0] DRY Javascript and typescript - Maybe make ONLY typescript and for javascript just remove types
8455
9260
  * Note: [🟡] This code should never be published outside of `@promptbook/cli`
@@ -8483,70 +9288,6 @@
8483
9288
  * TODO: [🏛] This can be part of markdown builder
8484
9289
  */
8485
9290
 
8486
- /**
8487
- * @@@
8488
- *
8489
- * @param text @@@
8490
- * @param _isFirstLetterCapital @@@
8491
- * @returns @@@
8492
- * @example 'helloWorld'
8493
- * @example 'iLovePromptbook'
8494
- * @public exported from `@promptbook/utils`
8495
- */
8496
- function normalizeTo_camelCase(text, _isFirstLetterCapital) {
8497
- var e_1, _a;
8498
- if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
8499
- var charType;
8500
- var lastCharType = null;
8501
- var normalizedName = '';
8502
- try {
8503
- for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
8504
- var char = text_1_1.value;
8505
- var normalizedChar = void 0;
8506
- if (/^[a-z]$/.test(char)) {
8507
- charType = 'LOWERCASE';
8508
- normalizedChar = char;
8509
- }
8510
- else if (/^[A-Z]$/.test(char)) {
8511
- charType = 'UPPERCASE';
8512
- normalizedChar = char.toLowerCase();
8513
- }
8514
- else if (/^[0-9]$/.test(char)) {
8515
- charType = 'NUMBER';
8516
- normalizedChar = char;
8517
- }
8518
- else {
8519
- charType = 'OTHER';
8520
- normalizedChar = '';
8521
- }
8522
- if (!lastCharType) {
8523
- if (_isFirstLetterCapital) {
8524
- normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
8525
- }
8526
- }
8527
- else if (charType !== lastCharType &&
8528
- !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
8529
- !(lastCharType === 'NUMBER') &&
8530
- !(charType === 'NUMBER')) {
8531
- normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
8532
- }
8533
- normalizedName += normalizedChar;
8534
- lastCharType = charType;
8535
- }
8536
- }
8537
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
8538
- finally {
8539
- try {
8540
- if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
8541
- }
8542
- finally { if (e_1) throw e_1.error; }
8543
- }
8544
- return normalizedName;
8545
- }
8546
- /**
8547
- * TODO: [🌺] Use some intermediate util splitWords
8548
- */
8549
-
8550
9291
  /**
8551
9292
  * Creates a Mermaid graph based on the promptbook
8552
9293
  *
@@ -8603,9 +9344,9 @@
8603
9344
  return promptbookMermaid;
8604
9345
  }
8605
9346
  /**
8606
- * TODO: !!!!!! FOREACH in mermaid graph
8607
- * TODO: !!!!!! Knowledge in mermaid graph
8608
- * TODO: !!!!!! Personas in mermaid graph
9347
+ * TODO: !!!!! FOREACH in mermaid graph
9348
+ * TODO: !!!!! Knowledge in mermaid graph
9349
+ * TODO: !!!!! Personas in mermaid graph
8609
9350
  * TODO: Maybe use some Mermaid package instead of string templating
8610
9351
  * TODO: [🕌] When more than 2 functionalities, split into separate functions
8611
9352
  */
@@ -8931,7 +9672,7 @@
8931
9672
  socket.on('connect', function () {
8932
9673
  resolve(socket);
8933
9674
  });
8934
- // TODO: !!!! Better timeout handling
9675
+ // TODO:[main] !!!! Better timeout handling
8935
9676
  setTimeout(function () {
8936
9677
  reject(new Error("Timeout while connecting to ".concat(_this.options.remoteUrl)));
8937
9678
  }, CONNECTION_TIMEOUT_MS);
@@ -9111,11 +9852,11 @@
9111
9852
  output: computeUsage("$2.40 / 1M tokens"),
9112
9853
  },
9113
9854
  },
9114
- // TODO: !!! Claude 1 and 2 has also completion versions - ask Hoagy
9855
+ // TODO:[main] !!! Claude 1 and 2 has also completion versions - ask Hoagy
9115
9856
  ]);
9116
9857
  /**
9117
9858
  * Note: [🤖] Add models of new variant
9118
- * TODO: [🧠] !!! Add embedding models OR Anthropic has only chat+completion models?
9859
+ * TODO: [🧠][main] !!! Add embedding models OR Anthropic has only chat+completion models?
9119
9860
  * TODO: [🧠] Some mechanism to propagate unsureness
9120
9861
  * TODO: [🧠][👮‍♀️] Put here more info like description, isVision, trainingDateCutoff, languages, strengths ( Top-level performance, intelligence, fluency, and understanding), contextWindow,...
9121
9862
  * TODO: [🎰] Some mechanism to auto-update available models
@@ -9324,7 +10065,7 @@
9324
10065
  resultContent = contentBlock.text;
9325
10066
  // eslint-disable-next-line prefer-const
9326
10067
  complete = getCurrentIsoDate();
9327
- usage = computeAnthropicClaudeUsage(content, '', rawResponse);
10068
+ usage = computeAnthropicClaudeUsage(rawPromptContent || '', resultContent || '', rawResponse);
9328
10069
  return [2 /*return*/, $asDeeplyFrozenSerializableJson('AnthropicClaudeExecutionTools ChatPromptResult', {
9329
10070
  content: resultContent,
9330
10071
  modelName: rawResponse.model,
@@ -9471,8 +10212,8 @@
9471
10212
  className: 'AnthropicClaudeExecutionTools',
9472
10213
  });
9473
10214
  /**
9474
- * TODO: [🧠] !!!! Make anonymous this with all LLM providers
9475
- * TODO: [🧠][🧱] !!!! Maybe change all `new AnthropicClaudeExecutionTools` -> `createAnthropicClaudeExecutionTools` in manual
10215
+ * TODO: [🧠][main] !!!! Make anonymous this with all LLM providers
10216
+ * TODO: [🧠][🧱][main] !!!! Maybe change all `new AnthropicClaudeExecutionTools` -> `createAnthropicClaudeExecutionTools` in manual
9476
10217
  * TODO: [🧠] Maybe auto-detect usage in browser and determine default value of `isProxied`
9477
10218
  * TODO: [🦺] Is there some way how to put `packageName` and `className` on top and function definition on bottom?
9478
10219
  * TODO: [🎶] Naming "constructor" vs "creator" vs "factory"
@@ -9850,6 +10591,7 @@
9850
10591
  prompt: computeUsage("$5.00 / 1M tokens"),
9851
10592
  output: computeUsage("$15.00 / 1M tokens"),
9852
10593
  },
10594
+ //TODO:[main] !!!!!! Add gpt-4o-mini-2024-07-18 and all others to be up to date
9853
10595
  },
9854
10596
  /**/
9855
10597
  /**/
@@ -9864,6 +10606,51 @@
9864
10606
  },
9865
10607
  /**/
9866
10608
  /**/
10609
+ {
10610
+ modelVariant: 'CHAT',
10611
+ modelTitle: 'o1-preview',
10612
+ modelName: 'o1-preview',
10613
+ pricing: {
10614
+ prompt: computeUsage("$15.00 / 1M tokens"),
10615
+ output: computeUsage("$60.00 / 1M tokens"),
10616
+ },
10617
+ },
10618
+ /**/
10619
+ /**/
10620
+ {
10621
+ modelVariant: 'CHAT',
10622
+ modelTitle: 'o1-preview-2024-09-12',
10623
+ modelName: 'o1-preview-2024-09-12',
10624
+ // <- TODO:[main] !!!!!! Some better system to organize theese date suffixes and versions
10625
+ pricing: {
10626
+ prompt: computeUsage("$15.00 / 1M tokens"),
10627
+ output: computeUsage("$60.00 / 1M tokens"),
10628
+ },
10629
+ },
10630
+ /**/
10631
+ /**/
10632
+ {
10633
+ modelVariant: 'CHAT',
10634
+ modelTitle: 'o1-mini',
10635
+ modelName: 'o1-mini',
10636
+ pricing: {
10637
+ prompt: computeUsage("$3.00 / 1M tokens"),
10638
+ output: computeUsage("$12.00 / 1M tokens"),
10639
+ },
10640
+ },
10641
+ /**/
10642
+ /**/
10643
+ {
10644
+ modelVariant: 'CHAT',
10645
+ modelTitle: 'o1-mini-2024-09-12',
10646
+ modelName: 'o1-mini-2024-09-12',
10647
+ pricing: {
10648
+ prompt: computeUsage("$3.00 / 1M tokens"),
10649
+ output: computeUsage("$12.00 / 1M tokens"),
10650
+ },
10651
+ },
10652
+ /**/
10653
+ /**/
9867
10654
  {
9868
10655
  modelVariant: 'CHAT',
9869
10656
  modelTitle: 'gpt-3.5-turbo-16k-0613',
@@ -9952,7 +10739,7 @@
9952
10739
  AzureOpenAiExecutionTools.prototype.listModels = function () {
9953
10740
  return __awaiter(this, void 0, void 0, function () {
9954
10741
  return __generator(this, function (_a) {
9955
- // TODO: !!! Do here some filtering which models are really available as deployment
10742
+ // TODO:[main] !!! Do here some filtering which models are really available as deployment
9956
10743
  // @see https://management.azure.com/subscriptions/subscriptionId/resourceGroups/resourceGroupName/providers/Microsoft.CognitiveServices/accounts/accountName/deployments?api-version=2023-05-01
9957
10744
  return [2 /*return*/, OPENAI_MODELS.map(function (_a) {
9958
10745
  var modelTitle = _a.modelTitle, modelName = _a.modelName, modelVariant = _a.modelVariant;
@@ -10438,7 +11225,7 @@
10438
11225
  resultContent = rawResponse.choices[0].message.content;
10439
11226
  // eslint-disable-next-line prefer-const
10440
11227
  complete = getCurrentIsoDate();
10441
- usage = computeOpenAiUsage(content, resultContent || '', rawResponse);
11228
+ usage = computeOpenAiUsage(content || '', resultContent || '', rawResponse);
10442
11229
  if (resultContent === null) {
10443
11230
  throw new PipelineExecutionError('No response message from OpenAI');
10444
11231
  }
@@ -10510,7 +11297,7 @@
10510
11297
  resultContent = rawResponse.choices[0].text;
10511
11298
  // eslint-disable-next-line prefer-const
10512
11299
  complete = getCurrentIsoDate();
10513
- usage = computeOpenAiUsage(content, resultContent || '', rawResponse);
11300
+ usage = computeOpenAiUsage(content || '', resultContent || '', rawResponse);
10514
11301
  return [2 /*return*/, $asDeeplyFrozenSerializableJson('OpenAiExecutionTools CompletionPromptResult', {
10515
11302
  content: resultContent,
10516
11303
  modelName: rawResponse.model || modelName,
@@ -10570,7 +11357,9 @@
10570
11357
  resultContent = rawResponse.data[0].embedding;
10571
11358
  // eslint-disable-next-line prefer-const
10572
11359
  complete = getCurrentIsoDate();
10573
- usage = computeOpenAiUsage(content, '', rawResponse);
11360
+ usage = computeOpenAiUsage(content || '', '',
11361
+ // <- Note: Embedding does not have result content
11362
+ rawResponse);
10574
11363
  return [2 /*return*/, $asDeeplyFrozenSerializableJson('OpenAiExecutionTools EmbeddingPromptResult', {
10575
11364
  content: resultContent,
10576
11365
  modelName: rawResponse.model || modelName,
@@ -10641,7 +11430,7 @@
10641
11430
  * @public exported from `@promptbook/openai`
10642
11431
  */
10643
11432
  var createOpenAiExecutionTools = Object.assign(function (options) {
10644
- // TODO: [🧠] !!!! If browser, auto add `dangerouslyAllowBrowser`
11433
+ // TODO: [🧠][main] !!!! If browser, auto add `dangerouslyAllowBrowser`
10645
11434
  if (($isRunningInBrowser() || $isRunningInWebWorker()) && !options.dangerouslyAllowBrowser) {
10646
11435
  options = __assign(__assign({}, options), { dangerouslyAllowBrowser: true });
10647
11436
  }