@promptbook/node 0.59.0-3 → 0.59.0-30

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 (583) hide show
  1. package/esm/index.es.js +2540 -1592
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/typings/promptbook-library/index.d.ts +25 -0
  4. package/esm/typings/src/_packages/cli.index.d.ts +10 -0
  5. package/{umd/typings → esm/typings/src}/_packages/core.index.d.ts +10 -9
  6. package/esm/typings/src/_packages/node.index.d.ts +4 -0
  7. package/{umd/typings → esm/typings/src}/_packages/types.index.d.ts +1 -1
  8. package/esm/typings/src/cli/actions/hello.d.ts +7 -0
  9. package/esm/typings/src/cli/actions/make.d.ts +7 -0
  10. package/esm/typings/src/cli/actions/prettify.d.ts +7 -0
  11. package/esm/typings/{conversion/prettify/prettifyPromptbookStringCli.d.ts → src/cli/promptbookCli.d.ts} +2 -2
  12. package/esm/typings/{config.d.ts → src/config.d.ts} +4 -0
  13. package/{umd/typings/conversion/validation/validatePromptbookJson.d.ts → esm/typings/src/conversion/validation/validatePromptbook.d.ts} +2 -2
  14. package/esm/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +21 -0
  15. package/{umd/typings → esm/typings/src}/knowledge/prepare-knowledge/pdf/prepareKnowledgeFromPdf.d.ts +3 -0
  16. package/esm/typings/{promptbook-library → src/library}/SimplePromptbookLibrary.d.ts +3 -1
  17. package/esm/typings/{promptbook-library/constructors/createPromptbookLibraryFromDirectory.d.ts → src/library/constructors/createLibraryFromDirectory.d.ts} +2 -2
  18. package/esm/typings/src/library/constructors/createLibraryFromJson.d.ts +12 -0
  19. package/esm/typings/{promptbook-library/constructors/createPromptbookLibraryFromPromise.d.ts → src/library/constructors/createLibraryFromPromise.d.ts} +3 -7
  20. package/{umd/typings/promptbook-library/constructors/createPromptbookLibraryFromUrl.d.ts → esm/typings/src/library/constructors/createLibraryFromUrl.d.ts} +2 -2
  21. package/esm/typings/{promptbook-library/constructors/createPromptbookSublibrary.d.ts → src/library/constructors/createSublibrary.d.ts} +1 -1
  22. package/esm/typings/src/library/libraryToJson.d.ts +8 -0
  23. package/esm/typings/{llm-providers → src/llm-providers}/anthropic-claude/anthropic-claude-models.d.ts +1 -0
  24. package/{umd/typings → esm/typings/src}/llm-providers/mocked/MockedEchoLlmExecutionTools.d.ts +1 -0
  25. package/{umd/typings → esm/typings/src}/llm-providers/mocked/MockedFackedLlmExecutionTools.d.ts +3 -0
  26. package/{umd/typings → esm/typings/src}/llm-providers/openai/OpenAiExecutionTools.d.ts +8 -0
  27. package/{umd/typings → esm/typings/src}/llm-providers/openai/openai-models.d.ts +1 -0
  28. package/{umd/typings → esm/typings/src}/llm-providers/remote/interfaces/RemoteServerOptions.d.ts +1 -1
  29. package/esm/typings/{llm-providers → src/llm-providers}/remote/startRemoteServer.d.ts +1 -1
  30. package/{umd/typings → esm/typings/src}/types/ModelRequirements.d.ts +1 -1
  31. package/esm/typings/{types → src/types}/PromptbookJson/MaterialKnowledgePieceJson.d.ts +2 -2
  32. package/package.json +4 -3
  33. package/umd/index.umd.js +2544 -1596
  34. package/umd/index.umd.js.map +1 -1
  35. package/umd/typings/promptbook-library/index.d.ts +25 -0
  36. package/umd/typings/src/_packages/cli.index.d.ts +10 -0
  37. package/{esm/typings → umd/typings/src}/_packages/core.index.d.ts +10 -9
  38. package/umd/typings/src/_packages/node.index.d.ts +4 -0
  39. package/{esm/typings → umd/typings/src}/_packages/types.index.d.ts +1 -1
  40. package/umd/typings/src/cli/actions/hello.d.ts +7 -0
  41. package/umd/typings/src/cli/actions/make.d.ts +7 -0
  42. package/umd/typings/src/cli/actions/prettify.d.ts +7 -0
  43. package/umd/typings/{conversion/prettify/prettifyPromptbookStringCli.d.ts → src/cli/promptbookCli.d.ts} +2 -2
  44. package/umd/typings/{config.d.ts → src/config.d.ts} +4 -0
  45. package/{esm/typings/conversion/validation/validatePromptbookJson.d.ts → umd/typings/src/conversion/validation/validatePromptbook.d.ts} +2 -2
  46. package/umd/typings/src/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +21 -0
  47. package/{esm/typings → umd/typings/src}/knowledge/prepare-knowledge/pdf/prepareKnowledgeFromPdf.d.ts +3 -0
  48. package/umd/typings/{promptbook-library → src/library}/SimplePromptbookLibrary.d.ts +3 -1
  49. package/umd/typings/{promptbook-library/constructors/createPromptbookLibraryFromDirectory.d.ts → src/library/constructors/createLibraryFromDirectory.d.ts} +2 -2
  50. package/umd/typings/src/library/constructors/createLibraryFromJson.d.ts +12 -0
  51. package/umd/typings/{promptbook-library/constructors/createPromptbookLibraryFromPromise.d.ts → src/library/constructors/createLibraryFromPromise.d.ts} +3 -7
  52. package/{esm/typings/promptbook-library/constructors/createPromptbookLibraryFromUrl.d.ts → umd/typings/src/library/constructors/createLibraryFromUrl.d.ts} +2 -2
  53. package/umd/typings/{promptbook-library/constructors/createPromptbookSublibrary.d.ts → src/library/constructors/createSublibrary.d.ts} +1 -1
  54. package/umd/typings/src/library/libraryToJson.d.ts +8 -0
  55. package/umd/typings/{llm-providers → src/llm-providers}/anthropic-claude/anthropic-claude-models.d.ts +1 -0
  56. package/{esm/typings → umd/typings/src}/llm-providers/mocked/MockedEchoLlmExecutionTools.d.ts +1 -0
  57. package/{esm/typings → umd/typings/src}/llm-providers/mocked/MockedFackedLlmExecutionTools.d.ts +3 -0
  58. package/{esm/typings → umd/typings/src}/llm-providers/openai/OpenAiExecutionTools.d.ts +8 -0
  59. package/{esm/typings → umd/typings/src}/llm-providers/openai/openai-models.d.ts +1 -0
  60. package/{esm/typings → umd/typings/src}/llm-providers/remote/interfaces/RemoteServerOptions.d.ts +1 -1
  61. package/umd/typings/{llm-providers → src/llm-providers}/remote/startRemoteServer.d.ts +1 -1
  62. package/{esm/typings → umd/typings/src}/types/ModelRequirements.d.ts +1 -1
  63. package/umd/typings/{types → src/types}/PromptbookJson/MaterialKnowledgePieceJson.d.ts +2 -2
  64. package/umd/typings/src/utils/unwrapResult.test.d.ts +1 -0
  65. package/umd/typings/src/utils/validators/url/isValidUrl.test.d.ts +1 -0
  66. package/esm/typings/_packages/cli.index.d.ts +0 -10
  67. package/esm/typings/_packages/node.index.d.ts +0 -4
  68. package/esm/typings/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +0 -7
  69. package/esm/typings/promptbook-library/constructors/createPromptbookLibraryFromSources.d.ts +0 -16
  70. package/umd/typings/_packages/cli.index.d.ts +0 -10
  71. package/umd/typings/_packages/node.index.d.ts +0 -4
  72. package/umd/typings/knowledge/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +0 -7
  73. package/umd/typings/promptbook-library/constructors/createPromptbookLibraryFromSources.d.ts +0 -16
  74. /package/esm/typings/{_packages → src/_packages}/anthropic-claude.index.d.ts +0 -0
  75. /package/esm/typings/{_packages → src/_packages}/azure-openai.index.d.ts +0 -0
  76. /package/esm/typings/{_packages → src/_packages}/execute-javascript.index.d.ts +0 -0
  77. /package/esm/typings/{_packages → src/_packages}/fake-llm.index.d.ts +0 -0
  78. /package/esm/typings/{_packages → src/_packages}/langtail.index.d.ts +0 -0
  79. /package/esm/typings/{_packages → src/_packages}/openai.index.d.ts +0 -0
  80. /package/esm/typings/{_packages → src/_packages}/remote-client.index.d.ts +0 -0
  81. /package/esm/typings/{_packages → src/_packages}/remote-server.index.d.ts +0 -0
  82. /package/esm/typings/{_packages → src/_packages}/utils.index.d.ts +0 -0
  83. /package/esm/typings/{conversion → src/conversion}/prettify/PrettifyOptions.d.ts +0 -0
  84. /package/esm/typings/{conversion → src/conversion}/prettify/prettifyPromptbookString.d.ts +0 -0
  85. /package/esm/typings/{conversion → src/conversion}/prettify/renderPromptbookMermaid.d.ts +0 -0
  86. /package/esm/typings/{conversion → src/conversion}/promptbookJsonToString.d.ts +0 -0
  87. /package/esm/typings/{conversion → src/conversion}/promptbookStringToJson.d.ts +0 -0
  88. /package/esm/typings/{conversion → src/conversion}/promptbookStringToJson.test.d.ts +0 -0
  89. /package/esm/typings/{conversion → src/conversion}/utils/extractParametersFromPromptTemplate.d.ts +0 -0
  90. /package/esm/typings/{conversion → src/conversion}/utils/extractParametersFromPromptTemplate.test.d.ts +0 -0
  91. /package/esm/typings/{conversion → src/conversion}/utils/extractVariables.d.ts +0 -0
  92. /package/esm/typings/{conversion → src/conversion}/utils/extractVariables.test.d.ts +0 -0
  93. /package/esm/typings/{conversion → src/conversion}/utils/parseCommand.d.ts +0 -0
  94. /package/esm/typings/{conversion → src/conversion}/utils/parseCommand.test.d.ts +0 -0
  95. /package/esm/typings/{conversion → src/conversion}/utils/parseNumber.d.ts +0 -0
  96. /package/esm/typings/{conversion → src/conversion}/utils/parseNumber.test.d.ts +0 -0
  97. /package/esm/typings/{conversion → src/conversion}/utils/renameParameter.d.ts +0 -0
  98. /package/esm/typings/{conversion → src/conversion}/utils/renameParameter.test.d.ts +0 -0
  99. /package/esm/typings/{conversion → src/conversion}/utils/titleToName.d.ts +0 -0
  100. /package/esm/typings/{conversion → src/conversion}/utils/titleToName.test.d.ts +0 -0
  101. /package/esm/typings/{conversion → src/conversion}/validation/_importPromptbook.d.ts +0 -0
  102. /package/esm/typings/{conversion → src/conversion}/validation/promptbookStringToJson-syntaxErrors.test.d.ts +0 -0
  103. /package/esm/typings/{conversion/validation/validatePromptbookJson-logicErrors.test.d.ts → src/conversion/validation/validatePromptbook-logicErrors.test.d.ts} +0 -0
  104. /package/esm/typings/{conversion/validation/validatePromptbookJson.test.d.ts → src/conversion/validation/validatePromptbook.test.d.ts} +0 -0
  105. /package/esm/typings/{errors → src/errors}/PromptbookExecutionError.d.ts +0 -0
  106. /package/esm/typings/{errors → src/errors}/PromptbookLibraryError.d.ts +0 -0
  107. /package/esm/typings/{errors → src/errors}/PromptbookLogicError.d.ts +0 -0
  108. /package/esm/typings/{errors → src/errors}/PromptbookNotFoundError.d.ts +0 -0
  109. /package/esm/typings/{errors → src/errors}/PromptbookReferenceError.d.ts +0 -0
  110. /package/esm/typings/{errors → src/errors}/PromptbookSyntaxError.d.ts +0 -0
  111. /package/esm/typings/{errors → src/errors}/TemplateError.d.ts +0 -0
  112. /package/esm/typings/{errors → src/errors}/UnexpectedError.d.ts +0 -0
  113. /package/esm/typings/{errors → src/errors}/_ExpectError.d.ts +0 -0
  114. /package/esm/typings/{execution → src/execution}/CommonExecutionToolsOptions.d.ts +0 -0
  115. /package/esm/typings/{execution → src/execution}/ExecutionTools.d.ts +0 -0
  116. /package/esm/typings/{execution → src/execution}/LlmExecutionTools.d.ts +0 -0
  117. /package/esm/typings/{execution → src/execution}/PromptResult.d.ts +0 -0
  118. /package/esm/typings/{execution → src/execution}/PromptbookExecutor.d.ts +0 -0
  119. /package/esm/typings/{execution → src/execution}/ScriptExecutionTools.d.ts +0 -0
  120. /package/esm/typings/{execution → src/execution}/UserInterfaceTools.d.ts +0 -0
  121. /package/esm/typings/{execution → src/execution}/addPromptResultUsage.test.d.ts +0 -0
  122. /package/esm/typings/{execution → src/execution}/assertsExecutionSuccessful.d.ts +0 -0
  123. /package/esm/typings/{execution → src/execution}/createPromptbookExecutor.d.ts +0 -0
  124. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/AutomaticTranslator.d.ts +0 -0
  125. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/DebugAutomaticTranslator.d.ts +0 -0
  126. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/FakeAutomaticTranslator.d.ts +0 -0
  127. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/LindatAutomaticTranslator.d.ts +0 -0
  128. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/TranslatorOptions.d.ts +0 -0
  129. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/utils/extractMultiplicatedOccurrence.d.ts +0 -0
  130. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/utils/extractMultiplicatedOccurrence.test.d.ts +0 -0
  131. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/translateMessages.d.ts +0 -0
  132. /package/esm/typings/{execution → src/execution}/utils/addUsage.d.ts +0 -0
  133. /package/esm/typings/{execution → src/execution}/utils/addUsage.test.d.ts +0 -0
  134. /package/esm/typings/{execution → src/execution}/utils/checkExpectations.d.ts +0 -0
  135. /package/esm/typings/{execution → src/execution}/utils/checkExpectations.test.d.ts +0 -0
  136. /package/esm/typings/{execution → src/execution}/utils/computeUsageCounts.d.ts +0 -0
  137. /package/esm/typings/{execution → src/execution}/utils/forEachAsync.d.ts +0 -0
  138. /package/esm/typings/{execution → src/execution}/utils/replaceParameters.d.ts +0 -0
  139. /package/esm/typings/{execution → src/execution}/utils/replaceParameters.test.d.ts +0 -0
  140. /package/esm/typings/{execution → src/execution}/utils/uncertainNumber.d.ts +0 -0
  141. /package/esm/typings/{execution → src/execution}/utils/usageToWorktime.d.ts +0 -0
  142. /package/esm/typings/{execution → src/execution}/utils/usageToWorktime.test.d.ts +0 -0
  143. /package/esm/typings/{expectations → src/expectations}/drafts/isDomainNameFree.d.ts +0 -0
  144. /package/esm/typings/{expectations → src/expectations}/drafts/isGithubNameFree.d.ts +0 -0
  145. /package/esm/typings/{formats → src/formats}/_common/FormatDefinition.d.ts +0 -0
  146. /package/esm/typings/{formats → src/formats}/csv/ListFormatDefinition.d.ts +0 -0
  147. /package/esm/typings/{formats → src/formats}/index.d.ts +0 -0
  148. /package/esm/typings/{formats → src/formats}/json/JsonFormatDefinition.d.ts +0 -0
  149. /package/esm/typings/{formats → src/formats}/json/utils/isValidJsonString.d.ts +0 -0
  150. /package/esm/typings/{formats → src/formats}/json/utils/isValidJsonString.test.d.ts +0 -0
  151. /package/esm/typings/{formats → src/formats}/list/ListFormatDefinition.d.ts +0 -0
  152. /package/esm/typings/{formats → src/formats}/xml/XmlFormatDefinition.d.ts +0 -0
  153. /package/esm/typings/{knowledge → src/knowledge}/dialogs/callback/CallbackInterfaceTools.d.ts +0 -0
  154. /package/esm/typings/{knowledge → src/knowledge}/dialogs/callback/CallbackInterfaceToolsOptions.d.ts +0 -0
  155. /package/esm/typings/{knowledge → src/knowledge}/dialogs/simple-prompt/SimplePromptInterfaceTools.d.ts +0 -0
  156. /package/esm/typings/{knowledge → src/knowledge}/dialogs/user-interface-execution-tools.test.d.ts +0 -0
  157. /package/esm/typings/{knowledge → src/knowledge}/prepare-knowledge/_common/IndexPreparer.d.ts +0 -0
  158. /package/esm/typings/{knowledge → src/knowledge}/prepare-knowledge/markdown/playground/markdown-knowledge-playground.d.ts +0 -0
  159. /package/esm/typings/{knowledge → src/knowledge}/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.test.d.ts +0 -0
  160. /package/esm/typings/{knowledge → src/knowledge}/prepare-knowledge/pdf/prepareKnowledgeFromPdf.test.d.ts +0 -0
  161. /package/esm/typings/{promptbook-library → src/library}/PromptbookLibrary.d.ts +0 -0
  162. /package/esm/typings/{llm-providers/mocked/fakeTextToExpectations.test.d.ts → src/library/constructors/createLibraryFromDirectory.test.d.ts} +0 -0
  163. /package/esm/typings/{llm-providers/mocked/faked-completion.test.d.ts → src/library/constructors/createLibraryFromJson.test.d.ts} +0 -0
  164. /package/esm/typings/{llm-providers/openai/computeUsage.test.d.ts → src/library/constructors/createLibraryFromPromise.test.d.ts} +0 -0
  165. /package/esm/typings/{promptbook-library → src/library}/constructors/justTestFsImport.d.ts +0 -0
  166. /package/esm/typings/{promptbook-library/constructors/createPromptbookLibraryFromDirectory.test.d.ts → src/library/libraryToJson.test.d.ts} +0 -0
  167. /package/esm/typings/{llm-providers → src/llm-providers}/anthropic-claude/AnthropicClaudeExecutionTools.d.ts +0 -0
  168. /package/esm/typings/{llm-providers → src/llm-providers}/anthropic-claude/AnthropicClaudeExecutionToolsOptions.d.ts +0 -0
  169. /package/esm/typings/{llm-providers → src/llm-providers}/anthropic-claude/playground/playground.d.ts +0 -0
  170. /package/esm/typings/{llm-providers → src/llm-providers}/azure-openai/AzureOpenAiExecutionTools.d.ts +0 -0
  171. /package/esm/typings/{llm-providers → src/llm-providers}/azure-openai/AzureOpenAiExecutionToolsOptions.d.ts +0 -0
  172. /package/esm/typings/{llm-providers → src/llm-providers}/azure-openai/playground/playground.d.ts +0 -0
  173. /package/esm/typings/{llm-providers → src/llm-providers}/langtail/LangtailExecutionTools.d.ts +0 -0
  174. /package/esm/typings/{llm-providers → src/llm-providers}/langtail/LangtailExecutionToolsOptions.d.ts +0 -0
  175. /package/esm/typings/{llm-providers → src/llm-providers}/langtail/playground/playground.d.ts +0 -0
  176. /package/esm/typings/{llm-providers → src/llm-providers}/mocked/fakeTextToExpectations.d.ts +0 -0
  177. /package/{umd/typings → esm/typings/src}/llm-providers/mocked/fakeTextToExpectations.test.d.ts +0 -0
  178. /package/{umd/typings → esm/typings/src}/llm-providers/mocked/faked-completion.test.d.ts +0 -0
  179. /package/esm/typings/{llm-providers → src/llm-providers}/mocked/joker.test.d.ts +0 -0
  180. /package/esm/typings/{llm-providers → src/llm-providers}/mocked/mocked-chat.test.d.ts +0 -0
  181. /package/esm/typings/{llm-providers → src/llm-providers}/mocked/mocked-completion.test.d.ts +0 -0
  182. /package/esm/typings/{llm-providers → src/llm-providers}/multiple/MultipleLlmExecutionTools.d.ts +0 -0
  183. /package/esm/typings/{llm-providers → src/llm-providers}/multiple/MultipleLlmExecutionToolsOptions.d.ts +0 -0
  184. /package/esm/typings/{llm-providers → src/llm-providers}/multiple/playground/playground.d.ts +0 -0
  185. /package/esm/typings/{llm-providers → src/llm-providers}/openai/OpenAiExecutionToolsOptions.d.ts +0 -0
  186. /package/esm/typings/{llm-providers → src/llm-providers}/openai/computeOpenaiUsage.d.ts +0 -0
  187. /package/esm/typings/{llm-providers → src/llm-providers}/openai/computeUsage.d.ts +0 -0
  188. /package/{umd/typings → esm/typings/src}/llm-providers/openai/computeUsage.test.d.ts +0 -0
  189. /package/esm/typings/{llm-providers → src/llm-providers}/openai/playground/playground.d.ts +0 -0
  190. /package/esm/typings/{llm-providers → src/llm-providers}/remote/RemoteLlmExecutionTools.d.ts +0 -0
  191. /package/esm/typings/{llm-providers → src/llm-providers}/remote/RemoteLlmExecutionToolsOptions.d.ts +0 -0
  192. /package/esm/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Error.d.ts +0 -0
  193. /package/esm/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Progress.d.ts +0 -0
  194. /package/esm/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Request.d.ts +0 -0
  195. /package/esm/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Response.d.ts +0 -0
  196. /package/esm/typings/{scripting → src/scripting}/_test/custom-function-async.test.ts.test.d.ts +0 -0
  197. /package/esm/typings/{scripting → src/scripting}/_test/custom-function-missing.test.d.ts +0 -0
  198. /package/esm/typings/{scripting → src/scripting}/_test/custom-function-with-dependencies.test.d.ts +0 -0
  199. /package/esm/typings/{scripting → src/scripting}/_test/custom-function.test.d.ts +0 -0
  200. /package/esm/typings/{scripting → src/scripting}/_test/postprocessing.test.d.ts +0 -0
  201. /package/esm/typings/{scripting → src/scripting}/_test/script-execution-errors.test.d.ts +0 -0
  202. /package/esm/typings/{scripting → src/scripting}/_test/script-execution-tools.test.d.ts +0 -0
  203. /package/esm/typings/{scripting → src/scripting}/javascript/JavascriptEvalExecutionTools.d.ts +0 -0
  204. /package/esm/typings/{scripting → src/scripting}/javascript/JavascriptEvalExecutionTools.test.d.ts +0 -0
  205. /package/esm/typings/{scripting → src/scripting}/javascript/JavascriptExecutionTools.d.ts +0 -0
  206. /package/esm/typings/{scripting → src/scripting}/javascript/JavascriptExecutionToolsOptions.d.ts +0 -0
  207. /package/esm/typings/{scripting → src/scripting}/javascript/utils/preserve.d.ts +0 -0
  208. /package/esm/typings/{scripting → src/scripting}/javascript/utils/unknownToString.d.ts +0 -0
  209. /package/esm/typings/{scripting → src/scripting}/python/PythonExecutionTools.d.ts +0 -0
  210. /package/esm/typings/{scripting → src/scripting}/typescript/TypescriptExecutionTools.d.ts +0 -0
  211. /package/esm/typings/{types → src/types}/Command.d.ts +0 -0
  212. /package/esm/typings/{types → src/types}/ExecutionTypes.d.ts +0 -0
  213. /package/esm/typings/{types → src/types}/Parameters.d.ts +0 -0
  214. /package/esm/typings/{types → src/types}/Prompt.d.ts +0 -0
  215. /package/esm/typings/{types → src/types}/PromptbookJson/KnowledgeJson.d.ts +0 -0
  216. /package/esm/typings/{types → src/types}/PromptbookJson/PromptTemplateJson.d.ts +0 -0
  217. /package/esm/typings/{types → src/types}/PromptbookJson/PromptTemplateParameterJson.d.ts +0 -0
  218. /package/esm/typings/{types → src/types}/PromptbookJson/PromptbookJson.d.ts +0 -0
  219. /package/esm/typings/{types → src/types}/PromptbookString.d.ts +0 -0
  220. /package/esm/typings/{types → src/types}/ScriptLanguage.d.ts +0 -0
  221. /package/esm/typings/{types → src/types}/TaskProgress.d.ts +0 -0
  222. /package/esm/typings/{types → src/types}/execution-report/ExecutionReportJson.d.ts +0 -0
  223. /package/esm/typings/{types → src/types}/execution-report/ExecutionReportString.d.ts +0 -0
  224. /package/esm/typings/{types → src/types}/execution-report/ExecutionReportStringOptions.d.ts +0 -0
  225. /package/esm/typings/{types → src/types}/execution-report/config.d.ts +0 -0
  226. /package/esm/typings/{types → src/types}/execution-report/countWorkingDuration.d.ts +0 -0
  227. /package/esm/typings/{types → src/types}/execution-report/countWorkingDuration.test.d.ts +0 -0
  228. /package/esm/typings/{types → src/types}/execution-report/executionReportJsonToString.d.ts +0 -0
  229. /package/esm/typings/{types → src/types}/typeAliasEmoji.d.ts +0 -0
  230. /package/esm/typings/{types → src/types}/typeAliases.d.ts +0 -0
  231. /package/esm/typings/{utils → src/utils}/FromtoItems.d.ts +0 -0
  232. /package/esm/typings/{utils → src/utils}/emojis.d.ts +0 -0
  233. /package/esm/typings/{utils → src/utils}/expectation-counters/countCharacters.d.ts +0 -0
  234. /package/esm/typings/{utils → src/utils}/expectation-counters/countCharacters.test.d.ts +0 -0
  235. /package/esm/typings/{utils → src/utils}/expectation-counters/countLines.d.ts +0 -0
  236. /package/esm/typings/{utils → src/utils}/expectation-counters/countLines.test.d.ts +0 -0
  237. /package/esm/typings/{utils → src/utils}/expectation-counters/countPages.d.ts +0 -0
  238. /package/esm/typings/{utils → src/utils}/expectation-counters/countPages.test.d.ts +0 -0
  239. /package/esm/typings/{utils → src/utils}/expectation-counters/countParagraphs.d.ts +0 -0
  240. /package/esm/typings/{utils → src/utils}/expectation-counters/countParagraphs.test.d.ts +0 -0
  241. /package/esm/typings/{utils → src/utils}/expectation-counters/countSentences.d.ts +0 -0
  242. /package/esm/typings/{utils → src/utils}/expectation-counters/countSentences.test.d.ts +0 -0
  243. /package/esm/typings/{utils → src/utils}/expectation-counters/countWords.d.ts +0 -0
  244. /package/esm/typings/{utils → src/utils}/expectation-counters/countWords.test.d.ts +0 -0
  245. /package/esm/typings/{utils → src/utils}/expectation-counters/index.d.ts +0 -0
  246. /package/esm/typings/{utils → src/utils}/extractParameters.d.ts +0 -0
  247. /package/esm/typings/{utils → src/utils}/extractParameters.test.d.ts +0 -0
  248. /package/esm/typings/{utils → src/utils}/formatNumber.d.ts +0 -0
  249. /package/esm/typings/{utils → src/utils}/formatNumber.test.d.ts +0 -0
  250. /package/esm/typings/{utils → src/utils}/getCurrentIsoDate.d.ts +0 -0
  251. /package/esm/typings/{utils → src/utils}/isRunningInWhatever.d.ts +0 -0
  252. /package/esm/typings/{utils → src/utils}/just.d.ts +0 -0
  253. /package/esm/typings/{utils → src/utils}/markdown/addAutoGeneratedSection.d.ts +0 -0
  254. /package/esm/typings/{utils → src/utils}/markdown/addAutoGeneratedSection.test.d.ts +0 -0
  255. /package/esm/typings/{utils → src/utils}/markdown/createMarkdownChart.d.ts +0 -0
  256. /package/esm/typings/{utils → src/utils}/markdown/createMarkdownChart.test.d.ts +0 -0
  257. /package/esm/typings/{utils → src/utils}/markdown/createMarkdownTable.d.ts +0 -0
  258. /package/esm/typings/{utils → src/utils}/markdown/createMarkdownTable.test.d.ts +0 -0
  259. /package/esm/typings/{utils → src/utils}/markdown/escapeMarkdownBlock.d.ts +0 -0
  260. /package/esm/typings/{utils → src/utils}/markdown/escapeMarkdownBlock.test.d.ts +0 -0
  261. /package/esm/typings/{utils → src/utils}/markdown/extractAllBlocksFromMarkdown.d.ts +0 -0
  262. /package/esm/typings/{utils → src/utils}/markdown/extractAllBlocksFromMarkdown.test.d.ts +0 -0
  263. /package/esm/typings/{utils → src/utils}/markdown/extractAllListItemsFromMarkdown.d.ts +0 -0
  264. /package/esm/typings/{utils → src/utils}/markdown/extractAllListItemsFromMarkdown.test.d.ts +0 -0
  265. /package/esm/typings/{utils → src/utils}/markdown/extractOneBlockFromMarkdown.d.ts +0 -0
  266. /package/esm/typings/{utils → src/utils}/markdown/extractOneBlockFromMarkdown.test.d.ts +0 -0
  267. /package/esm/typings/{utils → src/utils}/markdown/prettifyMarkdown.d.ts +0 -0
  268. /package/esm/typings/{utils → src/utils}/markdown/prettifyMarkdown.test.d.ts +0 -0
  269. /package/esm/typings/{utils → src/utils}/markdown/removeContentComments.d.ts +0 -0
  270. /package/esm/typings/{utils → src/utils}/markdown/removeContentComments.test.d.ts +0 -0
  271. /package/esm/typings/{utils → src/utils}/markdown/removeMarkdownFormatting.d.ts +0 -0
  272. /package/esm/typings/{utils → src/utils}/markdown/removeMarkdownFormatting.test.d.ts +0 -0
  273. /package/esm/typings/{utils → src/utils}/markdown-json/MarkdownStructure.d.ts +0 -0
  274. /package/esm/typings/{utils → src/utils}/markdown-json/countMarkdownStructureDeepness.d.ts +0 -0
  275. /package/esm/typings/{utils → src/utils}/markdown-json/countMarkdownStructureDeepness.test.d.ts +0 -0
  276. /package/esm/typings/{utils → src/utils}/markdown-json/markdownToMarkdownStructure.d.ts +0 -0
  277. /package/esm/typings/{utils → src/utils}/markdown-json/markdownToMarkdownStructure.test.d.ts +0 -0
  278. /package/esm/typings/{utils → src/utils}/normalization/DIACRITIC_VARIANTS_LETTERS.d.ts +0 -0
  279. /package/esm/typings/{utils → src/utils}/normalization/IKeywords.d.ts +0 -0
  280. /package/esm/typings/{utils → src/utils}/normalization/capitalize.d.ts +0 -0
  281. /package/esm/typings/{utils → src/utils}/normalization/capitalize.test.d.ts +0 -0
  282. /package/esm/typings/{utils → src/utils}/normalization/decapitalize.d.ts +0 -0
  283. /package/esm/typings/{utils → src/utils}/normalization/decapitalize.test.d.ts +0 -0
  284. /package/esm/typings/{utils → src/utils}/normalization/isValidKeyword.d.ts +0 -0
  285. /package/esm/typings/{utils → src/utils}/normalization/isValidKeyword.test.d.ts +0 -0
  286. /package/esm/typings/{utils → src/utils}/normalization/nameToUriPart.d.ts +0 -0
  287. /package/esm/typings/{utils → src/utils}/normalization/nameToUriPart.test.d.ts +0 -0
  288. /package/esm/typings/{utils → src/utils}/normalization/nameToUriParts.d.ts +0 -0
  289. /package/esm/typings/{utils → src/utils}/normalization/nameToUriParts.test.d.ts +0 -0
  290. /package/esm/typings/{utils → src/utils}/normalization/normalize-to-kebab-case.d.ts +0 -0
  291. /package/esm/typings/{utils → src/utils}/normalization/normalize-to-kebab-case.test.d.ts +0 -0
  292. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_PascalCase.d.ts +0 -0
  293. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_PascalCase.test.d.ts +0 -0
  294. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_SCREAMING_CASE.d.ts +0 -0
  295. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_SCREAMING_CASE.test.d.ts +0 -0
  296. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_camelCase.d.ts +0 -0
  297. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_camelCase.test.d.ts +0 -0
  298. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_snake_case.d.ts +0 -0
  299. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_snake_case.test.d.ts +0 -0
  300. /package/esm/typings/{utils → src/utils}/normalization/normalizeWhitespaces.d.ts +0 -0
  301. /package/esm/typings/{utils → src/utils}/normalization/normalizeWhitespaces.test.d.ts +0 -0
  302. /package/esm/typings/{utils → src/utils}/normalization/parseKeywords.d.ts +0 -0
  303. /package/esm/typings/{utils → src/utils}/normalization/parseKeywords.test.d.ts +0 -0
  304. /package/esm/typings/{utils → src/utils}/normalization/parseKeywordsFromString.d.ts +0 -0
  305. /package/esm/typings/{utils → src/utils}/normalization/parseKeywordsFromString.test.d.ts +0 -0
  306. /package/esm/typings/{utils → src/utils}/normalization/removeDiacritics.d.ts +0 -0
  307. /package/esm/typings/{utils → src/utils}/normalization/removeDiacritics.test.d.ts +0 -0
  308. /package/esm/typings/{utils → src/utils}/normalization/searchKeywords.d.ts +0 -0
  309. /package/esm/typings/{utils → src/utils}/normalization/searchKeywords.test.d.ts +0 -0
  310. /package/esm/typings/{utils → src/utils}/postprocessing/extractBlock.d.ts +0 -0
  311. /package/esm/typings/{utils → src/utils}/removeEmojis.d.ts +0 -0
  312. /package/esm/typings/{utils → src/utils}/removeEmojis.test.d.ts +0 -0
  313. /package/esm/typings/{utils → src/utils}/removeQuotes.d.ts +0 -0
  314. /package/esm/typings/{utils → src/utils}/removeQuotes.test.d.ts +0 -0
  315. /package/esm/typings/{utils → src/utils}/sets/difference.d.ts +0 -0
  316. /package/esm/typings/{utils → src/utils}/sets/difference.test.d.ts +0 -0
  317. /package/esm/typings/{utils → src/utils}/sets/intersection.d.ts +0 -0
  318. /package/esm/typings/{utils → src/utils}/sets/intersection.test.d.ts +0 -0
  319. /package/esm/typings/{utils → src/utils}/sets/union.d.ts +0 -0
  320. /package/esm/typings/{utils → src/utils}/sets/union.test.d.ts +0 -0
  321. /package/esm/typings/{utils → src/utils}/trimCodeBlock.d.ts +0 -0
  322. /package/esm/typings/{utils → src/utils}/trimCodeBlock.test.d.ts +0 -0
  323. /package/esm/typings/{utils → src/utils}/trimEndOfCodeBlock.d.ts +0 -0
  324. /package/esm/typings/{utils → src/utils}/trimEndOfCodeBlock.test.d.ts +0 -0
  325. /package/esm/typings/{utils → src/utils}/unwrapResult.d.ts +0 -0
  326. /package/esm/typings/{utils → src/utils}/unwrapResult.test.d.ts +0 -0
  327. /package/esm/typings/{utils → src/utils}/validators/url/isValidUrl.d.ts +0 -0
  328. /package/esm/typings/{utils → src/utils}/validators/url/isValidUrl.test.d.ts +0 -0
  329. /package/esm/typings/{version.d.ts → src/version.d.ts} +0 -0
  330. /package/umd/typings/{_packages → src/_packages}/anthropic-claude.index.d.ts +0 -0
  331. /package/umd/typings/{_packages → src/_packages}/azure-openai.index.d.ts +0 -0
  332. /package/umd/typings/{_packages → src/_packages}/execute-javascript.index.d.ts +0 -0
  333. /package/umd/typings/{_packages → src/_packages}/fake-llm.index.d.ts +0 -0
  334. /package/umd/typings/{_packages → src/_packages}/langtail.index.d.ts +0 -0
  335. /package/umd/typings/{_packages → src/_packages}/openai.index.d.ts +0 -0
  336. /package/umd/typings/{_packages → src/_packages}/remote-client.index.d.ts +0 -0
  337. /package/umd/typings/{_packages → src/_packages}/remote-server.index.d.ts +0 -0
  338. /package/umd/typings/{_packages → src/_packages}/utils.index.d.ts +0 -0
  339. /package/umd/typings/{conversion → src/conversion}/prettify/PrettifyOptions.d.ts +0 -0
  340. /package/umd/typings/{conversion → src/conversion}/prettify/prettifyPromptbookString.d.ts +0 -0
  341. /package/umd/typings/{conversion → src/conversion}/prettify/renderPromptbookMermaid.d.ts +0 -0
  342. /package/umd/typings/{conversion → src/conversion}/promptbookJsonToString.d.ts +0 -0
  343. /package/umd/typings/{conversion → src/conversion}/promptbookStringToJson.d.ts +0 -0
  344. /package/umd/typings/{conversion → src/conversion}/promptbookStringToJson.test.d.ts +0 -0
  345. /package/umd/typings/{conversion → src/conversion}/utils/extractParametersFromPromptTemplate.d.ts +0 -0
  346. /package/umd/typings/{conversion → src/conversion}/utils/extractParametersFromPromptTemplate.test.d.ts +0 -0
  347. /package/umd/typings/{conversion → src/conversion}/utils/extractVariables.d.ts +0 -0
  348. /package/umd/typings/{conversion → src/conversion}/utils/extractVariables.test.d.ts +0 -0
  349. /package/umd/typings/{conversion → src/conversion}/utils/parseCommand.d.ts +0 -0
  350. /package/umd/typings/{conversion → src/conversion}/utils/parseCommand.test.d.ts +0 -0
  351. /package/umd/typings/{conversion → src/conversion}/utils/parseNumber.d.ts +0 -0
  352. /package/umd/typings/{conversion → src/conversion}/utils/parseNumber.test.d.ts +0 -0
  353. /package/umd/typings/{conversion → src/conversion}/utils/renameParameter.d.ts +0 -0
  354. /package/umd/typings/{conversion → src/conversion}/utils/renameParameter.test.d.ts +0 -0
  355. /package/umd/typings/{conversion → src/conversion}/utils/titleToName.d.ts +0 -0
  356. /package/umd/typings/{conversion → src/conversion}/utils/titleToName.test.d.ts +0 -0
  357. /package/umd/typings/{conversion → src/conversion}/validation/_importPromptbook.d.ts +0 -0
  358. /package/umd/typings/{conversion → src/conversion}/validation/promptbookStringToJson-syntaxErrors.test.d.ts +0 -0
  359. /package/{esm/typings/promptbook-library/constructors/createPromptbookLibraryFromPromise.test.d.ts → umd/typings/src/conversion/validation/validatePromptbook-logicErrors.test.d.ts} +0 -0
  360. /package/{esm/typings/promptbook-library/constructors/createPromptbookLibraryFromSources.test.d.ts → umd/typings/src/conversion/validation/validatePromptbook.test.d.ts} +0 -0
  361. /package/umd/typings/{errors → src/errors}/PromptbookExecutionError.d.ts +0 -0
  362. /package/umd/typings/{errors → src/errors}/PromptbookLibraryError.d.ts +0 -0
  363. /package/umd/typings/{errors → src/errors}/PromptbookLogicError.d.ts +0 -0
  364. /package/umd/typings/{errors → src/errors}/PromptbookNotFoundError.d.ts +0 -0
  365. /package/umd/typings/{errors → src/errors}/PromptbookReferenceError.d.ts +0 -0
  366. /package/umd/typings/{errors → src/errors}/PromptbookSyntaxError.d.ts +0 -0
  367. /package/umd/typings/{errors → src/errors}/TemplateError.d.ts +0 -0
  368. /package/umd/typings/{errors → src/errors}/UnexpectedError.d.ts +0 -0
  369. /package/umd/typings/{errors → src/errors}/_ExpectError.d.ts +0 -0
  370. /package/umd/typings/{execution → src/execution}/CommonExecutionToolsOptions.d.ts +0 -0
  371. /package/umd/typings/{execution → src/execution}/ExecutionTools.d.ts +0 -0
  372. /package/umd/typings/{execution → src/execution}/LlmExecutionTools.d.ts +0 -0
  373. /package/umd/typings/{execution → src/execution}/PromptResult.d.ts +0 -0
  374. /package/umd/typings/{execution → src/execution}/PromptbookExecutor.d.ts +0 -0
  375. /package/umd/typings/{execution → src/execution}/ScriptExecutionTools.d.ts +0 -0
  376. /package/umd/typings/{execution → src/execution}/UserInterfaceTools.d.ts +0 -0
  377. /package/umd/typings/{execution → src/execution}/addPromptResultUsage.test.d.ts +0 -0
  378. /package/umd/typings/{execution → src/execution}/assertsExecutionSuccessful.d.ts +0 -0
  379. /package/umd/typings/{execution → src/execution}/createPromptbookExecutor.d.ts +0 -0
  380. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/AutomaticTranslator.d.ts +0 -0
  381. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/DebugAutomaticTranslator.d.ts +0 -0
  382. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/FakeAutomaticTranslator.d.ts +0 -0
  383. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/LindatAutomaticTranslator.d.ts +0 -0
  384. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/TranslatorOptions.d.ts +0 -0
  385. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/utils/extractMultiplicatedOccurrence.d.ts +0 -0
  386. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/utils/extractMultiplicatedOccurrence.test.d.ts +0 -0
  387. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/translateMessages.d.ts +0 -0
  388. /package/umd/typings/{execution → src/execution}/utils/addUsage.d.ts +0 -0
  389. /package/umd/typings/{execution → src/execution}/utils/addUsage.test.d.ts +0 -0
  390. /package/umd/typings/{execution → src/execution}/utils/checkExpectations.d.ts +0 -0
  391. /package/umd/typings/{execution → src/execution}/utils/checkExpectations.test.d.ts +0 -0
  392. /package/umd/typings/{execution → src/execution}/utils/computeUsageCounts.d.ts +0 -0
  393. /package/umd/typings/{execution → src/execution}/utils/forEachAsync.d.ts +0 -0
  394. /package/umd/typings/{execution → src/execution}/utils/replaceParameters.d.ts +0 -0
  395. /package/umd/typings/{execution → src/execution}/utils/replaceParameters.test.d.ts +0 -0
  396. /package/umd/typings/{execution → src/execution}/utils/uncertainNumber.d.ts +0 -0
  397. /package/umd/typings/{execution → src/execution}/utils/usageToWorktime.d.ts +0 -0
  398. /package/umd/typings/{execution → src/execution}/utils/usageToWorktime.test.d.ts +0 -0
  399. /package/umd/typings/{expectations → src/expectations}/drafts/isDomainNameFree.d.ts +0 -0
  400. /package/umd/typings/{expectations → src/expectations}/drafts/isGithubNameFree.d.ts +0 -0
  401. /package/umd/typings/{formats → src/formats}/_common/FormatDefinition.d.ts +0 -0
  402. /package/umd/typings/{formats → src/formats}/csv/ListFormatDefinition.d.ts +0 -0
  403. /package/umd/typings/{formats → src/formats}/index.d.ts +0 -0
  404. /package/umd/typings/{formats → src/formats}/json/JsonFormatDefinition.d.ts +0 -0
  405. /package/umd/typings/{formats → src/formats}/json/utils/isValidJsonString.d.ts +0 -0
  406. /package/umd/typings/{formats → src/formats}/json/utils/isValidJsonString.test.d.ts +0 -0
  407. /package/umd/typings/{formats → src/formats}/list/ListFormatDefinition.d.ts +0 -0
  408. /package/umd/typings/{formats → src/formats}/xml/XmlFormatDefinition.d.ts +0 -0
  409. /package/umd/typings/{knowledge → src/knowledge}/dialogs/callback/CallbackInterfaceTools.d.ts +0 -0
  410. /package/umd/typings/{knowledge → src/knowledge}/dialogs/callback/CallbackInterfaceToolsOptions.d.ts +0 -0
  411. /package/umd/typings/{knowledge → src/knowledge}/dialogs/simple-prompt/SimplePromptInterfaceTools.d.ts +0 -0
  412. /package/umd/typings/{knowledge → src/knowledge}/dialogs/user-interface-execution-tools.test.d.ts +0 -0
  413. /package/umd/typings/{knowledge → src/knowledge}/prepare-knowledge/_common/IndexPreparer.d.ts +0 -0
  414. /package/umd/typings/{knowledge → src/knowledge}/prepare-knowledge/markdown/playground/markdown-knowledge-playground.d.ts +0 -0
  415. /package/umd/typings/{knowledge → src/knowledge}/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.test.d.ts +0 -0
  416. /package/umd/typings/{knowledge → src/knowledge}/prepare-knowledge/pdf/prepareKnowledgeFromPdf.test.d.ts +0 -0
  417. /package/umd/typings/{promptbook-library → src/library}/PromptbookLibrary.d.ts +0 -0
  418. /package/umd/typings/{conversion/validation/validatePromptbookJson-logicErrors.test.d.ts → src/library/constructors/createLibraryFromDirectory.test.d.ts} +0 -0
  419. /package/umd/typings/{conversion/validation/validatePromptbookJson.test.d.ts → src/library/constructors/createLibraryFromJson.test.d.ts} +0 -0
  420. /package/umd/typings/{promptbook-library/constructors/createPromptbookLibraryFromDirectory.test.d.ts → src/library/constructors/createLibraryFromPromise.test.d.ts} +0 -0
  421. /package/umd/typings/{promptbook-library → src/library}/constructors/justTestFsImport.d.ts +0 -0
  422. /package/umd/typings/{promptbook-library/constructors/createPromptbookLibraryFromPromise.test.d.ts → src/library/libraryToJson.test.d.ts} +0 -0
  423. /package/umd/typings/{llm-providers → src/llm-providers}/anthropic-claude/AnthropicClaudeExecutionTools.d.ts +0 -0
  424. /package/umd/typings/{llm-providers → src/llm-providers}/anthropic-claude/AnthropicClaudeExecutionToolsOptions.d.ts +0 -0
  425. /package/umd/typings/{llm-providers → src/llm-providers}/anthropic-claude/playground/playground.d.ts +0 -0
  426. /package/umd/typings/{llm-providers → src/llm-providers}/azure-openai/AzureOpenAiExecutionTools.d.ts +0 -0
  427. /package/umd/typings/{llm-providers → src/llm-providers}/azure-openai/AzureOpenAiExecutionToolsOptions.d.ts +0 -0
  428. /package/umd/typings/{llm-providers → src/llm-providers}/azure-openai/playground/playground.d.ts +0 -0
  429. /package/umd/typings/{llm-providers → src/llm-providers}/langtail/LangtailExecutionTools.d.ts +0 -0
  430. /package/umd/typings/{llm-providers → src/llm-providers}/langtail/LangtailExecutionToolsOptions.d.ts +0 -0
  431. /package/umd/typings/{llm-providers → src/llm-providers}/langtail/playground/playground.d.ts +0 -0
  432. /package/umd/typings/{llm-providers → src/llm-providers}/mocked/fakeTextToExpectations.d.ts +0 -0
  433. /package/umd/typings/{promptbook-library/constructors/createPromptbookLibraryFromSources.test.d.ts → src/llm-providers/mocked/fakeTextToExpectations.test.d.ts} +0 -0
  434. /package/umd/typings/{scripting/_test/custom-function-async.test.ts.test.d.ts → src/llm-providers/mocked/faked-completion.test.d.ts} +0 -0
  435. /package/umd/typings/{llm-providers → src/llm-providers}/mocked/joker.test.d.ts +0 -0
  436. /package/umd/typings/{llm-providers → src/llm-providers}/mocked/mocked-chat.test.d.ts +0 -0
  437. /package/umd/typings/{llm-providers → src/llm-providers}/mocked/mocked-completion.test.d.ts +0 -0
  438. /package/umd/typings/{llm-providers → src/llm-providers}/multiple/MultipleLlmExecutionTools.d.ts +0 -0
  439. /package/umd/typings/{llm-providers → src/llm-providers}/multiple/MultipleLlmExecutionToolsOptions.d.ts +0 -0
  440. /package/umd/typings/{llm-providers → src/llm-providers}/multiple/playground/playground.d.ts +0 -0
  441. /package/umd/typings/{llm-providers → src/llm-providers}/openai/OpenAiExecutionToolsOptions.d.ts +0 -0
  442. /package/umd/typings/{llm-providers → src/llm-providers}/openai/computeOpenaiUsage.d.ts +0 -0
  443. /package/umd/typings/{llm-providers → src/llm-providers}/openai/computeUsage.d.ts +0 -0
  444. /package/umd/typings/{scripting/_test/custom-function-missing.test.d.ts → src/llm-providers/openai/computeUsage.test.d.ts} +0 -0
  445. /package/umd/typings/{llm-providers → src/llm-providers}/openai/playground/playground.d.ts +0 -0
  446. /package/umd/typings/{llm-providers → src/llm-providers}/remote/RemoteLlmExecutionTools.d.ts +0 -0
  447. /package/umd/typings/{llm-providers → src/llm-providers}/remote/RemoteLlmExecutionToolsOptions.d.ts +0 -0
  448. /package/umd/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Error.d.ts +0 -0
  449. /package/umd/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Progress.d.ts +0 -0
  450. /package/umd/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Request.d.ts +0 -0
  451. /package/umd/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Response.d.ts +0 -0
  452. /package/umd/typings/{scripting/_test/custom-function-with-dependencies.test.d.ts → src/scripting/_test/custom-function-async.test.ts.test.d.ts} +0 -0
  453. /package/umd/typings/{scripting/_test/custom-function.test.d.ts → src/scripting/_test/custom-function-missing.test.d.ts} +0 -0
  454. /package/umd/typings/{scripting/_test/postprocessing.test.d.ts → src/scripting/_test/custom-function-with-dependencies.test.d.ts} +0 -0
  455. /package/umd/typings/{scripting/_test/script-execution-errors.test.d.ts → src/scripting/_test/custom-function.test.d.ts} +0 -0
  456. /package/umd/typings/{scripting/_test/script-execution-tools.test.d.ts → src/scripting/_test/postprocessing.test.d.ts} +0 -0
  457. /package/umd/typings/{types/execution-report/countWorkingDuration.test.d.ts → src/scripting/_test/script-execution-errors.test.d.ts} +0 -0
  458. /package/umd/typings/{utils/expectation-counters/countCharacters.test.d.ts → src/scripting/_test/script-execution-tools.test.d.ts} +0 -0
  459. /package/umd/typings/{scripting → src/scripting}/javascript/JavascriptEvalExecutionTools.d.ts +0 -0
  460. /package/umd/typings/{scripting → src/scripting}/javascript/JavascriptEvalExecutionTools.test.d.ts +0 -0
  461. /package/umd/typings/{scripting → src/scripting}/javascript/JavascriptExecutionTools.d.ts +0 -0
  462. /package/umd/typings/{scripting → src/scripting}/javascript/JavascriptExecutionToolsOptions.d.ts +0 -0
  463. /package/umd/typings/{scripting → src/scripting}/javascript/utils/preserve.d.ts +0 -0
  464. /package/umd/typings/{scripting → src/scripting}/javascript/utils/unknownToString.d.ts +0 -0
  465. /package/umd/typings/{scripting → src/scripting}/python/PythonExecutionTools.d.ts +0 -0
  466. /package/umd/typings/{scripting → src/scripting}/typescript/TypescriptExecutionTools.d.ts +0 -0
  467. /package/umd/typings/{types → src/types}/Command.d.ts +0 -0
  468. /package/umd/typings/{types → src/types}/ExecutionTypes.d.ts +0 -0
  469. /package/umd/typings/{types → src/types}/Parameters.d.ts +0 -0
  470. /package/umd/typings/{types → src/types}/Prompt.d.ts +0 -0
  471. /package/umd/typings/{types → src/types}/PromptbookJson/KnowledgeJson.d.ts +0 -0
  472. /package/umd/typings/{types → src/types}/PromptbookJson/PromptTemplateJson.d.ts +0 -0
  473. /package/umd/typings/{types → src/types}/PromptbookJson/PromptTemplateParameterJson.d.ts +0 -0
  474. /package/umd/typings/{types → src/types}/PromptbookJson/PromptbookJson.d.ts +0 -0
  475. /package/umd/typings/{types → src/types}/PromptbookString.d.ts +0 -0
  476. /package/umd/typings/{types → src/types}/ScriptLanguage.d.ts +0 -0
  477. /package/umd/typings/{types → src/types}/TaskProgress.d.ts +0 -0
  478. /package/umd/typings/{types → src/types}/execution-report/ExecutionReportJson.d.ts +0 -0
  479. /package/umd/typings/{types → src/types}/execution-report/ExecutionReportString.d.ts +0 -0
  480. /package/umd/typings/{types → src/types}/execution-report/ExecutionReportStringOptions.d.ts +0 -0
  481. /package/umd/typings/{types → src/types}/execution-report/config.d.ts +0 -0
  482. /package/umd/typings/{types → src/types}/execution-report/countWorkingDuration.d.ts +0 -0
  483. /package/umd/typings/{utils/expectation-counters/countLines.test.d.ts → src/types/execution-report/countWorkingDuration.test.d.ts} +0 -0
  484. /package/umd/typings/{types → src/types}/execution-report/executionReportJsonToString.d.ts +0 -0
  485. /package/umd/typings/{types → src/types}/typeAliasEmoji.d.ts +0 -0
  486. /package/umd/typings/{types → src/types}/typeAliases.d.ts +0 -0
  487. /package/umd/typings/{utils → src/utils}/FromtoItems.d.ts +0 -0
  488. /package/umd/typings/{utils → src/utils}/emojis.d.ts +0 -0
  489. /package/umd/typings/{utils → src/utils}/expectation-counters/countCharacters.d.ts +0 -0
  490. /package/umd/typings/{utils/expectation-counters/countPages.test.d.ts → src/utils/expectation-counters/countCharacters.test.d.ts} +0 -0
  491. /package/umd/typings/{utils → src/utils}/expectation-counters/countLines.d.ts +0 -0
  492. /package/umd/typings/{utils/expectation-counters/countParagraphs.test.d.ts → src/utils/expectation-counters/countLines.test.d.ts} +0 -0
  493. /package/umd/typings/{utils → src/utils}/expectation-counters/countPages.d.ts +0 -0
  494. /package/umd/typings/{utils/expectation-counters/countSentences.test.d.ts → src/utils/expectation-counters/countPages.test.d.ts} +0 -0
  495. /package/umd/typings/{utils → src/utils}/expectation-counters/countParagraphs.d.ts +0 -0
  496. /package/umd/typings/{utils/expectation-counters/countWords.test.d.ts → src/utils/expectation-counters/countParagraphs.test.d.ts} +0 -0
  497. /package/umd/typings/{utils → src/utils}/expectation-counters/countSentences.d.ts +0 -0
  498. /package/umd/typings/{utils/extractParameters.test.d.ts → src/utils/expectation-counters/countSentences.test.d.ts} +0 -0
  499. /package/umd/typings/{utils → src/utils}/expectation-counters/countWords.d.ts +0 -0
  500. /package/umd/typings/{utils/formatNumber.test.d.ts → src/utils/expectation-counters/countWords.test.d.ts} +0 -0
  501. /package/umd/typings/{utils → src/utils}/expectation-counters/index.d.ts +0 -0
  502. /package/umd/typings/{utils → src/utils}/extractParameters.d.ts +0 -0
  503. /package/umd/typings/{utils/markdown-json/countMarkdownStructureDeepness.test.d.ts → src/utils/extractParameters.test.d.ts} +0 -0
  504. /package/umd/typings/{utils → src/utils}/formatNumber.d.ts +0 -0
  505. /package/umd/typings/{utils/markdown-json/markdownToMarkdownStructure.test.d.ts → src/utils/formatNumber.test.d.ts} +0 -0
  506. /package/umd/typings/{utils → src/utils}/getCurrentIsoDate.d.ts +0 -0
  507. /package/umd/typings/{utils → src/utils}/isRunningInWhatever.d.ts +0 -0
  508. /package/umd/typings/{utils → src/utils}/just.d.ts +0 -0
  509. /package/umd/typings/{utils → src/utils}/markdown/addAutoGeneratedSection.d.ts +0 -0
  510. /package/umd/typings/{utils/markdown/createMarkdownTable.test.d.ts → src/utils/markdown/addAutoGeneratedSection.test.d.ts} +0 -0
  511. /package/umd/typings/{utils → src/utils}/markdown/createMarkdownChart.d.ts +0 -0
  512. /package/umd/typings/{utils/markdown/escapeMarkdownBlock.test.d.ts → src/utils/markdown/createMarkdownChart.test.d.ts} +0 -0
  513. /package/umd/typings/{utils → src/utils}/markdown/createMarkdownTable.d.ts +0 -0
  514. /package/umd/typings/{utils/markdown/extractAllBlocksFromMarkdown.test.d.ts → src/utils/markdown/createMarkdownTable.test.d.ts} +0 -0
  515. /package/umd/typings/{utils → src/utils}/markdown/escapeMarkdownBlock.d.ts +0 -0
  516. /package/umd/typings/{utils/markdown/extractAllListItemsFromMarkdown.test.d.ts → src/utils/markdown/escapeMarkdownBlock.test.d.ts} +0 -0
  517. /package/umd/typings/{utils → src/utils}/markdown/extractAllBlocksFromMarkdown.d.ts +0 -0
  518. /package/umd/typings/{utils/markdown/extractOneBlockFromMarkdown.test.d.ts → src/utils/markdown/extractAllBlocksFromMarkdown.test.d.ts} +0 -0
  519. /package/umd/typings/{utils → src/utils}/markdown/extractAllListItemsFromMarkdown.d.ts +0 -0
  520. /package/umd/typings/{utils/markdown/prettifyMarkdown.test.d.ts → src/utils/markdown/extractAllListItemsFromMarkdown.test.d.ts} +0 -0
  521. /package/umd/typings/{utils → src/utils}/markdown/extractOneBlockFromMarkdown.d.ts +0 -0
  522. /package/umd/typings/{utils/markdown/removeContentComments.test.d.ts → src/utils/markdown/extractOneBlockFromMarkdown.test.d.ts} +0 -0
  523. /package/umd/typings/{utils → src/utils}/markdown/prettifyMarkdown.d.ts +0 -0
  524. /package/umd/typings/{utils/markdown/removeMarkdownFormatting.test.d.ts → src/utils/markdown/prettifyMarkdown.test.d.ts} +0 -0
  525. /package/umd/typings/{utils → src/utils}/markdown/removeContentComments.d.ts +0 -0
  526. /package/umd/typings/{utils/normalization/capitalize.test.d.ts → src/utils/markdown/removeContentComments.test.d.ts} +0 -0
  527. /package/umd/typings/{utils → src/utils}/markdown/removeMarkdownFormatting.d.ts +0 -0
  528. /package/umd/typings/{utils/normalization/decapitalize.test.d.ts → src/utils/markdown/removeMarkdownFormatting.test.d.ts} +0 -0
  529. /package/umd/typings/{utils → src/utils}/markdown-json/MarkdownStructure.d.ts +0 -0
  530. /package/umd/typings/{utils → src/utils}/markdown-json/countMarkdownStructureDeepness.d.ts +0 -0
  531. /package/umd/typings/{utils/markdown/addAutoGeneratedSection.test.d.ts → src/utils/markdown-json/countMarkdownStructureDeepness.test.d.ts} +0 -0
  532. /package/umd/typings/{utils → src/utils}/markdown-json/markdownToMarkdownStructure.d.ts +0 -0
  533. /package/umd/typings/{utils/markdown/createMarkdownChart.test.d.ts → src/utils/markdown-json/markdownToMarkdownStructure.test.d.ts} +0 -0
  534. /package/umd/typings/{utils → src/utils}/normalization/DIACRITIC_VARIANTS_LETTERS.d.ts +0 -0
  535. /package/umd/typings/{utils → src/utils}/normalization/IKeywords.d.ts +0 -0
  536. /package/umd/typings/{utils → src/utils}/normalization/capitalize.d.ts +0 -0
  537. /package/umd/typings/{utils/normalization/isValidKeyword.test.d.ts → src/utils/normalization/capitalize.test.d.ts} +0 -0
  538. /package/umd/typings/{utils → src/utils}/normalization/decapitalize.d.ts +0 -0
  539. /package/umd/typings/{utils/normalization/nameToUriPart.test.d.ts → src/utils/normalization/decapitalize.test.d.ts} +0 -0
  540. /package/umd/typings/{utils → src/utils}/normalization/isValidKeyword.d.ts +0 -0
  541. /package/umd/typings/{utils/normalization/nameToUriParts.test.d.ts → src/utils/normalization/isValidKeyword.test.d.ts} +0 -0
  542. /package/umd/typings/{utils → src/utils}/normalization/nameToUriPart.d.ts +0 -0
  543. /package/umd/typings/{utils/normalization/normalize-to-kebab-case.test.d.ts → src/utils/normalization/nameToUriPart.test.d.ts} +0 -0
  544. /package/umd/typings/{utils → src/utils}/normalization/nameToUriParts.d.ts +0 -0
  545. /package/umd/typings/{utils/normalization/normalizeTo_PascalCase.test.d.ts → src/utils/normalization/nameToUriParts.test.d.ts} +0 -0
  546. /package/umd/typings/{utils → src/utils}/normalization/normalize-to-kebab-case.d.ts +0 -0
  547. /package/umd/typings/{utils/normalization/normalizeTo_SCREAMING_CASE.test.d.ts → src/utils/normalization/normalize-to-kebab-case.test.d.ts} +0 -0
  548. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_PascalCase.d.ts +0 -0
  549. /package/umd/typings/{utils/normalization/normalizeTo_camelCase.test.d.ts → src/utils/normalization/normalizeTo_PascalCase.test.d.ts} +0 -0
  550. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_SCREAMING_CASE.d.ts +0 -0
  551. /package/umd/typings/{utils/normalization/normalizeTo_snake_case.test.d.ts → src/utils/normalization/normalizeTo_SCREAMING_CASE.test.d.ts} +0 -0
  552. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_camelCase.d.ts +0 -0
  553. /package/umd/typings/{utils/normalization/normalizeWhitespaces.test.d.ts → src/utils/normalization/normalizeTo_camelCase.test.d.ts} +0 -0
  554. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_snake_case.d.ts +0 -0
  555. /package/umd/typings/{utils/normalization/parseKeywords.test.d.ts → src/utils/normalization/normalizeTo_snake_case.test.d.ts} +0 -0
  556. /package/umd/typings/{utils → src/utils}/normalization/normalizeWhitespaces.d.ts +0 -0
  557. /package/umd/typings/{utils/normalization/parseKeywordsFromString.test.d.ts → src/utils/normalization/normalizeWhitespaces.test.d.ts} +0 -0
  558. /package/umd/typings/{utils → src/utils}/normalization/parseKeywords.d.ts +0 -0
  559. /package/umd/typings/{utils/normalization/removeDiacritics.test.d.ts → src/utils/normalization/parseKeywords.test.d.ts} +0 -0
  560. /package/umd/typings/{utils → src/utils}/normalization/parseKeywordsFromString.d.ts +0 -0
  561. /package/umd/typings/{utils/normalization/searchKeywords.test.d.ts → src/utils/normalization/parseKeywordsFromString.test.d.ts} +0 -0
  562. /package/umd/typings/{utils → src/utils}/normalization/removeDiacritics.d.ts +0 -0
  563. /package/umd/typings/{utils/removeEmojis.test.d.ts → src/utils/normalization/removeDiacritics.test.d.ts} +0 -0
  564. /package/umd/typings/{utils → src/utils}/normalization/searchKeywords.d.ts +0 -0
  565. /package/umd/typings/{utils/removeQuotes.test.d.ts → src/utils/normalization/searchKeywords.test.d.ts} +0 -0
  566. /package/umd/typings/{utils → src/utils}/postprocessing/extractBlock.d.ts +0 -0
  567. /package/umd/typings/{utils → src/utils}/removeEmojis.d.ts +0 -0
  568. /package/umd/typings/{utils/sets/difference.test.d.ts → src/utils/removeEmojis.test.d.ts} +0 -0
  569. /package/umd/typings/{utils → src/utils}/removeQuotes.d.ts +0 -0
  570. /package/umd/typings/{utils/sets/intersection.test.d.ts → src/utils/removeQuotes.test.d.ts} +0 -0
  571. /package/umd/typings/{utils → src/utils}/sets/difference.d.ts +0 -0
  572. /package/umd/typings/{utils/sets/union.test.d.ts → src/utils/sets/difference.test.d.ts} +0 -0
  573. /package/umd/typings/{utils → src/utils}/sets/intersection.d.ts +0 -0
  574. /package/umd/typings/{utils/trimCodeBlock.test.d.ts → src/utils/sets/intersection.test.d.ts} +0 -0
  575. /package/umd/typings/{utils → src/utils}/sets/union.d.ts +0 -0
  576. /package/umd/typings/{utils/trimEndOfCodeBlock.test.d.ts → src/utils/sets/union.test.d.ts} +0 -0
  577. /package/umd/typings/{utils → src/utils}/trimCodeBlock.d.ts +0 -0
  578. /package/umd/typings/{utils/unwrapResult.test.d.ts → src/utils/trimCodeBlock.test.d.ts} +0 -0
  579. /package/umd/typings/{utils → src/utils}/trimEndOfCodeBlock.d.ts +0 -0
  580. /package/umd/typings/{utils/validators/url/isValidUrl.test.d.ts → src/utils/trimEndOfCodeBlock.test.d.ts} +0 -0
  581. /package/umd/typings/{utils → src/utils}/unwrapResult.d.ts +0 -0
  582. /package/umd/typings/{utils → src/utils}/validators/url/isValidUrl.d.ts +0 -0
  583. /package/umd/typings/{version.d.ts → src/version.d.ts} +0 -0
package/umd/index.umd.js CHANGED
@@ -1,11 +1,12 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('fs/promises'), require('path'), require('spacetrim'), require('prettier'), require('prettier/parser-html')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'fs/promises', 'path', 'spacetrim', 'prettier', 'prettier/parser-html'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-node"] = {}, global.promises, global.path, global.spaceTrim, global.prettier, global.parserHtml));
5
- })(this, (function (exports, promises, path, spaceTrim, prettier, parserHtml) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('colors'), require('fs/promises'), require('path'), require('spacetrim'), require('prettier'), require('prettier/parser-html')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'colors', 'fs/promises', 'path', 'spacetrim', 'prettier', 'prettier/parser-html'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-node"] = {}, global.colors, global.promises, global.path, global.spaceTrim, global.prettier, global.parserHtml));
5
+ })(this, (function (exports, colors, promises, path, spaceTrim, prettier, parserHtml) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
9
+ var colors__default = /*#__PURE__*/_interopDefaultLegacy(colors);
9
10
  var spaceTrim__default = /*#__PURE__*/_interopDefaultLegacy(spaceTrim);
10
11
  var parserHtml__default = /*#__PURE__*/_interopDefaultLegacy(parserHtml);
11
12
 
@@ -128,6 +129,15 @@
128
129
  return to.concat(ar || Array.prototype.slice.call(from));
129
130
  }
130
131
 
132
+ /**
133
+ * The maximum number of iterations for a loops
134
+ */
135
+ var LOOP_LIMIT = 1000;
136
+ /**
137
+ * The name of the builded promptbook library made by CLI `promptbook make` and for lookup in `createLibraryFromDirectory`
138
+ */
139
+ var PROMPTBOOK_MAKED_BASE_FILENAME = "index";
140
+
131
141
  /**
132
142
  * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
133
143
  */
@@ -142,48 +152,60 @@
142
152
  return PromptbookSyntaxError;
143
153
  }(Error));
144
154
 
145
- // import prepareKnowledgeFromMarkdownStringPromptbook from './prepare-knowledge-from-markdown.ptbk.md';
146
- function prepareKnowledgeFromMarkdown(options) {
147
- return __awaiter(this, void 0, void 0, function () {
148
- return __generator(this, function (_a) {
149
- return [2 /*return*/, []];
150
- });
151
- });
152
- }
155
+ var promptbookLibrary = [{title:"Prepare Keywords",promptbookUrl:"https://promptbook.studio/promptbook/prepare-keywords.ptbk.md",promptbookVersion:"0.59.0-29",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"],executionType:"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:[]},{title:"Prepare Knowledge from Markdown",promptbookUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.59.0-29",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"],executionType:"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:[]}];
153
156
 
154
157
  /**
155
- * Supported script languages
158
+ * This error indicates errors during the execution of the promptbook
156
159
  */
157
- var SUPPORTED_SCRIPT_LANGUAGES = ['javascript', 'typescript', 'python'];
160
+ var PromptbookExecutionError = /** @class */ (function (_super) {
161
+ __extends(PromptbookExecutionError, _super);
162
+ function PromptbookExecutionError(message) {
163
+ var _this = _super.call(this, message) || this;
164
+ _this.name = 'PromptbookExecutionError';
165
+ Object.setPrototypeOf(_this, PromptbookExecutionError.prototype);
166
+ return _this;
167
+ }
168
+ return PromptbookExecutionError;
169
+ }(Error));
158
170
 
159
171
  /**
160
- * Computes the deepness of the markdown structure.
172
+ * Asserts that the execution of a promptnook is successful
161
173
  *
162
- * @private within the library
174
+ * @param executionResult - The partial result of the promptnook execution
175
+ * @throws {PromptbookExecutionError} If the execution is not successful or if multiple errors occurred
163
176
  */
164
- function countMarkdownStructureDeepness(markdownStructure) {
165
- var e_1, _a;
166
- var maxDeepness = 0;
167
- try {
168
- for (var _b = __values(markdownStructure.sections), _c = _b.next(); !_c.done; _c = _b.next()) {
169
- var section = _c.value;
170
- maxDeepness = Math.max(maxDeepness, countMarkdownStructureDeepness(section));
171
- }
177
+ function assertsExecutionSuccessful(executionResult) {
178
+ var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors;
179
+ if (isSuccessful === true) {
180
+ return;
172
181
  }
173
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
174
- finally {
175
- try {
176
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
177
- }
178
- finally { if (e_1) throw e_1.error; }
182
+ if (errors.length === 0) {
183
+ throw new PromptbookExecutionError("Promptnook Execution failed because of unknown reason");
184
+ }
185
+ else if (errors.length === 1) {
186
+ throw errors[0];
187
+ }
188
+ else {
189
+ throw new PromptbookExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Multiple errors occurred during promptnook execution\n\n ".concat(block(errors.map(function (error) { return '- ' + error.message; }).join('\n')), "\n "); }));
179
190
  }
180
- return maxDeepness + 1;
181
191
  }
192
+ /**
193
+ * TODO: [🧠] Can this return type be better typed than void
194
+ */
182
195
 
183
196
  /**
184
- * The maximum number of iterations for a loops
197
+ * This error indicates that the promptbook object has valid syntax but contains logical errors (like circular dependencies)
185
198
  */
186
- var LOOP_LIMIT = 1000;
199
+ var PromptbookLogicError = /** @class */ (function (_super) {
200
+ __extends(PromptbookLogicError, _super);
201
+ function PromptbookLogicError(message) {
202
+ var _this = _super.call(this, message) || this;
203
+ _this.name = 'PromptbookLogicError';
204
+ Object.setPrototypeOf(_this, PromptbookLogicError.prototype);
205
+ return _this;
206
+ }
207
+ return PromptbookLogicError;
208
+ }(Error));
187
209
 
188
210
  /**
189
211
  * This error type indicates that the error should not happen and its last check before crashing with some other error
@@ -200,804 +222,399 @@
200
222
  }(Error));
201
223
 
202
224
  /**
203
- * Parse a markdown string into a MarkdownStructure object.
204
- *
205
- * Note: This function does work with code blocks
206
- * Note: This function does not work with markdown comments
207
- *
208
- * @param markdown The markdown string to parse.
209
- * @returns The MarkdownStructure object.
225
+ * Tests if given string is valid URL.
210
226
  *
211
- * @private within the library
227
+ * Note: Dataurl are considered perfectly valid.
212
228
  */
213
- function markdownToMarkdownStructure(markdown) {
214
- var e_1, _a;
215
- var lines = markdown.split('\n');
216
- var root = { level: 0, title: '', contentLines: [], sections: [], parent: null };
217
- var current = root;
218
- var isInsideCodeBlock = false;
229
+ function isValidUrl(url) {
230
+ if (typeof url !== 'string') {
231
+ return false;
232
+ }
219
233
  try {
220
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
221
- var line = lines_1_1.value;
222
- var headingMatch = line.match(/^(?<mark>#{1,6})\s(?<title>.*)/);
223
- if (isInsideCodeBlock || !headingMatch) {
224
- if (line.startsWith('```')) {
225
- isInsideCodeBlock = !isInsideCodeBlock;
226
- }
227
- current.contentLines.push(line);
228
- }
229
- else {
230
- var level = headingMatch.groups.mark.length;
231
- var title = headingMatch.groups.title.trim();
232
- var parent_1 = void 0;
233
- if (level > current.level) {
234
- // Note: Going deeper (next section is child of current)
235
- parent_1 = current;
236
- }
237
- else {
238
- // Note: Going up or staying at the same level (next section is sibling or parent or grandparent,... of current)
239
- parent_1 = current;
240
- var loopLimit = LOOP_LIMIT;
241
- while (parent_1.level !== level - 1) {
242
- if (loopLimit-- < 0) {
243
- throw new UnexpectedError('Loop limit reached during parsing of markdown structure in `markdownToMarkdownStructure`');
244
- }
245
- if (parent_1.parent === null /* <- Note: We are in root */) {
246
- // [🌻]
247
- throw new Error(spaceTrim.spaceTrim("\n The file has an invalid structure.\n The markdown file must have exactly one top-level section.\n "));
248
- }
249
- parent_1 = parent_1.parent;
250
- }
251
- }
252
- var section = { level: level, title: title, contentLines: [], sections: [], parent: parent_1 };
253
- parent_1.sections.push(section);
254
- current = section;
255
- }
234
+ if (url.startsWith('blob:')) {
235
+ url = url.replace(/^blob:/, '');
256
236
  }
257
- }
258
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
259
- finally {
260
- try {
261
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
237
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
238
+ var urlObject = new URL(url);
239
+ if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
240
+ return false;
262
241
  }
263
- finally { if (e_1) throw e_1.error; }
242
+ return true;
264
243
  }
265
- if (root.sections.length === 1) {
266
- var markdownStructure = parsingMarkdownStructureToMarkdownStructure(root.sections[0]);
267
- return markdownStructure;
244
+ catch (error) {
245
+ return false;
268
246
  }
269
- // [🌻]
270
- throw new Error('The markdown file must have exactly one top-level section.');
271
- // return root;
272
- }
273
- /**
274
- * @private
275
- */
276
- function parsingMarkdownStructureToMarkdownStructure(parsingMarkdownStructure) {
277
- var level = parsingMarkdownStructure.level, title = parsingMarkdownStructure.title, contentLines = parsingMarkdownStructure.contentLines, sections = parsingMarkdownStructure.sections;
278
- return {
279
- level: level,
280
- title: title,
281
- content: spaceTrim.spaceTrim(contentLines.join('\n')),
282
- sections: sections.map(parsingMarkdownStructureToMarkdownStructure),
283
- };
284
247
  }
285
248
 
286
249
  /**
287
- * Utility function to extract all list items from markdown
250
+ * Validates PromptbookJson if it is logically valid
288
251
  *
289
- * Note: It works with both ul and ol
290
- * Note: It omits list items in code blocks
291
- * Note: It flattens nested lists
292
- * Note: It can not work with html syntax and comments
252
+ * It checks:
253
+ * - if it has correct parameters dependency
293
254
  *
294
- * @param markdown any valid markdown
295
- * @returns
255
+ * It does NOT check:
256
+ * - if it is valid json
257
+ * - if it is meaningful
258
+ *
259
+ * @param promptbook valid or invalid PromptbookJson
260
+ * @returns the same promptbook if it is logically valid
261
+ * @throws {PromptbookLogicError} on logical error in the promptbook
296
262
  */
297
- function extractAllListItemsFromMarkdown(markdown) {
298
- var e_1, _a;
299
- var lines = markdown.split('\n');
300
- var listItems = [];
301
- var isInCodeBlock = false;
263
+ function validatePromptbook(promptbook) {
264
+ // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
265
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
266
+ if (promptbook.promptbookUrl !== undefined) {
267
+ if (!isValidUrl(promptbook.promptbookUrl)) {
268
+ // TODO: This should be maybe the syntax error detected during parsing
269
+ throw new PromptbookLogicError("Invalid promptbook URL \"".concat(promptbook.promptbookUrl, "\""));
270
+ }
271
+ }
272
+ // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
273
+ if (!Array.isArray(promptbook.parameters)) {
274
+ // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
275
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Promptbook is valid JSON but with wrong structure\n\n promptbook.parameters expected to be an array, but got ".concat(typeof promptbook.parameters, "\n ")));
276
+ }
277
+ // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
278
+ if (!Array.isArray(promptbook.promptTemplates)) {
279
+ // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
280
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Promptbook is valid JSON but with wrong structure\n\n promptbook.promptTemplates expected to be an array, but got ".concat(typeof promptbook.promptTemplates, "\n ")));
281
+ }
282
+ var _loop_1 = function (parameter) {
283
+ if (parameter.isInput && parameter.isOutput) {
284
+ throw new PromptbookLogicError("Parameter {".concat(parameter.name, "} can not be both input and output"));
285
+ }
286
+ // Note: Testing that parameter is either intermediate or output BUT not created and unused
287
+ if (!parameter.isInput &&
288
+ !parameter.isOutput &&
289
+ !promptbook.promptTemplates.some(function (template) { return template.dependentParameterNames.includes(parameter.name); })) {
290
+ throw new PromptbookLogicError(spaceTrim.spaceTrim("\n Parameter {".concat(parameter.name, "} is created but not used\n\n You can declare {").concat(parameter.name, "} as output parameter by adding in the header:\n - OUTPUT PARAMETER `{").concat(parameter.name, "}` ").concat(parameter.description || '', "\n\n ")));
291
+ }
292
+ // Note: Testing that parameter is either input or result of some template
293
+ if (!parameter.isInput &&
294
+ !promptbook.promptTemplates.some(function (template) { return template.resultingParameterName === parameter.name; })) {
295
+ throw new PromptbookLogicError(spaceTrim.spaceTrim("\n Parameter {".concat(parameter.name, "} is declared but not defined\n\n You can do one of these:\n - Remove declaration of {").concat(parameter.name, "}\n - Add prompt template that results in -> {").concat(parameter.name, "}\n\n ")));
296
+ }
297
+ };
302
298
  try {
303
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
304
- var line = lines_1_1.value;
305
- var trimmedLine = line.trim();
306
- if (trimmedLine.startsWith('```')) {
307
- isInCodeBlock = !isInCodeBlock;
308
- }
309
- if (!isInCodeBlock && (trimmedLine.startsWith('-') || trimmedLine.match(/^\d+\./))) {
310
- var listItem = trimmedLine.replace(/^-|\d+\./, '').trim();
311
- listItems.push(listItem);
312
- }
299
+ // Note: Check each parameter individually
300
+ for (var _e = __values(promptbook.parameters), _f = _e.next(); !_f.done; _f = _e.next()) {
301
+ var parameter = _f.value;
302
+ _loop_1(parameter);
313
303
  }
314
304
  }
315
305
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
316
306
  finally {
317
307
  try {
318
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
308
+ if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
319
309
  }
320
310
  finally { if (e_1) throw e_1.error; }
321
311
  }
322
- return listItems;
323
- }
324
-
325
- /**
326
- * Makes first letter of a string uppercase
327
- *
328
- */
329
- function capitalize(word) {
330
- return word.substring(0, 1).toUpperCase() + word.substring(1);
331
- }
332
-
333
- /**
334
- * Extracts all code blocks from markdown.
335
- *
336
- * Note: There are 3 simmilar function:
337
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
338
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
339
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
340
- *
341
- * @param markdown any valid markdown
342
- * @returns code blocks with language and content
343
- *
344
- */
345
- function extractAllBlocksFromMarkdown(markdown) {
346
- var e_1, _a;
347
- var codeBlocks = [];
348
- var lines = markdown.split('\n');
349
- var currentCodeBlock = null;
312
+ // Note: Check each template individually
313
+ var definedParameters = new Set(promptbook.parameters.filter(function (_a) {
314
+ var isInput = _a.isInput;
315
+ return isInput;
316
+ }).map(function (_a) {
317
+ var name = _a.name;
318
+ return name;
319
+ }));
350
320
  try {
351
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
352
- var line = lines_1_1.value;
353
- if (line.startsWith('```')) {
354
- var language = line.slice(3).trim() || null;
355
- if (currentCodeBlock === null) {
356
- currentCodeBlock = { language: language, content: '' };
321
+ for (var _g = __values(promptbook.promptTemplates), _h = _g.next(); !_h.done; _h = _g.next()) {
322
+ var template = _h.value;
323
+ if (definedParameters.has(template.resultingParameterName)) {
324
+ throw new PromptbookLogicError("Parameter {".concat(template.resultingParameterName, "} is defined multiple times"));
325
+ }
326
+ definedParameters.add(template.resultingParameterName);
327
+ if (template.executionType === 'PROMPT_TEMPLATE' && template.modelRequirements.modelVariant === undefined) {
328
+ throw new PromptbookLogicError(spaceTrim.spaceTrim("\n\n You must specify MODEL VARIANT in the prompt template \"".concat(template.title, "\"\n\n For example:\n - MODEL VARIANT Chat\n - MODEL NAME `gpt-4-1106-preview`\n\n ")));
329
+ }
330
+ if (template.jokers && template.jokers.length > 0) {
331
+ if (!template.expectFormat &&
332
+ !template.expectations /* <- TODO: Require at least 1 -> min <- expectation to use jokers */) {
333
+ throw new PromptbookLogicError("Joker parameters are used for {".concat(template.resultingParameterName, "} but no expectations are defined"));
357
334
  }
358
- else {
359
- if (language !== null) {
360
- // [🌻]
361
- throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
335
+ try {
336
+ for (var _j = (e_3 = void 0, __values(template.jokers)), _k = _j.next(); !_k.done; _k = _j.next()) {
337
+ var joker = _k.value;
338
+ if (!template.dependentParameterNames.includes(joker)) {
339
+ throw new PromptbookLogicError("Parameter {".concat(joker, "} is used for {").concat(template.resultingParameterName, "} as joker but not in dependentParameterNames"));
340
+ }
362
341
  }
363
- codeBlocks.push(currentCodeBlock);
364
- currentCodeBlock = null;
342
+ }
343
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
344
+ finally {
345
+ try {
346
+ if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
347
+ }
348
+ finally { if (e_3) throw e_3.error; }
365
349
  }
366
350
  }
367
- else if (currentCodeBlock !== null) {
368
- if (currentCodeBlock.content !== '') {
369
- currentCodeBlock.content += '\n';
351
+ if (template.expectations) {
352
+ try {
353
+ for (var _l = (e_4 = void 0, __values(Object.entries(template.expectations))), _m = _l.next(); !_m.done; _m = _l.next()) {
354
+ var _o = __read(_m.value, 2), unit = _o[0], _p = _o[1], min = _p.min, max = _p.max;
355
+ if (min !== undefined && max !== undefined && min > max) {
356
+ throw new PromptbookLogicError("Min expectation (=".concat(min, ") of ").concat(unit, " is higher than max expectation (=").concat(max, ")"));
357
+ }
358
+ if (min !== undefined && min < 0) {
359
+ throw new PromptbookLogicError("Min expectation of ".concat(unit, " must be zero or positive"));
360
+ }
361
+ if (max !== undefined && max <= 0) {
362
+ throw new PromptbookLogicError("Max expectation of ".concat(unit, " must be positive"));
363
+ }
364
+ }
365
+ }
366
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
367
+ finally {
368
+ try {
369
+ if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
370
+ }
371
+ finally { if (e_4) throw e_4.error; }
370
372
  }
371
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
372
373
  }
373
374
  }
374
375
  }
375
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
376
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
376
377
  finally {
377
378
  try {
378
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
379
+ if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
379
380
  }
380
- finally { if (e_1) throw e_1.error; }
381
+ finally { if (e_2) throw e_2.error; }
381
382
  }
382
- if (currentCodeBlock !== null) {
383
- // [🌻]
384
- throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
383
+ // Note: Detect circular dependencies
384
+ var resovedParameters = promptbook.parameters
385
+ .filter(function (_a) {
386
+ var isInput = _a.isInput;
387
+ return isInput;
388
+ })
389
+ .map(function (_a) {
390
+ var name = _a.name;
391
+ return name;
392
+ });
393
+ var unresovedTemplates = __spreadArray([], __read(promptbook.promptTemplates), false);
394
+ var loopLimit = LOOP_LIMIT;
395
+ var _loop_2 = function () {
396
+ if (loopLimit-- < 0) {
397
+ throw new UnexpectedError('Loop limit reached during detection of circular dependencies in `validatePromptbook`');
398
+ }
399
+ var currentlyResovedTemplates = unresovedTemplates.filter(function (template) {
400
+ return template.dependentParameterNames.every(function (name) { return resovedParameters.includes(name); });
401
+ });
402
+ if (currentlyResovedTemplates.length === 0) {
403
+ throw new PromptbookLogicError(spaceTrim.spaceTrim(function (block) { return "\n\n Can not resolve some parameters\n It may be circular dependencies\n\n Can not resolve:\n ".concat(block(unresovedTemplates
404
+ .map(function (_a) {
405
+ var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
406
+ return "- {".concat(resultingParameterName, "} depends on ").concat(dependentParameterNames
407
+ .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
408
+ .join(', '));
409
+ })
410
+ .join('\n')), "\n\n Resolved:\n ").concat(block(resovedParameters.map(function (name) { return "- {".concat(name, "}"); }).join('\n')), "\n "); }));
411
+ }
412
+ resovedParameters = __spreadArray(__spreadArray([], __read(resovedParameters), false), __read(currentlyResovedTemplates.map(function (_a) {
413
+ var resultingParameterName = _a.resultingParameterName;
414
+ return resultingParameterName;
415
+ })), false);
416
+ unresovedTemplates = unresovedTemplates.filter(function (template) { return !currentlyResovedTemplates.includes(template); });
417
+ };
418
+ while (unresovedTemplates.length > 0) {
419
+ _loop_2();
385
420
  }
386
- return codeBlocks;
421
+ return promptbook;
387
422
  }
423
+ /**
424
+ * TODO: [🧠] Work with promptbookVersion
425
+ * TODO: Use here some json-schema, Zod or something similar and change it to:
426
+ * > /**
427
+ * > * Validates PromptbookJson if it is logically valid.
428
+ * > *
429
+ * > * It checks:
430
+ * > * - it has a valid structure
431
+ * > * - ...
432
+ * > ex port function validatePromptbook(promptbook: unknown): asserts promptbook is PromptbookJson {
433
+ */
388
434
 
389
435
  /**
390
- * Extracts exactly ONE code block from markdown.
391
- *
392
- * Note: If there are multiple or no code blocks the function throws an error
393
- *
394
- * Note: There are 3 simmilar function:
395
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
396
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
397
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
436
+ * This error occurs when some expectation is not met in the execution of the pipeline
398
437
  *
399
- * @param markdown any valid markdown
400
- * @returns code block with language and content
438
+ * @private Always catched and rethrown as `PromptbookExecutionError`
439
+ * Note: This is a kindof subtype of PromptbookExecutionError
401
440
  */
402
- function extractOneBlockFromMarkdown(markdown) {
403
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
404
- if (codeBlocks.length !== 1) {
405
- // TODO: Report more specific place where the error happened
406
- throw new Error(/* <- [🌻] */ 'There should be exactly one code block in the markdown');
441
+ var ExpectError = /** @class */ (function (_super) {
442
+ __extends(ExpectError, _super);
443
+ function ExpectError(message) {
444
+ var _this = _super.call(this, message) || this;
445
+ _this.name = 'ExpectError';
446
+ Object.setPrototypeOf(_this, ExpectError.prototype);
447
+ return _this;
407
448
  }
408
- return codeBlocks[0];
409
- }
410
- /***
411
- * TODO: [🍓][🌻] !!! Decide of this is internal util, external util OR validator/postprocessor
412
- */
449
+ return ExpectError;
450
+ }(Error));
413
451
 
414
452
  /**
415
- * Removes HTML or Markdown comments from a string.
416
- *
417
- * @param {string} content - The string to remove comments from.
418
- * @returns {string} The input string with all comments removed.
453
+ * Function isValidJsonString will tell you if the string is valid JSON or not
419
454
  */
420
- function removeContentComments(content) {
421
- return spaceTrim.spaceTrim(content.replace(/<!--(.*?)-->/gs, ''));
455
+ function isValidJsonString(value /* <-[👨‍⚖️] */) {
456
+ try {
457
+ JSON.parse(value);
458
+ return true;
459
+ }
460
+ catch (error) {
461
+ if (!(error instanceof Error)) {
462
+ throw error;
463
+ }
464
+ if (error.message.includes('Unexpected token')) {
465
+ return false;
466
+ }
467
+ return false;
468
+ }
422
469
  }
423
470
 
424
471
  /**
425
- * Creates a new set with all elements that are present in either set
472
+ * The version of the Promptbook library
426
473
  */
427
- function union() {
428
- var e_1, _a, e_2, _b;
429
- var sets = [];
474
+ var PROMPTBOOK_VERSION = '0.59.0-29';
475
+
476
+ /**
477
+ * Function `addUsage` will add multiple usages into one
478
+ *
479
+ * Note: If you provide 0 values, it returns void usage
480
+ */
481
+ function addUsage() {
482
+ var usageItems = [];
430
483
  for (var _i = 0; _i < arguments.length; _i++) {
431
- sets[_i] = arguments[_i];
432
- }
433
- var union = new Set();
434
- try {
435
- for (var sets_1 = __values(sets), sets_1_1 = sets_1.next(); !sets_1_1.done; sets_1_1 = sets_1.next()) {
436
- var set = sets_1_1.value;
437
- try {
438
- for (var _c = (e_2 = void 0, __values(Array.from(set))), _d = _c.next(); !_d.done; _d = _c.next()) {
439
- var item = _d.value;
440
- union.add(item);
484
+ usageItems[_i] = arguments[_i];
485
+ }
486
+ var initialStructure = {
487
+ price: { value: 0 },
488
+ input: {
489
+ tokensCount: { value: 0 },
490
+ charactersCount: { value: 0 },
491
+ wordsCount: { value: 0 },
492
+ sentencesCount: { value: 0 },
493
+ linesCount: { value: 0 },
494
+ paragraphsCount: { value: 0 },
495
+ pagesCount: { value: 0 },
496
+ },
497
+ output: {
498
+ tokensCount: { value: 0 },
499
+ charactersCount: { value: 0 },
500
+ wordsCount: { value: 0 },
501
+ sentencesCount: { value: 0 },
502
+ linesCount: { value: 0 },
503
+ paragraphsCount: { value: 0 },
504
+ pagesCount: { value: 0 },
505
+ },
506
+ };
507
+ return usageItems.reduce(function (acc, item) {
508
+ var e_1, _a, e_2, _b;
509
+ var _c;
510
+ acc.price.value += ((_c = item.price) === null || _c === void 0 ? void 0 : _c.value) || 0;
511
+ try {
512
+ for (var _d = __values(Object.keys(acc.input)), _e = _d.next(); !_e.done; _e = _d.next()) {
513
+ var key = _e.value;
514
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
515
+ //@ts-ignore
516
+ if (item.input[key]) {
517
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
518
+ //@ts-ignore
519
+ acc.input[key].value += item.input[key].value || 0;
520
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
521
+ //@ts-ignore
522
+ if (item.input[key].isUncertain) {
523
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
524
+ //@ts-ignore
525
+ acc.input[key].isUncertain = true;
526
+ }
441
527
  }
442
528
  }
443
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
444
- finally {
445
- try {
446
- if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
447
- }
448
- finally { if (e_2) throw e_2.error; }
529
+ }
530
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
531
+ finally {
532
+ try {
533
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
449
534
  }
535
+ finally { if (e_1) throw e_1.error; }
450
536
  }
451
- }
452
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
453
- finally {
454
537
  try {
455
- if (sets_1_1 && !sets_1_1.done && (_a = sets_1.return)) _a.call(sets_1);
538
+ for (var _f = __values(Object.keys(acc.output)), _g = _f.next(); !_g.done; _g = _f.next()) {
539
+ var key = _g.value;
540
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
541
+ //@ts-ignore
542
+ if (item.output[key]) {
543
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
544
+ //@ts-ignore
545
+ acc.output[key].value += item.output[key].value || 0;
546
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
547
+ //@ts-ignore
548
+ if (item.output[key].isUncertain) {
549
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
550
+ //@ts-ignore
551
+ acc.output[key].isUncertain = true;
552
+ }
553
+ }
554
+ }
456
555
  }
457
- finally { if (e_1) throw e_1.error; }
458
- }
459
- return union;
556
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
557
+ finally {
558
+ try {
559
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
560
+ }
561
+ finally { if (e_2) throw e_2.error; }
562
+ }
563
+ return acc;
564
+ }, initialStructure);
460
565
  }
461
566
 
462
567
  /**
463
- * The version of the Promptbook library
568
+ * Counts number of characters in the text
464
569
  */
465
- var PROMPTBOOK_VERSION = '0.59.0-2';
570
+ function countCharacters(text) {
571
+ // Remove null characters
572
+ text = text.replace(/\0/g, '');
573
+ // Replace emojis (and also ZWJ sequence) with hyphens
574
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
575
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
576
+ text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
577
+ return text.length;
578
+ }
466
579
 
467
580
  /**
468
- * Parses the template and returns the list of all parameter names
469
- *
470
- * @param template the template with parameters in {curly} braces
471
- * @returns the list of parameter names
581
+ * Counts number of lines in the text
472
582
  */
473
- function extractParameters(template) {
474
- var e_1, _a;
475
- var matches = template.matchAll(/{\w+}/g);
476
- var parameterNames = new Set();
477
- try {
478
- for (var matches_1 = __values(matches), matches_1_1 = matches_1.next(); !matches_1_1.done; matches_1_1 = matches_1.next()) {
479
- var match = matches_1_1.value;
480
- var parameterName = match[0].slice(1, -1);
481
- parameterNames.add(parameterName);
482
- }
483
- }
484
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
485
- finally {
486
- try {
487
- if (matches_1_1 && !matches_1_1.done && (_a = matches_1.return)) _a.call(matches_1);
488
- }
489
- finally { if (e_1) throw e_1.error; }
583
+ function countLines(text) {
584
+ if (text === '') {
585
+ return 0;
490
586
  }
491
- return parameterNames;
587
+ return text.split('\n').length;
492
588
  }
493
589
 
494
590
  /**
495
- * Parses the given script and returns the list of all used variables that are not defined in the script
496
- *
497
- * @param script from which to extract the variables
498
- * @returns the list of variable names
499
- * @throws {PromptbookSyntaxError} if the script is invalid
591
+ * Counts number of pages in the text
500
592
  */
501
- function extractVariables(script) {
502
- var variables = new Set();
503
- script = "(()=>{".concat(script, "})()");
504
- try {
505
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
506
- try {
507
- eval(script);
508
- }
509
- catch (error) {
510
- if (!(error instanceof ReferenceError)) {
511
- throw error;
512
- }
513
- var undefinedName = error.message.split(' ')[0];
514
- /*
515
- Note: Remapping error
516
- From: [ReferenceError: thing is not defined],
517
- To: [Error: Parameter {thing} is not defined],
518
- */
519
- if (!undefinedName) {
520
- throw error;
521
- }
522
- if (script.includes(undefinedName + '(')) {
523
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
524
- }
525
- else {
526
- variables.add(undefinedName);
527
- script = "const ".concat(undefinedName, " = '';") + script;
528
- }
529
- }
530
- }
531
- catch (error) {
532
- if (!(error instanceof Error)) {
533
- throw error;
534
- }
535
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.name), ": ").concat(block(error.message), "\n "); }));
536
- }
537
- return variables;
593
+ function countPages(text) {
594
+ var sentencesPerPage = 5; // Assuming each page has 5 sentences
595
+ var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
596
+ var pageCount = Math.ceil(sentences.length / sentencesPerPage);
597
+ return pageCount;
538
598
  }
539
- /**
540
- * TODO: [🔣] Support for multiple languages - python, java,...
541
- */
542
599
 
543
600
  /**
544
- * Parses the prompt template and returns the set of all used parameters
545
- *
546
- * @param promptTemplate the template with used parameters
547
- * @returns the set of parameter names
548
- * @throws {PromptbookSyntaxError} if the script is invalid
549
- */
550
- function extractParametersFromPromptTemplate(promptTemplate) {
551
- var e_1, _a, e_2, _b;
552
- var parameterNames = new Set();
553
- try {
554
- for (var _c = __values(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameters(promptTemplate.title)), false), __read(extractParameters(promptTemplate.description || '')), false), __read(extractParameters(promptTemplate.content)), false)), _d = _c.next(); !_d.done; _d = _c.next()) {
555
- var parameterName = _d.value;
556
- parameterNames.add(parameterName);
557
- }
558
- }
559
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
560
- finally {
561
- try {
562
- if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
563
- }
564
- finally { if (e_1) throw e_1.error; }
565
- }
566
- if (promptTemplate.executionType === 'SCRIPT') {
567
- try {
568
- for (var _e = __values(extractVariables(promptTemplate.content)), _f = _e.next(); !_f.done; _f = _e.next()) {
569
- var parameterName = _f.value;
570
- parameterNames.add(parameterName);
571
- }
572
- }
573
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
574
- finally {
575
- try {
576
- if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
577
- }
578
- finally { if (e_2) throw e_2.error; }
579
- }
580
- }
581
- return parameterNames;
582
- }
583
- /**
584
- * TODO: [🔣] If script require contentLanguage
601
+ * Counts number of paragraphs in the text
585
602
  */
586
-
587
- /* tslint:disable */
588
- /*
589
- TODO: Tests
590
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'Moje tabule' })).toEqual('/VtG7sR9rRJqwNEdM2/Moje tabule');
591
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'ěščřžžýáíúů' })).toEqual('/VtG7sR9rRJqwNEdM2/escrzyaieuu');
592
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj');
593
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj_ahojAhoj ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj-ahoj-ahoj-ahoj');
594
- */
595
- function normalizeTo_SCREAMING_CASE(sentence) {
596
- var e_1, _a;
597
- var charType;
598
- var lastCharType = 'OTHER';
599
- var normalizedName = '';
600
- try {
601
- for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
602
- var char = sentence_1_1.value;
603
- var normalizedChar = void 0;
604
- if (/^[a-z]$/.test(char)) {
605
- charType = 'LOWERCASE';
606
- normalizedChar = char.toUpperCase();
607
- }
608
- else if (/^[A-Z]$/.test(char)) {
609
- charType = 'UPPERCASE';
610
- normalizedChar = char;
611
- }
612
- else if (/^[0-9]$/.test(char)) {
613
- charType = 'NUMBER';
614
- normalizedChar = char;
615
- }
616
- else if (/^\/$/.test(char)) {
617
- charType = 'SLASH';
618
- normalizedChar = char;
619
- }
620
- else {
621
- charType = 'OTHER';
622
- normalizedChar = '_';
623
- }
624
- if (charType !== lastCharType &&
625
- !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
626
- !(lastCharType === 'NUMBER') &&
627
- !(charType === 'NUMBER')) {
628
- normalizedName += '_';
629
- }
630
- normalizedName += normalizedChar;
631
- lastCharType = charType;
632
- }
633
- }
634
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
635
- finally {
636
- try {
637
- if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
638
- }
639
- finally { if (e_1) throw e_1.error; }
640
- }
641
- normalizedName = normalizedName.replace(/_+/g, '_');
642
- normalizedName = normalizedName.replace(/_?\/_?/g, '/');
643
- normalizedName = normalizedName.replace(/^_/, '');
644
- normalizedName = normalizedName.replace(/_$/, '');
645
- return normalizedName;
603
+ function countParagraphs(text) {
604
+ return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
646
605
  }
647
- /**
648
- * TODO: [🌺] Use some intermediate util splitWords
649
- */
650
-
651
- /**
652
- * Execution type describes the way how the block is executed
653
- *
654
- * @see https://github.com/webgptorg/promptbook#execution-type
655
- */
656
- var ExecutionTypes = [
657
- 'PROMPT_TEMPLATE',
658
- 'SIMPLE_TEMPLATE',
659
- 'SCRIPT',
660
- 'PROMPT_DIALOG',
661
- // <- [🥻] Insert here when making new command
662
- ];
663
-
664
- /**
665
- * Units of text measurement
666
- */
667
- var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'LINES', 'PARAGRAPHS', 'PAGES'];
668
- /**
669
- * TODO: [💝] Unite object for expecting amount and format - remove expectFormat
670
- * TODO: use one helper type> (string_prompt | string_javascript | string_markdown) & string_template
671
- * TODO: [👙][🧠] Just selecting gpt3 or gpt4 level of model
672
- */
673
606
 
674
607
  /**
675
- * Removes Markdown formatting tags from a string.
676
- *
677
- * @param {string} str - The string to remove Markdown tags from.
678
- * @returns {string} The input string with all Markdown tags removed.
608
+ * Split text into sentences
679
609
  */
680
- function removeMarkdownFormatting(str) {
681
- // Remove bold formatting
682
- str = str.replace(/\*\*(.*?)\*\*/g, '$1');
683
- // Remove italic formatting
684
- str = str.replace(/\*(.*?)\*/g, '$1');
685
- // Remove code formatting
686
- str = str.replace(/`(.*?)`/g, '$1');
687
- return str;
610
+ function splitIntoSentences(text) {
611
+ return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
688
612
  }
689
-
690
613
  /**
691
- * Function parseNumber will parse number from string
692
- *
693
- * Unlike Number.parseInt, Number.parseFloat it will never ever result in NaN
694
- * Note: it also works only with decimal numbers
695
- *
696
- * @returns parsed number
697
- * @throws {PromptbookSyntaxError} if the value is not a number
698
- *
699
- * @private within the parseCommand
614
+ * Counts number of sentences in the text
700
615
  */
701
- function parseNumber(value) {
702
- var originalValue = value;
703
- if (typeof value === 'number') {
704
- value = value.toString(); // <- TODO: Maybe more efficient way to do this
705
- }
706
- if (typeof value !== 'string') {
707
- return 0;
708
- }
709
- value = value.trim();
710
- if (value.startsWith('+')) {
711
- return parseNumber(value.substring(1));
712
- }
713
- if (value.startsWith('-')) {
714
- var number = parseNumber(value.substring(1));
715
- if (number === 0) {
716
- return 0; // <- Note: To prevent -0
717
- }
718
- return -number;
719
- }
720
- value = value.replace(/,/g, '.');
721
- value = value.toUpperCase();
722
- if (value === '') {
723
- return 0;
724
- }
725
- if (value === '♾' || value.startsWith('INF')) {
726
- return Infinity;
727
- }
728
- if (value.includes('/')) {
729
- var _a = __read(value.split('/'), 2), numerator_ = _a[0], denominator_ = _a[1];
730
- var numerator = parseNumber(numerator_);
731
- var denominator = parseNumber(denominator_);
732
- if (denominator === 0) {
733
- throw new PromptbookSyntaxError("Unable to parse number from \"".concat(originalValue, "\" because denominator is zero"));
734
- }
735
- return numerator / denominator;
736
- }
737
- if (/^(NAN|NULL|NONE|UNDEFINED|ZERO|NO.*)$/.test(value)) {
738
- return 0;
739
- }
740
- if (value.includes('E')) {
741
- var _b = __read(value.split('E'), 2), significand = _b[0], exponent = _b[1];
742
- return parseNumber(significand) * Math.pow(10, parseNumber(exponent));
743
- }
744
- if (!/^[0-9.]+$/.test(value) || value.split('.').length > 2) {
745
- throw new PromptbookSyntaxError("Unable to parse number from \"".concat(originalValue, "\""));
746
- }
747
- var num = parseFloat(value);
748
- if (isNaN(num)) {
749
- throw new PromptbookSyntaxError("Unexpected NaN when parsing number from \"".concat(originalValue, "\""));
750
- }
751
- return num;
752
- }
753
- /**
754
- * TODO: Maybe use sth. like safe-eval in fraction/calculation case @see https://www.npmjs.com/package/safe-eval
755
- */
756
-
757
- /**
758
- * Parses one line of ul/ol to command
759
- *
760
- * @returns parsed command object
761
- * @throws {PromptbookSyntaxError} if the command is invalid
762
- *
763
- * @private within the promptbookStringToJson
764
- */
765
- function parseCommand(listItem) {
766
- var e_1, _a;
767
- if (listItem.includes('\n') || listItem.includes('\r')) {
768
- throw new PromptbookSyntaxError('Command can not contain new line characters:');
769
- }
770
- var type = listItem.trim();
771
- type = type.split('`').join('');
772
- type = type.split('"').join('');
773
- type = type.split("'").join('');
774
- type = type.split('~').join('');
775
- type = type.split('[').join('');
776
- type = type.split(']').join('');
777
- type = type.split('(').join('');
778
- type = type.split(')').join('');
779
- type = normalizeTo_SCREAMING_CASE(type);
780
- type = type.split('DIALOGUE').join('DIALOG');
781
- var listItemParts = listItem
782
- .split(' ')
783
- .map(function (part) { return part.trim(); })
784
- .filter(function (item) { return item !== ''; })
785
- .filter(function (item) { return !/^PTBK$/i.test(item); })
786
- .filter(function (item) { return !/^PROMPTBOOK$/i.test(item); })
787
- .map(removeMarkdownFormatting);
788
- if (type.startsWith('URL') ||
789
- type.startsWith('PTBK_URL') ||
790
- type.startsWith('PTBKURL') ||
791
- type.startsWith('PROMPTBOOK_URL') ||
792
- type.startsWith('PROMPTBOOKURL') ||
793
- type.startsWith('HTTPS')) {
794
- if (!(listItemParts.length === 2 || (listItemParts.length === 1 && type.startsWith('HTTPS')))) {
795
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n ")));
796
- }
797
- var promptbookUrlString = listItemParts.pop();
798
- var promptbookUrl = new URL(promptbookUrlString);
799
- if (promptbookUrl.protocol !== 'https:') {
800
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n Protocol must be HTTPS\n ")));
801
- }
802
- if (promptbookUrl.hash !== '') {
803
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n URL must not contain hash\n Hash is used for identification of the prompt template in the pipeline\n ")));
804
- }
805
- return {
806
- type: 'PROMPTBOOK_URL',
807
- promptbookUrl: promptbookUrl,
808
- };
809
- }
810
- else if (type.startsWith('PROMPTBOOK_VERSION') || type.startsWith('PTBK_VERSION')) {
811
- if (listItemParts.length !== 2) {
812
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_VERSION command:\n\n - ".concat(listItem, "\n ")));
813
- }
814
- var promptbookVersion = listItemParts.pop();
815
- // TODO: Validate version
816
- return {
817
- type: 'PROMPTBOOK_VERSION',
818
- promptbookVersion: promptbookVersion,
819
- };
820
- }
821
- else if (type.startsWith('EXECUTE') ||
822
- type.startsWith('EXEC') ||
823
- type.startsWith('PROMPT_DIALOG') ||
824
- type.startsWith('SIMPLE_TEMPLATE')) {
825
- var executionTypes = ExecutionTypes.filter(function (executionType) { return type.includes(executionType); });
826
- if (executionTypes.length !== 1) {
827
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type in command:\n\n - ".concat(listItem, "\n\n Supported execution types are:\n ").concat(block(ExecutionTypes.join(', ')), "\n "); }));
828
- }
829
- return {
830
- type: 'EXECUTE',
831
- executionType: executionTypes[0],
832
- };
833
- }
834
- else if (type.startsWith('MODEL')) {
835
- // TODO: Make this more elegant and dynamically
836
- if (type.startsWith('MODEL_VARIANT')) {
837
- if (type === 'MODEL_VARIANT_CHAT') {
838
- return {
839
- type: 'MODEL',
840
- key: 'modelVariant',
841
- value: 'CHAT',
842
- };
843
- }
844
- else if (type === 'MODEL_VARIANT_COMPLETION') {
845
- return {
846
- type: 'MODEL',
847
- key: 'modelVariant',
848
- value: 'COMPLETION',
849
- };
850
- }
851
- else {
852
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model variant in command:\n\n - ".concat(listItem, "\n\n Supported variants are:\n ").concat(block(['CHAT', 'COMPLETION'].join(', ')), "\n "); }));
853
- }
854
- }
855
- if (type.startsWith('MODEL_NAME')) {
856
- return {
857
- type: 'MODEL',
858
- key: 'modelName',
859
- value: listItemParts.pop(),
860
- };
861
- }
862
- else {
863
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model key in command:\n\n - ".concat(listItem, "\n\n Supported model keys are:\n ").concat(block(['variant', 'name'].join(', ')), "\n\n Example:\n\n - MODEL VARIANT Chat\n - MODEL NAME gpt-4\n "); }));
864
- }
865
- }
866
- else if (type.startsWith('PARAM') ||
867
- type.startsWith('INPUT_PARAM') ||
868
- type.startsWith('OUTPUT_PARAM') ||
869
- listItem.startsWith('{') ||
870
- listItem.startsWith('> {') /* <- Note: This is a bit hack to parse return parameters defined at the end of each section */) {
871
- var parametersMatch = listItem.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
872
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
873
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
874
- }
875
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
876
- var _b = parametersMatch.groups, parameterName = _b.parameterName, parameterDescription = _b.parameterDescription;
877
- if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
878
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Parameter {".concat(parameterName, "} can not contain another parameter in description:\n\n - ").concat(listItem, "\n ")));
879
- }
880
- var isInput = type.startsWith('INPUT');
881
- var isOutput = type.startsWith('OUTPUT');
882
- if (listItem.startsWith('> {')) {
883
- isInput = false;
884
- isOutput = false;
885
- }
886
- return {
887
- type: 'PARAMETER',
888
- parameterName: parameterName,
889
- parameterDescription: parameterDescription.trim() || null,
890
- isInput: isInput,
891
- isOutput: isOutput,
892
- };
893
- }
894
- else if (type.startsWith('JOKER')) {
895
- if (listItemParts.length !== 2) {
896
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid JOKER command:\n\n - ".concat(listItem, "\n ")));
897
- }
898
- var parametersMatch = (listItemParts.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
899
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
900
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
901
- }
902
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
903
- var parameterName = parametersMatch.groups.parameterName;
904
- return {
905
- type: 'JOKER',
906
- parameterName: parameterName,
907
- };
908
- }
909
- else if (type.startsWith('POSTPROCESS') || type.startsWith('POST_PROCESS')) {
910
- if (listItemParts.length !== 2) {
911
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid POSTPROCESSING command:\n\n - ".concat(listItem, "\n ")));
912
- }
913
- var functionName = listItemParts.pop();
914
- return {
915
- type: 'POSTPROCESS',
916
- functionName: functionName,
917
- };
918
- }
919
- else if (type.startsWith('EXPECT_JSON')) {
920
- return {
921
- type: 'EXPECT_FORMAT',
922
- format: 'JSON',
923
- };
924
- // [🥤]
925
- }
926
- else if (type.startsWith('EXPECT')) {
927
- try {
928
- listItemParts.shift();
929
- var sign = void 0;
930
- var signRaw = listItemParts.shift();
931
- if (/^exact/i.test(signRaw)) {
932
- sign = 'EXACTLY';
933
- }
934
- else if (/^min/i.test(signRaw)) {
935
- sign = 'MINIMUM';
936
- }
937
- else if (/^max/i.test(signRaw)) {
938
- sign = 'MAXIMUM';
939
- }
940
- else {
941
- throw new PromptbookSyntaxError("Invalid sign \"".concat(signRaw, "\", expected EXACTLY, MIN or MAX"));
942
- }
943
- var amountRaw = listItemParts.shift();
944
- var amount = parseNumber(amountRaw);
945
- if (amount < 0) {
946
- throw new PromptbookSyntaxError('Amount must be positive number or zero');
947
- }
948
- if (amount !== Math.floor(amount)) {
949
- throw new PromptbookSyntaxError('Amount must be whole number');
950
- }
951
- var unitRaw = listItemParts.shift();
952
- var unit = undefined;
953
- try {
954
- for (var EXPECTATION_UNITS_1 = __values(EXPECTATION_UNITS), EXPECTATION_UNITS_1_1 = EXPECTATION_UNITS_1.next(); !EXPECTATION_UNITS_1_1.done; EXPECTATION_UNITS_1_1 = EXPECTATION_UNITS_1.next()) {
955
- var existingUnit = EXPECTATION_UNITS_1_1.value;
956
- var existingUnitText = existingUnit;
957
- existingUnitText = existingUnitText.substring(0, existingUnitText.length - 1);
958
- if (existingUnitText === 'CHARACTER') {
959
- existingUnitText = 'CHAR';
960
- }
961
- if (new RegExp("^".concat(existingUnitText.toLowerCase())).test(unitRaw.toLowerCase()) ||
962
- new RegExp("^".concat(unitRaw.toLowerCase())).test(existingUnitText.toLowerCase())) {
963
- if (unit !== undefined) {
964
- throw new PromptbookSyntaxError("Ambiguous unit \"".concat(unitRaw, "\""));
965
- }
966
- unit = existingUnit;
967
- }
968
- }
969
- }
970
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
971
- finally {
972
- try {
973
- if (EXPECTATION_UNITS_1_1 && !EXPECTATION_UNITS_1_1.done && (_a = EXPECTATION_UNITS_1.return)) _a.call(EXPECTATION_UNITS_1);
974
- }
975
- finally { if (e_1) throw e_1.error; }
976
- }
977
- if (unit === undefined) {
978
- throw new PromptbookSyntaxError("Invalid unit \"".concat(unitRaw, "\""));
979
- }
980
- return {
981
- type: 'EXPECT_AMOUNT',
982
- sign: sign,
983
- unit: unit,
984
- amount: amount,
985
- };
986
- }
987
- catch (error) {
988
- if (!(error instanceof Error)) {
989
- throw error;
990
- }
991
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid EXPECT command; ".concat(error.message, ":\n\n - ").concat(listItem, "\n ")));
992
- }
993
- /*
994
- } else if (type.startsWith('__________________')) {
995
- // <- [🥻] Insert here when making new command
996
- */
997
- }
998
- else {
999
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Unknown command:\n\n - ".concat(listItem, "\n\n Supported commands are:\n - PROMPTBOOK_URL <url>\n - PROMPTBOOK_VERSION <version>\n - EXECUTE PROMPT TEMPLATE\n - EXECUTE SIMPLE TEMPLATE\n - SIMPLE TEMPLATE\n - EXECUTE SCRIPT\n - EXECUTE PROMPT_DIALOG'\n - PROMPT_DIALOG'\n - MODEL NAME <name>\n - MODEL VARIANT <\"Chat\"|\"Completion\">\n - INPUT PARAM {<name>} <description>\n - OUTPUT PARAM {<name>} <description>\n - POSTPROCESS `{functionName}`\n - JOKER {<name>}\n - EXPECT JSON\n - EXPECT <\"Exactly\"|\"Min\"|\"Max\"> <number> <\"Chars\"|\"Words\"|\"Sentences\"|\"Paragraphs\"|\"Pages\">\n\n ")));
1000
- }
616
+ function countSentences(text) {
617
+ return splitIntoSentences(text).length;
1001
618
  }
1002
619
 
1003
620
  var defaultDiacriticsRemovalMap = [
@@ -1252,674 +869,744 @@
1252
869
  });
1253
870
  }
1254
871
 
1255
- /* tslint:disable */
1256
- function normalizeToKebabCase(sentence) {
872
+ /**
873
+ * Counts number of words in the text
874
+ */
875
+ function countWords(text) {
876
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
877
+ text = removeDiacritics(text);
878
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
879
+ }
880
+
881
+ /**
882
+ * Index of all counter functions
883
+ */
884
+ var CountUtils = {
885
+ CHARACTERS: countCharacters,
886
+ WORDS: countWords,
887
+ SENTENCES: countSentences,
888
+ PARAGRAPHS: countParagraphs,
889
+ LINES: countLines,
890
+ PAGES: countPages,
891
+ };
892
+
893
+ /**
894
+ * Function checkExpectations will check if the expectations on given value are met
895
+ *
896
+ * Note: There are two simmilar functions:
897
+ * - `checkExpectations` which throws an error if the expectations are not met
898
+ * - `isPassingExpectations` which returns a boolean
899
+ *
900
+ * @throws {ExpectError} if the expectations are not met
901
+ * @returns {void} Nothing
902
+ */
903
+ function checkExpectations(expectations, value) {
1257
904
  var e_1, _a;
1258
- sentence = removeDiacritics(sentence);
1259
- var charType;
1260
- var lastCharType = 'OTHER';
1261
- var normalizedName = '';
1262
905
  try {
1263
- for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
1264
- var char = sentence_1_1.value;
1265
- var normalizedChar = void 0;
1266
- if (/^[a-z]$/.test(char)) {
1267
- charType = 'LOWERCASE';
1268
- normalizedChar = char;
1269
- }
1270
- else if (/^[A-Z]$/.test(char)) {
1271
- charType = 'UPPERCASE';
1272
- normalizedChar = char.toLowerCase();
1273
- }
1274
- else if (/^[0-9]$/.test(char)) {
1275
- charType = 'NUMBER';
1276
- normalizedChar = char;
1277
- }
1278
- else if (/^\/$/.test(char)) {
1279
- charType = 'SLASH';
1280
- normalizedChar = char;
1281
- }
1282
- else {
1283
- charType = 'OTHER';
1284
- normalizedChar = '-';
906
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
907
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
908
+ var amount = CountUtils[unit.toUpperCase()](value);
909
+ if (min && amount < min) {
910
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
911
+ } /* not else */
912
+ if (max && amount > max) {
913
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
1285
914
  }
1286
- if (charType !== lastCharType &&
1287
- !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
1288
- !(lastCharType === 'NUMBER') &&
1289
- !(charType === 'NUMBER')) {
1290
- normalizedName += '-';
1291
- }
1292
- normalizedName += normalizedChar;
1293
- lastCharType = charType;
1294
915
  }
1295
916
  }
1296
917
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
1297
918
  finally {
1298
919
  try {
1299
- if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
920
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
1300
921
  }
1301
922
  finally { if (e_1) throw e_1.error; }
1302
923
  }
1303
- normalizedName = normalizedName.split(/-+/g).join('-');
1304
- normalizedName = normalizedName.split(/-?\/-?/g).join('/');
1305
- normalizedName = normalizedName.replace(/^-/, '');
1306
- normalizedName = normalizedName.replace(/-$/, '');
1307
- return normalizedName;
1308
924
  }
925
+ /**
926
+ * TODO: [💝] Unite object for expecting amount and format
927
+ */
1309
928
 
1310
929
  /**
1311
- * Removes emojis from a string and fix whitespaces
930
+ * This error occurs during the parameter replacement in the template
1312
931
  *
1313
- * @param text with emojis
1314
- * @returns text without emojis
932
+ * Note: This is a kindof subtype of PromptbookExecutionError because it occurs during the execution of the pipeline
1315
933
  */
1316
- function removeEmojis(text) {
1317
- // Replace emojis (and also ZWJ sequence) with hyphens
1318
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
1319
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
1320
- text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
1321
- text = text.replace(/\p{Extended_Pictographic}/gu, '');
1322
- return text;
1323
- }
934
+ var TemplateError = /** @class */ (function (_super) {
935
+ __extends(TemplateError, _super);
936
+ function TemplateError(message) {
937
+ var _this = _super.call(this, message) || this;
938
+ _this.name = 'TemplateError';
939
+ Object.setPrototypeOf(_this, TemplateError.prototype);
940
+ return _this;
941
+ }
942
+ return TemplateError;
943
+ }(Error));
1324
944
 
1325
945
  /**
1326
- * Function normalizes title to name which can be used as identifier
946
+ * Replaces parameters in template with values from parameters object
947
+ *
948
+ * @param template the template with parameters in {curly} braces
949
+ * @param parameters the object with parameters
950
+ * @returns the template with replaced parameters
951
+ * @throws {TemplateError} if parameter is not defined, not closed, or not opened
952
+ *
953
+ * @private within the createPromptbookExecutor
1327
954
  */
1328
- function titleToName(value) {
1329
- value = removeEmojis(value);
1330
- value = normalizeToKebabCase(value);
1331
- // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
1332
- return value;
955
+ function replaceParameters(template, parameters) {
956
+ var replacedTemplate = template;
957
+ var match;
958
+ var loopLimit = LOOP_LIMIT;
959
+ var _loop_1 = function () {
960
+ if (loopLimit-- < 0) {
961
+ throw new UnexpectedError('Loop limit reached during parameters replacement in `replaceParameters`');
962
+ }
963
+ var precol = match.groups.precol;
964
+ var parameterName = match.groups.parameterName;
965
+ if (parameterName === '') {
966
+ return "continue";
967
+ }
968
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
969
+ throw new TemplateError('Parameter is already opened or not closed');
970
+ }
971
+ if (parameters[parameterName] === undefined) {
972
+ throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
973
+ }
974
+ var parameterValue = parameters[parameterName];
975
+ if (parameterValue === undefined) {
976
+ throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
977
+ }
978
+ parameterValue = parameterValue.toString();
979
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
980
+ parameterValue = parameterValue
981
+ .split('\n')
982
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
983
+ .join('\n');
984
+ }
985
+ replacedTemplate =
986
+ replacedTemplate.substring(0, match.index + precol.length) +
987
+ parameterValue +
988
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
989
+ };
990
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
991
+ .exec(replacedTemplate))) {
992
+ _loop_1();
993
+ }
994
+ // [💫] Check if there are parameters that are not closed properly
995
+ if (/{\w+$/.test(replacedTemplate)) {
996
+ throw new TemplateError('Parameter is not closed');
997
+ }
998
+ // [💫] Check if there are parameters that are not opened properly
999
+ if (/^\w+}/.test(replacedTemplate)) {
1000
+ throw new TemplateError('Parameter is not opened');
1001
+ }
1002
+ return replacedTemplate;
1333
1003
  }
1334
1004
 
1335
1005
  /**
1336
- * Compile promptbook from string (markdown) format to JSON format
1337
- *
1338
- * @param promptbookString {Promptbook} in string markdown format (.ptbk.md)
1339
- * @param options - Options and tools for the compilation
1340
- * @returns {Promptbook} compiled in JSON format (.ptbk.json)
1341
- * @throws {PromptbookSyntaxError} if the promptbook string is not valid
1006
+ * Creates executor function from promptbook and execution tools.
1342
1007
  *
1343
- * Note: This function does not validate logic of the pipeline only the syntax
1344
- * Note: This function acts as compilation process
1008
+ * @returns The executor function
1009
+ * @throws {PromptbookLogicError} on logical error in the promptbook
1345
1010
  */
1346
- function promptbookStringToJson(promptbookString, options) {
1347
- if (options === void 0) { options = {}; }
1348
- return __awaiter(this, void 0, void 0, function () {
1349
- var llmTools, promptbookJson, knowledge, addParam, markdownStructure, markdownStructureDeepness, description, defaultModelRequirements, listItems, listItems_1, listItems_1_1, listItem, command, _loop_1, _a, _b, section;
1350
- var e_1, _c, e_2, _d;
1351
- return __generator(this, function (_e) {
1352
- switch (_e.label) {
1353
- case 0:
1354
- llmTools = options.llmTools;
1355
- promptbookJson = {
1011
+ function createPromptbookExecutor(options) {
1012
+ var _this = this;
1013
+ var promptbook = options.promptbook, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
1014
+ var _b = settings.maxExecutionAttempts, maxExecutionAttempts = _b === void 0 ? 3 : _b;
1015
+ validatePromptbook(promptbook);
1016
+ var promptbookExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
1017
+ function executeSingleTemplate(currentTemplate) {
1018
+ return __awaiter(this, void 0, void 0, function () {
1019
+ var name, title, priority, prompt, chatThread, completionResult, result, resultString, expectError, scriptExecutionErrors, maxAttempts, jokers, attempt, isJokerAttempt, joker, _a, _b, _c, _d, scriptTools, error_2, e_2_1, _e, _f, functionName, postprocessingError, _g, _h, scriptTools, error_3, e_3_1, e_4_1, error_4;
1020
+ var e_2, _j, e_4, _k, e_3, _l, _m;
1021
+ var _this = this;
1022
+ return __generator(this, function (_o) {
1023
+ switch (_o.label) {
1024
+ case 0:
1025
+ name = "promptbook-executor-frame-".concat(currentTemplate.name);
1026
+ title = currentTemplate.title;
1027
+ priority = promptbook.promptTemplates.length - promptbook.promptTemplates.indexOf(currentTemplate);
1028
+ if (!onProgress /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
1029
+ return [4 /*yield*/, onProgress({
1030
+ name: name,
1031
+ title: title,
1032
+ isStarted: false,
1033
+ isDone: false,
1034
+ executionType: currentTemplate.executionType,
1035
+ parameterName: currentTemplate.resultingParameterName,
1036
+ parameterValue: null,
1037
+ // <- [3]
1038
+ })];
1039
+ case 1:
1040
+ _o.sent();
1041
+ _o.label = 2;
1042
+ case 2:
1043
+ result = null;
1044
+ resultString = null;
1045
+ expectError = null;
1046
+ maxAttempts = currentTemplate.executionType === 'PROMPT_DIALOG' ? Infinity : maxExecutionAttempts;
1047
+ jokers = currentTemplate.jokers || [];
1048
+ attempt = -jokers.length;
1049
+ _o.label = 3;
1050
+ case 3:
1051
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 49];
1052
+ isJokerAttempt = attempt < 0;
1053
+ joker = jokers[jokers.length + attempt];
1054
+ if (isJokerAttempt && !joker) {
1055
+ throw new UnexpectedError("Joker not found in attempt ".concat(attempt));
1056
+ }
1057
+ result = null;
1058
+ resultString = null;
1059
+ expectError = null;
1060
+ if (isJokerAttempt) {
1061
+ if (typeof parametersToPass[joker] === 'undefined') {
1062
+ throw new PromptbookExecutionError("Joker parameter {".concat(joker, "} not defined"));
1063
+ }
1064
+ resultString = parametersToPass[joker];
1065
+ }
1066
+ _o.label = 4;
1067
+ case 4:
1068
+ _o.trys.push([4, 45, 46, 47]);
1069
+ if (!!isJokerAttempt) return [3 /*break*/, 27];
1070
+ _a = currentTemplate.executionType;
1071
+ switch (_a) {
1072
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 5];
1073
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 6];
1074
+ case 'SCRIPT': return [3 /*break*/, 13];
1075
+ case 'PROMPT_DIALOG': return [3 /*break*/, 24];
1076
+ }
1077
+ return [3 /*break*/, 26];
1078
+ case 5:
1079
+ resultString = replaceParameters(currentTemplate.content, parametersToPass);
1080
+ return [3 /*break*/, 27];
1081
+ case 6:
1082
+ prompt = {
1083
+ title: currentTemplate.title,
1084
+ promptbookUrl: "".concat(promptbook.promptbookUrl
1085
+ ? promptbook.promptbookUrl
1086
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous PROMPTBOOKs, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
1087
+ parameters: parametersToPass,
1088
+ content: replaceParameters(currentTemplate.content, parametersToPass) /* <- [2] */,
1089
+ modelRequirements: currentTemplate.modelRequirements,
1090
+ expectations: currentTemplate.expectations,
1091
+ expectFormat: currentTemplate.expectFormat,
1092
+ postprocessing: (currentTemplate.postprocessing || []).map(function (functionName) { return function (result) { return __awaiter(_this, void 0, void 0, function () {
1093
+ var errors, _a, _b, scriptTools, error_5, e_5_1;
1094
+ var e_5, _c;
1095
+ return __generator(this, function (_d) {
1096
+ switch (_d.label) {
1097
+ case 0:
1098
+ errors = [];
1099
+ _d.label = 1;
1100
+ case 1:
1101
+ _d.trys.push([1, 8, 9, 10]);
1102
+ _a = __values(tools.script), _b = _a.next();
1103
+ _d.label = 2;
1104
+ case 2:
1105
+ if (!!_b.done) return [3 /*break*/, 7];
1106
+ scriptTools = _b.value;
1107
+ _d.label = 3;
1108
+ case 3:
1109
+ _d.trys.push([3, 5, , 6]);
1110
+ return [4 /*yield*/, scriptTools.execute({
1111
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
1112
+ script: "".concat(functionName, "(result)"),
1113
+ parameters: {
1114
+ result: result || '',
1115
+ // Note: No ...parametersToPass, because working with result only
1116
+ },
1117
+ })];
1118
+ case 4: return [2 /*return*/, _d.sent()];
1119
+ case 5:
1120
+ error_5 = _d.sent();
1121
+ if (!(error_5 instanceof Error)) {
1122
+ throw error_5;
1123
+ }
1124
+ errors.push(error_5);
1125
+ return [3 /*break*/, 6];
1126
+ case 6:
1127
+ _b = _a.next();
1128
+ return [3 /*break*/, 2];
1129
+ case 7: return [3 /*break*/, 10];
1130
+ case 8:
1131
+ e_5_1 = _d.sent();
1132
+ e_5 = { error: e_5_1 };
1133
+ return [3 /*break*/, 10];
1134
+ case 9:
1135
+ try {
1136
+ if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
1137
+ }
1138
+ finally { if (e_5) throw e_5.error; }
1139
+ return [7 /*endfinally*/];
1140
+ case 10:
1141
+ if (errors.length === 0) {
1142
+ throw new PromptbookExecutionError('Postprocessing in LlmExecutionTools failed because no ScriptExecutionTools were provided');
1143
+ }
1144
+ else if (errors.length === 1) {
1145
+ throw errors[0];
1146
+ }
1147
+ else {
1148
+ throw new PromptbookExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Postprocessing in LlmExecutionTools failed ".concat(errors.length, "x\n\n ").concat(block(errors.map(function (error) { return '- ' + error.message; }).join('\n\n')), "\n "); }));
1149
+ }
1150
+ }
1151
+ });
1152
+ }); }; }),
1153
+ };
1154
+ _b = currentTemplate.modelRequirements.modelVariant;
1155
+ switch (_b) {
1156
+ case 'CHAT': return [3 /*break*/, 7];
1157
+ case 'COMPLETION': return [3 /*break*/, 9];
1158
+ }
1159
+ return [3 /*break*/, 11];
1160
+ case 7: return [4 /*yield*/, tools.llm.gptChat(prompt)];
1161
+ case 8:
1162
+ chatThread = _o.sent();
1163
+ // TODO: [🍬] Destroy chatThread
1164
+ result = chatThread;
1165
+ resultString = chatThread.content;
1166
+ return [3 /*break*/, 12];
1167
+ case 9: return [4 /*yield*/, tools.llm.gptComplete(prompt)];
1168
+ case 10:
1169
+ completionResult = _o.sent();
1170
+ result = completionResult;
1171
+ resultString = completionResult.content;
1172
+ return [3 /*break*/, 12];
1173
+ case 11: throw new PromptbookExecutionError("Unknown model variant \"".concat(currentTemplate.modelRequirements.modelVariant, "\""));
1174
+ case 12: return [3 /*break*/, 27];
1175
+ case 13:
1176
+ if (tools.script.length === 0) {
1177
+ throw new PromptbookExecutionError('No script execution tools are available');
1178
+ }
1179
+ if (!currentTemplate.contentLanguage) {
1180
+ throw new PromptbookExecutionError("Script language is not defined for prompt template \"".concat(currentTemplate.name, "\""));
1181
+ }
1182
+ // TODO: DRY [1]
1183
+ scriptExecutionErrors = [];
1184
+ _o.label = 14;
1185
+ case 14:
1186
+ _o.trys.push([14, 21, 22, 23]);
1187
+ _c = (e_2 = void 0, __values(tools.script)), _d = _c.next();
1188
+ _o.label = 15;
1189
+ case 15:
1190
+ if (!!_d.done) return [3 /*break*/, 20];
1191
+ scriptTools = _d.value;
1192
+ _o.label = 16;
1193
+ case 16:
1194
+ _o.trys.push([16, 18, , 19]);
1195
+ return [4 /*yield*/, scriptTools.execute({
1196
+ scriptLanguage: currentTemplate.contentLanguage,
1197
+ script: currentTemplate.content,
1198
+ parameters: parametersToPass,
1199
+ })];
1200
+ case 17:
1201
+ resultString = _o.sent();
1202
+ return [3 /*break*/, 20];
1203
+ case 18:
1204
+ error_2 = _o.sent();
1205
+ if (!(error_2 instanceof Error)) {
1206
+ throw error_2;
1207
+ }
1208
+ scriptExecutionErrors.push(error_2);
1209
+ return [3 /*break*/, 19];
1210
+ case 19:
1211
+ _d = _c.next();
1212
+ return [3 /*break*/, 15];
1213
+ case 20: return [3 /*break*/, 23];
1214
+ case 21:
1215
+ e_2_1 = _o.sent();
1216
+ e_2 = { error: e_2_1 };
1217
+ return [3 /*break*/, 23];
1218
+ case 22:
1219
+ try {
1220
+ if (_d && !_d.done && (_j = _c.return)) _j.call(_c);
1221
+ }
1222
+ finally { if (e_2) throw e_2.error; }
1223
+ return [7 /*endfinally*/];
1224
+ case 23:
1225
+ if (resultString !== null) {
1226
+ return [3 /*break*/, 27];
1227
+ }
1228
+ if (scriptExecutionErrors.length === 1) {
1229
+ throw scriptExecutionErrors[0];
1230
+ }
1231
+ else {
1232
+ throw new PromptbookExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptExecutionErrors.length, " times\n\n ").concat(block(scriptExecutionErrors
1233
+ .map(function (error) { return '- ' + error.message; })
1234
+ .join('\n\n')), "\n "); }));
1235
+ }
1236
+ case 24:
1237
+ if (tools.userInterface === undefined) {
1238
+ throw new PromptbookExecutionError('User interface tools are not available');
1239
+ }
1240
+ return [4 /*yield*/, tools.userInterface.promptDialog({
1241
+ promptTitle: currentTemplate.title,
1242
+ promptMessage: replaceParameters(currentTemplate.description || '', parametersToPass),
1243
+ defaultValue: replaceParameters(currentTemplate.content, parametersToPass),
1244
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
1245
+ placeholder: undefined,
1246
+ priority: priority,
1247
+ })];
1248
+ case 25:
1249
+ // TODO: [🌹] When making next attempt for `PROMPT DIALOG`, preserve the previous user input
1250
+ resultString = _o.sent();
1251
+ return [3 /*break*/, 27];
1252
+ case 26: throw new PromptbookExecutionError(
1356
1253
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1357
- title: undefined /* <- Note: Putting here placeholder to keep `title` on top at final JSON */,
1358
- promptbookUrl: undefined /* <- Note: Putting here placeholder to keep `promptbookUrl` on top at final JSON */,
1359
- promptbookVersion: PROMPTBOOK_VERSION,
1360
- description: undefined /* <- Note: Putting here placeholder to keep `description` on top at final JSON */,
1361
- parameters: [],
1362
- promptTemplates: [],
1363
- knowledge: [],
1254
+ "Unknown execution type \"".concat(currentTemplate.executionType, "\""));
1255
+ case 27:
1256
+ if (!(!isJokerAttempt && currentTemplate.postprocessing)) return [3 /*break*/, 44];
1257
+ _o.label = 28;
1258
+ case 28:
1259
+ _o.trys.push([28, 42, 43, 44]);
1260
+ _e = (e_4 = void 0, __values(currentTemplate.postprocessing)), _f = _e.next();
1261
+ _o.label = 29;
1262
+ case 29:
1263
+ if (!!_f.done) return [3 /*break*/, 41];
1264
+ functionName = _f.value;
1265
+ // TODO: DRY [1]
1266
+ scriptExecutionErrors = [];
1267
+ postprocessingError = null;
1268
+ _o.label = 30;
1269
+ case 30:
1270
+ _o.trys.push([30, 37, 38, 39]);
1271
+ _g = (e_3 = void 0, __values(tools.script)), _h = _g.next();
1272
+ _o.label = 31;
1273
+ case 31:
1274
+ if (!!_h.done) return [3 /*break*/, 36];
1275
+ scriptTools = _h.value;
1276
+ _o.label = 32;
1277
+ case 32:
1278
+ _o.trys.push([32, 34, , 35]);
1279
+ return [4 /*yield*/, scriptTools.execute({
1280
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
1281
+ script: "".concat(functionName, "(resultString)"),
1282
+ parameters: {
1283
+ resultString: resultString || '',
1284
+ // Note: No ...parametersToPass, because working with result only
1285
+ },
1286
+ })];
1287
+ case 33:
1288
+ resultString = _o.sent();
1289
+ postprocessingError = null;
1290
+ return [3 /*break*/, 36];
1291
+ case 34:
1292
+ error_3 = _o.sent();
1293
+ if (!(error_3 instanceof Error)) {
1294
+ throw error_3;
1295
+ }
1296
+ postprocessingError = error_3;
1297
+ scriptExecutionErrors.push(error_3);
1298
+ return [3 /*break*/, 35];
1299
+ case 35:
1300
+ _h = _g.next();
1301
+ return [3 /*break*/, 31];
1302
+ case 36: return [3 /*break*/, 39];
1303
+ case 37:
1304
+ e_3_1 = _o.sent();
1305
+ e_3 = { error: e_3_1 };
1306
+ return [3 /*break*/, 39];
1307
+ case 38:
1308
+ try {
1309
+ if (_h && !_h.done && (_l = _g.return)) _l.call(_g);
1310
+ }
1311
+ finally { if (e_3) throw e_3.error; }
1312
+ return [7 /*endfinally*/];
1313
+ case 39:
1314
+ if (postprocessingError) {
1315
+ throw postprocessingError;
1316
+ }
1317
+ _o.label = 40;
1318
+ case 40:
1319
+ _f = _e.next();
1320
+ return [3 /*break*/, 29];
1321
+ case 41: return [3 /*break*/, 44];
1322
+ case 42:
1323
+ e_4_1 = _o.sent();
1324
+ e_4 = { error: e_4_1 };
1325
+ return [3 /*break*/, 44];
1326
+ case 43:
1327
+ try {
1328
+ if (_f && !_f.done && (_k = _e.return)) _k.call(_e);
1329
+ }
1330
+ finally { if (e_4) throw e_4.error; }
1331
+ return [7 /*endfinally*/];
1332
+ case 44:
1333
+ // TODO: [💝] Unite object for expecting amount and format
1334
+ if (currentTemplate.expectFormat) {
1335
+ if (currentTemplate.expectFormat === 'JSON') {
1336
+ if (!isValidJsonString(resultString || '')) {
1337
+ throw new ExpectError('Expected valid JSON string');
1338
+ }
1339
+ }
1340
+ }
1341
+ // TODO: [💝] Unite object for expecting amount and format
1342
+ if (currentTemplate.expectations) {
1343
+ checkExpectations(currentTemplate.expectations, resultString || '');
1344
+ }
1345
+ return [3 /*break*/, 49];
1346
+ case 45:
1347
+ error_4 = _o.sent();
1348
+ if (!(error_4 instanceof ExpectError)) {
1349
+ throw error_4;
1350
+ }
1351
+ expectError = error_4;
1352
+ return [3 /*break*/, 47];
1353
+ case 46:
1354
+ if (!isJokerAttempt &&
1355
+ currentTemplate.executionType === 'PROMPT_TEMPLATE' &&
1356
+ prompt
1357
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
1358
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
1359
+ ) {
1360
+ // TODO: [🧠] Maybe put other executionTypes into report
1361
+ executionReport.promptExecutions.push({
1362
+ prompt: {
1363
+ title: currentTemplate.title /* <- Note: If title in promptbook contains emojis, pass it innto report */,
1364
+ content: prompt.content,
1365
+ modelRequirements: prompt.modelRequirements,
1366
+ expectations: prompt.expectations,
1367
+ expectFormat: prompt.expectFormat,
1368
+ // <- Note: Do want to pass ONLY wanted information to the report
1369
+ },
1370
+ result: result || undefined,
1371
+ error: expectError || undefined,
1372
+ });
1373
+ }
1374
+ return [7 /*endfinally*/];
1375
+ case 47:
1376
+ if (expectError !== null && attempt === maxAttempts - 1) {
1377
+ throw new PromptbookExecutionError(spaceTrim.spaceTrim(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ---\n Last error ").concat((expectError === null || expectError === void 0 ? void 0 : expectError.name) || '', ":\n ").concat(block((expectError === null || expectError === void 0 ? void 0 : expectError.message) || ''), "\n\n Last result:\n ").concat(resultString, "\n ---\n "); }));
1378
+ }
1379
+ _o.label = 48;
1380
+ case 48:
1381
+ attempt++;
1382
+ return [3 /*break*/, 3];
1383
+ case 49:
1384
+ if (resultString === null) {
1385
+ throw new UnexpectedError('Something went wrong and prompt result is null');
1386
+ }
1387
+ if (onProgress /* <- [3] */) {
1388
+ onProgress({
1389
+ name: name,
1390
+ title: title,
1391
+ isStarted: true,
1392
+ isDone: true,
1393
+ executionType: currentTemplate.executionType,
1394
+ parameterName: currentTemplate.resultingParameterName,
1395
+ parameterValue: resultString,
1396
+ // <- [3]
1397
+ });
1398
+ }
1399
+ parametersToPass = __assign(__assign({}, parametersToPass), (_m = {}, _m[currentTemplate.resultingParameterName] = resultString /* <- Note: Not need to detect parameter collision here because Promptbook checks logic consistency during construction */, _m));
1400
+ return [2 /*return*/];
1401
+ }
1402
+ });
1403
+ });
1404
+ }
1405
+ var parametersToPass, executionReport, resovedParameters_1, unresovedTemplates, resolving_1, loopLimit, _loop_1, error_1, usage_1, _a, _b, parameter, usage;
1406
+ var e_1, _c;
1407
+ return __generator(this, function (_d) {
1408
+ switch (_d.label) {
1409
+ case 0:
1410
+ parametersToPass = inputParameters;
1411
+ executionReport = {
1412
+ promptbookUrl: promptbook.promptbookUrl,
1413
+ title: promptbook.title,
1414
+ promptbookUsedVersion: PROMPTBOOK_VERSION,
1415
+ promptbookRequestedVersion: promptbook.promptbookVersion,
1416
+ description: promptbook.description,
1417
+ promptExecutions: [],
1364
1418
  };
1365
- if (!llmTools) return [3 /*break*/, 2];
1366
- return [4 /*yield*/, prepareKnowledgeFromMarkdown()];
1419
+ _d.label = 1;
1367
1420
  case 1:
1368
- knowledge = _e.sent();
1369
- console.info('!!!! knowledge', knowledge);
1370
- _e.label = 2;
1371
- case 2:
1372
- // =============================================================
1373
- // Note: 1️⃣ Normalization of the PROMPTBOOK string
1374
- promptbookString = removeContentComments(promptbookString);
1375
- promptbookString = promptbookString.replaceAll(/`\{(?<parameterName>[a-z0-9_]+)\}`/gi, '{$<parameterName>}');
1376
- promptbookString = promptbookString.replaceAll(/`->\s+\{(?<parameterName>[a-z0-9_]+)\}`/gi, '-> {$<parameterName>}');
1377
- addParam = function (parameterCommand) {
1378
- var parameterName = parameterCommand.parameterName, parameterDescription = parameterCommand.parameterDescription, isInput = parameterCommand.isInput, isOutput = parameterCommand.isOutput;
1379
- var existingParameter = promptbookJson.parameters.find(function (parameter) { return parameter.name === parameterName; });
1380
- if (existingParameter &&
1381
- existingParameter.description &&
1382
- existingParameter.description !== parameterDescription &&
1383
- parameterDescription) {
1384
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim(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 "); }));
1385
- }
1386
- if (existingParameter) {
1387
- if (parameterDescription) {
1388
- existingParameter.description = parameterDescription;
1421
+ _d.trys.push([1, 6, , 7]);
1422
+ resovedParameters_1 = promptbook.parameters
1423
+ .filter(function (_a) {
1424
+ var isInput = _a.isInput;
1425
+ return isInput;
1426
+ })
1427
+ .map(function (_a) {
1428
+ var name = _a.name;
1429
+ return name;
1430
+ });
1431
+ unresovedTemplates = __spreadArray([], __read(promptbook.promptTemplates), false);
1432
+ resolving_1 = [];
1433
+ loopLimit = LOOP_LIMIT;
1434
+ _loop_1 = function () {
1435
+ var currentTemplate, work_1;
1436
+ return __generator(this, function (_e) {
1437
+ switch (_e.label) {
1438
+ case 0:
1439
+ if (loopLimit-- < 0) {
1440
+ throw new UnexpectedError('Loop limit reached during resolving parameters promptbook execution');
1441
+ }
1442
+ currentTemplate = unresovedTemplates.find(function (template) {
1443
+ return template.dependentParameterNames.every(function (name) { return resovedParameters_1.includes(name); });
1444
+ });
1445
+ if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
1446
+ throw new UnexpectedError(spaceTrim.spaceTrim("\n Can not resolve some parameters\n\n Note: This should be catched during validatePromptbook\n "));
1447
+ case 1:
1448
+ if (!!currentTemplate) return [3 /*break*/, 3];
1449
+ /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
1450
+ case 2:
1451
+ /* [5] */ _e.sent();
1452
+ return [3 /*break*/, 4];
1453
+ case 3:
1454
+ unresovedTemplates = unresovedTemplates.filter(function (template) { return template !== currentTemplate; });
1455
+ work_1 = executeSingleTemplate(currentTemplate)
1456
+ .then(function () {
1457
+ resovedParameters_1 = __spreadArray(__spreadArray([], __read(resovedParameters_1), false), [currentTemplate.resultingParameterName], false);
1458
+ })
1459
+ .then(function () {
1460
+ resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
1461
+ });
1462
+ resolving_1.push(work_1);
1463
+ _e.label = 4;
1464
+ case 4: return [2 /*return*/];
1389
1465
  }
1390
- }
1391
- else {
1392
- promptbookJson.parameters.push({
1393
- name: parameterName,
1394
- description: parameterDescription || undefined,
1395
- isInput: isInput,
1396
- isOutput: isOutput,
1397
- });
1398
- }
1466
+ });
1399
1467
  };
1400
- markdownStructure = markdownToMarkdownStructure(promptbookString);
1401
- markdownStructureDeepness = countMarkdownStructureDeepness(markdownStructure);
1402
- if (markdownStructureDeepness !== 2) {
1403
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid markdown structure.\n The markdown must have exactly 2 levels of headings (one top-level section and one section for each template).\n Now it has ".concat(markdownStructureDeepness, " levels of headings.\n ")));
1404
- }
1405
- promptbookJson.title = markdownStructure.title;
1406
- description = markdownStructure.content;
1407
- // Note: Remove codeblocks
1408
- description = description.split(/^```.*^```/gms).join('');
1409
- //Note: Remove lists and return statement
1410
- description = description.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
1411
- description = spaceTrim.spaceTrim(description);
1412
- if (description === '') {
1413
- description = undefined;
1468
+ _d.label = 2;
1469
+ case 2:
1470
+ if (!(unresovedTemplates.length > 0)) return [3 /*break*/, 4];
1471
+ return [5 /*yield**/, _loop_1()];
1472
+ case 3:
1473
+ _d.sent();
1474
+ return [3 /*break*/, 2];
1475
+ case 4: return [4 /*yield*/, Promise.all(resolving_1)];
1476
+ case 5:
1477
+ _d.sent();
1478
+ return [3 /*break*/, 7];
1479
+ case 6:
1480
+ error_1 = _d.sent();
1481
+ if (!(error_1 instanceof Error)) {
1482
+ throw error_1;
1414
1483
  }
1415
- promptbookJson.description = description;
1416
- defaultModelRequirements = {};
1417
- listItems = extractAllListItemsFromMarkdown(markdownStructure.content);
1484
+ usage_1 = addUsage.apply(void 0, __spreadArray([], __read(executionReport.promptExecutions.map(function (_a) {
1485
+ var result = _a.result;
1486
+ return (result === null || result === void 0 ? void 0 : result.usage) || addUsage();
1487
+ })), false));
1488
+ return [2 /*return*/, {
1489
+ isSuccessful: false,
1490
+ errors: [error_1],
1491
+ usage: usage_1,
1492
+ executionReport: executionReport,
1493
+ outputParameters: parametersToPass,
1494
+ }];
1495
+ case 7:
1418
1496
  try {
1419
- for (listItems_1 = __values(listItems), listItems_1_1 = listItems_1.next(); !listItems_1_1.done; listItems_1_1 = listItems_1.next()) {
1420
- listItem = listItems_1_1.value;
1421
- command = parseCommand(listItem);
1422
- switch (command.type) {
1423
- case 'PROMPTBOOK_URL':
1424
- promptbookJson.promptbookUrl = command.promptbookUrl.href;
1425
- break;
1426
- case 'PROMPTBOOK_VERSION':
1427
- promptbookJson.promptbookVersion = command.promptbookVersion;
1428
- break;
1429
- case 'MODEL':
1430
- defaultModelRequirements[command.key] = command.value;
1431
- break;
1432
- case 'PARAMETER':
1433
- addParam(command);
1434
- break;
1435
- default:
1436
- throw new PromptbookSyntaxError("Command ".concat(command.type, " is not allowed in the head of the promptbook ONLY at the prompt template block"));
1497
+ // Note: Filter ONLY output parameters
1498
+ for (_a = __values(promptbook.parameters), _b = _a.next(); !_b.done; _b = _a.next()) {
1499
+ parameter = _b.value;
1500
+ if (parameter.isOutput) {
1501
+ continue;
1437
1502
  }
1503
+ delete parametersToPass[parameter.name];
1438
1504
  }
1439
1505
  }
1440
1506
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
1441
1507
  finally {
1442
1508
  try {
1443
- if (listItems_1_1 && !listItems_1_1.done && (_c = listItems_1.return)) _c.call(listItems_1);
1509
+ if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
1444
1510
  }
1445
1511
  finally { if (e_1) throw e_1.error; }
1446
1512
  }
1447
- _loop_1 = function (section) {
1448
- var e_3, _f;
1449
- // TODO: Parse prompt template description (the content out of the codeblock and lists)
1450
- var templateModelRequirements = __assign({}, defaultModelRequirements);
1451
- var listItems_3 = extractAllListItemsFromMarkdown(section.content);
1452
- var dependentParameterNames = new Set();
1453
- var executionType = 'PROMPT_TEMPLATE';
1454
- var jokers = [];
1455
- var postprocessing = [];
1456
- var expectAmount = {};
1457
- var expectFormat = undefined;
1458
- var isExecutionTypeChanged = false;
1459
- try {
1460
- 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()) {
1461
- var listItem = listItems_2_1.value;
1462
- var command = parseCommand(listItem);
1463
- switch (command.type) {
1464
- case 'JOKER':
1465
- jokers.push(command.parameterName);
1466
- dependentParameterNames.add(command.parameterName);
1467
- break;
1468
- case 'EXECUTE':
1469
- if (isExecutionTypeChanged) {
1470
- throw new PromptbookSyntaxError('Execution type is already defined in the prompt template. It can be defined only once.');
1471
- }
1472
- executionType = command.executionType;
1473
- isExecutionTypeChanged = true;
1474
- break;
1475
- case 'MODEL':
1476
- templateModelRequirements[command.key] = command.value;
1477
- break;
1478
- case 'PARAMETER':
1479
- // Note: This is just for detecting resulitng parameter name
1480
- addParam(command);
1481
- break;
1482
- case 'POSTPROCESS':
1483
- postprocessing.push(command.functionName);
1484
- break;
1485
- case 'EXPECT_AMOUNT':
1486
- // eslint-disable-next-line no-case-declarations
1487
- var unit = command.unit.toLowerCase();
1488
- expectAmount[unit] = expectAmount[unit] || {};
1489
- if (command.sign === 'MINIMUM' || command.sign === 'EXACTLY') {
1490
- if (expectAmount[unit].min !== undefined) {
1491
- throw new PromptbookSyntaxError("Already defined minumum ".concat(expectAmount[unit].min, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
1492
- }
1493
- expectAmount[unit].min = command.amount;
1494
- } /* not else */
1495
- if (command.sign === 'MAXIMUM' || command.sign === 'EXACTLY') {
1496
- if (expectAmount[unit].max !== undefined) {
1497
- throw new PromptbookSyntaxError("Already defined maximum ".concat(expectAmount[unit].max, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
1498
- }
1499
- expectAmount[unit].max = command.amount;
1500
- }
1501
- break;
1502
- case 'EXPECT_FORMAT':
1503
- if (expectFormat !== undefined && command.format !== expectFormat) {
1504
- throw new PromptbookSyntaxError("Expect format is already defined to \"".concat(expectFormat, "\". Now you try to redefine it by \"").concat(command.format, "\"."));
1505
- }
1506
- expectFormat = command.format;
1507
- break;
1508
- default:
1509
- throw new PromptbookSyntaxError("Command ".concat(command.type, " is not allowed in the block of the prompt template ONLY at the head of the promptbook"));
1510
- }
1511
- }
1512
- }
1513
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
1514
- finally {
1515
- try {
1516
- if (listItems_2_1 && !listItems_2_1.done && (_f = listItems_2.return)) _f.call(listItems_2);
1517
- }
1518
- finally { if (e_3) throw e_3.error; }
1519
- }
1520
- var _g = extractOneBlockFromMarkdown(section.content), language = _g.language, content = _g.content;
1521
- if (executionType === 'SCRIPT') {
1522
- if (!language) {
1523
- throw new PromptbookSyntaxError('You must specify the language of the script in the prompt template');
1524
- }
1525
- else if (!SUPPORTED_SCRIPT_LANGUAGES.includes(language)) {
1526
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim(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 "); }));
1527
- }
1528
- }
1529
- var lastLine = section.content.split('\n').pop();
1530
- var match = /^->\s*\{(?<resultingParamName>[a-z0-9_]+)\}/im.exec(lastLine);
1531
- if (!match || match.groups === undefined || match.groups.resultingParamName === undefined) {
1532
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Invalid template - each section must end with \"-> {...}\"\n\n Invalid section:\n ".concat(block(
1533
- // TODO: Show code of invalid sections each time + DRY
1534
- section.content
1535
- .split('\n')
1536
- .map(function (line) { return "> ".concat(line); })
1537
- .join('\n')), "\n "); }));
1538
- }
1539
- var resultingParameterName = match.groups.resultingParamName;
1540
- // TODO: [1] DRY description
1541
- var description_1 = section.content;
1542
- // Note: Remove codeblocks
1543
- description_1 = description_1.split(/^```.*^```/gms).join('');
1544
- //Note: Remove lists and return statement
1545
- description_1 = description_1.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
1546
- description_1 = spaceTrim.spaceTrim(description_1);
1547
- if (description_1 === '') {
1548
- description_1 = undefined;
1549
- }
1550
- if (Object.keys(jokers).length === 0) {
1551
- jokers = undefined;
1552
- }
1553
- if (Object.keys(expectAmount).length === 0) {
1554
- expectAmount = undefined;
1555
- }
1556
- if (Object.keys(postprocessing).length === 0) {
1557
- postprocessing = undefined;
1558
- }
1559
- dependentParameterNames = union(dependentParameterNames, extractParametersFromPromptTemplate(__assign(__assign({}, section), { description: description_1, executionType: executionType, content: content })));
1560
- if (templateModelRequirements.modelVariant === undefined) {
1561
- templateModelRequirements.modelVariant = 'CHAT';
1562
- }
1563
- promptbookJson.promptTemplates.push({
1564
- name: titleToName(section.title),
1565
- title: section.title,
1566
- description: description_1,
1567
- dependentParameterNames: Array.from(dependentParameterNames),
1568
- executionType: executionType,
1569
- jokers: jokers,
1570
- postprocessing: postprocessing,
1571
- expectations: expectAmount,
1572
- expectFormat: expectFormat,
1573
- modelRequirements: templateModelRequirements,
1574
- contentLanguage: executionType === 'SCRIPT' ? language : undefined,
1575
- content: content,
1576
- resultingParameterName: resultingParameterName,
1577
- });
1578
- };
1579
- try {
1580
- for (_a = __values(markdownStructure.sections), _b = _a.next(); !_b.done; _b = _a.next()) {
1581
- section = _b.value;
1582
- _loop_1(section);
1583
- }
1584
- }
1585
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
1586
- finally {
1587
- try {
1588
- if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
1589
- }
1590
- finally { if (e_2) throw e_2.error; }
1591
- }
1592
- // =============================================================
1593
- return [2 /*return*/, promptbookJson];
1513
+ usage = addUsage.apply(void 0, __spreadArray([], __read(executionReport.promptExecutions.map(function (_a) {
1514
+ var result = _a.result;
1515
+ return (result === null || result === void 0 ? void 0 : result.usage) || addUsage();
1516
+ })), false));
1517
+ return [2 /*return*/, {
1518
+ isSuccessful: true,
1519
+ errors: [],
1520
+ usage: usage,
1521
+ executionReport: executionReport,
1522
+ outputParameters: parametersToPass,
1523
+ }];
1594
1524
  }
1595
1525
  });
1596
- });
1526
+ }); };
1527
+ return promptbookExecutor;
1597
1528
  }
1598
1529
  /**
1599
- * TODO: Report here line/column of error
1600
- * TODO: Use spaceTrim more effectively
1601
- * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
1602
- */
1603
-
1604
- /**
1605
- * This error indicates that the promptbook object has valid syntax but contains logical errors (like circular dependencies)
1530
+ * TODO: [🧠] When not meet expectations in PROMPT_DIALOG, make some way to tell the user
1531
+ * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
1532
+ * Note: CreatePromptbookExecutorOptions are just connected to PromptbookExecutor so do not extract to types folder
1533
+ * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
1606
1534
  */
1607
- var PromptbookLogicError = /** @class */ (function (_super) {
1608
- __extends(PromptbookLogicError, _super);
1609
- function PromptbookLogicError(message) {
1610
- var _this = _super.call(this, message) || this;
1611
- _this.name = 'PromptbookLogicError';
1612
- Object.setPrototypeOf(_this, PromptbookLogicError.prototype);
1613
- return _this;
1614
- }
1615
- return PromptbookLogicError;
1616
- }(Error));
1617
1535
 
1618
1536
  /**
1619
- * Tests if given string is valid URL.
1537
+ * Prettify the html code
1620
1538
  *
1621
- * Note: Dataurl are considered perfectly valid.
1539
+ * @param content raw html code
1540
+ * @returns formatted html code
1622
1541
  */
1623
- function isValidUrl(url) {
1624
- if (typeof url !== 'string') {
1625
- return false;
1626
- }
1542
+ function prettifyMarkdown(content) {
1627
1543
  try {
1628
- if (url.startsWith('blob:')) {
1629
- url = url.replace(/^blob:/, '');
1630
- }
1631
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1632
- var urlObject = new URL(url);
1633
- if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
1634
- return false;
1635
- }
1636
- return true;
1544
+ return prettier.format(content, {
1545
+ parser: 'markdown',
1546
+ plugins: [parserHtml__default["default"]],
1547
+ // TODO: DRY - make some import or auto-copy of .prettierrc
1548
+ endOfLine: 'lf',
1549
+ tabWidth: 4,
1550
+ singleQuote: true,
1551
+ trailingComma: 'all',
1552
+ arrowParens: 'always',
1553
+ printWidth: 120,
1554
+ htmlWhitespaceSensitivity: 'ignore',
1555
+ jsxBracketSameLine: false,
1556
+ bracketSpacing: true,
1557
+ });
1637
1558
  }
1638
1559
  catch (error) {
1639
- return false;
1560
+ console.error('There was an error with prettifying the markdown, using the original as the fallback', {
1561
+ error: error,
1562
+ html: content,
1563
+ });
1564
+ return content;
1640
1565
  }
1641
1566
  }
1642
1567
 
1643
1568
  /**
1644
- * Validates PromptbookJson if it is logically valid
1645
- *
1646
- * It checks:
1647
- * - if it has correct parameters dependency
1569
+ * Makes first letter of a string uppercase
1648
1570
  *
1649
- * It does NOT check:
1650
- * - if it is valid json
1651
- * - if it is meaningful
1571
+ */
1572
+ function capitalize(word) {
1573
+ return word.substring(0, 1).toUpperCase() + word.substring(1);
1574
+ }
1575
+
1576
+ /**
1577
+ * Converts promptbook in JSON format to string format
1652
1578
  *
1653
- * @param promptbook valid or invalid PromptbookJson
1654
- * @returns the same promptbook if it is logically valid
1655
- * @throws {PromptbookLogicError} on logical error in the promptbook
1579
+ * @param promptbookJson Promptbook in JSON format (.ptbk.json)
1580
+ * @returns Promptbook in string format (.ptbk.md)
1656
1581
  */
1657
- function validatePromptbookJson(promptbook) {
1658
- // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
1659
- var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
1660
- if (promptbook.promptbookUrl !== undefined) {
1661
- if (!isValidUrl(promptbook.promptbookUrl)) {
1662
- // TODO: This should be maybe the syntax error detected during parsing
1663
- throw new PromptbookLogicError("Invalid promptbook URL \"".concat(promptbook.promptbookUrl, "\""));
1664
- }
1665
- }
1666
- // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1667
- if (!Array.isArray(promptbook.parameters)) {
1668
- // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1669
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Promptbook is valid JSON but with wrong structure\n\n promptbook.parameters expected to be an array, but got ".concat(typeof promptbook.parameters, "\n ")));
1582
+ function promptbookJsonToString(promptbookJson) {
1583
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d, e_5, _e, e_6, _f;
1584
+ var title = promptbookJson.title, promptbookUrl = promptbookJson.promptbookUrl, promptbookVersion = promptbookJson.promptbookVersion, description = promptbookJson.description, parameters = promptbookJson.parameters, promptTemplates = promptbookJson.promptTemplates;
1585
+ var promptbookString = "# ".concat(title);
1586
+ if (description) {
1587
+ promptbookString += '\n\n';
1588
+ promptbookString += description;
1670
1589
  }
1671
- // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1672
- if (!Array.isArray(promptbook.promptTemplates)) {
1673
- // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1674
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Promptbook is valid JSON but with wrong structure\n\n promptbook.promptTemplates expected to be an array, but got ".concat(typeof promptbook.promptTemplates, "\n ")));
1590
+ // TODO:> const commands: Array<Command>
1591
+ var commands = [];
1592
+ if (promptbookUrl) {
1593
+ commands.push("PROMPTBOOK URL ".concat(promptbookUrl));
1675
1594
  }
1676
- var _loop_1 = function (parameter) {
1677
- if (parameter.isInput && parameter.isOutput) {
1678
- throw new PromptbookLogicError("Parameter {".concat(parameter.name, "} can not be both input and output"));
1679
- }
1680
- // Note: Testing that parameter is either intermediate or output BUT not created and unused
1681
- if (!parameter.isInput &&
1682
- !parameter.isOutput &&
1683
- !promptbook.promptTemplates.some(function (template) { return template.dependentParameterNames.includes(parameter.name); })) {
1684
- throw new PromptbookLogicError(spaceTrim.spaceTrim("\n Parameter {".concat(parameter.name, "} is created but not used\n\n You can declare {").concat(parameter.name, "} as output parameter by adding in the header:\n - OUTPUT PARAMETER `{").concat(parameter.name, "}` ").concat(parameter.description || '', "\n\n ")));
1685
- }
1686
- // Note: Testing that parameter is either input or result of some template
1687
- if (!parameter.isInput &&
1688
- !promptbook.promptTemplates.some(function (template) { return template.resultingParameterName === parameter.name; })) {
1689
- throw new PromptbookLogicError(spaceTrim.spaceTrim("\n Parameter {".concat(parameter.name, "} is declared but not defined\n\n You can do one of these:\n - Remove declaration of {").concat(parameter.name, "}\n - Add prompt template that results in -> {").concat(parameter.name, "}\n\n ")));
1690
- }
1691
- };
1595
+ commands.push("PROMPTBOOK VERSION ".concat(promptbookVersion));
1596
+ promptbookString = prettifyMarkdown(promptbookString);
1692
1597
  try {
1693
- // Note: Check each parameter individually
1694
- for (var _e = __values(promptbook.parameters), _f = _e.next(); !_f.done; _f = _e.next()) {
1695
- var parameter = _f.value;
1696
- _loop_1(parameter);
1598
+ for (var _g = __values(parameters.filter(function (_a) {
1599
+ var isInput = _a.isInput;
1600
+ return isInput;
1601
+ })), _h = _g.next(); !_h.done; _h = _g.next()) {
1602
+ var parameter = _h.value;
1603
+ commands.push("INPUT PARAMETER ".concat(promptTemplateParameterJsonToString(parameter)));
1697
1604
  }
1698
1605
  }
1699
1606
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
1700
1607
  finally {
1701
1608
  try {
1702
- if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
1703
- }
1704
- finally { if (e_1) throw e_1.error; }
1705
- }
1706
- // Note: Check each template individually
1707
- var definedParameters = new Set(promptbook.parameters.filter(function (_a) {
1708
- var isInput = _a.isInput;
1709
- return isInput;
1710
- }).map(function (_a) {
1711
- var name = _a.name;
1712
- return name;
1713
- }));
1714
- try {
1715
- for (var _g = __values(promptbook.promptTemplates), _h = _g.next(); !_h.done; _h = _g.next()) {
1716
- var template = _h.value;
1717
- if (definedParameters.has(template.resultingParameterName)) {
1718
- throw new PromptbookLogicError("Parameter {".concat(template.resultingParameterName, "} is defined multiple times"));
1719
- }
1720
- definedParameters.add(template.resultingParameterName);
1721
- if (template.executionType === 'PROMPT_TEMPLATE' &&
1722
- (template.modelRequirements.modelVariant === undefined)) {
1723
- throw new PromptbookLogicError(spaceTrim.spaceTrim("\n\n You must specify MODEL VARIANT in the prompt template \"".concat(template.title, "\"\n\n For example:\n - MODEL VARIANT Chat\n - MODEL NAME `gpt-4-1106-preview`\n\n ")));
1724
- }
1725
- if (template.jokers && template.jokers.length > 0) {
1726
- if (!template.expectFormat &&
1727
- !template.expectations /* <- TODO: Require at least 1 -> min <- expectation to use jokers */) {
1728
- throw new PromptbookLogicError("Joker parameters are used for {".concat(template.resultingParameterName, "} but no expectations are defined"));
1729
- }
1730
- try {
1731
- for (var _j = (e_3 = void 0, __values(template.jokers)), _k = _j.next(); !_k.done; _k = _j.next()) {
1732
- var joker = _k.value;
1733
- if (!template.dependentParameterNames.includes(joker)) {
1734
- throw new PromptbookLogicError("Parameter {".concat(joker, "} is used for {").concat(template.resultingParameterName, "} as joker but not in dependentParameterNames"));
1735
- }
1736
- }
1737
- }
1738
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
1739
- finally {
1740
- try {
1741
- if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
1742
- }
1743
- finally { if (e_3) throw e_3.error; }
1744
- }
1745
- }
1746
- if (template.expectations) {
1747
- try {
1748
- for (var _l = (e_4 = void 0, __values(Object.entries(template.expectations))), _m = _l.next(); !_m.done; _m = _l.next()) {
1749
- var _o = __read(_m.value, 2), unit = _o[0], _p = _o[1], min = _p.min, max = _p.max;
1750
- if (min !== undefined && max !== undefined && min > max) {
1751
- throw new PromptbookLogicError("Min expectation (=".concat(min, ") of ").concat(unit, " is higher than max expectation (=").concat(max, ")"));
1752
- }
1753
- if (min !== undefined && min < 0) {
1754
- throw new PromptbookLogicError("Min expectation of ".concat(unit, " must be zero or positive"));
1755
- }
1756
- if (max !== undefined && max <= 0) {
1757
- throw new PromptbookLogicError("Max expectation of ".concat(unit, " must be positive"));
1758
- }
1759
- }
1760
- }
1761
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
1762
- finally {
1763
- try {
1764
- if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
1765
- }
1766
- finally { if (e_4) throw e_4.error; }
1767
- }
1768
- }
1769
- }
1770
- }
1771
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
1772
- finally {
1773
- try {
1774
- if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
1775
- }
1776
- finally { if (e_2) throw e_2.error; }
1777
- }
1778
- // Note: Detect circular dependencies
1779
- var resovedParameters = promptbook.parameters
1780
- .filter(function (_a) {
1781
- var isInput = _a.isInput;
1782
- return isInput;
1783
- })
1784
- .map(function (_a) {
1785
- var name = _a.name;
1786
- return name;
1787
- });
1788
- var unresovedTemplates = __spreadArray([], __read(promptbook.promptTemplates), false);
1789
- var loopLimit = LOOP_LIMIT;
1790
- var _loop_2 = function () {
1791
- if (loopLimit-- < 0) {
1792
- throw new UnexpectedError('Loop limit reached during detection of circular dependencies in `validatePromptbookJson`');
1793
- }
1794
- var currentlyResovedTemplates = unresovedTemplates.filter(function (template) {
1795
- return template.dependentParameterNames.every(function (name) { return resovedParameters.includes(name); });
1796
- });
1797
- if (currentlyResovedTemplates.length === 0) {
1798
- throw new PromptbookLogicError(spaceTrim.spaceTrim(function (block) { return "\n\n Can not resolve some parameters\n It may be circular dependencies\n\n Can not resolve:\n ".concat(block(unresovedTemplates
1799
- .map(function (_a) {
1800
- var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
1801
- return "- {".concat(resultingParameterName, "} depends on ").concat(dependentParameterNames
1802
- .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
1803
- .join(', '));
1804
- })
1805
- .join('\n')), "\n\n Resolved:\n ").concat(block(resovedParameters.map(function (name) { return "- {".concat(name, "}"); }).join('\n')), "\n "); }));
1806
- }
1807
- resovedParameters = __spreadArray(__spreadArray([], __read(resovedParameters), false), __read(currentlyResovedTemplates.map(function (_a) {
1808
- var resultingParameterName = _a.resultingParameterName;
1809
- return resultingParameterName;
1810
- })), false);
1811
- unresovedTemplates = unresovedTemplates.filter(function (template) { return !currentlyResovedTemplates.includes(template); });
1812
- };
1813
- while (unresovedTemplates.length > 0) {
1814
- _loop_2();
1815
- }
1816
- return promptbook;
1817
- }
1818
- /**
1819
- * TODO: [🧠] Work with promptbookVersion
1820
- * TODO: Use here some json-schema, Zod or something similar and change it to:
1821
- * > /**
1822
- * > * Validates PromptbookJson if it is logically valid.
1823
- * > *
1824
- * > * It checks:
1825
- * > * - it has a valid structure
1826
- * > * - ...
1827
- * > ex port function validatePromptbookJson(promptbook: unknown): asserts promptbook is PromptbookJson {
1828
- */
1829
-
1830
- /**
1831
- * This error indicates that the promptbook library cannot be propperly loaded
1832
- */
1833
- var PromptbookLibraryError = /** @class */ (function (_super) {
1834
- __extends(PromptbookLibraryError, _super);
1835
- function PromptbookLibraryError(message) {
1836
- var _this = _super.call(this, message) || this;
1837
- _this.name = 'PromptbookLibraryError';
1838
- Object.setPrototypeOf(_this, PromptbookLibraryError.prototype);
1839
- return _this;
1840
- }
1841
- return PromptbookLibraryError;
1842
- }(Error));
1843
-
1844
- /**
1845
- * Detects if the code is running in a browser environment in main thread (Not in a web worker)
1846
- */
1847
- new Function("\n try {\n return this === window;\n } catch (e) {\n return false;\n }\n");
1848
- /**
1849
- * Detects if the code is running in a Node.js environment
1850
- */
1851
- var isRunningInNode = new Function("\n try {\n return this === global;\n } catch (e) {\n return false;\n }\n");
1852
- /**
1853
- * Detects if the code is running in a web worker
1854
- */
1855
- new Function("\n try {\n if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {\n return true;\n } else {\n return false;\n }\n } catch (e) {\n return false;\n }\n");
1856
-
1857
- /**
1858
- * Prettify the html code
1859
- *
1860
- * @param content raw html code
1861
- * @returns formatted html code
1862
- */
1863
- function prettifyMarkdown(content) {
1864
- try {
1865
- return prettier.format(content, {
1866
- parser: 'markdown',
1867
- plugins: [parserHtml__default["default"]],
1868
- // TODO: DRY - make some import or auto-copy of .prettierrc
1869
- endOfLine: 'lf',
1870
- tabWidth: 4,
1871
- singleQuote: true,
1872
- trailingComma: 'all',
1873
- arrowParens: 'always',
1874
- printWidth: 120,
1875
- htmlWhitespaceSensitivity: 'ignore',
1876
- jsxBracketSameLine: false,
1877
- bracketSpacing: true,
1878
- });
1879
- }
1880
- catch (error) {
1881
- console.error('There was an error with prettifying the markdown, using the original as the fallback', {
1882
- error: error,
1883
- html: content,
1884
- });
1885
- return content;
1886
- }
1887
- }
1888
-
1889
- /**
1890
- * Converts promptbook in JSON format to string format
1891
- *
1892
- * @param promptbookJson Promptbook in JSON format (.ptbk.json)
1893
- * @returns Promptbook in string format (.ptbk.md)
1894
- */
1895
- function promptbookJsonToString(promptbookJson) {
1896
- var e_1, _a, e_2, _b, e_3, _c, e_4, _d, e_5, _e, e_6, _f;
1897
- var title = promptbookJson.title, promptbookUrl = promptbookJson.promptbookUrl, promptbookVersion = promptbookJson.promptbookVersion, description = promptbookJson.description, parameters = promptbookJson.parameters, promptTemplates = promptbookJson.promptTemplates;
1898
- var promptbookString = "# ".concat(title);
1899
- if (description) {
1900
- promptbookString += '\n\n';
1901
- promptbookString += description;
1902
- }
1903
- // TODO:> const commands: Array<Command>
1904
- var commands = [];
1905
- if (promptbookUrl) {
1906
- commands.push("PROMPTBOOK URL ".concat(promptbookUrl));
1907
- }
1908
- commands.push("PROMPTBOOK VERSION ".concat(promptbookVersion));
1909
- promptbookString = prettifyMarkdown(promptbookString);
1910
- try {
1911
- for (var _g = __values(parameters.filter(function (_a) {
1912
- var isInput = _a.isInput;
1913
- return isInput;
1914
- })), _h = _g.next(); !_h.done; _h = _g.next()) {
1915
- var parameter = _h.value;
1916
- commands.push("INPUT PARAMETER ".concat(promptTemplateParameterJsonToString(parameter)));
1917
- }
1918
- }
1919
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1920
- finally {
1921
- try {
1922
- if (_h && !_h.done && (_a = _g.return)) _a.call(_g);
1609
+ if (_h && !_h.done && (_a = _g.return)) _a.call(_g);
1923
1610
  }
1924
1611
  finally { if (e_1) throw e_1.error; }
1925
1612
  }
@@ -2023,240 +1710,1496 @@
2023
1710
  if (min === max) {
2024
1711
  commands_1.push("EXPECT EXACTLY ".concat(min, " ").concat(capitalize(unit + (min > 1 ? 's' : ''))));
2025
1712
  }
2026
- else {
2027
- if (min !== undefined) {
2028
- commands_1.push("EXPECT MIN ".concat(min, " ").concat(capitalize(unit + (min > 1 ? 's' : ''))));
2029
- } /* not else */
2030
- if (max !== undefined) {
2031
- commands_1.push("EXPECT MAX ".concat(max, " ").concat(capitalize(unit + (max > 1 ? 's' : ''))));
2032
- }
1713
+ else {
1714
+ if (min !== undefined) {
1715
+ commands_1.push("EXPECT MIN ".concat(min, " ").concat(capitalize(unit + (min > 1 ? 's' : ''))));
1716
+ } /* not else */
1717
+ if (max !== undefined) {
1718
+ commands_1.push("EXPECT MAX ".concat(max, " ").concat(capitalize(unit + (max > 1 ? 's' : ''))));
1719
+ }
1720
+ }
1721
+ }
1722
+ }
1723
+ catch (e_6_1) { e_6 = { error: e_6_1 }; }
1724
+ finally {
1725
+ try {
1726
+ if (_m && !_m.done && (_f = _l.return)) _f.call(_l);
1727
+ }
1728
+ finally { if (e_6) throw e_6.error; }
1729
+ }
1730
+ } /* not else */
1731
+ if (expectFormat) {
1732
+ if (expectFormat === 'JSON') {
1733
+ // TODO: @deprecated remove
1734
+ commands_1.push("EXPECT JSON");
1735
+ }
1736
+ } /* not else */
1737
+ promptbookString += '\n\n';
1738
+ promptbookString += commands_1.map(function (command) { return "- ".concat(command); }).join('\n');
1739
+ promptbookString += '\n\n';
1740
+ promptbookString += '```' + contentLanguage;
1741
+ promptbookString += '\n';
1742
+ promptbookString += spaceTrim__default["default"](content);
1743
+ // <- TODO: !!! Escape
1744
+ // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
1745
+ promptbookString += '\n';
1746
+ promptbookString += '```';
1747
+ promptbookString += '\n\n';
1748
+ promptbookString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO: !!! If the parameter here has description, add it and use promptTemplateParameterJsonToString
1749
+ }
1750
+ }
1751
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
1752
+ finally {
1753
+ try {
1754
+ if (promptTemplates_1_1 && !promptTemplates_1_1.done && (_c = promptTemplates_1.return)) _c.call(promptTemplates_1);
1755
+ }
1756
+ finally { if (e_3) throw e_3.error; }
1757
+ }
1758
+ return promptbookString;
1759
+ }
1760
+ /**
1761
+ * @private internal util of promptbookJsonToString
1762
+ */
1763
+ function promptTemplateParameterJsonToString(promptTemplateParameterJson) {
1764
+ var name = promptTemplateParameterJson.name, description = promptTemplateParameterJson.description;
1765
+ var parameterString = "{".concat(name, "}");
1766
+ if (description) {
1767
+ parameterString = "".concat(parameterString, " ").concat(description);
1768
+ }
1769
+ return parameterString;
1770
+ }
1771
+ /**
1772
+ * TODO: Escape all
1773
+ */
1774
+
1775
+ /**
1776
+ * This error indicates that promptbook not found in the library
1777
+ */
1778
+ var PromptbookNotFoundError = /** @class */ (function (_super) {
1779
+ __extends(PromptbookNotFoundError, _super);
1780
+ function PromptbookNotFoundError(message) {
1781
+ var _this = _super.call(this, message) || this;
1782
+ _this.name = 'PromptbookNotFoundError';
1783
+ Object.setPrototypeOf(_this, PromptbookNotFoundError.prototype);
1784
+ return _this;
1785
+ }
1786
+ return PromptbookNotFoundError;
1787
+ }(Error));
1788
+
1789
+ /**
1790
+ * This error indicates errors in referencing promptbooks between each other
1791
+ */
1792
+ var PromptbookReferenceError = /** @class */ (function (_super) {
1793
+ __extends(PromptbookReferenceError, _super);
1794
+ function PromptbookReferenceError(message) {
1795
+ var _this = _super.call(this, message) || this;
1796
+ _this.name = 'PromptbookReferenceError';
1797
+ Object.setPrototypeOf(_this, PromptbookReferenceError.prototype);
1798
+ return _this;
1799
+ }
1800
+ return PromptbookReferenceError;
1801
+ }(Error));
1802
+
1803
+ /**
1804
+ * Library of promptbooks that groups together promptbooks for an application.
1805
+ * This implementation is a very thin wrapper around the Array / Map of promptbooks.
1806
+ *
1807
+ * @private use `createLibraryFromJson` instead
1808
+ * @see https://github.com/webgptorg/promptbook#promptbook-library
1809
+ */
1810
+ var SimplePromptbookLibrary = /** @class */ (function () {
1811
+ /**
1812
+ * Constructs a promptbook library from promptbooks
1813
+ *
1814
+ * @param promptbooks !!!
1815
+ *
1816
+ * @private Use instead `createLibraryFromJson`
1817
+ * Note: During the construction logic of all promptbooks are validated
1818
+ * Note: It is not recommended to use this constructor directly, use `createLibraryFromJson` *(or other variant)* instead
1819
+ */
1820
+ function SimplePromptbookLibrary() {
1821
+ var e_1, _a;
1822
+ var promptbooks = [];
1823
+ for (var _i = 0; _i < arguments.length; _i++) {
1824
+ promptbooks[_i] = arguments[_i];
1825
+ }
1826
+ this.library = new Map();
1827
+ try {
1828
+ for (var promptbooks_1 = __values(promptbooks), promptbooks_1_1 = promptbooks_1.next(); !promptbooks_1_1.done; promptbooks_1_1 = promptbooks_1.next()) {
1829
+ var promptbook = promptbooks_1_1.value;
1830
+ if (promptbook.promptbookUrl === undefined) {
1831
+ throw new PromptbookReferenceError(spaceTrim.spaceTrim("\n Promptbook with name \"".concat(promptbook.title, "\" does not have defined URL\n\n Note: Promptbooks without URLs are called anonymous promptbooks\n They can be used as standalone promptbooks, but they cannot be referenced by other promptbooks\n And also they cannot be used in the promptbook library\n\n ")));
1832
+ }
1833
+ validatePromptbook(promptbook);
1834
+ // Note: [🦄]
1835
+ if (this.library.has(promptbook.promptbookUrl) &&
1836
+ promptbookJsonToString(promptbook) !==
1837
+ promptbookJsonToString(this.library.get(promptbook.promptbookUrl))) {
1838
+ throw new PromptbookReferenceError(spaceTrim.spaceTrim("\n Promptbook with URL \"".concat(promptbook.promptbookUrl, "\" is already in the library\n\n Note: Promptbooks with the same URL are not allowed\n Note: Automatically check whether the promptbooks are the same BUT they are DIFFERENT\n\n ")));
1839
+ }
1840
+ this.library.set(promptbook.promptbookUrl, promptbook);
1841
+ }
1842
+ }
1843
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1844
+ finally {
1845
+ try {
1846
+ if (promptbooks_1_1 && !promptbooks_1_1.done && (_a = promptbooks_1.return)) _a.call(promptbooks_1);
1847
+ }
1848
+ finally { if (e_1) throw e_1.error; }
1849
+ }
1850
+ }
1851
+ /**
1852
+ * Gets all promptbooks in the library
1853
+ */
1854
+ SimplePromptbookLibrary.prototype.listPromptbooks = function () {
1855
+ return Array.from(this.library.keys());
1856
+ };
1857
+ /**
1858
+ * Gets promptbook by its URL
1859
+ *
1860
+ * Note: This is not a direct fetching from the URL, but a lookup in the library
1861
+ */
1862
+ SimplePromptbookLibrary.prototype.getPromptbookByUrl = function (url) {
1863
+ var _this = this;
1864
+ var promptbook = this.library.get(url);
1865
+ if (!promptbook) {
1866
+ if (this.listPromptbooks().length === 0) {
1867
+ throw new PromptbookNotFoundError(spaceTrim.spaceTrim("\n Promptbook with url \"".concat(url, "\" not found\n\n No promptbooks available\n ")));
1868
+ }
1869
+ throw new PromptbookNotFoundError(spaceTrim.spaceTrim(function (block) { return "\n Promptbook with url \"".concat(url, "\" not found\n\n Available promptbooks:\n ").concat(block(_this.listPromptbooks()
1870
+ .map(function (promptbookUrl) { return "- ".concat(promptbookUrl); })
1871
+ .join('\n')), "\n\n "); }));
1872
+ }
1873
+ return promptbook;
1874
+ };
1875
+ /**
1876
+ * Checks whether given prompt was defined in any promptbook in the library
1877
+ */
1878
+ SimplePromptbookLibrary.prototype.isResponsibleForPrompt = function (prompt) {
1879
+ return true;
1880
+ };
1881
+ return SimplePromptbookLibrary;
1882
+ }());
1883
+
1884
+ /**
1885
+ * Creates PromptbookLibrary from array of PromptbookJson or PromptbookString
1886
+ *
1887
+ * Note: Functions `libraryToJson` and `createLibraryFromJson` are complementary
1888
+ * Note: During the construction syntax and logic of all sources are validated
1889
+ *
1890
+ * @param promptbookSources
1891
+ * @returns PromptbookLibrary
1892
+ */
1893
+ function createLibraryFromJson() {
1894
+ var promptbooks = [];
1895
+ for (var _i = 0; _i < arguments.length; _i++) {
1896
+ promptbooks[_i] = arguments[_i];
1897
+ }
1898
+ return new (SimplePromptbookLibrary.bind.apply(SimplePromptbookLibrary, __spreadArray([void 0], __read(promptbooks), false)))();
1899
+ }
1900
+
1901
+ /* tslint:disable */
1902
+ function normalizeToKebabCase(sentence) {
1903
+ var e_1, _a;
1904
+ sentence = removeDiacritics(sentence);
1905
+ var charType;
1906
+ var lastCharType = 'OTHER';
1907
+ var normalizedName = '';
1908
+ try {
1909
+ for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
1910
+ var char = sentence_1_1.value;
1911
+ var normalizedChar = void 0;
1912
+ if (/^[a-z]$/.test(char)) {
1913
+ charType = 'LOWERCASE';
1914
+ normalizedChar = char;
1915
+ }
1916
+ else if (/^[A-Z]$/.test(char)) {
1917
+ charType = 'UPPERCASE';
1918
+ normalizedChar = char.toLowerCase();
1919
+ }
1920
+ else if (/^[0-9]$/.test(char)) {
1921
+ charType = 'NUMBER';
1922
+ normalizedChar = char;
1923
+ }
1924
+ else if (/^\/$/.test(char)) {
1925
+ charType = 'SLASH';
1926
+ normalizedChar = char;
1927
+ }
1928
+ else {
1929
+ charType = 'OTHER';
1930
+ normalizedChar = '-';
1931
+ }
1932
+ if (charType !== lastCharType &&
1933
+ !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
1934
+ !(lastCharType === 'NUMBER') &&
1935
+ !(charType === 'NUMBER')) {
1936
+ normalizedName += '-';
1937
+ }
1938
+ normalizedName += normalizedChar;
1939
+ lastCharType = charType;
1940
+ }
1941
+ }
1942
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1943
+ finally {
1944
+ try {
1945
+ if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
1946
+ }
1947
+ finally { if (e_1) throw e_1.error; }
1948
+ }
1949
+ normalizedName = normalizedName.split(/-+/g).join('-');
1950
+ normalizedName = normalizedName.split(/-?\/-?/g).join('/');
1951
+ normalizedName = normalizedName.replace(/^-/, '');
1952
+ normalizedName = normalizedName.replace(/-$/, '');
1953
+ return normalizedName;
1954
+ }
1955
+
1956
+ function prepareKnowledgeFromMarkdown(options) {
1957
+ return __awaiter(this, void 0, void 0, function () {
1958
+ var content, llmTools, _a, isVerbose, library, prepareKnowledgeFromMarkdownPromptbook, prepareKnowledgeFromMarkdownExecutor, prepareKeywordsPromptbook, prepareKeywordsExecutor, result, outputParameters, knowledgeRaw, knowledgeTextPieces, knowledge;
1959
+ var _this = this;
1960
+ return __generator(this, function (_b) {
1961
+ switch (_b.label) {
1962
+ case 0:
1963
+ content = options.content, llmTools = options.llmTools, _a = options.isVerbose, isVerbose = _a === void 0 ? false : _a;
1964
+ library = createLibraryFromJson.apply(void 0, __spreadArray([], __read(promptbookLibrary), false));
1965
+ return [4 /*yield*/, library.getPromptbookByUrl('https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md')];
1966
+ case 1:
1967
+ prepareKnowledgeFromMarkdownPromptbook = _b.sent();
1968
+ prepareKnowledgeFromMarkdownExecutor = createPromptbookExecutor({
1969
+ promptbook: prepareKnowledgeFromMarkdownPromptbook,
1970
+ tools: {
1971
+ llm: llmTools,
1972
+ script: [
1973
+ /* <- TODO: Allow to just keep script undefined */
1974
+ ],
1975
+ },
1976
+ });
1977
+ return [4 /*yield*/, library.getPromptbookByUrl('https://promptbook.studio/promptbook/prepare-keywords.ptbk.md')];
1978
+ case 2:
1979
+ prepareKeywordsPromptbook = _b.sent();
1980
+ prepareKeywordsExecutor = createPromptbookExecutor({
1981
+ promptbook: prepareKeywordsPromptbook,
1982
+ tools: {
1983
+ llm: llmTools,
1984
+ script: [
1985
+ /* <- TODO: Allow to just keep script undefined */
1986
+ ],
1987
+ },
1988
+ });
1989
+ return [4 /*yield*/, prepareKnowledgeFromMarkdownExecutor({ content: content })];
1990
+ case 3:
1991
+ result = _b.sent();
1992
+ assertsExecutionSuccessful(result);
1993
+ outputParameters = result.outputParameters;
1994
+ knowledgeRaw = outputParameters.knowledge;
1995
+ knowledgeTextPieces = (knowledgeRaw || '').split('\n---\n');
1996
+ if (isVerbose) {
1997
+ console.info('knowledgeTextPieces:', knowledgeTextPieces);
1998
+ }
1999
+ return [4 /*yield*/, Promise.all(knowledgeTextPieces.map(function (knowledgeTextPiece, i) { return __awaiter(_this, void 0, void 0, function () {
2000
+ var name, title, content, keywords, index, sources, result_1, _a, outputParameters_1, keywordsRaw, error_1;
2001
+ return __generator(this, function (_b) {
2002
+ switch (_b.label) {
2003
+ case 0:
2004
+ name = "piece-".concat(i);
2005
+ title = spaceTrim__default["default"](knowledgeTextPiece.substring(0, 100));
2006
+ content = spaceTrim__default["default"](knowledgeTextPiece);
2007
+ keywords = [];
2008
+ index = [];
2009
+ sources = [];
2010
+ _b.label = 1;
2011
+ case 1:
2012
+ _b.trys.push([1, 3, , 4]);
2013
+ // TODO: !!!! Summarize name and title from the content
2014
+ title = spaceTrim__default["default"](knowledgeTextPiece.substring(0, 30));
2015
+ name = normalizeToKebabCase(title);
2016
+ return [4 /*yield*/, prepareKeywordsExecutor({ content: content })];
2017
+ case 2:
2018
+ result_1 = _b.sent();
2019
+ _a = result_1.outputParameters, outputParameters_1 = _a === void 0 ? {} : _a;
2020
+ keywordsRaw = outputParameters_1.keywords;
2021
+ keywords = (keywordsRaw || '')
2022
+ .split(',')
2023
+ .map(function (keyword) { return keyword.trim(); })
2024
+ .filter(function (keyword) { return keyword !== ''; });
2025
+ if (isVerbose) {
2026
+ console.info("Keywords for \"".concat(title, "\":"), keywords);
2027
+ }
2028
+ // ---
2029
+ // TODO: !!!! Index through LLM model
2030
+ index.push({
2031
+ modelName: 'fake-model',
2032
+ position: new Array(25).fill(0).map(function () { return Math.random() * 2 - 1; }),
2033
+ });
2034
+ return [3 /*break*/, 4];
2035
+ case 3:
2036
+ error_1 = _b.sent();
2037
+ console.error(error_1);
2038
+ return [3 /*break*/, 4];
2039
+ case 4: return [2 /*return*/, {
2040
+ name: name,
2041
+ title: title,
2042
+ content: content,
2043
+ keywords: keywords,
2044
+ index: index,
2045
+ sources: sources,
2046
+ }];
2047
+ }
2048
+ });
2049
+ }); }))];
2050
+ case 4:
2051
+ knowledge = _b.sent();
2052
+ return [2 /*return*/, knowledge];
2053
+ }
2054
+ });
2055
+ });
2056
+ }
2057
+
2058
+ /**
2059
+ * Supported script languages
2060
+ */
2061
+ var SUPPORTED_SCRIPT_LANGUAGES = ['javascript', 'typescript', 'python'];
2062
+
2063
+ /**
2064
+ * Computes the deepness of the markdown structure.
2065
+ *
2066
+ * @private within the library
2067
+ */
2068
+ function countMarkdownStructureDeepness(markdownStructure) {
2069
+ var e_1, _a;
2070
+ var maxDeepness = 0;
2071
+ try {
2072
+ for (var _b = __values(markdownStructure.sections), _c = _b.next(); !_c.done; _c = _b.next()) {
2073
+ var section = _c.value;
2074
+ maxDeepness = Math.max(maxDeepness, countMarkdownStructureDeepness(section));
2075
+ }
2076
+ }
2077
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2078
+ finally {
2079
+ try {
2080
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2081
+ }
2082
+ finally { if (e_1) throw e_1.error; }
2083
+ }
2084
+ return maxDeepness + 1;
2085
+ }
2086
+
2087
+ /**
2088
+ * Parse a markdown string into a MarkdownStructure object.
2089
+ *
2090
+ * Note: This function does work with code blocks
2091
+ * Note: This function does not work with markdown comments
2092
+ *
2093
+ * @param markdown The markdown string to parse.
2094
+ * @returns The MarkdownStructure object.
2095
+ *
2096
+ * @private within the library
2097
+ */
2098
+ function markdownToMarkdownStructure(markdown) {
2099
+ var e_1, _a;
2100
+ var lines = markdown.split('\n');
2101
+ var root = { level: 0, title: '', contentLines: [], sections: [], parent: null };
2102
+ var current = root;
2103
+ var isInsideCodeBlock = false;
2104
+ try {
2105
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2106
+ var line = lines_1_1.value;
2107
+ var headingMatch = line.match(/^(?<mark>#{1,6})\s(?<title>.*)/);
2108
+ if (isInsideCodeBlock || !headingMatch) {
2109
+ if (line.startsWith('```')) {
2110
+ isInsideCodeBlock = !isInsideCodeBlock;
2111
+ }
2112
+ current.contentLines.push(line);
2113
+ }
2114
+ else {
2115
+ var level = headingMatch.groups.mark.length;
2116
+ var title = headingMatch.groups.title.trim();
2117
+ var parent_1 = void 0;
2118
+ if (level > current.level) {
2119
+ // Note: Going deeper (next section is child of current)
2120
+ parent_1 = current;
2121
+ }
2122
+ else {
2123
+ // Note: Going up or staying at the same level (next section is sibling or parent or grandparent,... of current)
2124
+ parent_1 = current;
2125
+ var loopLimit = LOOP_LIMIT;
2126
+ while (parent_1.level !== level - 1) {
2127
+ if (loopLimit-- < 0) {
2128
+ throw new UnexpectedError('Loop limit reached during parsing of markdown structure in `markdownToMarkdownStructure`');
2129
+ }
2130
+ if (parent_1.parent === null /* <- Note: We are in root */) {
2131
+ // [🌻]
2132
+ throw new Error(spaceTrim.spaceTrim("\n The file has an invalid structure.\n The markdown file must have exactly one top-level section.\n "));
2133
+ }
2134
+ parent_1 = parent_1.parent;
2135
+ }
2136
+ }
2137
+ var section = { level: level, title: title, contentLines: [], sections: [], parent: parent_1 };
2138
+ parent_1.sections.push(section);
2139
+ current = section;
2140
+ }
2141
+ }
2142
+ }
2143
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2144
+ finally {
2145
+ try {
2146
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2147
+ }
2148
+ finally { if (e_1) throw e_1.error; }
2149
+ }
2150
+ if (root.sections.length === 1) {
2151
+ var markdownStructure = parsingMarkdownStructureToMarkdownStructure(root.sections[0]);
2152
+ return markdownStructure;
2153
+ }
2154
+ // [🌻]
2155
+ throw new Error('The markdown file must have exactly one top-level section.');
2156
+ // return root;
2157
+ }
2158
+ /**
2159
+ * @private
2160
+ */
2161
+ function parsingMarkdownStructureToMarkdownStructure(parsingMarkdownStructure) {
2162
+ var level = parsingMarkdownStructure.level, title = parsingMarkdownStructure.title, contentLines = parsingMarkdownStructure.contentLines, sections = parsingMarkdownStructure.sections;
2163
+ return {
2164
+ level: level,
2165
+ title: title,
2166
+ content: spaceTrim.spaceTrim(contentLines.join('\n')),
2167
+ sections: sections.map(parsingMarkdownStructureToMarkdownStructure),
2168
+ };
2169
+ }
2170
+
2171
+ /**
2172
+ * Utility function to extract all list items from markdown
2173
+ *
2174
+ * Note: It works with both ul and ol
2175
+ * Note: It omits list items in code blocks
2176
+ * Note: It flattens nested lists
2177
+ * Note: It can not work with html syntax and comments
2178
+ *
2179
+ * @param markdown any valid markdown
2180
+ * @returns
2181
+ */
2182
+ function extractAllListItemsFromMarkdown(markdown) {
2183
+ var e_1, _a;
2184
+ var lines = markdown.split('\n');
2185
+ var listItems = [];
2186
+ var isInCodeBlock = false;
2187
+ try {
2188
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2189
+ var line = lines_1_1.value;
2190
+ var trimmedLine = line.trim();
2191
+ if (trimmedLine.startsWith('```')) {
2192
+ isInCodeBlock = !isInCodeBlock;
2193
+ }
2194
+ if (!isInCodeBlock && (trimmedLine.startsWith('-') || trimmedLine.match(/^\d+\./))) {
2195
+ var listItem = trimmedLine.replace(/^-|\d+\./, '').trim();
2196
+ listItems.push(listItem);
2197
+ }
2198
+ }
2199
+ }
2200
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2201
+ finally {
2202
+ try {
2203
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2204
+ }
2205
+ finally { if (e_1) throw e_1.error; }
2206
+ }
2207
+ return listItems;
2208
+ }
2209
+
2210
+ /**
2211
+ * Extracts all code blocks from markdown.
2212
+ *
2213
+ * Note: There are 3 simmilar function:
2214
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2215
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2216
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2217
+ *
2218
+ * @param markdown any valid markdown
2219
+ * @returns code blocks with language and content
2220
+ *
2221
+ */
2222
+ function extractAllBlocksFromMarkdown(markdown) {
2223
+ var e_1, _a;
2224
+ var codeBlocks = [];
2225
+ var lines = markdown.split('\n');
2226
+ var currentCodeBlock = null;
2227
+ try {
2228
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2229
+ var line = lines_1_1.value;
2230
+ if (line.startsWith('```')) {
2231
+ var language = line.slice(3).trim() || null;
2232
+ if (currentCodeBlock === null) {
2233
+ currentCodeBlock = { language: language, content: '' };
2234
+ }
2235
+ else {
2236
+ if (language !== null) {
2237
+ // [🌻]
2238
+ throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2239
+ }
2240
+ codeBlocks.push(currentCodeBlock);
2241
+ currentCodeBlock = null;
2242
+ }
2243
+ }
2244
+ else if (currentCodeBlock !== null) {
2245
+ if (currentCodeBlock.content !== '') {
2246
+ currentCodeBlock.content += '\n';
2247
+ }
2248
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2249
+ }
2250
+ }
2251
+ }
2252
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2253
+ finally {
2254
+ try {
2255
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2256
+ }
2257
+ finally { if (e_1) throw e_1.error; }
2258
+ }
2259
+ if (currentCodeBlock !== null) {
2260
+ // [🌻]
2261
+ throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2262
+ }
2263
+ return codeBlocks;
2264
+ }
2265
+
2266
+ /**
2267
+ * Extracts exactly ONE code block from markdown.
2268
+ *
2269
+ * Note: If there are multiple or no code blocks the function throws an error
2270
+ *
2271
+ * Note: There are 3 simmilar function:
2272
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2273
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2274
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2275
+ *
2276
+ * @param markdown any valid markdown
2277
+ * @returns code block with language and content
2278
+ */
2279
+ function extractOneBlockFromMarkdown(markdown) {
2280
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2281
+ if (codeBlocks.length !== 1) {
2282
+ // TODO: Report more specific place where the error happened
2283
+ throw new Error(/* <- [🌻] */ 'There should be exactly one code block in the markdown');
2284
+ }
2285
+ return codeBlocks[0];
2286
+ }
2287
+ /***
2288
+ * TODO: [🍓][🌻] !!! Decide of this is internal util, external util OR validator/postprocessor
2289
+ */
2290
+
2291
+ /**
2292
+ * Removes HTML or Markdown comments from a string.
2293
+ *
2294
+ * @param {string} content - The string to remove comments from.
2295
+ * @returns {string} The input string with all comments removed.
2296
+ */
2297
+ function removeContentComments(content) {
2298
+ return spaceTrim.spaceTrim(content.replace(/<!--(.*?)-->/gs, ''));
2299
+ }
2300
+
2301
+ /**
2302
+ * Creates a new set with all elements that are present in either set
2303
+ */
2304
+ function union() {
2305
+ var e_1, _a, e_2, _b;
2306
+ var sets = [];
2307
+ for (var _i = 0; _i < arguments.length; _i++) {
2308
+ sets[_i] = arguments[_i];
2309
+ }
2310
+ var union = new Set();
2311
+ try {
2312
+ for (var sets_1 = __values(sets), sets_1_1 = sets_1.next(); !sets_1_1.done; sets_1_1 = sets_1.next()) {
2313
+ var set = sets_1_1.value;
2314
+ try {
2315
+ for (var _c = (e_2 = void 0, __values(Array.from(set))), _d = _c.next(); !_d.done; _d = _c.next()) {
2316
+ var item = _d.value;
2317
+ union.add(item);
2318
+ }
2319
+ }
2320
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2321
+ finally {
2322
+ try {
2323
+ if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
2324
+ }
2325
+ finally { if (e_2) throw e_2.error; }
2326
+ }
2327
+ }
2328
+ }
2329
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2330
+ finally {
2331
+ try {
2332
+ if (sets_1_1 && !sets_1_1.done && (_a = sets_1.return)) _a.call(sets_1);
2333
+ }
2334
+ finally { if (e_1) throw e_1.error; }
2335
+ }
2336
+ return union;
2337
+ }
2338
+
2339
+ /**
2340
+ * Parses the template and returns the list of all parameter names
2341
+ *
2342
+ * @param template the template with parameters in {curly} braces
2343
+ * @returns the list of parameter names
2344
+ */
2345
+ function extractParameters(template) {
2346
+ var e_1, _a;
2347
+ var matches = template.matchAll(/{\w+}/g);
2348
+ var parameterNames = new Set();
2349
+ try {
2350
+ for (var matches_1 = __values(matches), matches_1_1 = matches_1.next(); !matches_1_1.done; matches_1_1 = matches_1.next()) {
2351
+ var match = matches_1_1.value;
2352
+ var parameterName = match[0].slice(1, -1);
2353
+ parameterNames.add(parameterName);
2354
+ }
2355
+ }
2356
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2357
+ finally {
2358
+ try {
2359
+ if (matches_1_1 && !matches_1_1.done && (_a = matches_1.return)) _a.call(matches_1);
2360
+ }
2361
+ finally { if (e_1) throw e_1.error; }
2362
+ }
2363
+ return parameterNames;
2364
+ }
2365
+
2366
+ /**
2367
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2368
+ *
2369
+ * @param script from which to extract the variables
2370
+ * @returns the list of variable names
2371
+ * @throws {PromptbookSyntaxError} if the script is invalid
2372
+ */
2373
+ function extractVariables(script) {
2374
+ var variables = new Set();
2375
+ script = "(()=>{".concat(script, "})()");
2376
+ try {
2377
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2378
+ try {
2379
+ eval(script);
2380
+ }
2381
+ catch (error) {
2382
+ if (!(error instanceof ReferenceError)) {
2383
+ throw error;
2384
+ }
2385
+ var undefinedName = error.message.split(' ')[0];
2386
+ /*
2387
+ Note: Remapping error
2388
+ From: [ReferenceError: thing is not defined],
2389
+ To: [Error: Parameter {thing} is not defined],
2390
+ */
2391
+ if (!undefinedName) {
2392
+ throw error;
2393
+ }
2394
+ if (script.includes(undefinedName + '(')) {
2395
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2396
+ }
2397
+ else {
2398
+ variables.add(undefinedName);
2399
+ script = "const ".concat(undefinedName, " = '';") + script;
2400
+ }
2401
+ }
2402
+ }
2403
+ catch (error) {
2404
+ if (!(error instanceof Error)) {
2405
+ throw error;
2406
+ }
2407
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.name), ": ").concat(block(error.message), "\n "); }));
2408
+ }
2409
+ return variables;
2410
+ }
2411
+ /**
2412
+ * TODO: [🔣] Support for multiple languages - python, java,...
2413
+ */
2414
+
2415
+ /**
2416
+ * Parses the prompt template and returns the set of all used parameters
2417
+ *
2418
+ * @param promptTemplate the template with used parameters
2419
+ * @returns the set of parameter names
2420
+ * @throws {PromptbookSyntaxError} if the script is invalid
2421
+ */
2422
+ function extractParametersFromPromptTemplate(promptTemplate) {
2423
+ var e_1, _a, e_2, _b;
2424
+ var parameterNames = new Set();
2425
+ try {
2426
+ for (var _c = __values(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameters(promptTemplate.title)), false), __read(extractParameters(promptTemplate.description || '')), false), __read(extractParameters(promptTemplate.content)), false)), _d = _c.next(); !_d.done; _d = _c.next()) {
2427
+ var parameterName = _d.value;
2428
+ parameterNames.add(parameterName);
2429
+ }
2430
+ }
2431
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2432
+ finally {
2433
+ try {
2434
+ if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
2435
+ }
2436
+ finally { if (e_1) throw e_1.error; }
2437
+ }
2438
+ if (promptTemplate.executionType === 'SCRIPT') {
2439
+ try {
2440
+ for (var _e = __values(extractVariables(promptTemplate.content)), _f = _e.next(); !_f.done; _f = _e.next()) {
2441
+ var parameterName = _f.value;
2442
+ parameterNames.add(parameterName);
2443
+ }
2444
+ }
2445
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2446
+ finally {
2447
+ try {
2448
+ if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
2449
+ }
2450
+ finally { if (e_2) throw e_2.error; }
2451
+ }
2452
+ }
2453
+ return parameterNames;
2454
+ }
2455
+ /**
2456
+ * TODO: [🔣] If script require contentLanguage
2457
+ */
2458
+
2459
+ /* tslint:disable */
2460
+ /*
2461
+ TODO: Tests
2462
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'Moje tabule' })).toEqual('/VtG7sR9rRJqwNEdM2/Moje tabule');
2463
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'ěščřžžýáíúů' })).toEqual('/VtG7sR9rRJqwNEdM2/escrzyaieuu');
2464
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj');
2465
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj_ahojAhoj ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj-ahoj-ahoj-ahoj');
2466
+ */
2467
+ function normalizeTo_SCREAMING_CASE(sentence) {
2468
+ var e_1, _a;
2469
+ var charType;
2470
+ var lastCharType = 'OTHER';
2471
+ var normalizedName = '';
2472
+ try {
2473
+ for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
2474
+ var char = sentence_1_1.value;
2475
+ var normalizedChar = void 0;
2476
+ if (/^[a-z]$/.test(char)) {
2477
+ charType = 'LOWERCASE';
2478
+ normalizedChar = char.toUpperCase();
2479
+ }
2480
+ else if (/^[A-Z]$/.test(char)) {
2481
+ charType = 'UPPERCASE';
2482
+ normalizedChar = char;
2483
+ }
2484
+ else if (/^[0-9]$/.test(char)) {
2485
+ charType = 'NUMBER';
2486
+ normalizedChar = char;
2487
+ }
2488
+ else if (/^\/$/.test(char)) {
2489
+ charType = 'SLASH';
2490
+ normalizedChar = char;
2491
+ }
2492
+ else {
2493
+ charType = 'OTHER';
2494
+ normalizedChar = '_';
2495
+ }
2496
+ if (charType !== lastCharType &&
2497
+ !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
2498
+ !(lastCharType === 'NUMBER') &&
2499
+ !(charType === 'NUMBER')) {
2500
+ normalizedName += '_';
2501
+ }
2502
+ normalizedName += normalizedChar;
2503
+ lastCharType = charType;
2504
+ }
2505
+ }
2506
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2507
+ finally {
2508
+ try {
2509
+ if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
2510
+ }
2511
+ finally { if (e_1) throw e_1.error; }
2512
+ }
2513
+ normalizedName = normalizedName.replace(/_+/g, '_');
2514
+ normalizedName = normalizedName.replace(/_?\/_?/g, '/');
2515
+ normalizedName = normalizedName.replace(/^_/, '');
2516
+ normalizedName = normalizedName.replace(/_$/, '');
2517
+ return normalizedName;
2518
+ }
2519
+ /**
2520
+ * TODO: [🌺] Use some intermediate util splitWords
2521
+ */
2522
+
2523
+ /**
2524
+ * Execution type describes the way how the block is executed
2525
+ *
2526
+ * @see https://github.com/webgptorg/promptbook#execution-type
2527
+ */
2528
+ var ExecutionTypes = [
2529
+ 'PROMPT_TEMPLATE',
2530
+ 'SIMPLE_TEMPLATE',
2531
+ 'SCRIPT',
2532
+ 'PROMPT_DIALOG',
2533
+ // <- [🥻] Insert here when making new command
2534
+ ];
2535
+
2536
+ /**
2537
+ * Units of text measurement
2538
+ */
2539
+ var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'LINES', 'PARAGRAPHS', 'PAGES'];
2540
+ /**
2541
+ * TODO: [💝] Unite object for expecting amount and format - remove expectFormat
2542
+ * TODO: use one helper type> (string_prompt | string_javascript | string_markdown) & string_template
2543
+ * TODO: [👙][🧠] Just selecting gpt3 or gpt4 level of model
2544
+ */
2545
+
2546
+ /**
2547
+ * Removes Markdown formatting tags from a string.
2548
+ *
2549
+ * @param {string} str - The string to remove Markdown tags from.
2550
+ * @returns {string} The input string with all Markdown tags removed.
2551
+ */
2552
+ function removeMarkdownFormatting(str) {
2553
+ // Remove bold formatting
2554
+ str = str.replace(/\*\*(.*?)\*\*/g, '$1');
2555
+ // Remove italic formatting
2556
+ str = str.replace(/\*(.*?)\*/g, '$1');
2557
+ // Remove code formatting
2558
+ str = str.replace(/`(.*?)`/g, '$1');
2559
+ return str;
2560
+ }
2561
+
2562
+ /**
2563
+ * Function parseNumber will parse number from string
2564
+ *
2565
+ * Unlike Number.parseInt, Number.parseFloat it will never ever result in NaN
2566
+ * Note: it also works only with decimal numbers
2567
+ *
2568
+ * @returns parsed number
2569
+ * @throws {PromptbookSyntaxError} if the value is not a number
2570
+ *
2571
+ * @private within the parseCommand
2572
+ */
2573
+ function parseNumber(value) {
2574
+ var originalValue = value;
2575
+ if (typeof value === 'number') {
2576
+ value = value.toString(); // <- TODO: Maybe more efficient way to do this
2577
+ }
2578
+ if (typeof value !== 'string') {
2579
+ return 0;
2580
+ }
2581
+ value = value.trim();
2582
+ if (value.startsWith('+')) {
2583
+ return parseNumber(value.substring(1));
2584
+ }
2585
+ if (value.startsWith('-')) {
2586
+ var number = parseNumber(value.substring(1));
2587
+ if (number === 0) {
2588
+ return 0; // <- Note: To prevent -0
2589
+ }
2590
+ return -number;
2591
+ }
2592
+ value = value.replace(/,/g, '.');
2593
+ value = value.toUpperCase();
2594
+ if (value === '') {
2595
+ return 0;
2596
+ }
2597
+ if (value === '♾' || value.startsWith('INF')) {
2598
+ return Infinity;
2599
+ }
2600
+ if (value.includes('/')) {
2601
+ var _a = __read(value.split('/'), 2), numerator_ = _a[0], denominator_ = _a[1];
2602
+ var numerator = parseNumber(numerator_);
2603
+ var denominator = parseNumber(denominator_);
2604
+ if (denominator === 0) {
2605
+ throw new PromptbookSyntaxError("Unable to parse number from \"".concat(originalValue, "\" because denominator is zero"));
2606
+ }
2607
+ return numerator / denominator;
2608
+ }
2609
+ if (/^(NAN|NULL|NONE|UNDEFINED|ZERO|NO.*)$/.test(value)) {
2610
+ return 0;
2611
+ }
2612
+ if (value.includes('E')) {
2613
+ var _b = __read(value.split('E'), 2), significand = _b[0], exponent = _b[1];
2614
+ return parseNumber(significand) * Math.pow(10, parseNumber(exponent));
2615
+ }
2616
+ if (!/^[0-9.]+$/.test(value) || value.split('.').length > 2) {
2617
+ throw new PromptbookSyntaxError("Unable to parse number from \"".concat(originalValue, "\""));
2618
+ }
2619
+ var num = parseFloat(value);
2620
+ if (isNaN(num)) {
2621
+ throw new PromptbookSyntaxError("Unexpected NaN when parsing number from \"".concat(originalValue, "\""));
2622
+ }
2623
+ return num;
2624
+ }
2625
+ /**
2626
+ * TODO: Maybe use sth. like safe-eval in fraction/calculation case @see https://www.npmjs.com/package/safe-eval
2627
+ */
2628
+
2629
+ /**
2630
+ * Parses one line of ul/ol to command
2631
+ *
2632
+ * @returns parsed command object
2633
+ * @throws {PromptbookSyntaxError} if the command is invalid
2634
+ *
2635
+ * @private within the promptbookStringToJson
2636
+ */
2637
+ function parseCommand(listItem) {
2638
+ var e_1, _a;
2639
+ if (listItem.includes('\n') || listItem.includes('\r')) {
2640
+ throw new PromptbookSyntaxError('Command can not contain new line characters:');
2641
+ }
2642
+ var type = listItem.trim();
2643
+ type = type.split('`').join('');
2644
+ type = type.split('"').join('');
2645
+ type = type.split("'").join('');
2646
+ type = type.split('~').join('');
2647
+ type = type.split('[').join('');
2648
+ type = type.split(']').join('');
2649
+ type = type.split('(').join('');
2650
+ type = type.split(')').join('');
2651
+ type = normalizeTo_SCREAMING_CASE(type);
2652
+ type = type.split('DIALOGUE').join('DIALOG');
2653
+ var listItemParts = listItem
2654
+ .split(' ')
2655
+ .map(function (part) { return part.trim(); })
2656
+ .filter(function (item) { return item !== ''; })
2657
+ .filter(function (item) { return !/^PTBK$/i.test(item); })
2658
+ .filter(function (item) { return !/^PROMPTBOOK$/i.test(item); })
2659
+ .map(removeMarkdownFormatting);
2660
+ if (type.startsWith('URL') ||
2661
+ type.startsWith('PTBK_URL') ||
2662
+ type.startsWith('PTBKURL') ||
2663
+ type.startsWith('PROMPTBOOK_URL') ||
2664
+ type.startsWith('PROMPTBOOKURL') ||
2665
+ type.startsWith('HTTPS')) {
2666
+ if (!(listItemParts.length === 2 || (listItemParts.length === 1 && type.startsWith('HTTPS')))) {
2667
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n ")));
2668
+ }
2669
+ var promptbookUrlString = listItemParts.pop();
2670
+ var promptbookUrl = new URL(promptbookUrlString);
2671
+ if (promptbookUrl.protocol !== 'https:') {
2672
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n Protocol must be HTTPS\n ")));
2673
+ }
2674
+ if (promptbookUrl.hash !== '') {
2675
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n URL must not contain hash\n Hash is used for identification of the prompt template in the pipeline\n ")));
2676
+ }
2677
+ return {
2678
+ type: 'PROMPTBOOK_URL',
2679
+ promptbookUrl: promptbookUrl,
2680
+ };
2681
+ }
2682
+ else if (type.startsWith('PROMPTBOOK_VERSION') || type.startsWith('PTBK_VERSION')) {
2683
+ if (listItemParts.length !== 2) {
2684
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_VERSION command:\n\n - ".concat(listItem, "\n ")));
2685
+ }
2686
+ var promptbookVersion = listItemParts.pop();
2687
+ // TODO: Validate version
2688
+ return {
2689
+ type: 'PROMPTBOOK_VERSION',
2690
+ promptbookVersion: promptbookVersion,
2691
+ };
2692
+ }
2693
+ else if (type.startsWith('EXECUTE') ||
2694
+ type.startsWith('EXEC') ||
2695
+ type.startsWith('PROMPT_DIALOG') ||
2696
+ type.startsWith('SIMPLE_TEMPLATE')) {
2697
+ var executionTypes = ExecutionTypes.filter(function (executionType) { return type.includes(executionType); });
2698
+ if (executionTypes.length !== 1) {
2699
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type in command:\n\n - ".concat(listItem, "\n\n Supported execution types are:\n ").concat(block(ExecutionTypes.join(', ')), "\n "); }));
2700
+ }
2701
+ return {
2702
+ type: 'EXECUTE',
2703
+ executionType: executionTypes[0],
2704
+ };
2705
+ }
2706
+ else if (type.startsWith('MODEL')) {
2707
+ // TODO: Make this more elegant and dynamically
2708
+ if (type.startsWith('MODEL_VARIANT')) {
2709
+ if (type === 'MODEL_VARIANT_CHAT') {
2710
+ return {
2711
+ type: 'MODEL',
2712
+ key: 'modelVariant',
2713
+ value: 'CHAT',
2714
+ };
2715
+ }
2716
+ else if (type === 'MODEL_VARIANT_COMPLETION') {
2717
+ return {
2718
+ type: 'MODEL',
2719
+ key: 'modelVariant',
2720
+ value: 'COMPLETION',
2721
+ };
2722
+ }
2723
+ else {
2724
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model variant in command:\n\n - ".concat(listItem, "\n\n Supported variants are:\n ").concat(block(['CHAT', 'COMPLETION'].join(', ')), "\n "); }));
2725
+ }
2726
+ }
2727
+ if (type.startsWith('MODEL_NAME')) {
2728
+ return {
2729
+ type: 'MODEL',
2730
+ key: 'modelName',
2731
+ value: listItemParts.pop(),
2732
+ };
2733
+ }
2734
+ else {
2735
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model key in command:\n\n - ".concat(listItem, "\n\n Supported model keys are:\n ").concat(block(['variant', 'name'].join(', ')), "\n\n Example:\n\n - MODEL VARIANT Chat\n - MODEL NAME gpt-4\n "); }));
2736
+ }
2737
+ }
2738
+ else if (type.startsWith('PARAM') ||
2739
+ type.startsWith('INPUT_PARAM') ||
2740
+ type.startsWith('OUTPUT_PARAM') ||
2741
+ listItem.startsWith('{') ||
2742
+ listItem.startsWith('> {') /* <- Note: This is a bit hack to parse return parameters defined at the end of each section */) {
2743
+ var parametersMatch = listItem.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
2744
+ if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
2745
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
2746
+ }
2747
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2748
+ var _b = parametersMatch.groups, parameterName = _b.parameterName, parameterDescription = _b.parameterDescription;
2749
+ if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
2750
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Parameter {".concat(parameterName, "} can not contain another parameter in description:\n\n - ").concat(listItem, "\n ")));
2751
+ }
2752
+ var isInput = type.startsWith('INPUT');
2753
+ var isOutput = type.startsWith('OUTPUT');
2754
+ if (listItem.startsWith('> {')) {
2755
+ isInput = false;
2756
+ isOutput = false;
2757
+ }
2758
+ return {
2759
+ type: 'PARAMETER',
2760
+ parameterName: parameterName,
2761
+ parameterDescription: parameterDescription.trim() || null,
2762
+ isInput: isInput,
2763
+ isOutput: isOutput,
2764
+ };
2765
+ }
2766
+ else if (type.startsWith('JOKER')) {
2767
+ if (listItemParts.length !== 2) {
2768
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid JOKER command:\n\n - ".concat(listItem, "\n ")));
2769
+ }
2770
+ var parametersMatch = (listItemParts.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
2771
+ if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
2772
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
2773
+ }
2774
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2775
+ var parameterName = parametersMatch.groups.parameterName;
2776
+ return {
2777
+ type: 'JOKER',
2778
+ parameterName: parameterName,
2779
+ };
2780
+ }
2781
+ else if (type.startsWith('POSTPROCESS') || type.startsWith('POST_PROCESS')) {
2782
+ if (listItemParts.length !== 2) {
2783
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid POSTPROCESSING command:\n\n - ".concat(listItem, "\n ")));
2784
+ }
2785
+ var functionName = listItemParts.pop();
2786
+ return {
2787
+ type: 'POSTPROCESS',
2788
+ functionName: functionName,
2789
+ };
2790
+ }
2791
+ else if (type.startsWith('EXPECT_JSON')) {
2792
+ return {
2793
+ type: 'EXPECT_FORMAT',
2794
+ format: 'JSON',
2795
+ };
2796
+ // [🥤]
2797
+ }
2798
+ else if (type.startsWith('EXPECT')) {
2799
+ try {
2800
+ listItemParts.shift();
2801
+ var sign = void 0;
2802
+ var signRaw = listItemParts.shift();
2803
+ if (/^exact/i.test(signRaw)) {
2804
+ sign = 'EXACTLY';
2805
+ }
2806
+ else if (/^min/i.test(signRaw)) {
2807
+ sign = 'MINIMUM';
2808
+ }
2809
+ else if (/^max/i.test(signRaw)) {
2810
+ sign = 'MAXIMUM';
2811
+ }
2812
+ else {
2813
+ throw new PromptbookSyntaxError("Invalid sign \"".concat(signRaw, "\", expected EXACTLY, MIN or MAX"));
2814
+ }
2815
+ var amountRaw = listItemParts.shift();
2816
+ var amount = parseNumber(amountRaw);
2817
+ if (amount < 0) {
2818
+ throw new PromptbookSyntaxError('Amount must be positive number or zero');
2819
+ }
2820
+ if (amount !== Math.floor(amount)) {
2821
+ throw new PromptbookSyntaxError('Amount must be whole number');
2822
+ }
2823
+ var unitRaw = listItemParts.shift();
2824
+ var unit = undefined;
2825
+ try {
2826
+ for (var EXPECTATION_UNITS_1 = __values(EXPECTATION_UNITS), EXPECTATION_UNITS_1_1 = EXPECTATION_UNITS_1.next(); !EXPECTATION_UNITS_1_1.done; EXPECTATION_UNITS_1_1 = EXPECTATION_UNITS_1.next()) {
2827
+ var existingUnit = EXPECTATION_UNITS_1_1.value;
2828
+ var existingUnitText = existingUnit;
2829
+ existingUnitText = existingUnitText.substring(0, existingUnitText.length - 1);
2830
+ if (existingUnitText === 'CHARACTER') {
2831
+ existingUnitText = 'CHAR';
2832
+ }
2833
+ if (new RegExp("^".concat(existingUnitText.toLowerCase())).test(unitRaw.toLowerCase()) ||
2834
+ new RegExp("^".concat(unitRaw.toLowerCase())).test(existingUnitText.toLowerCase())) {
2835
+ if (unit !== undefined) {
2836
+ throw new PromptbookSyntaxError("Ambiguous unit \"".concat(unitRaw, "\""));
2837
+ }
2838
+ unit = existingUnit;
2839
+ }
2840
+ }
2841
+ }
2842
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2843
+ finally {
2844
+ try {
2845
+ if (EXPECTATION_UNITS_1_1 && !EXPECTATION_UNITS_1_1.done && (_a = EXPECTATION_UNITS_1.return)) _a.call(EXPECTATION_UNITS_1);
2846
+ }
2847
+ finally { if (e_1) throw e_1.error; }
2848
+ }
2849
+ if (unit === undefined) {
2850
+ throw new PromptbookSyntaxError("Invalid unit \"".concat(unitRaw, "\""));
2851
+ }
2852
+ return {
2853
+ type: 'EXPECT_AMOUNT',
2854
+ sign: sign,
2855
+ unit: unit,
2856
+ amount: amount,
2857
+ };
2858
+ }
2859
+ catch (error) {
2860
+ if (!(error instanceof Error)) {
2861
+ throw error;
2862
+ }
2863
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid EXPECT command; ".concat(error.message, ":\n\n - ").concat(listItem, "\n ")));
2864
+ }
2865
+ /*
2866
+ } else if (type.startsWith('__________________')) {
2867
+ // <- [🥻] Insert here when making new command
2868
+ */
2869
+ }
2870
+ else {
2871
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Unknown command:\n\n - ".concat(listItem, "\n\n Supported commands are:\n - PROMPTBOOK_URL <url>\n - PROMPTBOOK_VERSION <version>\n - EXECUTE PROMPT TEMPLATE\n - EXECUTE SIMPLE TEMPLATE\n - SIMPLE TEMPLATE\n - EXECUTE SCRIPT\n - EXECUTE PROMPT_DIALOG'\n - PROMPT_DIALOG'\n - MODEL NAME <name>\n - MODEL VARIANT <\"Chat\"|\"Completion\">\n - INPUT PARAM {<name>} <description>\n - OUTPUT PARAM {<name>} <description>\n - POSTPROCESS `{functionName}`\n - JOKER {<name>}\n - EXPECT JSON\n - EXPECT <\"Exactly\"|\"Min\"|\"Max\"> <number> <\"Chars\"|\"Words\"|\"Sentences\"|\"Paragraphs\"|\"Pages\">\n\n ")));
2872
+ }
2873
+ }
2874
+
2875
+ /**
2876
+ * Removes emojis from a string and fix whitespaces
2877
+ *
2878
+ * @param text with emojis
2879
+ * @returns text without emojis
2880
+ */
2881
+ function removeEmojis(text) {
2882
+ // Replace emojis (and also ZWJ sequence) with hyphens
2883
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
2884
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
2885
+ text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
2886
+ text = text.replace(/\p{Extended_Pictographic}/gu, '');
2887
+ return text;
2888
+ }
2889
+
2890
+ /**
2891
+ * Function normalizes title to name which can be used as identifier
2892
+ */
2893
+ function titleToName(value) {
2894
+ value = removeEmojis(value);
2895
+ value = normalizeToKebabCase(value);
2896
+ // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
2897
+ return value;
2898
+ }
2899
+
2900
+ /**
2901
+ * Compile promptbook from string (markdown) format to JSON format
2902
+ *
2903
+ * @param promptbookString {Promptbook} in string markdown format (.ptbk.md)
2904
+ * @param options - Options and tools for the compilation
2905
+ * @returns {Promptbook} compiled in JSON format (.ptbk.json)
2906
+ * @throws {PromptbookSyntaxError} if the promptbook string is not valid
2907
+ *
2908
+ * Note: This function does not validate logic of the pipeline only the syntax
2909
+ * Note: This function acts as compilation process
2910
+ */
2911
+ function promptbookStringToJson(promptbookString, options) {
2912
+ if (options === void 0) { options = {}; }
2913
+ return __awaiter(this, void 0, void 0, function () {
2914
+ var llmTools, promptbookJson, knowledge, addParam, markdownStructure, markdownStructureDeepness, description, defaultModelRequirements, listItems, listItems_1, listItems_1_1, listItem, command, _loop_1, _a, _b, section;
2915
+ var e_1, _c, e_2, _d;
2916
+ return __generator(this, function (_e) {
2917
+ switch (_e.label) {
2918
+ case 0:
2919
+ llmTools = options.llmTools;
2920
+ promptbookJson = {
2921
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2922
+ title: undefined /* <- Note: Putting here placeholder to keep `title` on top at final JSON */,
2923
+ promptbookUrl: undefined /* <- Note: Putting here placeholder to keep `promptbookUrl` on top at final JSON */,
2924
+ promptbookVersion: PROMPTBOOK_VERSION,
2925
+ description: undefined /* <- Note: Putting here placeholder to keep `description` on top at final JSON */,
2926
+ parameters: [],
2927
+ promptTemplates: [],
2928
+ knowledge: [],
2929
+ };
2930
+ if (!llmTools) return [3 /*break*/, 2];
2931
+ return [4 /*yield*/, prepareKnowledgeFromMarkdown({
2932
+ content: 'Roses are red, violets are blue, programmers use Promptbook, users too',
2933
+ llmTools: llmTools,
2934
+ })];
2935
+ case 1:
2936
+ knowledge = _e.sent();
2937
+ console.info('!!!! knowledge', knowledge);
2938
+ _e.label = 2;
2939
+ case 2:
2940
+ // =============================================================
2941
+ // Note: 1️⃣ Normalization of the PROMPTBOOK string
2942
+ promptbookString = removeContentComments(promptbookString);
2943
+ promptbookString = promptbookString.replaceAll(/`\{(?<parameterName>[a-z0-9_]+)\}`/gi, '{$<parameterName>}');
2944
+ promptbookString = promptbookString.replaceAll(/`->\s+\{(?<parameterName>[a-z0-9_]+)\}`/gi, '-> {$<parameterName>}');
2945
+ addParam = function (parameterCommand) {
2946
+ var parameterName = parameterCommand.parameterName, parameterDescription = parameterCommand.parameterDescription, isInput = parameterCommand.isInput, isOutput = parameterCommand.isOutput;
2947
+ var existingParameter = promptbookJson.parameters.find(function (parameter) { return parameter.name === parameterName; });
2948
+ if (existingParameter &&
2949
+ existingParameter.description &&
2950
+ existingParameter.description !== parameterDescription &&
2951
+ parameterDescription) {
2952
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim(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 "); }));
2953
+ }
2954
+ if (existingParameter) {
2955
+ if (parameterDescription) {
2956
+ existingParameter.description = parameterDescription;
2957
+ }
2958
+ }
2959
+ else {
2960
+ promptbookJson.parameters.push({
2961
+ name: parameterName,
2962
+ description: parameterDescription || undefined,
2963
+ isInput: isInput,
2964
+ isOutput: isOutput,
2965
+ });
2966
+ }
2967
+ };
2968
+ markdownStructure = markdownToMarkdownStructure(promptbookString);
2969
+ markdownStructureDeepness = countMarkdownStructureDeepness(markdownStructure);
2970
+ if (markdownStructureDeepness !== 2) {
2971
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid markdown structure.\n The markdown must have exactly 2 levels of headings (one top-level section and one section for each template).\n Now it has ".concat(markdownStructureDeepness, " levels of headings.\n ")));
2972
+ }
2973
+ promptbookJson.title = markdownStructure.title;
2974
+ description = markdownStructure.content;
2975
+ // Note: Remove codeblocks
2976
+ description = description.split(/^```.*^```/gms).join('');
2977
+ //Note: Remove lists and return statement
2978
+ description = description.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
2979
+ description = spaceTrim.spaceTrim(description);
2980
+ if (description === '') {
2981
+ description = undefined;
2982
+ }
2983
+ promptbookJson.description = description;
2984
+ defaultModelRequirements = {};
2985
+ listItems = extractAllListItemsFromMarkdown(markdownStructure.content);
2986
+ try {
2987
+ for (listItems_1 = __values(listItems), listItems_1_1 = listItems_1.next(); !listItems_1_1.done; listItems_1_1 = listItems_1.next()) {
2988
+ listItem = listItems_1_1.value;
2989
+ command = parseCommand(listItem);
2990
+ switch (command.type) {
2991
+ case 'PROMPTBOOK_URL':
2992
+ promptbookJson.promptbookUrl = command.promptbookUrl.href;
2993
+ break;
2994
+ case 'PROMPTBOOK_VERSION':
2995
+ promptbookJson.promptbookVersion = command.promptbookVersion;
2996
+ break;
2997
+ case 'MODEL':
2998
+ defaultModelRequirements[command.key] = command.value;
2999
+ break;
3000
+ case 'PARAMETER':
3001
+ addParam(command);
3002
+ break;
3003
+ default:
3004
+ throw new PromptbookSyntaxError("Command ".concat(command.type, " is not allowed in the head of the promptbook ONLY at the prompt template block"));
3005
+ }
3006
+ }
3007
+ }
3008
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3009
+ finally {
3010
+ try {
3011
+ if (listItems_1_1 && !listItems_1_1.done && (_c = listItems_1.return)) _c.call(listItems_1);
3012
+ }
3013
+ finally { if (e_1) throw e_1.error; }
3014
+ }
3015
+ _loop_1 = function (section) {
3016
+ var e_3, _f;
3017
+ // TODO: Parse prompt template description (the content out of the codeblock and lists)
3018
+ var templateModelRequirements = __assign({}, defaultModelRequirements);
3019
+ var listItems_3 = extractAllListItemsFromMarkdown(section.content);
3020
+ var dependentParameterNames = new Set();
3021
+ var executionType = 'PROMPT_TEMPLATE';
3022
+ var jokers = [];
3023
+ var postprocessing = [];
3024
+ var expectAmount = {};
3025
+ var expectFormat = undefined;
3026
+ var isExecutionTypeChanged = false;
3027
+ try {
3028
+ 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()) {
3029
+ var listItem = listItems_2_1.value;
3030
+ var command = parseCommand(listItem);
3031
+ switch (command.type) {
3032
+ case 'JOKER':
3033
+ jokers.push(command.parameterName);
3034
+ dependentParameterNames.add(command.parameterName);
3035
+ break;
3036
+ case 'EXECUTE':
3037
+ if (isExecutionTypeChanged) {
3038
+ throw new PromptbookSyntaxError('Execution type is already defined in the prompt template. It can be defined only once.');
3039
+ }
3040
+ executionType = command.executionType;
3041
+ isExecutionTypeChanged = true;
3042
+ break;
3043
+ case 'MODEL':
3044
+ templateModelRequirements[command.key] = command.value;
3045
+ break;
3046
+ case 'PARAMETER':
3047
+ // Note: This is just for detecting resulitng parameter name
3048
+ addParam(command);
3049
+ break;
3050
+ case 'POSTPROCESS':
3051
+ postprocessing.push(command.functionName);
3052
+ break;
3053
+ case 'EXPECT_AMOUNT':
3054
+ // eslint-disable-next-line no-case-declarations
3055
+ var unit = command.unit.toLowerCase();
3056
+ expectAmount[unit] = expectAmount[unit] || {};
3057
+ if (command.sign === 'MINIMUM' || command.sign === 'EXACTLY') {
3058
+ if (expectAmount[unit].min !== undefined) {
3059
+ throw new PromptbookSyntaxError("Already defined minumum ".concat(expectAmount[unit].min, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
3060
+ }
3061
+ expectAmount[unit].min = command.amount;
3062
+ } /* not else */
3063
+ if (command.sign === 'MAXIMUM' || command.sign === 'EXACTLY') {
3064
+ if (expectAmount[unit].max !== undefined) {
3065
+ throw new PromptbookSyntaxError("Already defined maximum ".concat(expectAmount[unit].max, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
3066
+ }
3067
+ expectAmount[unit].max = command.amount;
3068
+ }
3069
+ break;
3070
+ case 'EXPECT_FORMAT':
3071
+ if (expectFormat !== undefined && command.format !== expectFormat) {
3072
+ throw new PromptbookSyntaxError("Expect format is already defined to \"".concat(expectFormat, "\". Now you try to redefine it by \"").concat(command.format, "\"."));
3073
+ }
3074
+ expectFormat = command.format;
3075
+ break;
3076
+ default:
3077
+ throw new PromptbookSyntaxError("Command ".concat(command.type, " is not allowed in the block of the prompt template ONLY at the head of the promptbook"));
3078
+ }
3079
+ }
3080
+ }
3081
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
3082
+ finally {
3083
+ try {
3084
+ if (listItems_2_1 && !listItems_2_1.done && (_f = listItems_2.return)) _f.call(listItems_2);
3085
+ }
3086
+ finally { if (e_3) throw e_3.error; }
3087
+ }
3088
+ var _g = extractOneBlockFromMarkdown(section.content), language = _g.language, content = _g.content;
3089
+ if (executionType === 'SCRIPT') {
3090
+ if (!language) {
3091
+ throw new PromptbookSyntaxError('You must specify the language of the script in the prompt template');
3092
+ }
3093
+ else if (!SUPPORTED_SCRIPT_LANGUAGES.includes(language)) {
3094
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim(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 "); }));
3095
+ }
3096
+ }
3097
+ var lastLine = section.content.split('\n').pop();
3098
+ var match = /^->\s*\{(?<resultingParamName>[a-z0-9_]+)\}/im.exec(lastLine);
3099
+ if (!match || match.groups === undefined || match.groups.resultingParamName === undefined) {
3100
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Invalid template - each section must end with \"-> {...}\"\n\n Invalid section:\n ".concat(block(
3101
+ // TODO: Show code of invalid sections each time + DRY
3102
+ section.content
3103
+ .split('\n')
3104
+ .map(function (line) { return "> ".concat(line); })
3105
+ .join('\n')), "\n "); }));
3106
+ }
3107
+ var resultingParameterName = match.groups.resultingParamName;
3108
+ // TODO: [1] DRY description
3109
+ var description_1 = section.content;
3110
+ // Note: Remove codeblocks
3111
+ description_1 = description_1.split(/^```.*^```/gms).join('');
3112
+ //Note: Remove lists and return statement
3113
+ description_1 = description_1.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
3114
+ description_1 = spaceTrim.spaceTrim(description_1);
3115
+ if (description_1 === '') {
3116
+ description_1 = undefined;
3117
+ }
3118
+ if (Object.keys(jokers).length === 0) {
3119
+ jokers = undefined;
2033
3120
  }
2034
- }
2035
- }
2036
- catch (e_6_1) { e_6 = { error: e_6_1 }; }
2037
- finally {
3121
+ if (Object.keys(expectAmount).length === 0) {
3122
+ expectAmount = undefined;
3123
+ }
3124
+ if (Object.keys(postprocessing).length === 0) {
3125
+ postprocessing = undefined;
3126
+ }
3127
+ dependentParameterNames = union(dependentParameterNames, extractParametersFromPromptTemplate(__assign(__assign({}, section), { description: description_1, executionType: executionType, content: content })));
3128
+ if (templateModelRequirements.modelVariant === undefined) {
3129
+ templateModelRequirements.modelVariant = 'CHAT';
3130
+ }
3131
+ var template = {
3132
+ name: titleToName(section.title),
3133
+ title: section.title,
3134
+ description: description_1,
3135
+ dependentParameterNames: Array.from(dependentParameterNames),
3136
+ executionType: executionType,
3137
+ jokers: jokers,
3138
+ postprocessing: postprocessing,
3139
+ expectations: expectAmount,
3140
+ expectFormat: expectFormat,
3141
+ modelRequirements: templateModelRequirements,
3142
+ contentLanguage: executionType === 'SCRIPT' ? language : undefined,
3143
+ content: content,
3144
+ resultingParameterName: resultingParameterName,
3145
+ };
3146
+ if (executionType !== 'PROMPT_TEMPLATE') {
3147
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
3148
+ delete template.modelRequirements;
3149
+ }
3150
+ promptbookJson.promptTemplates.push(template);
3151
+ };
2038
3152
  try {
2039
- if (_m && !_m.done && (_f = _l.return)) _f.call(_l);
3153
+ for (_a = __values(markdownStructure.sections), _b = _a.next(); !_b.done; _b = _a.next()) {
3154
+ section = _b.value;
3155
+ _loop_1(section);
3156
+ }
2040
3157
  }
2041
- finally { if (e_6) throw e_6.error; }
2042
- }
2043
- } /* not else */
2044
- if (expectFormat) {
2045
- if (expectFormat === 'JSON') {
2046
- // TODO: @deprecated remove
2047
- commands_1.push("EXPECT JSON");
2048
- }
2049
- } /* not else */
2050
- promptbookString += '\n\n';
2051
- promptbookString += commands_1.map(function (command) { return "- ".concat(command); }).join('\n');
2052
- promptbookString += '\n\n';
2053
- promptbookString += '```' + contentLanguage;
2054
- promptbookString += '\n';
2055
- promptbookString += spaceTrim__default["default"](content);
2056
- // <- TODO: !!! Escape
2057
- // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
2058
- promptbookString += '\n';
2059
- promptbookString += '```';
2060
- promptbookString += '\n\n';
2061
- promptbookString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO: !!! If the parameter here has description, add it and use promptTemplateParameterJsonToString
2062
- }
2063
- }
2064
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2065
- finally {
2066
- try {
2067
- if (promptTemplates_1_1 && !promptTemplates_1_1.done && (_c = promptTemplates_1.return)) _c.call(promptTemplates_1);
2068
- }
2069
- finally { if (e_3) throw e_3.error; }
2070
- }
2071
- return promptbookString;
2072
- }
2073
- /**
2074
- * @private internal util of promptbookJsonToString
2075
- */
2076
- function promptTemplateParameterJsonToString(promptTemplateParameterJson) {
2077
- var name = promptTemplateParameterJson.name, description = promptTemplateParameterJson.description;
2078
- var parameterString = "{".concat(name, "}");
2079
- if (description) {
2080
- parameterString = "".concat(parameterString, " ").concat(description);
2081
- }
2082
- return parameterString;
3158
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
3159
+ finally {
3160
+ try {
3161
+ if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
3162
+ }
3163
+ finally { if (e_2) throw e_2.error; }
3164
+ }
3165
+ // =============================================================
3166
+ return [2 /*return*/, promptbookJson];
3167
+ }
3168
+ });
3169
+ });
2083
3170
  }
2084
3171
  /**
2085
- * TODO: Escape all
2086
- */
2087
-
2088
- /**
2089
- * This error indicates that promptbook not found in the library
3172
+ * TODO: Report here line/column of error
3173
+ * TODO: Use spaceTrim more effectively
3174
+ * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
2090
3175
  */
2091
- var PromptbookNotFoundError = /** @class */ (function (_super) {
2092
- __extends(PromptbookNotFoundError, _super);
2093
- function PromptbookNotFoundError(message) {
2094
- var _this = _super.call(this, message) || this;
2095
- _this.name = 'PromptbookNotFoundError';
2096
- Object.setPrototypeOf(_this, PromptbookNotFoundError.prototype);
2097
- return _this;
2098
- }
2099
- return PromptbookNotFoundError;
2100
- }(Error));
2101
3176
 
2102
3177
  /**
2103
- * This error indicates errors in referencing promptbooks between each other
3178
+ * This error indicates that the promptbook library cannot be propperly loaded
2104
3179
  */
2105
- var PromptbookReferenceError = /** @class */ (function (_super) {
2106
- __extends(PromptbookReferenceError, _super);
2107
- function PromptbookReferenceError(message) {
3180
+ var PromptbookLibraryError = /** @class */ (function (_super) {
3181
+ __extends(PromptbookLibraryError, _super);
3182
+ function PromptbookLibraryError(message) {
2108
3183
  var _this = _super.call(this, message) || this;
2109
- _this.name = 'PromptbookReferenceError';
2110
- Object.setPrototypeOf(_this, PromptbookReferenceError.prototype);
3184
+ _this.name = 'PromptbookLibraryError';
3185
+ Object.setPrototypeOf(_this, PromptbookLibraryError.prototype);
2111
3186
  return _this;
2112
3187
  }
2113
- return PromptbookReferenceError;
3188
+ return PromptbookLibraryError;
2114
3189
  }(Error));
2115
3190
 
2116
3191
  /**
2117
- * Library of promptbooks that groups together promptbooks for an application.
2118
- * This implementation is a very thin wrapper around the Array / Map of promptbooks.
2119
- *
2120
- * @see https://github.com/webgptorg/promptbook#promptbook-library
3192
+ * Detects if the code is running in a browser environment in main thread (Not in a web worker)
2121
3193
  */
2122
- var SimplePromptbookLibrary = /** @class */ (function () {
2123
- /**
2124
- * Constructs a promptbook library from promptbooks
2125
- *
2126
- * @param promptbooks !!!
2127
- *
2128
- * Note: During the construction logic of all promptbooks are validated
2129
- * Note: It is not recommended to use this constructor directly, use `createPromptbookLibraryFromSources` *(or other variant)* instead
2130
- */
2131
- function SimplePromptbookLibrary() {
2132
- var e_1, _a;
2133
- var promptbooks = [];
2134
- for (var _i = 0; _i < arguments.length; _i++) {
2135
- promptbooks[_i] = arguments[_i];
2136
- }
2137
- this.library = new Map();
2138
- try {
2139
- for (var promptbooks_1 = __values(promptbooks), promptbooks_1_1 = promptbooks_1.next(); !promptbooks_1_1.done; promptbooks_1_1 = promptbooks_1.next()) {
2140
- var promptbook = promptbooks_1_1.value;
2141
- if (promptbook.promptbookUrl === undefined) {
2142
- throw new PromptbookReferenceError(spaceTrim.spaceTrim("\n Promptbook with name \"".concat(promptbook.title, "\" does not have defined URL\n\n Note: Promptbooks without URLs are called anonymous promptbooks\n They can be used as standalone promptbooks, but they cannot be referenced by other promptbooks\n And also they cannot be used in the promptbook library\n\n ")));
2143
- }
2144
- validatePromptbookJson(promptbook);
2145
- // Note: [🦄]
2146
- if (this.library.has(promptbook.promptbookUrl) &&
2147
- promptbookJsonToString(promptbook) !==
2148
- promptbookJsonToString(this.library.get(promptbook.promptbookUrl))) {
2149
- throw new PromptbookReferenceError(spaceTrim.spaceTrim("\n Promptbook with URL \"".concat(promptbook.promptbookUrl, "\" is already in the library\n\n Note: Promptbooks with the same URL are not allowed\n Note: Automatically check whether the promptbooks are the same BUT they are DIFFERENT\n\n ")));
2150
- }
2151
- this.library.set(promptbook.promptbookUrl, promptbook);
2152
- }
2153
- }
2154
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2155
- finally {
2156
- try {
2157
- if (promptbooks_1_1 && !promptbooks_1_1.done && (_a = promptbooks_1.return)) _a.call(promptbooks_1);
2158
- }
2159
- finally { if (e_1) throw e_1.error; }
2160
- }
2161
- }
2162
- /**
2163
- * Gets all promptbooks in the library
2164
- */
2165
- SimplePromptbookLibrary.prototype.listPromptbooks = function () {
2166
- return Array.from(this.library.keys());
2167
- };
2168
- /**
2169
- * Gets promptbook by its URL
2170
- *
2171
- * Note: This is not a direct fetching from the URL, but a lookup in the library
2172
- */
2173
- SimplePromptbookLibrary.prototype.getPromptbookByUrl = function (url) {
2174
- var _this = this;
2175
- var promptbook = this.library.get(url);
2176
- if (!promptbook) {
2177
- if (this.listPromptbooks().length === 0) {
2178
- throw new PromptbookNotFoundError(spaceTrim.spaceTrim("\n Promptbook with url \"".concat(url, "\" not found\n\n No promptbooks available\n ")));
2179
- }
2180
- throw new PromptbookNotFoundError(spaceTrim.spaceTrim(function (block) { return "\n Promptbook with url \"".concat(url, "\" not found\n\n Available promptbooks:\n ").concat(block(_this.listPromptbooks()
2181
- .map(function (promptbookUrl) { return "- ".concat(promptbookUrl); })
2182
- .join('\n')), "\n\n "); }));
2183
- }
2184
- return promptbook;
2185
- };
2186
- /**
2187
- * Checks whether given prompt was defined in any promptbook in the library
2188
- */
2189
- SimplePromptbookLibrary.prototype.isResponsibleForPrompt = function (prompt) {
2190
- return true;
2191
- };
2192
- return SimplePromptbookLibrary;
2193
- }());
2194
-
3194
+ new Function("\n try {\n return this === window;\n } catch (e) {\n return false;\n }\n");
2195
3195
  /**
2196
- * Creates PromptbookLibrary from array of PromptbookJson or PromptbookString
2197
- *
2198
- * Note: You can combine `PromptbookString` (`.ptbk.md`) with `PromptbookJson` BUT it is not recommended
2199
- * Note: During the construction syntax and logic of all sources are validated
2200
- *
2201
- * @param promptbookSources
2202
- * @returns PromptbookLibrary
3196
+ * Detects if the code is running in a Node.js environment
2203
3197
  */
2204
- function createPromptbookLibraryFromSources() {
2205
- var promptbookSources = [];
2206
- for (var _i = 0; _i < arguments.length; _i++) {
2207
- promptbookSources[_i] = arguments[_i];
2208
- }
2209
- return __awaiter(this, void 0, void 0, function () {
2210
- var promptbooks, promptbookSources_1, promptbookSources_1_1, source, promptbook, e_1_1;
2211
- var e_1, _a;
2212
- return __generator(this, function (_b) {
2213
- switch (_b.label) {
2214
- case 0:
2215
- promptbooks = new Array();
2216
- _b.label = 1;
2217
- case 1:
2218
- _b.trys.push([1, 8, 9, 10]);
2219
- promptbookSources_1 = __values(promptbookSources), promptbookSources_1_1 = promptbookSources_1.next();
2220
- _b.label = 2;
2221
- case 2:
2222
- if (!!promptbookSources_1_1.done) return [3 /*break*/, 7];
2223
- source = promptbookSources_1_1.value;
2224
- promptbook = void 0;
2225
- if (!(typeof source === 'string')) return [3 /*break*/, 4];
2226
- return [4 /*yield*/, promptbookStringToJson(source)];
2227
- case 3:
2228
- // Note: When directly creating from string, no need to validate the source
2229
- // The validation is performed always before execution
2230
- promptbook = _b.sent();
2231
- return [3 /*break*/, 5];
2232
- case 4:
2233
- promptbook = source;
2234
- _b.label = 5;
2235
- case 5:
2236
- promptbooks.push(promptbook);
2237
- _b.label = 6;
2238
- case 6:
2239
- promptbookSources_1_1 = promptbookSources_1.next();
2240
- return [3 /*break*/, 2];
2241
- case 7: return [3 /*break*/, 10];
2242
- case 8:
2243
- e_1_1 = _b.sent();
2244
- e_1 = { error: e_1_1 };
2245
- return [3 /*break*/, 10];
2246
- case 9:
2247
- try {
2248
- if (promptbookSources_1_1 && !promptbookSources_1_1.done && (_a = promptbookSources_1.return)) _a.call(promptbookSources_1);
2249
- }
2250
- finally { if (e_1) throw e_1.error; }
2251
- return [7 /*endfinally*/];
2252
- case 10: return [2 /*return*/, new (SimplePromptbookLibrary.bind.apply(SimplePromptbookLibrary, __spreadArray([void 0], __read(promptbooks), false)))()];
2253
- }
2254
- });
2255
- });
2256
- }
3198
+ var isRunningInNode = new Function("\n try {\n return this === global;\n } catch (e) {\n return false;\n }\n");
2257
3199
  /**
2258
- * TODO: !!!! [🧠] Library precompilation and do not mix markdown and json promptbooks
3200
+ * Detects if the code is running in a web worker
2259
3201
  */
3202
+ new Function("\n try {\n if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {\n return true;\n } else {\n return false;\n }\n } catch (e) {\n return false;\n }\n");
2260
3203
 
2261
3204
  /**
2262
3205
  * Constructs Promptbook from async sources
@@ -2265,19 +3208,19 @@
2265
3208
  * - Factory function that returns Promise of array of PromptbookJson or PromptbookString
2266
3209
  *
2267
3210
  * Note: This is useful as internal tool for other constructor functions like
2268
- * `createPromptbookLibraryFromUrl` or `createPromptbookLibraryFromDirectory`
3211
+ * `createLibraryFromUrl` or `createLibraryFromDirectory`
2269
3212
  * Consider using those functions instead of this one
2270
3213
  *
2271
3214
  * Note: The function does NOT return promise it returns the library directly which waits for the sources to be resolved
2272
3215
  * when error occurs in given promise or factory function, it is thrown during `listPromptbooks` or `getPromptbookByUrl` call
2273
3216
  *
2274
- * Note: Consider using `createPromptbookLibraryFromDirectory` or `createPromptbookLibraryFromUrl`
3217
+ * Note: Consider using `createLibraryFromDirectory` or `createLibraryFromUrl`
2275
3218
  *
2276
3219
  * @param promptbookSourcesPromiseOrFactory
2277
3220
  * @returns PromptbookLibrary
2278
3221
  * @deprecated Do not use, it will became internal tool for other constructor functions
2279
3222
  */
2280
- function createPromptbookLibraryFromPromise(promptbookSourcesPromiseOrFactory) {
3223
+ function createLibraryFromPromise(promptbookSourcesPromiseOrFactory) {
2281
3224
  var library;
2282
3225
  function forSources() {
2283
3226
  return __awaiter(this, void 0, void 0, function () {
@@ -2292,9 +3235,7 @@
2292
3235
  return [4 /*yield*/, promptbookSourcesPromiseOrFactory];
2293
3236
  case 1:
2294
3237
  promptbookSources = _a.sent();
2295
- return [4 /*yield*/, createPromptbookLibraryFromSources.apply(void 0, __spreadArray([], __read(promptbookSources), false))];
2296
- case 2:
2297
- library = _a.sent();
3238
+ library = createLibraryFromJson.apply(void 0, __spreadArray([], __read(promptbookSources), false));
2298
3239
  return [2 /*return*/];
2299
3240
  }
2300
3241
  });
@@ -2342,9 +3283,6 @@
2342
3283
  isResponsibleForPrompt: isResponsibleForPrompt,
2343
3284
  };
2344
3285
  }
2345
- /**
2346
- * TODO: !!!! [🧠] Library precompilation and do not mix markdown and json promptbooks
2347
- */
2348
3286
 
2349
3287
  /**
2350
3288
  * Constructs Promptbook from given directory
@@ -2355,32 +3293,42 @@
2355
3293
  * @param options - Misc options for the library
2356
3294
  * @returns PromptbookLibrary
2357
3295
  */
2358
- function createPromptbookLibraryFromDirectory(path, options) {
3296
+ function createLibraryFromDirectory(path$1, options) {
2359
3297
  return __awaiter(this, void 0, void 0, function () {
2360
- var _a, _b, isRecursive, _c, isVerbose, _d, isLazyLoaded, _e, isCrashOnError, library;
3298
+ var makedLibraryFilePath, makedLibraryFileExists, _a, _b, isRecursive, _c, isVerbose, _d, isLazyLoaded, _e, isCrashOnError, library;
2361
3299
  var _this = this;
2362
3300
  return __generator(this, function (_f) {
2363
3301
  switch (_f.label) {
2364
3302
  case 0:
2365
3303
  if (!isRunningInNode()) {
2366
- throw new Error('Function `createPromptbookLibraryFromDirectory` can only be run in Node.js environment because it reads the file system.');
3304
+ throw new Error('Function `createLibraryFromDirectory` can only be run in Node.js environment because it reads the file system.');
3305
+ }
3306
+ makedLibraryFilePath = path.join(path$1, "".concat(PROMPTBOOK_MAKED_BASE_FILENAME, ".json"));
3307
+ return [4 /*yield*/, promises.access(makedLibraryFilePath, promises.constants.R_OK)
3308
+ .then(function () { return true; })
3309
+ .catch(function () { return false; })];
3310
+ case 1:
3311
+ makedLibraryFileExists = _f.sent();
3312
+ if (!makedLibraryFileExists) {
3313
+ console.info(colors__default["default"].yellow("Tip: Prebuild your promptbook library (file with supposed prebuild ".concat(makedLibraryFilePath, " not found) with CLI util \"promptbook make\" to speed up the library creation.")));
3314
+ }
3315
+ else {
3316
+ colors__default["default"].green("Using your prebuild promptbook library ".concat(makedLibraryFilePath));
3317
+ // TODO: !!!!! Implement;
2367
3318
  }
2368
3319
  _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;
2369
- library = createPromptbookLibraryFromPromise(function () { return __awaiter(_this, void 0, void 0, function () {
3320
+ library = createLibraryFromPromise(function () { return __awaiter(_this, void 0, void 0, function () {
2370
3321
  var fileNames, promptbooks, _loop_1, fileNames_1, fileNames_1_1, fileName, e_1_1;
2371
3322
  var e_1, _a;
2372
3323
  return __generator(this, function (_b) {
2373
3324
  switch (_b.label) {
2374
3325
  case 0:
2375
3326
  if (isVerbose) {
2376
- console.info("Creating promptbook library from path ".concat(path));
3327
+ console.info("Creating promptbook library from path ".concat(path$1.split('\\').join('/')));
2377
3328
  }
2378
- return [4 /*yield*/, listAllFiles(path, isRecursive)];
3329
+ return [4 /*yield*/, listAllFiles(path$1, isRecursive)];
2379
3330
  case 1:
2380
3331
  fileNames = _b.sent();
2381
- if (isVerbose) {
2382
- console.info('createPromptbookLibraryFromDirectory', { path: path, isRecursive: isRecursive, fileNames: fileNames });
2383
- }
2384
3332
  promptbooks = [];
2385
3333
  _loop_1 = function (fileName) {
2386
3334
  var promptbook, promptbookString, _c, _d, error_1, wrappedErrorMessage;
@@ -2400,7 +3348,7 @@
2400
3348
  case 3:
2401
3349
  if (!fileName.endsWith('.ptbk.json')) return [3 /*break*/, 5];
2402
3350
  if (isVerbose) {
2403
- console.info("Loading ".concat(fileName));
3351
+ console.info("Loading ".concat(fileName.split('\\').join('/')));
2404
3352
  }
2405
3353
  _d = (_c = JSON).parse;
2406
3354
  return [4 /*yield*/, promises.readFile(fileName, 'utf8')];
@@ -2410,7 +3358,7 @@
2410
3358
  return [3 /*break*/, 6];
2411
3359
  case 5:
2412
3360
  if (isVerbose) {
2413
- console.info("Skipping file ".concat(fileName));
3361
+ console.info("Skipping file ".concat(fileName.split('\\').join('/')));
2414
3362
  }
2415
3363
  _e.label = 6;
2416
3364
  case 6:
@@ -2418,17 +3366,17 @@
2418
3366
  if (promptbook !== null) {
2419
3367
  if (!promptbook.promptbookUrl) {
2420
3368
  if (isVerbose) {
2421
- console.info("Not loading ".concat(fileName, " - missing URL"));
3369
+ console.info("Not loading ".concat(fileName.split('\\').join('/'), " - missing URL"));
2422
3370
  }
2423
3371
  }
2424
3372
  else {
2425
3373
  if (isVerbose) {
2426
- console.info("Loading ".concat(fileName));
3374
+ console.info("Loading ".concat(fileName.split('\\').join('/')));
2427
3375
  }
2428
3376
  if (!isCrashOnError) {
2429
3377
  // Note: Validate promptbook to check if it is logically correct to not crash on invalid promptbooks
2430
3378
  // But be handled in current try-catch block
2431
- validatePromptbookJson(promptbook);
3379
+ validatePromptbook(promptbook);
2432
3380
  }
2433
3381
  // Note: [🦄] Promptbook with same url uniqueness will be checked automatically in SimplePromptbookLibrary
2434
3382
  promptbooks.push(promptbook);
@@ -2480,12 +3428,12 @@
2480
3428
  }
2481
3429
  });
2482
3430
  }); });
2483
- if (!(isLazyLoaded === false)) return [3 /*break*/, 2];
3431
+ if (!(isLazyLoaded === false)) return [3 /*break*/, 3];
2484
3432
  return [4 /*yield*/, library.listPromptbooks()];
2485
- case 1:
3433
+ case 2:
2486
3434
  _f.sent();
2487
- _f.label = 2;
2488
- case 2: return [2 /*return*/, library];
3435
+ _f.label = 3;
3436
+ case 3: return [2 /*return*/, library];
2489
3437
  }
2490
3438
  });
2491
3439
  });
@@ -2496,7 +3444,7 @@
2496
3444
  * @param path
2497
3445
  * @param isRecursive
2498
3446
  * @returns List of all files in the directory
2499
- * @private internal function for `createPromptbookLibraryFromDirectory`
3447
+ * @private internal function for `createLibraryFromDirectory`
2500
3448
  */
2501
3449
  function listAllFiles(path$1, isRecursive) {
2502
3450
  return __awaiter(this, void 0, void 0, function () {
@@ -2554,7 +3502,7 @@
2554
3502
  */
2555
3503
 
2556
3504
  exports.PROMPTBOOK_VERSION = PROMPTBOOK_VERSION;
2557
- exports.createPromptbookLibraryFromDirectory = createPromptbookLibraryFromDirectory;
3505
+ exports.createLibraryFromDirectory = createLibraryFromDirectory;
2558
3506
 
2559
3507
  Object.defineProperty(exports, '__esModule', { value: true });
2560
3508