@promptbook/vercel 0.86.10 → 0.86.22

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/umd/index.umd.js CHANGED
@@ -16,153 +16,31 @@
16
16
  * @generated
17
17
  * @see https://github.com/webgptorg/book
18
18
  */
19
- var BOOK_LANGUAGE_VERSION = '1.0.0';
19
+ const BOOK_LANGUAGE_VERSION = '1.0.0';
20
20
  /**
21
21
  * The version of the Promptbook engine
22
22
  *
23
23
  * @generated
24
24
  * @see https://github.com/webgptorg/promptbook
25
25
  */
26
- var PROMPTBOOK_ENGINE_VERSION = '0.86.10';
26
+ const PROMPTBOOK_ENGINE_VERSION = '0.86.22';
27
27
  /**
28
28
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
29
29
  * Note: [💞] Ignore a discrepancy between file name and entity name
30
30
  */
31
31
 
32
- /*! *****************************************************************************
33
- Copyright (c) Microsoft Corporation.
34
-
35
- Permission to use, copy, modify, and/or distribute this software for any
36
- purpose with or without fee is hereby granted.
37
-
38
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
39
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
40
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
41
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
42
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
43
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
44
- PERFORMANCE OF THIS SOFTWARE.
45
- ***************************************************************************** */
46
- /* global Reflect, Promise */
47
-
48
- var extendStatics = function(d, b) {
49
- extendStatics = Object.setPrototypeOf ||
50
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
51
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
52
- return extendStatics(d, b);
53
- };
54
-
55
- function __extends(d, b) {
56
- if (typeof b !== "function" && b !== null)
57
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
58
- extendStatics(d, b);
59
- function __() { this.constructor = d; }
60
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
61
- }
62
-
63
- var __assign = function() {
64
- __assign = Object.assign || function __assign(t) {
65
- for (var s, i = 1, n = arguments.length; i < n; i++) {
66
- s = arguments[i];
67
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
68
- }
69
- return t;
70
- };
71
- return __assign.apply(this, arguments);
72
- };
73
-
74
- function __awaiter(thisArg, _arguments, P, generator) {
75
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
76
- return new (P || (P = Promise))(function (resolve, reject) {
77
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
78
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
79
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
80
- step((generator = generator.apply(thisArg, _arguments || [])).next());
81
- });
82
- }
83
-
84
- function __generator(thisArg, body) {
85
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
86
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
87
- function verb(n) { return function (v) { return step([n, v]); }; }
88
- function step(op) {
89
- if (f) throw new TypeError("Generator is already executing.");
90
- while (_) try {
91
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
92
- if (y = 0, t) op = [op[0] & 2, t.value];
93
- switch (op[0]) {
94
- case 0: case 1: t = op; break;
95
- case 4: _.label++; return { value: op[1], done: false };
96
- case 5: _.label++; y = op[1]; op = [0]; continue;
97
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
98
- default:
99
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
100
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
101
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
102
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
103
- if (t[2]) _.ops.pop();
104
- _.trys.pop(); continue;
105
- }
106
- op = body.call(thisArg, _);
107
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
108
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
109
- }
110
- }
111
-
112
- function __values(o) {
113
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
114
- if (m) return m.call(o);
115
- if (o && typeof o.length === "number") return {
116
- next: function () {
117
- if (o && i >= o.length) o = void 0;
118
- return { value: o && o[i++], done: !o };
119
- }
120
- };
121
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
122
- }
123
-
124
- function __read(o, n) {
125
- var m = typeof Symbol === "function" && o[Symbol.iterator];
126
- if (!m) return o;
127
- var i = m.call(o), r, ar = [], e;
128
- try {
129
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
130
- }
131
- catch (error) { e = { error: error }; }
132
- finally {
133
- try {
134
- if (r && !r.done && (m = i["return"])) m.call(i);
135
- }
136
- finally { if (e) throw e.error; }
137
- }
138
- return ar;
139
- }
140
-
141
- function __spreadArray(to, from, pack) {
142
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
143
- if (ar || !(i in from)) {
144
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
145
- ar[i] = from[i];
146
- }
147
- }
148
- return to.concat(ar || Array.prototype.slice.call(from));
149
- }
150
-
151
32
  /**
152
33
  * This error indicates errors during the execution of the pipeline
153
34
  *
154
35
  * @public exported from `@promptbook/core`
155
36
  */
156
- var PipelineExecutionError = /** @class */ (function (_super) {
157
- __extends(PipelineExecutionError, _super);
158
- function PipelineExecutionError(message) {
159
- var _this = _super.call(this, message) || this;
160
- _this.name = 'PipelineExecutionError';
161
- Object.setPrototypeOf(_this, PipelineExecutionError.prototype);
162
- return _this;
37
+ class PipelineExecutionError extends Error {
38
+ constructor(message) {
39
+ super(message);
40
+ this.name = 'PipelineExecutionError';
41
+ Object.setPrototypeOf(this, PipelineExecutionError.prototype);
163
42
  }
164
- return PipelineExecutionError;
165
- }(Error));
43
+ }
166
44
 
167
45
  /**
168
46
  * Freezes the given object and all its nested objects recursively
@@ -174,26 +52,15 @@
174
52
  * @public exported from `@promptbook/utils`
175
53
  */
176
54
  function $deepFreeze(objectValue) {
177
- var e_1, _a;
178
55
  if (Array.isArray(objectValue)) {
179
- return Object.freeze(objectValue.map(function (item) { return $deepFreeze(item); }));
180
- }
181
- var propertyNames = Object.getOwnPropertyNames(objectValue);
182
- try {
183
- for (var propertyNames_1 = __values(propertyNames), propertyNames_1_1 = propertyNames_1.next(); !propertyNames_1_1.done; propertyNames_1_1 = propertyNames_1.next()) {
184
- var propertyName = propertyNames_1_1.value;
185
- var value = objectValue[propertyName];
186
- if (value && typeof value === 'object') {
187
- $deepFreeze(value);
188
- }
189
- }
56
+ return Object.freeze(objectValue.map((item) => $deepFreeze(item)));
190
57
  }
191
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
192
- finally {
193
- try {
194
- if (propertyNames_1_1 && !propertyNames_1_1.done && (_a = propertyNames_1.return)) _a.call(propertyNames_1);
58
+ const propertyNames = Object.getOwnPropertyNames(objectValue);
59
+ for (const propertyName of propertyNames) {
60
+ const value = objectValue[propertyName];
61
+ if (value && typeof value === 'object') {
62
+ $deepFreeze(value);
195
63
  }
196
- finally { if (e_1) throw e_1.error; }
197
64
  }
198
65
  Object.freeze(objectValue);
199
66
  return objectValue;
@@ -233,7 +100,7 @@
233
100
  *
234
101
  * @public exported from `@promptbook/core`
235
102
  */
236
- var UNCERTAIN_USAGE = $deepFreeze({
103
+ const UNCERTAIN_USAGE = $deepFreeze({
237
104
  price: { value: 0, isUncertain: true },
238
105
  input: {
239
106
  tokensCount: { value: 0, isUncertain: true },
@@ -277,32 +144,32 @@
277
144
  *
278
145
  * @public exported from `@promptbook/core`
279
146
  */
280
- var NAME = "Promptbook";
147
+ const NAME = `Promptbook`;
281
148
  /**
282
149
  * Email of the responsible person
283
150
  *
284
151
  * @public exported from `@promptbook/core`
285
152
  */
286
- var ADMIN_EMAIL = 'pavol@ptbk.io';
153
+ const ADMIN_EMAIL = 'pavol@ptbk.io';
287
154
  /**
288
155
  * Name of the responsible person for the Promptbook on GitHub
289
156
  *
290
157
  * @public exported from `@promptbook/core`
291
158
  */
292
- var ADMIN_GITHUB_NAME = 'hejny';
159
+ const ADMIN_GITHUB_NAME = 'hejny';
293
160
  // <- TODO: [🧠] Better system for generator warnings - not always "code" and "by `@promptbook/cli`"
294
161
  /**
295
162
  * The maximum number of iterations for a loops
296
163
  *
297
164
  * @private within the repository - too low-level in comparison with other `MAX_...`
298
165
  */
299
- var LOOP_LIMIT = 1000;
166
+ const LOOP_LIMIT = 1000;
300
167
  /**
301
168
  * Strings to represent various values in the context of parameter values
302
169
  *
303
170
  * @public exported from `@promptbook/utils`
304
171
  */
305
- var VALUE_STRINGS = {
172
+ const VALUE_STRINGS = {
306
173
  empty: '(nothing; empty string)',
307
174
  null: '(no value; null)',
308
175
  undefined: '(unknown value; undefined)',
@@ -316,7 +183,7 @@
316
183
  *
317
184
  * @public exported from `@promptbook/utils`
318
185
  */
319
- var SMALL_NUMBER = 0.001;
186
+ const SMALL_NUMBER = 0.001;
320
187
  // <- TODO: [🧜‍♂️]
321
188
  /**
322
189
  * @@@
@@ -341,8 +208,11 @@
341
208
  * @public exported from `@promptbook/utils`
342
209
  */
343
210
  function orderJson(options) {
344
- var value = options.value, order = options.order;
345
- var orderedValue = __assign(__assign({}, (order === undefined ? {} : Object.fromEntries(order.map(function (key) { return [key, undefined]; })))), value);
211
+ const { value, order } = options;
212
+ const orderedValue = {
213
+ ...(order === undefined ? {} : Object.fromEntries(order.map((key) => [key, undefined]))),
214
+ ...value,
215
+ };
346
216
  return orderedValue;
347
217
  }
348
218
 
@@ -352,11 +222,37 @@
352
222
  * @private private within the repository
353
223
  */
354
224
  function getErrorReportUrl(error) {
355
- var report = {
356
- title: "\uD83D\uDC1C Error report from ".concat(NAME),
357
- body: spaceTrim__default["default"](function (block) { return "\n\n\n `".concat(error.name || 'Error', "` has occurred in the [").concat(NAME, "], please look into it @").concat(ADMIN_GITHUB_NAME, ".\n\n ```\n ").concat(block(error.message || '(no error message)'), "\n ```\n\n\n ## More info:\n\n - **Promptbook engine version:** ").concat(PROMPTBOOK_ENGINE_VERSION, "\n - **Book language version:** ").concat(BOOK_LANGUAGE_VERSION, "\n - **Time:** ").concat(new Date().toISOString(), "\n\n <details>\n <summary>Stack trace:</summary>\n\n ## Stack trace:\n\n ```stacktrace\n ").concat(block(error.stack || '(empty)'), "\n ```\n </details>\n\n "); }),
225
+ const report = {
226
+ title: `🐜 Error report from ${NAME}`,
227
+ body: spaceTrim__default["default"]((block) => `
228
+
229
+
230
+ \`${error.name || 'Error'}\` has occurred in the [${NAME}], please look into it @${ADMIN_GITHUB_NAME}.
231
+
232
+ \`\`\`
233
+ ${block(error.message || '(no error message)')}
234
+ \`\`\`
235
+
236
+
237
+ ## More info:
238
+
239
+ - **Promptbook engine version:** ${PROMPTBOOK_ENGINE_VERSION}
240
+ - **Book language version:** ${BOOK_LANGUAGE_VERSION}
241
+ - **Time:** ${new Date().toISOString()}
242
+
243
+ <details>
244
+ <summary>Stack trace:</summary>
245
+
246
+ ## Stack trace:
247
+
248
+ \`\`\`stacktrace
249
+ ${block(error.stack || '(empty)')}
250
+ \`\`\`
251
+ </details>
252
+
253
+ `),
358
254
  };
359
- var reportUrl = new URL("https://github.com/webgptorg/promptbook/issues/new");
255
+ const reportUrl = new URL(`https://github.com/webgptorg/promptbook/issues/new`);
360
256
  reportUrl.searchParams.set('labels', 'bug');
361
257
  reportUrl.searchParams.set('assignees', ADMIN_GITHUB_NAME);
362
258
  reportUrl.searchParams.set('title', report.title);
@@ -369,16 +265,24 @@
369
265
  *
370
266
  * @public exported from `@promptbook/core`
371
267
  */
372
- var UnexpectedError = /** @class */ (function (_super) {
373
- __extends(UnexpectedError, _super);
374
- function UnexpectedError(message) {
375
- 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 pipeline collection\n\n Please report issue:\n ").concat(block(getErrorReportUrl(new Error(message)).href), "\n\n Or contact us on ").concat(ADMIN_EMAIL, "\n\n "); })) || this;
376
- _this.name = 'UnexpectedError';
377
- Object.setPrototypeOf(_this, UnexpectedError.prototype);
378
- return _this;
268
+ class UnexpectedError extends Error {
269
+ constructor(message) {
270
+ super(spaceTrim.spaceTrim((block) => `
271
+ ${block(message)}
272
+
273
+ Note: This error should not happen.
274
+ It's probbably a bug in the pipeline collection
275
+
276
+ Please report issue:
277
+ ${block(getErrorReportUrl(new Error(message)).href)}
278
+
279
+ Or contact us on ${ADMIN_EMAIL}
280
+
281
+ `));
282
+ this.name = 'UnexpectedError';
283
+ Object.setPrototypeOf(this, UnexpectedError.prototype);
379
284
  }
380
- return UnexpectedError;
381
- }(Error));
285
+ }
382
286
 
383
287
  /**
384
288
  * Checks if the value is [🚉] serializable as JSON
@@ -401,10 +305,9 @@
401
305
  * @public exported from `@promptbook/utils`
402
306
  */
403
307
  function checkSerializableAsJson(options) {
404
- var e_1, _a;
405
- var value = options.value, name = options.name, message = options.message;
308
+ const { value, name, message } = options;
406
309
  if (value === undefined) {
407
- throw new UnexpectedError("".concat(name, " is undefined"));
310
+ throw new UnexpectedError(`${name} is undefined`);
408
311
  }
409
312
  else if (value === null) {
410
313
  return;
@@ -419,49 +322,54 @@
419
322
  return;
420
323
  }
421
324
  else if (typeof value === 'symbol') {
422
- throw new UnexpectedError("".concat(name, " is symbol"));
325
+ throw new UnexpectedError(`${name} is symbol`);
423
326
  }
424
327
  else if (typeof value === 'function') {
425
- throw new UnexpectedError("".concat(name, " is function"));
328
+ throw new UnexpectedError(`${name} is function`);
426
329
  }
427
330
  else if (typeof value === 'object' && Array.isArray(value)) {
428
- for (var i = 0; i < value.length; i++) {
429
- checkSerializableAsJson({ name: "".concat(name, "[").concat(i, "]"), value: value[i], message: message });
331
+ for (let i = 0; i < value.length; i++) {
332
+ checkSerializableAsJson({ name: `${name}[${i}]`, value: value[i], message });
430
333
  }
431
334
  }
432
335
  else if (typeof value === 'object') {
433
336
  if (value instanceof Date) {
434
- throw new UnexpectedError(spaceTrim__default["default"](function (block) { return "\n `".concat(name, "` is Date\n\n Use `string_date_iso8601` instead\n\n Additional message for `").concat(name, "`:\n ").concat(block(message || '(nothing)'), "\n "); }));
337
+ throw new UnexpectedError(spaceTrim__default["default"]((block) => `
338
+ \`${name}\` is Date
339
+
340
+ Use \`string_date_iso8601\` instead
341
+
342
+ Additional message for \`${name}\`:
343
+ ${block(message || '(nothing)')}
344
+ `));
435
345
  }
436
346
  else if (value instanceof Map) {
437
- throw new UnexpectedError("".concat(name, " is Map"));
347
+ throw new UnexpectedError(`${name} is Map`);
438
348
  }
439
349
  else if (value instanceof Set) {
440
- throw new UnexpectedError("".concat(name, " is Set"));
350
+ throw new UnexpectedError(`${name} is Set`);
441
351
  }
442
352
  else if (value instanceof RegExp) {
443
- throw new UnexpectedError("".concat(name, " is RegExp"));
353
+ throw new UnexpectedError(`${name} is RegExp`);
444
354
  }
445
355
  else if (value instanceof Error) {
446
- throw new UnexpectedError(spaceTrim__default["default"](function (block) { return "\n `".concat(name, "` is unserialized Error\n\n Use function `serializeError`\n\n Additional message for `").concat(name, "`:\n ").concat(block(message || '(nothing)'), "\n\n "); }));
356
+ throw new UnexpectedError(spaceTrim__default["default"]((block) => `
357
+ \`${name}\` is unserialized Error
358
+
359
+ Use function \`serializeError\`
360
+
361
+ Additional message for \`${name}\`:
362
+ ${block(message || '(nothing)')}
363
+
364
+ `));
447
365
  }
448
366
  else {
449
- try {
450
- for (var _b = __values(Object.entries(value)), _c = _b.next(); !_c.done; _c = _b.next()) {
451
- var _d = __read(_c.value, 2), subName = _d[0], subValue = _d[1];
452
- if (subValue === undefined) {
453
- // Note: undefined in object is serializable - it is just omited
454
- continue;
455
- }
456
- checkSerializableAsJson({ name: "".concat(name, ".").concat(subName), value: subValue, message: message });
367
+ for (const [subName, subValue] of Object.entries(value)) {
368
+ if (subValue === undefined) {
369
+ // Note: undefined in object is serializable - it is just omited
370
+ continue;
457
371
  }
458
- }
459
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
460
- finally {
461
- try {
462
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
463
- }
464
- finally { if (e_1) throw e_1.error; }
372
+ checkSerializableAsJson({ name: `${name}.${subName}`, value: subValue, message });
465
373
  }
466
374
  try {
467
375
  JSON.stringify(value); // <- TODO: [0]
@@ -470,7 +378,14 @@
470
378
  if (!(error instanceof Error)) {
471
379
  throw error;
472
380
  }
473
- throw new UnexpectedError(spaceTrim__default["default"](function (block) { return "\n `".concat(name, "` is not serializable\n\n ").concat(block(error.stack || error.message), "\n\n Additional message for `").concat(name, "`:\n ").concat(block(message || '(nothing)'), "\n "); }));
381
+ throw new UnexpectedError(spaceTrim__default["default"]((block) => `
382
+ \`${name}\` is not serializable
383
+
384
+ ${block(error.stack || error.message)}
385
+
386
+ Additional message for \`${name}\`:
387
+ ${block(message || '(nothing)')}
388
+ `));
474
389
  }
475
390
  /*
476
391
  TODO: [0] Is there some more elegant way to check circular references?
@@ -495,7 +410,12 @@
495
410
  }
496
411
  }
497
412
  else {
498
- throw new UnexpectedError(spaceTrim__default["default"](function (block) { return "\n `".concat(name, "` is unknown type\n\n Additional message for `").concat(name, "`:\n ").concat(block(message || '(nothing)'), "\n "); }));
413
+ throw new UnexpectedError(spaceTrim__default["default"]((block) => `
414
+ \`${name}\` is unknown type
415
+
416
+ Additional message for \`${name}\`:
417
+ ${block(message || '(nothing)')}
418
+ `));
499
419
  }
500
420
  }
501
421
  /**
@@ -541,9 +461,9 @@
541
461
  * @public exported from `@promptbook/utils`
542
462
  */
543
463
  function exportJson(options) {
544
- var name = options.name, value = options.value, order = options.order, message = options.message;
545
- checkSerializableAsJson({ name: name, value: value, message: message });
546
- var orderedValue =
464
+ const { name, value, order, message } = options;
465
+ checkSerializableAsJson({ name, value, message });
466
+ const orderedValue =
547
467
  // TODO: Fix error "Type instantiation is excessively deep and possibly infinite."
548
468
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
549
469
  // @ts-ignore
@@ -566,19 +486,19 @@
566
486
  *
567
487
  * @private within the repository
568
488
  */
569
- var REPLACING_NONCE = 'ptbkauk42kV2dzao34faw7FudQUHYPtW';
489
+ const REPLACING_NONCE = 'ptbkauk42kV2dzao34faw7FudQUHYPtW';
570
490
  /**
571
491
  * @@@
572
492
  *
573
493
  * @private within the repository
574
494
  */
575
- var RESERVED_PARAMETER_MISSING_VALUE = 'MISSING-' + REPLACING_NONCE;
495
+ const RESERVED_PARAMETER_MISSING_VALUE = 'MISSING-' + REPLACING_NONCE;
576
496
  /**
577
497
  * @@@
578
498
  *
579
499
  * @private within the repository
580
500
  */
581
- var RESERVED_PARAMETER_RESTRICTED = 'RESTRICTED-' + REPLACING_NONCE;
501
+ const RESERVED_PARAMETER_RESTRICTED = 'RESTRICTED-' + REPLACING_NONCE;
582
502
  /**
583
503
  * The names of the parameters that are reserved for special purposes
584
504
  *
@@ -586,7 +506,7 @@
586
506
  */
587
507
  exportJson({
588
508
  name: 'RESERVED_PARAMETER_NAMES',
589
- message: "The names of the parameters that are reserved for special purposes",
509
+ message: `The names of the parameters that are reserved for special purposes`,
590
510
  value: [
591
511
  'content',
592
512
  'context',
@@ -608,16 +528,13 @@
608
528
  *
609
529
  * @public exported from `@promptbook/core`
610
530
  */
611
- var LimitReachedError = /** @class */ (function (_super) {
612
- __extends(LimitReachedError, _super);
613
- function LimitReachedError(message) {
614
- var _this = _super.call(this, message) || this;
615
- _this.name = 'LimitReachedError';
616
- Object.setPrototypeOf(_this, LimitReachedError.prototype);
617
- return _this;
531
+ class LimitReachedError extends Error {
532
+ constructor(message) {
533
+ super(message);
534
+ this.name = 'LimitReachedError';
535
+ Object.setPrototypeOf(this, LimitReachedError.prototype);
618
536
  }
619
- return LimitReachedError;
620
- }(Error));
537
+ }
621
538
 
622
539
  /**
623
540
  * Format either small or big number
@@ -637,9 +554,9 @@
637
554
  else if (value === -Infinity) {
638
555
  return VALUE_STRINGS.negativeInfinity;
639
556
  }
640
- for (var exponent = 0; exponent < 15; exponent++) {
641
- var factor = Math.pow(10, exponent);
642
- var valueRounded = Math.round(value * factor) / factor;
557
+ for (let exponent = 0; exponent < 15; exponent++) {
558
+ const factor = 10 ** exponent;
559
+ const valueRounded = Math.round(value * factor) / factor;
643
560
  if (Math.abs(value - valueRounded) / value < SMALL_NUMBER) {
644
561
  return valueRounded.toFixed(exponent);
645
562
  }
@@ -707,47 +624,38 @@
707
624
  * @public exported from `@promptbook/utils`
708
625
  */
709
626
  function templateParameters(template, parameters) {
710
- var e_1, _a;
711
- try {
712
- for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
713
- var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
714
- if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
715
- throw new UnexpectedError("Parameter `{".concat(parameterName, "}` has missing value"));
716
- }
717
- else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
718
- // TODO: [🍵]
719
- throw new UnexpectedError("Parameter `{".concat(parameterName, "}` is restricted to use"));
720
- }
627
+ for (const [parameterName, parameterValue] of Object.entries(parameters)) {
628
+ if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
629
+ throw new UnexpectedError(`Parameter \`{${parameterName}}\` has missing value`);
721
630
  }
722
- }
723
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
724
- finally {
725
- try {
726
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
631
+ else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
632
+ // TODO: [🍵]
633
+ throw new UnexpectedError(`Parameter \`{${parameterName}}\` is restricted to use`);
727
634
  }
728
- finally { if (e_1) throw e_1.error; }
729
635
  }
730
- var replacedTemplates = template;
731
- var match;
732
- var loopLimit = LOOP_LIMIT;
733
- var _loop_1 = function () {
636
+ let replacedTemplates = template;
637
+ let match;
638
+ let loopLimit = LOOP_LIMIT;
639
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
640
+ .exec(replacedTemplates))) {
734
641
  if (loopLimit-- < 0) {
735
642
  throw new LimitReachedError('Loop limit reached during parameters replacement in `templateParameters`');
736
643
  }
737
- var precol = match.groups.precol;
738
- var parameterName = match.groups.parameterName;
644
+ const precol = match.groups.precol;
645
+ const parameterName = match.groups.parameterName;
739
646
  if (parameterName === '') {
740
- return "continue";
647
+ // Note: Skip empty placeholders. It's used to avoid confusion with JSON-like strings
648
+ continue;
741
649
  }
742
650
  if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
743
651
  throw new PipelineExecutionError('Parameter is already opened or not closed');
744
652
  }
745
653
  if (parameters[parameterName] === undefined) {
746
- throw new PipelineExecutionError("Parameter `{".concat(parameterName, "}` is not defined"));
654
+ throw new PipelineExecutionError(`Parameter \`{${parameterName}}\` is not defined`);
747
655
  }
748
- var parameterValue = parameters[parameterName];
656
+ let parameterValue = parameters[parameterName];
749
657
  if (parameterValue === undefined) {
750
- throw new PipelineExecutionError("Parameter `{".concat(parameterName, "}` is not defined"));
658
+ throw new PipelineExecutionError(`Parameter \`{${parameterName}}\` is not defined`);
751
659
  }
752
660
  parameterValue = valueToString(parameterValue);
753
661
  // Escape curly braces in parameter values to prevent prompt-injection
@@ -755,17 +663,13 @@
755
663
  if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
756
664
  parameterValue = parameterValue
757
665
  .split('\n')
758
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
666
+ .map((line, index) => (index === 0 ? line : `${precol}${line}`))
759
667
  .join('\n');
760
668
  }
761
669
  replacedTemplates =
762
670
  replacedTemplates.substring(0, match.index + precol.length) +
763
671
  parameterValue +
764
672
  replacedTemplates.substring(match.index + precol.length + parameterName.length + 2);
765
- };
766
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
767
- .exec(replacedTemplates))) {
768
- _loop_1();
769
673
  }
770
674
  // [💫] Check if there are parameters that are not closed properly
771
675
  if (/{\w+$/.test(replacedTemplates)) {
@@ -799,8 +703,8 @@
799
703
  return value.map(asSerializable);
800
704
  }
801
705
  else if (value !== null && typeof value === 'object') {
802
- var result = {};
803
- for (var key in value) {
706
+ const result = {};
707
+ for (const key in value) {
804
708
  if (Object.prototype.hasOwnProperty.call(value, key)) {
805
709
  result[key] = asSerializable(value[key]);
806
710
  }
@@ -818,131 +722,119 @@
818
722
  * @public exported from `@promptbook/vercel`
819
723
  */
820
724
  function createExecutionToolsFromVercelProvider(options) {
821
- var title = options.title, description = options.description;
822
- var vercelProvider = options.vercelProvider, availableModels = options.availableModels, userId = options.userId, _a = options.additionalChatSettings, additionalChatSettings = _a === void 0 ? {} : _a;
725
+ let { title, description } = options;
726
+ const { vercelProvider, availableModels, userId, additionalChatSettings = {} } = options;
823
727
  if (!/Vercel/i.test(title)) {
824
- title = "".concat(title, " (through Vercel)");
728
+ title = `${title} (through Vercel)`;
825
729
  } /* not else */
826
730
  if (description === undefined) {
827
- description = "Implementation of ".concat(title, " through Vercel");
731
+ description = `Implementation of ${title} through Vercel`;
828
732
  } /* not else */
829
733
  if (!/Vercel/i.test(description)) {
830
- description = "".concat(description, " (through Vercel)");
734
+ description = `${description} (through Vercel)`;
831
735
  } /* not else */
832
736
  return {
833
- title: title,
834
- description: description,
835
- checkConfiguration: function () {
737
+ title,
738
+ description,
739
+ checkConfiguration() {
836
740
  // Note: There is no way how to check configuration of Vercel provider
837
741
  return Promise.resolve();
838
742
  },
839
- listModels: function () {
840
- return __awaiter(this, void 0, void 0, function () {
841
- return __generator(this, function (_a) {
842
- return [2 /*return*/, availableModels];
843
- });
844
- });
743
+ async listModels() {
744
+ return availableModels;
845
745
  },
846
- callChatModel: function (prompt) {
746
+ async callChatModel(prompt) {
847
747
  var _a;
848
- return __awaiter(this, void 0, void 0, function () {
849
- var content, parameters, modelRequirements, modelName, model, rawPromptContent, rawRequest, start, rawResponse, complete, usage;
850
- var _this = this;
851
- return __generator(this, function (_b) {
852
- switch (_b.label) {
853
- case 0:
854
- content = prompt.content, parameters = prompt.parameters, modelRequirements = prompt.modelRequirements;
855
- if (modelRequirements.modelVariant !== 'CHAT') {
856
- throw new PipelineExecutionError('Use callChatModel only for CHAT variant');
857
- }
858
- modelName = modelRequirements.modelName ||
859
- ((_a = availableModels.find(function (_a) {
860
- var modelVariant = _a.modelVariant;
861
- return modelVariant === 'CHAT';
862
- })) === null || _a === void 0 ? void 0 : _a.modelName);
863
- if (!modelName) {
864
- throw new PipelineExecutionError(spaceTrim__default["default"]("\n Can not determine which model to use.\n\n You need to provide at least one of:\n 1) In `createExecutionToolsFromVercelProvider` options, provide `availableModels` with at least one model\n 2) In `prompt.modelRequirements`, provide `modelName` with the name of the model to use\n\n "));
865
- }
866
- return [4 /*yield*/, vercelProvider.chat(modelName, __assign({ user: (userId === null || userId === void 0 ? void 0 : userId.toString()) || undefined }, additionalChatSettings))];
867
- case 1:
868
- model = _b.sent();
869
- rawPromptContent = templateParameters(content, __assign(__assign({}, parameters), { modelName: modelName }));
870
- rawRequest = {
871
- // <- TODO: [☂]
872
- inputFormat: 'messages',
873
- mode: {
874
- type: 'regular',
875
- tools: [
876
- /* <- TODO: Pass the tools */
877
- ],
878
- },
879
- prompt: __spreadArray(__spreadArray([], __read((modelRequirements.systemMessage === undefined
880
- ? []
881
- : [
882
- {
883
- role: 'system',
884
- content: modelRequirements.systemMessage,
885
- },
886
- ])), false), [
887
- {
888
- role: 'user',
889
- content: [
890
- {
891
- type: 'text',
892
- text: rawPromptContent,
893
- },
894
- ],
895
- },
896
- ], false),
897
- };
898
- start = $getCurrentDate();
899
- if (options.isVerbose) {
900
- console.info(colors__default["default"].bgWhite('rawRequest'), JSON.stringify(rawRequest, null, 4));
901
- }
902
- return [4 /*yield*/, (function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
903
- switch (_a.label) {
904
- case 0: return [4 /*yield*/, model.doGenerate(rawRequest)];
905
- case 1: return [2 /*return*/, _a.sent()];
906
- }
907
- }); }); })().catch(function (error) {
908
- // <- Note: This weird structure is here to catch errors in both sync and async `doGenerate`
909
- if (options.isVerbose) {
910
- console.info(colors__default["default"].bgRed('error'), error);
911
- }
912
- throw error;
913
- })];
914
- case 2:
915
- rawResponse = _b.sent();
916
- return [4 /*yield*/, model.doGenerate(rawRequest)];
917
- case 3:
918
- _b.sent();
919
- if (options.isVerbose) {
920
- console.info(colors__default["default"].bgWhite('rawResponse'), JSON.stringify(rawResponse, null, 4));
921
- }
922
- if (rawResponse.text === undefined) {
923
- throw new PipelineExecutionError('No response message');
924
- }
925
- complete = $getCurrentDate();
926
- usage = UNCERTAIN_USAGE;
927
- return [2 /*return*/, exportJson({
928
- name: 'promptResult',
929
- message: "Result of `createExecutionToolsFromVercelProvider.callChatModel`",
930
- value: {
931
- content: rawResponse.text,
932
- modelName: modelName,
933
- timing: {
934
- start: start,
935
- complete: complete,
936
- },
937
- usage: usage,
938
- rawPromptContent: rawPromptContent,
939
- rawRequest: rawRequest,
940
- rawResponse: asSerializable(rawResponse),
941
- // <- [🗯]
942
- },
943
- })];
944
- }
945
- });
748
+ const { content, parameters, modelRequirements } = prompt;
749
+ if (modelRequirements.modelVariant !== 'CHAT') {
750
+ throw new PipelineExecutionError('Use callChatModel only for CHAT variant');
751
+ }
752
+ const modelName = modelRequirements.modelName ||
753
+ ((_a = availableModels.find(({ modelVariant }) => modelVariant === 'CHAT')) === null || _a === void 0 ? void 0 : _a.modelName);
754
+ if (!modelName) {
755
+ throw new PipelineExecutionError(spaceTrim__default["default"](`
756
+ Can not determine which model to use.
757
+
758
+ You need to provide at least one of:
759
+ 1) In \`createExecutionToolsFromVercelProvider\` options, provide \`availableModels\` with at least one model
760
+ 2) In \`prompt.modelRequirements\`, provide \`modelName\` with the name of the model to use
761
+
762
+ `));
763
+ }
764
+ const model = await vercelProvider.chat(modelName, {
765
+ user: (userId === null || userId === void 0 ? void 0 : userId.toString()) || undefined,
766
+ ...additionalChatSettings,
767
+ });
768
+ const rawPromptContent = templateParameters(content, { ...parameters, modelName });
769
+ const rawRequest = {
770
+ // <- TODO: [☂]
771
+ inputFormat: 'messages',
772
+ mode: {
773
+ type: 'regular',
774
+ tools: [
775
+ /* <- TODO: Pass the tools */
776
+ ],
777
+ },
778
+ prompt: [
779
+ ...(modelRequirements.systemMessage === undefined
780
+ ? []
781
+ : [
782
+ {
783
+ role: 'system',
784
+ content: modelRequirements.systemMessage,
785
+ },
786
+ ]),
787
+ {
788
+ role: 'user',
789
+ content: [
790
+ {
791
+ type: 'text',
792
+ text: rawPromptContent,
793
+ },
794
+ ],
795
+ },
796
+ ],
797
+ };
798
+ const start = $getCurrentDate();
799
+ if (options.isVerbose) {
800
+ console.info(colors__default["default"].bgWhite('rawRequest'), JSON.stringify(rawRequest, null, 4));
801
+ }
802
+ const rawResponse = await (async () => await model.doGenerate(rawRequest))().catch((error) => {
803
+ // <- Note: This weird structure is here to catch errors in both sync and async `doGenerate`
804
+ if (options.isVerbose) {
805
+ console.info(colors__default["default"].bgRed('error'), error);
806
+ }
807
+ throw error;
808
+ });
809
+ await model.doGenerate(rawRequest);
810
+ if (options.isVerbose) {
811
+ console.info(colors__default["default"].bgWhite('rawResponse'), JSON.stringify(rawResponse, null, 4));
812
+ }
813
+ if (rawResponse.text === undefined) {
814
+ throw new PipelineExecutionError('No response message');
815
+ }
816
+ const complete = $getCurrentDate();
817
+ /*
818
+ TODO: [🕘] Usage count
819
+ const usage = computeOpenAiUsage(content || '', resultContent || '', rawResponse);
820
+ */
821
+ const usage = UNCERTAIN_USAGE;
822
+ return exportJson({
823
+ name: 'promptResult',
824
+ message: `Result of \`createExecutionToolsFromVercelProvider.callChatModel\``,
825
+ value: {
826
+ content: rawResponse.text,
827
+ modelName,
828
+ timing: {
829
+ start,
830
+ complete,
831
+ },
832
+ usage,
833
+ rawPromptContent,
834
+ rawRequest,
835
+ rawResponse: asSerializable(rawResponse),
836
+ // <- [🗯]
837
+ },
946
838
  });
947
839
  },
948
840
  };