@promptbook/core 0.67.3 → 0.67.5

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.
@@ -1,4 +1,6 @@
1
1
  import { PROMPTBOOK_VERSION } from '../version';
2
+ import { extractBlock } from '../postprocessing/utils/extractBlock';
3
+ import { extractJsonBlock } from '../postprocessing/utils/extractJsonBlock';
2
4
  import type { string_markdown } from '../types/typeAliases';
3
5
  import type { string_markdown_section } from '../types/typeAliases';
4
6
  import type { string_markdown_section_content } from '../types/typeAliases';
@@ -17,6 +19,8 @@ import { removeContentComments } from '../utils/markdown/removeContentComments';
17
19
  import { removeMarkdownFormatting } from '../utils/markdown/removeMarkdownFormatting';
18
20
  import { splitMarkdownIntoSections } from '../utils/markdown/splitMarkdownIntoSections';
19
21
  export { PROMPTBOOK_VERSION };
22
+ export { extractBlock };
23
+ export { extractJsonBlock };
20
24
  export type { string_markdown };
21
25
  export type { string_markdown_section };
22
26
  export type { string_markdown_section_content };
@@ -8,7 +8,6 @@ import { deserializeError } from '../errors/utils/deserializeError';
8
8
  import { serializeError } from '../errors/utils/serializeError';
9
9
  import { forEachAsync } from '../execution/utils/forEachAsync';
10
10
  import { isValidJsonString } from '../formats/json/utils/isValidJsonString';
11
- import { extractBlock } from '../postprocessing/utils/extractBlock';
12
11
  import { $currentDate } from '../utils/$currentDate';
13
12
  import { $isRunningInBrowser } from '../utils/environment/$isRunningInBrowser';
14
13
  import { $isRunningInNode } from '../utils/environment/$isRunningInNode';
@@ -80,7 +79,6 @@ export { deserializeError };
80
79
  export { serializeError };
81
80
  export { forEachAsync };
82
81
  export { isValidJsonString };
83
- export { extractBlock };
84
82
  export { $currentDate };
85
83
  export { $isRunningInBrowser };
86
84
  export { $isRunningInNode };
@@ -62,6 +62,7 @@ export type FormatDefinition<TValue extends TPartialValue, TPartialValue extends
62
62
  extractValues(value: string, schema?: TSchema): Array<string>;
63
63
  };
64
64
  /**
65
+ * TODO: [♏] Add some prepare hook to modify prompt according to the format
65
66
  * TODO: [🍓]`name` and `aliases` should be UPPERCASE only and interpreted as case-insensitive (via normalization)
66
67
  * TODO: [🍓][👨‍⚖️] Compute TPartialValue dynamically - PartialString<TValue>
67
68
  * TODO: [🍓][🧠] Should execution tools be aviable to heal, canBeValid and isValid?
@@ -2,16 +2,15 @@ import type { string_markdown } from '../../types/typeAliases';
2
2
  /**
3
3
  * Extracts code block from markdown.
4
4
  *
5
- * Note: If there are multiple or no code blocks the function throws an error
5
+ * - When there are multiple or no code blocks the function throws a `ParsingError`
6
6
  *
7
- * Note: There are 3 simmilar function:
7
+ * Note: There are multiple simmilar function:
8
8
  * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
9
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
9
10
  * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
10
11
  * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
11
12
  *
12
- * @public exported from `@promptbook/utils`
13
+ * @public exported from `@promptbook/markdown-utils`
14
+ * @throws {ParsingError} if there is not exactly one code block in the markdown
13
15
  */
14
16
  export declare function extractBlock(markdown: string_markdown): string;
15
- /**
16
- * TODO: [🧠][🌻] Maybe export through `@promptbook/markdown-utils` not `@promptbook/utils`
17
- */
@@ -0,0 +1,25 @@
1
+ import type { string_json } from '../../types/typeAliases';
2
+ import type { string_markdown } from '../../types/typeAliases';
3
+ import type { really_unknown } from '../../utils/organization/really_unknown';
4
+ /**
5
+ * Extracts extracts exactly one valid JSON code block
6
+ *
7
+ * - When given string is a valid JSON as it is, it just returns it
8
+ * - When there is no JSON code block the function throws a `ParsingError`
9
+ * - When there are multiple JSON code blocks the function throws a `ParsingError`
10
+ *
11
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
12
+ * Note: There are multiple simmilar function:
13
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
14
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
15
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
16
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
17
+ *
18
+ * @public exported from `@promptbook/markdown-utils`
19
+ * @throws {ParsingError} if there is no valid JSON block in the markdown
20
+ */
21
+ export declare function extractJsonBlock(markdown: string_markdown): string_json<really_unknown>;
22
+ /**
23
+ * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
24
+ * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
25
+ */
@@ -19,13 +19,15 @@ export type CodeBlock = {
19
19
  /**
20
20
  * Extracts all code blocks from markdown.
21
21
  *
22
- * Note: There are 3 simmilar function:
22
+ * Note: There are multiple simmilar function:
23
23
  * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
24
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
24
25
  * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
25
26
  * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
26
27
  *
27
28
  * @param markdown any valid markdown
28
29
  * @returns code blocks with language and content
30
+ * @throws {ParsingError} if block is not closed properly
29
31
  * @public exported from `@promptbook/markdown-utils`
30
32
  */
31
33
  export declare function extractAllBlocksFromMarkdown(markdown: string_markdown): Array<CodeBlock>;
@@ -3,16 +3,18 @@ import type { CodeBlock } from './extractAllBlocksFromMarkdown';
3
3
  /**
4
4
  * Extracts exactly ONE code block from markdown.
5
5
  *
6
- * Note: If there are multiple or no code blocks the function throws an error
6
+ * - When there are multiple or no code blocks the function throws a `ParsingError`
7
7
  *
8
- * Note: There are 3 simmilar function:
8
+ * Note: There are multiple simmilar function:
9
9
  * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
10
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
10
11
  * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
11
12
  * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
12
13
  *
13
14
  * @param markdown any valid markdown
14
15
  * @returns code block with language and content
15
16
  * @public exported from `@promptbook/markdown-utils`
17
+ * @throws {ParsingError} if there is not exactly one code block in the markdown
16
18
  */
17
19
  export declare function extractOneBlockFromMarkdown(markdown: string_markdown): CodeBlock;
18
20
  /***
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promptbook/core",
3
- "version": "0.67.3",
3
+ "version": "0.67.5",
4
4
  "description": "Supercharge your use of large language models",
5
5
  "private": false,
6
6
  "sideEffects": false,
package/umd/index.umd.js CHANGED
@@ -16,7 +16,7 @@
16
16
  /**
17
17
  * The version of the Promptbook library
18
18
  */
19
- var PROMPTBOOK_VERSION = '0.67.2';
19
+ var PROMPTBOOK_VERSION = '0.67.4';
20
20
  // TODO: !!!! List here all the versions and annotate + put into script
21
21
 
22
22
  /*! *****************************************************************************
@@ -1786,7 +1786,7 @@
1786
1786
  });
1787
1787
  }
1788
1788
 
1789
- var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.67.2",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",modelRequirements:{modelVariant:"CHAT"},content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",dependentParameterNames:["knowledgeContent"],resultingParameterName:"knowledgePieces"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",promptbookVersion:"0.67.2",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",modelRequirements:{modelVariant:"CHAT"},content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",dependentParameterNames:["knowledgePieceContent"],resultingParameterName:"keywords"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",promptbookVersion:"0.67.2",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",modelRequirements:{modelVariant:"CHAT"},content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"],resultingParameterName:"title"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",promptbookVersion:"0.67.2",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",modelRequirements:{modelVariant:"CHAT"},content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",expectFormat:"JSON",dependentParameterNames:["availableModelNames","personaDescription"],resultingParameterName:"modelRequirements"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
1789
+ var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.67.4",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",modelRequirements:{modelVariant:"CHAT"},content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",dependentParameterNames:["knowledgeContent"],resultingParameterName:"knowledgePieces"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-from-markdown.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.ptbk.md",promptbookVersion:"0.67.4",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",modelRequirements:{modelVariant:"CHAT"},content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",dependentParameterNames:["knowledgePieceContent"],resultingParameterName:"keywords"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-keywords.ptbk.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.ptbk.md",promptbookVersion:"0.67.4",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"knowledge",title:"Knowledge",modelRequirements:{modelVariant:"CHAT"},content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Title should be concise and clear\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"],resultingParameterName:"title"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-knowledge-title.ptbk.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.ptbk.md",promptbookVersion:"0.67.4",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],promptTemplates:[{blockType:"PROMPT_TEMPLATE",name:"make-model-requirements",title:"Make modelRequirements",modelRequirements:{modelVariant:"CHAT"},content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Sample\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",expectFormat:"JSON",dependentParameterNames:["availableModelNames","personaDescription"],resultingParameterName:"modelRequirements"}],knowledgeSources:[],knowledgePieces:[],personas:[],preparations:[],sourceFile:"./promptbook-collection/prepare-persona.ptbk.md"}];
1790
1790
 
1791
1791
  var defaultDiacriticsRemovalMap = [
1792
1792
  {
@@ -2755,6 +2755,122 @@
2755
2755
  * TODO: [👷‍♂️] @@@ Manual about construction of llmTools
2756
2756
  */
2757
2757
 
2758
+ /**
2759
+ * Extracts all code blocks from markdown.
2760
+ *
2761
+ * Note: There are multiple simmilar function:
2762
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2763
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
2764
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2765
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2766
+ *
2767
+ * @param markdown any valid markdown
2768
+ * @returns code blocks with language and content
2769
+ * @throws {ParsingError} if block is not closed properly
2770
+ * @public exported from `@promptbook/markdown-utils`
2771
+ */
2772
+ function extractAllBlocksFromMarkdown(markdown) {
2773
+ var e_1, _a;
2774
+ var codeBlocks = [];
2775
+ var lines = markdown.split('\n');
2776
+ // Note: [0] Ensure that the last block notated by gt > will be closed
2777
+ lines.push('');
2778
+ var currentCodeBlock = null;
2779
+ try {
2780
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2781
+ var line = lines_1_1.value;
2782
+ if (line.startsWith('> ') || line === '>') {
2783
+ if (currentCodeBlock === null) {
2784
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2785
+ } /* not else */
2786
+ if (currentCodeBlock.blockNotation === '>') {
2787
+ if (currentCodeBlock.content !== '') {
2788
+ currentCodeBlock.content += '\n';
2789
+ }
2790
+ currentCodeBlock.content += line.slice(2);
2791
+ }
2792
+ }
2793
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2794
+ codeBlocks.push(currentCodeBlock);
2795
+ currentCodeBlock = null;
2796
+ }
2797
+ /* not else */
2798
+ if (line.startsWith('```')) {
2799
+ var language = line.slice(3).trim() || null;
2800
+ if (currentCodeBlock === null) {
2801
+ currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2802
+ }
2803
+ else {
2804
+ if (language !== null) {
2805
+ throw new ParsingError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2806
+ }
2807
+ codeBlocks.push(currentCodeBlock);
2808
+ currentCodeBlock = null;
2809
+ }
2810
+ }
2811
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2812
+ if (currentCodeBlock.content !== '') {
2813
+ currentCodeBlock.content += '\n';
2814
+ }
2815
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2816
+ }
2817
+ }
2818
+ }
2819
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2820
+ finally {
2821
+ try {
2822
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2823
+ }
2824
+ finally { if (e_1) throw e_1.error; }
2825
+ }
2826
+ if (currentCodeBlock !== null) {
2827
+ throw new ParsingError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2828
+ }
2829
+ return codeBlocks;
2830
+ }
2831
+ /**
2832
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2833
+ */
2834
+
2835
+ /**
2836
+ * Extracts extracts exactly one valid JSON code block
2837
+ *
2838
+ * - When given string is a valid JSON as it is, it just returns it
2839
+ * - When there is no JSON code block the function throws a `ParsingError`
2840
+ * - When there are multiple JSON code blocks the function throws a `ParsingError`
2841
+ *
2842
+ * Note: It is not important if marked as ```json BUT if it is VALID JSON
2843
+ * Note: There are multiple simmilar function:
2844
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2845
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
2846
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2847
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2848
+ *
2849
+ * @public exported from `@promptbook/markdown-utils`
2850
+ * @throws {ParsingError} if there is no valid JSON block in the markdown
2851
+ */
2852
+ function extractJsonBlock(markdown) {
2853
+ if (isValidJsonString(markdown)) {
2854
+ return markdown;
2855
+ }
2856
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2857
+ var jsonBlocks = codeBlocks.filter(function (_a) {
2858
+ var content = _a.content;
2859
+ return isValidJsonString(content);
2860
+ });
2861
+ if (jsonBlocks.length === 0) {
2862
+ throw new Error('There is no valid JSON block in the markdown');
2863
+ }
2864
+ if (jsonBlocks.length > 1) {
2865
+ throw new Error('There are multiple JSON code blocks in the markdown');
2866
+ }
2867
+ return jsonBlocks[0].content;
2868
+ }
2869
+ /**
2870
+ * TODO: Add some auto-healing logic + extract YAML, JSON5, TOML, etc.
2871
+ * TODO: [🏢] Make this logic part of `JsonFormatDefinition` or `isValidJsonString`
2872
+ */
2873
+
2758
2874
  /**
2759
2875
  * Determine if the pipeline is fully prepared
2760
2876
  *
@@ -2806,6 +2922,27 @@
2806
2922
  return [input];
2807
2923
  }
2808
2924
 
2925
+ /**
2926
+ * Just says that the variable is not used but should be kept
2927
+ * No side effects.
2928
+ *
2929
+ * Note: It can be usefull for:
2930
+ *
2931
+ * 1) Suppressing eager optimization of unused imports
2932
+ * 2) Suppressing eslint errors of unused variables in the tests
2933
+ * 3) Keeping the type of the variable for type testing
2934
+ *
2935
+ * @param value any values
2936
+ * @returns void
2937
+ * @private within the repository
2938
+ */
2939
+ function keepUnused() {
2940
+ var valuesToKeep = [];
2941
+ for (var _i = 0; _i < arguments.length; _i++) {
2942
+ valuesToKeep[_i] = arguments[_i];
2943
+ }
2944
+ }
2945
+
2809
2946
  /**
2810
2947
  * Just marks a place of place where should be something implemented
2811
2948
  * No side effects.
@@ -3268,7 +3405,11 @@
3268
3405
  usedParameterNames = extractParameterNamesFromPromptTemplate(currentTemplate);
3269
3406
  dependentParameterNames = new Set(currentTemplate.dependentParameterNames);
3270
3407
  if (union(difference(usedParameterNames, dependentParameterNames), difference(dependentParameterNames, usedParameterNames)).size !== 0) {
3271
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Dependent parameters are not consistent used parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Dependent parameters:\n ").concat(Array.from(dependentParameterNames).join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames).join(', '), "\n\n "); }));
3408
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Dependent parameters are not consistent with used parameters:\n\n ".concat(block(pipelineIdentification), "\n\n Dependent parameters:\n ").concat(Array.from(dependentParameterNames)
3409
+ .map(function (name) { return "{".concat(name, "}"); })
3410
+ .join(', '), "\n\n Used parameters:\n ").concat(Array.from(usedParameterNames)
3411
+ .map(function (name) { return "{".concat(name, "}"); })
3412
+ .join(', '), "\n\n "); }));
3272
3413
  }
3273
3414
  _b = (_a = Object).freeze;
3274
3415
  _c = [{}];
@@ -3563,9 +3704,20 @@
3563
3704
  if (currentTemplate.expectFormat) {
3564
3705
  if (currentTemplate.expectFormat === 'JSON') {
3565
3706
  if (!isValidJsonString(resultString || '')) {
3566
- throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(pipelineIdentification), "\n "); }));
3707
+ // TODO: [🏢] Do more universally via `FormatDefinition`
3708
+ try {
3709
+ resultString = extractJsonBlock(resultString || '');
3710
+ }
3711
+ catch (error) {
3712
+ keepUnused(error);
3713
+ throw new ExpectError(spaceTrim.spaceTrim(function (block) { return "\n Expected valid JSON string\n\n ".concat(block(
3714
+ /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ ''), "\n "); }));
3715
+ }
3567
3716
  }
3568
3717
  }
3718
+ else {
3719
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Unknown expectFormat \"".concat(currentTemplate.expectFormat, "\"\n\n ").concat(block(pipelineIdentification), "\n "); }));
3720
+ }
3569
3721
  }
3570
3722
  // TODO: [💝] Unite object for expecting amount and format
3571
3723
  if (currentTemplate.expectations) {
@@ -3596,7 +3748,18 @@
3596
3748
  return [7 /*endfinally*/];
3597
3749
  case 46:
3598
3750
  if (expectError !== null && attempt === maxAttempts - 1) {
3599
- throw new PipelineExecutionError(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 "); }));
3751
+ throw new PipelineExecutionError(spaceTrim.spaceTrim(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ").concat(block(pipelineIdentification), "\n\n ---\n The Prompt:\n ").concat(block(prompt.content
3752
+ .split('\n')
3753
+ .map(function (line) { return "> ".concat(line); })
3754
+ .join('\n')), "\n\n Last error ").concat((expectError === null || expectError === void 0 ? void 0 : expectError.name) || '', ":\n ").concat(block(((expectError === null || expectError === void 0 ? void 0 : expectError.message) || '')
3755
+ .split('\n')
3756
+ .map(function (line) { return "> ".concat(line); })
3757
+ .join('\n')), "\n\n Last result:\n ").concat(block(resultString === null
3758
+ ? 'null'
3759
+ : resultString
3760
+ .split('\n')
3761
+ .map(function (line) { return "> ".concat(line); })
3762
+ .join('\n')), "\n ---\n "); }));
3600
3763
  }
3601
3764
  return [2 /*return*/];
3602
3765
  }
@@ -5690,94 +5853,21 @@
5690
5853
  return listItems;
5691
5854
  }
5692
5855
 
5693
- /**
5694
- * Extracts all code blocks from markdown.
5695
- *
5696
- * Note: There are 3 simmilar function:
5697
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
5698
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
5699
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
5700
- *
5701
- * @param markdown any valid markdown
5702
- * @returns code blocks with language and content
5703
- * @public exported from `@promptbook/markdown-utils`
5704
- */
5705
- function extractAllBlocksFromMarkdown(markdown) {
5706
- var e_1, _a;
5707
- var codeBlocks = [];
5708
- var lines = markdown.split('\n');
5709
- // Note: [0] Ensure that the last block notated by gt > will be closed
5710
- lines.push('');
5711
- var currentCodeBlock = null;
5712
- try {
5713
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
5714
- var line = lines_1_1.value;
5715
- if (line.startsWith('> ') || line === '>') {
5716
- if (currentCodeBlock === null) {
5717
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
5718
- } /* not else */
5719
- if (currentCodeBlock.blockNotation === '>') {
5720
- if (currentCodeBlock.content !== '') {
5721
- currentCodeBlock.content += '\n';
5722
- }
5723
- currentCodeBlock.content += line.slice(2);
5724
- }
5725
- }
5726
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
5727
- codeBlocks.push(currentCodeBlock);
5728
- currentCodeBlock = null;
5729
- }
5730
- /* not else */
5731
- if (line.startsWith('```')) {
5732
- var language = line.slice(3).trim() || null;
5733
- if (currentCodeBlock === null) {
5734
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
5735
- }
5736
- else {
5737
- if (language !== null) {
5738
- throw new ParsingError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
5739
- }
5740
- codeBlocks.push(currentCodeBlock);
5741
- currentCodeBlock = null;
5742
- }
5743
- }
5744
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
5745
- if (currentCodeBlock.content !== '') {
5746
- currentCodeBlock.content += '\n';
5747
- }
5748
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
5749
- }
5750
- }
5751
- }
5752
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
5753
- finally {
5754
- try {
5755
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
5756
- }
5757
- finally { if (e_1) throw e_1.error; }
5758
- }
5759
- if (currentCodeBlock !== null) {
5760
- throw new ParsingError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
5761
- }
5762
- return codeBlocks;
5763
- }
5764
- /**
5765
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
5766
- */
5767
-
5768
5856
  /**
5769
5857
  * Extracts exactly ONE code block from markdown.
5770
5858
  *
5771
- * Note: If there are multiple or no code blocks the function throws an error
5859
+ * - When there are multiple or no code blocks the function throws a `ParsingError`
5772
5860
  *
5773
- * Note: There are 3 simmilar function:
5861
+ * Note: There are multiple simmilar function:
5774
5862
  * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
5863
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
5775
5864
  * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
5776
5865
  * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
5777
5866
  *
5778
5867
  * @param markdown any valid markdown
5779
5868
  * @returns code block with language and content
5780
5869
  * @public exported from `@promptbook/markdown-utils`
5870
+ * @throws {ParsingError} if there is not exactly one code block in the markdown
5781
5871
  */
5782
5872
  function extractOneBlockFromMarkdown(markdown) {
5783
5873
  var codeBlocks = extractAllBlocksFromMarkdown(markdown);
@@ -6407,7 +6497,7 @@
6407
6497
  var placeForSection = removeContentComments(content).match(/^##.*$/im);
6408
6498
  if (!placeForSection) {
6409
6499
  throw new ParsingError(
6410
- // <- [🧠] Maybe something better than `ParsingError`
6500
+ // <- [🧠] Maybe something better tha `ParsingError`
6411
6501
  "No place where to put the section <!--".concat(sectionName, "-->"));
6412
6502
  // <- [🚞]
6413
6503
  }