@promptbook/remote-server 0.98.0-5 โ†’ 0.98.0-8

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.
package/esm/index.es.js CHANGED
@@ -33,7 +33,7 @@ const BOOK_LANGUAGE_VERSION = '1.0.0';
33
33
  * @generated
34
34
  * @see https://github.com/webgptorg/promptbook
35
35
  */
36
- const PROMPTBOOK_ENGINE_VERSION = '0.98.0-5';
36
+ const PROMPTBOOK_ENGINE_VERSION = '0.98.0-8';
37
37
  /**
38
38
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
39
39
  * Note: [๐Ÿ’ž] Ignore a discrepancy between file name and entity name
@@ -173,7 +173,7 @@ const DEFAULT_MAX_PARALLEL_COUNT = 5; // <- TODO: [๐Ÿคนโ€โ™‚๏ธ]
173
173
  *
174
174
  * @public exported from `@promptbook/core`
175
175
  */
176
- const DEFAULT_MAX_EXECUTION_ATTEMPTS = 3; // <- TODO: [๐Ÿคนโ€โ™‚๏ธ]
176
+ const DEFAULT_MAX_EXECUTION_ATTEMPTS = 7; // <- TODO: [๐Ÿคนโ€โ™‚๏ธ]
177
177
  // <- TODO: [๐Ÿ•] Make also `BOOKS_DIRNAME_ALTERNATIVES`
178
178
  // TODO: Just `.promptbook` in config, hardcode subfolders like `download-cache` or `execution-cache`
179
179
  /**
@@ -1891,7 +1891,7 @@ function jsonParse(value) {
1891
1891
  throw new Error(spaceTrim((block) => `
1892
1892
  ${block(error.message)}
1893
1893
 
1894
- The JSON text:
1894
+ The expected JSON text:
1895
1895
  ${block(value)}
1896
1896
  `));
1897
1897
  }
@@ -4813,6 +4813,94 @@ function mapAvailableToExpectedParameters(options) {
4813
4813
  return mappedParameters;
4814
4814
  }
4815
4815
 
4816
+ /**
4817
+ * Just says that the variable is not used but should be kept
4818
+ * No side effects.
4819
+ *
4820
+ * Note: It can be useful for:
4821
+ *
4822
+ * 1) Suppressing eager optimization of unused imports
4823
+ * 2) Suppressing eslint errors of unused variables in the tests
4824
+ * 3) Keeping the type of the variable for type testing
4825
+ *
4826
+ * @param value any values
4827
+ * @returns void
4828
+ * @private within the repository
4829
+ */
4830
+ function keepUnused(...valuesToKeep) {
4831
+ }
4832
+
4833
+ /**
4834
+ * Replaces parameters in template with values from parameters object
4835
+ *
4836
+ * Note: This function is not places strings into string,
4837
+ * It's more complex and can handle this operation specifically for LLM models
4838
+ *
4839
+ * @param template the template with parameters in {curly} braces
4840
+ * @param parameters the object with parameters
4841
+ * @returns the template with replaced parameters
4842
+ * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
4843
+ * @public exported from `@promptbook/utils`
4844
+ */
4845
+ function templateParameters(template, parameters) {
4846
+ for (const [parameterName, parameterValue] of Object.entries(parameters)) {
4847
+ if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
4848
+ throw new UnexpectedError(`Parameter \`{${parameterName}}\` has missing value`);
4849
+ }
4850
+ else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
4851
+ // TODO: [๐Ÿต]
4852
+ throw new UnexpectedError(`Parameter \`{${parameterName}}\` is restricted to use`);
4853
+ }
4854
+ }
4855
+ let replacedTemplates = template;
4856
+ let match;
4857
+ let loopLimit = LOOP_LIMIT;
4858
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
4859
+ .exec(replacedTemplates))) {
4860
+ if (loopLimit-- < 0) {
4861
+ throw new LimitReachedError('Loop limit reached during parameters replacement in `templateParameters`');
4862
+ }
4863
+ const precol = match.groups.precol;
4864
+ const parameterName = match.groups.parameterName;
4865
+ if (parameterName === '') {
4866
+ // Note: Skip empty placeholders. It's used to avoid confusion with JSON-like strings
4867
+ continue;
4868
+ }
4869
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
4870
+ throw new PipelineExecutionError('Parameter is already opened or not closed');
4871
+ }
4872
+ if (parameters[parameterName] === undefined) {
4873
+ throw new PipelineExecutionError(`Parameter \`{${parameterName}}\` is not defined`);
4874
+ }
4875
+ let parameterValue = parameters[parameterName];
4876
+ if (parameterValue === undefined) {
4877
+ throw new PipelineExecutionError(`Parameter \`{${parameterName}}\` is not defined`);
4878
+ }
4879
+ parameterValue = valueToString(parameterValue);
4880
+ // Escape curly braces in parameter values to prevent prompt-injection
4881
+ parameterValue = parameterValue.replace(/[{}]/g, '\\$&');
4882
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
4883
+ parameterValue = parameterValue
4884
+ .split('\n')
4885
+ .map((line, index) => (index === 0 ? line : `${precol}${line}`))
4886
+ .join('\n');
4887
+ }
4888
+ replacedTemplates =
4889
+ replacedTemplates.substring(0, match.index + precol.length) +
4890
+ parameterValue +
4891
+ replacedTemplates.substring(match.index + precol.length + parameterName.length + 2);
4892
+ }
4893
+ // [๐Ÿ’ซ] Check if there are parameters that are not closed properly
4894
+ if (/{\w+$/.test(replacedTemplates)) {
4895
+ throw new PipelineExecutionError('Parameter is not closed');
4896
+ }
4897
+ // [๐Ÿ’ซ] Check if there are parameters that are not opened properly
4898
+ if (/^\w+}/.test(replacedTemplates)) {
4899
+ throw new PipelineExecutionError('Parameter is not opened');
4900
+ }
4901
+ return replacedTemplates;
4902
+ }
4903
+
4816
4904
  /**
4817
4905
  * Extracts all code blocks from markdown.
4818
4906
  *
@@ -4915,94 +5003,6 @@ function extractJsonBlock(markdown) {
4915
5003
  * TODO: [๐Ÿข] Make this logic part of `JsonFormatParser` or `isValidJsonString`
4916
5004
  */
4917
5005
 
4918
- /**
4919
- * Just says that the variable is not used but should be kept
4920
- * No side effects.
4921
- *
4922
- * Note: It can be useful for:
4923
- *
4924
- * 1) Suppressing eager optimization of unused imports
4925
- * 2) Suppressing eslint errors of unused variables in the tests
4926
- * 3) Keeping the type of the variable for type testing
4927
- *
4928
- * @param value any values
4929
- * @returns void
4930
- * @private within the repository
4931
- */
4932
- function keepUnused(...valuesToKeep) {
4933
- }
4934
-
4935
- /**
4936
- * Replaces parameters in template with values from parameters object
4937
- *
4938
- * Note: This function is not places strings into string,
4939
- * It's more complex and can handle this operation specifically for LLM models
4940
- *
4941
- * @param template the template with parameters in {curly} braces
4942
- * @param parameters the object with parameters
4943
- * @returns the template with replaced parameters
4944
- * @throws {PipelineExecutionError} if parameter is not defined, not closed, or not opened
4945
- * @public exported from `@promptbook/utils`
4946
- */
4947
- function templateParameters(template, parameters) {
4948
- for (const [parameterName, parameterValue] of Object.entries(parameters)) {
4949
- if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
4950
- throw new UnexpectedError(`Parameter \`{${parameterName}}\` has missing value`);
4951
- }
4952
- else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
4953
- // TODO: [๐Ÿต]
4954
- throw new UnexpectedError(`Parameter \`{${parameterName}}\` is restricted to use`);
4955
- }
4956
- }
4957
- let replacedTemplates = template;
4958
- let match;
4959
- let loopLimit = LOOP_LIMIT;
4960
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
4961
- .exec(replacedTemplates))) {
4962
- if (loopLimit-- < 0) {
4963
- throw new LimitReachedError('Loop limit reached during parameters replacement in `templateParameters`');
4964
- }
4965
- const precol = match.groups.precol;
4966
- const parameterName = match.groups.parameterName;
4967
- if (parameterName === '') {
4968
- // Note: Skip empty placeholders. It's used to avoid confusion with JSON-like strings
4969
- continue;
4970
- }
4971
- if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
4972
- throw new PipelineExecutionError('Parameter is already opened or not closed');
4973
- }
4974
- if (parameters[parameterName] === undefined) {
4975
- throw new PipelineExecutionError(`Parameter \`{${parameterName}}\` is not defined`);
4976
- }
4977
- let parameterValue = parameters[parameterName];
4978
- if (parameterValue === undefined) {
4979
- throw new PipelineExecutionError(`Parameter \`{${parameterName}}\` is not defined`);
4980
- }
4981
- parameterValue = valueToString(parameterValue);
4982
- // Escape curly braces in parameter values to prevent prompt-injection
4983
- parameterValue = parameterValue.replace(/[{}]/g, '\\$&');
4984
- if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
4985
- parameterValue = parameterValue
4986
- .split('\n')
4987
- .map((line, index) => (index === 0 ? line : `${precol}${line}`))
4988
- .join('\n');
4989
- }
4990
- replacedTemplates =
4991
- replacedTemplates.substring(0, match.index + precol.length) +
4992
- parameterValue +
4993
- replacedTemplates.substring(match.index + precol.length + parameterName.length + 2);
4994
- }
4995
- // [๐Ÿ’ซ] Check if there are parameters that are not closed properly
4996
- if (/{\w+$/.test(replacedTemplates)) {
4997
- throw new PipelineExecutionError('Parameter is not closed');
4998
- }
4999
- // [๐Ÿ’ซ] Check if there are parameters that are not opened properly
5000
- if (/^\w+}/.test(replacedTemplates)) {
5001
- throw new PipelineExecutionError('Parameter is not opened');
5002
- }
5003
- return replacedTemplates;
5004
- }
5005
-
5006
5006
  /**
5007
5007
  * Counts number of characters in the text
5008
5008
  *
@@ -5163,6 +5163,68 @@ function checkExpectations(expectations, value) {
5163
5163
  * Note: [๐Ÿ’] and [๐Ÿค ] are interconnected together
5164
5164
  */
5165
5165
 
5166
+ /**
5167
+ * Validates a prompt result against expectations and format requirements.
5168
+ * This function provides a common abstraction for result validation that can be used
5169
+ * by both execution logic and caching logic to ensure consistency.
5170
+ *
5171
+ * @param options - The validation options including result string, expectations, and format
5172
+ * @returns Validation result with processed string and validity status
5173
+ * @private internal function of `createPipelineExecutor` and `cacheLlmTools`
5174
+ */
5175
+ function validatePromptResult(options) {
5176
+ const { resultString, expectations, format } = options;
5177
+ let processedResultString = resultString;
5178
+ let validationError;
5179
+ try {
5180
+ // TODO: [๐Ÿ’] Unite object for expecting amount and format
5181
+ if (format) {
5182
+ if (format === 'JSON') {
5183
+ if (!isValidJsonString(processedResultString)) {
5184
+ // TODO: [๐Ÿข] Do more universally via `FormatParser`
5185
+ try {
5186
+ processedResultString = extractJsonBlock(processedResultString);
5187
+ }
5188
+ catch (error) {
5189
+ keepUnused(error);
5190
+ throw new ExpectError(spaceTrim$1((block) => `
5191
+ Expected valid JSON string
5192
+
5193
+ The expected JSON text:
5194
+ ${block(processedResultString)}
5195
+ `));
5196
+ }
5197
+ }
5198
+ }
5199
+ else {
5200
+ throw new UnexpectedError(`Unknown format "${format}"`);
5201
+ }
5202
+ }
5203
+ // TODO: [๐Ÿ’] Unite object for expecting amount and format
5204
+ if (expectations) {
5205
+ checkExpectations(expectations, processedResultString);
5206
+ }
5207
+ return {
5208
+ isValid: true,
5209
+ processedResultString,
5210
+ };
5211
+ }
5212
+ catch (error) {
5213
+ if (error instanceof ExpectError) {
5214
+ validationError = error;
5215
+ }
5216
+ else {
5217
+ // Re-throw non-ExpectError errors (like UnexpectedError)
5218
+ throw error;
5219
+ }
5220
+ return {
5221
+ isValid: false,
5222
+ processedResultString,
5223
+ error: validationError,
5224
+ };
5225
+ }
5226
+ }
5227
+
5166
5228
  /**
5167
5229
  * Executes a pipeline task with multiple attempts, including joker and retry logic. Handles different task types
5168
5230
  * (prompt, script, dialog, etc.), applies postprocessing, checks expectations, and updates the execution report.
@@ -5185,13 +5247,13 @@ async function executeAttempts(options) {
5185
5247
  // TODO: [๐Ÿš] Make arrayable LLMs -> single LLM DRY
5186
5248
  const _llms = arrayableToArray(tools.llm);
5187
5249
  const llmTools = _llms.length === 1 ? _llms[0] : joinLlmExecutionTools(..._llms);
5188
- attempts: for (let attempt = -jokerParameterNames.length; attempt < maxAttempts; attempt++) {
5189
- const isJokerAttempt = attempt < 0;
5190
- const jokerParameterName = jokerParameterNames[jokerParameterNames.length + attempt];
5250
+ attempts: for (let attemptIndex = -jokerParameterNames.length; attemptIndex < maxAttempts; attemptIndex++) {
5251
+ const isJokerAttempt = attemptIndex < 0;
5252
+ const jokerParameterName = jokerParameterNames[jokerParameterNames.length + attemptIndex];
5191
5253
  // TODO: [๐Ÿง ][๐Ÿญ] JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
5192
5254
  if (isJokerAttempt && !jokerParameterName) {
5193
5255
  throw new UnexpectedError(spaceTrim$1((block) => `
5194
- Joker not found in attempt ${attempt}
5256
+ Joker not found in attempt ${attemptIndex}
5195
5257
 
5196
5258
  ${block(pipelineIdentification)}
5197
5259
  `));
@@ -5389,35 +5451,18 @@ async function executeAttempts(options) {
5389
5451
  }
5390
5452
  }
5391
5453
  // TODO: [๐Ÿ’] Unite object for expecting amount and format
5392
- if (task.format) {
5393
- if (task.format === 'JSON') {
5394
- if (!isValidJsonString($ongoingTaskResult.$resultString || '')) {
5395
- // TODO: [๐Ÿข] Do more universally via `FormatParser`
5396
- try {
5397
- $ongoingTaskResult.$resultString = extractJsonBlock($ongoingTaskResult.$resultString || '');
5398
- }
5399
- catch (error) {
5400
- keepUnused(error);
5401
- throw new ExpectError(spaceTrim$1((block) => `
5402
- Expected valid JSON string
5403
-
5404
- ${block(
5405
- /*<- Note: No need for `pipelineIdentification`, it will be catched and added later */ '')}
5406
- `));
5407
- }
5408
- }
5409
- }
5410
- else {
5411
- throw new UnexpectedError(spaceTrim$1((block) => `
5412
- Unknown format "${task.format}"
5413
-
5414
- ${block(pipelineIdentification)}
5415
- `));
5454
+ // Use the common validation function for both format and expectations
5455
+ if (task.format || task.expectations) {
5456
+ const validationResult = validatePromptResult({
5457
+ resultString: $ongoingTaskResult.$resultString || '',
5458
+ expectations: task.expectations,
5459
+ format: task.format,
5460
+ });
5461
+ if (!validationResult.isValid) {
5462
+ throw validationResult.error;
5416
5463
  }
5417
- }
5418
- // TODO: [๐Ÿ’] Unite object for expecting amount and format
5419
- if (task.expectations) {
5420
- checkExpectations(task.expectations, $ongoingTaskResult.$resultString || '');
5464
+ // Update the result string in case format processing modified it (e.g., JSON extraction)
5465
+ $ongoingTaskResult.$resultString = validationResult.processedResultString;
5421
5466
  }
5422
5467
  break attempts;
5423
5468
  }
@@ -5431,6 +5476,7 @@ async function executeAttempts(options) {
5431
5476
  $ongoingTaskResult.$failedResults = [];
5432
5477
  }
5433
5478
  $ongoingTaskResult.$failedResults.push({
5479
+ attemptIndex,
5434
5480
  result: $ongoingTaskResult.$resultString,
5435
5481
  error: error,
5436
5482
  });
@@ -5455,19 +5501,13 @@ async function executeAttempts(options) {
5455
5501
  });
5456
5502
  }
5457
5503
  }
5458
- if ($ongoingTaskResult.$expectError !== null && attempt === maxAttempts - 1) {
5459
- // Store the current failure before throwing
5460
- $ongoingTaskResult.$failedResults = $ongoingTaskResult.$failedResults || [];
5461
- $ongoingTaskResult.$failedResults.push({
5462
- result: $ongoingTaskResult.$resultString,
5463
- error: $ongoingTaskResult.$expectError,
5464
- });
5465
- // Create a summary of all failures
5504
+ if ($ongoingTaskResult.$expectError !== null && attemptIndex === maxAttempts - 1) {
5505
+ // Note: Create a summary of all failures
5466
5506
  const failuresSummary = $ongoingTaskResult.$failedResults
5467
- .map((failure, index) => spaceTrim$1((block) => {
5507
+ .map((failure) => spaceTrim$1((block) => {
5468
5508
  var _a, _b;
5469
5509
  return `
5470
- Attempt ${index + 1}:
5510
+ Attempt ${failure.attemptIndex + 1}:
5471
5511
  Error ${((_a = failure.error) === null || _a === void 0 ? void 0 : _a.name) || ''}:
5472
5512
  ${block((_b = failure.error) === null || _b === void 0 ? void 0 : _b.message.split('\n').map((line) => `> ${line}`).join('\n'))}
5473
5513