@promptbook/core 0.61.0-2 → 0.61.0-20

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 (359) hide show
  1. package/esm/index.es.js +1737 -942
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/typings/promptbook-collection/index.d.ts +200 -30
  4. package/esm/typings/src/_packages/core.index.d.ts +7 -2
  5. package/esm/typings/src/_packages/execute-javascript.index.d.ts +1 -1
  6. package/esm/typings/src/_packages/node.index.d.ts +2 -1
  7. package/esm/typings/src/_packages/types.index.d.ts +11 -7
  8. package/esm/typings/src/_packages/utils.index.d.ts +8 -6
  9. package/esm/typings/src/cli/cli-commands/hello.d.ts +3 -0
  10. package/esm/typings/src/cli/cli-commands/make.d.ts +3 -0
  11. package/esm/typings/src/cli/cli-commands/prettify.d.ts +3 -0
  12. package/esm/typings/src/cli/promptbookCli.d.ts +1 -0
  13. package/esm/typings/src/collection/PipelineCollection.d.ts +1 -1
  14. package/esm/typings/src/collection/SimplePipelineCollection.d.ts +10 -10
  15. package/esm/typings/src/collection/constructors/createCollectionFromDirectory.d.ts +8 -7
  16. package/esm/typings/src/collection/constructors/createCollectionFromUrl.d.ts +2 -2
  17. package/esm/typings/src/commands/KNOWLEDGE/KnowledgeCommand.d.ts +2 -3
  18. package/esm/typings/src/commands/MODEL/ModelCommand.d.ts +2 -2
  19. package/esm/typings/src/commands/PERSONA/PersonaCommand.d.ts +4 -2
  20. package/esm/typings/src/commands/_BOILERPLATE/boilerplateCommandParser.d.ts +1 -0
  21. package/esm/typings/src/commands/_common/types/CommandParser.d.ts +42 -14
  22. package/esm/typings/src/config.d.ts +38 -1
  23. package/esm/typings/src/config.test.d.ts +4 -0
  24. package/esm/typings/src/conversion/pipelineJsonToString.d.ts +1 -1
  25. package/esm/typings/src/conversion/pipelineStringToJson.d.ts +9 -5
  26. package/esm/typings/src/conversion/pipelineStringToJsonSync.d.ts +5 -3
  27. package/esm/typings/src/conversion/prettify/PrettifyOptions.d.ts +2 -2
  28. package/esm/typings/src/conversion/utils/extractParametersFromPromptTemplate.d.ts +2 -2
  29. package/esm/typings/src/conversion/utils/renameParameter.d.ts +3 -3
  30. package/esm/typings/src/conversion/utils/stringifyPipelineJson.d.ts +13 -0
  31. package/esm/typings/src/conversion/validation/_importPipeline.d.ts +12 -3
  32. package/esm/typings/src/conversion/validation/validatePipeline.d.ts +10 -1
  33. package/esm/typings/src/errors/EnvironmentMismatchError.d.ts +7 -0
  34. package/esm/typings/src/errors/LimitReachedError.d.ts +7 -0
  35. package/esm/typings/src/errors/VersionMismatchError.d.ts +8 -0
  36. package/esm/typings/src/execution/CommonExecutionToolsOptions.d.ts +1 -0
  37. package/esm/typings/src/execution/LlmExecutionTools.d.ts +10 -8
  38. package/esm/typings/src/execution/PipelineExecutor.d.ts +9 -8
  39. package/esm/typings/src/execution/PromptResult.d.ts +28 -58
  40. package/esm/typings/src/execution/PromptResultUsage.d.ts +26 -0
  41. package/esm/typings/src/execution/ScriptExecutionTools.d.ts +5 -4
  42. package/esm/typings/src/execution/UncertainNumber.d.ts +18 -0
  43. package/esm/typings/src/execution/UserInterfaceTools.d.ts +5 -5
  44. package/esm/typings/src/execution/createPipelineExecutor.d.ts +19 -3
  45. package/esm/typings/src/execution/translation/automatic-translate/automatic-translators/TranslatorOptions.d.ts +2 -2
  46. package/esm/typings/src/execution/utils/addUsage.d.ts +58 -2
  47. package/esm/typings/src/execution/utils/computeUsageCounts.d.ts +1 -1
  48. package/esm/typings/src/execution/utils/forEachAsync.d.ts +1 -1
  49. package/esm/typings/src/execution/utils/uncertainNumber.d.ts +1 -1
  50. package/esm/typings/src/execution/utils/usageToWorktime.d.ts +2 -2
  51. package/esm/typings/src/formats/_common/FormatDefinition.d.ts +1 -1
  52. package/esm/typings/src/formats/csv/ListFormatDefinition.d.ts +2 -1
  53. package/esm/typings/src/formats/json/JsonFormatDefinition.d.ts +2 -1
  54. package/esm/typings/src/formats/list/ListFormatDefinition.d.ts +2 -1
  55. package/esm/typings/src/formats/xml/XmlFormatDefinition.d.ts +1 -0
  56. package/esm/typings/src/knowledge/dialogs/callback/CallbackInterfaceToolsOptions.d.ts +1 -1
  57. package/esm/typings/src/knowledge/dialogs/simple-prompt/SimplePromptInterfaceTools.d.ts +3 -0
  58. package/esm/typings/src/knowledge/prepare-knowledge/_common/Scraper.d.ts +27 -0
  59. package/esm/typings/src/knowledge/prepare-knowledge/_common/prepareKnowledgePieces.d.ts +18 -0
  60. package/esm/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +9 -23
  61. package/esm/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.test.d.ts +3 -0
  62. package/esm/typings/src/knowledge/prepare-knowledge/pdf/prepareKnowledgeFromPdf.d.ts +8 -14
  63. package/esm/typings/src/llm-providers/_common/createLlmToolsFromEnv.d.ts +30 -0
  64. package/esm/typings/src/llm-providers/_common/getLlmToolsForCli.d.ts +10 -0
  65. package/esm/typings/src/llm-providers/_common/getLlmToolsForTestingAndScriptsAndPlayground.d.ts +11 -0
  66. package/esm/typings/src/llm-providers/_common/utils/cache/CacheItem.d.ts +29 -0
  67. package/esm/typings/src/llm-providers/_common/utils/cache/CacheLlmToolsOptions.d.ts +10 -0
  68. package/esm/typings/src/llm-providers/_common/utils/cache/cacheLlmTools.d.ts +16 -0
  69. package/esm/typings/src/llm-providers/_common/utils/count-total-cost/LlmExecutionToolsWithTotalCost.d.ts +11 -0
  70. package/esm/typings/src/llm-providers/_common/utils/count-total-cost/countTotalCost.d.ts +14 -0
  71. package/esm/typings/src/llm-providers/_common/utils/count-total-cost/limitTotalCost.d.ts +32 -0
  72. package/esm/typings/src/llm-providers/anthropic-claude/AnthropicClaudeExecutionTools.d.ts +3 -2
  73. package/esm/typings/src/llm-providers/anthropic-claude/AnthropicClaudeExecutionToolsOptions.d.ts +1 -1
  74. package/esm/typings/src/llm-providers/anthropic-claude/anthropic-claude-models.d.ts +3 -3
  75. package/esm/typings/src/llm-providers/anthropic-claude/playground/playground.d.ts +3 -0
  76. package/esm/typings/src/llm-providers/azure-openai/AzureOpenAiExecutionTools.d.ts +5 -4
  77. package/esm/typings/src/llm-providers/azure-openai/AzureOpenAiExecutionToolsOptions.d.ts +5 -5
  78. package/esm/typings/src/llm-providers/azure-openai/playground/playground.d.ts +3 -0
  79. package/esm/typings/src/llm-providers/langtail/LangtailExecutionTools.d.ts +3 -0
  80. package/esm/typings/src/llm-providers/langtail/LangtailExecutionToolsOptions.d.ts +1 -1
  81. package/esm/typings/src/llm-providers/mocked/MockedEchoLlmExecutionTools.d.ts +5 -5
  82. package/esm/typings/src/llm-providers/mocked/MockedFackedLlmExecutionTools.d.ts +7 -7
  83. package/esm/typings/src/llm-providers/multiple/MultipleLlmExecutionTools.d.ts +12 -8
  84. package/esm/typings/src/llm-providers/openai/OpenAiExecutionTools.d.ts +7 -6
  85. package/esm/typings/src/llm-providers/openai/OpenAiExecutionToolsOptions.d.ts +1 -1
  86. package/esm/typings/src/llm-providers/openai/computeOpenaiUsage.d.ts +1 -1
  87. package/esm/typings/src/llm-providers/openai/computeUsage.d.ts +2 -2
  88. package/esm/typings/src/llm-providers/openai/openai-models.d.ts +3 -2
  89. package/esm/typings/src/llm-providers/openai/playground/playground.d.ts +3 -0
  90. package/esm/typings/src/llm-providers/remote/RemoteLlmExecutionTools.d.ts +9 -7
  91. package/esm/typings/src/llm-providers/remote/RemoteLlmExecutionToolsOptions.d.ts +1 -1
  92. package/esm/typings/src/personas/preparePersona.d.ts +15 -0
  93. package/esm/typings/src/prepare/PrepareOptions.d.ts +22 -0
  94. package/esm/typings/src/prepare/isPipelinePrepared.d.ts +10 -0
  95. package/esm/typings/src/prepare/preparePipeline.d.ts +18 -0
  96. package/esm/typings/src/prepare/unpreparePipeline.d.ts +9 -0
  97. package/esm/typings/src/scripting/javascript/JavascriptExecutionToolsOptions.d.ts +1 -1
  98. package/esm/typings/src/scripting/javascript/utils/preserve.d.ts +1 -1
  99. package/esm/typings/src/scripting/javascript/utils/unknownToString.d.ts +2 -1
  100. package/esm/typings/src/storage/_common/PromptbookStorage.d.ts +25 -0
  101. package/esm/typings/src/storage/_common/PromptbookStorage.test-type.d.ts +5 -0
  102. package/esm/typings/src/storage/files-storage/FilesStorage.d.ts +30 -0
  103. package/esm/typings/src/storage/files-storage/FilesStorageOptions.d.ts +13 -0
  104. package/esm/typings/src/storage/files-storage/utils/nameToSubfolderPath.d.ts +7 -0
  105. package/esm/typings/src/storage/files-storage/utils/nameToSubfolderPath.test.d.ts +1 -0
  106. package/esm/typings/src/storage/local-storage/getLocalStorage.d.ts +9 -0
  107. package/esm/typings/src/storage/local-storage/getSessionStorage.d.ts +9 -0
  108. package/esm/typings/src/storage/memory/MemoryStorage.d.ts +34 -0
  109. package/esm/typings/src/storage/utils/PrefixStorage.d.ts +26 -0
  110. package/esm/typings/src/storage/utils/makePromptbookStorageFromWebStorage.d.ts +11 -0
  111. package/esm/typings/src/types/ModelRequirements.d.ts +71 -11
  112. package/esm/typings/src/types/ModelVariant.d.ts +14 -0
  113. package/esm/typings/src/types/PipelineJson/Expectations.d.ts +6 -2
  114. package/esm/typings/src/types/PipelineJson/KnowledgePieceJson.d.ts +67 -0
  115. package/esm/typings/src/types/PipelineJson/KnowledgeSourceJson.d.ts +24 -0
  116. package/esm/typings/src/types/PipelineJson/LlmTemplateJson.d.ts +9 -1
  117. package/esm/typings/src/types/PipelineJson/PersonaJson.d.ts +38 -0
  118. package/esm/typings/src/types/PipelineJson/PipelineJson.d.ts +29 -4
  119. package/esm/typings/src/types/PipelineJson/PreparationJson.d.ts +21 -0
  120. package/esm/typings/src/types/PipelineJson/PromptDialogJson.d.ts +5 -0
  121. package/esm/typings/src/types/PipelineJson/PromptTemplateJson.d.ts +5 -1
  122. package/esm/typings/src/types/PipelineJson/PromptTemplateJsonCommon.d.ts +13 -4
  123. package/esm/typings/src/types/PipelineJson/PromptTemplateParameterJson.d.ts +11 -2
  124. package/esm/typings/src/types/PipelineJson/ScriptJson.d.ts +2 -0
  125. package/esm/typings/src/types/PipelineJson/SimpleTemplateJson.d.ts +2 -0
  126. package/esm/typings/src/types/PipelineString.d.ts +1 -1
  127. package/esm/typings/src/types/Prompt.d.ts +54 -10
  128. package/esm/typings/src/types/execution-report/ExecutionReportJson.d.ts +4 -4
  129. package/esm/typings/src/types/execution-report/ExecutionReportStringOptions.d.ts +3 -3
  130. package/esm/typings/src/types/execution-report/countWorkingDuration.d.ts +1 -1
  131. package/esm/typings/src/types/typeAliases.d.ts +114 -15
  132. package/esm/typings/src/utils/FromtoItems.d.ts +3 -3
  133. package/esm/typings/src/utils/currentDate.d.ts +7 -0
  134. package/esm/typings/src/utils/deepClone.d.ts +9 -0
  135. package/esm/typings/src/utils/deepFreeze.d.ts +22 -0
  136. package/esm/typings/src/utils/emojis.d.ts +2 -2
  137. package/esm/typings/src/utils/extractParameters.d.ts +2 -2
  138. package/esm/typings/src/utils/formatNumber.d.ts +1 -1
  139. package/esm/typings/src/utils/isRunningInWhatever.d.ts +3 -0
  140. package/esm/typings/src/utils/markdown/addAutoGeneratedSection.d.ts +3 -3
  141. package/esm/typings/src/utils/markdown/createMarkdownChart.d.ts +7 -10
  142. package/esm/typings/src/utils/markdown/createMarkdownTable.d.ts +1 -1
  143. package/esm/typings/src/utils/markdown/extractAllBlocksFromMarkdown-real.test.d.ts +1 -0
  144. package/esm/typings/src/utils/markdown/extractAllBlocksFromMarkdown.d.ts +9 -2
  145. package/esm/typings/src/utils/markdown/extractOneBlockFromMarkdown.d.ts +1 -1
  146. package/esm/typings/src/utils/markdown/parseMarkdownSection.d.ts +3 -3
  147. package/esm/typings/src/utils/normalization/parseKeywords.d.ts +2 -1
  148. package/esm/typings/src/utils/organization/TODO_USE.d.ts +12 -0
  149. package/esm/typings/src/utils/organization/TODO_any.d.ts +6 -0
  150. package/esm/typings/src/utils/organization/TODO_object.d.ts +6 -0
  151. package/esm/typings/src/utils/organization/TODO_unknown.d.ts +6 -0
  152. package/esm/typings/src/utils/organization/___.d.ts +6 -0
  153. package/esm/typings/src/utils/{just.d.ts → organization/just.d.ts} +5 -1
  154. package/esm/typings/src/utils/organization/keepUnused.d.ts +16 -0
  155. package/esm/typings/src/utils/organization/really_any.d.ts +6 -0
  156. package/esm/typings/src/utils/organization/really_unknown.d.ts +6 -0
  157. package/esm/typings/src/utils/random/randomSeed.d.ts +7 -0
  158. package/{umd/typings/src/execution → esm/typings/src}/utils/replaceParameters.d.ts +2 -4
  159. package/esm/typings/src/utils/replaceParameters.test.d.ts +1 -0
  160. package/esm/typings/src/utils/sets/difference.d.ts +3 -0
  161. package/esm/typings/src/utils/validators/email/isValidEmail.d.ts +2 -1
  162. package/esm/typings/src/utils/validators/filePath/isValidFilePath.d.ts +2 -1
  163. package/esm/typings/src/utils/validators/javascriptName/isValidJavascriptName.d.ts +2 -1
  164. package/esm/typings/src/utils/validators/semanticVersion/isValidPromptbookVersion.d.ts +2 -1
  165. package/esm/typings/src/utils/validators/semanticVersion/isValidSemanticVersion.d.ts +2 -1
  166. package/esm/typings/src/utils/validators/url/isValidPipelineUrl.d.ts +2 -1
  167. package/esm/typings/src/utils/validators/url/isValidUrl.d.ts +2 -1
  168. package/esm/typings/src/utils/validators/uuid/isValidUuid.d.ts +2 -1
  169. package/package.json +1 -1
  170. package/umd/index.umd.js +1740 -941
  171. package/umd/index.umd.js.map +1 -1
  172. package/umd/typings/promptbook-collection/index.d.ts +200 -30
  173. package/umd/typings/src/_packages/core.index.d.ts +7 -2
  174. package/umd/typings/src/_packages/execute-javascript.index.d.ts +1 -1
  175. package/umd/typings/src/_packages/node.index.d.ts +2 -1
  176. package/umd/typings/src/_packages/types.index.d.ts +11 -7
  177. package/umd/typings/src/_packages/utils.index.d.ts +8 -6
  178. package/umd/typings/src/cli/cli-commands/hello.d.ts +3 -0
  179. package/umd/typings/src/cli/cli-commands/make.d.ts +3 -0
  180. package/umd/typings/src/cli/cli-commands/prettify.d.ts +3 -0
  181. package/umd/typings/src/cli/promptbookCli.d.ts +1 -0
  182. package/umd/typings/src/collection/PipelineCollection.d.ts +1 -1
  183. package/umd/typings/src/collection/SimplePipelineCollection.d.ts +10 -10
  184. package/umd/typings/src/collection/constructors/createCollectionFromDirectory.d.ts +8 -7
  185. package/umd/typings/src/collection/constructors/createCollectionFromUrl.d.ts +2 -2
  186. package/umd/typings/src/commands/KNOWLEDGE/KnowledgeCommand.d.ts +2 -3
  187. package/umd/typings/src/commands/MODEL/ModelCommand.d.ts +2 -2
  188. package/umd/typings/src/commands/PERSONA/PersonaCommand.d.ts +4 -2
  189. package/umd/typings/src/commands/_BOILERPLATE/boilerplateCommandParser.d.ts +1 -0
  190. package/umd/typings/src/commands/_common/types/CommandParser.d.ts +42 -14
  191. package/umd/typings/src/config.d.ts +38 -1
  192. package/umd/typings/src/config.test.d.ts +4 -0
  193. package/umd/typings/src/conversion/pipelineJsonToString.d.ts +1 -1
  194. package/umd/typings/src/conversion/pipelineStringToJson.d.ts +9 -5
  195. package/umd/typings/src/conversion/pipelineStringToJsonSync.d.ts +5 -3
  196. package/umd/typings/src/conversion/prettify/PrettifyOptions.d.ts +2 -2
  197. package/umd/typings/src/conversion/utils/extractParametersFromPromptTemplate.d.ts +2 -2
  198. package/umd/typings/src/conversion/utils/renameParameter.d.ts +3 -3
  199. package/umd/typings/src/conversion/utils/stringifyPipelineJson.d.ts +13 -0
  200. package/umd/typings/src/conversion/utils/stringifyPipelineJson.test.d.ts +1 -0
  201. package/umd/typings/src/conversion/validation/_importPipeline.d.ts +12 -3
  202. package/umd/typings/src/conversion/validation/validatePipeline.d.ts +10 -1
  203. package/umd/typings/src/errors/EnvironmentMismatchError.d.ts +7 -0
  204. package/umd/typings/src/errors/LimitReachedError.d.ts +7 -0
  205. package/umd/typings/src/errors/VersionMismatchError.d.ts +8 -0
  206. package/umd/typings/src/execution/CommonExecutionToolsOptions.d.ts +1 -0
  207. package/umd/typings/src/execution/LlmExecutionTools.d.ts +10 -8
  208. package/umd/typings/src/execution/PipelineExecutor.d.ts +9 -8
  209. package/umd/typings/src/execution/PromptResult.d.ts +28 -58
  210. package/umd/typings/src/execution/PromptResultUsage.d.ts +26 -0
  211. package/umd/typings/src/execution/ScriptExecutionTools.d.ts +5 -4
  212. package/umd/typings/src/execution/UncertainNumber.d.ts +18 -0
  213. package/umd/typings/src/execution/UserInterfaceTools.d.ts +5 -5
  214. package/umd/typings/src/execution/createPipelineExecutor.d.ts +19 -3
  215. package/umd/typings/src/execution/translation/automatic-translate/automatic-translators/TranslatorOptions.d.ts +2 -2
  216. package/umd/typings/src/execution/utils/addUsage.d.ts +58 -2
  217. package/umd/typings/src/execution/utils/computeUsageCounts.d.ts +1 -1
  218. package/umd/typings/src/execution/utils/forEachAsync.d.ts +1 -1
  219. package/umd/typings/src/execution/utils/uncertainNumber.d.ts +1 -1
  220. package/umd/typings/src/execution/utils/usageToWorktime.d.ts +2 -2
  221. package/umd/typings/src/formats/_common/FormatDefinition.d.ts +1 -1
  222. package/umd/typings/src/formats/csv/ListFormatDefinition.d.ts +2 -1
  223. package/umd/typings/src/formats/json/JsonFormatDefinition.d.ts +2 -1
  224. package/umd/typings/src/formats/list/ListFormatDefinition.d.ts +2 -1
  225. package/umd/typings/src/formats/xml/XmlFormatDefinition.d.ts +1 -0
  226. package/umd/typings/src/knowledge/dialogs/callback/CallbackInterfaceToolsOptions.d.ts +1 -1
  227. package/umd/typings/src/knowledge/dialogs/simple-prompt/SimplePromptInterfaceTools.d.ts +3 -0
  228. package/umd/typings/src/knowledge/prepare-knowledge/_common/Scraper.d.ts +27 -0
  229. package/umd/typings/src/knowledge/prepare-knowledge/_common/prepareKnowledgePieces.d.ts +18 -0
  230. package/umd/typings/src/knowledge/prepare-knowledge/_common/prepareKnowledgePieces.test.d.ts +1 -0
  231. package/umd/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +9 -23
  232. package/umd/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.test.d.ts +3 -0
  233. package/umd/typings/src/knowledge/prepare-knowledge/pdf/prepareKnowledgeFromPdf.d.ts +8 -14
  234. package/umd/typings/src/llm-providers/_common/createLlmToolsFromEnv.d.ts +30 -0
  235. package/umd/typings/src/llm-providers/_common/getLlmToolsForCli.d.ts +10 -0
  236. package/umd/typings/src/llm-providers/_common/getLlmToolsForTestingAndScriptsAndPlayground.d.ts +11 -0
  237. package/umd/typings/src/llm-providers/_common/utils/cache/CacheItem.d.ts +29 -0
  238. package/umd/typings/src/llm-providers/_common/utils/cache/CacheLlmToolsOptions.d.ts +10 -0
  239. package/umd/typings/src/llm-providers/_common/utils/cache/cacheLlmTools.d.ts +16 -0
  240. package/umd/typings/src/llm-providers/_common/utils/count-total-cost/LlmExecutionToolsWithTotalCost.d.ts +11 -0
  241. package/umd/typings/src/llm-providers/_common/utils/count-total-cost/countTotalCost.d.ts +14 -0
  242. package/umd/typings/src/llm-providers/_common/utils/count-total-cost/limitTotalCost.d.ts +32 -0
  243. package/umd/typings/src/llm-providers/anthropic-claude/AnthropicClaudeExecutionTools.d.ts +3 -2
  244. package/umd/typings/src/llm-providers/anthropic-claude/AnthropicClaudeExecutionToolsOptions.d.ts +1 -1
  245. package/umd/typings/src/llm-providers/anthropic-claude/anthropic-claude-models.d.ts +3 -3
  246. package/umd/typings/src/llm-providers/anthropic-claude/playground/playground.d.ts +3 -0
  247. package/umd/typings/src/llm-providers/azure-openai/AzureOpenAiExecutionTools.d.ts +5 -4
  248. package/umd/typings/src/llm-providers/azure-openai/AzureOpenAiExecutionToolsOptions.d.ts +5 -5
  249. package/umd/typings/src/llm-providers/azure-openai/playground/playground.d.ts +3 -0
  250. package/umd/typings/src/llm-providers/langtail/LangtailExecutionTools.d.ts +3 -0
  251. package/umd/typings/src/llm-providers/langtail/LangtailExecutionToolsOptions.d.ts +1 -1
  252. package/umd/typings/src/llm-providers/mocked/MockedEchoLlmExecutionTools.d.ts +5 -5
  253. package/umd/typings/src/llm-providers/mocked/MockedFackedLlmExecutionTools.d.ts +7 -7
  254. package/umd/typings/src/llm-providers/multiple/MultipleLlmExecutionTools.d.ts +12 -8
  255. package/umd/typings/src/llm-providers/openai/OpenAiExecutionTools.d.ts +7 -6
  256. package/umd/typings/src/llm-providers/openai/OpenAiExecutionToolsOptions.d.ts +1 -1
  257. package/umd/typings/src/llm-providers/openai/computeOpenaiUsage.d.ts +1 -1
  258. package/umd/typings/src/llm-providers/openai/computeUsage.d.ts +2 -2
  259. package/umd/typings/src/llm-providers/openai/openai-models.d.ts +3 -2
  260. package/umd/typings/src/llm-providers/openai/playground/playground.d.ts +3 -0
  261. package/umd/typings/src/llm-providers/remote/RemoteLlmExecutionTools.d.ts +9 -7
  262. package/umd/typings/src/llm-providers/remote/RemoteLlmExecutionToolsOptions.d.ts +1 -1
  263. package/umd/typings/src/personas/preparePersona.d.ts +15 -0
  264. package/umd/typings/src/personas/preparePersona.test.d.ts +1 -0
  265. package/umd/typings/src/prepare/PrepareOptions.d.ts +22 -0
  266. package/umd/typings/src/prepare/isPipelinePrepared.d.ts +10 -0
  267. package/umd/typings/src/prepare/isPipelinePrepared.test.d.ts +1 -0
  268. package/umd/typings/src/prepare/preparePipeline.d.ts +18 -0
  269. package/umd/typings/src/prepare/unpreparePipeline.d.ts +9 -0
  270. package/umd/typings/src/scripting/javascript/JavascriptExecutionToolsOptions.d.ts +1 -1
  271. package/umd/typings/src/scripting/javascript/utils/preserve.d.ts +1 -1
  272. package/umd/typings/src/scripting/javascript/utils/unknownToString.d.ts +2 -1
  273. package/umd/typings/src/storage/_common/PromptbookStorage.d.ts +25 -0
  274. package/umd/typings/src/storage/_common/PromptbookStorage.test-type.d.ts +5 -0
  275. package/umd/typings/src/storage/files-storage/FilesStorage.d.ts +30 -0
  276. package/umd/typings/src/storage/files-storage/FilesStorageOptions.d.ts +13 -0
  277. package/umd/typings/src/storage/files-storage/utils/nameToSubfolderPath.d.ts +7 -0
  278. package/umd/typings/src/storage/files-storage/utils/nameToSubfolderPath.test.d.ts +1 -0
  279. package/umd/typings/src/storage/local-storage/getLocalStorage.d.ts +9 -0
  280. package/umd/typings/src/storage/local-storage/getSessionStorage.d.ts +9 -0
  281. package/umd/typings/src/storage/memory/MemoryStorage.d.ts +34 -0
  282. package/umd/typings/src/storage/utils/PrefixStorage.d.ts +26 -0
  283. package/umd/typings/src/storage/utils/makePromptbookStorageFromWebStorage.d.ts +11 -0
  284. package/umd/typings/src/types/ModelRequirements.d.ts +71 -11
  285. package/umd/typings/src/types/ModelVariant.d.ts +14 -0
  286. package/umd/typings/src/types/PipelineJson/Expectations.d.ts +6 -2
  287. package/umd/typings/src/types/PipelineJson/KnowledgePieceJson.d.ts +67 -0
  288. package/umd/typings/src/types/PipelineJson/KnowledgeSourceJson.d.ts +24 -0
  289. package/umd/typings/src/types/PipelineJson/LlmTemplateJson.d.ts +9 -1
  290. package/umd/typings/src/types/PipelineJson/PersonaJson.d.ts +38 -0
  291. package/umd/typings/src/types/PipelineJson/PipelineJson.d.ts +29 -4
  292. package/umd/typings/src/types/PipelineJson/PreparationJson.d.ts +21 -0
  293. package/umd/typings/src/types/PipelineJson/PromptDialogJson.d.ts +5 -0
  294. package/umd/typings/src/types/PipelineJson/PromptTemplateJson.d.ts +5 -1
  295. package/umd/typings/src/types/PipelineJson/PromptTemplateJsonCommon.d.ts +13 -4
  296. package/umd/typings/src/types/PipelineJson/PromptTemplateParameterJson.d.ts +11 -2
  297. package/umd/typings/src/types/PipelineJson/ScriptJson.d.ts +2 -0
  298. package/umd/typings/src/types/PipelineJson/SimpleTemplateJson.d.ts +2 -0
  299. package/umd/typings/src/types/PipelineString.d.ts +1 -1
  300. package/umd/typings/src/types/Prompt.d.ts +54 -10
  301. package/umd/typings/src/types/execution-report/ExecutionReportJson.d.ts +4 -4
  302. package/umd/typings/src/types/execution-report/ExecutionReportStringOptions.d.ts +3 -3
  303. package/umd/typings/src/types/execution-report/countWorkingDuration.d.ts +1 -1
  304. package/umd/typings/src/types/typeAliases.d.ts +114 -15
  305. package/umd/typings/src/utils/FromtoItems.d.ts +3 -3
  306. package/umd/typings/src/utils/currentDate.d.ts +7 -0
  307. package/umd/typings/src/utils/deepClone.d.ts +9 -0
  308. package/umd/typings/src/utils/deepFreeze.d.ts +22 -0
  309. package/umd/typings/src/utils/emojis.d.ts +2 -2
  310. package/umd/typings/src/utils/extractParameters.d.ts +2 -2
  311. package/umd/typings/src/utils/formatNumber.d.ts +1 -1
  312. package/umd/typings/src/utils/isRunningInWhatever.d.ts +3 -0
  313. package/umd/typings/src/utils/markdown/addAutoGeneratedSection.d.ts +3 -3
  314. package/umd/typings/src/utils/markdown/createMarkdownChart.d.ts +7 -10
  315. package/umd/typings/src/utils/markdown/createMarkdownTable.d.ts +1 -1
  316. package/umd/typings/src/utils/markdown/extractAllBlocksFromMarkdown-real.test.d.ts +1 -0
  317. package/umd/typings/src/utils/markdown/extractAllBlocksFromMarkdown.d.ts +9 -2
  318. package/umd/typings/src/utils/markdown/extractOneBlockFromMarkdown.d.ts +1 -1
  319. package/umd/typings/src/utils/markdown/parseMarkdownSection.d.ts +3 -3
  320. package/umd/typings/src/utils/normalization/parseKeywords.d.ts +2 -1
  321. package/umd/typings/src/utils/organization/TODO_USE.d.ts +12 -0
  322. package/umd/typings/src/utils/organization/TODO_any.d.ts +6 -0
  323. package/umd/typings/src/utils/organization/TODO_object.d.ts +6 -0
  324. package/umd/typings/src/utils/organization/TODO_unknown.d.ts +6 -0
  325. package/umd/typings/src/utils/organization/___.d.ts +6 -0
  326. package/umd/typings/src/utils/{just.d.ts → organization/just.d.ts} +5 -1
  327. package/umd/typings/src/utils/organization/keepUnused.d.ts +16 -0
  328. package/umd/typings/src/utils/organization/really_any.d.ts +6 -0
  329. package/umd/typings/src/utils/organization/really_unknown.d.ts +6 -0
  330. package/umd/typings/src/utils/random/randomSeed.d.ts +7 -0
  331. package/{esm/typings/src/execution → umd/typings/src}/utils/replaceParameters.d.ts +2 -4
  332. package/umd/typings/src/utils/replaceParameters.test.d.ts +1 -0
  333. package/umd/typings/src/utils/sets/difference.d.ts +3 -0
  334. package/umd/typings/src/utils/validators/email/isValidEmail.d.ts +2 -1
  335. package/umd/typings/src/utils/validators/filePath/isValidFilePath.d.ts +2 -1
  336. package/umd/typings/src/utils/validators/javascriptName/isValidJavascriptName.d.ts +2 -1
  337. package/umd/typings/src/utils/validators/semanticVersion/isValidPromptbookVersion.d.ts +2 -1
  338. package/umd/typings/src/utils/validators/semanticVersion/isValidSemanticVersion.d.ts +2 -1
  339. package/umd/typings/src/utils/validators/url/isValidPipelineUrl.d.ts +2 -1
  340. package/umd/typings/src/utils/validators/url/isValidUrl.d.ts +2 -1
  341. package/umd/typings/src/utils/validators/uuid/isValidUuid.d.ts +2 -1
  342. package/esm/typings/src/collection/constructors/justTestFsImport.d.ts +0 -7
  343. package/esm/typings/src/personas/personaToModelRequirements.d.ts +0 -6
  344. package/esm/typings/src/types/Parameters.d.ts +0 -14
  345. package/esm/typings/src/types/PipelineJson/KnowledgeJson.d.ts +0 -6
  346. package/esm/typings/src/types/PipelineJson/MaterialKnowledgePieceJson.d.ts +0 -28
  347. package/umd/typings/src/collection/constructors/justTestFsImport.d.ts +0 -7
  348. package/umd/typings/src/personas/personaToModelRequirements.d.ts +0 -6
  349. package/umd/typings/src/types/Parameters.d.ts +0 -14
  350. package/umd/typings/src/types/PipelineJson/KnowledgeJson.d.ts +0 -6
  351. package/umd/typings/src/types/PipelineJson/MaterialKnowledgePieceJson.d.ts +0 -28
  352. /package/esm/typings/src/_packages/{markdown-utils.d.ts → markdown-utils.index.d.ts} +0 -0
  353. /package/esm/typings/src/{execution/addPromptResultUsage.test.d.ts → conversion/utils/stringifyPipelineJson.test.d.ts} +0 -0
  354. /package/esm/typings/src/{execution/utils/replaceParameters.test.d.ts → knowledge/prepare-knowledge/_common/prepareKnowledgePieces.test.d.ts} +0 -0
  355. /package/{umd/typings/src/execution/addPromptResultUsage.test.d.ts → esm/typings/src/personas/preparePersona.test.d.ts} +0 -0
  356. /package/esm/typings/src/{utils/postprocessing → postprocessing/utils}/extractBlock.d.ts +0 -0
  357. /package/{umd/typings/src/execution/utils/replaceParameters.test.d.ts → esm/typings/src/prepare/isPipelinePrepared.test.d.ts} +0 -0
  358. /package/umd/typings/src/_packages/{markdown-utils.d.ts → markdown-utils.index.d.ts} +0 -0
  359. /package/umd/typings/src/{utils/postprocessing → postprocessing/utils}/extractBlock.d.ts +0 -0
package/esm/index.es.js CHANGED
@@ -251,7 +251,7 @@ function pipelineJsonToString(pipelineJson) {
251
251
  /* Note: Not using:> name, */
252
252
  title_1 = promptTemplate.title, description_1 = promptTemplate.description,
253
253
  /* Note: dependentParameterNames, */
254
- jokers = promptTemplate.jokers, blockType = promptTemplate.blockType, content = promptTemplate.content, postprocessing = promptTemplate.postprocessing, expectations = promptTemplate.expectations, expectFormat = promptTemplate.expectFormat, resultingParameterName = promptTemplate.resultingParameterName;
254
+ jokers = promptTemplate.jokerParameterNames, blockType = promptTemplate.blockType, content = promptTemplate.content, postprocessing = promptTemplate.postprocessingFunctionNames, expectations = promptTemplate.expectations, expectFormat = promptTemplate.expectFormat, resultingParameterName = promptTemplate.resultingParameterName;
255
255
  pipelineString += '\n\n';
256
256
  pipelineString += "## ".concat(title_1);
257
257
  if (description_1) {
@@ -385,23 +385,107 @@ function promptTemplateParameterJsonToString(promptTemplateParameterJson) {
385
385
  return parameterString;
386
386
  }
387
387
  /**
388
- * TODO: !!!!! Implement new features and commands into `promptTemplateParameterJsonToString`
388
+ * TODO: !!!! Implement new features and commands into `promptTemplateParameterJsonToString`
389
389
  * TODO: [🧠] Is there a way to auto-detect missing features in pipelineJsonToString
390
390
  * TODO: Escape all
391
391
  */
392
392
 
393
+ /**
394
+ * @@@
395
+ *
396
+ * @returns The same object as the input, but deeply frozen
397
+ *
398
+ * Note: This function mutates the object and returns the original (but mutated-deep-freezed) object
399
+ */
400
+ function deepFreeze(objectValue) {
401
+ var e_1, _a;
402
+ var propertyNames = Object.getOwnPropertyNames(objectValue);
403
+ try {
404
+ for (var propertyNames_1 = __values(propertyNames), propertyNames_1_1 = propertyNames_1.next(); !propertyNames_1_1.done; propertyNames_1_1 = propertyNames_1.next()) {
405
+ var propertyName = propertyNames_1_1.value;
406
+ var value = objectValue[propertyName];
407
+ if (value && typeof value === 'object') {
408
+ deepFreeze(value);
409
+ }
410
+ }
411
+ }
412
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
413
+ finally {
414
+ try {
415
+ if (propertyNames_1_1 && !propertyNames_1_1.done && (_a = propertyNames_1.return)) _a.call(propertyNames_1);
416
+ }
417
+ finally { if (e_1) throw e_1.error; }
418
+ }
419
+ return Object.freeze(objectValue);
420
+ }
421
+ /**
422
+ * @@@
423
+ * @@@
424
+ *
425
+ * @returns The same object as the input, but deeply frozen
426
+ *
427
+ * Note: This function mutates the object and returns the original (but mutated-deep-freezed) object
428
+ */
429
+ function deepFreezeWithSameType(objectValue) {
430
+ return deepFreeze(objectValue);
431
+ }
432
+ /**
433
+ * TODO: [🔼] Export from `@promptbook/utils`
434
+ * TODO: [🧠] Is there a way how to meaningfully test this utility
435
+ */
436
+
437
+ /**
438
+ * Returns the same value that is passed as argument.
439
+ * No side effects.
440
+ *
441
+ * Note: It can be usefull for:
442
+ *
443
+ * 1) Leveling indentation
444
+ * 2) Putting always-true or always-false conditions without getting eslint errors
445
+ *
446
+ * @param value any values
447
+ * @returns the same values
448
+ * @private within the repository
449
+ */
450
+ function just(value) {
451
+ if (value === undefined) {
452
+ return undefined;
453
+ }
454
+ return value;
455
+ }
456
+
393
457
  /**
394
458
  * The maximum number of iterations for a loops
395
459
  */
396
460
  var LOOP_LIMIT = 1000;
461
+ /**
462
+ * The maximum number of (LLM) tasks running in parallel
463
+ */
464
+ var MAX_PARALLEL_COUNT = 5;
465
+ /**
466
+ * The maximum number of attempts to execute LLM task before giving up
467
+ */
468
+ var MAX_EXECUTION_ATTEMPTS = 3;
397
469
  /**
398
470
  * The names of the parameters that are reserved for special purposes
399
471
  */
400
- var RESERVED_PARAMETER_NAMES = [
472
+ var RESERVED_PARAMETER_NAMES = deepFreeze([
401
473
  'context',
474
+ 'currentDate',
402
475
  // <- TODO: Add more like 'date', 'modelName',...
403
476
  // <- TODO: Add [emoji] + instructions ACRY when adding new reserved parameter
404
- ];
477
+ ]);
478
+ /**
479
+ * Nonce which is used for replacing things in strings
480
+ */
481
+ var REPLACING_NONCE = 'u$k42k%!V2zo34w7Fu#@QUHYPW';
482
+ /*
483
+ TODO: !!! Just testing false-negative detection of [🟡][🟢][🔵][⚪] leak
484
+ */
485
+ // [🟡][🟢][🔵][⚪]
486
+ /**
487
+ * TODO: [🔼] Export all to core
488
+ */
405
489
 
406
490
  /**
407
491
  * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
@@ -604,7 +688,7 @@ function isValidPipelineUrl(url) {
604
688
  */
605
689
  function validatePipeline(pipeline) {
606
690
  // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
607
- var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
691
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d, e_5, _e;
608
692
  if (pipeline.pipelineUrl !== undefined && !isValidPipelineUrl(pipeline.pipelineUrl)) {
609
693
  // <- Note: [🚲]
610
694
  throw new PipelineLogicError("Invalid promptbook URL \"".concat(pipeline.pipelineUrl, "\""));
@@ -641,19 +725,19 @@ function validatePipeline(pipeline) {
641
725
  };
642
726
  try {
643
727
  // Note: Check each parameter individually
644
- for (var _e = __values(pipeline.parameters), _f = _e.next(); !_f.done; _f = _e.next()) {
645
- var parameter = _f.value;
728
+ for (var _f = __values(pipeline.parameters), _g = _f.next(); !_g.done; _g = _f.next()) {
729
+ var parameter = _g.value;
646
730
  _loop_1(parameter);
647
731
  }
648
732
  }
649
733
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
650
734
  finally {
651
735
  try {
652
- if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
736
+ if (_g && !_g.done && (_a = _f.return)) _a.call(_f);
653
737
  }
654
738
  finally { if (e_1) throw e_1.error; }
655
739
  }
656
- // Note: Check each template individually
740
+ // Note: All input parameters are defined - so that they can be used as result of some template
657
741
  var definedParameters = new Set(pipeline.parameters.filter(function (_a) {
658
742
  var isInput = _a.isInput;
659
743
  return isInput;
@@ -662,23 +746,27 @@ function validatePipeline(pipeline) {
662
746
  return name;
663
747
  }));
664
748
  try {
665
- for (var _g = __values(pipeline.promptTemplates), _h = _g.next(); !_h.done; _h = _g.next()) {
666
- var template = _h.value;
749
+ // Note: Checking each template individually
750
+ for (var _h = __values(pipeline.promptTemplates), _j = _h.next(); !_j.done; _j = _h.next()) {
751
+ var template = _j.value;
667
752
  if (definedParameters.has(template.resultingParameterName)) {
668
753
  throw new PipelineLogicError("Parameter {".concat(template.resultingParameterName, "} is defined multiple times"));
669
754
  }
755
+ if (RESERVED_PARAMETER_NAMES.includes(template.resultingParameterName)) {
756
+ throw new PipelineLogicError("Parameter name {".concat(template.resultingParameterName, "} is reserved, please use fifferent name"));
757
+ }
670
758
  definedParameters.add(template.resultingParameterName);
671
759
  if (template.blockType === 'PROMPT_TEMPLATE' && template.modelRequirements.modelVariant === undefined) {
672
760
  throw new PipelineLogicError(spaceTrim$1("\n\n You must specify MODEL VARIANT in the prompt template \"".concat(template.title, "\"\n\n For example:\n - MODEL VARIANT Chat\n - MODEL NAME `gpt-4-1106-preview`\n\n ")));
673
761
  }
674
- if (template.jokers && template.jokers.length > 0) {
762
+ if (template.jokerParameterNames && template.jokerParameterNames.length > 0) {
675
763
  if (!template.expectFormat &&
676
764
  !template.expectations /* <- TODO: Require at least 1 -> min <- expectation to use jokers */) {
677
765
  throw new PipelineLogicError("Joker parameters are used for {".concat(template.resultingParameterName, "} but no expectations are defined"));
678
766
  }
679
767
  try {
680
- for (var _j = (e_3 = void 0, __values(template.jokers)), _k = _j.next(); !_k.done; _k = _j.next()) {
681
- var joker = _k.value;
768
+ for (var _k = (e_3 = void 0, __values(template.jokerParameterNames)), _l = _k.next(); !_l.done; _l = _k.next()) {
769
+ var joker = _l.value;
682
770
  if (!template.dependentParameterNames.includes(joker)) {
683
771
  throw new PipelineLogicError("Parameter {".concat(joker, "} is used for {").concat(template.resultingParameterName, "} as joker but not in dependentParameterNames"));
684
772
  }
@@ -687,15 +775,15 @@ function validatePipeline(pipeline) {
687
775
  catch (e_3_1) { e_3 = { error: e_3_1 }; }
688
776
  finally {
689
777
  try {
690
- if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
778
+ if (_l && !_l.done && (_c = _k.return)) _c.call(_k);
691
779
  }
692
780
  finally { if (e_3) throw e_3.error; }
693
781
  }
694
782
  }
695
783
  if (template.expectations) {
696
784
  try {
697
- for (var _l = (e_4 = void 0, __values(Object.entries(template.expectations))), _m = _l.next(); !_m.done; _m = _l.next()) {
698
- var _o = __read(_m.value, 2), unit = _o[0], _p = _o[1], min = _p.min, max = _p.max;
785
+ for (var _m = (e_4 = void 0, __values(Object.entries(template.expectations))), _o = _m.next(); !_o.done; _o = _m.next()) {
786
+ var _p = __read(_o.value, 2), unit = _p[0], _q = _p[1], min = _q.min, max = _q.max;
699
787
  if (min !== undefined && max !== undefined && min > max) {
700
788
  throw new PipelineLogicError("Min expectation (=".concat(min, ") of ").concat(unit, " is higher than max expectation (=").concat(max, ")"));
701
789
  }
@@ -710,7 +798,7 @@ function validatePipeline(pipeline) {
710
798
  catch (e_4_1) { e_4 = { error: e_4_1 }; }
711
799
  finally {
712
800
  try {
713
- if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
801
+ if (_o && !_o.done && (_d = _m.return)) _d.call(_m);
714
802
  }
715
803
  finally { if (e_4) throw e_4.error; }
716
804
  }
@@ -720,7 +808,7 @@ function validatePipeline(pipeline) {
720
808
  catch (e_2_1) { e_2 = { error: e_2_1 }; }
721
809
  finally {
722
810
  try {
723
- if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
811
+ if (_j && !_j.done && (_b = _h.return)) _b.call(_h);
724
812
  }
725
813
  finally { if (e_2) throw e_2.error; }
726
814
  }
@@ -734,10 +822,26 @@ function validatePipeline(pipeline) {
734
822
  var name = _a.name;
735
823
  return name;
736
824
  });
825
+ try {
826
+ // Note: All reserved parameters are resolved
827
+ for (var 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()) {
828
+ var reservedParameterName = RESERVED_PARAMETER_NAMES_1_1.value;
829
+ resovedParameters = __spreadArray(__spreadArray([], __read(resovedParameters), false), [reservedParameterName], false);
830
+ }
831
+ }
832
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
833
+ finally {
834
+ try {
835
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_e = RESERVED_PARAMETER_NAMES_1.return)) _e.call(RESERVED_PARAMETER_NAMES_1);
836
+ }
837
+ finally { if (e_5) throw e_5.error; }
838
+ }
737
839
  var unresovedTemplates = __spreadArray([], __read(pipeline.promptTemplates), false);
840
+ // <- TODO: [🧠][🥜]
738
841
  var loopLimit = LOOP_LIMIT;
739
842
  var _loop_2 = function () {
740
843
  if (loopLimit-- < 0) {
844
+ // Note: Really UnexpectedError not LimitReachedError - this should not happen and be caught below
741
845
  throw new UnexpectedError('Loop limit reached during detection of circular dependencies in `validatePipeline`');
742
846
  }
743
847
  var currentlyResovedTemplates = unresovedTemplates.filter(function (template) {
@@ -747,11 +851,11 @@ function validatePipeline(pipeline) {
747
851
  throw new PipelineLogicError(spaceTrim$1(function (block) { return "\n\n Can not resolve some parameters:\n Either you are using a parameter that is not defined, or there are some circular dependencies.\n\n Can not resolve:\n ".concat(block(unresovedTemplates
748
852
  .map(function (_a) {
749
853
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
750
- return "- {".concat(resultingParameterName, "} depends on ").concat(dependentParameterNames
854
+ return "- Parameter {".concat(resultingParameterName, "} which depends on ").concat(dependentParameterNames
751
855
  .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
752
- .join(', '));
856
+ .join(' and '));
753
857
  })
754
- .join('\n')), "\n\n Resolved:\n ").concat(block(resovedParameters.map(function (name) { return "- {".concat(name, "}"); }).join('\n')), "\n "); }));
858
+ .join('\n')), "\n\n Resolved:\n ").concat(block(resovedParameters.map(function (name) { return "- Parameter {".concat(name, "}"); }).join('\n')), "\n "); }));
755
859
  }
756
860
  resovedParameters = __spreadArray(__spreadArray([], __read(resovedParameters), false), __read(currentlyResovedTemplates.map(function (_a) {
757
861
  var resultingParameterName = _a.resultingParameterName;
@@ -773,7 +877,16 @@ function validatePipeline(pipeline) {
773
877
  * > * It checks:
774
878
  * > * - it has a valid structure
775
879
  * > * - ...
776
- * > ex port function validatePipeline(promptbook: unknown): asserts promptbook is PipelineJson {
880
+ * > ex port function validatePipeline(promptbook: really_unknown): asserts promptbook is PipelineJson {
881
+ */
882
+ /**
883
+ * TODO: [🧠][🐣] !!!! Validate that all samples match expectations
884
+ * TODO: [🧠][🐣] !!!! Validate that knowledge is valid (non-void)
885
+ * TODO: [🧠][🐣] !!!! Validate that persona can be used only with CHAT variant
886
+ * TODO: !!!! Validate that parameter with reserved name not used RESERVED_PARAMETER_NAMES
887
+ * TODO: !!!! Validate that reserved parameter is not used as joker
888
+ * TODO: [🧠] !!! Validationg not only logic itself but imports around - files and websites and rerefenced pipelines exists
889
+ * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
777
890
  */
778
891
 
779
892
  /**
@@ -805,79 +918,100 @@ var ReferenceError$1 = /** @class */ (function (_super) {
805
918
  }(Error));
806
919
 
807
920
  /**
808
- * Library of promptbooks that groups together promptbooks for an application.
809
- * This implementation is a very thin wrapper around the Array / Map of promptbooks.
921
+ * Unprepare just strips the preparation data of the pipeline
922
+ */
923
+ function unpreparePipeline(pipeline) {
924
+ var personas = pipeline.personas, knowledgeSources = pipeline.knowledgeSources;
925
+ personas = personas.map(function (persona) { return (__assign(__assign({}, persona), { modelRequirements: undefined, preparationIds: undefined })); });
926
+ knowledgeSources = knowledgeSources.map(function (knowledgeSource) { return (__assign(__assign({}, knowledgeSource), { preparationIds: undefined })); });
927
+ return __assign(__assign({}, pipeline), { knowledgeSources: knowledgeSources, knowledgePieces: [], personas: personas, preparations: [] });
928
+ }
929
+ /**
930
+ * TODO: [🔼] !!! Export via `@promptbook/core`
931
+ * TODO: Write tests for `preparePipeline`
932
+ */
933
+
934
+ /**
935
+ * Library of pipelines that groups together pipelines for an application.
936
+ * This implementation is a very thin wrapper around the Array / Map of pipelines.
810
937
  *
811
938
  * @private use `createCollectionFromJson` instead
812
- * @see https://github.com/webgptorg/promptbook#promptbook-collection
939
+ * @see https://github.com/webgptorg/pipeline#pipeline-collection
813
940
  */
814
941
  var SimplePipelineCollection = /** @class */ (function () {
815
942
  /**
816
- * Constructs a pipeline collection from promptbooks
943
+ * Constructs a pipeline collection from pipelines
817
944
  *
818
- * @param promptbooks !!!
945
+ * @param pipelines @@@
819
946
  *
820
947
  * @private Use instead `createCollectionFromJson`
821
- * Note: During the construction logic of all promptbooks are validated
948
+ * Note: During the construction logic of all pipelines are validated
822
949
  * Note: It is not recommended to use this constructor directly, use `createCollectionFromJson` *(or other variant)* instead
823
950
  */
824
951
  function SimplePipelineCollection() {
825
952
  var e_1, _a;
826
- var promptbooks = [];
953
+ var pipelines = [];
827
954
  for (var _i = 0; _i < arguments.length; _i++) {
828
- promptbooks[_i] = arguments[_i];
955
+ pipelines[_i] = arguments[_i];
829
956
  }
830
957
  this.collection = new Map();
831
958
  try {
832
- for (var promptbooks_1 = __values(promptbooks), promptbooks_1_1 = promptbooks_1.next(); !promptbooks_1_1.done; promptbooks_1_1 = promptbooks_1.next()) {
833
- var promptbook = promptbooks_1_1.value;
834
- if (promptbook.pipelineUrl === undefined) {
835
- throw new ReferenceError$1(spaceTrim$1("\n Promptbook with name \"".concat(promptbook.title, "\" does not have defined URL\n\n File:\n ").concat(promptbook.sourceFile || 'Unknown', "\n\n Note: Promptbooks without URLs are called anonymous promptbooks\n They can be used as standalone promptbooks, but they cannot be referenced by other promptbooks\n And also they cannot be used in the pipeline collection\n\n ")));
959
+ for (var pipelines_1 = __values(pipelines), pipelines_1_1 = pipelines_1.next(); !pipelines_1_1.done; pipelines_1_1 = pipelines_1.next()) {
960
+ var pipeline = pipelines_1_1.value;
961
+ // TODO: [👠] DRY
962
+ if (pipeline.pipelineUrl === undefined) {
963
+ throw new ReferenceError$1(spaceTrim$1("\n Pipeline with name \"".concat(pipeline.title, "\" does not have defined URL\n\n File:\n ").concat(pipeline.sourceFile || 'Unknown', "\n\n Note: Pipelines without URLs are called anonymous pipelines\n They can be used as standalone pipelines, but they cannot be referenced by other pipelines\n And also they cannot be used in the pipeline collection\n\n ")));
836
964
  }
837
- validatePipeline(promptbook);
965
+ // Note: [🐨]
966
+ validatePipeline(pipeline);
967
+ // TODO: [🦄] DRY
838
968
  // Note: [🦄]
839
- if (this.collection.has(promptbook.pipelineUrl) &&
840
- pipelineJsonToString(promptbook) !== pipelineJsonToString(this.collection.get(promptbook.pipelineUrl))) {
841
- var existing = this.collection.get(promptbook.pipelineUrl);
842
- throw new ReferenceError$1(spaceTrim$1("\n Promptbook with URL \"".concat(promptbook.pipelineUrl, "\" is already in the collection\n\n Conflicting files:\n ").concat(existing.sourceFile || 'Unknown', "\n ").concat(promptbook.sourceFile || 'Unknown', "\n\n Note: Promptbooks with the same URL are not allowed\n Only exepction is when the promptbooks are identical\n\n ")));
969
+ if (
970
+ // TODO: [🐽]
971
+ this.collection.has(pipeline.pipelineUrl) &&
972
+ pipelineJsonToString(unpreparePipeline(pipeline)) !==
973
+ pipelineJsonToString(unpreparePipeline(this.collection.get(pipeline.pipelineUrl)))) {
974
+ var existing = this.collection.get(pipeline.pipelineUrl);
975
+ throw new ReferenceError$1(spaceTrim$1("\n Pipeline with URL \"".concat(pipeline.pipelineUrl, "\" is already in the collection\n\n Conflicting files:\n ").concat(existing.sourceFile || 'Unknown', "\n ").concat(pipeline.sourceFile || 'Unknown', "\n\n Note: Pipelines with the same URL are not allowed\n Only exepction is when the pipelines are identical\n\n ")));
843
976
  }
844
- this.collection.set(promptbook.pipelineUrl, promptbook);
977
+ // Note: [🧠] Overwrite existing pipeline with the same URL
978
+ this.collection.set(pipeline.pipelineUrl, pipeline);
845
979
  }
846
980
  }
847
981
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
848
982
  finally {
849
983
  try {
850
- if (promptbooks_1_1 && !promptbooks_1_1.done && (_a = promptbooks_1.return)) _a.call(promptbooks_1);
984
+ if (pipelines_1_1 && !pipelines_1_1.done && (_a = pipelines_1.return)) _a.call(pipelines_1);
851
985
  }
852
986
  finally { if (e_1) throw e_1.error; }
853
987
  }
854
988
  }
855
989
  /**
856
- * Gets all promptbooks in the collection
990
+ * Gets all pipelines in the collection
857
991
  */
858
992
  SimplePipelineCollection.prototype.listPipelines = function () {
859
993
  return Array.from(this.collection.keys());
860
994
  };
861
995
  /**
862
- * Gets promptbook by its URL
996
+ * Gets pipeline by its URL
863
997
  *
864
998
  * Note: This is not a direct fetching from the URL, but a lookup in the collection
865
999
  */
866
1000
  SimplePipelineCollection.prototype.getPipelineByUrl = function (url) {
867
1001
  var _this = this;
868
- var promptbook = this.collection.get(url);
869
- if (!promptbook) {
1002
+ var pipeline = this.collection.get(url);
1003
+ if (!pipeline) {
870
1004
  if (this.listPipelines().length === 0) {
871
- throw new NotFoundError(spaceTrim$1("\n Promptbook with url \"".concat(url, "\" not found\n\n No promptbooks available\n ")));
1005
+ throw new NotFoundError(spaceTrim$1("\n Pipeline with url \"".concat(url, "\" not found\n\n No pipelines available\n ")));
872
1006
  }
873
- throw new NotFoundError(spaceTrim$1(function (block) { return "\n Promptbook with url \"".concat(url, "\" not found\n\n Available promptbooks:\n ").concat(block(_this.listPipelines()
1007
+ throw new NotFoundError(spaceTrim$1(function (block) { return "\n Pipeline with url \"".concat(url, "\" not found\n\n Available pipelines:\n ").concat(block(_this.listPipelines()
874
1008
  .map(function (pipelineUrl) { return "- ".concat(pipelineUrl); })
875
1009
  .join('\n')), "\n\n "); }));
876
1010
  }
877
- return promptbook;
1011
+ return pipeline;
878
1012
  };
879
1013
  /**
880
- * Checks whether given prompt was defined in any promptbook in the collection
1014
+ * Checks whether given prompt was defined in any pipeline in the collection
881
1015
  */
882
1016
  SimplePipelineCollection.prototype.isResponsibleForPrompt = function (prompt) {
883
1017
  return true;
@@ -1119,7 +1253,199 @@ var BlockTypes = [
1119
1253
  // <- [🩻]
1120
1254
  ];
1121
1255
 
1122
- var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.61.0-1",parameters:[{name:"content",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledge",description:"The knowledge JSON object",isInput:false,isOutput:true}],promptTemplates:[{name:"knowledge",title:"Knowledge",dependentParameterNames:["content"],blockType:"PROMPT_TEMPLATE",modelRequirements:{modelVariant:"CHAT",modelName:"claude-3-opus-20240229"},content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {content}",resultingParameterName:"knowledge"}],knowledge:[{name:"n",title:"N",content:"D",keywords:["E"],index:[{modelName:"mocked-facked",position:[-0.8022132744698469,-0.0007443037013543652,-0.34872812971894707,-0.331923610323706,0.36013380510747606,0.3272238545809909,0.9972619939249201,0.261533967444473,0.969397219635256,0.17310495233925405,0.1658542147196167,0.9463503306650436,-0.11780402348338725,-0.19232799237848175,0.6226110088018051,0.2759831058911306,-0.5311583719379294,0.18853474356656497,-0.4508505143158268,-0.6183896225862329,0.5050055293473035,0.1478100741208901,-0.21453327800030664,0.09724866792207987,0.5336888252898944]}],sources:[{title:"Markdown document",href:"#"}]}],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",promptbookVersion:"0.61.0-1",parameters:[{name:"content",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],promptTemplates:[{name:"knowledge",title:"Knowledge",dependentParameterNames:["content"],blockType:"PROMPT_TEMPLATE",modelRequirements:{modelVariant:"CHAT",modelName:"claude-3-opus-20240229"},content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {content}",resultingParameterName:"keywords"}],knowledge:[{name:"e",title:"E",content:"A",keywords:["L"],index:[{modelName:"mocked-facked",position:[-0.10884747467629419,-0.5326698151631195,-0.9465176322534181,0.7751385851237287,-0.7692699503104152,-0.9601969759421696,0.33722965766570434,0.17842011981786943,0.0276452884638827,-0.5983538271731308,-0.127805978741649,-0.6304775592815672,0.8849987254326983,0.1675220238760482,-0.8943010776373641,-0.9569796049357393,0.24933996044411444,0.8210261943632116,0.7193141705292407,0.06170351501887783,0.26972150191994837,-0.5340726089187089,0.12061502629384036,0.29495956103603005,-0.53082082537217]}],sources:[{title:"Markdown document",href:"#"}]}],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",promptbookVersion:"0.61.0-1",parameters:[{name:"content",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],promptTemplates:[{name:"knowledge",title:"Knowledge",dependentParameterNames:["content"],blockType:"PROMPT_TEMPLATE",expectations:{words:{min:1,max:8}},modelRequirements:{modelVariant:"CHAT",modelName:"claude-3-opus-20240229"},content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {content}",resultingParameterName:"title"}],knowledge:[{name:"s",title:"S",content:"A",keywords:["S"],index:[{modelName:"mocked-facked",position:[-0.916989680936596,0.9339948002315257,0.6004732120236658,0.0028125597650441314,-0.055419157811128716,0.013537996506097105,-0.8796279521347974,0.12223482268345887,0.31637982343954674,0.19555443419711915,-0.1664084533259853,-0.3527797149266507,0.3732921105225979,-0.7943618527999234,0.09240919193726871,0.8207777669058434,0.6464285109148693,0.008174116471551418,-0.933937225718561,-0.790531259317556,-0.04738702314966625,-0.9357754186773284,-0.3074287982247097,-0.4579908642989361,0.9857246614213477]}],sources:[{title:"Markdown document",href:"#"}]}],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"}];
1256
+ /**
1257
+ * @@@
1258
+ */
1259
+ function deepClone(objectValue) {
1260
+ return JSON.parse(JSON.stringify(objectValue));
1261
+ /*
1262
+ TODO: [🧠] Is there a better implementation?
1263
+ > const propertyNames = Object.getOwnPropertyNames(objectValue);
1264
+ > for (const propertyName of propertyNames) {
1265
+ > const value = (objectValue as really_any)[propertyName];
1266
+ > if (value && typeof value === 'object') {
1267
+ > deepClone(value);
1268
+ > }
1269
+ > }
1270
+ > return Object.assign({}, objectValue);
1271
+ */
1272
+ }
1273
+ /**
1274
+ * TODO: [🔼] Export from `@promptbook/utils`
1275
+ * TODO: [🧠] Is there a way how to meaningfully test this utility
1276
+ */
1277
+
1278
+ /**
1279
+ * @@@
1280
+ *
1281
+ * TODO: [🔼] Export with addUsage
1282
+ */
1283
+ var ZERO_USAGE = deepFreeze({
1284
+ price: { value: 0 },
1285
+ input: {
1286
+ tokensCount: { value: 0 },
1287
+ charactersCount: { value: 0 },
1288
+ wordsCount: { value: 0 },
1289
+ sentencesCount: { value: 0 },
1290
+ linesCount: { value: 0 },
1291
+ paragraphsCount: { value: 0 },
1292
+ pagesCount: { value: 0 },
1293
+ },
1294
+ output: {
1295
+ tokensCount: { value: 0 },
1296
+ charactersCount: { value: 0 },
1297
+ wordsCount: { value: 0 },
1298
+ sentencesCount: { value: 0 },
1299
+ linesCount: { value: 0 },
1300
+ paragraphsCount: { value: 0 },
1301
+ pagesCount: { value: 0 },
1302
+ },
1303
+ });
1304
+ /**
1305
+ * Function `addUsage` will add multiple usages into one
1306
+ *
1307
+ * Note: If you provide 0 values, it returns ZERO_USAGE
1308
+ */
1309
+ function addUsage() {
1310
+ var usageItems = [];
1311
+ for (var _i = 0; _i < arguments.length; _i++) {
1312
+ usageItems[_i] = arguments[_i];
1313
+ }
1314
+ return usageItems.reduce(function (acc, item) {
1315
+ var e_1, _a, e_2, _b;
1316
+ var _c;
1317
+ acc.price.value += ((_c = item.price) === null || _c === void 0 ? void 0 : _c.value) || 0;
1318
+ try {
1319
+ for (var _d = __values(Object.keys(acc.input)), _e = _d.next(); !_e.done; _e = _d.next()) {
1320
+ var key = _e.value;
1321
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1322
+ //@ts-ignore
1323
+ if (item.input[key]) {
1324
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1325
+ //@ts-ignore
1326
+ acc.input[key].value += item.input[key].value || 0;
1327
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1328
+ //@ts-ignore
1329
+ if (item.input[key].isUncertain) {
1330
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1331
+ //@ts-ignore
1332
+ acc.input[key].isUncertain = true;
1333
+ }
1334
+ }
1335
+ }
1336
+ }
1337
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1338
+ finally {
1339
+ try {
1340
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
1341
+ }
1342
+ finally { if (e_1) throw e_1.error; }
1343
+ }
1344
+ try {
1345
+ for (var _f = __values(Object.keys(acc.output)), _g = _f.next(); !_g.done; _g = _f.next()) {
1346
+ var key = _g.value;
1347
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1348
+ //@ts-ignore
1349
+ if (item.output[key]) {
1350
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1351
+ //@ts-ignore
1352
+ acc.output[key].value += item.output[key].value || 0;
1353
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1354
+ //@ts-ignore
1355
+ if (item.output[key].isUncertain) {
1356
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1357
+ //@ts-ignore
1358
+ acc.output[key].isUncertain = true;
1359
+ }
1360
+ }
1361
+ }
1362
+ }
1363
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
1364
+ finally {
1365
+ try {
1366
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
1367
+ }
1368
+ finally { if (e_2) throw e_2.error; }
1369
+ }
1370
+ return acc;
1371
+ }, deepClone(ZERO_USAGE));
1372
+ }
1373
+
1374
+ /**
1375
+ * Async version of Array.forEach
1376
+ *
1377
+ * @param array - Array to iterate over
1378
+ * @param options - Options for the function
1379
+ * @param callbackfunction - Function to call for each item
1380
+ */
1381
+ function forEachAsync(array, options, callbackfunction) {
1382
+ return __awaiter(this, void 0, void 0, function () {
1383
+ var _a, maxParallelCount, index, runningTasks, tasks, _loop_1, _b, _c, item, e_1_1;
1384
+ var e_1, _d;
1385
+ return __generator(this, function (_e) {
1386
+ switch (_e.label) {
1387
+ case 0:
1388
+ _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? Infinity : _a;
1389
+ index = 0;
1390
+ runningTasks = [];
1391
+ tasks = [];
1392
+ _loop_1 = function (item) {
1393
+ var currentIndex, task;
1394
+ return __generator(this, function (_f) {
1395
+ switch (_f.label) {
1396
+ case 0:
1397
+ currentIndex = index++;
1398
+ task = callbackfunction(item, currentIndex, array);
1399
+ tasks.push(task);
1400
+ runningTasks.push(task);
1401
+ /* not await */ Promise.resolve(task).then(function () {
1402
+ runningTasks = runningTasks.filter(function (t) { return t !== task; });
1403
+ });
1404
+ if (!(maxParallelCount < runningTasks.length)) return [3 /*break*/, 2];
1405
+ return [4 /*yield*/, Promise.race(runningTasks)];
1406
+ case 1:
1407
+ _f.sent();
1408
+ _f.label = 2;
1409
+ case 2: return [2 /*return*/];
1410
+ }
1411
+ });
1412
+ };
1413
+ _e.label = 1;
1414
+ case 1:
1415
+ _e.trys.push([1, 6, 7, 8]);
1416
+ _b = __values(array), _c = _b.next();
1417
+ _e.label = 2;
1418
+ case 2:
1419
+ if (!!_c.done) return [3 /*break*/, 5];
1420
+ item = _c.value;
1421
+ return [5 /*yield**/, _loop_1(item)];
1422
+ case 3:
1423
+ _e.sent();
1424
+ _e.label = 4;
1425
+ case 4:
1426
+ _c = _b.next();
1427
+ return [3 /*break*/, 2];
1428
+ case 5: return [3 /*break*/, 8];
1429
+ case 6:
1430
+ e_1_1 = _e.sent();
1431
+ e_1 = { error: e_1_1 };
1432
+ return [3 /*break*/, 8];
1433
+ case 7:
1434
+ try {
1435
+ if (_c && !_c.done && (_d = _b.return)) _d.call(_b);
1436
+ }
1437
+ finally { if (e_1) throw e_1.error; }
1438
+ return [7 /*endfinally*/];
1439
+ case 8: return [4 /*yield*/, Promise.all(tasks)];
1440
+ case 9:
1441
+ _e.sent();
1442
+ return [2 /*return*/];
1443
+ }
1444
+ });
1445
+ });
1446
+ }
1447
+
1448
+ var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.61.0-19",parameters:[{name:"content",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledge",description:"The knowledge JSON object",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",modelRequirements:{modelVariant:"CHAT",modelName:"claude-3-opus-20240229"},content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {content}",dependentParameterNames:["content"],resultingParameterName:"knowledge"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[{id:1,promptbookVersion:"0.61.0-19",modelUsage:{price:{value:0},input:{tokensCount:{value:0},charactersCount:{value:0},wordsCount:{value:0},sentencesCount:{value:0},linesCount:{value:0},paragraphsCount:{value:0},pagesCount:{value:0}},output:{tokensCount:{value:0},charactersCount:{value:0},wordsCount:{value:0},sentencesCount:{value:0},linesCount:{value:0},paragraphsCount:{value:0},pagesCount:{value:0}}}}],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",promptbookVersion:"0.61.0-19",parameters:[{name:"content",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",modelRequirements:{modelVariant:"CHAT",modelName:"claude-3-opus-20240229"},content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {content}",dependentParameterNames:["content"],resultingParameterName:"keywords"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[{id:1,promptbookVersion:"0.61.0-19",modelUsage:{price:{value:0},input:{tokensCount:{value:0},charactersCount:{value:0},wordsCount:{value:0},sentencesCount:{value:0},linesCount:{value:0},paragraphsCount:{value:0},pagesCount:{value:0}},output:{tokensCount:{value:0},charactersCount:{value:0},wordsCount:{value:0},sentencesCount:{value:0},linesCount:{value:0},paragraphsCount:{value:0},pagesCount:{value:0}}}}],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",promptbookVersion:"0.61.0-19",parameters:[{name:"content",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",modelRequirements:{modelVariant:"CHAT",modelName:"claude-3-opus-20240229"},content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {content}",expectations:{words:{min:1,max:8}},dependentParameterNames:["content"],resultingParameterName:"title"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[{id:1,promptbookVersion:"0.61.0-19",modelUsage:{price:{value:0},input:{tokensCount:{value:0},charactersCount:{value:0},wordsCount:{value:0},sentencesCount:{value:0},linesCount:{value:0},paragraphsCount:{value:0},pagesCount:{value:0}},output:{tokensCount:{value:0},charactersCount:{value:0},wordsCount:{value:0},sentencesCount:{value:0},linesCount:{value:0},paragraphsCount:{value:0},pagesCount:{value:0}}}}],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",promptbookVersion:"0.61.0-19",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",modelRequirements:{modelVariant:"CHAT",modelName:"gpt-4-turbo"},content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n### Option `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Option `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Option `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",expectFormat:"JSON",dependentParameterNames:["availableModelNames","personaDescription"],resultingParameterName:"modelRequirements"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[{id:1,promptbookVersion:"0.61.0-19",modelUsage:{price:{value:0},input:{tokensCount:{value:0},charactersCount:{value:0},wordsCount:{value:0},sentencesCount:{value:0},linesCount:{value:0},paragraphsCount:{value:0},pagesCount:{value:0}},output:{tokensCount:{value:0},charactersCount:{value:0},wordsCount:{value:0},sentencesCount:{value:0},linesCount:{value:0},paragraphsCount:{value:0},pagesCount:{value:0}}}}],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
1123
1449
 
1124
1450
  var defaultDiacriticsRemovalMap = [
1125
1451
  {
@@ -1446,6 +1772,14 @@ function removeEmojis(text) {
1446
1772
  * Function normalizes title to name which can be used as identifier
1447
1773
  */
1448
1774
  function titleToName(value) {
1775
+ if (value.startsWith('http://') || value.startsWith('https://')) {
1776
+ // TODO: Maybe check against some list unallowed characters
1777
+ return value;
1778
+ }
1779
+ if (value.startsWith('./') || value.startsWith('../')) {
1780
+ // TODO: Maybe check against some list unallowed characters
1781
+ return value;
1782
+ }
1449
1783
  value = removeEmojis(value);
1450
1784
  value = normalizeToKebabCase(value);
1451
1785
  // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
@@ -1492,43 +1826,176 @@ function assertsExecutionSuccessful(executionResult) {
1492
1826
  */
1493
1827
 
1494
1828
  /**
1495
- * This error occurs when some expectation is not met in the execution of the pipeline
1829
+ * Parses the template and returns the list of all parameter names
1496
1830
  *
1497
- * @private Always catched and rethrown as `PipelineExecutionError`
1498
- * Note: This is a kindof subtype of PipelineExecutionError
1831
+ * @param template the template with parameters in {curly} braces
1832
+ * @returns the list of parameter names
1499
1833
  */
1500
- var ExpectError = /** @class */ (function (_super) {
1501
- __extends(ExpectError, _super);
1502
- function ExpectError(message) {
1503
- var _this = _super.call(this, message) || this;
1504
- _this.name = 'ExpectError';
1505
- Object.setPrototypeOf(_this, ExpectError.prototype);
1506
- return _this;
1834
+ function extractParameters(template) {
1835
+ var e_1, _a;
1836
+ var matches = template.matchAll(/{\w+}/g);
1837
+ var parameterNames = new Set();
1838
+ try {
1839
+ for (var matches_1 = __values(matches), matches_1_1 = matches_1.next(); !matches_1_1.done; matches_1_1 = matches_1.next()) {
1840
+ var match = matches_1_1.value;
1841
+ var parameterName = match[0].slice(1, -1);
1842
+ parameterNames.add(parameterName);
1843
+ }
1507
1844
  }
1508
- return ExpectError;
1509
- }(Error));
1845
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1846
+ finally {
1847
+ try {
1848
+ if (matches_1_1 && !matches_1_1.done && (_a = matches_1.return)) _a.call(matches_1);
1849
+ }
1850
+ finally { if (e_1) throw e_1.error; }
1851
+ }
1852
+ return parameterNames;
1853
+ }
1510
1854
 
1511
1855
  /**
1512
- * Function isValidJsonString will tell you if the string is valid JSON or not
1856
+ * Parses the given script and returns the list of all used variables that are not defined in the script
1857
+ *
1858
+ * @param script from which to extract the variables
1859
+ * @returns the list of variable names
1860
+ * @throws {ParsingError} if the script is invalid
1513
1861
  */
1514
- function isValidJsonString(value /* <-[👨‍⚖️] */) {
1862
+ function extractVariables(script) {
1863
+ var variables = new Set();
1864
+ script = "(()=>{".concat(script, "})()");
1515
1865
  try {
1516
- JSON.parse(value);
1517
- return true;
1866
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
1867
+ try {
1868
+ eval(script);
1869
+ }
1870
+ catch (error) {
1871
+ if (!(error instanceof ReferenceError)) {
1872
+ throw error;
1873
+ }
1874
+ var undefinedName = error.message.split(' ')[0];
1875
+ /*
1876
+ Note: Parsing the error
1877
+ [ReferenceError: thing is not defined]
1878
+ */
1879
+ if (!undefinedName) {
1880
+ throw error;
1881
+ }
1882
+ if (script.includes(undefinedName + '(')) {
1883
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
1884
+ }
1885
+ else {
1886
+ variables.add(undefinedName);
1887
+ script = "const ".concat(undefinedName, " = '';") + script;
1888
+ }
1889
+ }
1518
1890
  }
1519
1891
  catch (error) {
1520
1892
  if (!(error instanceof Error)) {
1521
1893
  throw error;
1522
1894
  }
1523
- if (error.message.includes('Unexpected token')) {
1524
- return false;
1525
- }
1526
- return false;
1895
+ throw new ParsingError(spaceTrim$1(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.name), ": ").concat(block(error.message), "\n "); }));
1527
1896
  }
1897
+ return variables;
1528
1898
  }
1899
+ /**
1900
+ * TODO: [🔣] Support for multiple languages - python, java,...
1901
+ */
1529
1902
 
1530
1903
  /**
1531
- * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
1904
+ * Parses the prompt template and returns the set of all used parameters
1905
+ *
1906
+ * @param promptTemplate the template with used parameters
1907
+ * @returns the set of parameter names
1908
+ * @throws {ParsingError} if the script is invalid
1909
+ */
1910
+ function extractParametersFromPromptTemplate(promptTemplate) {
1911
+ var e_1, _a, e_2, _b, e_3, _c;
1912
+ var title = promptTemplate.title, description = promptTemplate.description, blockType = promptTemplate.blockType, content = promptTemplate.content, jokerParameterNames = promptTemplate.jokerParameterNames;
1913
+ var parameterNames = new Set();
1914
+ try {
1915
+ for (var _d = __values(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameters(title)), false), __read(extractParameters(description || '')), false), __read(extractParameters(content)), false)), _e = _d.next(); !_e.done; _e = _d.next()) {
1916
+ var parameterName = _e.value;
1917
+ parameterNames.add(parameterName);
1918
+ }
1919
+ }
1920
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1921
+ finally {
1922
+ try {
1923
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
1924
+ }
1925
+ finally { if (e_1) throw e_1.error; }
1926
+ }
1927
+ if (blockType === 'SCRIPT') {
1928
+ try {
1929
+ for (var _f = __values(extractVariables(content)), _g = _f.next(); !_g.done; _g = _f.next()) {
1930
+ var parameterName = _g.value;
1931
+ parameterNames.add(parameterName);
1932
+ }
1933
+ }
1934
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
1935
+ finally {
1936
+ try {
1937
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
1938
+ }
1939
+ finally { if (e_2) throw e_2.error; }
1940
+ }
1941
+ }
1942
+ try {
1943
+ for (var _h = __values(jokerParameterNames || []), _j = _h.next(); !_j.done; _j = _h.next()) {
1944
+ var jokerName = _j.value;
1945
+ parameterNames.add(jokerName);
1946
+ }
1947
+ }
1948
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
1949
+ finally {
1950
+ try {
1951
+ if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
1952
+ }
1953
+ finally { if (e_3) throw e_3.error; }
1954
+ }
1955
+ return parameterNames;
1956
+ }
1957
+ /**
1958
+ * TODO: [🔣] If script require contentLanguage
1959
+ */
1960
+
1961
+ /**
1962
+ * This error occurs when some expectation is not met in the execution of the pipeline
1963
+ *
1964
+ * @private Always catched and rethrown as `PipelineExecutionError`
1965
+ * Note: This is a kindof subtype of PipelineExecutionError
1966
+ */
1967
+ var ExpectError = /** @class */ (function (_super) {
1968
+ __extends(ExpectError, _super);
1969
+ function ExpectError(message) {
1970
+ var _this = _super.call(this, message) || this;
1971
+ _this.name = 'ExpectError';
1972
+ Object.setPrototypeOf(_this, ExpectError.prototype);
1973
+ return _this;
1974
+ }
1975
+ return ExpectError;
1976
+ }(Error));
1977
+
1978
+ /**
1979
+ * Function isValidJsonString will tell you if the string is valid JSON or not
1980
+ */
1981
+ function isValidJsonString(value /* <-[👨‍⚖️] */) {
1982
+ try {
1983
+ JSON.parse(value);
1984
+ return true;
1985
+ }
1986
+ catch (error) {
1987
+ if (!(error instanceof Error)) {
1988
+ throw error;
1989
+ }
1990
+ if (error.message.includes('Unexpected token')) {
1991
+ return false;
1992
+ }
1993
+ return false;
1994
+ }
1995
+ }
1996
+
1997
+ /**
1998
+ * Multiple LLM Execution Tools is a proxy server that uses multiple execution tools internally and exposes the executor interface externally.
1532
1999
  *
1533
2000
  * @private Internal utility of `joinLlmExecutionTools`
1534
2001
  */
@@ -1657,7 +2124,7 @@ var MultipleLlmExecutionTools = /** @class */ (function () {
1657
2124
  throw new PipelineExecutionError(spaceTrim(function (block) { return "\n All execution tools failed:\n\n ".concat(block(errors.map(function (error) { return "- ".concat(error.name || 'Error', ": ").concat(error.message); }).join('\n')), "\n\n "); }));
1658
2125
  }
1659
2126
  else {
1660
- throw new PipelineExecutionError(spaceTrim(function (block) { return "\n No execution tools available for model variant \"".concat(prompt.modelRequirements.modelVariant, "\".\n\n tl;dr\n\n You have provided no LLM Execution Tools that support model variant \"").concat(prompt.modelRequirements.modelVariant, ":\n ").concat(block(_this.llmExecutionTools
2127
+ throw new PipelineExecutionError(spaceTrim(function (block) { return "\n You have not provided any `LlmExecutionTools` that support model variant \"".concat(prompt.modelRequirements.modelVariant, "\n\n Available `LlmExecutionTools`:\n ").concat(block(_this.llmExecutionTools
1661
2128
  .map(function (tools) { return "- ".concat(tools.title, " ").concat(tools.description || ''); })
1662
2129
  .join('\n')), "\n\n "); }));
1663
2130
  }
@@ -1667,7 +2134,7 @@ var MultipleLlmExecutionTools = /** @class */ (function () {
1667
2134
  };
1668
2135
  /**
1669
2136
  * List all available models that can be used
1670
- * This liost is a combination of all available models from all execution tools
2137
+ * This lists is a combination of all available models from all execution tools
1671
2138
  */
1672
2139
  MultipleLlmExecutionTools.prototype.listModels = function () {
1673
2140
  return __awaiter(this, void 0, void 0, function () {
@@ -1713,6 +2180,8 @@ var MultipleLlmExecutionTools = /** @class */ (function () {
1713
2180
  }());
1714
2181
  /**
1715
2182
  * TODO: [🧠][🎛] Aggregating multiple models - have result not only from one first aviable model BUT all of them
2183
+ * TODO: [🏖] If no llmTools have for example not defined `callCompletionModel` this will still return object with defined `callCompletionModel` which just throws `PipelineExecutionError`, make it undefined instead
2184
+ * Look how `countTotalUsage` (and `cacheLlmTools`) implements it
1716
2185
  */
1717
2186
 
1718
2187
  /**
@@ -1734,7 +2203,7 @@ function joinLlmExecutionTools() {
1734
2203
  llmExecutionTools[_i] = arguments[_i];
1735
2204
  }
1736
2205
  if (llmExecutionTools.length === 0) {
1737
- var warningMessage = spaceTrim("\n You have provided no LLM Execution Tools.\n This means that you won't be able to execute any prompts that require large language models like GPT-4 or Anthropic's Claude.\n\n Technically, it's not an error, but it's probably not what you want because it does not make sense to use Promptbook without language models.\n ");
2206
+ var warningMessage = spaceTrim("\n You have not provided any `LlmExecutionTools`\n This means that you won't be able to execute any prompts that require large language models like GPT-4 or Anthropic's Claude.\n\n Technically, it's not an error, but it's probably not what you want because it does not make sense to use Promptbook without language models.\n ");
1738
2207
  // TODO: [🟥] Detect browser / node and make it colorfull
1739
2208
  console.warn(warningMessage);
1740
2209
  /*
@@ -1761,6 +2230,31 @@ function joinLlmExecutionTools() {
1761
2230
  return new (MultipleLlmExecutionTools.bind.apply(MultipleLlmExecutionTools, __spreadArray([void 0], __read(llmExecutionTools), false)))();
1762
2231
  }
1763
2232
 
2233
+ /**
2234
+ * Determine if the pipeline is fully prepared
2235
+ */
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
+ console.log('!!!!', 'Not all personas have modelRequirements');
2241
+ return false;
2242
+ }
2243
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2244
+ console.log('!!!!', 'Not all knowledgeSources have preparationIds');
2245
+ return false;
2246
+ }
2247
+ // TODO: !!!!! Is context in each template
2248
+ // TODO: !!!!! Are samples prepared
2249
+ // TODO: !!!!! Are templates prepared
2250
+ return true;
2251
+ }
2252
+ /**
2253
+ * TODO: [🐠] Maybe base this on `makeValidator`
2254
+ * TODO: [🔼] Export via core or utils
2255
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2256
+ */
2257
+
1764
2258
  /**
1765
2259
  * Takes an item or an array of items and returns an array of items
1766
2260
  *
@@ -1781,102 +2275,173 @@ function arrayableToArray(input) {
1781
2275
  }
1782
2276
 
1783
2277
  /**
1784
- * The version of the Promptbook library
2278
+ * Just marks a place of place where should be something implemented
2279
+ * No side effects.
2280
+ *
2281
+ * Note: It can be usefull suppressing eslint errors of unused variables
2282
+ *
2283
+ * @param value any values
2284
+ * @returns void
2285
+ * @private within the repository
1785
2286
  */
1786
- var PROMPTBOOK_VERSION = '0.61.0-1';
1787
- // TODO: !!!! List here all the versions and annotate + put into script
2287
+ function TODO_USE() {
2288
+ var value = [];
2289
+ for (var _i = 0; _i < arguments.length; _i++) {
2290
+ value[_i] = arguments[_i];
2291
+ }
2292
+ }
1788
2293
 
1789
2294
  /**
1790
- * Function `addUsage` will add multiple usages into one
2295
+ * This error type indicates that some limit was reached
2296
+ */
2297
+ var LimitReachedError = /** @class */ (function (_super) {
2298
+ __extends(LimitReachedError, _super);
2299
+ function LimitReachedError(message) {
2300
+ var _this = _super.call(this, message) || this;
2301
+ _this.name = 'LimitReachedError';
2302
+ Object.setPrototypeOf(_this, LimitReachedError.prototype);
2303
+ return _this;
2304
+ }
2305
+ return LimitReachedError;
2306
+ }(Error));
2307
+
2308
+ /**
2309
+ * Replaces parameters in template with values from parameters object
1791
2310
  *
1792
- * Note: If you provide 0 values, it returns void usage
2311
+ * @param template the template with parameters in {curly} braces
2312
+ * @param parameters the object with parameters
2313
+ * @returns the template with replaced parameters
2314
+ * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
1793
2315
  */
1794
- function addUsage() {
1795
- var usageItems = [];
1796
- for (var _i = 0; _i < arguments.length; _i++) {
1797
- usageItems[_i] = arguments[_i];
2316
+ function replaceParameters(template, parameters) {
2317
+ var replacedTemplate = template;
2318
+ var match;
2319
+ var loopLimit = LOOP_LIMIT;
2320
+ var _loop_1 = function () {
2321
+ if (loopLimit-- < 0) {
2322
+ throw new LimitReachedError('Loop limit reached during parameters replacement in `replaceParameters`');
2323
+ }
2324
+ var precol = match.groups.precol;
2325
+ var parameterName = match.groups.parameterName;
2326
+ if (parameterName === '') {
2327
+ return "continue";
2328
+ }
2329
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
2330
+ throw new PipelineExecutionError('Parameter is already opened or not closed');
2331
+ }
2332
+ if (parameters[parameterName] === undefined) {
2333
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2334
+ }
2335
+ var parameterValue = parameters[parameterName];
2336
+ if (parameterValue === undefined) {
2337
+ throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2338
+ }
2339
+ parameterValue = parameterValue.toString();
2340
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
2341
+ parameterValue = parameterValue
2342
+ .split('\n')
2343
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
2344
+ .join('\n');
2345
+ }
2346
+ replacedTemplate =
2347
+ replacedTemplate.substring(0, match.index + precol.length) +
2348
+ parameterValue +
2349
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
2350
+ };
2351
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
2352
+ .exec(replacedTemplate))) {
2353
+ _loop_1();
1798
2354
  }
1799
- var initialStructure = {
1800
- price: { value: 0 },
1801
- input: {
1802
- tokensCount: { value: 0 },
1803
- charactersCount: { value: 0 },
1804
- wordsCount: { value: 0 },
1805
- sentencesCount: { value: 0 },
1806
- linesCount: { value: 0 },
1807
- paragraphsCount: { value: 0 },
1808
- pagesCount: { value: 0 },
1809
- },
1810
- output: {
1811
- tokensCount: { value: 0 },
1812
- charactersCount: { value: 0 },
1813
- wordsCount: { value: 0 },
1814
- sentencesCount: { value: 0 },
1815
- linesCount: { value: 0 },
1816
- paragraphsCount: { value: 0 },
1817
- pagesCount: { value: 0 },
1818
- },
2355
+ // [💫] Check if there are parameters that are not closed properly
2356
+ if (/{\w+$/.test(replacedTemplate)) {
2357
+ throw new PipelineExecutionError('Parameter is not closed');
2358
+ }
2359
+ // [💫] Check if there are parameters that are not opened properly
2360
+ if (/^\w+}/.test(replacedTemplate)) {
2361
+ throw new PipelineExecutionError('Parameter is not opened');
2362
+ }
2363
+ return replacedTemplate;
2364
+ }
2365
+
2366
+ /**
2367
+ * Create difference set of two sets.
2368
+ *
2369
+ * @deprecated use new javascript set methods instead @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
2370
+ */
2371
+ function difference(a, b, isEqual) {
2372
+ var e_1, _a;
2373
+ if (isEqual === void 0) { isEqual = function (a, b) { return a === b; }; }
2374
+ var diff = new Set();
2375
+ var _loop_1 = function (itemA) {
2376
+ if (!Array.from(b).some(function (itemB) { return isEqual(itemA, itemB); })) {
2377
+ diff.add(itemA);
2378
+ }
1819
2379
  };
1820
- return usageItems.reduce(function (acc, item) {
1821
- var e_1, _a, e_2, _b;
1822
- var _c;
1823
- acc.price.value += ((_c = item.price) === null || _c === void 0 ? void 0 : _c.value) || 0;
2380
+ try {
2381
+ for (var _b = __values(Array.from(a)), _c = _b.next(); !_c.done; _c = _b.next()) {
2382
+ var itemA = _c.value;
2383
+ _loop_1(itemA);
2384
+ }
2385
+ }
2386
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2387
+ finally {
1824
2388
  try {
1825
- for (var _d = __values(Object.keys(acc.input)), _e = _d.next(); !_e.done; _e = _d.next()) {
1826
- var key = _e.value;
1827
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1828
- //@ts-ignore
1829
- if (item.input[key]) {
1830
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1831
- //@ts-ignore
1832
- acc.input[key].value += item.input[key].value || 0;
1833
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1834
- //@ts-ignore
1835
- if (item.input[key].isUncertain) {
1836
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1837
- //@ts-ignore
1838
- acc.input[key].isUncertain = true;
1839
- }
1840
- }
1841
- }
2389
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
1842
2390
  }
1843
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1844
- finally {
2391
+ finally { if (e_1) throw e_1.error; }
2392
+ }
2393
+ return diff;
2394
+ }
2395
+ /**
2396
+ * TODO: [🧠][💯] Maybe also implement symmetricDifference
2397
+ */
2398
+
2399
+ /**
2400
+ * Creates a new set with all elements that are present in either set
2401
+ *
2402
+ * @deprecated use new javascript set methods instead @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
2403
+ */
2404
+ function union() {
2405
+ var e_1, _a, e_2, _b;
2406
+ var sets = [];
2407
+ for (var _i = 0; _i < arguments.length; _i++) {
2408
+ sets[_i] = arguments[_i];
2409
+ }
2410
+ var union = new Set();
2411
+ try {
2412
+ for (var sets_1 = __values(sets), sets_1_1 = sets_1.next(); !sets_1_1.done; sets_1_1 = sets_1.next()) {
2413
+ var set = sets_1_1.value;
1845
2414
  try {
1846
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
2415
+ for (var _c = (e_2 = void 0, __values(Array.from(set))), _d = _c.next(); !_d.done; _d = _c.next()) {
2416
+ var item = _d.value;
2417
+ union.add(item);
2418
+ }
1847
2419
  }
1848
- finally { if (e_1) throw e_1.error; }
1849
- }
1850
- try {
1851
- for (var _f = __values(Object.keys(acc.output)), _g = _f.next(); !_g.done; _g = _f.next()) {
1852
- var key = _g.value;
1853
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1854
- //@ts-ignore
1855
- if (item.output[key]) {
1856
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1857
- //@ts-ignore
1858
- acc.output[key].value += item.output[key].value || 0;
1859
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1860
- //@ts-ignore
1861
- if (item.output[key].isUncertain) {
1862
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1863
- //@ts-ignore
1864
- acc.output[key].isUncertain = true;
1865
- }
2420
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2421
+ finally {
2422
+ try {
2423
+ if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
1866
2424
  }
2425
+ finally { if (e_2) throw e_2.error; }
1867
2426
  }
1868
2427
  }
1869
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
1870
- finally {
1871
- try {
1872
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
1873
- }
1874
- finally { if (e_2) throw e_2.error; }
2428
+ }
2429
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2430
+ finally {
2431
+ try {
2432
+ if (sets_1_1 && !sets_1_1.done && (_a = sets_1.return)) _a.call(sets_1);
1875
2433
  }
1876
- return acc;
1877
- }, initialStructure);
2434
+ finally { if (e_1) throw e_1.error; }
2435
+ }
2436
+ return union;
1878
2437
  }
1879
2438
 
2439
+ /**
2440
+ * The version of the Promptbook library
2441
+ */
2442
+ var PROMPTBOOK_VERSION = '0.61.0-19';
2443
+ // TODO: !!!! List here all the versions and annotate + put into script
2444
+
1880
2445
  /**
1881
2446
  * Counts number of characters in the text
1882
2447
  */
@@ -2008,66 +2573,6 @@ function isPassingExpectations(expectations, value) {
2008
2573
  * TODO: [💝] Unite object for expecting amount and format
2009
2574
  */
2010
2575
 
2011
- /**
2012
- * Replaces parameters in template with values from parameters object
2013
- *
2014
- * @param template the template with parameters in {curly} braces
2015
- * @param parameters the object with parameters
2016
- * @returns the template with replaced parameters
2017
- * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
2018
- *
2019
- * @private within the createPipelineExecutor
2020
- */
2021
- function replaceParameters(template, parameters) {
2022
- var replacedTemplate = template;
2023
- var match;
2024
- var loopLimit = LOOP_LIMIT;
2025
- var _loop_1 = function () {
2026
- if (loopLimit-- < 0) {
2027
- throw new UnexpectedError('Loop limit reached during parameters replacement in `replaceParameters`');
2028
- }
2029
- var precol = match.groups.precol;
2030
- var parameterName = match.groups.parameterName;
2031
- if (parameterName === '') {
2032
- return "continue";
2033
- }
2034
- if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
2035
- throw new PipelineExecutionError('Parameter is already opened or not closed');
2036
- }
2037
- if (parameters[parameterName] === undefined) {
2038
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2039
- }
2040
- var parameterValue = parameters[parameterName];
2041
- if (parameterValue === undefined) {
2042
- throw new PipelineExecutionError("Parameter {".concat(parameterName, "} is not defined"));
2043
- }
2044
- parameterValue = parameterValue.toString();
2045
- if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
2046
- parameterValue = parameterValue
2047
- .split('\n')
2048
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
2049
- .join('\n');
2050
- }
2051
- replacedTemplate =
2052
- replacedTemplate.substring(0, match.index + precol.length) +
2053
- parameterValue +
2054
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
2055
- };
2056
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
2057
- .exec(replacedTemplate))) {
2058
- _loop_1();
2059
- }
2060
- // [💫] Check if there are parameters that are not closed properly
2061
- if (/{\w+$/.test(replacedTemplate)) {
2062
- throw new PipelineExecutionError('Parameter is not closed');
2063
- }
2064
- // [💫] Check if there are parameters that are not opened properly
2065
- if (/^\w+}/.test(replacedTemplate)) {
2066
- throw new PipelineExecutionError('Parameter is not opened');
2067
- }
2068
- return replacedTemplate;
2069
- }
2070
-
2071
2576
  /**
2072
2577
  * Creates executor function from pipeline and execution tools.
2073
2578
  *
@@ -2076,21 +2581,73 @@ function replaceParameters(template, parameters) {
2076
2581
  */
2077
2582
  function createPipelineExecutor(options) {
2078
2583
  var _this = this;
2079
- var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
2080
- var _b = settings.maxExecutionAttempts, maxExecutionAttempts = _b === void 0 ? 3 : _b;
2081
- // TODO: !!!!! Implement new commands
2082
- validatePipeline(pipeline);
2083
- // TODO: !!!!! Do here materialization of still unmaterialized or dynamic knowledge
2084
- // TODO: !!!!! Do here personaToModelRequirements
2584
+ var rawPipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
2585
+ 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 ? false : _d;
2586
+ validatePipeline(rawPipeline);
2085
2587
  var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
2588
+ var pipeline;
2589
+ if (isPipelinePrepared(rawPipeline)) {
2590
+ pipeline = rawPipeline;
2591
+ }
2592
+ else {
2593
+ console.warn(spaceTrim$1("\n Pipeline ".concat(rawPipeline.pipelineUrl || rawPipeline.sourceFile || rawPipeline.title, " is not prepared\n\n It will be prepared ad-hoc before the first execution\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n ")));
2594
+ }
2086
2595
  var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
2596
+ function getContextForTemplate(// <- TODO: [🧠][🥜]
2597
+ template) {
2598
+ return __awaiter(this, void 0, void 0, function () {
2599
+ return __generator(this, function (_a) {
2600
+ // TODO: !!!!!! Implement Better - use real index and keyword search
2601
+ TODO_USE(template);
2602
+ return [2 /*return*/, pipeline.knowledgePieces.map(function (_a) {
2603
+ var content = _a.content;
2604
+ return "- ".concat(content);
2605
+ }).join('\n')];
2606
+ });
2607
+ });
2608
+ }
2609
+ function getReservedParametersForTemplate(template) {
2610
+ return __awaiter(this, void 0, void 0, function () {
2611
+ var context, currentDate, reservedParameters, RESERVED_PARAMETER_NAMES_1, RESERVED_PARAMETER_NAMES_1_1, parameterName;
2612
+ var e_3, _a;
2613
+ return __generator(this, function (_b) {
2614
+ switch (_b.label) {
2615
+ case 0: return [4 /*yield*/, getContextForTemplate(template)];
2616
+ case 1:
2617
+ context = _b.sent();
2618
+ currentDate = new Date().toISOString();
2619
+ reservedParameters = {
2620
+ context: context,
2621
+ currentDate: currentDate,
2622
+ };
2623
+ try {
2624
+ // Note: Doublecheck that ALL reserved parameters are defined:
2625
+ 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()) {
2626
+ parameterName = RESERVED_PARAMETER_NAMES_1_1.value;
2627
+ if (reservedParameters[parameterName] === undefined) {
2628
+ throw new UnexpectedError("Reserved parameter {".concat(parameterName, "} is not defined"));
2629
+ }
2630
+ }
2631
+ }
2632
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
2633
+ finally {
2634
+ try {
2635
+ if (RESERVED_PARAMETER_NAMES_1_1 && !RESERVED_PARAMETER_NAMES_1_1.done && (_a = RESERVED_PARAMETER_NAMES_1.return)) _a.call(RESERVED_PARAMETER_NAMES_1);
2636
+ }
2637
+ finally { if (e_3) throw e_3.error; }
2638
+ }
2639
+ return [2 /*return*/, reservedParameters];
2640
+ }
2641
+ });
2642
+ });
2643
+ }
2087
2644
  function executeSingleTemplate(currentTemplate) {
2088
2645
  return __awaiter(this, void 0, void 0, function () {
2089
- var name, title, priority, prompt, chatResult, completionResult, embeddingResult, result, resultString, expectError, scriptPipelineExecutionErrors, maxAttempts, jokers, attempt, isJokerAttempt, joker, _a, _b, _c, _d, scriptTools, error_2, e_2_1, _e, _f, functionName, postprocessingError, _g, _h, scriptTools, error_3, e_3_1, e_4_1, error_4;
2090
- var e_2, _j, e_4, _k, e_3, _l, _m;
2646
+ var name, title, priority, usedParameterNames, dependentParameterNames, definedParameters, _a, _b, _c, definedParameterNames, parameters, _d, _e, parameterName, prompt, chatResult, completionResult, embeddingResult, result, resultString, expectError, scriptPipelineExecutionErrors, maxAttempts, jokerParameterNames, attempt, isJokerAttempt, jokerParameterName, _f, _g, _h, _j, scriptTools, error_2, e_4_1, _k, _l, functionName, postprocessingError, _m, _o, scriptTools, error_3, e_5_1, e_6_1, error_4;
2647
+ var e_7, _p, e_4, _q, e_6, _r, e_5, _s, _t;
2091
2648
  var _this = this;
2092
- return __generator(this, function (_o) {
2093
- switch (_o.label) {
2649
+ return __generator(this, function (_u) {
2650
+ switch (_u.label) {
2094
2651
  case 0:
2095
2652
  name = "pipeline-executor-frame-".concat(currentTemplate.name);
2096
2653
  title = currentTemplate.title;
@@ -2107,61 +2664,108 @@ function createPipelineExecutor(options) {
2107
2664
  // <- [3]
2108
2665
  })];
2109
2666
  case 1:
2110
- _o.sent();
2111
- _o.label = 2;
2667
+ _u.sent();
2668
+ _u.label = 2;
2112
2669
  case 2:
2670
+ usedParameterNames = extractParametersFromPromptTemplate(currentTemplate);
2671
+ dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
2672
+ if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
2673
+ throw new UnexpectedError(spaceTrim$1("\n Dependent parameters are not consistent used parameters:\n\n Dependent parameters:\n ".concat(Array.from(dependentParameterNames).join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames).join(', '), "\n\n ")));
2674
+ }
2675
+ _b = (_a = Object).freeze;
2676
+ _c = [{}];
2677
+ return [4 /*yield*/, getReservedParametersForTemplate(currentTemplate)];
2678
+ case 3:
2679
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_u.sent())])), parametersToPass])]);
2680
+ definedParameterNames = new Set(Object.keys(definedParameters));
2681
+ parameters = {};
2682
+ try {
2683
+ // Note: [2] Check that all used parameters are defined and removing unused parameters for this template
2684
+ for (_d = __values(Array.from(union(definedParameterNames, usedParameterNames, dependentParameterNames))), _e = _d.next(); !_e.done; _e = _d.next()) {
2685
+ parameterName = _e.value;
2686
+ // Situation: Parameter is defined and used
2687
+ if (definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
2688
+ parameters[parameterName] = definedParameters[parameterName];
2689
+ }
2690
+ // Situation: Parameter is defined but NOT used
2691
+ else if (definedParameterNames.has(parameterName) && !usedParameterNames.has(parameterName)) {
2692
+ // Do not pass this parameter to prompt
2693
+ }
2694
+ // Situation: Parameter is NOT defined BUT used
2695
+ else if (!definedParameterNames.has(parameterName) && usedParameterNames.has(parameterName)) {
2696
+ // Houston, we have a problem
2697
+ // Note: Checking part is also done in `validatePipeline`, but it’s good to doublecheck
2698
+ throw new UnexpectedError(spaceTrim$1("\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 ")));
2699
+ }
2700
+ }
2701
+ }
2702
+ catch (e_7_1) { e_7 = { error: e_7_1 }; }
2703
+ finally {
2704
+ try {
2705
+ if (_e && !_e.done && (_p = _d.return)) _p.call(_d);
2706
+ }
2707
+ finally { if (e_7) throw e_7.error; }
2708
+ }
2709
+ // Note: Now we can freeze `parameters` because we are sure that all and only used parameters are defined
2710
+ Object.freeze(parameters);
2113
2711
  result = null;
2114
2712
  resultString = null;
2115
2713
  expectError = null;
2116
2714
  maxAttempts = currentTemplate.blockType === 'PROMPT_DIALOG' ? Infinity : maxExecutionAttempts;
2117
- jokers = currentTemplate.jokers || [];
2118
- attempt = -jokers.length;
2119
- _o.label = 3;
2120
- case 3:
2121
- if (!(attempt < maxAttempts)) return [3 /*break*/, 51];
2715
+ jokerParameterNames = currentTemplate.jokerParameterNames || [];
2716
+ attempt = -jokerParameterNames.length;
2717
+ _u.label = 4;
2718
+ case 4:
2719
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 52];
2122
2720
  isJokerAttempt = attempt < 0;
2123
- joker = jokers[jokers.length + attempt];
2124
- if (isJokerAttempt && !joker) {
2721
+ jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
2722
+ if (isJokerAttempt && !jokerParameterName) {
2125
2723
  throw new UnexpectedError("Joker not found in attempt ".concat(attempt));
2126
2724
  }
2127
2725
  result = null;
2128
2726
  resultString = null;
2129
2727
  expectError = null;
2130
2728
  if (isJokerAttempt) {
2131
- if (typeof parametersToPass[joker] === 'undefined') {
2132
- throw new PipelineExecutionError("Joker parameter {".concat(joker, "} not defined"));
2729
+ if (parameters[jokerParameterName] === undefined) {
2730
+ throw new PipelineExecutionError("Joker parameter {".concat(jokerParameterName, "} not defined"));
2731
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
2732
+ }
2733
+ else {
2734
+ resultString = parameters[jokerParameterName];
2133
2735
  }
2134
- resultString = parametersToPass[joker];
2135
- }
2136
- _o.label = 4;
2137
- case 4:
2138
- _o.trys.push([4, 47, 48, 49]);
2139
- if (!!isJokerAttempt) return [3 /*break*/, 29];
2140
- _a = currentTemplate.blockType;
2141
- switch (_a) {
2142
- case 'SIMPLE_TEMPLATE': return [3 /*break*/, 5];
2143
- case 'PROMPT_TEMPLATE': return [3 /*break*/, 6];
2144
- case 'SCRIPT': return [3 /*break*/, 15];
2145
- case 'PROMPT_DIALOG': return [3 /*break*/, 26];
2146
2736
  }
2147
- return [3 /*break*/, 28];
2737
+ _u.label = 5;
2148
2738
  case 5:
2149
- resultString = replaceParameters(currentTemplate.content, parametersToPass);
2739
+ _u.trys.push([5, 48, 49, 50]);
2740
+ if (!!isJokerAttempt) return [3 /*break*/, 30];
2741
+ _f = currentTemplate.blockType;
2742
+ switch (_f) {
2743
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 6];
2744
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 7];
2745
+ case 'SCRIPT': return [3 /*break*/, 16];
2746
+ case 'PROMPT_DIALOG': return [3 /*break*/, 27];
2747
+ }
2150
2748
  return [3 /*break*/, 29];
2151
2749
  case 6:
2750
+ resultString = replaceParameters(currentTemplate.content, parameters);
2751
+ return [3 /*break*/, 30];
2752
+ case 7:
2152
2753
  prompt = {
2153
2754
  title: currentTemplate.title,
2154
2755
  pipelineUrl: "".concat(pipeline.pipelineUrl
2155
2756
  ? pipeline.pipelineUrl
2156
2757
  : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
2157
- parameters: parametersToPass,
2158
- content: replaceParameters(currentTemplate.content, parametersToPass) /* <- [2] */,
2758
+ parameters: parameters,
2759
+ content: currentTemplate.content,
2159
2760
  modelRequirements: currentTemplate.modelRequirements,
2160
- expectations: currentTemplate.expectations,
2761
+ expectations: __assign(__assign({}, (pipeline.personas.find(function (_a) {
2762
+ var name = _a.name;
2763
+ return name === currentTemplate.personaName;
2764
+ }) || {})), currentTemplate.expectations),
2161
2765
  expectFormat: currentTemplate.expectFormat,
2162
- postprocessing: (currentTemplate.postprocessing || []).map(function (functionName) { return function (result) { return __awaiter(_this, void 0, void 0, function () {
2163
- var errors, _a, _b, scriptTools, error_5, e_5_1;
2164
- var e_5, _c;
2766
+ postprocessing: (currentTemplate.postprocessingFunctionNames || []).map(function (functionName) { return function (result) { return __awaiter(_this, void 0, void 0, function () {
2767
+ var errors, _a, _b, scriptTools, error_5, e_8_1;
2768
+ var e_8, _c;
2165
2769
  return __generator(this, function (_d) {
2166
2770
  switch (_d.label) {
2167
2771
  case 0:
@@ -2182,7 +2786,7 @@ function createPipelineExecutor(options) {
2182
2786
  script: "".concat(functionName, "(result)"),
2183
2787
  parameters: {
2184
2788
  result: result || '',
2185
- // Note: No ...parametersToPass, because working with result only
2789
+ // Note: No ...parametersForTemplate, because working with result only
2186
2790
  },
2187
2791
  })];
2188
2792
  case 4: return [2 /*return*/, _d.sent()];
@@ -2191,6 +2795,9 @@ function createPipelineExecutor(options) {
2191
2795
  if (!(error_5 instanceof Error)) {
2192
2796
  throw error_5;
2193
2797
  }
2798
+ if (error_5 instanceof UnexpectedError) {
2799
+ throw error_5;
2800
+ }
2194
2801
  errors.push(error_5);
2195
2802
  return [3 /*break*/, 6];
2196
2803
  case 6:
@@ -2198,14 +2805,14 @@ function createPipelineExecutor(options) {
2198
2805
  return [3 /*break*/, 2];
2199
2806
  case 7: return [3 /*break*/, 10];
2200
2807
  case 8:
2201
- e_5_1 = _d.sent();
2202
- e_5 = { error: e_5_1 };
2808
+ e_8_1 = _d.sent();
2809
+ e_8 = { error: e_8_1 };
2203
2810
  return [3 /*break*/, 10];
2204
2811
  case 9:
2205
2812
  try {
2206
2813
  if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
2207
2814
  }
2208
- finally { if (e_5) throw e_5.error; }
2815
+ finally { if (e_8) throw e_8.error; }
2209
2816
  return [7 /*endfinally*/];
2210
2817
  case 10:
2211
2818
  if (errors.length === 0) {
@@ -2221,35 +2828,35 @@ function createPipelineExecutor(options) {
2221
2828
  });
2222
2829
  }); }; }),
2223
2830
  };
2224
- _b = currentTemplate.modelRequirements.modelVariant;
2225
- switch (_b) {
2226
- case 'CHAT': return [3 /*break*/, 7];
2227
- case 'COMPLETION': return [3 /*break*/, 9];
2228
- case 'EMBEDDING': return [3 /*break*/, 11];
2831
+ _g = currentTemplate.modelRequirements.modelVariant;
2832
+ switch (_g) {
2833
+ case 'CHAT': return [3 /*break*/, 8];
2834
+ case 'COMPLETION': return [3 /*break*/, 10];
2835
+ case 'EMBEDDING': return [3 /*break*/, 12];
2229
2836
  }
2230
- return [3 /*break*/, 13];
2231
- case 7: return [4 /*yield*/, llmTools.callChatModel(prompt)];
2232
- case 8:
2233
- chatResult = _o.sent();
2837
+ return [3 /*break*/, 14];
2838
+ case 8: return [4 /*yield*/, llmTools.callChatModel(deepFreeze(prompt))];
2839
+ case 9:
2840
+ chatResult = _u.sent();
2234
2841
  // TODO: [🍬] Destroy chatThread
2235
2842
  result = chatResult;
2236
2843
  resultString = chatResult.content;
2237
- return [3 /*break*/, 14];
2238
- case 9: return [4 /*yield*/, llmTools.callCompletionModel(prompt)];
2239
- case 10:
2240
- completionResult = _o.sent();
2844
+ return [3 /*break*/, 15];
2845
+ case 10: return [4 /*yield*/, llmTools.callCompletionModel(deepFreeze(prompt))];
2846
+ case 11:
2847
+ completionResult = _u.sent();
2241
2848
  result = completionResult;
2242
2849
  resultString = completionResult.content;
2243
- return [3 /*break*/, 14];
2244
- case 11: return [4 /*yield*/, llmTools.callEmbeddingModel(prompt)];
2245
- case 12:
2246
- embeddingResult = _o.sent();
2850
+ return [3 /*break*/, 15];
2851
+ case 12: return [4 /*yield*/, llmTools.callEmbeddingModel(deepFreeze(prompt))];
2852
+ case 13:
2853
+ embeddingResult = _u.sent();
2247
2854
  result = embeddingResult;
2248
2855
  resultString = embeddingResult.content.join(',');
2249
- return [3 /*break*/, 14];
2250
- case 13: throw new PipelineExecutionError("Unknown model variant \"".concat(currentTemplate.modelRequirements.modelVariant, "\""));
2251
- case 14: return [3 /*break*/, 29];
2252
- case 15:
2856
+ return [3 /*break*/, 15];
2857
+ case 14: throw new PipelineExecutionError("Unknown model variant \"".concat(currentTemplate.modelRequirements.modelVariant, "\""));
2858
+ case 15: return [3 /*break*/, 30];
2859
+ case 16:
2253
2860
  if (arrayableToArray(tools.script).length === 0) {
2254
2861
  throw new PipelineExecutionError('No script execution tools are available');
2255
2862
  }
@@ -2258,49 +2865,52 @@ function createPipelineExecutor(options) {
2258
2865
  }
2259
2866
  // TODO: DRY [1]
2260
2867
  scriptPipelineExecutionErrors = [];
2261
- _o.label = 16;
2262
- case 16:
2263
- _o.trys.push([16, 23, 24, 25]);
2264
- _c = (e_2 = void 0, __values(arrayableToArray(tools.script))), _d = _c.next();
2265
- _o.label = 17;
2868
+ _u.label = 17;
2266
2869
  case 17:
2267
- if (!!_d.done) return [3 /*break*/, 22];
2268
- scriptTools = _d.value;
2269
- _o.label = 18;
2870
+ _u.trys.push([17, 24, 25, 26]);
2871
+ _h = (e_4 = void 0, __values(arrayableToArray(tools.script))), _j = _h.next();
2872
+ _u.label = 18;
2270
2873
  case 18:
2271
- _o.trys.push([18, 20, , 21]);
2272
- return [4 /*yield*/, scriptTools.execute({
2874
+ if (!!_j.done) return [3 /*break*/, 23];
2875
+ scriptTools = _j.value;
2876
+ _u.label = 19;
2877
+ case 19:
2878
+ _u.trys.push([19, 21, , 22]);
2879
+ return [4 /*yield*/, scriptTools.execute(deepFreeze({
2273
2880
  scriptLanguage: currentTemplate.contentLanguage,
2274
2881
  script: currentTemplate.content,
2275
- parameters: parametersToPass,
2276
- })];
2277
- case 19:
2278
- resultString = _o.sent();
2279
- return [3 /*break*/, 22];
2882
+ parameters: parameters,
2883
+ }))];
2280
2884
  case 20:
2281
- error_2 = _o.sent();
2885
+ resultString = _u.sent();
2886
+ return [3 /*break*/, 23];
2887
+ case 21:
2888
+ error_2 = _u.sent();
2282
2889
  if (!(error_2 instanceof Error)) {
2283
2890
  throw error_2;
2284
2891
  }
2892
+ if (error_2 instanceof UnexpectedError) {
2893
+ throw error_2;
2894
+ }
2285
2895
  scriptPipelineExecutionErrors.push(error_2);
2286
- return [3 /*break*/, 21];
2287
- case 21:
2288
- _d = _c.next();
2289
- return [3 /*break*/, 17];
2290
- case 22: return [3 /*break*/, 25];
2291
- case 23:
2292
- e_2_1 = _o.sent();
2293
- e_2 = { error: e_2_1 };
2294
- return [3 /*break*/, 25];
2896
+ return [3 /*break*/, 22];
2897
+ case 22:
2898
+ _j = _h.next();
2899
+ return [3 /*break*/, 18];
2900
+ case 23: return [3 /*break*/, 26];
2295
2901
  case 24:
2902
+ e_4_1 = _u.sent();
2903
+ e_4 = { error: e_4_1 };
2904
+ return [3 /*break*/, 26];
2905
+ case 25:
2296
2906
  try {
2297
- if (_d && !_d.done && (_j = _c.return)) _j.call(_c);
2907
+ if (_j && !_j.done && (_q = _h.return)) _q.call(_h);
2298
2908
  }
2299
- finally { if (e_2) throw e_2.error; }
2909
+ finally { if (e_4) throw e_4.error; }
2300
2910
  return [7 /*endfinally*/];
2301
- case 25:
2911
+ case 26:
2302
2912
  if (resultString !== null) {
2303
- return [3 /*break*/, 29];
2913
+ return [3 /*break*/, 30];
2304
2914
  }
2305
2915
  if (scriptPipelineExecutionErrors.length === 1) {
2306
2916
  throw scriptPipelineExecutionErrors[0];
@@ -2310,101 +2920,104 @@ function createPipelineExecutor(options) {
2310
2920
  .map(function (error) { return '- ' + error.message; })
2311
2921
  .join('\n\n')), "\n "); }));
2312
2922
  }
2313
- case 26:
2923
+ case 27:
2314
2924
  if (tools.userInterface === undefined) {
2315
2925
  throw new PipelineExecutionError('User interface tools are not available');
2316
2926
  }
2317
- return [4 /*yield*/, tools.userInterface.promptDialog({
2927
+ return [4 /*yield*/, tools.userInterface.promptDialog(deepFreeze({
2318
2928
  promptTitle: currentTemplate.title,
2319
- promptMessage: replaceParameters(currentTemplate.description || '', parametersToPass),
2320
- defaultValue: replaceParameters(currentTemplate.content, parametersToPass),
2929
+ promptMessage: replaceParameters(currentTemplate.description || '', parameters),
2930
+ defaultValue: replaceParameters(currentTemplate.content, parameters),
2321
2931
  // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
2322
2932
  placeholder: undefined,
2323
2933
  priority: priority,
2324
- })];
2325
- case 27:
2934
+ }))];
2935
+ case 28:
2326
2936
  // TODO: [🌹] When making next attempt for `PROMPT DIALOG`, preserve the previous user input
2327
- resultString = _o.sent();
2328
- return [3 /*break*/, 29];
2329
- case 28: throw new PipelineExecutionError("Unknown execution type \"".concat(currentTemplate.blockType, "\""));
2330
- case 29:
2331
- if (!(!isJokerAttempt && currentTemplate.postprocessing)) return [3 /*break*/, 46];
2332
- _o.label = 30;
2937
+ resultString = _u.sent();
2938
+ return [3 /*break*/, 30];
2939
+ case 29: throw new PipelineExecutionError("Unknown execution type \"".concat(currentTemplate.blockType, "\""));
2333
2940
  case 30:
2334
- _o.trys.push([30, 44, 45, 46]);
2335
- _e = (e_4 = void 0, __values(currentTemplate.postprocessing)), _f = _e.next();
2336
- _o.label = 31;
2941
+ if (!(!isJokerAttempt && currentTemplate.postprocessingFunctionNames)) return [3 /*break*/, 47];
2942
+ _u.label = 31;
2337
2943
  case 31:
2338
- if (!!_f.done) return [3 /*break*/, 43];
2339
- functionName = _f.value;
2944
+ _u.trys.push([31, 45, 46, 47]);
2945
+ _k = (e_6 = void 0, __values(currentTemplate.postprocessingFunctionNames)), _l = _k.next();
2946
+ _u.label = 32;
2947
+ case 32:
2948
+ if (!!_l.done) return [3 /*break*/, 44];
2949
+ functionName = _l.value;
2340
2950
  // TODO: DRY [1]
2341
2951
  scriptPipelineExecutionErrors = [];
2342
2952
  postprocessingError = null;
2343
- _o.label = 32;
2344
- case 32:
2345
- _o.trys.push([32, 39, 40, 41]);
2346
- _g = (e_3 = void 0, __values(arrayableToArray(tools.script))), _h = _g.next();
2347
- _o.label = 33;
2953
+ _u.label = 33;
2348
2954
  case 33:
2349
- if (!!_h.done) return [3 /*break*/, 38];
2350
- scriptTools = _h.value;
2351
- _o.label = 34;
2955
+ _u.trys.push([33, 40, 41, 42]);
2956
+ _m = (e_5 = void 0, __values(arrayableToArray(tools.script))), _o = _m.next();
2957
+ _u.label = 34;
2352
2958
  case 34:
2353
- _o.trys.push([34, 36, , 37]);
2959
+ if (!!_o.done) return [3 /*break*/, 39];
2960
+ scriptTools = _o.value;
2961
+ _u.label = 35;
2962
+ case 35:
2963
+ _u.trys.push([35, 37, , 38]);
2354
2964
  return [4 /*yield*/, scriptTools.execute({
2355
2965
  scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
2356
2966
  script: "".concat(functionName, "(resultString)"),
2357
2967
  parameters: {
2358
2968
  resultString: resultString || '',
2359
- // Note: No ...parametersToPass, because working with result only
2969
+ // Note: No ...parametersForTemplate, because working with result only
2360
2970
  },
2361
2971
  })];
2362
- case 35:
2363
- resultString = _o.sent();
2364
- postprocessingError = null;
2365
- return [3 /*break*/, 38];
2366
2972
  case 36:
2367
- error_3 = _o.sent();
2973
+ resultString = _u.sent();
2974
+ postprocessingError = null;
2975
+ return [3 /*break*/, 39];
2976
+ case 37:
2977
+ error_3 = _u.sent();
2368
2978
  if (!(error_3 instanceof Error)) {
2369
2979
  throw error_3;
2370
2980
  }
2981
+ if (error_3 instanceof UnexpectedError) {
2982
+ throw error_3;
2983
+ }
2371
2984
  postprocessingError = error_3;
2372
2985
  scriptPipelineExecutionErrors.push(error_3);
2373
- return [3 /*break*/, 37];
2374
- case 37:
2375
- _h = _g.next();
2376
- return [3 /*break*/, 33];
2377
- case 38: return [3 /*break*/, 41];
2378
- case 39:
2379
- e_3_1 = _o.sent();
2380
- e_3 = { error: e_3_1 };
2381
- return [3 /*break*/, 41];
2986
+ return [3 /*break*/, 38];
2987
+ case 38:
2988
+ _o = _m.next();
2989
+ return [3 /*break*/, 34];
2990
+ case 39: return [3 /*break*/, 42];
2382
2991
  case 40:
2992
+ e_5_1 = _u.sent();
2993
+ e_5 = { error: e_5_1 };
2994
+ return [3 /*break*/, 42];
2995
+ case 41:
2383
2996
  try {
2384
- if (_h && !_h.done && (_l = _g.return)) _l.call(_g);
2997
+ if (_o && !_o.done && (_s = _m.return)) _s.call(_m);
2385
2998
  }
2386
- finally { if (e_3) throw e_3.error; }
2999
+ finally { if (e_5) throw e_5.error; }
2387
3000
  return [7 /*endfinally*/];
2388
- case 41:
3001
+ case 42:
2389
3002
  if (postprocessingError) {
2390
3003
  throw postprocessingError;
2391
3004
  }
2392
- _o.label = 42;
2393
- case 42:
2394
- _f = _e.next();
2395
- return [3 /*break*/, 31];
2396
- case 43: return [3 /*break*/, 46];
2397
- case 44:
2398
- e_4_1 = _o.sent();
2399
- e_4 = { error: e_4_1 };
2400
- return [3 /*break*/, 46];
3005
+ _u.label = 43;
3006
+ case 43:
3007
+ _l = _k.next();
3008
+ return [3 /*break*/, 32];
3009
+ case 44: return [3 /*break*/, 47];
2401
3010
  case 45:
3011
+ e_6_1 = _u.sent();
3012
+ e_6 = { error: e_6_1 };
3013
+ return [3 /*break*/, 47];
3014
+ case 46:
2402
3015
  try {
2403
- if (_f && !_f.done && (_k = _e.return)) _k.call(_e);
3016
+ if (_l && !_l.done && (_r = _k.return)) _r.call(_k);
2404
3017
  }
2405
- finally { if (e_4) throw e_4.error; }
3018
+ finally { if (e_6) throw e_6.error; }
2406
3019
  return [7 /*endfinally*/];
2407
- case 46:
3020
+ case 47:
2408
3021
  // TODO: [💝] Unite object for expecting amount and format
2409
3022
  if (currentTemplate.expectFormat) {
2410
3023
  if (currentTemplate.expectFormat === 'JSON') {
@@ -2417,15 +3030,18 @@ function createPipelineExecutor(options) {
2417
3030
  if (currentTemplate.expectations) {
2418
3031
  checkExpectations(currentTemplate.expectations, resultString || '');
2419
3032
  }
2420
- return [3 /*break*/, 51];
2421
- case 47:
2422
- error_4 = _o.sent();
3033
+ return [3 /*break*/, 52];
3034
+ case 48:
3035
+ error_4 = _u.sent();
2423
3036
  if (!(error_4 instanceof ExpectError)) {
2424
3037
  throw error_4;
2425
3038
  }
3039
+ if (error_4 instanceof UnexpectedError) {
3040
+ throw error_4;
3041
+ }
2426
3042
  expectError = error_4;
2427
- return [3 /*break*/, 49];
2428
- case 48:
3043
+ return [3 /*break*/, 50];
3044
+ case 49:
2429
3045
  if (!isJokerAttempt &&
2430
3046
  currentTemplate.blockType === 'PROMPT_TEMPLATE' &&
2431
3047
  prompt
@@ -2447,15 +3063,15 @@ function createPipelineExecutor(options) {
2447
3063
  });
2448
3064
  }
2449
3065
  return [7 /*endfinally*/];
2450
- case 49:
3066
+ case 50:
2451
3067
  if (expectError !== null && attempt === maxAttempts - 1) {
2452
3068
  throw new PipelineExecutionError(spaceTrim$1(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ---\n Last error ").concat((expectError === null || expectError === void 0 ? void 0 : expectError.name) || '', ":\n ").concat(block((expectError === null || expectError === void 0 ? void 0 : expectError.message) || ''), "\n\n Last result:\n ").concat(resultString, "\n ---\n "); }));
2453
3069
  }
2454
- _o.label = 50;
2455
- case 50:
2456
- attempt++;
2457
- return [3 /*break*/, 3];
3070
+ _u.label = 51;
2458
3071
  case 51:
3072
+ attempt++;
3073
+ return [3 /*break*/, 4];
3074
+ case 52:
2459
3075
  if (resultString === null) {
2460
3076
  throw new UnexpectedError('Something went wrong and prompt result is null');
2461
3077
  }
@@ -2471,18 +3087,27 @@ function createPipelineExecutor(options) {
2471
3087
  // <- [3]
2472
3088
  });
2473
3089
  }
2474
- parametersToPass = __assign(__assign({}, parametersToPass), (_m = {}, _m[currentTemplate.resultingParameterName] = resultString /* <- Note: Not need to detect parameter collision here because pipeline checks logic consistency during construction */, _m));
3090
+ parametersToPass = Object.freeze(__assign(__assign({}, parametersToPass), (_t = {}, _t[currentTemplate.resultingParameterName] = resultString /* <- Note: Not need to detect parameter collision here because pipeline checks logic consistency during construction */, _t)));
2475
3091
  return [2 /*return*/];
2476
3092
  }
2477
3093
  });
2478
3094
  });
2479
3095
  }
2480
- var parametersToPass, executionReport, resovedParameters_1, unresovedTemplates, resolving_1, loopLimit, _loop_1, error_1, usage_1, _a, _b, parameter, usage;
2481
- var e_1, _c;
2482
- return __generator(this, function (_d) {
2483
- switch (_d.label) {
3096
+ var executionReport, _a, _b, parameter, parametersToPass, resovedParameters_1, unresovedTemplates_1, resolving_1, loopLimit, _loop_1, error_1, usage_1, outputParameters, errors, _c, _d, parameter, usage;
3097
+ var e_1, _e, e_2, _f;
3098
+ return __generator(this, function (_g) {
3099
+ switch (_g.label) {
2484
3100
  case 0:
2485
- parametersToPass = inputParameters;
3101
+ if (!(pipeline === undefined)) return [3 /*break*/, 2];
3102
+ return [4 /*yield*/, preparePipeline(rawPipeline, {
3103
+ llmTools: llmTools,
3104
+ isVerbose: isVerbose,
3105
+ maxParallelCount: maxParallelCount,
3106
+ })];
3107
+ case 1:
3108
+ pipeline = _g.sent();
3109
+ _g.label = 2;
3110
+ case 2:
2486
3111
  executionReport = {
2487
3112
  pipelineUrl: pipeline.pipelineUrl,
2488
3113
  title: pipeline.title,
@@ -2491,9 +3116,35 @@ function createPipelineExecutor(options) {
2491
3116
  description: pipeline.description,
2492
3117
  promptExecutions: [],
2493
3118
  };
2494
- _d.label = 1;
2495
- case 1:
2496
- _d.trys.push([1, 6, , 7]);
3119
+ try {
3120
+ // Note: Check that all input input parameters are defined
3121
+ for (_a = __values(pipeline.parameters), _b = _a.next(); !_b.done; _b = _a.next()) {
3122
+ parameter = _b.value;
3123
+ if (parameter.isInput && inputParameters[parameter.name] === undefined) {
3124
+ return [2 /*return*/, deepFreezeWithSameType({
3125
+ isSuccessful: false,
3126
+ errors: [
3127
+ new PipelineExecutionError("Parameter {".concat(parameter.name, "} is required as an input parameter")),
3128
+ // <- TODO: !!!!! Test this error
3129
+ ],
3130
+ executionReport: executionReport,
3131
+ outputParameters: {},
3132
+ usage: ZERO_USAGE,
3133
+ })];
3134
+ }
3135
+ }
3136
+ }
3137
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3138
+ finally {
3139
+ try {
3140
+ if (_b && !_b.done && (_e = _a.return)) _e.call(_a);
3141
+ }
3142
+ finally { if (e_1) throw e_1.error; }
3143
+ }
3144
+ parametersToPass = inputParameters;
3145
+ _g.label = 3;
3146
+ case 3:
3147
+ _g.trys.push([3, 8, , 9]);
2497
3148
  resovedParameters_1 = pipeline.parameters
2498
3149
  .filter(function (_a) {
2499
3150
  var isInput = _a.isInput;
@@ -2503,30 +3154,36 @@ function createPipelineExecutor(options) {
2503
3154
  var name = _a.name;
2504
3155
  return name;
2505
3156
  });
2506
- unresovedTemplates = __spreadArray([], __read(pipeline.promptTemplates), false);
3157
+ unresovedTemplates_1 = __spreadArray([], __read(pipeline.promptTemplates), false);
2507
3158
  resolving_1 = [];
2508
3159
  loopLimit = LOOP_LIMIT;
2509
3160
  _loop_1 = function () {
2510
3161
  var currentTemplate, work_1;
2511
- return __generator(this, function (_e) {
2512
- switch (_e.label) {
3162
+ return __generator(this, function (_h) {
3163
+ switch (_h.label) {
2513
3164
  case 0:
2514
3165
  if (loopLimit-- < 0) {
3166
+ // Note: Really UnexpectedError not LimitReachedError - this should be catched during validatePipeline
2515
3167
  throw new UnexpectedError('Loop limit reached during resolving parameters pipeline execution');
2516
3168
  }
2517
- currentTemplate = unresovedTemplates.find(function (template) {
3169
+ currentTemplate = unresovedTemplates_1.find(function (template) {
2518
3170
  return template.dependentParameterNames.every(function (name) { return resovedParameters_1.includes(name); });
2519
3171
  });
2520
3172
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
2521
- throw new UnexpectedError(spaceTrim$1("\n Can not resolve some parameters\n\n Note: This should be catched during validatePipeline\n "));
3173
+ throw new UnexpectedError(spaceTrim$1(function (block) { return "\n Can not resolve some parameters\n\n Note: This should be catched in `validatePipeline`\n\n\n Unresolved parameters:\n ".concat(block(unresovedTemplates_1
3174
+ .map(function (_a) {
3175
+ var resultingParameterName = _a.resultingParameterName;
3176
+ return "- {".concat(resultingParameterName, "}");
3177
+ })
3178
+ .join('\n')), "\n\n Resolved parameters:\n ").concat(block(resovedParameters_1.map(function (name) { return "- {".concat(name, "}"); }).join('\n')), "\n "); }));
2522
3179
  case 1:
2523
3180
  if (!!currentTemplate) return [3 /*break*/, 3];
2524
3181
  /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
2525
3182
  case 2:
2526
- /* [5] */ _e.sent();
3183
+ /* [5] */ _h.sent();
2527
3184
  return [3 /*break*/, 4];
2528
3185
  case 3:
2529
- unresovedTemplates = unresovedTemplates.filter(function (template) { return template !== currentTemplate; });
3186
+ unresovedTemplates_1 = unresovedTemplates_1.filter(function (template) { return template !== currentTemplate; });
2530
3187
  work_1 = executeSingleTemplate(currentTemplate)
2531
3188
  .then(function () {
2532
3189
  resovedParameters_1 = __spreadArray(__spreadArray([], __read(resovedParameters_1), false), [currentTemplate.resultingParameterName], false);
@@ -2535,120 +3192,133 @@ function createPipelineExecutor(options) {
2535
3192
  resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
2536
3193
  });
2537
3194
  resolving_1.push(work_1);
2538
- _e.label = 4;
3195
+ _h.label = 4;
2539
3196
  case 4: return [2 /*return*/];
2540
3197
  }
2541
3198
  });
2542
3199
  };
2543
- _d.label = 2;
2544
- case 2:
2545
- if (!(unresovedTemplates.length > 0)) return [3 /*break*/, 4];
3200
+ _g.label = 4;
3201
+ case 4:
3202
+ if (!(unresovedTemplates_1.length > 0)) return [3 /*break*/, 6];
2546
3203
  return [5 /*yield**/, _loop_1()];
2547
- case 3:
2548
- _d.sent();
2549
- return [3 /*break*/, 2];
2550
- case 4: return [4 /*yield*/, Promise.all(resolving_1)];
2551
3204
  case 5:
2552
- _d.sent();
2553
- return [3 /*break*/, 7];
2554
- case 6:
2555
- error_1 = _d.sent();
3205
+ _g.sent();
3206
+ return [3 /*break*/, 4];
3207
+ case 6: return [4 /*yield*/, Promise.all(resolving_1)];
3208
+ case 7:
3209
+ _g.sent();
3210
+ return [3 /*break*/, 9];
3211
+ case 8:
3212
+ error_1 = _g.sent();
2556
3213
  if (!(error_1 instanceof Error)) {
2557
3214
  throw error_1;
2558
3215
  }
2559
3216
  usage_1 = addUsage.apply(void 0, __spreadArray([], __read(executionReport.promptExecutions.map(function (_a) {
2560
3217
  var result = _a.result;
2561
- return (result === null || result === void 0 ? void 0 : result.usage) || addUsage();
3218
+ return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
2562
3219
  })), false));
2563
- return [2 /*return*/, {
3220
+ return [2 /*return*/, deepFreezeWithSameType({
2564
3221
  isSuccessful: false,
2565
3222
  errors: [error_1],
2566
3223
  usage: usage_1,
2567
3224
  executionReport: executionReport,
2568
3225
  outputParameters: parametersToPass,
2569
- }];
2570
- case 7:
3226
+ })];
3227
+ case 9:
3228
+ outputParameters = {};
3229
+ errors = [];
2571
3230
  try {
2572
3231
  // Note: Filter ONLY output parameters
2573
- for (_a = __values(pipeline.parameters), _b = _a.next(); !_b.done; _b = _a.next()) {
2574
- parameter = _b.value;
2575
- if (parameter.isOutput) {
3232
+ for (_c = __values(pipeline.parameters.filter(function (_a) {
3233
+ var isOutput = _a.isOutput;
3234
+ return isOutput;
3235
+ })), _d = _c.next(); !_d.done; _d = _c.next()) {
3236
+ parameter = _d.value;
3237
+ if (parametersToPass[parameter.name] === undefined) {
3238
+ errors.push(new PipelineExecutionError("Parameter {".concat(parameter.name, "} is required as an output parameter but not set in the pipeline")));
2576
3239
  continue;
2577
3240
  }
2578
- delete parametersToPass[parameter.name];
3241
+ outputParameters[parameter.name] = parametersToPass[parameter.name] || '';
2579
3242
  }
2580
3243
  }
2581
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
3244
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2582
3245
  finally {
2583
3246
  try {
2584
- if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
3247
+ if (_d && !_d.done && (_f = _c.return)) _f.call(_c);
2585
3248
  }
2586
- finally { if (e_1) throw e_1.error; }
3249
+ finally { if (e_2) throw e_2.error; }
2587
3250
  }
2588
3251
  usage = addUsage.apply(void 0, __spreadArray([], __read(executionReport.promptExecutions.map(function (_a) {
2589
3252
  var result = _a.result;
2590
- return (result === null || result === void 0 ? void 0 : result.usage) || addUsage();
3253
+ return (result === null || result === void 0 ? void 0 : result.usage) || ZERO_USAGE;
2591
3254
  })), false));
2592
- return [2 /*return*/, {
3255
+ return [2 /*return*/, deepFreezeWithSameType({
2593
3256
  isSuccessful: true,
2594
- errors: [],
3257
+ errors: errors,
2595
3258
  usage: usage,
2596
3259
  executionReport: executionReport,
2597
- outputParameters: parametersToPass,
2598
- }];
3260
+ outputParameters: outputParameters,
3261
+ })];
2599
3262
  }
2600
3263
  });
2601
3264
  }); };
2602
3265
  return pipelineExecutor;
2603
3266
  }
2604
3267
  /**
3268
+ * TODO: Use isVerbose here (not only pass to `preparePipeline`)
3269
+ * TODO: [🪂] Use maxParallelCount here (not only pass to `preparePipeline`)
3270
+ * TODO: [♈] Probbably move expectations from templates to parameters
2605
3271
  * TODO: [🧠] When not meet expectations in PROMPT_DIALOG, make some way to tell the user
2606
3272
  * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
2607
3273
  * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
2608
3274
  * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
3275
+ * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
2609
3276
  */
2610
3277
 
2611
- function prepareKnowledgeFromMarkdown(options) {
3278
+ /**
3279
+ * @@@
3280
+ */
3281
+ function prepareKnowledgeFromMarkdown(content /* <- TODO: [🖖] (?maybe not) Always the file */, options) {
2612
3282
  return __awaiter(this, void 0, void 0, function () {
2613
- var content, llmTools, _a, isVerbose, collection, prepareKnowledgeFromMarkdownExecutor, _b, prepareTitleExecutor, _c, prepareKeywordsExecutor, _d, result, outputParameters, knowledgeRaw, knowledgeTextPieces, knowledge;
2614
- var _e, _f, _g;
3283
+ var llmTools, _a, maxParallelCount, _b, isVerbose, collection, prepareKnowledgeFromMarkdownExecutor, _c, prepareTitleExecutor, _d, prepareKeywordsExecutor, _e, result, outputParameters, knowledgeRaw, knowledgeTextPieces, knowledge;
3284
+ var _f, _g, _h;
2615
3285
  var _this = this;
2616
- return __generator(this, function (_h) {
2617
- switch (_h.label) {
3286
+ return __generator(this, function (_j) {
3287
+ switch (_j.label) {
2618
3288
  case 0:
2619
- content = options.content, llmTools = options.llmTools, _a = options.isVerbose, isVerbose = _a === void 0 ? false : _a;
3289
+ llmTools = options.llmTools, _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a, _b = options.isVerbose, isVerbose = _b === void 0 ? false : _b;
3290
+ TODO_USE(maxParallelCount); // <- [🪂]
2620
3291
  collection = createCollectionFromJson.apply(void 0, __spreadArray([], __read(PipelineCollection), false));
2621
- _b = createPipelineExecutor;
2622
- _e = {};
2623
- return [4 /*yield*/, collection.getPipelineByUrl('https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md')];
2624
- case 1:
2625
- prepareKnowledgeFromMarkdownExecutor = _b.apply(void 0, [(_e.pipeline = _h.sent(),
2626
- _e.tools = {
2627
- llm: llmTools,
2628
- },
2629
- _e)]);
2630
3292
  _c = createPipelineExecutor;
2631
3293
  _f = {};
2632
- return [4 /*yield*/, collection.getPipelineByUrl('https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md')];
2633
- case 2:
2634
- prepareTitleExecutor = _c.apply(void 0, [(_f.pipeline = _h.sent(),
3294
+ return [4 /*yield*/, collection.getPipelineByUrl('https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md')];
3295
+ case 1:
3296
+ prepareKnowledgeFromMarkdownExecutor = _c.apply(void 0, [(_f.pipeline = _j.sent(),
2635
3297
  _f.tools = {
2636
3298
  llm: llmTools,
2637
3299
  },
2638
3300
  _f)]);
2639
3301
  _d = createPipelineExecutor;
2640
3302
  _g = {};
2641
- return [4 /*yield*/, collection.getPipelineByUrl('https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md')];
2642
- case 3:
2643
- prepareKeywordsExecutor = _d.apply(void 0, [(_g.pipeline = _h.sent(),
3303
+ return [4 /*yield*/, collection.getPipelineByUrl('https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md')];
3304
+ case 2:
3305
+ prepareTitleExecutor = _d.apply(void 0, [(_g.pipeline = _j.sent(),
2644
3306
  _g.tools = {
2645
3307
  llm: llmTools,
2646
3308
  },
2647
3309
  _g)]);
3310
+ _e = createPipelineExecutor;
3311
+ _h = {};
3312
+ return [4 /*yield*/, collection.getPipelineByUrl('https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md')];
3313
+ case 3:
3314
+ prepareKeywordsExecutor = _e.apply(void 0, [(_h.pipeline = _j.sent(),
3315
+ _h.tools = {
3316
+ llm: llmTools,
3317
+ },
3318
+ _h)]);
2648
3319
  return [4 /*yield*/, prepareKnowledgeFromMarkdownExecutor({ content: content })];
2649
3320
  case 4:
2650
- result = _h.sent();
2651
- // TODO: [0] !!! Aggeregate usage
3321
+ result = _j.sent();
2652
3322
  assertsExecutionSuccessful(result);
2653
3323
  outputParameters = result.outputParameters;
2654
3324
  knowledgeRaw = outputParameters.knowledge;
@@ -2657,9 +3327,9 @@ function prepareKnowledgeFromMarkdown(options) {
2657
3327
  console.info('knowledgeTextPieces:', knowledgeTextPieces);
2658
3328
  }
2659
3329
  return [4 /*yield*/, Promise.all(
2660
- // TODO: !!! Do not send all at once but in chunks
3330
+ // TODO: [🪂] !! Do not send all at once but in chunks
2661
3331
  knowledgeTextPieces.map(function (knowledgeTextPiece, i) { return __awaiter(_this, void 0, void 0, function () {
2662
- var name, title, content, keywords, index, sources, titleResult, _a, titleRaw, keywordsResult, _b, keywordsRaw, embeddingResult, error_1;
3332
+ var name, title, content, keywords, index, titleResult, _a, titleRaw, keywordsResult, _b, keywordsRaw, embeddingResult, error_1;
2663
3333
  return __generator(this, function (_c) {
2664
3334
  switch (_c.label) {
2665
3335
  case 0:
@@ -2668,12 +3338,6 @@ function prepareKnowledgeFromMarkdown(options) {
2668
3338
  content = spaceTrim(knowledgeTextPiece);
2669
3339
  keywords = [];
2670
3340
  index = [];
2671
- sources = [
2672
- {
2673
- title: 'Markdown document' /* <- TODO: !!! Unhardcode */,
2674
- href: '#' /* <- TODO: !!! Unhardcode */,
2675
- },
2676
- ];
2677
3341
  _c.label = 1;
2678
3342
  case 1:
2679
3343
  _c.trys.push([1, 7, , 8]);
@@ -2708,7 +3372,6 @@ function prepareKnowledgeFromMarkdown(options) {
2708
3372
  })];
2709
3373
  case 5:
2710
3374
  embeddingResult = _c.sent();
2711
- // TODO: [0] !!! Aggeregate usage embeddingResult.usage
2712
3375
  index.push({
2713
3376
  modelName: embeddingResult.modelName,
2714
3377
  position: embeddingResult.content,
@@ -2726,21 +3389,403 @@ function prepareKnowledgeFromMarkdown(options) {
2726
3389
  content: content,
2727
3390
  keywords: keywords,
2728
3391
  index: index,
2729
- sources: sources,
3392
+ // <- TODO: [☀] sources,
2730
3393
  }];
2731
3394
  }
2732
3395
  });
2733
3396
  }); }))];
2734
3397
  case 5:
2735
- knowledge = _h.sent();
3398
+ knowledge = _j.sent();
2736
3399
  return [2 /*return*/, knowledge];
2737
3400
  }
2738
3401
  });
2739
- });
2740
- }
3402
+ });
3403
+ }
3404
+ /**
3405
+ * TODO: [🐝][🔼] !!! Export via `@promptbook/markdown`
3406
+ * TODO: [🪂] Do it in parallel 11:11
3407
+ * Note: No need to aggregate usage here, it is done by intercepting the llmTools
3408
+ */
3409
+
3410
+ /**
3411
+ * Prepares the knowle
3412
+ *
3413
+ * @see https://github.com/webgptorg/promptbook/discussions/41
3414
+ */
3415
+ function prepareKnowledgePieces(knowledgeSources, options) {
3416
+ return __awaiter(this, void 0, void 0, function () {
3417
+ var _a, maxParallelCount, knowledgePrepared;
3418
+ var _this = this;
3419
+ return __generator(this, function (_b) {
3420
+ switch (_b.label) {
3421
+ case 0:
3422
+ _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a;
3423
+ knowledgePrepared = [];
3424
+ return [4 /*yield*/, forEachAsync(knowledgeSources, { maxParallelCount: maxParallelCount }, function (knowledgeSource) { return __awaiter(_this, void 0, void 0, function () {
3425
+ var partialPieces, pieces;
3426
+ return __generator(this, function (_a) {
3427
+ switch (_a.label) {
3428
+ case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.source, // <- TODO: [🐝] !!! Unhardcode markdown, detect which type it is
3429
+ options)];
3430
+ case 1:
3431
+ partialPieces = _a.sent();
3432
+ pieces = partialPieces.map(function (partialPiece) { return (__assign(__assign({}, partialPiece), { sources: [
3433
+ {
3434
+ name: knowledgeSource.name,
3435
+ // line, column <- TODO: [☀]
3436
+ // <- TODO: [❎]
3437
+ },
3438
+ ] })); });
3439
+ knowledgePrepared.push.apply(knowledgePrepared, __spreadArray([], __read(pieces), false));
3440
+ return [2 /*return*/];
3441
+ }
3442
+ });
3443
+ }); })];
3444
+ case 1:
3445
+ _b.sent();
3446
+ return [2 /*return*/, knowledgePrepared];
3447
+ }
3448
+ });
3449
+ });
3450
+ }
3451
+ /*
3452
+ TODO: [🧊] This is how it can look in future
3453
+ > type PrepareKnowledgeKnowledge = {
3454
+ > /**
3455
+ > * Unprepared knowledge
3456
+ > * /
3457
+ > readonly knowledgeSources: Array<KnowledgeSourceJson>;
3458
+ > };
3459
+ >
3460
+ > export async function prepareKnowledgePieces(
3461
+ > knowledge: PrepareKnowledgeKnowledge,
3462
+ > options: PrepareOptions,
3463
+ > ):
3464
+ */
3465
+ /**
3466
+ * TODO: [🐝][🔼] !!! Export via `@promptbook/core`
3467
+ * TODO: [🧊] In future one preparation can take data from previous preparation and save tokens and time
3468
+ * Put `knowledgePieces` into `PrepareKnowledgeOptions`
3469
+ * TODO: [🪂] More than max things can run in parallel by acident [1,[2a,2b,_],[3a,3b,_]]
3470
+ * TODO: [🧠][❎] Do here propper M:N mapping
3471
+ * [x] One source can make multiple pieces
3472
+ * [ ] One piece can have multiple sources
3473
+ */
3474
+
3475
+ /**
3476
+ * Prepares the persona for the pipeline
3477
+ *
3478
+ * @see https://github.com/webgptorg/promptbook/discussions/22
3479
+ */
3480
+ function preparePersona(personaDescription, options) {
3481
+ return __awaiter(this, void 0, void 0, function () {
3482
+ var llmTools, _a, isVerbose, collection, preparePersonaExecutor, _b, availableModels, availableModelNames, result, outputParameters, modelRequirementsRaw, modelRequirements, modelName, systemMessage, temperature;
3483
+ var _c;
3484
+ return __generator(this, function (_d) {
3485
+ switch (_d.label) {
3486
+ case 0:
3487
+ llmTools = options.llmTools, _a = options.isVerbose, isVerbose = _a === void 0 ? false : _a;
3488
+ collection = createCollectionFromJson.apply(void 0, __spreadArray([], __read(PipelineCollection), false));
3489
+ _b = createPipelineExecutor;
3490
+ _c = {};
3491
+ return [4 /*yield*/, collection.getPipelineByUrl('https://promptbook.studio/promptbook/prepare-persona.ptbk.md')];
3492
+ case 1:
3493
+ preparePersonaExecutor = _b.apply(void 0, [(_c.pipeline = _d.sent(),
3494
+ _c.tools = {
3495
+ llm: llmTools,
3496
+ },
3497
+ _c)]);
3498
+ return [4 /*yield*/, llmTools.listModels()];
3499
+ case 2:
3500
+ availableModels = _d.sent();
3501
+ availableModelNames = availableModels
3502
+ .filter(function (_a) {
3503
+ var modelVariant = _a.modelVariant;
3504
+ return modelVariant === 'CHAT';
3505
+ })
3506
+ .map(function (_a) {
3507
+ var modelName = _a.modelName;
3508
+ return modelName;
3509
+ })
3510
+ .join(',');
3511
+ return [4 /*yield*/, preparePersonaExecutor({ availableModelNames: availableModelNames, personaDescription: personaDescription })];
3512
+ case 3:
3513
+ result = _d.sent();
3514
+ assertsExecutionSuccessful(result);
3515
+ outputParameters = result.outputParameters;
3516
+ modelRequirementsRaw = outputParameters.modelRequirements;
3517
+ modelRequirements = JSON.parse(modelRequirementsRaw);
3518
+ if (isVerbose) {
3519
+ console.info("PERSONA ".concat(personaDescription), modelRequirements);
3520
+ }
3521
+ modelName = modelRequirements.modelName, systemMessage = modelRequirements.systemMessage, temperature = modelRequirements.temperature;
3522
+ return [2 /*return*/, {
3523
+ modelVariant: 'CHAT',
3524
+ modelName: modelName,
3525
+ systemMessage: systemMessage,
3526
+ temperature: temperature,
3527
+ }];
3528
+ }
3529
+ });
3530
+ });
3531
+ }
3532
+ /**
3533
+ * TODO: [🔼] !!! Export via `@promptbook/core`
3534
+ * TODO: [🏢] !! Check validity of `modelName` in pipeline
3535
+ * TODO: [🏢] !! Check validity of `systemMessage` in pipeline
3536
+ * TODO: [🏢] !! Check validity of `temperature` in pipeline
3537
+ */
3538
+
3539
+ /**
3540
+ * Prepare pipeline from string (markdown) format to JSON format
3541
+ *
3542
+ * Note: This function does not validate logic of the pipeline
3543
+ * Note: This function acts as part of compilation process
3544
+ */
3545
+ function preparePipeline(pipeline, options) {
3546
+ return __awaiter(this, void 0, void 0, function () {
3547
+ var _a, maxParallelCount,
3548
+ /*
3549
+ <- TODO: [🧠][0] `promptbookVersion` */
3550
+ knowledgeSources /*
3551
+ <- TODO: [🧊] `knowledgePieces` */, personas /*
3552
+ <- TODO: [🧊] `preparations` */, currentPreparation, preparations, preparedPersonas, knowledgeSourcesPrepared, partialknowledgePiecesPrepared, knowledgePiecesPrepared;
3553
+ var _this = this;
3554
+ return __generator(this, function (_b) {
3555
+ switch (_b.label) {
3556
+ case 0:
3557
+ _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a;
3558
+ knowledgeSources = pipeline.knowledgeSources, personas = pipeline.personas;
3559
+ currentPreparation = {
3560
+ id: 1,
3561
+ // TODO: [🍥]> date: $currentDate(),
3562
+ promptbookVersion: PROMPTBOOK_VERSION,
3563
+ modelUsage: ZERO_USAGE,
3564
+ };
3565
+ preparations = [
3566
+ // ...preparations
3567
+ // <- TODO: [🧊]
3568
+ currentPreparation,
3569
+ ];
3570
+ preparedPersonas = new Array(personas.length);
3571
+ return [4 /*yield*/, forEachAsync(personas, { maxParallelCount: maxParallelCount /* <- TODO: [🪂] When there are subtasks, this maximul limit can be broken */ }, function (persona, index) { return __awaiter(_this, void 0, void 0, function () {
3572
+ var modelRequirements, preparedPersona;
3573
+ return __generator(this, function (_a) {
3574
+ switch (_a.label) {
3575
+ case 0: return [4 /*yield*/, preparePersona(persona.description, options)];
3576
+ case 1:
3577
+ modelRequirements = _a.sent();
3578
+ preparedPersona = __assign(__assign({}, persona), { modelRequirements: modelRequirements, preparationIds: [/* TODO: [🧊] -> */ currentPreparation.id] });
3579
+ preparedPersonas[index] = preparedPersona;
3580
+ return [2 /*return*/];
3581
+ }
3582
+ });
3583
+ }); })];
3584
+ case 1:
3585
+ _b.sent();
3586
+ knowledgeSourcesPrepared = knowledgeSources.map(function (source) { return (__assign(__assign({}, source), { preparationIds: [/* TODO: [🧊] -> */ currentPreparation.id] })); });
3587
+ return [4 /*yield*/, prepareKnowledgePieces(knowledgeSources /* <- TODO: [🧊] {knowledgeSources, knowledgePieces} */, options)];
3588
+ case 2:
3589
+ partialknowledgePiecesPrepared = _b.sent();
3590
+ knowledgePiecesPrepared = partialknowledgePiecesPrepared.map(function (piece) { return (__assign(__assign({}, piece), { preparationIds: [/* TODO: [🧊] -> */ currentPreparation.id] })); });
3591
+ // ----- /Knowledge preparation -----
3592
+ // TODO: !!!!! Add context to each template (if missing)
3593
+ // TODO: !!!!! Apply samples to each template (if missing)
3594
+ return [2 /*return*/, __assign(__assign({}, pipeline), { knowledgeSources: knowledgeSourcesPrepared, knowledgePieces: knowledgePiecesPrepared, personas: preparedPersonas, preparations: preparations })];
3595
+ }
3596
+ });
3597
+ });
3598
+ }
3599
+ /**
3600
+ * TODO: !!!!! Index the samples and maybe templates
3601
+ * TODO: [🔼] !!! Export via `@promptbook/core`
3602
+ * TODO: Write tests for `preparePipeline`
3603
+ * TODO: [🏏] Leverage the batch API and build queues @see https://platform.openai.com/docs/guides/batch
3604
+ * TODO: [🧊] In future one preparation can take data from previous preparation and save tokens and time
3605
+ * TODO: [🎐] !!!! Use here countTotalUsage
3606
+ * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
3607
+ */
3608
+
3609
+ /**
3610
+ * Tests if given string is valid URL.
3611
+ *
3612
+ * Note: This does not check if the file exists only if the path is valid
3613
+ */
3614
+ function isValidFilePath(filePath) {
3615
+ if (typeof filePath !== 'string') {
3616
+ return false;
3617
+ }
3618
+ var filePathSlashes = filePath.split('\\').join('/');
3619
+ // Absolute Unix path: /hello.txt
3620
+ if (/^(\/)/i.test(filePathSlashes)) {
3621
+ return true;
3622
+ }
3623
+ // Absolute Windows path: /hello.txt
3624
+ if (/^([A-Z]{1,2}:\/?)\//i.test(filePathSlashes)) {
3625
+ return true;
3626
+ }
3627
+ // Relative path: ./hello.txt
3628
+ if (/^(\.\.?\/)+/i.test(filePathSlashes)) {
3629
+ return true;
3630
+ }
3631
+ return false;
3632
+ }
3633
+
3634
+ /**
3635
+ * Parses the knowledge command
3636
+ *
3637
+ * @see ./KNOWLEDGE-README.md for more details
3638
+ * @private within the commands folder
3639
+ */
3640
+ var knowledgeCommandParser = {
3641
+ /**
3642
+ * Name of the command
3643
+ */
3644
+ name: 'KNOWLEDGE',
3645
+ /**
3646
+ * BOILERPLATE command can be used in:
3647
+ */
3648
+ usagePlaces: ['PIPELINE_HEAD'],
3649
+ /**
3650
+ * Description of the KNOWLEDGE command
3651
+ */
3652
+ description: "Tells promptbook which external knowledge to use",
3653
+ /**
3654
+ * Link to discussion
3655
+ */
3656
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/41',
3657
+ /**
3658
+ * Example usages of the KNOWLEDGE command
3659
+ */
3660
+ examples: [
3661
+ 'KNOWLEDGE https://www.pavolhejny.com/',
3662
+ 'KNOWLEDGE ./hejny-cv.txt',
3663
+ 'KNOWLEDGE ./hejny-cv.md',
3664
+ 'KNOWLEDGE ./hejny-cv.pdf',
3665
+ 'KNOWLEDGE ./hejny-cv.docx',
3666
+ ],
3667
+ /**
3668
+ * Parses the KNOWLEDGE command
3669
+ */
3670
+ parse: function (input) {
3671
+ var args = input.args;
3672
+ var source = args[0];
3673
+ if (source === undefined) {
3674
+ throw new ParsingError("Source is not defined");
3675
+ }
3676
+ if (source.startsWith('http://')) {
3677
+ throw new ParsingError("Source is not secure");
3678
+ }
3679
+ if (!(isValidFilePath(source) || isValidUrl(source))) {
3680
+ throw new ParsingError("Source not valid");
3681
+ }
3682
+ if (source.startsWith('../') || source.startsWith('/') || /^[A-Z]:[\\/]+/i.test(source)) {
3683
+ throw new ParsingError("Source cannot be outside of the .ptbk.md folder");
3684
+ }
3685
+ return {
3686
+ type: 'KNOWLEDGE',
3687
+ source: source,
3688
+ };
3689
+ },
3690
+ /**
3691
+ * Note: Prototype of [🍧] (remove this comment after full implementation)
3692
+ */
3693
+ applyToPipelineJson: function (personaCommand, subjects) {
3694
+ var source = personaCommand.source;
3695
+ var pipelineJson = subjects.pipelineJson;
3696
+ var name = titleToName(source);
3697
+ pipelineJson.knowledgeSources.push({
3698
+ name: name,
3699
+ source: source,
3700
+ });
3701
+ },
3702
+ };
3703
+
2741
3704
  /**
2742
- * 11:11
3705
+ * Parses the persona command
3706
+ *
3707
+ * @see ./PERSONA-README.md for more details
3708
+ * @private within the commands folder
2743
3709
  */
3710
+ var personaCommandParser = {
3711
+ /**
3712
+ * Name of the command
3713
+ */
3714
+ name: 'PERSONA',
3715
+ /**
3716
+ * Aliases for the PERSONA command
3717
+ */
3718
+ aliasNames: ['PERSON'],
3719
+ /**
3720
+ * PERSONA command can be used in:
3721
+ */
3722
+ usagePlaces: ['PIPELINE_HEAD', 'PIPELINE_TEMPLATE'],
3723
+ /**
3724
+ * Description of the PERSONA command
3725
+ */
3726
+ description: "Persona command is used to specify who the system is, it will be transformed into system message, top_t,...",
3727
+ /**
3728
+ * Link to discussion
3729
+ */
3730
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/22',
3731
+ /**
3732
+ * Example usages of the PERSONA command
3733
+ */
3734
+ examples: ['PERSONA Jane, skilled copywriter', 'PERSONA Joe, male 28 years old, programmer'],
3735
+ /**
3736
+ * Parses the PERSONA command
3737
+ */
3738
+ parse: function (input) {
3739
+ var rawArgs = input.rawArgs;
3740
+ var _a = __read(rawArgs.split(/[,;:]/, 2), 2), personaNameRaw = _a[0], personaDescriptionRaw = _a[1];
3741
+ var personaName = (personaNameRaw || '').trim();
3742
+ if (personaName === '') {
3743
+ throw new ParsingError("You must set name for the persona");
3744
+ }
3745
+ var personaDescription = (personaDescriptionRaw || '').trim();
3746
+ if (personaDescription === '') {
3747
+ personaDescription = null;
3748
+ }
3749
+ return {
3750
+ type: 'PERSONA',
3751
+ personaName: personaName,
3752
+ personaDescription: personaDescription,
3753
+ };
3754
+ },
3755
+ /**
3756
+ * Note: Prototype of [🍧] (remove this comment after full implementation)
3757
+ */
3758
+ applyToPipelineJson: function (personaCommand, subjects) {
3759
+ var personaName = personaCommand.personaName, personaDescription = personaCommand.personaDescription;
3760
+ var pipelineJson = subjects.pipelineJson, templateJson = subjects.templateJson;
3761
+ if (templateJson !== null) {
3762
+ if (templateJson.blockType !== 'PROMPT_TEMPLATE') {
3763
+ throw new ParsingError("PERSONA command can be used only in PROMPT_TEMPLATE block");
3764
+ }
3765
+ templateJson.personaName = personaName;
3766
+ }
3767
+ var persona = pipelineJson.personas.find(function (persona) { return persona.name === personaName; });
3768
+ if (persona === undefined) {
3769
+ pipelineJson.personas.push({
3770
+ name: personaName,
3771
+ description: personaDescription || '',
3772
+ });
3773
+ return;
3774
+ }
3775
+ if (persona.description === personaDescription) {
3776
+ return;
3777
+ }
3778
+ if (personaDescription === null) {
3779
+ return;
3780
+ }
3781
+ if (persona.description === '') {
3782
+ persona.description = personaDescription;
3783
+ return;
3784
+ }
3785
+ console.warn(spaceTrim("\n\n Persona \"".concat(personaName, "\" is defined multiple times with different description:\n\n First definition:\n ").concat(persona.description, "\n\n Second definition:\n ").concat(personaDescription, "\n\n ")));
3786
+ persona.description += spaceTrim('\n\n' + personaDescription);
3787
+ },
3788
+ };
2744
3789
 
2745
3790
  /**
2746
3791
  * Removes Markdown formatting tags from a string.
@@ -2860,7 +3905,7 @@ var blockCommandParser = {
2860
3905
  /**
2861
3906
  * Link to discussion
2862
3907
  */
2863
- discussionUrl: 'https://github.com/webgptorg/promptbook/discussions/64',
3908
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/64',
2864
3909
  /**
2865
3910
  * Example usages of the BLOCK command
2866
3911
  */
@@ -2880,7 +3925,7 @@ var blockCommandParser = {
2880
3925
  'Knowledge BLOCK',
2881
3926
  // 'Knowledge', // <- Note: [⛱] For execution blocks which are also separate commands shortcut does not work
2882
3927
  //---
2883
- /* TODO: !!!! Not implemented block types will be in examples in future -> */
3928
+ /* Note: Not implemented block types will be in examples in future -> */
2884
3929
  'Instrument BLOCK',
2885
3930
  // 'Instrument', // <- Note: [⛱]
2886
3931
  'Action BLOCK',
@@ -2888,6 +3933,7 @@ var blockCommandParser = {
2888
3933
  //---
2889
3934
  /* <- TODO: [🧠] Maybe dynamic */
2890
3935
  ],
3936
+ // TODO: [♓️] order: -10 /* <- Note: Putting before other commands */
2891
3937
  /**
2892
3938
  * Parses the BLOCK command
2893
3939
  */
@@ -2896,19 +3942,19 @@ var blockCommandParser = {
2896
3942
  normalized = normalized.split('EXAMPLE').join('SAMPLE');
2897
3943
  var blockTypes = BlockTypes.filter(function (blockType) { return normalized.includes(blockType); });
2898
3944
  if (blockTypes.length !== 1) {
2899
- // console.log('!!!', { blockType });
2900
3945
  throw new ParsingError(spaceTrim(function (block) { return "\n Unknown block type in BLOCK command\n\n Supported block types are:\n ".concat(block(BlockTypes.join(', ')), "\n "); }));
2901
3946
  }
2902
- // TODO: !!!! Not supported yet
3947
+ var blockType = blockTypes[0];
2903
3948
  return {
2904
3949
  type: 'BLOCK',
2905
- blockType: blockTypes[0],
3950
+ blockType: blockType,
2906
3951
  };
2907
3952
  },
2908
3953
  };
2909
3954
 
2910
3955
  /**
2911
3956
  * Units of text measurement
3957
+ * @see https://github.com/webgptorg/promptbook/discussions/30
2912
3958
  */
2913
3959
  var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'LINES', 'PARAGRAPHS', 'PAGES'];
2914
3960
  /**
@@ -3004,7 +4050,7 @@ var expectCommandParser = {
3004
4050
  /**
3005
4051
  * Link to discussion
3006
4052
  */
3007
- discussionUrl: 'https://github.com/webgptorg/promptbook/discussions/30',
4053
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/30',
3008
4054
  /**
3009
4055
  * Example usages of the EXPECT command
3010
4056
  */
@@ -3122,7 +4168,7 @@ var jokerCommandParser = {
3122
4168
  /**
3123
4169
  * Link to discussion
3124
4170
  */
3125
- discussionUrl: 'https://github.com/webgptorg/promptbook/discussions/66',
4171
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/66',
3126
4172
  /**
3127
4173
  * Example usages of the JOKER command
3128
4174
  */
@@ -3145,94 +4191,11 @@ var jokerCommandParser = {
3145
4191
  };
3146
4192
 
3147
4193
  /**
3148
- * Tests if given string is valid URL.
3149
- *
3150
- * Note: This does not check if the file exists only if the path is valid
3151
- */
3152
- function isValidFilePath(filePath) {
3153
- if (typeof filePath !== 'string') {
3154
- return false;
3155
- }
3156
- var filePathSlashes = filePath.split('\\').join('/');
3157
- // Absolute Unix path: /hello.txt
3158
- if (/^(\/)/i.test(filePathSlashes)) {
3159
- return true;
3160
- }
3161
- // Absolute Windows path: /hello.txt
3162
- if (/^([A-Z]{1,2}:\/?)\//i.test(filePathSlashes)) {
3163
- return true;
3164
- }
3165
- // Relative path: ./hello.txt
3166
- if (/^(\.\.?\/)+/i.test(filePathSlashes)) {
3167
- return true;
3168
- }
3169
- return false;
3170
- }
3171
-
3172
- /**
3173
- * Parses the knowledge command
4194
+ * @@@
3174
4195
  *
3175
- * @see ./KNOWLEDGE-README.md for more details
3176
- * @private within the commands folder
4196
+ * @private for `ModelVariant` and `modelCommandParser`
3177
4197
  */
3178
- var knowledgeCommandParser = {
3179
- /**
3180
- * Name of the command
3181
- */
3182
- name: 'KNOWLEDGE',
3183
- /**
3184
- * BOILERPLATE command can be used in:
3185
- */
3186
- usagePlaces: ['PIPELINE_HEAD'],
3187
- /**
3188
- * Description of the KNOWLEDGE command
3189
- */
3190
- description: "Tells promptbook which external knowledge to use",
3191
- /**
3192
- * Link to discussion
3193
- */
3194
- discussionUrl: 'https://github.com/webgptorg/promptbook/discussions/41',
3195
- /**
3196
- * Example usages of the KNOWLEDGE command
3197
- */
3198
- examples: [
3199
- 'KNOWLEDGE https://www.pavolhejny.com/',
3200
- 'KNOWLEDGE ./hejny-cv.txt',
3201
- 'KNOWLEDGE ./hejny-cv.md',
3202
- 'KNOWLEDGE ./hejny-cv.pdf',
3203
- 'KNOWLEDGE ./hejny-cv.docx',
3204
- ],
3205
- /**
3206
- * Parses the KNOWLEDGE command
3207
- */
3208
- parse: function (input) {
3209
- var args = input.args;
3210
- var source = args[0];
3211
- if (source === undefined) {
3212
- throw new ParsingError("Source is not defined");
3213
- }
3214
- if (source.startsWith('http://')) {
3215
- throw new ParsingError("Source is not secure");
3216
- }
3217
- if (!(isValidFilePath(source) || isValidUrl(source))) {
3218
- throw new ParsingError("Source not valid");
3219
- }
3220
- if (source.startsWith('../') || source.startsWith('/') || /^[A-Z]:[\\/]+/i.test(source)) {
3221
- throw new ParsingError("Source cannot be outside of the .ptbk.md folder");
3222
- }
3223
- return {
3224
- type: 'KNOWLEDGE',
3225
- source: source,
3226
- };
3227
- },
3228
- };
3229
-
3230
4198
  var MODEL_VARIANTS = ['COMPLETION', 'CHAT', 'EMBEDDING' /* <- TODO [🏳] */ /* <- [🤖] */];
3231
- /**
3232
- * TODO: Maybe figure out better word than "variant"
3233
- * TODO: Add here more requirement options like max context size, max tokens, etc.
3234
- * TODO: [👙][🧠] Just selecting gpt3 or gpt4 level of model
3235
- */
3236
4199
 
3237
4200
  /**
3238
4201
  * Parses the model command
@@ -3248,7 +4211,11 @@ var modelCommandParser = {
3248
4211
  /**
3249
4212
  * BOILERPLATE command can be used in:
3250
4213
  */
3251
- usagePlaces: ['PIPELINE_HEAD', 'PIPELINE_TEMPLATE'],
4214
+ usagePlaces: [
4215
+ 'PIPELINE_HEAD',
4216
+ // <- TODO: [🧠][❔] Should there be possibility to set MODEL for entire pipeline?
4217
+ 'PIPELINE_TEMPLATE',
4218
+ ],
3252
4219
  /**
3253
4220
  * Description of the MODEL command
3254
4221
  */
@@ -3256,7 +4223,7 @@ var modelCommandParser = {
3256
4223
  /**
3257
4224
  * Link to discussion
3258
4225
  */
3259
- discussionUrl: 'https://github.com/webgptorg/promptbook/discussions/67',
4226
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/67',
3260
4227
  /**
3261
4228
  * Example usages of the MODEL command
3262
4229
  */
@@ -3336,7 +4303,7 @@ var parameterCommandParser = {
3336
4303
  /**
3337
4304
  * Link to discussion
3338
4305
  */
3339
- discussionUrl: 'https://github.com/webgptorg/promptbook/discussions/68',
4306
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/68',
3340
4307
  /**
3341
4308
  * Example usages of the PARAMETER command
3342
4309
  */
@@ -3370,59 +4337,6 @@ var parameterCommandParser = {
3370
4337
  },
3371
4338
  };
3372
4339
 
3373
- /**
3374
- * Parses the persona command
3375
- *
3376
- * @see ./PERSONA-README.md for more details
3377
- * @private within the commands folder
3378
- */
3379
- var personaCommandParser = {
3380
- /**
3381
- * Name of the command
3382
- */
3383
- name: 'PERSONA',
3384
- /**
3385
- * Aliases for the PERSONA command
3386
- */
3387
- aliasNames: ['PERSON'],
3388
- /**
3389
- * PERSONA command can be used in:
3390
- */
3391
- usagePlaces: ['PIPELINE_HEAD', 'PIPELINE_TEMPLATE'],
3392
- /**
3393
- * Description of the PERSONA command
3394
- */
3395
- description: "Persona command is used to specify who the system is, it will be transformed into system message, top_t,...",
3396
- /**
3397
- * Link to discussion
3398
- */
3399
- discussionUrl: 'https://github.com/webgptorg/promptbook/discussions/22',
3400
- /**
3401
- * Example usages of the PERSONA command
3402
- */
3403
- examples: ['PERSONA Jane, skilled copywriter', 'PERSONA Joe, male 28 years old, programmer'],
3404
- /**
3405
- * Parses the PERSONA command
3406
- */
3407
- parse: function (input) {
3408
- var rawArgs = input.rawArgs;
3409
- var _a = __read(rawArgs.split(/[,;:]/, 2), 2), personaNameRaw = _a[0], personaDescriptionRaw = _a[1];
3410
- var personaName = (personaNameRaw || '').trim();
3411
- if (personaName === '') {
3412
- throw new ParsingError("You must set name for the persona");
3413
- }
3414
- var personaDescription = (personaDescriptionRaw || '').trim();
3415
- if (personaDescription === '') {
3416
- personaDescription = null;
3417
- }
3418
- return {
3419
- type: 'PERSONA',
3420
- personaName: personaName,
3421
- personaDescription: personaDescription,
3422
- };
3423
- },
3424
- };
3425
-
3426
4340
  function isValidJavascriptName(javascriptName) {
3427
4341
  if (typeof javascriptName !== 'string') {
3428
4342
  return false;
@@ -3453,7 +4367,7 @@ var postprocessCommandParser = {
3453
4367
  /**
3454
4368
  * Link to discussion
3455
4369
  */
3456
- discussionUrl: 'https://github.com/webgptorg/promptbook/discussions/31',
4370
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/31',
3457
4371
  /**
3458
4372
  * Example usages of the POSTPROCESS command
3459
4373
  */
@@ -3508,7 +4422,7 @@ var promptbookVersionCommandParser = {
3508
4422
  /**
3509
4423
  * Link to discussion
3510
4424
  */
3511
- discussionUrl: 'https://github.com/webgptorg/promptbook/discussions/69',
4425
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/69',
3512
4426
  /**
3513
4427
  * Example usages of the PROMPTBOOK_VERSION command
3514
4428
  */
@@ -3561,7 +4475,7 @@ var urlCommandParser = {
3561
4475
  /**
3562
4476
  * Link to discussion
3563
4477
  */
3564
- discussionUrl: 'https://github.com/webgptorg/promptbook/discussions/70',
4478
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/70',
3565
4479
  /**
3566
4480
  * Example usages of the URL command
3567
4481
  */
@@ -3609,22 +4523,6 @@ var urlCommandParser = {
3609
4523
  },
3610
4524
  };
3611
4525
 
3612
- /**
3613
- * Returns the same value that is passed as argument.
3614
- * No side effects.
3615
- *
3616
- * Note: It can be usefull for leveling indentation
3617
- *
3618
- * @param value any values
3619
- * @returns the same values
3620
- */
3621
- function just(value) {
3622
- if (value === undefined) {
3623
- return undefined;
3624
- }
3625
- return value;
3626
- }
3627
-
3628
4526
  /**
3629
4527
  * Parses the action command
3630
4528
  *
@@ -3647,7 +4545,7 @@ var actionCommandParser = {
3647
4545
  /**
3648
4546
  * Link to discussion
3649
4547
  */
3650
- discussionUrl: 'https://github.com/webgptorg/promptbook/discussions/72',
4548
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/72',
3651
4549
  /**
3652
4550
  * Example usages of the ACTION command
3653
4551
  */
@@ -3656,7 +4554,8 @@ var actionCommandParser = {
3656
4554
  * Parses the ACTION command
3657
4555
  */
3658
4556
  parse: function (input) {
3659
- input.args;
4557
+ var args = input.args;
4558
+ TODO_USE(args);
3660
4559
  return {
3661
4560
  type: 'ACTION',
3662
4561
  };
@@ -3685,7 +4584,7 @@ var instrumentCommandParser = {
3685
4584
  /**
3686
4585
  * Link to discussion
3687
4586
  */
3688
- discussionUrl: 'https://github.com/webgptorg/promptbook/discussions/71',
4587
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/71',
3689
4588
  /**
3690
4589
  * Example usages of the INSTRUMENT command
3691
4590
  */
@@ -3694,7 +4593,8 @@ var instrumentCommandParser = {
3694
4593
  * Parses the INSTRUMENT command
3695
4594
  */
3696
4595
  parse: function (input) {
3697
- input.args;
4596
+ var args = input.args;
4597
+ TODO_USE(args);
3698
4598
  return {
3699
4599
  type: 'INSTRUMENT',
3700
4600
  };
@@ -3727,7 +4627,7 @@ var boilerplateCommandParser = {
3727
4627
  /**
3728
4628
  * Link to discussion
3729
4629
  */
3730
- discussionUrl: 'https://github.com/webgptorg/promptbook/discussions/@@',
4630
+ documentationUrl: 'https://github.com/webgptorg/promptbook/discussions/@@',
3731
4631
  /**
3732
4632
  * Example usages of the BOILERPLATE command
3733
4633
  */
@@ -3752,6 +4652,7 @@ var boilerplateCommandParser = {
3752
4652
  };
3753
4653
  /**
3754
4654
  * TODO: [💐] Implement BOILERPLATE command into `pipelineStringToJsonSync` function
4655
+ * Note: [⚪] This should never be in any released package
3755
4656
  */
3756
4657
 
3757
4658
  /**
@@ -3770,7 +4671,7 @@ var COMMANDS = [
3770
4671
  actionCommandParser,
3771
4672
  instrumentCommandParser,
3772
4673
  personaCommandParser,
3773
- boilerplateCommandParser, // <- TODO: !!!! Only in development, remove in production
4674
+ boilerplateCommandParser, // <- TODO: !! Only in development, remove in production
3774
4675
  ];
3775
4676
 
3776
4677
  /**
@@ -3856,18 +4757,18 @@ function parseCommand(raw, usagePlace) {
3856
4757
  }));
3857
4758
  }
3858
4759
  /**
3859
- * !!!
4760
+ * @@@
3860
4761
  */
3861
4762
  function getSupportedCommandsMessage() {
3862
4763
  return COMMANDS.flatMap(function (_a) {
3863
- var name = _a.name, aliasNames = _a.aliasNames, description = _a.description, discussionUrl = _a.discussionUrl;
4764
+ var name = _a.name, aliasNames = _a.aliasNames, description = _a.description, documentationUrl = _a.documentationUrl;
3864
4765
  return __spreadArray([
3865
- "- **".concat(name, "** ").concat(description, ", see [discussion](").concat(discussionUrl, ")")
4766
+ "- **".concat(name, "** ").concat(description, ", see [discussion](").concat(documentationUrl, ")")
3866
4767
  ], __read((aliasNames || []).map(function (aliasName) { return " - **".concat(aliasName, "** Alias for **").concat(name, "**"); })), false);
3867
4768
  }).join('\n');
3868
4769
  }
3869
4770
  /**
3870
- * !!!
4771
+ * @@@
3871
4772
  */
3872
4773
  function parseCommandVariant(input) {
3873
4774
  var e_1, _a;
@@ -3876,7 +4777,6 @@ function parseCommandVariant(input) {
3876
4777
  var _loop_1 = function (commandParser) {
3877
4778
  var name_1 = commandParser.name, aliasNames = commandParser.aliasNames, deprecatedNames = commandParser.deprecatedNames, parse = commandParser.parse;
3878
4779
  var names = __spreadArray(__spreadArray([name_1], __read((aliasNames || [])), false), __read((deprecatedNames || [])), false);
3879
- // console.log('!!!', { commandName, names });
3880
4780
  if (names.includes(commandName)) {
3881
4781
  try {
3882
4782
  return { value: parse({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args }) };
@@ -3986,25 +4886,42 @@ function extractAllBlocksFromMarkdown(markdown) {
3986
4886
  var e_1, _a;
3987
4887
  var codeBlocks = [];
3988
4888
  var lines = markdown.split('\n');
4889
+ // Note: [0] Ensure that the last block notated by gt > will be closed
4890
+ lines.push('');
3989
4891
  var currentCodeBlock = null;
3990
4892
  try {
3991
4893
  for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
3992
4894
  var line = lines_1_1.value;
4895
+ if (line.startsWith('> ') || line === '>') {
4896
+ if (currentCodeBlock === null) {
4897
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
4898
+ } /* not else */
4899
+ if (currentCodeBlock.blockNotation === '>') {
4900
+ if (currentCodeBlock.content !== '') {
4901
+ currentCodeBlock.content += '\n';
4902
+ }
4903
+ currentCodeBlock.content += line.slice(2);
4904
+ }
4905
+ }
4906
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
4907
+ codeBlocks.push(currentCodeBlock);
4908
+ currentCodeBlock = null;
4909
+ }
4910
+ /* not else */
3993
4911
  if (line.startsWith('```')) {
3994
4912
  var language = line.slice(3).trim() || null;
3995
4913
  if (currentCodeBlock === null) {
3996
- currentCodeBlock = { language: language, content: '' };
4914
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
3997
4915
  }
3998
4916
  else {
3999
4917
  if (language !== null) {
4000
- // [🌻]
4001
- throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
4918
+ throw new ParsingError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
4002
4919
  }
4003
4920
  codeBlocks.push(currentCodeBlock);
4004
4921
  currentCodeBlock = null;
4005
4922
  }
4006
4923
  }
4007
- else if (currentCodeBlock !== null) {
4924
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
4008
4925
  if (currentCodeBlock.content !== '') {
4009
4926
  currentCodeBlock.content += '\n';
4010
4927
  }
@@ -4020,11 +4937,13 @@ function extractAllBlocksFromMarkdown(markdown) {
4020
4937
  finally { if (e_1) throw e_1.error; }
4021
4938
  }
4022
4939
  if (currentCodeBlock !== null) {
4023
- // [🌻]
4024
- throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
4940
+ throw new ParsingError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
4025
4941
  }
4026
4942
  return codeBlocks;
4027
4943
  }
4944
+ /**
4945
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
4946
+ */
4028
4947
 
4029
4948
  /**
4030
4949
  * Extracts exactly ONE code block from markdown.
@@ -4042,13 +4961,12 @@ function extractAllBlocksFromMarkdown(markdown) {
4042
4961
  function extractOneBlockFromMarkdown(markdown) {
4043
4962
  var codeBlocks = extractAllBlocksFromMarkdown(markdown);
4044
4963
  if (codeBlocks.length !== 1) {
4045
- // TODO: Report more specific place where the error happened
4046
- throw new Error(/* <- [🌻] */ 'There should be exactly one code block in the markdown');
4964
+ throw new ParsingError(spaceTrim(function (block) { return "\n There should be exactly 1 code block, found ".concat(codeBlocks.length, " code blocks\n\n ").concat(block(codeBlocks.map(function (block, i) { return "Block ".concat(i + 1, ":\n").concat(block.content); }).join('\n\n\n')), "\n "); }));
4047
4965
  }
4048
4966
  return codeBlocks[0];
4049
4967
  }
4050
4968
  /***
4051
- * TODO: [🍓][🌻] !!! Decide of this is internal util, external util OR validator/postprocessor
4969
+ * TODO: [🍓][🌻] Decide of this is internal util, external util OR validator/postprocessor
4052
4970
  */
4053
4971
 
4054
4972
  /**
@@ -4058,13 +4976,13 @@ function parseMarkdownSection(value) {
4058
4976
  var _a, _b;
4059
4977
  var lines = value.split('\n');
4060
4978
  if (!lines[0].startsWith('#')) {
4061
- throw new Error('Markdown section must start with heading');
4979
+ throw new ParsingError('Markdown section must start with heading');
4062
4980
  }
4063
4981
  var title = lines[0].replace(/^#+\s*/, '');
4064
4982
  var level = (_b = (_a = lines[0].match(/^#+/)) === null || _a === void 0 ? void 0 : _a[0].length) !== null && _b !== void 0 ? _b : 0;
4065
4983
  var content = spaceTrim(lines.slice(1).join('\n'));
4066
4984
  if (level < 1 || level > 6) {
4067
- throw new Error('Markdown section must have heading level between 1 and 6');
4985
+ throw new ParsingError('Markdown section must have heading level between 1 and 6');
4068
4986
  }
4069
4987
  return { title: title, level: level, content: content };
4070
4988
  }
@@ -4201,203 +5119,14 @@ function removeContentComments(content) {
4201
5119
  }
4202
5120
 
4203
5121
  /**
4204
- * Create difference set of two sets.
4205
- *
4206
- * @deprecated use new javascript set methods instead @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
4207
- */
4208
- function difference(a, b, isEqual) {
4209
- var e_1, _a;
4210
- if (isEqual === void 0) { isEqual = function (a, b) { return a === b; }; }
4211
- var diff = new Set();
4212
- var _loop_1 = function (itemA) {
4213
- if (!Array.from(b).some(function (itemB) { return isEqual(itemA, itemB); })) {
4214
- diff.add(itemA);
4215
- }
4216
- };
4217
- try {
4218
- for (var _b = __values(Array.from(a)), _c = _b.next(); !_c.done; _c = _b.next()) {
4219
- var itemA = _c.value;
4220
- _loop_1(itemA);
4221
- }
4222
- }
4223
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
4224
- finally {
4225
- try {
4226
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
4227
- }
4228
- finally { if (e_1) throw e_1.error; }
4229
- }
4230
- return diff;
4231
- }
4232
-
4233
- /**
4234
- * Creates a new set with all elements that are present in either set
4235
- *
4236
- * @deprecated use new javascript set methods instead @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
4237
- */
4238
- function union() {
4239
- var e_1, _a, e_2, _b;
4240
- var sets = [];
4241
- for (var _i = 0; _i < arguments.length; _i++) {
4242
- sets[_i] = arguments[_i];
4243
- }
4244
- var union = new Set();
4245
- try {
4246
- for (var sets_1 = __values(sets), sets_1_1 = sets_1.next(); !sets_1_1.done; sets_1_1 = sets_1.next()) {
4247
- var set = sets_1_1.value;
4248
- try {
4249
- for (var _c = (e_2 = void 0, __values(Array.from(set))), _d = _c.next(); !_d.done; _d = _c.next()) {
4250
- var item = _d.value;
4251
- union.add(item);
4252
- }
4253
- }
4254
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
4255
- finally {
4256
- try {
4257
- if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
4258
- }
4259
- finally { if (e_2) throw e_2.error; }
4260
- }
4261
- }
4262
- }
4263
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
4264
- finally {
4265
- try {
4266
- if (sets_1_1 && !sets_1_1.done && (_a = sets_1.return)) _a.call(sets_1);
4267
- }
4268
- finally { if (e_1) throw e_1.error; }
4269
- }
4270
- return union;
4271
- }
4272
-
4273
- /**
4274
- * Parses the template and returns the list of all parameter names
4275
- *
4276
- * @param template the template with parameters in {curly} braces
4277
- * @returns the list of parameter names
4278
- */
4279
- function extractParameters(template) {
4280
- var e_1, _a;
4281
- var matches = template.matchAll(/{\w+}/g);
4282
- var parameterNames = new Set();
4283
- try {
4284
- for (var matches_1 = __values(matches), matches_1_1 = matches_1.next(); !matches_1_1.done; matches_1_1 = matches_1.next()) {
4285
- var match = matches_1_1.value;
4286
- var parameterName = match[0].slice(1, -1);
4287
- parameterNames.add(parameterName);
4288
- }
4289
- }
4290
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
4291
- finally {
4292
- try {
4293
- if (matches_1_1 && !matches_1_1.done && (_a = matches_1.return)) _a.call(matches_1);
4294
- }
4295
- finally { if (e_1) throw e_1.error; }
4296
- }
4297
- return parameterNames;
4298
- }
4299
-
4300
- /**
4301
- * Parses the given script and returns the list of all used variables that are not defined in the script
4302
- *
4303
- * @param script from which to extract the variables
4304
- * @returns the list of variable names
4305
- * @throws {ParsingError} if the script is invalid
4306
- */
4307
- function extractVariables(script) {
4308
- var variables = new Set();
4309
- script = "(()=>{".concat(script, "})()");
4310
- try {
4311
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
4312
- try {
4313
- eval(script);
4314
- }
4315
- catch (error) {
4316
- if (!(error instanceof ReferenceError)) {
4317
- throw error;
4318
- }
4319
- var undefinedName = error.message.split(' ')[0];
4320
- /*
4321
- Note: Parsing the error
4322
- [ReferenceError: thing is not defined]
4323
- */
4324
- if (!undefinedName) {
4325
- throw error;
4326
- }
4327
- if (script.includes(undefinedName + '(')) {
4328
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
4329
- }
4330
- else {
4331
- variables.add(undefinedName);
4332
- script = "const ".concat(undefinedName, " = '';") + script;
4333
- }
4334
- }
4335
- }
4336
- catch (error) {
4337
- if (!(error instanceof Error)) {
4338
- throw error;
4339
- }
4340
- throw new ParsingError(spaceTrim$1(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.name), ": ").concat(block(error.message), "\n "); }));
4341
- }
4342
- return variables;
4343
- }
4344
- /**
4345
- * TODO: [🔣] Support for multiple languages - python, java,...
4346
- */
4347
-
4348
- /**
4349
- * Parses the prompt template and returns the set of all used parameters
4350
- *
4351
- * @param promptTemplate the template with used parameters
4352
- * @returns the set of parameter names
4353
- * @throws {ParsingError} if the script is invalid
4354
- */
4355
- function extractParametersFromPromptTemplate(promptTemplate) {
4356
- var e_1, _a, e_2, _b;
4357
- var parameterNames = new Set();
4358
- try {
4359
- for (var _c = __values(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameters(promptTemplate.title)), false), __read(extractParameters(promptTemplate.description || '')), false), __read(extractParameters(promptTemplate.content)), false)), _d = _c.next(); !_d.done; _d = _c.next()) {
4360
- var parameterName = _d.value;
4361
- parameterNames.add(parameterName);
4362
- }
4363
- }
4364
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
4365
- finally {
4366
- try {
4367
- if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
4368
- }
4369
- finally { if (e_1) throw e_1.error; }
4370
- }
4371
- if (promptTemplate.blockType === 'SCRIPT') {
4372
- try {
4373
- for (var _e = __values(extractVariables(promptTemplate.content)), _f = _e.next(); !_f.done; _f = _e.next()) {
4374
- var parameterName = _f.value;
4375
- parameterNames.add(parameterName);
4376
- }
4377
- }
4378
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
4379
- finally {
4380
- try {
4381
- if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
4382
- }
4383
- finally { if (e_2) throw e_2.error; }
4384
- }
4385
- }
4386
- return parameterNames;
4387
- }
4388
- /**
4389
- * TODO: [🔣] If script require contentLanguage
4390
- */
4391
-
4392
- /**
4393
- * Compile promptbook from string (markdown) format to JSON format synchronously
5122
+ * Compile pipeline from string (markdown) format to JSON format synchronously
4394
5123
  *
4395
- * Note: There are two similar functions:
5124
+ * Note: There are 3 similar functions:
4396
5125
  * - `pipelineStringToJson` **(preferred)** - which propperly compiles the promptbook and use embedding for external knowledge
4397
5126
  * - `pipelineStringToJsonSync` - use only if you need to compile promptbook synchronously and it contains NO external knowledge
5127
+ * - `preparePipeline` - just one step in the compilation process
4398
5128
  *
4399
5129
  * @param pipelineString {Promptbook} in string markdown format (.ptbk.md)
4400
- * @param options - Options and tools for the compilation
4401
5130
  * @returns {Promptbook} compiled in JSON format (.ptbk.json)
4402
5131
  * @throws {ParsingError} if the promptbook string is not valid
4403
5132
  *
@@ -4413,7 +5142,10 @@ function pipelineStringToJsonSync(pipelineString) {
4413
5142
  description: undefined /* <- Note: Putting here placeholder to keep `description` on top at final JSON */,
4414
5143
  parameters: [],
4415
5144
  promptTemplates: [],
4416
- knowledge: [],
5145
+ knowledgeSources: [],
5146
+ knowledgePieces: [],
5147
+ personas: [],
5148
+ preparations: [],
4417
5149
  };
4418
5150
  // =============================================================
4419
5151
  // Note: 1️⃣ Parsing of the markdown into object
@@ -4443,7 +5175,7 @@ function pipelineStringToJsonSync(pipelineString) {
4443
5175
  existingParameter.description &&
4444
5176
  existingParameter.description !== parameterDescription &&
4445
5177
  parameterDescription) {
4446
- throw new ParsingError(spaceTrim$1(function (block) { return "\n Parameter {".concat(parameterName, "} is defined multiple times with different description.\n\n First definition:\n ").concat(block(existingParameter.description || '[undefined]'), "\n\n Second definition:\n ").concat(block(parameterDescription || '[undefined]'), "\n "); }));
5178
+ throw new ParsingError(spaceTrim$1(function (block) { return "\n Parameter {".concat(parameterName, "} is defined multiple times with different description:\n\n First definition:\n ").concat(block(existingParameter.description || '[undefined]'), "\n\n Second definition:\n ").concat(block(parameterDescription || '[undefined]'), "\n "); }));
4447
5179
  }
4448
5180
  if (existingParameter) {
4449
5181
  if (parameterDescription) {
@@ -4462,11 +5194,12 @@ function pipelineStringToJsonSync(pipelineString) {
4462
5194
  // =============================================================
4463
5195
  // Note: 3️⃣ Process pipeline head
4464
5196
  pipelineJson.title = pipelineHead.title;
4465
- // TODO: [1] DRY description
5197
+ // TODO: [🎾][1] DRY description
4466
5198
  var description = pipelineHead.content;
4467
- // Note: Remove codeblocks - TODO: Maybe put this into util (exported from `@promptbool/utils`)
5199
+ // Note: Remove codeblocks - TODO: [🎾] Make util removeAllBlocksFromMarkdown (exported from `@promptbool/utils`)
4468
5200
  description = description.split(/^```.*^```/gms).join('');
4469
- //Note: Remove lists and return statement - TODO: Maybe put this into util (exported from `@promptbool/utils`)
5201
+ description = description.split(/^>.*$/gm).join('');
5202
+ //Note: Remove lists and return statement - TODO: [🎾] Make util (exported from `@promptbool/utils`)
4470
5203
  description = description.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
4471
5204
  description = spaceTrim$1(description);
4472
5205
  if (description === '') {
@@ -4494,7 +5227,7 @@ function pipelineStringToJsonSync(pipelineString) {
4494
5227
  pipelineJson.pipelineUrl = command.pipelineUrl.href;
4495
5228
  break;
4496
5229
  case 'KNOWLEDGE':
4497
- console.error(new NotYetImplementedError('Knowledge is not implemented yet'));
5230
+ knowledgeCommandParser.applyToPipelineJson(command, { pipelineJson: pipelineJson, templateJson: null });
4498
5231
  break;
4499
5232
  case 'ACTION':
4500
5233
  console.error(new NotYetImplementedError('Actions are not implemented yet'));
@@ -4503,7 +5236,8 @@ function pipelineStringToJsonSync(pipelineString) {
4503
5236
  console.error(new NotYetImplementedError('Instruments are not implemented yet'));
4504
5237
  break;
4505
5238
  case 'PERSONA':
4506
- console.error(new NotYetImplementedError('Personas are not implemented yet'));
5239
+ personaCommandParser.applyToPipelineJson(command, { pipelineJson: pipelineJson, templateJson: null });
5240
+ // <- Note: Prototype of [🍧] (remove this comment after full implementation)
4507
5241
  break;
4508
5242
  case 'BOILERPLATE':
4509
5243
  throw new ParsingError('BOILERPLATE command is only for testing purposes and should not be used in the .ptbk.md file'); // <- TODO: [🚞]
@@ -4526,29 +5260,83 @@ function pipelineStringToJsonSync(pipelineString) {
4526
5260
  // TODO: Parse prompt template description (the content out of the codeblock and lists)
4527
5261
  var templateModelRequirements = __assign({}, defaultModelRequirements);
4528
5262
  var listItems_3 = extractAllListItemsFromMarkdown(section.content);
4529
- var dependentParameterNames = new Set();
4530
- var blockType = 'PROMPT_TEMPLATE';
4531
- var jokers = [];
4532
- var postprocessing = [];
4533
- var expectAmount = {};
4534
- var expectFormat = undefined;
4535
- var isBlockTypeChanged = false;
5263
+ var lastLine = section.content.split('\n').pop();
5264
+ var resultingParameterNameMatch = /^->\s*\{(?<resultingParamName>[a-z0-9_]+)\}/im.exec(lastLine);
5265
+ var resultingParameterName = null;
5266
+ if (resultingParameterNameMatch &&
5267
+ resultingParameterNameMatch.groups !== undefined &&
5268
+ resultingParameterNameMatch.groups.resultingParamName !== undefined) {
5269
+ resultingParameterName = resultingParameterNameMatch.groups.resultingParamName;
5270
+ }
5271
+ var expectResultingParameterName = function () {
5272
+ if (resultingParameterName !== null) {
5273
+ return resultingParameterName;
5274
+ }
5275
+ throw new ParsingError(spaceTrim$1(function (block) { return "\n Template section must end with -> {parameterName}\n\n Invalid section:\n ".concat(block(
5276
+ // TODO: Show code of invalid sections each time + DRY
5277
+ section.content
5278
+ .split('\n')
5279
+ .map(function (line) { return " | ".concat(line); } /* <- TODO: [🚞] */)
5280
+ .join('\n')), "\n "); }));
5281
+ };
5282
+ var _e = extractOneBlockFromMarkdown(section.content), language = _e.language, content = _e.content;
5283
+ // TODO: [🎾][1] DRY description
5284
+ var description_1 = section.content;
5285
+ // Note: Remove codeblocks - TODO: [🎾]
5286
+ description_1 = description_1.split(/^```.*^```/gms).join('');
5287
+ description_1 = description_1.split(/^>.*$/gm).join('');
5288
+ //Note: Remove lists and return statement - TODO: [🎾]
5289
+ description_1 = description_1.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
5290
+ description_1 = spaceTrim$1(description_1);
5291
+ if (description_1 === '') {
5292
+ description_1 = undefined;
5293
+ }
5294
+ var templateJson = {
5295
+ blockType: 'PROMPT_TEMPLATE',
5296
+ name: titleToName(section.title),
5297
+ title: section.title,
5298
+ description: description_1,
5299
+ modelRequirements: templateModelRequirements,
5300
+ content: content,
5301
+ };
5302
+ /**
5303
+ * This is nessesary because block type can be
5304
+ * - Set zero times, so anticipate 'PROMPT_TEMPLATE'
5305
+ * - Set one time
5306
+ * - Set more times - throw error
5307
+ *
5308
+ * Note: [2]
5309
+ */
5310
+ var isBlockTypeSet = false;
4536
5311
  try {
4537
5312
  for (var listItems_2 = (e_3 = void 0, __values(listItems_3)), listItems_2_1 = listItems_2.next(); !listItems_2_1.done; listItems_2_1 = listItems_2.next()) {
4538
5313
  var listItem = listItems_2_1.value;
4539
5314
  var command = parseCommand(listItem, 'PIPELINE_TEMPLATE');
5315
+ // TODO [🍧][♓️] List commands and before apply order them
4540
5316
  switch (command.type) {
4541
5317
  // TODO: [🍧] Use here applyToPipelineJson and remove switch statement
4542
5318
  case 'BLOCK':
4543
- if (isBlockTypeChanged) {
5319
+ if (isBlockTypeSet) {
4544
5320
  throw new ParsingError('Block type is already defined in the prompt template. It can be defined only once.');
4545
5321
  }
4546
5322
  if (command.blockType === 'SAMPLE') {
4547
- console.error(new NotYetImplementedError('Block type SAMPLE is not implemented yet'));
5323
+ expectResultingParameterName();
5324
+ var parameter = pipelineJson.parameters.find(function (param) { return param.name === resultingParameterName; });
5325
+ if (parameter === undefined) {
5326
+ throw new UnexpectedError("Can not find parameter {".concat(resultingParameterName, "} to assign sample value"));
5327
+ }
5328
+ parameter.sampleValues = parameter.sampleValues || [];
5329
+ parameter.sampleValues.push(content);
4548
5330
  return "continue-templates";
4549
5331
  }
4550
5332
  if (command.blockType === 'KNOWLEDGE') {
4551
- console.error(new NotYetImplementedError('Knowledge is not implemented yet'));
5333
+ knowledgeCommandParser.applyToPipelineJson({
5334
+ type: 'KNOWLEDGE',
5335
+ source: content, // <- TODO: [🐝] !!! Work with KNOWLEDGE which not referring to the source file or website, but its content itself
5336
+ }, {
5337
+ pipelineJson: pipelineJson,
5338
+ templateJson: templateJson,
5339
+ });
4552
5340
  return "continue-templates";
4553
5341
  }
4554
5342
  if (command.blockType === 'ACTION') {
@@ -4559,35 +5347,37 @@ function pipelineStringToJsonSync(pipelineString) {
4559
5347
  console.error(new NotYetImplementedError('Instruments are not implemented yet'));
4560
5348
  return "continue-templates";
4561
5349
  }
4562
- blockType = command.blockType;
4563
- isBlockTypeChanged = true;
5350
+ expectResultingParameterName();
5351
+ templateJson.blockType = command.blockType;
5352
+ isBlockTypeSet = true; //<- Note: [2]
4564
5353
  break;
4565
5354
  case 'EXPECT_AMOUNT':
4566
5355
  // eslint-disable-next-line no-case-declarations
4567
5356
  var unit = command.unit.toLowerCase();
4568
- expectAmount[unit] = expectAmount[unit] || {};
5357
+ templateJson.expectations = templateJson.expectations || {};
5358
+ templateJson.expectations[unit] = templateJson.expectations[unit] || {};
4569
5359
  if (command.sign === 'MINIMUM' || command.sign === 'EXACTLY') {
4570
- if (expectAmount[unit].min !== undefined) {
4571
- throw new ParsingError("Already defined minumum ".concat(expectAmount[unit].min, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
5360
+ if (templateJson.expectations[unit].min !== undefined) {
5361
+ throw new ParsingError("Already defined minumum ".concat(templateJson.expectations[unit].min, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
4572
5362
  }
4573
- expectAmount[unit].min = command.amount;
5363
+ templateJson.expectations[unit].min = command.amount;
4574
5364
  } /* not else */
4575
5365
  if (command.sign === 'MAXIMUM' || command.sign === 'EXACTLY') {
4576
- if (expectAmount[unit].max !== undefined) {
4577
- throw new ParsingError("Already defined maximum ".concat(expectAmount[unit].max, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
5366
+ if (templateJson.expectations[unit].max !== undefined) {
5367
+ throw new ParsingError("Already defined maximum ".concat(templateJson.expectations[unit].max, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
4578
5368
  }
4579
- expectAmount[unit].max = command.amount;
5369
+ templateJson.expectations[unit].max = command.amount;
4580
5370
  }
4581
5371
  break;
4582
5372
  case 'EXPECT_FORMAT':
4583
- if (expectFormat !== undefined && command.format !== expectFormat) {
4584
- throw new ParsingError("Expect format is already defined to \"".concat(expectFormat, "\". Now you try to redefine it by \"").concat(command.format, "\"."));
5373
+ if (templateJson.expectFormat !== undefined && command.format !== templateJson.expectFormat) {
5374
+ throw new ParsingError(spaceTrim$1("\n Expect format is already defined to \"".concat(templateJson.expectFormat, "\".\n Now you try to redefine it by \"").concat(command.format, "\".\n ")));
4585
5375
  }
4586
- expectFormat = command.format;
5376
+ templateJson.expectFormat = command.format;
4587
5377
  break;
4588
5378
  case 'JOKER':
4589
- jokers.push(command.parameterName);
4590
- dependentParameterNames.add(command.parameterName);
5379
+ templateJson.jokerParameterNames = templateJson.jokerParameterNames || [];
5380
+ templateJson.jokerParameterNames.push(command.parameterName);
4591
5381
  break;
4592
5382
  case 'MODEL':
4593
5383
  templateModelRequirements[command.key] = command.value;
@@ -4597,19 +5387,24 @@ function pipelineStringToJsonSync(pipelineString) {
4597
5387
  defineParam(command);
4598
5388
  break;
4599
5389
  case 'POSTPROCESS':
4600
- postprocessing.push(command.functionName);
5390
+ templateJson.postprocessingFunctionNames = templateJson.postprocessingFunctionNames || [];
5391
+ templateJson.postprocessingFunctionNames.push(command.functionName);
4601
5392
  break;
4602
5393
  case 'KNOWLEDGE':
4603
- console.error(new NotYetImplementedError('Knowledge is not implemented yet'));
5394
+ // TODO: [👙] The knowledge is maybe relevant for just this template
5395
+ knowledgeCommandParser.applyToPipelineJson(command, { pipelineJson: pipelineJson, templateJson: templateJson });
4604
5396
  break;
4605
5397
  case 'ACTION':
5398
+ // TODO: [👙] The action is maybe relevant for just this template
4606
5399
  console.error(new NotYetImplementedError('Actions are not implemented yet'));
4607
5400
  break;
4608
5401
  case 'INSTRUMENT':
5402
+ // TODO: [👙] The instrument is maybe relevant for just this template
4609
5403
  console.error(new NotYetImplementedError('Instruments are not implemented yet'));
4610
5404
  break;
4611
5405
  case 'PERSONA':
4612
- console.error(new NotYetImplementedError('Personas are not implemented yet'));
5406
+ personaCommandParser.applyToPipelineJson(command, { pipelineJson: pipelineJson, templateJson: templateJson });
5407
+ // <- Note: Prototype of [🍧] (remove this comment after full implementation)
4613
5408
  break;
4614
5409
  case 'BOILERPLATE':
4615
5410
  console.error(new ParsingError('BOILERPLATE command is only for testing purposes and should not be used in the .ptbk.md file'));
@@ -4627,70 +5422,29 @@ function pipelineStringToJsonSync(pipelineString) {
4627
5422
  }
4628
5423
  finally { if (e_3) throw e_3.error; }
4629
5424
  }
4630
- var _e = extractOneBlockFromMarkdown(section.content), language = _e.language, content = _e.content;
4631
- if (blockType === 'SCRIPT') {
5425
+ // TODO: [🍧] Should be done in BLOCK command
5426
+ if (templateJson.blockType === 'SCRIPT') {
4632
5427
  if (!language) {
4633
5428
  throw new ParsingError('You must specify the language of the script in the prompt template');
4634
5429
  }
4635
- else if (!SUPPORTED_SCRIPT_LANGUAGES.includes(language)) {
5430
+ if (!SUPPORTED_SCRIPT_LANGUAGES.includes(language)) {
4636
5431
  throw new ParsingError(spaceTrim$1(function (block) { return "\n Script language ".concat(language, " is not supported.\n\n Supported languages are:\n ").concat(block(SUPPORTED_SCRIPT_LANGUAGES.join(', ')), "\n\n "); }));
4637
5432
  }
5433
+ templateJson.contentLanguage = language;
4638
5434
  }
4639
- var lastLine = section.content.split('\n').pop();
4640
- var match = /^->\s*\{(?<resultingParamName>[a-z0-9_]+)\}/im.exec(lastLine);
4641
- if (!match || match.groups === undefined || match.groups.resultingParamName === undefined) {
4642
- throw new ParsingError(spaceTrim$1(function (block) { return "\n Each section must end with -> {parameterName}\n\n Invalid section:\n ".concat(block(
4643
- // TODO: Show code of invalid sections each time + DRY
4644
- section.content
4645
- .split('\n')
4646
- .map(function (line) { return " | ".concat(line); } /* <- TODO: [🚞] */)
4647
- .join('\n')), "\n "); }));
4648
- }
4649
- var resultingParameterName = match.groups.resultingParamName;
4650
- // TODO: [1] DRY description
4651
- var description_1 = section.content;
4652
- // Note: Remove codeblocks
4653
- description_1 = description_1.split(/^```.*^```/gms).join('');
4654
- //Note: Remove lists and return statement
4655
- description_1 = description_1.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
4656
- description_1 = spaceTrim$1(description_1);
4657
- if (description_1 === '') {
4658
- description_1 = undefined;
4659
- }
4660
- if (Object.keys(jokers).length === 0) {
4661
- jokers = undefined;
4662
- }
4663
- if (Object.keys(expectAmount).length === 0) {
4664
- expectAmount = undefined;
4665
- }
4666
- if (Object.keys(postprocessing).length === 0) {
4667
- postprocessing = undefined;
4668
- }
4669
- dependentParameterNames = union(dependentParameterNames, extractParametersFromPromptTemplate(__assign(__assign({}, section), { description: description_1, blockType: blockType, content: content })));
5435
+ // TODO: [🍧][❔] Should be done in BLOCK command
4670
5436
  if (templateModelRequirements.modelVariant === undefined) {
4671
5437
  templateModelRequirements.modelVariant = 'CHAT';
4672
5438
  }
4673
- dependentParameterNames = difference(dependentParameterNames, new Set(RESERVED_PARAMETER_NAMES));
4674
- var template = {
4675
- name: titleToName(section.title),
4676
- title: section.title,
4677
- description: description_1,
4678
- dependentParameterNames: Array.from(dependentParameterNames),
4679
- blockType: blockType,
4680
- jokers: jokers,
4681
- postprocessing: postprocessing,
4682
- expectations: expectAmount,
4683
- expectFormat: expectFormat,
4684
- modelRequirements: templateModelRequirements,
4685
- contentLanguage: blockType === 'SCRIPT' ? language : undefined,
4686
- content: content,
4687
- resultingParameterName: resultingParameterName,
4688
- };
4689
- if (blockType !== 'PROMPT_TEMPLATE') {
4690
- delete template.modelRequirements;
5439
+ templateJson.dependentParameterNames = Array.from(extractParametersFromPromptTemplate(templateJson));
5440
+ // TODO: [🍧][❔] Remove this condition - modelRequirements should be put here via BLOCK command not removed when PROMPT_TEMPLATE
5441
+ if (templateJson.blockType !== 'PROMPT_TEMPLATE') {
5442
+ delete templateJson.modelRequirements;
4691
5443
  }
5444
+ // TODO: [🍧] Make this better - for example each command parser can call and apply this
5445
+ templateJson.resultingParameterName = expectResultingParameterName( /* <- Note: This is once more redundant */);
4692
5446
  // TODO: [🍧] What actually about preparation and pushing the block into `promptTemplates`
4693
- pipelineJson.promptTemplates.push(template /* <- !!! */);
5447
+ pipelineJson.promptTemplates.push(templateJson);
4694
5448
  };
4695
5449
  try {
4696
5450
  // =============================================================
@@ -4757,14 +5511,17 @@ function pipelineStringToJsonSync(pipelineString) {
4757
5511
  * TODO: Use spaceTrim more effectively
4758
5512
  * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
4759
5513
  * TODO: [🥞] Not optimal parsing because `splitMarkdownIntoSections` is executed twice with same string, once through `flattenMarkdown` and second directly here
5514
+ * TODO: [♈] Probbably move expectations from templates to parameters
5515
+ * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
4760
5516
  */
4761
5517
 
4762
5518
  /**
4763
- * Compile promptbook from string (markdown) format to JSON format
5519
+ * Compile pipeline from string (markdown) format to JSON format
4764
5520
  *
4765
- * Note: There are two similar functions:
5521
+ * Note: There are 3 similar functions:
4766
5522
  * - `pipelineStringToJson` **(preferred)** - which propperly compiles the promptbook and use embedding for external knowledge
4767
5523
  * - `pipelineStringToJsonSync` - use only if you need to compile promptbook synchronously and it contains NO external knowledge
5524
+ * - `preparePipeline` - just one step in the compilation process
4768
5525
  *
4769
5526
  * @param pipelineString {Promptbook} in string markdown format (.ptbk.md)
4770
5527
  * @param options - Options and tools for the compilation
@@ -4775,22 +5532,18 @@ function pipelineStringToJsonSync(pipelineString) {
4775
5532
  * Note: This function acts as compilation process
4776
5533
  */
4777
5534
  function pipelineStringToJson(pipelineString, options) {
4778
- if (options === void 0) { options = {}; }
5535
+ if (options === void 0) { options = { llmTools: null }; }
4779
5536
  return __awaiter(this, void 0, void 0, function () {
4780
- var llmTools, pipelineJson, knowledge;
5537
+ var llmTools, pipelineJson;
4781
5538
  return __generator(this, function (_a) {
4782
5539
  switch (_a.label) {
4783
5540
  case 0:
4784
5541
  llmTools = options.llmTools;
4785
5542
  pipelineJson = pipelineStringToJsonSync(pipelineString);
4786
- if (!llmTools) return [3 /*break*/, 2];
4787
- return [4 /*yield*/, prepareKnowledgeFromMarkdown({
4788
- content: 'Roses are red, violets are blue, programmers use Promptbook, users too',
4789
- llmTools: llmTools,
4790
- })];
5543
+ if (!(llmTools !== null)) return [3 /*break*/, 2];
5544
+ return [4 /*yield*/, preparePipeline(pipelineJson, { llmTools: llmTools })];
4791
5545
  case 1:
4792
- knowledge = _a.sent();
4793
- pipelineJson = __assign(__assign({}, pipelineJson), { knowledge: __spreadArray(__spreadArray([], __read((pipelineJson.knowledge || [])), false), __read(knowledge), false) });
5546
+ pipelineJson = _a.sent();
4794
5547
  _a.label = 2;
4795
5548
  case 2: return [2 /*return*/, pipelineJson];
4796
5549
  }
@@ -4799,12 +5552,13 @@ function pipelineStringToJson(pipelineString, options) {
4799
5552
  }
4800
5553
  /**
4801
5554
  * TODO: [🏏] Leverage the batch API and build queues @see https://platform.openai.com/docs/guides/batch
5555
+ * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
4802
5556
  */
4803
5557
 
4804
5558
  /**
4805
5559
  * Add or modify an auto-generated section in a markdown file
4806
5560
  *
4807
- * @private within the package
5561
+ * @private within the repository
4808
5562
  */
4809
5563
  function addAutoGeneratedSection(content, options) {
4810
5564
  var sectionName = options.sectionName, sectionContent = options.sectionContent;
@@ -4816,7 +5570,10 @@ function addAutoGeneratedSection(content, options) {
4816
5570
  }
4817
5571
  var placeForSection = removeContentComments(content).match(/^##.*$/im);
4818
5572
  if (!placeForSection) {
4819
- throw new Error("No place where to put the section <!--".concat(sectionName, "-->"));
5573
+ throw new ParsingError(
5574
+ // <- [🧠] Maybe something better than `ParsingError`
5575
+ "No place where to put the section <!--".concat(sectionName, "-->"));
5576
+ // <- [🚞]
4820
5577
  }
4821
5578
  var _a = __read(placeForSection, 1), heading = _a[0];
4822
5579
  return content.replace(heading, "<!--".concat(sectionName, "-->\n").concat(warningLine, "\n").concat(sectionContent, "\n<!--/").concat(sectionName, "-->\n\n").concat(heading));
@@ -4973,6 +5730,27 @@ function prettifyPipelineString(pipelineString, options) {
4973
5730
  * TODO: [🕌] When more than 2 functionalities, split into separate functions
4974
5731
  */
4975
5732
 
5733
+ /**
5734
+ * Stringify the PipelineJson with proper formatting
5735
+ *
5736
+ * Note: [0] It can be used for more JSON types like whole collection of pipelines, single knowledge piece, etc.
5737
+ * Note: In contrast to JSON.stringify, this function ensures that **embedding index** is on single line
5738
+ */
5739
+ function stringifyPipelineJson(pipeline) {
5740
+ var pipelineJsonStringified = JSON.stringify(pipeline, null, 4);
5741
+ for (var i = 0; i < LOOP_LIMIT; i++) {
5742
+ pipelineJsonStringified = pipelineJsonStringified.replace(/(-?0\.\d+),[\n\s]+(-?0\.\d+)/gms, "$1".concat(REPLACING_NONCE, "$2"));
5743
+ }
5744
+ pipelineJsonStringified = pipelineJsonStringified.split(REPLACING_NONCE).join(', ');
5745
+ pipelineJsonStringified += '\n';
5746
+ return pipelineJsonStringified;
5747
+ }
5748
+ /**
5749
+ * TODO: !!!! Not Working propperly @see https://promptbook.studio/samples/mixed-knowledge.ptbk.md
5750
+ * TODO: [🧠][0] Maybe rename to `stringifyPipelineJson`, `stringifyIndexedJson`,...
5751
+ * TODO: [🧠] Maybe more elegant solution than replacing via regex
5752
+ */
5753
+
4976
5754
  /**
4977
5755
  * This error indicates that the pipeline collection cannot be propperly loaded
4978
5756
  */
@@ -4987,6 +5765,20 @@ var CollectionError = /** @class */ (function (_super) {
4987
5765
  return CollectionError;
4988
5766
  }(Error));
4989
5767
 
5768
+ /**
5769
+ * This error type indicates that the version of the pipeline is not matching the expected version
5770
+ */
5771
+ var VersionMismatchError = /** @class */ (function (_super) {
5772
+ __extends(VersionMismatchError, _super);
5773
+ function VersionMismatchError(message, expectedVersion) {
5774
+ var _this = _super.call(this, spaceTrim$1(function (block) { return "\n ".concat(block(message), "\n\n This error indicates that there is error with compatibility\n\n Expected version:\n ").concat(expectedVersion, "\n\n Current version:\n ").concat(PROMPTBOOK_VERSION, "\n\n "); })) || this;
5775
+ _this.name = 'UnexpectedError';
5776
+ Object.setPrototypeOf(_this, VersionMismatchError.prototype);
5777
+ return _this;
5778
+ }
5779
+ return VersionMismatchError;
5780
+ }(Error));
5781
+
4990
5782
  /**
4991
5783
  * Pretty print an embedding vector for logging
4992
5784
  */
@@ -5074,6 +5866,9 @@ var SimplePromptInterfaceTools = /** @class */ (function () {
5074
5866
  };
5075
5867
  return SimplePromptInterfaceTools;
5076
5868
  }());
5869
+ /**
5870
+ * Note: [🔵] This code should never be published outside of `@promptbook/browser`
5871
+ */
5077
5872
 
5078
5873
  /**
5079
5874
  * Default options for generating an execution report string
@@ -5086,7 +5881,7 @@ var ExecutionReportStringOptionsDefaults = {
5086
5881
  /**
5087
5882
  * Format either small or big number
5088
5883
  *
5089
- * @private within the package
5884
+ * @private within the repository
5090
5885
  */
5091
5886
  function formatNumber(value) {
5092
5887
  if (value === 0) {
@@ -5106,7 +5901,7 @@ function formatNumber(value) {
5106
5901
  /**
5107
5902
  * Create a markdown table from a 2D array of strings
5108
5903
  *
5109
- * @private within the package
5904
+ * @private within the repository
5110
5905
  */
5111
5906
  function createMarkdownTable(table) {
5112
5907
  var columnWidths = table.reduce(function (widths, row) {
@@ -5134,7 +5929,7 @@ function createMarkdownTable(table) {
5134
5929
  /**
5135
5930
  * Function createMarkdownChart will draw a chart in markdown from ⬛+🟦 tiles
5136
5931
  *
5137
- * @private within the package
5932
+ * @private within the repository
5138
5933
  */
5139
5934
  function createMarkdownChart(options) {
5140
5935
  var e_1, _a;
@@ -5187,7 +5982,7 @@ var MOMENT_ARG_THRESHOLDS = {
5187
5982
  /**
5188
5983
  * Count the duration of working time
5189
5984
  *
5190
- * @private within the package
5985
+ * @private within the repository
5191
5986
  */
5192
5987
  function countWorkingDuration(items) {
5193
5988
  var e_1, _a;
@@ -5385,5 +6180,5 @@ function executionReportJsonToString(executionReportJson, options) {
5385
6180
  * TODO: [🧠] Allow to filter out some parts of the report by options
5386
6181
  */
5387
6182
 
5388
- export { BlockTypes, CallbackInterfaceTools, CollectionError, ExecutionReportStringOptionsDefaults, ExpectError, NotFoundError, PROMPTBOOK_VERSION, ParsingError, PipelineExecutionError, PipelineLogicError, RESERVED_PARAMETER_NAMES, ReferenceError$1 as ReferenceError, SimplePromptInterfaceTools, UnexpectedError, addUsage, assertsExecutionSuccessful, checkExpectations, collectionToJson, createCollectionFromJson, createCollectionFromPromise, createCollectionFromUrl, createPipelineExecutor, createSubcollection, embeddingVectorToString, executionReportJsonToString, isPassingExpectations, joinLlmExecutionTools, pipelineJsonToString, pipelineStringToJson, pipelineStringToJsonSync, prepareKnowledgeFromMarkdown, prettifyPipelineString, usageToWorktime, validatePipeline };
6183
+ export { BlockTypes, CallbackInterfaceTools, CollectionError, ExecutionReportStringOptionsDefaults, ExpectError, NotFoundError, PROMPTBOOK_VERSION, ParsingError, PipelineExecutionError, PipelineLogicError, RESERVED_PARAMETER_NAMES, ReferenceError$1 as ReferenceError, SimplePromptInterfaceTools, UnexpectedError, VersionMismatchError, addUsage, assertsExecutionSuccessful, checkExpectations, collectionToJson, createCollectionFromJson, createCollectionFromPromise, createCollectionFromUrl, createPipelineExecutor, createSubcollection, embeddingVectorToString, executionReportJsonToString, isPassingExpectations, joinLlmExecutionTools, pipelineJsonToString, pipelineStringToJson, pipelineStringToJsonSync, prepareKnowledgeFromMarkdown, preparePipeline, prettifyPipelineString, stringifyPipelineJson, unpreparePipeline, usageToWorktime, validatePipeline };
5389
6184
  //# sourceMappingURL=index.es.js.map