@promptbook/core 0.48.0 → 0.48.1-0

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 (23) hide show
  1. package/esm/index.es.js +226 -20
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/typings/_packages/utils.index.d.ts +2 -1
  4. package/esm/typings/conversion/prettify/renderPromptbookMermaid.d.ts +15 -2
  5. package/esm/typings/conversion/promptbookJsonToString.d.ts +1 -0
  6. package/esm/typings/conversion/utils/renameParameter.d.ts +25 -0
  7. package/esm/typings/conversion/validation/_importPromptbook.d.ts +1 -0
  8. package/esm/typings/conversion/validation/validatePromptbookJson.d.ts +3 -2
  9. package/esm/typings/utils/markdown/prettifyMarkdown.d.ts +2 -2
  10. package/package.json +2 -1
  11. package/umd/index.umd.js +265 -59
  12. package/umd/index.umd.js.map +1 -1
  13. package/umd/typings/_packages/utils.index.d.ts +2 -1
  14. package/umd/typings/conversion/prettify/renderPromptbookMermaid.d.ts +15 -2
  15. package/umd/typings/conversion/promptbookJsonToString.d.ts +1 -0
  16. package/umd/typings/conversion/promptbookStringToJson.test.d.ts +1 -0
  17. package/umd/typings/conversion/utils/renameParameter.d.ts +25 -0
  18. package/umd/typings/conversion/utils/renameParameter.test.d.ts +1 -0
  19. package/umd/typings/conversion/validation/_importPromptbook.d.ts +1 -0
  20. package/umd/typings/conversion/validation/validatePromptbookJson.d.ts +3 -2
  21. package/umd/typings/utils/markdown/prettifyMarkdown.d.ts +2 -2
  22. /package/esm/typings/conversion/{validation/promptbookStringToJson.test.d.ts → promptbookStringToJson.test.d.ts} +0 -0
  23. /package/{umd/typings/conversion/validation/promptbookStringToJson.test.d.ts → esm/typings/conversion/utils/renameParameter.test.d.ts} +0 -0
package/umd/index.umd.js CHANGED
@@ -1,12 +1,12 @@
1
1
  (function (global, factory) {
2
2
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('moment')) :
3
3
  typeof define === 'function' && define.amd ? define(['exports', 'spacetrim', 'prettier', 'prettier/parser-html', 'moment'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-core"] = {}, global.spaceTrim));
5
- })(this, (function (exports, spaceTrim) { 'use strict';
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-core"] = {}, global.spacetrim, global.prettier, global.parserHtml));
5
+ })(this, (function (exports, 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 spaceTrim__default = /*#__PURE__*/_interopDefaultLegacy(spaceTrim);
9
+ var parserHtml__default = /*#__PURE__*/_interopDefaultLegacy(parserHtml);
10
10
 
11
11
  /*! *****************************************************************************
12
12
  Copyright (c) Microsoft Corporation.
@@ -212,7 +212,7 @@
212
212
  var UnexpectedError = /** @class */ (function (_super) {
213
213
  __extends(UnexpectedError, _super);
214
214
  function UnexpectedError(message) {
215
- var _this = _super.call(this, spaceTrim.spaceTrim(function (block) { return "\n ".concat(block(message), "\n\n Note: This error should not happen.\n It's probbably a bug in the promptbook library\n\n Please report issue:\n https://github.com/webgptorg/promptbook/issues\n\n Or contact us on me@pavolhejny.com\n\n "); })) || this;
215
+ var _this = _super.call(this, spacetrim.spaceTrim(function (block) { return "\n ".concat(block(message), "\n\n Note: This error should not happen.\n It's probbably a bug in the promptbook library\n\n Please report issue:\n https://github.com/webgptorg/promptbook/issues\n\n Or contact us on me@pavolhejny.com\n\n "); })) || this;
216
216
  _this.name = 'UnexpectedError';
217
217
  Object.setPrototypeOf(_this, UnexpectedError.prototype);
218
218
  return _this;
@@ -265,7 +265,7 @@
265
265
  }
266
266
  if (parent_1.parent === null /* <- Note: We are in root */) {
267
267
  // [🌻]
268
- throw new Error(spaceTrim.spaceTrim("\n The file has an invalid structure.\n The markdown file must have exactly one top-level section.\n "));
268
+ throw new Error(spacetrim.spaceTrim("\n The file has an invalid structure.\n The markdown file must have exactly one top-level section.\n "));
269
269
  }
270
270
  parent_1 = parent_1.parent;
271
271
  }
@@ -299,7 +299,7 @@
299
299
  return {
300
300
  level: level,
301
301
  title: title,
302
- content: spaceTrim.spaceTrim(contentLines.join('\n')),
302
+ content: spacetrim.spaceTrim(contentLines.join('\n')),
303
303
  sections: sections.map(parsingMarkdownStructureToMarkdownStructure),
304
304
  };
305
305
  }
@@ -439,13 +439,13 @@
439
439
  * @returns {string} The input string with all comments removed.
440
440
  */
441
441
  function removeContentComments(content) {
442
- return spaceTrim.spaceTrim(content.replace(/<!--(.*?)-->/gs, ''));
442
+ return spacetrim.spaceTrim(content.replace(/<!--(.*?)-->/gs, ''));
443
443
  }
444
444
 
445
445
  /**
446
446
  * The version of the Promptbook library
447
447
  */
448
- var PROMPTBOOK_VERSION = '0.48.0-1';
448
+ var PROMPTBOOK_VERSION = '0.48.0';
449
449
 
450
450
  /**
451
451
  * Parses the given script and returns the list of all used variables that are not defined in the script
@@ -490,11 +490,43 @@
490
490
  if (!(error instanceof Error)) {
491
491
  throw error;
492
492
  }
493
- 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 "); }));
493
+ 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 "); }));
494
494
  }
495
495
  return variables;
496
496
  }
497
497
 
498
+ /**
499
+ * Prettify the html code
500
+ *
501
+ * @param content raw html code
502
+ * @returns formatted html code
503
+ */
504
+ function prettifyMarkdown(content) {
505
+ try {
506
+ return prettier.format(content, {
507
+ parser: 'markdown',
508
+ plugins: [parserHtml__default["default"]],
509
+ // TODO: DRY - make some import or auto-copy of .prettierrc
510
+ endOfLine: 'lf',
511
+ tabWidth: 4,
512
+ singleQuote: true,
513
+ trailingComma: 'all',
514
+ arrowParens: 'always',
515
+ printWidth: 120,
516
+ htmlWhitespaceSensitivity: 'ignore',
517
+ jsxBracketSameLine: false,
518
+ bracketSpacing: true,
519
+ });
520
+ }
521
+ catch (error) {
522
+ console.error('There was an error with prettifying the markdown, using the original as the fallback', {
523
+ error: error,
524
+ html: content,
525
+ });
526
+ return content;
527
+ }
528
+ }
529
+
498
530
  /**
499
531
  * Removes emojis from a string and fix whitespaces
500
532
  *
@@ -587,6 +619,20 @@
587
619
  * TODO: Maybe use sth. like safe-eval in fraction/calculation case @see https://www.npmjs.com/package/safe-eval
588
620
  */
589
621
 
622
+ /**
623
+ * This error indicates that the promptbook object has valid syntax but contains logical errors (like circular dependencies)
624
+ */
625
+ var PromptbookLogicError = /** @class */ (function (_super) {
626
+ __extends(PromptbookLogicError, _super);
627
+ function PromptbookLogicError(message) {
628
+ var _this = _super.call(this, message) || this;
629
+ _this.name = 'PromptbookLogicError';
630
+ Object.setPrototypeOf(_this, PromptbookLogicError.prototype);
631
+ return _this;
632
+ }
633
+ return PromptbookLogicError;
634
+ }(Error));
635
+
590
636
  /**
591
637
  * This error indicates errors during the execution of the promptbook
592
638
  */
@@ -1270,15 +1316,15 @@
1270
1316
  type.startsWith('PROMPTBOOKURL') ||
1271
1317
  type.startsWith('HTTPS')) {
1272
1318
  if (!(listItemParts.length === 2 || (listItemParts.length === 1 && type.startsWith('HTTPS')))) {
1273
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n ")));
1319
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n ")));
1274
1320
  }
1275
1321
  var promptbookUrlString = listItemParts.pop();
1276
1322
  var promptbookUrl = new URL(promptbookUrlString);
1277
1323
  if (promptbookUrl.protocol !== 'https:') {
1278
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n Protocol must be HTTPS\n ")));
1324
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n Protocol must be HTTPS\n ")));
1279
1325
  }
1280
1326
  if (promptbookUrl.hash !== '') {
1281
- 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 ")));
1327
+ 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 ")));
1282
1328
  }
1283
1329
  return {
1284
1330
  type: 'PROMPTBOOK_URL',
@@ -1287,7 +1333,7 @@
1287
1333
  }
1288
1334
  else if (type.startsWith('PROMPTBOOK_VERSION') || type.startsWith('PTBK_VERSION')) {
1289
1335
  if (listItemParts.length !== 2) {
1290
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_VERSION command:\n\n - ".concat(listItem, "\n ")));
1336
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim("\n Invalid PROMPTBOOK_VERSION command:\n\n - ".concat(listItem, "\n ")));
1291
1337
  }
1292
1338
  var promptbookVersion = listItemParts.pop();
1293
1339
  // TODO: Validate version
@@ -1302,7 +1348,7 @@
1302
1348
  type.startsWith('SIMPLE_TEMPLATE')) {
1303
1349
  var executionTypes = ExecutionTypes.filter(function (executionType) { return type.includes(executionType); });
1304
1350
  if (executionTypes.length !== 1) {
1305
- 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 "); }));
1351
+ 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 "); }));
1306
1352
  }
1307
1353
  return {
1308
1354
  type: 'EXECUTE',
@@ -1327,7 +1373,7 @@
1327
1373
  };
1328
1374
  }
1329
1375
  else {
1330
- 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 "); }));
1376
+ 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 "); }));
1331
1377
  }
1332
1378
  }
1333
1379
  if (type.startsWith('MODEL_NAME')) {
@@ -1338,7 +1384,7 @@
1338
1384
  };
1339
1385
  }
1340
1386
  else {
1341
- 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 "); }));
1387
+ 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 "); }));
1342
1388
  }
1343
1389
  }
1344
1390
  else if (type.startsWith('PARAM') ||
@@ -1348,12 +1394,12 @@
1348
1394
  listItem.startsWith('> {') /* <- Note: This is a bit hack to parse return parameters defined at the end of each section */) {
1349
1395
  var parametersMatch = listItem.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
1350
1396
  if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
1351
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
1397
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
1352
1398
  }
1353
1399
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1354
1400
  var _b = parametersMatch.groups, parameterName = _b.parameterName, parameterDescription = _b.parameterDescription;
1355
1401
  if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
1356
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Parameter {".concat(parameterName, "} can not contain another parameter in description:\n\n - ").concat(listItem, "\n ")));
1402
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim("\n Parameter {".concat(parameterName, "} can not contain another parameter in description:\n\n - ").concat(listItem, "\n ")));
1357
1403
  }
1358
1404
  var isInput = type.startsWith('INPUT');
1359
1405
  var isOutput = type.startsWith('OUTPUT');
@@ -1371,11 +1417,11 @@
1371
1417
  }
1372
1418
  else if (type.startsWith('JOKER')) {
1373
1419
  if (listItemParts.length !== 2) {
1374
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid JOKER command:\n\n - ".concat(listItem, "\n ")));
1420
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim("\n Invalid JOKER command:\n\n - ".concat(listItem, "\n ")));
1375
1421
  }
1376
1422
  var parametersMatch = (listItemParts.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
1377
1423
  if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
1378
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
1424
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
1379
1425
  }
1380
1426
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1381
1427
  var parameterName = parametersMatch.groups.parameterName;
@@ -1386,7 +1432,7 @@
1386
1432
  }
1387
1433
  else if (type.startsWith('POSTPROCESS') || type.startsWith('POST_PROCESS')) {
1388
1434
  if (listItemParts.length !== 2) {
1389
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid POSTPROCESSING command:\n\n - ".concat(listItem, "\n ")));
1435
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim("\n Invalid POSTPROCESSING command:\n\n - ".concat(listItem, "\n ")));
1390
1436
  }
1391
1437
  var functionName = listItemParts.pop();
1392
1438
  return {
@@ -1466,7 +1512,7 @@
1466
1512
  if (!(error instanceof Error)) {
1467
1513
  throw error;
1468
1514
  }
1469
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid EXPECT command; ".concat(error.message, ":\n\n - ").concat(listItem, "\n ")));
1515
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim("\n Invalid EXPECT command; ".concat(error.message, ":\n\n - ").concat(listItem, "\n ")));
1470
1516
  }
1471
1517
  /*
1472
1518
  } else if (type.startsWith('__________________')) {
@@ -1474,7 +1520,7 @@
1474
1520
  */
1475
1521
  }
1476
1522
  else {
1477
- 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 ")));
1523
+ 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 ")));
1478
1524
  }
1479
1525
  }
1480
1526
 
@@ -1510,7 +1556,7 @@
1510
1556
  existingParameter.description &&
1511
1557
  existingParameter.description !== parameterDescription &&
1512
1558
  parameterDescription) {
1513
- 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 "); }));
1559
+ 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 "); }));
1514
1560
  }
1515
1561
  if (existingParameter) {
1516
1562
  if (parameterDescription) {
@@ -1531,7 +1577,7 @@
1531
1577
  var markdownStructure = markdownToMarkdownStructure(promptbookString);
1532
1578
  var markdownStructureDeepness = countMarkdownStructureDeepness(markdownStructure);
1533
1579
  if (markdownStructureDeepness !== 2) {
1534
- 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 ")));
1580
+ 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 ")));
1535
1581
  }
1536
1582
  promptbookJson.title = markdownStructure.title;
1537
1583
  // TODO: [1] DRY description
@@ -1540,7 +1586,7 @@
1540
1586
  description = description.split(/^```.*^```/gms).join('');
1541
1587
  //Note: Remove lists and return statement
1542
1588
  description = description.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
1543
- description = spaceTrim.spaceTrim(description);
1589
+ description = spacetrim.spaceTrim(description);
1544
1590
  if (description === '') {
1545
1591
  description = undefined;
1546
1592
  }
@@ -1655,13 +1701,13 @@
1655
1701
  throw new PromptbookSyntaxError('You must specify the language of the script in the prompt template');
1656
1702
  }
1657
1703
  else if (!SUPPORTED_SCRIPT_LANGUAGES.includes(language)) {
1658
- 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 "); }));
1704
+ 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 "); }));
1659
1705
  }
1660
1706
  }
1661
1707
  var lastLine = section.content.split('\n').pop();
1662
1708
  var match = /^->\s*\{(?<resultingParamName>[a-z0-9_]+)\}/im.exec(lastLine);
1663
1709
  if (!match || match.groups === undefined || match.groups.resultingParamName === undefined) {
1664
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Invalid template - each section must end with \"-> {...}\"\n\n Invalid section:\n ".concat(block(
1710
+ throw new PromptbookSyntaxError(spacetrim.spaceTrim(function (block) { return "\n Invalid template - each section must end with \"-> {...}\"\n\n Invalid section:\n ".concat(block(
1665
1711
  // TODO: Show code of invalid sections each time + DRY
1666
1712
  section.content
1667
1713
  .split('\n')
@@ -1675,7 +1721,7 @@
1675
1721
  description_1 = description_1.split(/^```.*^```/gms).join('');
1676
1722
  //Note: Remove lists and return statement
1677
1723
  description_1 = description_1.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
1678
- description_1 = spaceTrim.spaceTrim(description_1);
1724
+ description_1 = spacetrim.spaceTrim(description_1);
1679
1725
  if (description_1 === '') {
1680
1726
  description_1 = undefined;
1681
1727
  }
@@ -1756,28 +1802,186 @@
1756
1802
  */
1757
1803
 
1758
1804
  function promptbookJsonToString(promptbookJson) {
1759
- return spaceTrim__default["default"](function (block) { return "\n\n # ".concat(block(promptbookJson.title), "\n\n "); });
1805
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d, e_5, _e;
1806
+ var title = promptbookJson.title, promptbookUrl = promptbookJson.promptbookUrl, promptbookVersion = promptbookJson.promptbookVersion, description = promptbookJson.description, parameters = promptbookJson.parameters, promptTemplates = promptbookJson.promptTemplates;
1807
+ var promptbookString = "# ".concat(title);
1808
+ if (description) {
1809
+ promptbookString += '\n\n';
1810
+ promptbookString += description;
1811
+ }
1812
+ // TODO:> const commands: Array<Command>
1813
+ var commands = [];
1814
+ if (promptbookUrl) {
1815
+ commands.push("PROMPTBOOK URL ".concat(promptbookUrl));
1816
+ }
1817
+ commands.push("PROMPTBOOK VERSION ".concat(promptbookVersion));
1818
+ promptbookString = prettifyMarkdown(promptbookString);
1819
+ try {
1820
+ for (var parameters_1 = __values(parameters), parameters_1_1 = parameters_1.next(); !parameters_1_1.done; parameters_1_1 = parameters_1.next()) {
1821
+ var parameter = parameters_1_1.value;
1822
+ var isInput = parameter.isInput, isOutput = parameter.isOutput;
1823
+ if (isInput) {
1824
+ commands.push("INPUT PARAMETER ".concat(promptTemplateParameterJsonToString(parameter)));
1825
+ }
1826
+ else if (isOutput) {
1827
+ commands.push("OUTPUT PARAMETER ".concat(promptTemplateParameterJsonToString(parameter)));
1828
+ }
1829
+ }
1830
+ }
1831
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1832
+ finally {
1833
+ try {
1834
+ if (parameters_1_1 && !parameters_1_1.done && (_a = parameters_1.return)) _a.call(parameters_1);
1835
+ }
1836
+ finally { if (e_1) throw e_1.error; }
1837
+ }
1838
+ promptbookString += '\n\n';
1839
+ promptbookString += commands.map(function (command) { return "- ".concat(command); }).join('\n');
1840
+ try {
1841
+ for (var promptTemplates_1 = __values(promptTemplates), promptTemplates_1_1 = promptTemplates_1.next(); !promptTemplates_1_1.done; promptTemplates_1_1 = promptTemplates_1.next()) {
1842
+ var promptTemplate = promptTemplates_1_1.value;
1843
+ var
1844
+ /* Note: Not using:> name, */
1845
+ title_1 = promptTemplate.title, description_1 = promptTemplate.description,
1846
+ /* Note: dependentParameterNames, */
1847
+ jokers = promptTemplate.jokers, executionType = promptTemplate.executionType, content = promptTemplate.content, postprocessing = promptTemplate.postprocessing, expectations = promptTemplate.expectations, expectFormat = promptTemplate.expectFormat, resultingParameterName = promptTemplate.resultingParameterName;
1848
+ promptbookString += '\n\n';
1849
+ promptbookString += "## ".concat(title_1);
1850
+ if (description_1) {
1851
+ promptbookString += '\n\n';
1852
+ promptbookString += description_1;
1853
+ }
1854
+ // TODO:> const commands: Array<Command>
1855
+ var commands_1 = [];
1856
+ var contentLanguage = 'markdown';
1857
+ if (executionType === 'PROMPT_TEMPLATE') {
1858
+ var modelRequirements = promptTemplate.modelRequirements;
1859
+ var modelName = modelRequirements.modelName, modelVariant = modelRequirements.modelVariant;
1860
+ commands_1.push("EXECUTE PROMPT TEMPLATE");
1861
+ if (modelVariant) {
1862
+ commands_1.push("MODEL VARIANT ".concat(capitalize(modelVariant)));
1863
+ }
1864
+ if (modelName) {
1865
+ commands_1.push("MODEL NAME `".concat(modelName, "`"));
1866
+ }
1867
+ }
1868
+ else if (executionType === 'SIMPLE_TEMPLATE') {
1869
+ commands_1.push("SIMPLE TEMPLATE");
1870
+ // Note: Nothing special here
1871
+ }
1872
+ else if (executionType === 'SCRIPT') {
1873
+ commands_1.push("EXECUTE SCRIPT");
1874
+ if (promptTemplate.contentLanguage) {
1875
+ contentLanguage = promptTemplate.contentLanguage;
1876
+ }
1877
+ else {
1878
+ contentLanguage = '';
1879
+ }
1880
+ }
1881
+ else if (executionType === 'PROMPT_DIALOG') {
1882
+ commands_1.push("PROMPT DIALOG");
1883
+ // Note: Nothing special here
1884
+ }
1885
+ if (jokers) {
1886
+ try {
1887
+ for (var jokers_1 = (e_3 = void 0, __values(jokers)), jokers_1_1 = jokers_1.next(); !jokers_1_1.done; jokers_1_1 = jokers_1.next()) {
1888
+ var joker = jokers_1_1.value;
1889
+ commands_1.push("JOKER {".concat(joker, "}"));
1890
+ }
1891
+ }
1892
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
1893
+ finally {
1894
+ try {
1895
+ if (jokers_1_1 && !jokers_1_1.done && (_c = jokers_1.return)) _c.call(jokers_1);
1896
+ }
1897
+ finally { if (e_3) throw e_3.error; }
1898
+ }
1899
+ } /* not else */
1900
+ if (postprocessing) {
1901
+ try {
1902
+ for (var postprocessing_1 = (e_4 = void 0, __values(postprocessing)), postprocessing_1_1 = postprocessing_1.next(); !postprocessing_1_1.done; postprocessing_1_1 = postprocessing_1.next()) {
1903
+ var postprocessingFunctionName = postprocessing_1_1.value;
1904
+ commands_1.push("POSTPROCESSING `".concat(postprocessingFunctionName, "`"));
1905
+ }
1906
+ }
1907
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
1908
+ finally {
1909
+ try {
1910
+ if (postprocessing_1_1 && !postprocessing_1_1.done && (_d = postprocessing_1.return)) _d.call(postprocessing_1);
1911
+ }
1912
+ finally { if (e_4) throw e_4.error; }
1913
+ }
1914
+ } /* not else */
1915
+ if (expectations) {
1916
+ try {
1917
+ for (var _f = (e_5 = void 0, __values(Object.entries(expectations))), _g = _f.next(); !_g.done; _g = _f.next()) {
1918
+ var _h = __read(_g.value, 2), unit = _h[0], _j = _h[1], min = _j.min, max = _j.max;
1919
+ if (min === max) {
1920
+ commands_1.push("EXPECT EXACTLY ".concat(min, " ").concat(capitalize(unit + (min > 1 ? 's' : ''))));
1921
+ }
1922
+ else {
1923
+ if (min !== undefined) {
1924
+ commands_1.push("EXPECT MIN ".concat(min, " ").concat(capitalize(unit + (min > 1 ? 's' : ''))));
1925
+ } /* not else */
1926
+ if (max !== undefined) {
1927
+ commands_1.push("EXPECT MAX ".concat(max, " ").concat(capitalize(unit + (max > 1 ? 's' : ''))));
1928
+ }
1929
+ }
1930
+ }
1931
+ }
1932
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
1933
+ finally {
1934
+ try {
1935
+ if (_g && !_g.done && (_e = _f.return)) _e.call(_f);
1936
+ }
1937
+ finally { if (e_5) throw e_5.error; }
1938
+ }
1939
+ } /* not else */
1940
+ if (expectFormat) {
1941
+ if (expectFormat === 'JSON') {
1942
+ // TODO: @deprecated remove
1943
+ commands_1.push("EXPECT JSON");
1944
+ }
1945
+ } /* not else */
1946
+ promptbookString += '\n\n';
1947
+ promptbookString += commands_1.map(function (command) { return "- ".concat(command); }).join('\n');
1948
+ promptbookString += '\n\n';
1949
+ promptbookString += '```' + contentLanguage;
1950
+ promptbookString += '\n';
1951
+ promptbookString += content; // <- TODO: !!! Escape
1952
+ promptbookString += '\n';
1953
+ promptbookString += '```';
1954
+ promptbookString += '\n\n';
1955
+ promptbookString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO: !!! If the parameter here has description, add it and use promptTemplateParameterJsonToString
1956
+ }
1957
+ }
1958
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
1959
+ finally {
1960
+ try {
1961
+ if (promptTemplates_1_1 && !promptTemplates_1_1.done && (_b = promptTemplates_1.return)) _b.call(promptTemplates_1);
1962
+ }
1963
+ finally { if (e_2) throw e_2.error; }
1964
+ }
1965
+ return promptbookString;
1966
+ }
1967
+ /**
1968
+ * @private internal util of promptbookJsonToString
1969
+ */
1970
+ function promptTemplateParameterJsonToString(promptTemplateParameterJson) {
1971
+ var name = promptTemplateParameterJson.name, description = promptTemplateParameterJson.description;
1972
+ var parameterString = "{".concat(name, "}");
1973
+ if (description) {
1974
+ parameterString = "".concat(parameterString, " ").concat(description);
1975
+ }
1976
+ return parameterString;
1760
1977
  }
1761
1978
  /**
1762
1979
  * TODO: !!!!! Implement
1763
1980
  * TODO: !!!!! Annotate and warn
1764
1981
  * TODO: !!!!! Test + test together with promptbookStringToJson
1982
+ * TODO: Escape all
1765
1983
  */
1766
1984
 
1767
- /**
1768
- * This error indicates that the promptbook object has valid syntax but contains logical errors (like circular dependencies)
1769
- */
1770
- var PromptbookLogicError = /** @class */ (function (_super) {
1771
- __extends(PromptbookLogicError, _super);
1772
- function PromptbookLogicError(message) {
1773
- var _this = _super.call(this, message) || this;
1774
- _this.name = 'PromptbookLogicError';
1775
- Object.setPrototypeOf(_this, PromptbookLogicError.prototype);
1776
- return _this;
1777
- }
1778
- return PromptbookLogicError;
1779
- }(Error));
1780
-
1781
1985
  /**
1782
1986
  * Tests if given string is valid URL.
1783
1987
  *
@@ -1804,7 +2008,7 @@
1804
2008
  }
1805
2009
 
1806
2010
  /**
1807
- * Validates PromptbookJson if it is logically valid.
2011
+ * Validates PromptbookJson if it is logically valid
1808
2012
  *
1809
2013
  * It checks:
1810
2014
  * - if it has correct parameters dependency
@@ -1814,6 +2018,7 @@
1814
2018
  * - if it is meaningful
1815
2019
  *
1816
2020
  * @param promptbook valid or invalid PromptbookJson
2021
+ * @returns the same promptbook if it is logically valid
1817
2022
  * @throws {PromptbookLogicError} on logical error in the promptbook
1818
2023
  */
1819
2024
  function validatePromptbookJson(promptbook) {
@@ -1832,12 +2037,12 @@
1832
2037
  if (!parameter.isInput &&
1833
2038
  !parameter.isOutput &&
1834
2039
  !promptbook.promptTemplates.some(function (template) { return template.dependentParameterNames.includes(parameter.name); })) {
1835
- 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 ")));
2040
+ 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 ")));
1836
2041
  }
1837
2042
  // Note: Testing that parameter is either input or result of some template
1838
2043
  if (!parameter.isInput &&
1839
2044
  !promptbook.promptTemplates.some(function (template) { return template.resultingParameterName === parameter.name; })) {
1840
- 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 ")));
2045
+ 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 ")));
1841
2046
  }
1842
2047
  };
1843
2048
  try {
@@ -1872,7 +2077,7 @@
1872
2077
  if (template.executionType === 'PROMPT_TEMPLATE' &&
1873
2078
  (template.modelRequirements.modelVariant === undefined ||
1874
2079
  template.modelRequirements.modelName === undefined)) {
1875
- throw new PromptbookLogicError(spaceTrim.spaceTrim("\n\n You must specify MODEL VARIANT and MODEL NAME in the prompt template \"".concat(template.title, "\"\n\n For example:\n - MODEL VARIANT Chat\n - MODEL NAME `gpt-4-1106-preview`\n\n ")));
2080
+ throw new PromptbookLogicError(spacetrim.spaceTrim("\n\n You must specify MODEL VARIANT and MODEL NAME in the prompt template \"".concat(template.title, "\"\n\n For example:\n - MODEL VARIANT Chat\n - MODEL NAME `gpt-4-1106-preview`\n\n ")));
1876
2081
  }
1877
2082
  if (template.jokers && template.jokers.length > 0) {
1878
2083
  if (!template.expectFormat &&
@@ -1947,7 +2152,7 @@
1947
2152
  return template.dependentParameterNames.every(function (name) { return resovedParameters.includes(name); });
1948
2153
  });
1949
2154
  if (currentlyResovedTemplates.length === 0) {
1950
- 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
2155
+ 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
1951
2156
  .map(function (_a) {
1952
2157
  var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
1953
2158
  return "- {".concat(resultingParameterName, "} depends on ").concat(dependentParameterNames
@@ -1965,6 +2170,7 @@
1965
2170
  while (unresovedTemplates.length > 0) {
1966
2171
  _loop_2();
1967
2172
  }
2173
+ return promptbook;
1968
2174
  }
1969
2175
  /**
1970
2176
  * TODO: [🧠] Work with promptbookVersion
@@ -2120,7 +2326,7 @@
2120
2326
  throw errors[0];
2121
2327
  }
2122
2328
  else {
2123
- 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 "); }));
2329
+ 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 "); }));
2124
2330
  }
2125
2331
  }
2126
2332
  });
@@ -2204,7 +2410,7 @@
2204
2410
  throw scriptExecutionErrors[0];
2205
2411
  }
2206
2412
  else {
2207
- throw new PromptbookExecutionError(spaceTrim.spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptExecutionErrors.length, " times\n\n ").concat(block(scriptExecutionErrors
2413
+ throw new PromptbookExecutionError(spacetrim.spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptExecutionErrors.length, " times\n\n ").concat(block(scriptExecutionErrors
2208
2414
  .map(function (error) { return '- ' + error.message; })
2209
2415
  .join('\n\n')), "\n "); }));
2210
2416
  }
@@ -2344,7 +2550,7 @@
2344
2550
  return [7 /*endfinally*/];
2345
2551
  case 47:
2346
2552
  if (expectError !== null && attempt === maxAttempts - 1) {
2347
- 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 "); }));
2553
+ 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 "); }));
2348
2554
  }
2349
2555
  _o.label = 48;
2350
2556
  case 48:
@@ -2413,7 +2619,7 @@
2413
2619
  return template.dependentParameterNames.every(function (name) { return resovedParameters_1.includes(name); });
2414
2620
  });
2415
2621
  if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
2416
- throw new UnexpectedError(spaceTrim.spaceTrim("\n Can not resolve some parameters\n\n Note: This should be catched during validatePromptbookJson\n "));
2622
+ throw new UnexpectedError(spacetrim.spaceTrim("\n Can not resolve some parameters\n\n Note: This should be catched during validatePromptbookJson\n "));
2417
2623
  case 1:
2418
2624
  if (!!currentTemplate) return [3 /*break*/, 3];
2419
2625
  /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
@@ -2513,7 +2719,7 @@
2513
2719
  case 1:
2514
2720
  answer = _a.sent();
2515
2721
  if (this.options.isVerbose) {
2516
- console.info(spaceTrim.spaceTrim(function (block) { return "\n \uD83D\uDCD6 ".concat(block(options.promptTitle), "\n \uD83D\uDC64 ").concat(block(answer), "\n "); }));
2722
+ console.info(spacetrim.spaceTrim(function (block) { return "\n \uD83D\uDCD6 ".concat(block(options.promptTitle), "\n \uD83D\uDC64 ").concat(block(answer), "\n "); }));
2517
2723
  }
2518
2724
  return [2 /*return*/, answer];
2519
2725
  }
@@ -2540,9 +2746,9 @@
2540
2746
  return __awaiter(this, void 0, void 0, function () {
2541
2747
  var answer;
2542
2748
  return __generator(this, function (_a) {
2543
- answer = window.prompt(spaceTrim.spaceTrim(function (block) { return "\n ".concat(block(options.promptTitle), "\n\n ").concat(block(options.promptMessage), "\n "); }));
2749
+ answer = window.prompt(spacetrim.spaceTrim(function (block) { return "\n ".concat(block(options.promptTitle), "\n\n ").concat(block(options.promptMessage), "\n "); }));
2544
2750
  if (this.options.isVerbose) {
2545
- console.info(spaceTrim.spaceTrim(function (block) { return "\n \uD83D\uDCD6 ".concat(block(options.promptTitle), "\n \uD83D\uDC64 ").concat(block(answer || '🚫 User cancelled prompt'), "\n "); }));
2751
+ console.info(spacetrim.spaceTrim(function (block) { return "\n \uD83D\uDCD6 ".concat(block(options.promptTitle), "\n \uD83D\uDC64 ").concat(block(answer || '🚫 User cancelled prompt'), "\n "); }));
2546
2752
  }
2547
2753
  if (answer === null) {
2548
2754
  throw new PromptbookExecutionError('User cancelled prompt');
@@ -2608,7 +2814,7 @@
2608
2814
  for (var promptbooks_1 = __values(promptbooks), promptbooks_1_1 = promptbooks_1.next(); !promptbooks_1_1.done; promptbooks_1_1 = promptbooks_1.next()) {
2609
2815
  var promptbook = promptbooks_1_1.value;
2610
2816
  if (promptbook.promptbookUrl === undefined) {
2611
- 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 ")));
2817
+ 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 ")));
2612
2818
  }
2613
2819
  validatePromptbookJson(promptbook);
2614
2820
  this.library.set(promptbook.promptbookUrl, promptbook);
@@ -2637,7 +2843,7 @@
2637
2843
  var _this = this;
2638
2844
  var promptbook = this.library.get(url);
2639
2845
  if (!promptbook) {
2640
- 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()
2846
+ 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()
2641
2847
  .map(function (promptbookUrl) { return "- ".concat(promptbookUrl); })
2642
2848
  .join('\n')), "\n\n "); }));
2643
2849
  }
@@ -2815,7 +3021,7 @@
2815
3021
  case 0:
2816
3022
  if (!!predicate(url)) return [3 /*break*/, 2];
2817
3023
  _a = PromptbookNotFoundError.bind;
2818
- return [4 /*yield*/, spaceTrim.spaceTrim(function (block) { return __awaiter(_this, void 0, void 0, function () {
3024
+ return [4 /*yield*/, spacetrim.spaceTrim(function (block) { return __awaiter(_this, void 0, void 0, function () {
2819
3025
  var _a, _b, _c, _d, _e, _f;
2820
3026
  return __generator(this, function (_g) {
2821
3027
  switch (_g.label) {