@promptbook/documents 0.112.0-39 β†’ 0.112.0-41

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 (56) hide show
  1. package/README.md +23 -21
  2. package/esm/index.es.js +481 -288
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/src/book-2.0/agent-source/createAgentModelRequirementsWithCommitments.d.ts +8 -2
  5. package/esm/src/book-components/Chat/Chat/ChatInputArea.d.ts +0 -10
  6. package/esm/src/book-components/Chat/Chat/ChatInputUploadedFile.d.ts +10 -0
  7. package/esm/src/book-components/Chat/Chat/ChatToolCallModalContent.d.ts +46 -0
  8. package/esm/src/book-components/Chat/Chat/resolveRunBrowserToolCallDetailsState.d.ts +146 -0
  9. package/esm/src/book-components/Chat/Chat/useChatInputAreaAttachments.d.ts +1 -1
  10. package/esm/src/book-components/Chat/Chat/useChatInputAreaComposer.d.ts +39 -0
  11. package/esm/src/book-components/Chat/Chat/useChatPostprocessedMessages.d.ts +17 -0
  12. package/esm/src/book-components/Chat/Chat/useChatScrollState.d.ts +34 -0
  13. package/esm/src/book-components/Chat/Chat/useChatToolCallModalState.d.ts +61 -0
  14. package/esm/src/book-components/Chat/Chat/useChatToolCallState.d.ts +35 -0
  15. package/esm/src/book-components/Chat/LlmChat/useLlmChatMessageHandler.d.ts +58 -0
  16. package/esm/src/book-components/Chat/LlmChat/useLlmChatMessages.d.ts +29 -0
  17. package/esm/src/book-components/Chat/LlmChat/useLlmChatState.d.ts +53 -0
  18. package/esm/src/collection/pipeline-collection/constructors/createPipelineCollectionFromDirectory.d.ts +7 -1
  19. package/esm/src/llm-providers/agent/AgentLlmExecutionTools.d.ts +52 -0
  20. package/esm/src/llm-providers/openai/OpenAiAssistantExecutionTools.d.ts +128 -0
  21. package/esm/src/llm-providers/openai/OpenAiCompatibleExecutionTools.d.ts +3 -3
  22. package/esm/src/llm-providers/openai/OpenAiVectorStoreHandler.d.ts +54 -0
  23. package/esm/src/llm-providers/openai/utils/OpenAiCompatibleUnsupportedParameterRetrier.d.ts +29 -0
  24. package/esm/src/llm-providers/openai/utils/callOpenAiCompatibleChatModel.d.ts +28 -0
  25. package/esm/src/types/number_usd.d.ts +1 -1
  26. package/esm/src/types/string_parameter_name.d.ts +2 -2
  27. package/esm/src/types/typeAliases.d.ts +2 -2
  28. package/esm/src/version.d.ts +1 -1
  29. package/package.json +2 -2
  30. package/umd/index.umd.js +481 -288
  31. package/umd/index.umd.js.map +1 -1
  32. package/umd/src/book-2.0/agent-source/createAgentModelRequirementsWithCommitments.d.ts +8 -2
  33. package/umd/src/book-components/Chat/Chat/ChatInputArea.d.ts +0 -10
  34. package/umd/src/book-components/Chat/Chat/ChatInputUploadedFile.d.ts +10 -0
  35. package/umd/src/book-components/Chat/Chat/ChatToolCallModalContent.d.ts +46 -0
  36. package/umd/src/book-components/Chat/Chat/resolveRunBrowserToolCallDetailsState.d.ts +146 -0
  37. package/umd/src/book-components/Chat/Chat/useChatInputAreaAttachments.d.ts +1 -1
  38. package/umd/src/book-components/Chat/Chat/useChatInputAreaComposer.d.ts +39 -0
  39. package/umd/src/book-components/Chat/Chat/useChatPostprocessedMessages.d.ts +17 -0
  40. package/umd/src/book-components/Chat/Chat/useChatScrollState.d.ts +34 -0
  41. package/umd/src/book-components/Chat/Chat/useChatToolCallModalState.d.ts +61 -0
  42. package/umd/src/book-components/Chat/Chat/useChatToolCallState.d.ts +35 -0
  43. package/umd/src/book-components/Chat/LlmChat/useLlmChatMessageHandler.d.ts +58 -0
  44. package/umd/src/book-components/Chat/LlmChat/useLlmChatMessages.d.ts +29 -0
  45. package/umd/src/book-components/Chat/LlmChat/useLlmChatState.d.ts +53 -0
  46. package/umd/src/collection/pipeline-collection/constructors/createPipelineCollectionFromDirectory.d.ts +7 -1
  47. package/umd/src/llm-providers/agent/AgentLlmExecutionTools.d.ts +52 -0
  48. package/umd/src/llm-providers/openai/OpenAiAssistantExecutionTools.d.ts +128 -0
  49. package/umd/src/llm-providers/openai/OpenAiCompatibleExecutionTools.d.ts +3 -3
  50. package/umd/src/llm-providers/openai/OpenAiVectorStoreHandler.d.ts +54 -0
  51. package/umd/src/llm-providers/openai/utils/OpenAiCompatibleUnsupportedParameterRetrier.d.ts +29 -0
  52. package/umd/src/llm-providers/openai/utils/callOpenAiCompatibleChatModel.d.ts +28 -0
  53. package/umd/src/types/number_usd.d.ts +1 -1
  54. package/umd/src/types/string_parameter_name.d.ts +2 -2
  55. package/umd/src/types/typeAliases.d.ts +2 -2
  56. package/umd/src/version.d.ts +1 -1
package/esm/index.es.js CHANGED
@@ -26,7 +26,7 @@ const BOOK_LANGUAGE_VERSION = '2.0.0';
26
26
  * @generated
27
27
  * @see https://github.com/webgptorg/promptbook
28
28
  */
29
- const PROMPTBOOK_ENGINE_VERSION = '0.112.0-39';
29
+ const PROMPTBOOK_ENGINE_VERSION = '0.112.0-41';
30
30
  /**
31
31
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
32
32
  * Note: [πŸ’ž] Ignore a discrepancy between file name and entity name
@@ -6283,317 +6283,511 @@ function validatePromptResult(options) {
6283
6283
  * @private internal utility of `createPipelineExecutor`
6284
6284
  */
6285
6285
  async function executeAttempts(options) {
6286
- const { jokerParameterNames, priority, maxAttempts, // <- Note: [πŸ’‚]
6287
- preparedContent, parameters, task, preparedPipeline, tools, $executionReport, pipelineIdentification, maxExecutionAttempts, onProgress, logLlmCall, } = options;
6288
- const $ongoingTaskResult = {
6286
+ const $ongoingTaskResult = createOngoingTaskResult();
6287
+ const llmTools = getSingleLlmExecutionTools(options.tools.llm);
6288
+ attempts: for (let attemptIndex = -options.jokerParameterNames.length; attemptIndex < options.maxAttempts; attemptIndex++) {
6289
+ const attempt = createAttemptDescriptor({
6290
+ attemptIndex,
6291
+ jokerParameterNames: options.jokerParameterNames,
6292
+ pipelineIdentification: options.pipelineIdentification,
6293
+ });
6294
+ resetAttemptExecutionState($ongoingTaskResult);
6295
+ try {
6296
+ await executeSingleAttempt({
6297
+ attempt,
6298
+ options,
6299
+ llmTools,
6300
+ $ongoingTaskResult,
6301
+ });
6302
+ break attempts;
6303
+ }
6304
+ catch (error) {
6305
+ if (!(error instanceof ExpectError)) {
6306
+ throw error;
6307
+ }
6308
+ recordFailedAttempt({
6309
+ error,
6310
+ attemptIndex,
6311
+ onProgress: options.onProgress,
6312
+ $ongoingTaskResult,
6313
+ });
6314
+ }
6315
+ finally {
6316
+ reportPromptExecution({
6317
+ attempt,
6318
+ task: options.task,
6319
+ $executionReport: options.$executionReport,
6320
+ logLlmCall: options.logLlmCall,
6321
+ $ongoingTaskResult,
6322
+ });
6323
+ }
6324
+ throwIfFinalAttemptFailed({
6325
+ attemptIndex,
6326
+ maxAttempts: options.maxAttempts,
6327
+ maxExecutionAttempts: options.maxExecutionAttempts,
6328
+ pipelineIdentification: options.pipelineIdentification,
6329
+ $ongoingTaskResult,
6330
+ });
6331
+ }
6332
+ return getSuccessfulResultString({
6333
+ pipelineIdentification: options.pipelineIdentification,
6334
+ $ongoingTaskResult,
6335
+ });
6336
+ }
6337
+ /**
6338
+ * Creates mutable attempt state for one task execution lifecycle.
6339
+ */
6340
+ function createOngoingTaskResult() {
6341
+ return {
6289
6342
  $result: null,
6290
6343
  $resultString: null,
6291
6344
  $expectError: null,
6292
6345
  $scriptPipelineExecutionErrors: [],
6293
- $failedResults: [], // Track all failed attempts
6346
+ $failedResults: [],
6294
6347
  };
6295
- const llmTools = getSingleLlmExecutionTools(tools.llm);
6296
- attempts: for (let attemptIndex = -jokerParameterNames.length; attemptIndex < maxAttempts; attemptIndex++) {
6297
- const isJokerAttempt = attemptIndex < 0;
6298
- const jokerParameterName = jokerParameterNames[jokerParameterNames.length + attemptIndex];
6299
- // TODO: [🧠][🍭] JOKERS, EXPECTATIONS, POSTPROCESSING and FOREACH
6300
- if (isJokerAttempt && !jokerParameterName) {
6301
- throw new UnexpectedError(spaceTrim$1((block) => `
6302
- Joker not found in attempt ${attemptIndex}
6348
+ }
6349
+ /**
6350
+ * Resolves the bookkeeping for one loop iteration, including joker lookup.
6351
+ */
6352
+ function createAttemptDescriptor(options) {
6353
+ const { attemptIndex, jokerParameterNames, pipelineIdentification } = options;
6354
+ const isJokerAttempt = attemptIndex < 0;
6355
+ const jokerParameterName = isJokerAttempt
6356
+ ? jokerParameterNames[jokerParameterNames.length + attemptIndex]
6357
+ : undefined;
6358
+ if (isJokerAttempt && !jokerParameterName) {
6359
+ throw new UnexpectedError(spaceTrim$1((block) => `
6360
+ Joker not found in attempt ${attemptIndex}
6303
6361
 
6304
- ${block(pipelineIdentification)}
6362
+ ${block(pipelineIdentification)}
6363
+ `));
6364
+ }
6365
+ return {
6366
+ attemptIndex,
6367
+ isJokerAttempt,
6368
+ jokerParameterName,
6369
+ };
6370
+ }
6371
+ /**
6372
+ * Clears the per-attempt result slots while preserving cumulative failure history.
6373
+ */
6374
+ function resetAttemptExecutionState($ongoingTaskResult) {
6375
+ $ongoingTaskResult.$result = null;
6376
+ $ongoingTaskResult.$resultString = null;
6377
+ $ongoingTaskResult.$expectError = null;
6378
+ }
6379
+ /**
6380
+ * Executes one loop iteration, from joker resolution or task execution through validation.
6381
+ */
6382
+ async function executeSingleAttempt(options) {
6383
+ const { attempt, options: executeAttemptsOptions, llmTools, $ongoingTaskResult } = options;
6384
+ if (attempt.isJokerAttempt) {
6385
+ resolveJokerAttemptResult({
6386
+ jokerParameterName: attempt.jokerParameterName,
6387
+ parameters: executeAttemptsOptions.parameters,
6388
+ pipelineIdentification: executeAttemptsOptions.pipelineIdentification,
6389
+ $ongoingTaskResult,
6390
+ });
6391
+ }
6392
+ else {
6393
+ await executeTaskAttempt({
6394
+ options: executeAttemptsOptions,
6395
+ llmTools,
6396
+ $ongoingTaskResult,
6397
+ });
6398
+ await applyPostprocessingFunctions({
6399
+ task: executeAttemptsOptions.task,
6400
+ tools: executeAttemptsOptions.tools,
6401
+ $ongoingTaskResult,
6402
+ });
6403
+ }
6404
+ validateAttemptResult({
6405
+ task: executeAttemptsOptions.task,
6406
+ $ongoingTaskResult,
6407
+ });
6408
+ }
6409
+ /**
6410
+ * Resolves the shortcut value used by a joker attempt.
6411
+ */
6412
+ function resolveJokerAttemptResult(options) {
6413
+ const { jokerParameterName, parameters, pipelineIdentification, $ongoingTaskResult } = options;
6414
+ if (parameters[jokerParameterName] === undefined) {
6415
+ throw new PipelineExecutionError(spaceTrim$1((block) => `
6416
+ Joker parameter {${jokerParameterName}} not defined
6417
+
6418
+ ${block(pipelineIdentification)}
6419
+ `));
6420
+ // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
6421
+ }
6422
+ $ongoingTaskResult.$resultString = parameters[jokerParameterName];
6423
+ }
6424
+ /**
6425
+ * Dispatches non-joker execution to the handler for the current task type.
6426
+ */
6427
+ async function executeTaskAttempt(options) {
6428
+ const { options: executeAttemptsOptions, llmTools, $ongoingTaskResult } = options;
6429
+ const { task } = executeAttemptsOptions;
6430
+ switch (task.taskType) {
6431
+ case 'SIMPLE_TASK':
6432
+ executeSimpleTaskAttempt({
6433
+ preparedContent: executeAttemptsOptions.preparedContent,
6434
+ parameters: executeAttemptsOptions.parameters,
6435
+ $ongoingTaskResult,
6436
+ });
6437
+ return;
6438
+ case 'PROMPT_TASK':
6439
+ await executePromptTaskAttempt({
6440
+ preparedPipeline: executeAttemptsOptions.preparedPipeline,
6441
+ task,
6442
+ parameters: executeAttemptsOptions.parameters,
6443
+ preparedContent: executeAttemptsOptions.preparedContent,
6444
+ pipelineIdentification: executeAttemptsOptions.pipelineIdentification,
6445
+ llmTools,
6446
+ $ongoingTaskResult,
6447
+ });
6448
+ return;
6449
+ case 'SCRIPT_TASK':
6450
+ await executeScriptTaskAttempt({
6451
+ tools: executeAttemptsOptions.tools,
6452
+ task,
6453
+ preparedContent: executeAttemptsOptions.preparedContent,
6454
+ parameters: executeAttemptsOptions.parameters,
6455
+ pipelineIdentification: executeAttemptsOptions.pipelineIdentification,
6456
+ $ongoingTaskResult,
6457
+ });
6458
+ return;
6459
+ case 'DIALOG_TASK':
6460
+ await executeDialogTaskAttempt({
6461
+ tools: executeAttemptsOptions.tools,
6462
+ task,
6463
+ parameters: executeAttemptsOptions.parameters,
6464
+ preparedContent: executeAttemptsOptions.preparedContent,
6465
+ priority: executeAttemptsOptions.priority,
6466
+ pipelineIdentification: executeAttemptsOptions.pipelineIdentification,
6467
+ $ongoingTaskResult,
6468
+ });
6469
+ return;
6470
+ default:
6471
+ throw new PipelineExecutionError(spaceTrim$1((block) => `
6472
+ Unknown execution type "${task.taskType}"
6473
+
6474
+ ${block(executeAttemptsOptions.pipelineIdentification)}
6305
6475
  `));
6306
- }
6307
- $ongoingTaskResult.$result = null;
6308
- $ongoingTaskResult.$resultString = null;
6309
- $ongoingTaskResult.$expectError = null;
6310
- if (isJokerAttempt) {
6311
- if (parameters[jokerParameterName] === undefined) {
6312
- throw new PipelineExecutionError(spaceTrim$1((block) => `
6313
- Joker parameter {${jokerParameterName}} not defined
6476
+ }
6477
+ }
6478
+ /**
6479
+ * Executes a simple templated task with no external tools.
6480
+ */
6481
+ function executeSimpleTaskAttempt(options) {
6482
+ const { preparedContent, parameters, $ongoingTaskResult } = options;
6483
+ $ongoingTaskResult.$resultString = templateParameters(preparedContent, parameters);
6484
+ }
6485
+ /**
6486
+ * Builds the prompt for a prompt task and calls the appropriate LLM variant.
6487
+ */
6488
+ async function executePromptTaskAttempt(options) {
6489
+ const { preparedPipeline, task, parameters, preparedContent, pipelineIdentification, llmTools, $ongoingTaskResult, } = options;
6490
+ const modelRequirements = {
6491
+ modelVariant: 'CHAT',
6492
+ ...(preparedPipeline.defaultModelRequirements || {}),
6493
+ ...(task.modelRequirements || {}),
6494
+ }; /* <- Note: [πŸ€›] */
6495
+ $ongoingTaskResult.$prompt = {
6496
+ title: task.title,
6497
+ pipelineUrl: `${preparedPipeline.pipelineUrl ? preparedPipeline.pipelineUrl : 'anonymous'}#${task.name
6498
+ // <- TODO: Here should be maybe also subformat index to distinguish between same task with different subformat values
6499
+ }`,
6500
+ parameters,
6501
+ content: preparedContent,
6502
+ modelRequirements,
6503
+ expectations: {
6504
+ ...(preparedPipeline.personas.find(({ name }) => name === task.personaName) || {}),
6505
+ ...task.expectations,
6506
+ },
6507
+ format: task.format,
6508
+ postprocessingFunctionNames: task.postprocessingFunctionNames,
6509
+ }; // <- TODO: Not very good type guard
6510
+ switch (modelRequirements.modelVariant) {
6511
+ case 'CHAT':
6512
+ $ongoingTaskResult.$chatResult = await llmTools.callChatModel(
6513
+ // <- TODO: [🧁] Check that `callChatModel` is defined
6514
+ $deepFreeze($ongoingTaskResult.$prompt));
6515
+ // TODO: [🍬] Destroy chatThread
6516
+ $ongoingTaskResult.$result = $ongoingTaskResult.$chatResult;
6517
+ $ongoingTaskResult.$resultString = $ongoingTaskResult.$chatResult.content;
6518
+ return;
6519
+ case 'COMPLETION':
6520
+ $ongoingTaskResult.$completionResult = await llmTools.callCompletionModel(
6521
+ // <- TODO: [🧁] Check that `callCompletionModel` is defined
6522
+ $deepFreeze($ongoingTaskResult.$prompt));
6523
+ $ongoingTaskResult.$result = $ongoingTaskResult.$completionResult;
6524
+ $ongoingTaskResult.$resultString = $ongoingTaskResult.$completionResult.content;
6525
+ return;
6526
+ case 'EMBEDDING':
6527
+ case 'IMAGE_GENERATION':
6528
+ throw new PipelineExecutionError(spaceTrim$1((block) => `
6529
+ ${modelRequirements.modelVariant} model can not be used in pipeline
6314
6530
 
6315
- ${block(pipelineIdentification)}
6316
- `));
6317
- // <- TODO: This is maybe `PipelineLogicError` which should be detected in `validatePipeline` and here just thrown as `UnexpectedError`
6318
- }
6319
- else {
6320
- $ongoingTaskResult.$resultString = parameters[jokerParameterName];
6321
- }
6322
- }
6323
- try {
6324
- if (!isJokerAttempt) {
6325
- taskType: switch (task.taskType) {
6326
- case 'SIMPLE_TASK':
6327
- $ongoingTaskResult.$resultString = templateParameters(preparedContent, parameters);
6328
- break taskType;
6329
- case 'PROMPT_TASK':
6330
- {
6331
- const modelRequirements = {
6332
- modelVariant: 'CHAT',
6333
- ...(preparedPipeline.defaultModelRequirements || {}),
6334
- ...(task.modelRequirements || {}),
6335
- }; /* <- Note: [πŸ€›] */
6336
- $ongoingTaskResult.$prompt = {
6337
- title: task.title,
6338
- pipelineUrl: `${preparedPipeline.pipelineUrl
6339
- ? preparedPipeline.pipelineUrl
6340
- : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous pipelines, do here some auto-url like SHA-256 based ad-hoc identifier? */}#${task.name
6341
- // <- TODO: Here should be maybe also subformat index to distinguish between same task with different subformat values
6342
- }`,
6343
- parameters,
6344
- content: preparedContent,
6345
- modelRequirements,
6346
- expectations: {
6347
- ...(preparedPipeline.personas.find(({ name }) => name === task.personaName) || {}),
6348
- ...task.expectations,
6349
- },
6350
- format: task.format,
6351
- postprocessingFunctionNames: task.postprocessingFunctionNames,
6352
- }; // <- TODO: Not very good type guard
6353
- variant: switch (modelRequirements.modelVariant) {
6354
- case 'CHAT':
6355
- $ongoingTaskResult.$chatResult = await llmTools.callChatModel(
6356
- // <- TODO: [🧁] Check that `callChatModel` is defined
6357
- $deepFreeze($ongoingTaskResult.$prompt));
6358
- // TODO: [🍬] Destroy chatThread
6359
- $ongoingTaskResult.$result = $ongoingTaskResult.$chatResult;
6360
- $ongoingTaskResult.$resultString = $ongoingTaskResult.$chatResult.content;
6361
- break variant;
6362
- case 'COMPLETION':
6363
- $ongoingTaskResult.$completionResult = await llmTools.callCompletionModel(
6364
- // <- TODO: [🧁] Check that `callCompletionModel` is defined
6365
- $deepFreeze($ongoingTaskResult.$prompt));
6366
- $ongoingTaskResult.$result = $ongoingTaskResult.$completionResult;
6367
- $ongoingTaskResult.$resultString = $ongoingTaskResult.$completionResult.content;
6368
- break variant;
6369
- case 'EMBEDDING':
6370
- case 'IMAGE_GENERATION':
6371
- throw new PipelineExecutionError(spaceTrim$1((block) => `
6372
- ${modelRequirements.modelVariant} model can not be used in pipeline
6373
-
6374
- This should be catched during parsing
6375
-
6376
- ${block(pipelineIdentification)}
6377
-
6378
- `));
6379
- break variant;
6380
- // <- case [πŸ€–]:
6381
- default:
6382
- throw new PipelineExecutionError(spaceTrim$1((block) => `
6383
- Unknown model variant "${task.modelRequirements.modelVariant}"
6384
-
6385
- ${block(pipelineIdentification)}
6386
-
6387
- `));
6388
- }
6389
- }
6390
- break;
6391
- case 'SCRIPT_TASK':
6392
- if (arrayableToArray(tools.script).length === 0) {
6393
- throw new PipelineExecutionError(spaceTrim$1((block) => `
6394
- No script execution tools are available
6531
+ This should be catched during parsing
6395
6532
 
6396
- ${block(pipelineIdentification)}
6397
- `));
6398
- }
6399
- if (!task.contentLanguage) {
6400
- throw new PipelineExecutionError(spaceTrim$1((block) => `
6401
- Script language is not defined for SCRIPT TASK "${task.name}"
6533
+ ${block(pipelineIdentification)}
6402
6534
 
6403
- ${block(pipelineIdentification)}
6404
- `));
6405
- }
6406
- // TODO: DRY [☯]
6407
- scripts: for (const scriptTools of arrayableToArray(tools.script)) {
6408
- try {
6409
- $ongoingTaskResult.$resultString = await scriptTools.execute($deepFreeze({
6410
- scriptLanguage: task.contentLanguage,
6411
- script: preparedContent,
6412
- parameters,
6413
- }));
6414
- break scripts;
6415
- }
6416
- catch (error) {
6417
- assertsError(error);
6418
- if (error instanceof UnexpectedError) {
6419
- throw error;
6420
- }
6421
- $ongoingTaskResult.$scriptPipelineExecutionErrors.push(error);
6422
- }
6423
- }
6424
- if ($ongoingTaskResult.$resultString !== null) {
6425
- break taskType;
6426
- }
6427
- if ($ongoingTaskResult.$scriptPipelineExecutionErrors.length === 1) {
6428
- throw $ongoingTaskResult.$scriptPipelineExecutionErrors[0];
6429
- }
6430
- else {
6431
- throw new PipelineExecutionError(spaceTrim$1((block) => `
6432
- Script execution failed ${$ongoingTaskResult.$scriptPipelineExecutionErrors.length}x
6535
+ `));
6536
+ // <- case [πŸ€–]:
6537
+ default:
6538
+ throw new PipelineExecutionError(spaceTrim$1((block) => `
6539
+ Unknown model variant "${task.modelRequirements.modelVariant}"
6433
6540
 
6434
- ${block(pipelineIdentification)}
6541
+ ${block(pipelineIdentification)}
6435
6542
 
6436
- ${block($ongoingTaskResult.$scriptPipelineExecutionErrors
6437
- .map((error) => '- ' + error.message)
6438
- .join('\n\n'))}
6439
- `));
6440
- }
6441
- // Note: This line is unreachable because of the break taskType above
6442
- break taskType;
6443
- case 'DIALOG_TASK':
6444
- if (tools.userInterface === undefined) {
6445
- throw new PipelineExecutionError(spaceTrim$1((block) => `
6446
- User interface tools are not available
6543
+ `));
6544
+ }
6545
+ }
6546
+ /**
6547
+ * Executes a script task with the first script tool that succeeds.
6548
+ */
6549
+ async function executeScriptTaskAttempt(options) {
6550
+ const { tools, task, preparedContent, parameters, pipelineIdentification, $ongoingTaskResult } = options;
6551
+ const scriptExecutionTools = arrayableToArray(tools.script);
6552
+ if (scriptExecutionTools.length === 0) {
6553
+ throw new PipelineExecutionError(spaceTrim$1((block) => `
6554
+ No script execution tools are available
6447
6555
 
6448
- ${block(pipelineIdentification)}
6449
- `));
6450
- }
6451
- // TODO: [🌹] When making next attempt for `DIALOG TASK`, preserve the previous user input
6452
- $ongoingTaskResult.$resultString = await tools.userInterface.promptDialog($deepFreeze({
6453
- promptTitle: task.title,
6454
- promptMessage: templateParameters(task.description || '', parameters),
6455
- defaultValue: templateParameters(preparedContent, parameters),
6456
- // TODO: [🧠] Figure out how to define placeholder in .book.md file
6457
- placeholder: undefined,
6458
- priority,
6459
- }));
6460
- break taskType;
6461
- // <- case: [πŸ…±]
6462
- default:
6463
- throw new PipelineExecutionError(spaceTrim$1((block) => `
6464
- Unknown execution type "${task.taskType}"
6556
+ ${block(pipelineIdentification)}
6557
+ `));
6558
+ }
6559
+ if (!task.contentLanguage) {
6560
+ throw new PipelineExecutionError(spaceTrim$1((block) => `
6561
+ Script language is not defined for SCRIPT TASK "${task.name}"
6465
6562
 
6466
- ${block(pipelineIdentification)}
6467
- `));
6468
- }
6469
- }
6470
- if (!isJokerAttempt && task.postprocessingFunctionNames) {
6471
- for (const functionName of task.postprocessingFunctionNames) {
6472
- let postprocessingError = null;
6473
- scripts: for (const scriptTools of arrayableToArray(tools.script)) {
6474
- try {
6475
- $ongoingTaskResult.$resultString = await scriptTools.execute({
6476
- scriptLanguage: `javascript` /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
6477
- script: `${functionName}(resultString)`,
6478
- parameters: {
6479
- resultString: $ongoingTaskResult.$resultString || '',
6480
- // Note: No ...parametersForTask, because working with result only
6481
- },
6482
- });
6483
- postprocessingError = null;
6484
- break scripts;
6485
- }
6486
- catch (error) {
6487
- assertsError(error);
6488
- if (error instanceof UnexpectedError) {
6489
- throw error;
6490
- }
6491
- postprocessingError = error;
6492
- $ongoingTaskResult.$scriptPipelineExecutionErrors.push(error);
6493
- }
6494
- }
6495
- if (postprocessingError) {
6496
- throw postprocessingError;
6497
- }
6498
- }
6499
- }
6500
- // TODO: [πŸ’] Unite object for expecting amount and format
6501
- // Use the common validation function for both format and expectations
6502
- if (task.format || task.expectations) {
6503
- const validationResult = validatePromptResult({
6504
- resultString: $ongoingTaskResult.$resultString || '',
6505
- expectations: task.expectations,
6506
- format: task.format,
6507
- });
6508
- if (!validationResult.isValid) {
6509
- throw validationResult.error;
6510
- }
6511
- // Update the result string in case format processing modified it (e.g., JSON extraction)
6512
- $ongoingTaskResult.$resultString = validationResult.processedResultString;
6513
- }
6514
- break attempts;
6563
+ ${block(pipelineIdentification)}
6564
+ `));
6565
+ }
6566
+ for (const scriptTools of scriptExecutionTools) {
6567
+ try {
6568
+ $ongoingTaskResult.$resultString = await scriptTools.execute($deepFreeze({
6569
+ scriptLanguage: task.contentLanguage,
6570
+ script: preparedContent,
6571
+ parameters,
6572
+ }));
6573
+ return;
6515
6574
  }
6516
6575
  catch (error) {
6517
- if (!(error instanceof ExpectError)) {
6576
+ assertsError(error);
6577
+ if (error instanceof UnexpectedError) {
6518
6578
  throw error;
6519
6579
  }
6520
- $ongoingTaskResult.$expectError = error;
6521
- // Store each failed attempt
6522
- if (!Array.isArray($ongoingTaskResult.$failedResults)) {
6523
- $ongoingTaskResult.$failedResults = [];
6524
- }
6525
- $ongoingTaskResult.$failedResults.push({
6526
- attemptIndex,
6527
- result: $ongoingTaskResult.$resultString,
6528
- error: error,
6529
- });
6530
- // Report failed attempt
6531
- onProgress({
6532
- errors: [error],
6580
+ $ongoingTaskResult.$scriptPipelineExecutionErrors.push(error);
6581
+ }
6582
+ }
6583
+ throw createScriptExecutionFailure({
6584
+ pipelineIdentification,
6585
+ $ongoingTaskResult,
6586
+ });
6587
+ }
6588
+ /**
6589
+ * Creates the final script-task error after all script tools have failed.
6590
+ */
6591
+ function createScriptExecutionFailure(options) {
6592
+ const { pipelineIdentification, $ongoingTaskResult } = options;
6593
+ if ($ongoingTaskResult.$scriptPipelineExecutionErrors.length === 1) {
6594
+ return $ongoingTaskResult.$scriptPipelineExecutionErrors[0];
6595
+ }
6596
+ return new PipelineExecutionError(spaceTrim$1((block) => `
6597
+ Script execution failed ${$ongoingTaskResult.$scriptPipelineExecutionErrors.length}x
6598
+
6599
+ ${block(pipelineIdentification)}
6600
+
6601
+ ${block($ongoingTaskResult.$scriptPipelineExecutionErrors.map((error) => '- ' + error.message).join('\n\n'))}
6602
+ `));
6603
+ }
6604
+ /**
6605
+ * Executes a dialog task through the configured user-interface tools.
6606
+ */
6607
+ async function executeDialogTaskAttempt(options) {
6608
+ const { tools, task, parameters, preparedContent, priority, pipelineIdentification, $ongoingTaskResult } = options;
6609
+ if (tools.userInterface === undefined) {
6610
+ throw new PipelineExecutionError(spaceTrim$1((block) => `
6611
+ User interface tools are not available
6612
+
6613
+ ${block(pipelineIdentification)}
6614
+ `));
6615
+ }
6616
+ // TODO: [🌹] When making next attempt for `DIALOG TASK`, preserve the previous user input
6617
+ $ongoingTaskResult.$resultString = await tools.userInterface.promptDialog($deepFreeze({
6618
+ promptTitle: task.title,
6619
+ promptMessage: templateParameters(task.description || '', parameters),
6620
+ defaultValue: templateParameters(preparedContent, parameters),
6621
+ // TODO: [🧠] Figure out how to define placeholder in .book.md file
6622
+ placeholder: undefined,
6623
+ priority,
6624
+ }));
6625
+ }
6626
+ /**
6627
+ * Runs all configured postprocessing functions in order.
6628
+ */
6629
+ async function applyPostprocessingFunctions(options) {
6630
+ const { task } = options;
6631
+ if (!task.postprocessingFunctionNames) {
6632
+ return;
6633
+ }
6634
+ for (const functionName of task.postprocessingFunctionNames) {
6635
+ await executePostprocessingFunction({
6636
+ functionName,
6637
+ tools: options.tools,
6638
+ $ongoingTaskResult: options.$ongoingTaskResult,
6639
+ });
6640
+ }
6641
+ }
6642
+ /**
6643
+ * Executes one postprocessing function against the current result string.
6644
+ */
6645
+ async function executePostprocessingFunction(options) {
6646
+ const { functionName, tools, $ongoingTaskResult } = options;
6647
+ let postprocessingError = null;
6648
+ for (const scriptTools of arrayableToArray(tools.script)) {
6649
+ try {
6650
+ $ongoingTaskResult.$resultString = await scriptTools.execute({
6651
+ scriptLanguage: `javascript` /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
6652
+ script: `${functionName}(resultString)`,
6653
+ parameters: {
6654
+ resultString: $ongoingTaskResult.$resultString || '',
6655
+ // Note: No ...parametersForTask, because working with result only
6656
+ },
6533
6657
  });
6658
+ postprocessingError = null;
6659
+ return;
6534
6660
  }
6535
- finally {
6536
- if (!isJokerAttempt && task.taskType === 'PROMPT_TASK' && $ongoingTaskResult.$prompt) {
6537
- // Note: [2] When some expected parameter is not defined, error will occur in templateParameters
6538
- // In that case we don’t want to make a report about it because it’s not a llm execution error
6539
- const executionPromptReport = {
6540
- prompt: {
6541
- ...$ongoingTaskResult.$prompt,
6542
- // <- TODO: [🧠] How to pick everyhing except `pipelineUrl`
6543
- },
6544
- result: $ongoingTaskResult.$result || undefined,
6545
- error: $ongoingTaskResult.$expectError === null
6546
- ? undefined
6547
- : serializeError($ongoingTaskResult.$expectError),
6548
- };
6549
- $executionReport.promptExecutions.push(executionPromptReport);
6550
- if (logLlmCall) {
6551
- logLlmCall({
6552
- modelName: 'model' /* <- TODO: How to get model name from the report */,
6553
- report: executionPromptReport,
6554
- });
6555
- }
6661
+ catch (error) {
6662
+ assertsError(error);
6663
+ if (error instanceof UnexpectedError) {
6664
+ throw error;
6556
6665
  }
6666
+ postprocessingError = error;
6667
+ $ongoingTaskResult.$scriptPipelineExecutionErrors.push(error);
6557
6668
  }
6558
- if ($ongoingTaskResult.$expectError !== null && attemptIndex === maxAttempts - 1) {
6559
- // Note: Create a summary of all failures
6560
- const failuresSummary = $ongoingTaskResult.$failedResults
6561
- .map((failure) => spaceTrim$1((block) => {
6562
- var _a, _b;
6563
- return `
6564
- Attempt ${failure.attemptIndex + 1}:
6565
- Error ${((_a = failure.error) === null || _a === void 0 ? void 0 : _a.name) || ''}:
6566
- ${block((_b = failure.error) === null || _b === void 0 ? void 0 : _b.message.split(/\r?\n/).map((line) => `> ${line}`).join('\n'))}
6567
-
6568
- Result:
6569
- ${block(failure.result === null
6570
- ? 'null'
6571
- : spaceTrim$1(failure.result)
6572
- .split(/\r?\n/)
6573
- .map((line) => `> ${line}`)
6574
- .join('\n'))}
6575
- `;
6576
- }))
6577
- .join('\n\n---\n\n');
6578
- throw new PipelineExecutionError(spaceTrim$1((block) => {
6579
- var _a;
6580
- return `
6581
- LLM execution failed ${maxExecutionAttempts}x
6669
+ }
6670
+ if (postprocessingError) {
6671
+ throw postprocessingError;
6672
+ }
6673
+ }
6674
+ /**
6675
+ * Validates the current result string against expectations and format constraints.
6676
+ */
6677
+ function validateAttemptResult(options) {
6678
+ const { task, $ongoingTaskResult } = options;
6679
+ if (!task.format && !task.expectations) {
6680
+ return;
6681
+ }
6682
+ // TODO: [πŸ’] Unite object for expecting amount and format
6683
+ // Use the common validation function for both format and expectations
6684
+ const validationResult = validatePromptResult({
6685
+ resultString: $ongoingTaskResult.$resultString || '',
6686
+ expectations: task.expectations,
6687
+ format: task.format,
6688
+ });
6689
+ if (!validationResult.isValid) {
6690
+ throw validationResult.error;
6691
+ }
6692
+ // Update the result string in case format processing modified it (e.g., JSON extraction)
6693
+ $ongoingTaskResult.$resultString = validationResult.processedResultString;
6694
+ }
6695
+ /**
6696
+ * Stores one failed attempt and reports the expectation error upstream.
6697
+ */
6698
+ function recordFailedAttempt(options) {
6699
+ const { error, attemptIndex, onProgress, $ongoingTaskResult } = options;
6700
+ $ongoingTaskResult.$expectError = error;
6701
+ $ongoingTaskResult.$failedResults.push({
6702
+ attemptIndex,
6703
+ result: $ongoingTaskResult.$resultString,
6704
+ error,
6705
+ });
6706
+ onProgress({
6707
+ errors: [error],
6708
+ });
6709
+ }
6710
+ /**
6711
+ * Appends the prompt execution report for prompt-task attempts.
6712
+ */
6713
+ function reportPromptExecution(options) {
6714
+ const { attempt, task, $executionReport, logLlmCall, $ongoingTaskResult } = options;
6715
+ if (attempt.isJokerAttempt || task.taskType !== 'PROMPT_TASK' || !$ongoingTaskResult.$prompt) {
6716
+ return;
6717
+ }
6718
+ // Note: [2] When some expected parameter is not defined, error will occur in templateParameters
6719
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
6720
+ const executionPromptReport = {
6721
+ prompt: {
6722
+ ...$ongoingTaskResult.$prompt,
6723
+ // <- TODO: [🧠] How to pick everyhing except `pipelineUrl`
6724
+ },
6725
+ result: $ongoingTaskResult.$result || undefined,
6726
+ error: $ongoingTaskResult.$expectError === null ? undefined : serializeError($ongoingTaskResult.$expectError),
6727
+ };
6728
+ $executionReport.promptExecutions.push(executionPromptReport);
6729
+ if (logLlmCall) {
6730
+ logLlmCall({
6731
+ modelName: 'model' /* <- TODO: How to get model name from the report */,
6732
+ report: executionPromptReport,
6733
+ });
6734
+ }
6735
+ }
6736
+ /**
6737
+ * Throws the aggregated retry error after the last regular attempt fails expectations.
6738
+ */
6739
+ function throwIfFinalAttemptFailed(options) {
6740
+ const { attemptIndex, maxAttempts, maxExecutionAttempts, pipelineIdentification, $ongoingTaskResult } = options;
6741
+ if ($ongoingTaskResult.$expectError === null || attemptIndex !== maxAttempts - 1) {
6742
+ return;
6743
+ }
6744
+ throw new PipelineExecutionError(spaceTrim$1((block) => {
6745
+ var _a;
6746
+ return `
6747
+ LLM execution failed ${maxExecutionAttempts}x
6582
6748
 
6583
- ${block(pipelineIdentification)}
6749
+ ${block(pipelineIdentification)}
6584
6750
 
6585
- The Prompt:
6586
- ${block((((_a = $ongoingTaskResult.$prompt) === null || _a === void 0 ? void 0 : _a.content) || '')
6587
- .split(/\r?\n/)
6588
- .map((line) => `> ${line}`)
6589
- .join('\n'))}
6751
+ The Prompt:
6752
+ ${block(quoteMultilineText(((_a = $ongoingTaskResult.$prompt) === null || _a === void 0 ? void 0 : _a.content) || ''))}
6590
6753
 
6591
- All Failed Attempts:
6592
- ${block(failuresSummary)}
6593
- `;
6594
- }));
6595
- }
6596
- }
6754
+ All Failed Attempts:
6755
+ ${block(createFailuresSummary($ongoingTaskResult.$failedResults))}
6756
+ `;
6757
+ }));
6758
+ }
6759
+ /**
6760
+ * Renders the retry history into the aggregated final error body.
6761
+ */
6762
+ function createFailuresSummary($failedResults) {
6763
+ return $failedResults
6764
+ .map((failure) => spaceTrim$1((block) => {
6765
+ var _a, _b;
6766
+ return `
6767
+ Attempt ${failure.attemptIndex + 1}:
6768
+ Error ${((_a = failure.error) === null || _a === void 0 ? void 0 : _a.name) || ''}:
6769
+ ${block(quoteMultilineText(((_b = failure.error) === null || _b === void 0 ? void 0 : _b.message) || ''))}
6770
+
6771
+ Result:
6772
+ ${block(failure.result === null ? 'null' : quoteMultilineText(spaceTrim$1(failure.result)))}
6773
+ `;
6774
+ }))
6775
+ .join('\n\n---\n\n');
6776
+ }
6777
+ /**
6778
+ * Formats multiline text as a quoted markdown block.
6779
+ */
6780
+ function quoteMultilineText(text) {
6781
+ return text
6782
+ .split(/\r?\n/)
6783
+ .map((line) => `> ${line}`)
6784
+ .join('\n');
6785
+ }
6786
+ /**
6787
+ * Returns the successful result string or raises an unexpected internal-state error.
6788
+ */
6789
+ function getSuccessfulResultString(options) {
6790
+ const { pipelineIdentification, $ongoingTaskResult } = options;
6597
6791
  if ($ongoingTaskResult.$resultString === null) {
6598
6792
  throw new UnexpectedError(spaceTrim$1((block) => `
6599
6793
  Something went wrong and prompt result is null
@@ -6603,7 +6797,6 @@ async function executeAttempts(options) {
6603
6797
  }
6604
6798
  return $ongoingTaskResult.$resultString;
6605
6799
  }
6606
- // TODO: Break into smaller functions
6607
6800
 
6608
6801
  /**
6609
6802
  * Executes a pipeline task that requires mapping or iterating over subvalues of a parameter (such as rows in a CSV).