@promptbook/node 0.61.0-1 → 0.61.0-11

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 (225) hide show
  1. package/esm/index.es.js +736 -344
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/typings/promptbook-collection/index.d.ts +196 -23
  4. package/esm/typings/src/_packages/core.index.d.ts +5 -1
  5. package/esm/typings/src/_packages/types.index.d.ts +6 -4
  6. package/esm/typings/src/_packages/utils.index.d.ts +4 -3
  7. package/esm/typings/src/collection/constructors/createCollectionFromDirectory.d.ts +1 -1
  8. package/esm/typings/src/collection/constructors/createCollectionFromUrl.d.ts +2 -2
  9. package/esm/typings/src/commands/MODEL/ModelCommand.d.ts +1 -1
  10. package/esm/typings/src/commands/PERSONA/PersonaCommand.d.ts +4 -2
  11. package/esm/typings/src/commands/_common/types/CommandParser.d.ts +15 -12
  12. package/esm/typings/src/config.d.ts +8 -0
  13. package/esm/typings/src/conversion/pipelineStringToJson.d.ts +9 -5
  14. package/esm/typings/src/conversion/pipelineStringToJsonSync.d.ts +5 -3
  15. package/esm/typings/src/conversion/prettify/PrettifyOptions.d.ts +2 -2
  16. package/esm/typings/src/conversion/utils/renameParameter.d.ts +3 -3
  17. package/esm/typings/src/conversion/validation/_importPipeline.d.ts +2 -2
  18. package/esm/typings/src/conversion/validation/validatePipeline.d.ts +4 -0
  19. package/esm/typings/src/errors/EnvironmentMismatchError.d.ts +7 -0
  20. package/esm/typings/src/errors/VersionMismatchError.d.ts +8 -0
  21. package/esm/typings/src/execution/LlmExecutionTools.d.ts +3 -1
  22. package/esm/typings/src/execution/PipelineExecutor.d.ts +8 -7
  23. package/esm/typings/src/execution/PromptResult.d.ts +17 -5
  24. package/esm/typings/src/execution/ScriptExecutionTools.d.ts +6 -4
  25. package/esm/typings/src/execution/UserInterfaceTools.d.ts +5 -5
  26. package/esm/typings/src/execution/createPipelineExecutor.d.ts +4 -1
  27. package/esm/typings/src/execution/translation/automatic-translate/automatic-translators/TranslatorOptions.d.ts +2 -2
  28. package/esm/typings/src/execution/utils/forEachAsync.d.ts +1 -1
  29. package/esm/typings/src/formats/csv/ListFormatDefinition.d.ts +1 -1
  30. package/esm/typings/src/formats/json/JsonFormatDefinition.d.ts +1 -1
  31. package/esm/typings/src/formats/list/ListFormatDefinition.d.ts +1 -1
  32. package/esm/typings/src/knowledge/dialogs/callback/CallbackInterfaceToolsOptions.d.ts +1 -1
  33. package/esm/typings/src/knowledge/prepare-knowledge/_common/prepareKnowledgePieces.d.ts +18 -0
  34. package/esm/typings/src/knowledge/prepare-knowledge/_common/prepareKnowledgePieces.test.d.ts +1 -0
  35. package/esm/typings/src/knowledge/prepare-knowledge/_common/utils/getLlmToolsForTestingAndScriptsAndPlayground.d.ts +10 -0
  36. package/esm/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +8 -23
  37. package/esm/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.test.d.ts +3 -0
  38. package/esm/typings/src/knowledge/prepare-knowledge/pdf/prepareKnowledgeFromPdf.d.ts +7 -14
  39. package/esm/typings/src/llm-providers/anthropic-claude/AnthropicClaudeExecutionToolsOptions.d.ts +1 -1
  40. package/esm/typings/src/llm-providers/anthropic-claude/anthropic-claude-models.d.ts +2 -2
  41. package/esm/typings/src/llm-providers/anthropic-claude/playground/playground.d.ts +3 -0
  42. package/esm/typings/src/llm-providers/azure-openai/AzureOpenAiExecutionToolsOptions.d.ts +5 -5
  43. package/esm/typings/src/llm-providers/azure-openai/playground/playground.d.ts +3 -0
  44. package/esm/typings/src/llm-providers/mocked/MockedEchoLlmExecutionTools.d.ts +1 -1
  45. package/esm/typings/src/llm-providers/mocked/MockedFackedLlmExecutionTools.d.ts +1 -1
  46. package/esm/typings/src/llm-providers/multiple/MultipleLlmExecutionTools.d.ts +3 -1
  47. package/esm/typings/src/llm-providers/openai/OpenAiExecutionToolsOptions.d.ts +1 -1
  48. package/esm/typings/src/llm-providers/openai/openai-models.d.ts +3 -2
  49. package/esm/typings/src/llm-providers/openai/playground/playground.d.ts +3 -0
  50. package/esm/typings/src/llm-providers/remote/RemoteLlmExecutionToolsOptions.d.ts +1 -1
  51. package/esm/typings/src/llm-providers/utils/cache/CacheItem.d.ts +29 -0
  52. package/esm/typings/src/llm-providers/utils/cache/CacheLlmToolsOptions.d.ts +10 -0
  53. package/esm/typings/src/llm-providers/utils/cache/cacheLlmTools.d.ts +17 -0
  54. package/esm/typings/src/llm-providers/utils/count-total-cost/LlmExecutionToolsWithTotalCost.d.ts +11 -0
  55. package/esm/typings/src/llm-providers/utils/count-total-cost/countTotalCost.d.ts +14 -0
  56. package/esm/typings/src/llm-providers/utils/createLlmToolsFromEnv.d.ts +21 -0
  57. package/esm/typings/src/personas/preparePersona.d.ts +10 -0
  58. package/esm/typings/src/personas/preparePersona.test.d.ts +1 -0
  59. package/esm/typings/src/prepare/PrepareOptions.d.ts +22 -0
  60. package/esm/typings/src/prepare/preparePipeline.d.ts +16 -0
  61. package/esm/typings/src/prepare/unpreparePipeline.d.ts +8 -0
  62. package/esm/typings/src/scripting/javascript/JavascriptExecutionToolsOptions.d.ts +1 -1
  63. package/esm/typings/src/scripting/javascript/utils/preserve.d.ts +1 -1
  64. package/esm/typings/src/storage/_common/PromptbookStorage.d.ts +24 -0
  65. package/esm/typings/src/storage/_common/PromptbookStorage.test-type.d.ts +5 -0
  66. package/esm/typings/src/storage/files-storage/FilesStorage.d.ts +28 -0
  67. package/esm/typings/src/storage/files-storage/FilesStorageOptions.d.ts +10 -0
  68. package/esm/typings/src/storage/files-storage/utils/nameToSubfolderPath.d.ts +7 -0
  69. package/esm/typings/src/storage/files-storage/utils/nameToSubfolderPath.test.d.ts +1 -0
  70. package/esm/typings/src/storage/local-storage/getLocalStorage.d.ts +8 -0
  71. package/esm/typings/src/storage/local-storage/getSessionStorage.d.ts +8 -0
  72. package/esm/typings/src/storage/memory/MemoryStorage.d.ts +31 -0
  73. package/esm/typings/src/storage/utils/PrefixStorage.d.ts +23 -0
  74. package/esm/typings/src/storage/utils/makePromptbookStorageFromWebStorage.d.ts +12 -0
  75. package/esm/typings/src/types/ModelRequirements.d.ts +22 -1
  76. package/esm/typings/src/types/PipelineJson/Expectations.d.ts +6 -2
  77. package/esm/typings/src/types/PipelineJson/KnowledgePieceJson.d.ts +67 -0
  78. package/esm/typings/src/types/PipelineJson/KnowledgeSourceJson.d.ts +24 -0
  79. package/esm/typings/src/types/PipelineJson/LlmTemplateJson.d.ts +8 -1
  80. package/esm/typings/src/types/PipelineJson/PersonaJson.d.ts +40 -0
  81. package/esm/typings/src/types/PipelineJson/PipelineJson.d.ts +27 -3
  82. package/esm/typings/src/types/PipelineJson/PreparationJson.d.ts +21 -0
  83. package/esm/typings/src/types/PipelineJson/PromptDialogJson.d.ts +2 -0
  84. package/esm/typings/src/types/PipelineJson/PromptTemplateJson.d.ts +1 -1
  85. package/esm/typings/src/types/PipelineJson/PromptTemplateJsonCommon.d.ts +8 -1
  86. package/esm/typings/src/types/PipelineJson/PromptTemplateParameterJson.d.ts +11 -2
  87. package/esm/typings/src/types/PipelineJson/ScriptJson.d.ts +2 -0
  88. package/esm/typings/src/types/PipelineJson/SimpleTemplateJson.d.ts +2 -0
  89. package/esm/typings/src/types/Prompt.d.ts +5 -2
  90. package/esm/typings/src/types/execution-report/ExecutionReportJson.d.ts +4 -4
  91. package/esm/typings/src/types/execution-report/ExecutionReportStringOptions.d.ts +3 -3
  92. package/esm/typings/src/types/typeAliases.d.ts +62 -14
  93. package/esm/typings/src/utils/FromtoItems.d.ts +3 -3
  94. package/esm/typings/src/utils/currentDate.d.ts +7 -0
  95. package/esm/typings/src/utils/markdown/addAutoGeneratedSection.d.ts +2 -2
  96. package/esm/typings/src/utils/markdown/createMarkdownChart.d.ts +6 -9
  97. package/esm/typings/src/utils/markdown/extractAllBlocksFromMarkdown-real.test.d.ts +1 -0
  98. package/esm/typings/src/utils/markdown/extractAllBlocksFromMarkdown.d.ts +9 -2
  99. package/esm/typings/src/utils/markdown/extractOneBlockFromMarkdown.d.ts +1 -1
  100. package/esm/typings/src/utils/markdown/parseMarkdownSection.d.ts +3 -3
  101. package/esm/typings/src/utils/organization/TODO.d.ts +4 -0
  102. package/esm/typings/src/utils/organization/TODO_USE.d.ts +11 -0
  103. package/esm/typings/src/utils/organization/___.d.ts +4 -0
  104. package/esm/typings/src/utils/organization/notUsing.d.ts +11 -0
  105. package/esm/typings/src/utils/organization/really_any.d.ts +4 -0
  106. package/esm/typings/src/utils/random/randomSeed.d.ts +7 -0
  107. package/package.json +2 -2
  108. package/umd/index.umd.js +736 -344
  109. package/umd/index.umd.js.map +1 -1
  110. package/umd/typings/promptbook-collection/index.d.ts +196 -23
  111. package/umd/typings/src/_packages/core.index.d.ts +5 -1
  112. package/umd/typings/src/_packages/types.index.d.ts +6 -4
  113. package/umd/typings/src/_packages/utils.index.d.ts +4 -3
  114. package/umd/typings/src/collection/constructors/createCollectionFromDirectory.d.ts +1 -1
  115. package/umd/typings/src/collection/constructors/createCollectionFromUrl.d.ts +2 -2
  116. package/umd/typings/src/commands/MODEL/ModelCommand.d.ts +1 -1
  117. package/umd/typings/src/commands/PERSONA/PersonaCommand.d.ts +4 -2
  118. package/umd/typings/src/commands/_common/types/CommandParser.d.ts +15 -12
  119. package/umd/typings/src/config.d.ts +8 -0
  120. package/umd/typings/src/conversion/pipelineStringToJson.d.ts +9 -5
  121. package/umd/typings/src/conversion/pipelineStringToJsonSync.d.ts +5 -3
  122. package/umd/typings/src/conversion/prettify/PrettifyOptions.d.ts +2 -2
  123. package/umd/typings/src/conversion/utils/renameParameter.d.ts +3 -3
  124. package/umd/typings/src/conversion/validation/_importPipeline.d.ts +2 -2
  125. package/umd/typings/src/conversion/validation/validatePipeline.d.ts +4 -0
  126. package/umd/typings/src/errors/EnvironmentMismatchError.d.ts +7 -0
  127. package/umd/typings/src/errors/VersionMismatchError.d.ts +8 -0
  128. package/umd/typings/src/execution/LlmExecutionTools.d.ts +3 -1
  129. package/umd/typings/src/execution/PipelineExecutor.d.ts +8 -7
  130. package/umd/typings/src/execution/PromptResult.d.ts +17 -5
  131. package/umd/typings/src/execution/ScriptExecutionTools.d.ts +6 -4
  132. package/umd/typings/src/execution/UserInterfaceTools.d.ts +5 -5
  133. package/umd/typings/src/execution/createPipelineExecutor.d.ts +4 -1
  134. package/umd/typings/src/execution/translation/automatic-translate/automatic-translators/TranslatorOptions.d.ts +2 -2
  135. package/umd/typings/src/execution/utils/forEachAsync.d.ts +1 -1
  136. package/umd/typings/src/formats/csv/ListFormatDefinition.d.ts +1 -1
  137. package/umd/typings/src/formats/json/JsonFormatDefinition.d.ts +1 -1
  138. package/umd/typings/src/formats/list/ListFormatDefinition.d.ts +1 -1
  139. package/umd/typings/src/knowledge/dialogs/callback/CallbackInterfaceToolsOptions.d.ts +1 -1
  140. package/umd/typings/src/knowledge/prepare-knowledge/_common/prepareKnowledgePieces.d.ts +18 -0
  141. package/umd/typings/src/knowledge/prepare-knowledge/_common/prepareKnowledgePieces.test.d.ts +1 -0
  142. package/umd/typings/src/knowledge/prepare-knowledge/_common/utils/getLlmToolsForTestingAndScriptsAndPlayground.d.ts +10 -0
  143. package/umd/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +8 -23
  144. package/umd/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.test.d.ts +3 -0
  145. package/umd/typings/src/knowledge/prepare-knowledge/pdf/prepareKnowledgeFromPdf.d.ts +7 -14
  146. package/umd/typings/src/llm-providers/anthropic-claude/AnthropicClaudeExecutionToolsOptions.d.ts +1 -1
  147. package/umd/typings/src/llm-providers/anthropic-claude/anthropic-claude-models.d.ts +2 -2
  148. package/umd/typings/src/llm-providers/anthropic-claude/playground/playground.d.ts +3 -0
  149. package/umd/typings/src/llm-providers/azure-openai/AzureOpenAiExecutionToolsOptions.d.ts +5 -5
  150. package/umd/typings/src/llm-providers/azure-openai/playground/playground.d.ts +3 -0
  151. package/umd/typings/src/llm-providers/mocked/MockedEchoLlmExecutionTools.d.ts +1 -1
  152. package/umd/typings/src/llm-providers/mocked/MockedFackedLlmExecutionTools.d.ts +1 -1
  153. package/umd/typings/src/llm-providers/multiple/MultipleLlmExecutionTools.d.ts +3 -1
  154. package/umd/typings/src/llm-providers/openai/OpenAiExecutionToolsOptions.d.ts +1 -1
  155. package/umd/typings/src/llm-providers/openai/openai-models.d.ts +3 -2
  156. package/umd/typings/src/llm-providers/openai/playground/playground.d.ts +3 -0
  157. package/umd/typings/src/llm-providers/remote/RemoteLlmExecutionToolsOptions.d.ts +1 -1
  158. package/umd/typings/src/llm-providers/utils/cache/CacheItem.d.ts +29 -0
  159. package/umd/typings/src/llm-providers/utils/cache/CacheLlmToolsOptions.d.ts +10 -0
  160. package/umd/typings/src/llm-providers/utils/cache/cacheLlmTools.d.ts +17 -0
  161. package/umd/typings/src/llm-providers/utils/count-total-cost/LlmExecutionToolsWithTotalCost.d.ts +11 -0
  162. package/umd/typings/src/llm-providers/utils/count-total-cost/countTotalCost.d.ts +14 -0
  163. package/umd/typings/src/llm-providers/utils/createLlmToolsFromEnv.d.ts +21 -0
  164. package/umd/typings/src/personas/preparePersona.d.ts +10 -0
  165. package/umd/typings/src/personas/preparePersona.test.d.ts +1 -0
  166. package/umd/typings/src/prepare/PrepareOptions.d.ts +22 -0
  167. package/umd/typings/src/prepare/preparePipeline.d.ts +16 -0
  168. package/umd/typings/src/prepare/unpreparePipeline.d.ts +8 -0
  169. package/umd/typings/src/scripting/javascript/JavascriptExecutionToolsOptions.d.ts +1 -1
  170. package/umd/typings/src/scripting/javascript/utils/preserve.d.ts +1 -1
  171. package/umd/typings/src/storage/_common/PromptbookStorage.d.ts +24 -0
  172. package/umd/typings/src/storage/_common/PromptbookStorage.test-type.d.ts +5 -0
  173. package/umd/typings/src/storage/files-storage/FilesStorage.d.ts +28 -0
  174. package/umd/typings/src/storage/files-storage/FilesStorageOptions.d.ts +10 -0
  175. package/umd/typings/src/storage/files-storage/utils/nameToSubfolderPath.d.ts +7 -0
  176. package/umd/typings/src/storage/files-storage/utils/nameToSubfolderPath.test.d.ts +1 -0
  177. package/umd/typings/src/storage/local-storage/getLocalStorage.d.ts +8 -0
  178. package/umd/typings/src/storage/local-storage/getSessionStorage.d.ts +8 -0
  179. package/umd/typings/src/storage/memory/MemoryStorage.d.ts +31 -0
  180. package/umd/typings/src/storage/utils/PrefixStorage.d.ts +23 -0
  181. package/umd/typings/src/storage/utils/makePromptbookStorageFromWebStorage.d.ts +12 -0
  182. package/umd/typings/src/types/ModelRequirements.d.ts +22 -1
  183. package/umd/typings/src/types/PipelineJson/Expectations.d.ts +6 -2
  184. package/umd/typings/src/types/PipelineJson/KnowledgePieceJson.d.ts +67 -0
  185. package/umd/typings/src/types/PipelineJson/KnowledgeSourceJson.d.ts +24 -0
  186. package/umd/typings/src/types/PipelineJson/LlmTemplateJson.d.ts +8 -1
  187. package/umd/typings/src/types/PipelineJson/PersonaJson.d.ts +40 -0
  188. package/umd/typings/src/types/PipelineJson/PipelineJson.d.ts +27 -3
  189. package/umd/typings/src/types/PipelineJson/PreparationJson.d.ts +21 -0
  190. package/umd/typings/src/types/PipelineJson/PromptDialogJson.d.ts +2 -0
  191. package/umd/typings/src/types/PipelineJson/PromptTemplateJson.d.ts +1 -1
  192. package/umd/typings/src/types/PipelineJson/PromptTemplateJsonCommon.d.ts +8 -1
  193. package/umd/typings/src/types/PipelineJson/PromptTemplateParameterJson.d.ts +11 -2
  194. package/umd/typings/src/types/PipelineJson/ScriptJson.d.ts +2 -0
  195. package/umd/typings/src/types/PipelineJson/SimpleTemplateJson.d.ts +2 -0
  196. package/umd/typings/src/types/Prompt.d.ts +5 -2
  197. package/umd/typings/src/types/execution-report/ExecutionReportJson.d.ts +4 -4
  198. package/umd/typings/src/types/execution-report/ExecutionReportStringOptions.d.ts +3 -3
  199. package/umd/typings/src/types/typeAliases.d.ts +62 -14
  200. package/umd/typings/src/utils/FromtoItems.d.ts +3 -3
  201. package/umd/typings/src/utils/currentDate.d.ts +7 -0
  202. package/umd/typings/src/utils/markdown/addAutoGeneratedSection.d.ts +2 -2
  203. package/umd/typings/src/utils/markdown/createMarkdownChart.d.ts +6 -9
  204. package/umd/typings/src/utils/markdown/extractAllBlocksFromMarkdown-real.test.d.ts +1 -0
  205. package/umd/typings/src/utils/markdown/extractAllBlocksFromMarkdown.d.ts +9 -2
  206. package/umd/typings/src/utils/markdown/extractOneBlockFromMarkdown.d.ts +1 -1
  207. package/umd/typings/src/utils/markdown/parseMarkdownSection.d.ts +3 -3
  208. package/umd/typings/src/utils/organization/TODO.d.ts +4 -0
  209. package/umd/typings/src/utils/organization/TODO_USE.d.ts +11 -0
  210. package/umd/typings/src/utils/organization/___.d.ts +4 -0
  211. package/umd/typings/src/utils/organization/notUsing.d.ts +11 -0
  212. package/umd/typings/src/utils/organization/really_any.d.ts +4 -0
  213. package/umd/typings/src/utils/random/randomSeed.d.ts +7 -0
  214. package/esm/typings/src/collection/constructors/justTestFsImport.d.ts +0 -7
  215. package/esm/typings/src/personas/personaToModelRequirements.d.ts +0 -6
  216. package/esm/typings/src/types/PipelineJson/KnowledgeJson.d.ts +0 -6
  217. package/esm/typings/src/types/PipelineJson/MaterialKnowledgePieceJson.d.ts +0 -28
  218. package/umd/typings/src/collection/constructors/justTestFsImport.d.ts +0 -7
  219. package/umd/typings/src/personas/personaToModelRequirements.d.ts +0 -6
  220. package/umd/typings/src/types/PipelineJson/KnowledgeJson.d.ts +0 -6
  221. package/umd/typings/src/types/PipelineJson/MaterialKnowledgePieceJson.d.ts +0 -28
  222. /package/esm/typings/src/_packages/{markdown-utils.d.ts → markdown-utils.index.d.ts} +0 -0
  223. /package/esm/typings/src/utils/{just.d.ts → organization/just.d.ts} +0 -0
  224. /package/umd/typings/src/_packages/{markdown-utils.d.ts → markdown-utils.index.d.ts} +0 -0
  225. /package/umd/typings/src/utils/{just.d.ts → organization/just.d.ts} +0 -0
package/esm/index.es.js CHANGED
@@ -128,6 +128,10 @@ function __spreadArray(to, from, pack) {
128
128
  * The maximum number of iterations for a loops
129
129
  */
130
130
  var LOOP_LIMIT = 1000;
131
+ /**
132
+ * The maximum number of (LLM) tasks running in parallel
133
+ */
134
+ var MAX_PARALLEL_COUNT = 5;
131
135
  /**
132
136
  * The name of the builded pipeline collection made by CLI `ptbk make` and for lookup in `createCollectionFromDirectory`
133
137
  */
@@ -141,7 +145,172 @@ var RESERVED_PARAMETER_NAMES = [
141
145
  // <- TODO: Add [emoji] + instructions ACRY when adding new reserved parameter
142
146
  ];
143
147
 
144
- var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.61.0-0",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:"u",title:"U",content:"E",keywords:["E"],index:[{modelName:"mocked-facked",position:[0.3862088172833116,0.7349284028017404,-0.9438230019966163,-0.9250069104750818,-0.026138914694730175,-0.7268311159817045,-0.07935019253731612,0.6470171268509612,-0.43852570574155214,0.34435062959144824,-0.03450022605546588,-0.5277705379240651,0.00828213142899159,0.15691069644743383,-0.625404064630672,-0.33277847012240613,-0.2936622789266794,0.18401827710902152,0.3055511517178138,0.2943796117307138,0.7709829510346151,-0.4424955841467506,0.6031092188828207,-0.02473045258733153,0.33586695334417804]}],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-0",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:"s",title:"S",content:"A",keywords:["I"],index:[{modelName:"mocked-facked",position:[0.6409598940537844,-0.599282163088533,-0.7951357406825994,0.5034713531055992,0.9186084716269733,-0.6841151439158257,-0.39762364246107484,-0.7646814627420149,0.9551202443145854,0.36871821752653666,0.27710484531156565,-0.6886362623745139,0.1246419058549284,-0.7957866917804912,-0.4688680561538634,-0.7037555014650994,0.003694510488622793,0.3186841135345695,-0.7081253398806422,0.7052620275090136,-0.9744710956043585,0.6828863755008538,-0.021569809814358187,-0.23961644339743904,-0.5963677915161343]}],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-0",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:"c",title:"C",content:"A",keywords:["E"],index:[{modelName:"mocked-facked",position:[0.3053077802556703,0.45834476154202175,0.11951317167907494,-0.8925032092763412,-0.041809804577583876,-0.7087885568549193,0.0373992576888198,0.9495631083993494,-0.6050023289380846,0.14919003109680862,-0.3228347383159025,0.3273383195761892,-0.5509884895794359,0.7137115707360451,-0.3455818427015154,-0.7130289858826453,0.6105746565153107,-0.30829913719966573,0.6287711326338274,-0.8588121879147286,-0.583980568533244,-0.23082011458606733,-0.10987445073290791,-0.1129755192200137,0.4046462365369812]}],sources:[{title:"Markdown document",href:"#"}]}],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"}];
148
+ /**
149
+ * Function `addUsage` will add multiple usages into one
150
+ *
151
+ * Note: If you provide 0 values, it returns void usage
152
+ */
153
+ function addUsage() {
154
+ var usageItems = [];
155
+ for (var _i = 0; _i < arguments.length; _i++) {
156
+ usageItems[_i] = arguments[_i];
157
+ }
158
+ var initialStructure = {
159
+ price: { value: 0 },
160
+ input: {
161
+ tokensCount: { value: 0 },
162
+ charactersCount: { value: 0 },
163
+ wordsCount: { value: 0 },
164
+ sentencesCount: { value: 0 },
165
+ linesCount: { value: 0 },
166
+ paragraphsCount: { value: 0 },
167
+ pagesCount: { value: 0 },
168
+ },
169
+ output: {
170
+ tokensCount: { value: 0 },
171
+ charactersCount: { value: 0 },
172
+ wordsCount: { value: 0 },
173
+ sentencesCount: { value: 0 },
174
+ linesCount: { value: 0 },
175
+ paragraphsCount: { value: 0 },
176
+ pagesCount: { value: 0 },
177
+ },
178
+ };
179
+ return usageItems.reduce(function (acc, item) {
180
+ var e_1, _a, e_2, _b;
181
+ var _c;
182
+ acc.price.value += ((_c = item.price) === null || _c === void 0 ? void 0 : _c.value) || 0;
183
+ try {
184
+ for (var _d = __values(Object.keys(acc.input)), _e = _d.next(); !_e.done; _e = _d.next()) {
185
+ var key = _e.value;
186
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
187
+ //@ts-ignore
188
+ if (item.input[key]) {
189
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
190
+ //@ts-ignore
191
+ acc.input[key].value += item.input[key].value || 0;
192
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
193
+ //@ts-ignore
194
+ if (item.input[key].isUncertain) {
195
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
196
+ //@ts-ignore
197
+ acc.input[key].isUncertain = true;
198
+ }
199
+ }
200
+ }
201
+ }
202
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
203
+ finally {
204
+ try {
205
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
206
+ }
207
+ finally { if (e_1) throw e_1.error; }
208
+ }
209
+ try {
210
+ for (var _f = __values(Object.keys(acc.output)), _g = _f.next(); !_g.done; _g = _f.next()) {
211
+ var key = _g.value;
212
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
213
+ //@ts-ignore
214
+ if (item.output[key]) {
215
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
216
+ //@ts-ignore
217
+ acc.output[key].value += item.output[key].value || 0;
218
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
219
+ //@ts-ignore
220
+ if (item.output[key].isUncertain) {
221
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
222
+ //@ts-ignore
223
+ acc.output[key].isUncertain = true;
224
+ }
225
+ }
226
+ }
227
+ }
228
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
229
+ finally {
230
+ try {
231
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
232
+ }
233
+ finally { if (e_2) throw e_2.error; }
234
+ }
235
+ return acc;
236
+ }, initialStructure);
237
+ }
238
+
239
+ /**
240
+ * Async version of Array.forEach
241
+ *
242
+ * @param array - Array to iterate over
243
+ * @param options - Options for the function
244
+ * @param callbackfunction - Function to call for each item
245
+ */
246
+ function forEachAsync(array, options, callbackfunction) {
247
+ return __awaiter(this, void 0, void 0, function () {
248
+ var _a, maxParallelCount, index, runningTasks, tasks, _loop_1, _b, _c, item, e_1_1;
249
+ var e_1, _d;
250
+ return __generator(this, function (_e) {
251
+ switch (_e.label) {
252
+ case 0:
253
+ _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? Infinity : _a;
254
+ index = 0;
255
+ runningTasks = [];
256
+ tasks = [];
257
+ _loop_1 = function (item) {
258
+ var currentIndex, task;
259
+ return __generator(this, function (_f) {
260
+ switch (_f.label) {
261
+ case 0:
262
+ currentIndex = index++;
263
+ task = callbackfunction(item, currentIndex, array);
264
+ tasks.push(task);
265
+ runningTasks.push(task);
266
+ /* not await */ Promise.resolve(task).then(function () {
267
+ runningTasks = runningTasks.filter(function (t) { return t !== task; });
268
+ });
269
+ if (!(maxParallelCount < runningTasks.length)) return [3 /*break*/, 2];
270
+ return [4 /*yield*/, Promise.race(runningTasks)];
271
+ case 1:
272
+ _f.sent();
273
+ _f.label = 2;
274
+ case 2: return [2 /*return*/];
275
+ }
276
+ });
277
+ };
278
+ _e.label = 1;
279
+ case 1:
280
+ _e.trys.push([1, 6, 7, 8]);
281
+ _b = __values(array), _c = _b.next();
282
+ _e.label = 2;
283
+ case 2:
284
+ if (!!_c.done) return [3 /*break*/, 5];
285
+ item = _c.value;
286
+ return [5 /*yield**/, _loop_1(item)];
287
+ case 3:
288
+ _e.sent();
289
+ _e.label = 4;
290
+ case 4:
291
+ _c = _b.next();
292
+ return [3 /*break*/, 2];
293
+ case 5: return [3 /*break*/, 8];
294
+ case 6:
295
+ e_1_1 = _e.sent();
296
+ e_1 = { error: e_1_1 };
297
+ return [3 /*break*/, 8];
298
+ case 7:
299
+ try {
300
+ if (_c && !_c.done && (_d = _b.return)) _d.call(_b);
301
+ }
302
+ finally { if (e_1) throw e_1.error; }
303
+ return [7 /*endfinally*/];
304
+ case 8: return [4 /*yield*/, Promise.all(tasks)];
305
+ case 9:
306
+ _e.sent();
307
+ return [2 /*return*/];
308
+ }
309
+ });
310
+ });
311
+ }
312
+
313
+ var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.61.0-10",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",personaName:null,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"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[{id:1,promptbookVersion:"0.61.0-10",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-10",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",personaName:null,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"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[{id:1,promptbookVersion:"0.61.0-10",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-10",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}},personaName:null,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"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[{id:1,promptbookVersion:"0.61.0-10",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-10",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:[{name:"make-model-requirements",title:"Make modelRequirements",dependentParameterNames:["availableModelNames","personaDescription"],blockType:"PROMPT_TEMPLATE",expectFormat:"JSON",personaName:null,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}",resultingParameterName:"modelRequirements"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[{id:1,promptbookVersion:"0.61.0-10",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"}];
145
314
 
146
315
  /**
147
316
  * Prettify the html code
@@ -758,6 +927,10 @@ function validatePipeline(pipeline) {
758
927
  * > * - ...
759
928
  * > ex port function validatePipeline(promptbook: unknown): asserts promptbook is PipelineJson {
760
929
  */
930
+ /**
931
+ * TODO: [🧠] !!!!! Validate new things
932
+ * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
933
+ */
761
934
 
762
935
  /**
763
936
  * This error indicates that promptbook not found in the collection
@@ -1210,6 +1383,14 @@ function removeEmojis(text) {
1210
1383
  * Function normalizes title to name which can be used as identifier
1211
1384
  */
1212
1385
  function titleToName(value) {
1386
+ if (value.startsWith('http://') || value.startsWith('https://')) {
1387
+ // TODO: Maybe check against some list unallowed characters
1388
+ return value;
1389
+ }
1390
+ if (value.startsWith('./') || value.startsWith('../')) {
1391
+ // TODO: Maybe check against some list unallowed characters
1392
+ return value;
1393
+ }
1213
1394
  value = removeEmojis(value);
1214
1395
  value = normalizeToKebabCase(value);
1215
1396
  // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
@@ -1431,7 +1612,7 @@ var MultipleLlmExecutionTools = /** @class */ (function () {
1431
1612
  };
1432
1613
  /**
1433
1614
  * List all available models that can be used
1434
- * This liost is a combination of all available models from all execution tools
1615
+ * This lists is a combination of all available models from all execution tools
1435
1616
  */
1436
1617
  MultipleLlmExecutionTools.prototype.listModels = function () {
1437
1618
  return __awaiter(this, void 0, void 0, function () {
@@ -1477,6 +1658,8 @@ var MultipleLlmExecutionTools = /** @class */ (function () {
1477
1658
  }());
1478
1659
  /**
1479
1660
  * TODO: [🧠][🎛] Aggregating multiple models - have result not only from one first aviable model BUT all of them
1661
+ * 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
1662
+ * Look how `countTotalUsage` (and `cacheLlmTools`) implements it
1480
1663
  */
1481
1664
 
1482
1665
  /**
@@ -1547,100 +1730,9 @@ function arrayableToArray(input) {
1547
1730
  /**
1548
1731
  * The version of the Promptbook library
1549
1732
  */
1550
- var PROMPTBOOK_VERSION = '0.61.0-0';
1733
+ var PROMPTBOOK_VERSION = '0.61.0-10';
1551
1734
  // TODO: !!!! List here all the versions and annotate + put into script
1552
1735
 
1553
- /**
1554
- * Function `addUsage` will add multiple usages into one
1555
- *
1556
- * Note: If you provide 0 values, it returns void usage
1557
- */
1558
- function addUsage() {
1559
- var usageItems = [];
1560
- for (var _i = 0; _i < arguments.length; _i++) {
1561
- usageItems[_i] = arguments[_i];
1562
- }
1563
- var initialStructure = {
1564
- price: { value: 0 },
1565
- input: {
1566
- tokensCount: { value: 0 },
1567
- charactersCount: { value: 0 },
1568
- wordsCount: { value: 0 },
1569
- sentencesCount: { value: 0 },
1570
- linesCount: { value: 0 },
1571
- paragraphsCount: { value: 0 },
1572
- pagesCount: { value: 0 },
1573
- },
1574
- output: {
1575
- tokensCount: { value: 0 },
1576
- charactersCount: { value: 0 },
1577
- wordsCount: { value: 0 },
1578
- sentencesCount: { value: 0 },
1579
- linesCount: { value: 0 },
1580
- paragraphsCount: { value: 0 },
1581
- pagesCount: { value: 0 },
1582
- },
1583
- };
1584
- return usageItems.reduce(function (acc, item) {
1585
- var e_1, _a, e_2, _b;
1586
- var _c;
1587
- acc.price.value += ((_c = item.price) === null || _c === void 0 ? void 0 : _c.value) || 0;
1588
- try {
1589
- for (var _d = __values(Object.keys(acc.input)), _e = _d.next(); !_e.done; _e = _d.next()) {
1590
- var key = _e.value;
1591
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1592
- //@ts-ignore
1593
- if (item.input[key]) {
1594
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1595
- //@ts-ignore
1596
- acc.input[key].value += item.input[key].value || 0;
1597
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1598
- //@ts-ignore
1599
- if (item.input[key].isUncertain) {
1600
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1601
- //@ts-ignore
1602
- acc.input[key].isUncertain = true;
1603
- }
1604
- }
1605
- }
1606
- }
1607
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1608
- finally {
1609
- try {
1610
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
1611
- }
1612
- finally { if (e_1) throw e_1.error; }
1613
- }
1614
- try {
1615
- for (var _f = __values(Object.keys(acc.output)), _g = _f.next(); !_g.done; _g = _f.next()) {
1616
- var key = _g.value;
1617
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1618
- //@ts-ignore
1619
- if (item.output[key]) {
1620
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1621
- //@ts-ignore
1622
- acc.output[key].value += item.output[key].value || 0;
1623
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1624
- //@ts-ignore
1625
- if (item.output[key].isUncertain) {
1626
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1627
- //@ts-ignore
1628
- acc.output[key].isUncertain = true;
1629
- }
1630
- }
1631
- }
1632
- }
1633
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
1634
- finally {
1635
- try {
1636
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
1637
- }
1638
- finally { if (e_2) throw e_2.error; }
1639
- }
1640
- return acc;
1641
- }, initialStructure);
1642
- }
1643
-
1644
1736
  /**
1645
1737
  * Counts number of characters in the text
1646
1738
  */
@@ -1821,10 +1913,7 @@ function createPipelineExecutor(options) {
1821
1913
  var _this = this;
1822
1914
  var pipeline = options.pipeline, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
1823
1915
  var _b = settings.maxExecutionAttempts, maxExecutionAttempts = _b === void 0 ? 3 : _b;
1824
- // TODO: !!!!! Implement new commands
1825
1916
  validatePipeline(pipeline);
1826
- // TODO: !!!!! Do here materialization of still unmaterialized or dynamic knowledge
1827
- // TODO: !!!!! Do here personaToModelRequirements
1828
1917
  var llmTools = joinLlmExecutionTools.apply(void 0, __spreadArray([], __read(arrayableToArray(tools.llm)), false));
1829
1918
  var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
1830
1919
  function executeSingleTemplate(currentTemplate) {
@@ -1899,7 +1988,10 @@ function createPipelineExecutor(options) {
1899
1988
  : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
1900
1989
  parameters: parametersToPass,
1901
1990
  content: replaceParameters(currentTemplate.content, parametersToPass) /* <- [2] */,
1991
+ // <- TODO: !!!!! Apply {context} and knowledges
1992
+ // <- TODO: !!!!! Apply samples
1902
1993
  modelRequirements: currentTemplate.modelRequirements,
1994
+ // <- TODO: !!!!! Apply persona
1903
1995
  expectations: currentTemplate.expectations,
1904
1996
  expectFormat: currentTemplate.expectFormat,
1905
1997
  postprocessing: (currentTemplate.postprocessing || []).map(function (functionName) { return function (result) { return __awaiter(_this, void 0, void 0, function () {
@@ -2345,53 +2437,75 @@ function createPipelineExecutor(options) {
2345
2437
  return pipelineExecutor;
2346
2438
  }
2347
2439
  /**
2440
+ * TODO: [🪂] Pass maxParallelCount here
2441
+ * TODO: [♈] Probbably move expectations from templates to parameters
2348
2442
  * TODO: [🧠] When not meet expectations in PROMPT_DIALOG, make some way to tell the user
2349
2443
  * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
2350
2444
  * Note: CreatePipelineExecutorOptions are just connected to PipelineExecutor so do not extract to types folder
2351
2445
  * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
2446
+ * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
2447
+ */
2448
+
2449
+ /**
2450
+ * Just marks a place of place where should be something implemented
2451
+ * No side effects.
2452
+ *
2453
+ * Note: It can be usefull suppressing eslint errors of unused variables
2454
+ *
2455
+ * @param value any values
2456
+ * @returns void
2352
2457
  */
2458
+ function TODO_USE() {
2459
+ var value = [];
2460
+ for (var _i = 0; _i < arguments.length; _i++) {
2461
+ value[_i] = arguments[_i];
2462
+ }
2463
+ }
2353
2464
 
2354
- function prepareKnowledgeFromMarkdown(options) {
2465
+ /**
2466
+ * @@@
2467
+ */
2468
+ function prepareKnowledgeFromMarkdown(content /* <- TODO: [🖖] (?maybe not) Always the file */, options) {
2355
2469
  return __awaiter(this, void 0, void 0, function () {
2356
- var content, llmTools, _a, isVerbose, collection, prepareKnowledgeFromMarkdownExecutor, _b, prepareTitleExecutor, _c, prepareKeywordsExecutor, _d, result, outputParameters, knowledgeRaw, knowledgeTextPieces, knowledge;
2357
- var _e, _f, _g;
2470
+ var llmTools, _a, maxParallelCount, _b, isVerbose, collection, prepareKnowledgeFromMarkdownExecutor, _c, prepareTitleExecutor, _d, prepareKeywordsExecutor, _e, result, outputParameters, knowledgeRaw, knowledgeTextPieces, knowledge;
2471
+ var _f, _g, _h;
2358
2472
  var _this = this;
2359
- return __generator(this, function (_h) {
2360
- switch (_h.label) {
2473
+ return __generator(this, function (_j) {
2474
+ switch (_j.label) {
2361
2475
  case 0:
2362
- content = options.content, llmTools = options.llmTools, _a = options.isVerbose, isVerbose = _a === void 0 ? false : _a;
2476
+ llmTools = options.llmTools, _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a, _b = options.isVerbose, isVerbose = _b === void 0 ? false : _b;
2477
+ TODO_USE(maxParallelCount); // <- [🪂]
2363
2478
  collection = createCollectionFromJson.apply(void 0, __spreadArray([], __read(PipelineCollection), false));
2364
- _b = createPipelineExecutor;
2365
- _e = {};
2366
- return [4 /*yield*/, collection.getPipelineByUrl('https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md')];
2367
- case 1:
2368
- prepareKnowledgeFromMarkdownExecutor = _b.apply(void 0, [(_e.pipeline = _h.sent(),
2369
- _e.tools = {
2370
- llm: llmTools,
2371
- },
2372
- _e)]);
2373
2479
  _c = createPipelineExecutor;
2374
2480
  _f = {};
2375
- return [4 /*yield*/, collection.getPipelineByUrl('https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md')];
2376
- case 2:
2377
- prepareTitleExecutor = _c.apply(void 0, [(_f.pipeline = _h.sent(),
2481
+ return [4 /*yield*/, collection.getPipelineByUrl('https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md')];
2482
+ case 1:
2483
+ prepareKnowledgeFromMarkdownExecutor = _c.apply(void 0, [(_f.pipeline = _j.sent(),
2378
2484
  _f.tools = {
2379
2485
  llm: llmTools,
2380
2486
  },
2381
2487
  _f)]);
2382
2488
  _d = createPipelineExecutor;
2383
2489
  _g = {};
2384
- return [4 /*yield*/, collection.getPipelineByUrl('https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md')];
2385
- case 3:
2386
- prepareKeywordsExecutor = _d.apply(void 0, [(_g.pipeline = _h.sent(),
2490
+ return [4 /*yield*/, collection.getPipelineByUrl('https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md')];
2491
+ case 2:
2492
+ prepareTitleExecutor = _d.apply(void 0, [(_g.pipeline = _j.sent(),
2387
2493
  _g.tools = {
2388
2494
  llm: llmTools,
2389
2495
  },
2390
2496
  _g)]);
2497
+ _e = createPipelineExecutor;
2498
+ _h = {};
2499
+ return [4 /*yield*/, collection.getPipelineByUrl('https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md')];
2500
+ case 3:
2501
+ prepareKeywordsExecutor = _e.apply(void 0, [(_h.pipeline = _j.sent(),
2502
+ _h.tools = {
2503
+ llm: llmTools,
2504
+ },
2505
+ _h)]);
2391
2506
  return [4 /*yield*/, prepareKnowledgeFromMarkdownExecutor({ content: content })];
2392
2507
  case 4:
2393
- result = _h.sent();
2394
- // TODO: [0] !!! Aggeregate usage
2508
+ result = _j.sent();
2395
2509
  assertsExecutionSuccessful(result);
2396
2510
  outputParameters = result.outputParameters;
2397
2511
  knowledgeRaw = outputParameters.knowledge;
@@ -2400,9 +2514,9 @@ function prepareKnowledgeFromMarkdown(options) {
2400
2514
  console.info('knowledgeTextPieces:', knowledgeTextPieces);
2401
2515
  }
2402
2516
  return [4 /*yield*/, Promise.all(
2403
- // TODO: !!! Do not send all at once but in chunks
2517
+ // TODO: [🪂] !! Do not send all at once but in chunks
2404
2518
  knowledgeTextPieces.map(function (knowledgeTextPiece, i) { return __awaiter(_this, void 0, void 0, function () {
2405
- var name, title, content, keywords, index, sources, titleResult, _a, titleRaw, keywordsResult, _b, keywordsRaw, embeddingResult, error_1;
2519
+ var name, title, content, keywords, index, titleResult, _a, titleRaw, keywordsResult, _b, keywordsRaw, embeddingResult, error_1;
2406
2520
  return __generator(this, function (_c) {
2407
2521
  switch (_c.label) {
2408
2522
  case 0:
@@ -2411,12 +2525,6 @@ function prepareKnowledgeFromMarkdown(options) {
2411
2525
  content = spaceTrim(knowledgeTextPiece);
2412
2526
  keywords = [];
2413
2527
  index = [];
2414
- sources = [
2415
- {
2416
- title: 'Markdown document' /* <- TODO: !!! Unhardcode */,
2417
- href: '#' /* <- TODO: !!! Unhardcode */,
2418
- },
2419
- ];
2420
2528
  _c.label = 1;
2421
2529
  case 1:
2422
2530
  _c.trys.push([1, 7, , 8]);
@@ -2451,7 +2559,6 @@ function prepareKnowledgeFromMarkdown(options) {
2451
2559
  })];
2452
2560
  case 5:
2453
2561
  embeddingResult = _c.sent();
2454
- // TODO: [0] !!! Aggeregate usage embeddingResult.usage
2455
2562
  index.push({
2456
2563
  modelName: embeddingResult.modelName,
2457
2564
  position: embeddingResult.content,
@@ -2469,37 +2576,404 @@ function prepareKnowledgeFromMarkdown(options) {
2469
2576
  content: content,
2470
2577
  keywords: keywords,
2471
2578
  index: index,
2472
- sources: sources,
2579
+ // <- TODO: [☀] sources,
2473
2580
  }];
2474
2581
  }
2475
2582
  });
2476
2583
  }); }))];
2477
2584
  case 5:
2478
- knowledge = _h.sent();
2585
+ knowledge = _j.sent();
2479
2586
  return [2 /*return*/, knowledge];
2480
2587
  }
2481
2588
  });
2482
2589
  });
2483
2590
  }
2484
2591
  /**
2485
- * 11:11
2592
+ * TODO: [🪂] Do it in parallel 11:11
2593
+ * Note: No need to aggregate usage here, it is done by intercepting the llmTools
2486
2594
  */
2487
2595
 
2488
2596
  /**
2489
- * Removes Markdown formatting tags from a string.
2597
+ * Prepares the knowle
2490
2598
  *
2491
- * @param {string} str - The string to remove Markdown tags from.
2492
- * @returns {string} The input string with all Markdown tags removed.
2599
+ * @see https://github.com/webgptorg/promptbook/discussions/41
2600
+ * @private within the package
2493
2601
  */
2494
- function removeMarkdownFormatting(str) {
2495
- // Remove bold formatting
2496
- str = str.replace(/\*\*(.*?)\*\*/g, '$1');
2497
- // Remove italic formatting
2498
- str = str.replace(/\*(.*?)\*/g, '$1');
2499
- // Remove code formatting
2500
- str = str.replace(/`(.*?)`/g, '$1');
2501
- return str;
2502
- }
2602
+ function prepareKnowledgePieces(knowledgeSources, options) {
2603
+ return __awaiter(this, void 0, void 0, function () {
2604
+ var _a, maxParallelCount, knowledgePrepared;
2605
+ var _this = this;
2606
+ return __generator(this, function (_b) {
2607
+ switch (_b.label) {
2608
+ case 0:
2609
+ _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a;
2610
+ knowledgePrepared = [];
2611
+ return [4 /*yield*/, forEachAsync(knowledgeSources, { maxParallelCount: maxParallelCount }, function (knowledgeSource) { return __awaiter(_this, void 0, void 0, function () {
2612
+ var partialPieces, pieces;
2613
+ return __generator(this, function (_a) {
2614
+ switch (_a.label) {
2615
+ case 0: return [4 /*yield*/, prepareKnowledgeFromMarkdown(knowledgeSource.source, // <- TODO: !!!!! Unhardcode markdown, detect which type it is
2616
+ options)];
2617
+ case 1:
2618
+ partialPieces = _a.sent();
2619
+ pieces = partialPieces.map(function (partialPiece) { return (__assign(__assign({}, partialPiece), { sources: [
2620
+ {
2621
+ name: knowledgeSource.name,
2622
+ // line, column <- TODO: [☀]
2623
+ // <- TODO: [❎]
2624
+ },
2625
+ ] })); });
2626
+ knowledgePrepared.push.apply(knowledgePrepared, __spreadArray([], __read(pieces), false));
2627
+ return [2 /*return*/];
2628
+ }
2629
+ });
2630
+ }); })];
2631
+ case 1:
2632
+ _b.sent();
2633
+ return [2 /*return*/, knowledgePrepared];
2634
+ }
2635
+ });
2636
+ });
2637
+ }
2638
+ /*
2639
+ TODO: [🧊] This is how it can look in future
2640
+ > type PrepareKnowledgeKnowledge = {
2641
+ > /**
2642
+ > * Unprepared knowledge
2643
+ > * /
2644
+ > readonly knowledgeSources: Array<KnowledgeSourceJson>;
2645
+ > };
2646
+ >
2647
+ > export async function prepareKnowledgePieces(
2648
+ > knowledge: PrepareKnowledgeKnowledge,
2649
+ > options: PrepareOptions,
2650
+ > ):
2651
+ */
2652
+ /**
2653
+ * TODO: [🧊] In future one preparation can take data from previous preparation and save tokens and time
2654
+ * Put `knowledgePieces` into `PrepareKnowledgeOptions`
2655
+ * TODO: [🪂] More than max things can run in parallel by acident [1,[2a,2b,_],[3a,3b,_]]
2656
+ * TODO: [🧠][❎] Do here propper M:N mapping
2657
+ * [x] One source can make multiple pieces
2658
+ * [ ] One piece can have multiple sources
2659
+ */
2660
+
2661
+ /**
2662
+ * Prepares the persona for the pipeline
2663
+ *
2664
+ * @see https://github.com/webgptorg/promptbook/discussions/22
2665
+ * @private within the package
2666
+ */
2667
+ function preparePersona(personaDescription, options) {
2668
+ return __awaiter(this, void 0, void 0, function () {
2669
+ var llmTools, _a, isVerbose, collection, preparePersonaExecutor, _b, availableModels, availableModelNames, result, outputParameters, modelRequirementsRaw, modelRequirements, modelName, systemMessage, temperature;
2670
+ var _c;
2671
+ return __generator(this, function (_d) {
2672
+ switch (_d.label) {
2673
+ case 0:
2674
+ llmTools = options.llmTools, _a = options.isVerbose, isVerbose = _a === void 0 ? false : _a;
2675
+ collection = createCollectionFromJson.apply(void 0, __spreadArray([], __read(PipelineCollection), false));
2676
+ _b = createPipelineExecutor;
2677
+ _c = {};
2678
+ return [4 /*yield*/, collection.getPipelineByUrl('https://promptbook.studio/promptbook/prepare-persona.ptbk.md')];
2679
+ case 1:
2680
+ preparePersonaExecutor = _b.apply(void 0, [(_c.pipeline = _d.sent(),
2681
+ _c.tools = {
2682
+ llm: llmTools,
2683
+ },
2684
+ _c)]);
2685
+ return [4 /*yield*/, llmTools.listModels()];
2686
+ case 2:
2687
+ availableModels = _d.sent();
2688
+ availableModelNames = availableModels
2689
+ .filter(function (_a) {
2690
+ var modelVariant = _a.modelVariant;
2691
+ return modelVariant === 'CHAT';
2692
+ })
2693
+ .map(function (_a) {
2694
+ var modelName = _a.modelName;
2695
+ return modelName;
2696
+ })
2697
+ .join(',');
2698
+ return [4 /*yield*/, preparePersonaExecutor({ availableModelNames: availableModelNames, personaDescription: personaDescription })];
2699
+ case 3:
2700
+ result = _d.sent();
2701
+ assertsExecutionSuccessful(result);
2702
+ outputParameters = result.outputParameters;
2703
+ modelRequirementsRaw = outputParameters.modelRequirements;
2704
+ modelRequirements = JSON.parse(modelRequirementsRaw);
2705
+ if (isVerbose) {
2706
+ console.info("PERSONA ".concat(personaDescription), modelRequirements);
2707
+ }
2708
+ modelName = modelRequirements.modelName, systemMessage = modelRequirements.systemMessage, temperature = modelRequirements.temperature;
2709
+ // TODO: !!! Check validity of `modelName`
2710
+ // TODO: !!! Check validity of `systemMessage`
2711
+ // TODO: !!! Check validity of `temperature`
2712
+ return [2 /*return*/, {
2713
+ modelVariant: 'CHAT',
2714
+ modelName: modelName,
2715
+ systemMessage: systemMessage,
2716
+ temperature: temperature,
2717
+ }];
2718
+ }
2719
+ });
2720
+ });
2721
+ }
2722
+
2723
+ /**
2724
+ * Prepare pipeline from string (markdown) format to JSON format
2725
+ *
2726
+ * Note: This function does not validate logic of the pipeline
2727
+ * Note: This function acts as part of compilation process
2728
+ */
2729
+ function preparePipeline(pipeline, options) {
2730
+ return __awaiter(this, void 0, void 0, function () {
2731
+ var _a, maxParallelCount,
2732
+ /*
2733
+ <- TODO: [🧠][0] `promptbookVersion` */
2734
+ knowledgeSources /*
2735
+ <- TODO: [🧊] `knowledgePieces` */, personas /*
2736
+ <- TODO: [🧊] `preparations` */, currentPreparation, preparations, preparedPersonas, knowledgeSourcesPrepared, partialknowledgePiecesPrepared, knowledgePiecesPrepared;
2737
+ var _this = this;
2738
+ return __generator(this, function (_b) {
2739
+ switch (_b.label) {
2740
+ case 0:
2741
+ _a = options.maxParallelCount, maxParallelCount = _a === void 0 ? MAX_PARALLEL_COUNT : _a;
2742
+ knowledgeSources = pipeline.knowledgeSources, personas = pipeline.personas;
2743
+ currentPreparation = {
2744
+ id: 1,
2745
+ // TODO: [🍥]> date: $currentDate(),
2746
+ promptbookVersion: PROMPTBOOK_VERSION,
2747
+ modelUsage: addUsage(),
2748
+ };
2749
+ preparations = [
2750
+ // ...preparations
2751
+ // <- TODO: [🧊]
2752
+ currentPreparation,
2753
+ ];
2754
+ preparedPersonas = new Array(personas.length);
2755
+ 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 () {
2756
+ var modelRequirements, preparedPersona;
2757
+ return __generator(this, function (_a) {
2758
+ switch (_a.label) {
2759
+ case 0: return [4 /*yield*/, preparePersona(persona.description, options)];
2760
+ case 1:
2761
+ modelRequirements = _a.sent();
2762
+ preparedPersona = __assign(__assign({}, persona), { modelRequirements: modelRequirements, preparationIds: [/* TODO: [🧊] -> */ currentPreparation.id] });
2763
+ preparedPersonas[index] = preparedPersona;
2764
+ return [2 /*return*/];
2765
+ }
2766
+ });
2767
+ }); })];
2768
+ case 1:
2769
+ _b.sent();
2770
+ knowledgeSourcesPrepared = knowledgeSources.map(function (source) { return (__assign(__assign({}, source), { preparationIds: [/* TODO: [🧊] -> */ currentPreparation.id] })); });
2771
+ return [4 /*yield*/, prepareKnowledgePieces(knowledgeSources /* <- TODO: [🧊] {knowledgeSources, knowledgePieces} */, options)];
2772
+ case 2:
2773
+ partialknowledgePiecesPrepared = _b.sent();
2774
+ knowledgePiecesPrepared = partialknowledgePiecesPrepared.map(function (piece) { return (__assign(__assign({}, piece), { preparationIds: [/* TODO: [🧊] -> */ currentPreparation.id] })); });
2775
+ // ----- /Knowledge preparation -----
2776
+ return [2 /*return*/, __assign(__assign({}, pipeline), { knowledgeSources: knowledgeSourcesPrepared, knowledgePieces: knowledgePiecesPrepared, personas: preparedPersonas, preparations: preparations })];
2777
+ }
2778
+ });
2779
+ });
2780
+ }
2781
+ /**
2782
+ * TODO: Write tests for `preparePipeline`
2783
+ * TODO: [🏏] Leverage the batch API and build queues @see https://platform.openai.com/docs/guides/batch
2784
+ * TODO: [🧊] In future one preparation can take data from previous preparation and save tokens and time
2785
+ * TODO: !!!!! Use here countTotalUsage
2786
+ * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
2787
+ */
2788
+
2789
+ /**
2790
+ * Tests if given string is valid URL.
2791
+ *
2792
+ * Note: This does not check if the file exists only if the path is valid
2793
+ */
2794
+ function isValidFilePath(filePath) {
2795
+ if (typeof filePath !== 'string') {
2796
+ return false;
2797
+ }
2798
+ var filePathSlashes = filePath.split('\\').join('/');
2799
+ // Absolute Unix path: /hello.txt
2800
+ if (/^(\/)/i.test(filePathSlashes)) {
2801
+ return true;
2802
+ }
2803
+ // Absolute Windows path: /hello.txt
2804
+ if (/^([A-Z]{1,2}:\/?)\//i.test(filePathSlashes)) {
2805
+ return true;
2806
+ }
2807
+ // Relative path: ./hello.txt
2808
+ if (/^(\.\.?\/)+/i.test(filePathSlashes)) {
2809
+ return true;
2810
+ }
2811
+ return false;
2812
+ }
2813
+
2814
+ /**
2815
+ * Parses the knowledge command
2816
+ *
2817
+ * @see ./KNOWLEDGE-README.md for more details
2818
+ * @private within the commands folder
2819
+ */
2820
+ var knowledgeCommandParser = {
2821
+ /**
2822
+ * Name of the command
2823
+ */
2824
+ name: 'KNOWLEDGE',
2825
+ /**
2826
+ * BOILERPLATE command can be used in:
2827
+ */
2828
+ usagePlaces: ['PIPELINE_HEAD'],
2829
+ /**
2830
+ * Description of the KNOWLEDGE command
2831
+ */
2832
+ description: "Tells promptbook which external knowledge to use",
2833
+ /**
2834
+ * Link to discussion
2835
+ */
2836
+ discussionUrl: 'https://github.com/webgptorg/promptbook/discussions/41',
2837
+ /**
2838
+ * Example usages of the KNOWLEDGE command
2839
+ */
2840
+ examples: [
2841
+ 'KNOWLEDGE https://www.pavolhejny.com/',
2842
+ 'KNOWLEDGE ./hejny-cv.txt',
2843
+ 'KNOWLEDGE ./hejny-cv.md',
2844
+ 'KNOWLEDGE ./hejny-cv.pdf',
2845
+ 'KNOWLEDGE ./hejny-cv.docx',
2846
+ ],
2847
+ /**
2848
+ * Parses the KNOWLEDGE command
2849
+ */
2850
+ parse: function (input) {
2851
+ var args = input.args;
2852
+ var source = args[0];
2853
+ if (source === undefined) {
2854
+ throw new ParsingError("Source is not defined");
2855
+ }
2856
+ if (source.startsWith('http://')) {
2857
+ throw new ParsingError("Source is not secure");
2858
+ }
2859
+ if (!(isValidFilePath(source) || isValidUrl(source))) {
2860
+ throw new ParsingError("Source not valid");
2861
+ }
2862
+ if (source.startsWith('../') || source.startsWith('/') || /^[A-Z]:[\\/]+/i.test(source)) {
2863
+ throw new ParsingError("Source cannot be outside of the .ptbk.md folder");
2864
+ }
2865
+ return {
2866
+ type: 'KNOWLEDGE',
2867
+ source: source,
2868
+ };
2869
+ },
2870
+ /**
2871
+ * Note: Prototype of [🍧] (remove this comment after full implementation)
2872
+ */
2873
+ applyToPipelineJson: function (pipelineJson, personaCommand) {
2874
+ var source = personaCommand.source;
2875
+ var name = titleToName(source);
2876
+ pipelineJson.knowledgeSources.push({
2877
+ name: name,
2878
+ source: source,
2879
+ });
2880
+ },
2881
+ };
2882
+
2883
+ /**
2884
+ * Parses the persona command
2885
+ *
2886
+ * @see ./PERSONA-README.md for more details
2887
+ * @private within the commands folder
2888
+ */
2889
+ var personaCommandParser = {
2890
+ /**
2891
+ * Name of the command
2892
+ */
2893
+ name: 'PERSONA',
2894
+ /**
2895
+ * Aliases for the PERSONA command
2896
+ */
2897
+ aliasNames: ['PERSON'],
2898
+ /**
2899
+ * PERSONA command can be used in:
2900
+ */
2901
+ usagePlaces: ['PIPELINE_HEAD', 'PIPELINE_TEMPLATE'],
2902
+ /**
2903
+ * Description of the PERSONA command
2904
+ */
2905
+ description: "Persona command is used to specify who the system is, it will be transformed into system message, top_t,...",
2906
+ /**
2907
+ * Link to discussion
2908
+ */
2909
+ discussionUrl: 'https://github.com/webgptorg/promptbook/discussions/22',
2910
+ /**
2911
+ * Example usages of the PERSONA command
2912
+ */
2913
+ examples: ['PERSONA Jane, skilled copywriter', 'PERSONA Joe, male 28 years old, programmer'],
2914
+ /**
2915
+ * Parses the PERSONA command
2916
+ */
2917
+ parse: function (input) {
2918
+ var rawArgs = input.rawArgs;
2919
+ var _a = __read(rawArgs.split(/[,;:]/, 2), 2), personaNameRaw = _a[0], personaDescriptionRaw = _a[1];
2920
+ var personaName = (personaNameRaw || '').trim();
2921
+ if (personaName === '') {
2922
+ throw new ParsingError("You must set name for the persona");
2923
+ }
2924
+ var personaDescription = (personaDescriptionRaw || '').trim();
2925
+ if (personaDescription === '') {
2926
+ personaDescription = null;
2927
+ }
2928
+ return {
2929
+ type: 'PERSONA',
2930
+ personaName: personaName,
2931
+ personaDescription: personaDescription,
2932
+ };
2933
+ },
2934
+ /**
2935
+ * Note: Prototype of [🍧] (remove this comment after full implementation)
2936
+ */
2937
+ applyToPipelineJson: function (pipelineJson, personaCommand) {
2938
+ var personaName = personaCommand.personaName, personaDescription = personaCommand.personaDescription;
2939
+ var persona = pipelineJson.personas.find(function (persona) { return persona.name === personaName; });
2940
+ if (persona === undefined) {
2941
+ pipelineJson.personas.push({
2942
+ name: personaName,
2943
+ description: personaDescription || '',
2944
+ });
2945
+ return;
2946
+ }
2947
+ if (persona.description === personaDescription) {
2948
+ return;
2949
+ }
2950
+ if (personaDescription === null) {
2951
+ return;
2952
+ }
2953
+ if (persona.description === '') {
2954
+ persona.description = personaDescription;
2955
+ return;
2956
+ }
2957
+ 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 ")));
2958
+ persona.description += spaceTrim('\n\n' + personaDescription);
2959
+ },
2960
+ };
2961
+
2962
+ /**
2963
+ * Removes Markdown formatting tags from a string.
2964
+ *
2965
+ * @param {string} str - The string to remove Markdown tags from.
2966
+ * @returns {string} The input string with all Markdown tags removed.
2967
+ */
2968
+ function removeMarkdownFormatting(str) {
2969
+ // Remove bold formatting
2970
+ str = str.replace(/\*\*(.*?)\*\*/g, '$1');
2971
+ // Remove italic formatting
2972
+ str = str.replace(/\*(.*?)\*/g, '$1');
2973
+ // Remove code formatting
2974
+ str = str.replace(/`(.*?)`/g, '$1');
2975
+ return str;
2976
+ }
2503
2977
 
2504
2978
  function normalizeTo_SCREAMING_CASE(text) {
2505
2979
  var e_1, _a;
@@ -2656,7 +3130,6 @@ var blockCommandParser = {
2656
3130
  normalized = normalized.split('EXAMPLE').join('SAMPLE');
2657
3131
  var blockTypes = BlockTypes.filter(function (blockType) { return normalized.includes(blockType); });
2658
3132
  if (blockTypes.length !== 1) {
2659
- // console.log('!!!', { blockType });
2660
3133
  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 "); }));
2661
3134
  }
2662
3135
  // TODO: !!!! Not supported yet
@@ -2669,6 +3142,7 @@ var blockCommandParser = {
2669
3142
 
2670
3143
  /**
2671
3144
  * Units of text measurement
3145
+ * @see https://github.com/webgptorg/promptbook/discussions/30
2672
3146
  */
2673
3147
  var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'LINES', 'PARAGRAPHS', 'PAGES'];
2674
3148
  /**
@@ -2904,94 +3378,15 @@ var jokerCommandParser = {
2904
3378
  },
2905
3379
  };
2906
3380
 
2907
- /**
2908
- * Tests if given string is valid URL.
2909
- *
2910
- * Note: This does not check if the file exists only if the path is valid
2911
- */
2912
- function isValidFilePath(filePath) {
2913
- if (typeof filePath !== 'string') {
2914
- return false;
2915
- }
2916
- var filePathSlashes = filePath.split('\\').join('/');
2917
- // Absolute Unix path: /hello.txt
2918
- if (/^(\/)/i.test(filePathSlashes)) {
2919
- return true;
2920
- }
2921
- // Absolute Windows path: /hello.txt
2922
- if (/^([A-Z]{1,2}:\/?)\//i.test(filePathSlashes)) {
2923
- return true;
2924
- }
2925
- // Relative path: ./hello.txt
2926
- if (/^(\.\.?\/)+/i.test(filePathSlashes)) {
2927
- return true;
2928
- }
2929
- return false;
2930
- }
2931
-
2932
- /**
2933
- * Parses the knowledge command
2934
- *
2935
- * @see ./KNOWLEDGE-README.md for more details
2936
- * @private within the commands folder
2937
- */
2938
- var knowledgeCommandParser = {
2939
- /**
2940
- * Name of the command
2941
- */
2942
- name: 'KNOWLEDGE',
2943
- /**
2944
- * BOILERPLATE command can be used in:
2945
- */
2946
- usagePlaces: ['PIPELINE_HEAD'],
2947
- /**
2948
- * Description of the KNOWLEDGE command
2949
- */
2950
- description: "Tells promptbook which external knowledge to use",
2951
- /**
2952
- * Link to discussion
2953
- */
2954
- discussionUrl: 'https://github.com/webgptorg/promptbook/discussions/41',
2955
- /**
2956
- * Example usages of the KNOWLEDGE command
2957
- */
2958
- examples: [
2959
- 'KNOWLEDGE https://www.pavolhejny.com/',
2960
- 'KNOWLEDGE ./hejny-cv.txt',
2961
- 'KNOWLEDGE ./hejny-cv.md',
2962
- 'KNOWLEDGE ./hejny-cv.pdf',
2963
- 'KNOWLEDGE ./hejny-cv.docx',
2964
- ],
2965
- /**
2966
- * Parses the KNOWLEDGE command
2967
- */
2968
- parse: function (input) {
2969
- var args = input.args;
2970
- var source = args[0];
2971
- if (source === undefined) {
2972
- throw new ParsingError("Source is not defined");
2973
- }
2974
- if (source.startsWith('http://')) {
2975
- throw new ParsingError("Source is not secure");
2976
- }
2977
- if (!(isValidFilePath(source) || isValidUrl(source))) {
2978
- throw new ParsingError("Source not valid");
2979
- }
2980
- if (source.startsWith('../') || source.startsWith('/') || /^[A-Z]:[\\/]+/i.test(source)) {
2981
- throw new ParsingError("Source cannot be outside of the .ptbk.md folder");
2982
- }
2983
- return {
2984
- type: 'KNOWLEDGE',
2985
- source: source,
2986
- };
2987
- },
2988
- };
2989
-
2990
3381
  var MODEL_VARIANTS = ['COMPLETION', 'CHAT', 'EMBEDDING' /* <- TODO [🏳] */ /* <- [🤖] */];
2991
3382
  /**
3383
+ * TODO: [🈁] `seed` should maybe be somewhere else (not in `ModelRequirements`) (simmilar that `user` identification is not here)
3384
+ * TODO: [🧠][💱] Add more model options: `stop_token`, `logit_bias`, `logprobs` (`top_logprobs`), `top_k`, `top_p`, `presence_penalty`, `frequency_penalty`, `bestOf`, `logitBias`, `logitBiasType`,...
3385
+ * [💱] Probbably keep using just `temperature` in Promptbook (not `top_k` and `top_p`)
3386
+ * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
2992
3387
  * TODO: Maybe figure out better word than "variant"
2993
3388
  * TODO: Add here more requirement options like max context size, max tokens, etc.
2994
- * TODO: [👙][🧠] Just selecting gpt3 or gpt4 level of model
3389
+ * TODO: [💕][🧠] Just selecting gpt3 or gpt4 level of model
2995
3390
  */
2996
3391
 
2997
3392
  /**
@@ -3130,59 +3525,6 @@ var parameterCommandParser = {
3130
3525
  },
3131
3526
  };
3132
3527
 
3133
- /**
3134
- * Parses the persona command
3135
- *
3136
- * @see ./PERSONA-README.md for more details
3137
- * @private within the commands folder
3138
- */
3139
- var personaCommandParser = {
3140
- /**
3141
- * Name of the command
3142
- */
3143
- name: 'PERSONA',
3144
- /**
3145
- * Aliases for the PERSONA command
3146
- */
3147
- aliasNames: ['PERSON'],
3148
- /**
3149
- * PERSONA command can be used in:
3150
- */
3151
- usagePlaces: ['PIPELINE_HEAD', 'PIPELINE_TEMPLATE'],
3152
- /**
3153
- * Description of the PERSONA command
3154
- */
3155
- description: "Persona command is used to specify who the system is, it will be transformed into system message, top_t,...",
3156
- /**
3157
- * Link to discussion
3158
- */
3159
- discussionUrl: 'https://github.com/webgptorg/promptbook/discussions/22',
3160
- /**
3161
- * Example usages of the PERSONA command
3162
- */
3163
- examples: ['PERSONA Jane, skilled copywriter', 'PERSONA Joe, male 28 years old, programmer'],
3164
- /**
3165
- * Parses the PERSONA command
3166
- */
3167
- parse: function (input) {
3168
- var rawArgs = input.rawArgs;
3169
- var _a = __read(rawArgs.split(/[,;:]/, 2), 2), personaNameRaw = _a[0], personaDescriptionRaw = _a[1];
3170
- var personaName = (personaNameRaw || '').trim();
3171
- if (personaName === '') {
3172
- throw new ParsingError("You must set name for the persona");
3173
- }
3174
- var personaDescription = (personaDescriptionRaw || '').trim();
3175
- if (personaDescription === '') {
3176
- personaDescription = null;
3177
- }
3178
- return {
3179
- type: 'PERSONA',
3180
- personaName: personaName,
3181
- personaDescription: personaDescription,
3182
- };
3183
- },
3184
- };
3185
-
3186
3528
  function isValidJavascriptName(javascriptName) {
3187
3529
  if (typeof javascriptName !== 'string') {
3188
3530
  return false;
@@ -3400,7 +3742,8 @@ var actionCommandParser = {
3400
3742
  * Parses the ACTION command
3401
3743
  */
3402
3744
  parse: function (input) {
3403
- input.args;
3745
+ var args = input.args;
3746
+ TODO_USE(args);
3404
3747
  return {
3405
3748
  type: 'ACTION',
3406
3749
  };
@@ -3438,7 +3781,8 @@ var instrumentCommandParser = {
3438
3781
  * Parses the INSTRUMENT command
3439
3782
  */
3440
3783
  parse: function (input) {
3441
- input.args;
3784
+ var args = input.args;
3785
+ TODO_USE(args);
3442
3786
  return {
3443
3787
  type: 'INSTRUMENT',
3444
3788
  };
@@ -3620,7 +3964,6 @@ function parseCommandVariant(input) {
3620
3964
  var _loop_1 = function (commandParser) {
3621
3965
  var name_1 = commandParser.name, aliasNames = commandParser.aliasNames, deprecatedNames = commandParser.deprecatedNames, parse = commandParser.parse;
3622
3966
  var names = __spreadArray(__spreadArray([name_1], __read((aliasNames || [])), false), __read((deprecatedNames || [])), false);
3623
- // console.log('!!!', { commandName, names });
3624
3967
  if (names.includes(commandName)) {
3625
3968
  try {
3626
3969
  return { value: parse({ usagePlace: usagePlace, raw: raw, rawArgs: rawArgs, normalized: normalized, args: args }) };
@@ -3730,25 +4073,42 @@ function extractAllBlocksFromMarkdown(markdown) {
3730
4073
  var e_1, _a;
3731
4074
  var codeBlocks = [];
3732
4075
  var lines = markdown.split('\n');
4076
+ // Note: [0] Ensure that the last block notated by gt > will be closed
4077
+ lines.push('');
3733
4078
  var currentCodeBlock = null;
3734
4079
  try {
3735
4080
  for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
3736
4081
  var line = lines_1_1.value;
4082
+ if (line.startsWith('> ') || line === '>') {
4083
+ if (currentCodeBlock === null) {
4084
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
4085
+ } /* not else */
4086
+ if (currentCodeBlock.blockNotation === '>') {
4087
+ if (currentCodeBlock.content !== '') {
4088
+ currentCodeBlock.content += '\n';
4089
+ }
4090
+ currentCodeBlock.content += line.slice(2);
4091
+ }
4092
+ }
4093
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
4094
+ codeBlocks.push(currentCodeBlock);
4095
+ currentCodeBlock = null;
4096
+ }
4097
+ /* not else */
3737
4098
  if (line.startsWith('```')) {
3738
4099
  var language = line.slice(3).trim() || null;
3739
4100
  if (currentCodeBlock === null) {
3740
- currentCodeBlock = { language: language, content: '' };
4101
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
3741
4102
  }
3742
4103
  else {
3743
4104
  if (language !== null) {
3744
- // [🌻]
3745
- throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
4105
+ throw new ParsingError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
3746
4106
  }
3747
4107
  codeBlocks.push(currentCodeBlock);
3748
4108
  currentCodeBlock = null;
3749
4109
  }
3750
4110
  }
3751
- else if (currentCodeBlock !== null) {
4111
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
3752
4112
  if (currentCodeBlock.content !== '') {
3753
4113
  currentCodeBlock.content += '\n';
3754
4114
  }
@@ -3764,11 +4124,13 @@ function extractAllBlocksFromMarkdown(markdown) {
3764
4124
  finally { if (e_1) throw e_1.error; }
3765
4125
  }
3766
4126
  if (currentCodeBlock !== null) {
3767
- // [🌻]
3768
- throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
4127
+ throw new ParsingError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
3769
4128
  }
3770
4129
  return codeBlocks;
3771
4130
  }
4131
+ /**
4132
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
4133
+ */
3772
4134
 
3773
4135
  /**
3774
4136
  * Extracts exactly ONE code block from markdown.
@@ -3786,13 +4148,12 @@ function extractAllBlocksFromMarkdown(markdown) {
3786
4148
  function extractOneBlockFromMarkdown(markdown) {
3787
4149
  var codeBlocks = extractAllBlocksFromMarkdown(markdown);
3788
4150
  if (codeBlocks.length !== 1) {
3789
- // TODO: Report more specific place where the error happened
3790
- throw new Error(/* <- [🌻] */ 'There should be exactly one code block in the markdown');
4151
+ 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 "); }));
3791
4152
  }
3792
4153
  return codeBlocks[0];
3793
4154
  }
3794
4155
  /***
3795
- * TODO: [🍓][🌻] !!! Decide of this is internal util, external util OR validator/postprocessor
4156
+ * TODO: [🍓][🌻] Decide of this is internal util, external util OR validator/postprocessor
3796
4157
  */
3797
4158
 
3798
4159
  /**
@@ -3802,13 +4163,13 @@ function parseMarkdownSection(value) {
3802
4163
  var _a, _b;
3803
4164
  var lines = value.split('\n');
3804
4165
  if (!lines[0].startsWith('#')) {
3805
- throw new Error('Markdown section must start with heading');
4166
+ throw new ParsingError('Markdown section must start with heading');
3806
4167
  }
3807
4168
  var title = lines[0].replace(/^#+\s*/, '');
3808
4169
  var level = (_b = (_a = lines[0].match(/^#+/)) === null || _a === void 0 ? void 0 : _a[0].length) !== null && _b !== void 0 ? _b : 0;
3809
4170
  var content = spaceTrim(lines.slice(1).join('\n'));
3810
4171
  if (level < 1 || level > 6) {
3811
- throw new Error('Markdown section must have heading level between 1 and 6');
4172
+ throw new ParsingError('Markdown section must have heading level between 1 and 6');
3812
4173
  }
3813
4174
  return { title: title, level: level, content: content };
3814
4175
  }
@@ -4134,14 +4495,14 @@ function extractParametersFromPromptTemplate(promptTemplate) {
4134
4495
  */
4135
4496
 
4136
4497
  /**
4137
- * Compile promptbook from string (markdown) format to JSON format synchronously
4498
+ * Compile pipeline from string (markdown) format to JSON format synchronously
4138
4499
  *
4139
- * Note: There are two similar functions:
4500
+ * Note: There are 3 similar functions:
4140
4501
  * - `pipelineStringToJson` **(preferred)** - which propperly compiles the promptbook and use embedding for external knowledge
4141
4502
  * - `pipelineStringToJsonSync` - use only if you need to compile promptbook synchronously and it contains NO external knowledge
4503
+ * - `preparePipeline` - just one step in the compilation process
4142
4504
  *
4143
4505
  * @param pipelineString {Promptbook} in string markdown format (.ptbk.md)
4144
- * @param options - Options and tools for the compilation
4145
4506
  * @returns {Promptbook} compiled in JSON format (.ptbk.json)
4146
4507
  * @throws {ParsingError} if the promptbook string is not valid
4147
4508
  *
@@ -4157,7 +4518,10 @@ function pipelineStringToJsonSync(pipelineString) {
4157
4518
  description: undefined /* <- Note: Putting here placeholder to keep `description` on top at final JSON */,
4158
4519
  parameters: [],
4159
4520
  promptTemplates: [],
4160
- knowledge: [],
4521
+ knowledgeSources: [],
4522
+ knowledgePieces: [],
4523
+ personas: [],
4524
+ preparations: [],
4161
4525
  };
4162
4526
  // =============================================================
4163
4527
  // Note: 1️⃣ Parsing of the markdown into object
@@ -4187,7 +4551,7 @@ function pipelineStringToJsonSync(pipelineString) {
4187
4551
  existingParameter.description &&
4188
4552
  existingParameter.description !== parameterDescription &&
4189
4553
  parameterDescription) {
4190
- 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 "); }));
4554
+ 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 "); }));
4191
4555
  }
4192
4556
  if (existingParameter) {
4193
4557
  if (parameterDescription) {
@@ -4206,11 +4570,12 @@ function pipelineStringToJsonSync(pipelineString) {
4206
4570
  // =============================================================
4207
4571
  // Note: 3️⃣ Process pipeline head
4208
4572
  pipelineJson.title = pipelineHead.title;
4209
- // TODO: [1] DRY description
4573
+ // TODO: [🎾][1] DRY description
4210
4574
  var description = pipelineHead.content;
4211
- // Note: Remove codeblocks - TODO: Maybe put this into util (exported from `@promptbool/utils`)
4575
+ // Note: Remove codeblocks - TODO: [🎾] Make util removeAllBlocksFromMarkdown (exported from `@promptbool/utils`)
4212
4576
  description = description.split(/^```.*^```/gms).join('');
4213
- //Note: Remove lists and return statement - TODO: Maybe put this into util (exported from `@promptbool/utils`)
4577
+ description = description.split(/^>.*$/gm).join('');
4578
+ //Note: Remove lists and return statement - TODO: [🎾] Make util (exported from `@promptbool/utils`)
4214
4579
  description = description.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
4215
4580
  description = spaceTrim$1(description);
4216
4581
  if (description === '') {
@@ -4238,7 +4603,7 @@ function pipelineStringToJsonSync(pipelineString) {
4238
4603
  pipelineJson.pipelineUrl = command.pipelineUrl.href;
4239
4604
  break;
4240
4605
  case 'KNOWLEDGE':
4241
- console.error(new NotYetImplementedError('Knowledge is not implemented yet'));
4606
+ knowledgeCommandParser.applyToPipelineJson(pipelineJson, command);
4242
4607
  break;
4243
4608
  case 'ACTION':
4244
4609
  console.error(new NotYetImplementedError('Actions are not implemented yet'));
@@ -4247,7 +4612,8 @@ function pipelineStringToJsonSync(pipelineString) {
4247
4612
  console.error(new NotYetImplementedError('Instruments are not implemented yet'));
4248
4613
  break;
4249
4614
  case 'PERSONA':
4250
- console.error(new NotYetImplementedError('Personas are not implemented yet'));
4615
+ personaCommandParser.applyToPipelineJson(pipelineJson, command);
4616
+ // <- Note: Prototype of [🍧] (remove this comment after full implementation)
4251
4617
  break;
4252
4618
  case 'BOILERPLATE':
4253
4619
  throw new ParsingError('BOILERPLATE command is only for testing purposes and should not be used in the .ptbk.md file'); // <- TODO: [🚞]
@@ -4276,7 +4642,27 @@ function pipelineStringToJsonSync(pipelineString) {
4276
4642
  var postprocessing = [];
4277
4643
  var expectAmount = {};
4278
4644
  var expectFormat = undefined;
4279
- var isBlockTypeChanged = false;
4645
+ var isBlockTypeSet = false;
4646
+ var lastLine = section.content.split('\n').pop();
4647
+ var resultingParameterNameMatch = /^->\s*\{(?<resultingParamName>[a-z0-9_]+)\}/im.exec(lastLine);
4648
+ var resultingParameterName = null;
4649
+ if (resultingParameterNameMatch &&
4650
+ resultingParameterNameMatch.groups !== undefined &&
4651
+ resultingParameterNameMatch.groups.resultingParamName !== undefined) {
4652
+ resultingParameterName = resultingParameterNameMatch.groups.resultingParamName;
4653
+ }
4654
+ var expectResultingParameterName = function () {
4655
+ if (resultingParameterName !== null) {
4656
+ return resultingParameterName;
4657
+ }
4658
+ throw new ParsingError(spaceTrim$1(function (block) { return "\n Template section must end with -> {parameterName}\n\n Invalid section:\n ".concat(block(
4659
+ // TODO: Show code of invalid sections each time + DRY
4660
+ section.content
4661
+ .split('\n')
4662
+ .map(function (line) { return " | ".concat(line); } /* <- TODO: [🚞] */)
4663
+ .join('\n')), "\n "); }));
4664
+ };
4665
+ var _e = extractOneBlockFromMarkdown(section.content), language = _e.language, content = _e.content;
4280
4666
  try {
4281
4667
  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()) {
4282
4668
  var listItem = listItems_2_1.value;
@@ -4284,15 +4670,24 @@ function pipelineStringToJsonSync(pipelineString) {
4284
4670
  switch (command.type) {
4285
4671
  // TODO: [🍧] Use here applyToPipelineJson and remove switch statement
4286
4672
  case 'BLOCK':
4287
- if (isBlockTypeChanged) {
4673
+ if (isBlockTypeSet) {
4288
4674
  throw new ParsingError('Block type is already defined in the prompt template. It can be defined only once.');
4289
4675
  }
4290
4676
  if (command.blockType === 'SAMPLE') {
4291
- console.error(new NotYetImplementedError('Block type SAMPLE is not implemented yet'));
4677
+ expectResultingParameterName();
4678
+ var parameter = pipelineJson.parameters.find(function (param) { return param.name === resultingParameterName; });
4679
+ if (parameter === undefined) {
4680
+ throw new UnexpectedError("Can not find parameter {".concat(resultingParameterName, "} to assign sample value"));
4681
+ }
4682
+ parameter.sampleValues = parameter.sampleValues || [];
4683
+ parameter.sampleValues.push(content);
4292
4684
  return "continue-templates";
4293
4685
  }
4294
4686
  if (command.blockType === 'KNOWLEDGE') {
4295
- console.error(new NotYetImplementedError('Knowledge is not implemented yet'));
4687
+ knowledgeCommandParser.applyToPipelineJson(pipelineJson, {
4688
+ type: 'KNOWLEDGE',
4689
+ source: content, // <- TODO: !!!! Working KNOWLEDGE which not referring to the source file/wweb, but its content itseld
4690
+ });
4296
4691
  return "continue-templates";
4297
4692
  }
4298
4693
  if (command.blockType === 'ACTION') {
@@ -4303,8 +4698,9 @@ function pipelineStringToJsonSync(pipelineString) {
4303
4698
  console.error(new NotYetImplementedError('Instruments are not implemented yet'));
4304
4699
  return "continue-templates";
4305
4700
  }
4701
+ expectResultingParameterName();
4306
4702
  blockType = command.blockType;
4307
- isBlockTypeChanged = true;
4703
+ isBlockTypeSet = true;
4308
4704
  break;
4309
4705
  case 'EXPECT_AMOUNT':
4310
4706
  // eslint-disable-next-line no-case-declarations
@@ -4344,16 +4740,20 @@ function pipelineStringToJsonSync(pipelineString) {
4344
4740
  postprocessing.push(command.functionName);
4345
4741
  break;
4346
4742
  case 'KNOWLEDGE':
4347
- console.error(new NotYetImplementedError('Knowledge is not implemented yet'));
4743
+ // TODO: [👙] The knowledge is maybe relevant for just this template
4744
+ knowledgeCommandParser.applyToPipelineJson(pipelineJson, command);
4348
4745
  break;
4349
4746
  case 'ACTION':
4747
+ // TODO: [👙] The action is maybe relevant for just this template
4350
4748
  console.error(new NotYetImplementedError('Actions are not implemented yet'));
4351
4749
  break;
4352
4750
  case 'INSTRUMENT':
4751
+ // TODO: [👙] The instrument is maybe relevant for just this template
4353
4752
  console.error(new NotYetImplementedError('Instruments are not implemented yet'));
4354
4753
  break;
4355
4754
  case 'PERSONA':
4356
- console.error(new NotYetImplementedError('Personas are not implemented yet'));
4755
+ personaCommandParser.applyToPipelineJson(pipelineJson, command);
4756
+ // <- Note: Prototype of [🍧] (remove this comment after full implementation)
4357
4757
  break;
4358
4758
  case 'BOILERPLATE':
4359
4759
  console.error(new ParsingError('BOILERPLATE command is only for testing purposes and should not be used in the .ptbk.md file'));
@@ -4371,7 +4771,6 @@ function pipelineStringToJsonSync(pipelineString) {
4371
4771
  }
4372
4772
  finally { if (e_3) throw e_3.error; }
4373
4773
  }
4374
- var _e = extractOneBlockFromMarkdown(section.content), language = _e.language, content = _e.content;
4375
4774
  if (blockType === 'SCRIPT') {
4376
4775
  if (!language) {
4377
4776
  throw new ParsingError('You must specify the language of the script in the prompt template');
@@ -4380,22 +4779,12 @@ function pipelineStringToJsonSync(pipelineString) {
4380
4779
  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 "); }));
4381
4780
  }
4382
4781
  }
4383
- var lastLine = section.content.split('\n').pop();
4384
- var match = /^->\s*\{(?<resultingParamName>[a-z0-9_]+)\}/im.exec(lastLine);
4385
- if (!match || match.groups === undefined || match.groups.resultingParamName === undefined) {
4386
- throw new ParsingError(spaceTrim$1(function (block) { return "\n Each section must end with -> {parameterName}\n\n Invalid section:\n ".concat(block(
4387
- // TODO: Show code of invalid sections each time + DRY
4388
- section.content
4389
- .split('\n')
4390
- .map(function (line) { return " | ".concat(line); } /* <- TODO: [🚞] */)
4391
- .join('\n')), "\n "); }));
4392
- }
4393
- var resultingParameterName = match.groups.resultingParamName;
4394
- // TODO: [1] DRY description
4782
+ // TODO: [🎾][1] DRY description
4395
4783
  var description_1 = section.content;
4396
- // Note: Remove codeblocks
4784
+ // Note: Remove codeblocks - TODO: [🎾]
4397
4785
  description_1 = description_1.split(/^```.*^```/gms).join('');
4398
- //Note: Remove lists and return statement
4786
+ description_1 = description_1.split(/^>.*$/gm).join('');
4787
+ //Note: Remove lists and return statement - TODO: [🎾]
4399
4788
  description_1 = description_1.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
4400
4789
  description_1 = spaceTrim$1(description_1);
4401
4790
  if (description_1 === '') {
@@ -4425,10 +4814,11 @@ function pipelineStringToJsonSync(pipelineString) {
4425
4814
  postprocessing: postprocessing,
4426
4815
  expectations: expectAmount,
4427
4816
  expectFormat: expectFormat,
4817
+ personaName: null,
4428
4818
  modelRequirements: templateModelRequirements,
4429
4819
  contentLanguage: blockType === 'SCRIPT' ? language : undefined,
4430
4820
  content: content,
4431
- resultingParameterName: resultingParameterName,
4821
+ resultingParameterName: expectResultingParameterName( /* <- Note: This is once more redundant */),
4432
4822
  };
4433
4823
  if (blockType !== 'PROMPT_TEMPLATE') {
4434
4824
  delete template.modelRequirements;
@@ -4501,14 +4891,17 @@ function pipelineStringToJsonSync(pipelineString) {
4501
4891
  * TODO: Use spaceTrim more effectively
4502
4892
  * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
4503
4893
  * TODO: [🥞] Not optimal parsing because `splitMarkdownIntoSections` is executed twice with same string, once through `flattenMarkdown` and second directly here
4894
+ * TODO: [♈] Probbably move expectations from templates to parameters
4895
+ * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
4504
4896
  */
4505
4897
 
4506
4898
  /**
4507
- * Compile promptbook from string (markdown) format to JSON format
4899
+ * Compile pipeline from string (markdown) format to JSON format
4508
4900
  *
4509
- * Note: There are two similar functions:
4901
+ * Note: There are 3 similar functions:
4510
4902
  * - `pipelineStringToJson` **(preferred)** - which propperly compiles the promptbook and use embedding for external knowledge
4511
4903
  * - `pipelineStringToJsonSync` - use only if you need to compile promptbook synchronously and it contains NO external knowledge
4904
+ * - `preparePipeline` - just one step in the compilation process
4512
4905
  *
4513
4906
  * @param pipelineString {Promptbook} in string markdown format (.ptbk.md)
4514
4907
  * @param options - Options and tools for the compilation
@@ -4519,22 +4912,18 @@ function pipelineStringToJsonSync(pipelineString) {
4519
4912
  * Note: This function acts as compilation process
4520
4913
  */
4521
4914
  function pipelineStringToJson(pipelineString, options) {
4522
- if (options === void 0) { options = {}; }
4915
+ if (options === void 0) { options = { llmTools: null }; }
4523
4916
  return __awaiter(this, void 0, void 0, function () {
4524
- var llmTools, pipelineJson, knowledge;
4917
+ var llmTools, pipelineJson;
4525
4918
  return __generator(this, function (_a) {
4526
4919
  switch (_a.label) {
4527
4920
  case 0:
4528
4921
  llmTools = options.llmTools;
4529
4922
  pipelineJson = pipelineStringToJsonSync(pipelineString);
4530
- if (!llmTools) return [3 /*break*/, 2];
4531
- return [4 /*yield*/, prepareKnowledgeFromMarkdown({
4532
- content: 'Roses are red, violets are blue, programmers use Promptbook, users too',
4533
- llmTools: llmTools,
4534
- })];
4923
+ if (!(llmTools !== null)) return [3 /*break*/, 2];
4924
+ return [4 /*yield*/, preparePipeline(pipelineJson, { llmTools: llmTools })];
4535
4925
  case 1:
4536
- knowledge = _a.sent();
4537
- pipelineJson = __assign(__assign({}, pipelineJson), { knowledge: __spreadArray(__spreadArray([], __read((pipelineJson.knowledge || [])), false), __read(knowledge), false) });
4926
+ pipelineJson = _a.sent();
4538
4927
  _a.label = 2;
4539
4928
  case 2: return [2 /*return*/, pipelineJson];
4540
4929
  }
@@ -4543,6 +4932,7 @@ function pipelineStringToJson(pipelineString, options) {
4543
4932
  }
4544
4933
  /**
4545
4934
  * TODO: [🏏] Leverage the batch API and build queues @see https://platform.openai.com/docs/guides/batch
4935
+ * TODO: [🛠] Actions, instruments (and maybe knowledge) => Functions and tools
4546
4936
  */
4547
4937
 
4548
4938
  /**
@@ -4669,7 +5059,7 @@ function createCollectionFromPromise(promptbookSourcesPromiseOrFactory) {
4669
5059
  */
4670
5060
  function createCollectionFromDirectory(path, options) {
4671
5061
  return __awaiter(this, void 0, void 0, function () {
4672
- var makedLibraryFilePath, makedLibraryFileExists, _a, _b, isRecursive, _c, isVerbose, _d, isLazyLoaded, _e, isCrashOnError, collection;
5062
+ var makedLibraryFilePath, makedLibraryFileExists, _a, _b, isRecursive, _c, isVerbose, _d, isLazyLoaded, _e, isCrashedOnError, collection;
4673
5063
  var _this = this;
4674
5064
  return __generator(this, function (_f) {
4675
5065
  switch (_f.label) {
@@ -4689,8 +5079,9 @@ function createCollectionFromDirectory(path, options) {
4689
5079
  else {
4690
5080
  colors.green("(In future, not implemented yet) Using your prebuild pipeline collection ".concat(makedLibraryFilePath));
4691
5081
  // TODO: !! Implement;
5082
+ // TODO: [🌗]
4692
5083
  }
4693
- _a = options || {}, _b = _a.isRecursive, isRecursive = _b === void 0 ? true : _b, _c = _a.isVerbose, isVerbose = _c === void 0 ? false : _c, _d = _a.isLazyLoaded, isLazyLoaded = _d === void 0 ? false : _d, _e = _a.isCrashOnError, isCrashOnError = _e === void 0 ? true : _e;
5084
+ _a = options || {}, _b = _a.isRecursive, isRecursive = _b === void 0 ? true : _b, _c = _a.isVerbose, isVerbose = _c === void 0 ? false : _c, _d = _a.isLazyLoaded, isLazyLoaded = _d === void 0 ? false : _d, _e = _a.isCrashedOnError, isCrashedOnError = _e === void 0 ? true : _e;
4694
5085
  collection = createCollectionFromPromise(function () { return __awaiter(_this, void 0, void 0, function () {
4695
5086
  var fileNames, promptbooks, _loop_1, fileNames_1, fileNames_1_1, fileName, e_1_1;
4696
5087
  var e_1, _a;
@@ -4733,6 +5124,7 @@ function createCollectionFromDirectory(path, options) {
4733
5124
  case 5:
4734
5125
  // TODO: Handle non-valid JSON files
4735
5126
  promptbook = _d.apply(_c, [_e.sent()]);
5127
+ // TODO: [🌗]
4736
5128
  promptbook = __assign(__assign({}, promptbook), { sourceFile: sourceFile });
4737
5129
  return [3 /*break*/, 7];
4738
5130
  case 6:
@@ -4752,7 +5144,7 @@ function createCollectionFromDirectory(path, options) {
4752
5144
  if (isVerbose) {
4753
5145
  console.info("Loading ".concat(fileName.split('\\').join('/')));
4754
5146
  }
4755
- if (!isCrashOnError) {
5147
+ if (!isCrashedOnError) {
4756
5148
  // Note: Validate promptbook to check if it is logically correct to not crash on invalid promptbooks
4757
5149
  // But be handled in current try-catch block
4758
5150
  validatePipeline(promptbook);
@@ -4768,7 +5160,7 @@ function createCollectionFromDirectory(path, options) {
4768
5160
  throw error_1;
4769
5161
  }
4770
5162
  wrappedErrorMessage = spaceTrim(function (block) { return "\n Error during loading pipeline from file ".concat(fileName.split('\\').join('/'), ":\n\n ").concat(block(error_1.message), "\n\n "); });
4771
- if (isCrashOnError) {
5163
+ if (isCrashedOnError) {
4772
5164
  throw new CollectionError(wrappedErrorMessage);
4773
5165
  }
4774
5166
  // TODO: [🟥] Detect browser / node and make it colorfull